Q:

Code Transformation from Java to Go

I don't know syntax of Go. Can anybody help me to convert following java code in google's go language .
import java.io.*;

class FileWrite
{
  public static void main(String args[])
  {
    try {
      // Create file
      FileWriter fstream = new FileWriter("out.txt");
      BufferedWriter out = new BufferedWriter(fstream);
      out.write("Hello Java");
      // Close the output stream
      out.close();
    } catch (Exception e){ //Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

This java code creates a file named out.txt and write a string (Hello Java) on the file.

A:

package main

import (
    "fmt"
    "os"
)

func main() {
    fd, err := os.Create("out.txt")
    if err != nil {
        fmt.Println(os.Stderr, err)
        return
    }
    // defer calls a function at the end of the current function.
    defer fd.Close()

    fd.WriteString("Hello Gopher!\n")
}

I hope this helps. If this is not clear, please specify which part needs explanation.

A:

For example,
package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
)

func main() {
    f, err := os.Create("out.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()
    wtr := bufio.NewWriter(f)
    abc := 1
    _, err = wtr.WriteString("Hello Go " + strconv.Itoa(abc) + " ok\n")
    if err != nil {
        fmt.Println(err)
        return
    }
    err = wtr.Flush()
    if err != nil {
        fmt.Println(err)
        return
    }
}

file out.txt:
Hello Go 1 ok\n

String literals
A string literal represents a string constant obtained from
  concatenating a sequence of characters. There are two forms: raw
  string literals and interpreted string literals.
Raw string literals are character sequences between back quotes ``.
  Within the quotes, any character is legal except back quote. The value
  of a raw string literal is the string composed of the uninterpreted
  characters between the quotes; in particular, backslashes have no
  special meaning and the string may span multiple lines.
Interpreted string literals are character sequences between double
  quotes "". The text between the quotes, which may not span multiple
  lines, forms the value of the literal, with backslash escapes
  interpreted as they are in character literals (except that \' is
  illegal and \" is legal). The three-digit octal (\nnn) and two-digit
  hexadecimal (\xnn) escapes represent individual bytes of the resulting
  string; all other escapes represent the (possibly multi-byte) UTF-8
  encoding of individual characters. Thus inside a string literal \377
  and \xFF represent a single byte of value 0xFF=255, while ÿ, \u00FF,
  \U000000FF and \xc3\xbf represent the two bytes 0xc3 0xbf of the UTF-8
  encoding of character U+00FF.

A:

But, how this problem can solved ? play.golang.org/p/169zmQvK7m –
  alessandro

For example,
package main

import (
    "fmt"
    "os"
    "strconv"
)

func routine(fd *os.File) {
    abc := 1
    fd.WriteString("Hello Go " + strconv.Itoa(abc) + " ok\n")
    fd.WriteString("\nHello Gopher!\n")
}

func main() {
    fd, err := os.Create("out.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer fd.Close()
    abc := 1
    fd.WriteString("Hello Go " + strconv.Itoa(abc) + " ok\n")
    fd.WriteString("\nHello Gopher!\n")
    routine(fd)
}


Q:

Richfaces fileupload Error

I have tries to upload the file using rich:fileupload componenet.When i tried to upload the file,it arise the error,
The error is
Aug 24, 2011 9:41:19 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NullPointerException
        at org.richfaces.renderkit.FileUploadRendererBase.doDecode(FileUploadRendererBase.java:140)
        at org.ajax4jsf.renderkit.RendererBase.decode(RendererBase.java:75)
        at javax.faces.component.UIComponentBase.decode(UIComponentBase.java:764)
        at javax.faces.component.UIInput.decode(UIInput.java:719)
        at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1006)
        at javax.faces.component.UIInput.processDecodes(UIInput.java:633)
        at javax.faces.component.UIForm.processDecodes(UIForm.java:203)
        at org.ajax4jsf.component.AjaxViewRoot$1.invokeContextCallback(AjaxViewRoot.java:392)
        at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:238)
        at org.ajax4jsf.component.AjaxViewRoot.processDecodes(AjaxViewRoot.java:409)
        at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:101)
        at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251)
        at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:244)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
        at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
        at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:365)
        at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:495)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:341)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Thread.java:679)

Please help me to resolve this issue.

A:

The stacktrace hints that you're using both RichFaces 3.3 and Tomahawk 1.x. Both component libraries offers file upload components and extracts uploaded files from the request body using a special Filter. The stacktrace shows that the Tomahawk one is parsing the request body before the RichFaces one.
at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:365)
...
at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:341)

Once a request body is been parsed, it cannot be parsed anymore. RichFaces is therefore unable to extract the uploaded file from the request body. The NullPointerException which you're facing is just the unforeseen consequence of this (the RichFaces guys should have thrown a more clear exception instead, something like an IllegalStateException with the message "Uploaded file is missing in the request body" or like, but ala).
If you want to use RichFaces file upload functionality, then you've really got to remove the Tomahawk's ExtensionsFilter from web.xml. You'll only miss the <t:inputFileUpload> functionality and some minor features (scripts/stylesheets) of specific look'n'feel components. Other Tomahawk components should remain working fine.


Q:

How is the Bernoulli's Principle related to a campfire blowpipe?

My uncle recently told me that a campfire blowpipe (It is used to blow air into the fire so that it continues to burn) works on the Bernoulli's Principle. How is it so?

A:

If by campfire blowpipe is intended something like the schematic, where the user blows into the left side and the right side is pointed at the fire, then your uncle is loosely correct.
Because of the continuity requirement and assuming air is not very compressible at low pressures and speeds, then the outlet and inlet airspeeds, resp. $v_2$ and $v_1$ are related by:
$$A_1v_1\approx A_2v_2$$
So:
$$v_2\approx \frac{A_1}{A_2}v_1$$
Thus $v_2 > v_1$.
So the campfire blowpipe allows to, from a safe distance, direct a high speed jet of air onto the fire, acc. Bernoulli's Principle, applied here:
$$\frac12 v_1^2+\frac{p_1}{\rho}+gz=\frac12 v_2^2+\frac{p_0}{\rho}+gz$$
Or:
$$\frac12(v_2^2-v_1^2)=\frac{p_1-p_0}{\rho}$$
Where $p_1$ is provided by the user and $p_0$ is the atmospheric pressure.
Combined with the equation higher up, $v_2$ could then be estimated.


Q:

C# app connection with Siemens S7-200

I have an issue with getting data from PLC to PC. I have S7-200 and CP 243-1 communication module.
I need to read data from PLC. I have read a lot about libnodave library and tried to write an app for myself for communication and downloaded sample in Vb link on template.
In my app I get exception error

Cannot download DLL "libnodave.dll". Module not found.

But in references of project I added libnodave.net.dll... I have no idea.
All my attempts failed and maybe somebody know how to use libnodave or other libraries for communication PC with PLC Siemens S7-200. Thanks in advance.
Regards.

A:

Just a wild shot, but is the libnodave.dll a native DLL and libnodave.net.dll a wrapper for this DLL?
Then you need to make sure that libnodave.dll is found on the search path. Ideally, you copy that DLL to the output folder of your project, so that both libnodave.dll and libnodave.net.dll are in the same folder. You can do this automatically by adding the native DLL to the root of your project (not referencing it, adding it like a normal existing file), setting its build type to "none" and "copy always". This will make sure the DLL is always copied to the bin/debug or bin/release folder.
As you can not add native DLLs as references to a .NET project, chances are the developers created a .NET wrapper that can  be added, but can't be used standalone. It will call functions in the native DLL by P/Invoke.

From the "link on template" page you linked:

You need copy libnodave.net.dll file in the your PC and add references in the VB.NET project properties. This implements a bridge layer between libnodave.dll and applications written in MS .Net languages.

This means that my above guess seems to be right. You need both DLLs. The page continues to say:

Also copy libnodave.dll in the same directory where is exe file is located.

PS: Please make sure to use to correct bittyness for your project. The native DLL might be 32-bit, so you might have to set the target platform from "Any CPU" to "x86" to make it work.


Q:

Showing UINavigationController in a Modal segue (ViewController)?

I have now been stuck on this problem for more then 2 weeks! In my project, I have 1 single ViewController(slide) I want to enable both landscape and portrait in. The rest of all controllers/views(slides) I want to enable portrait-mode only.
The tricky part is, the "ViewController" I am referring to is connected to both NavigationControllers and TabBarControllers. See the scheme below where the ViewController I want to enable both landscape/portrait is named: ReferredViewController.
TabBarController ----> NavigationController ----> FristViewController --(push event)--> ReferredViewController
So far I have tried to make a CATEGORY for both NavigationControllers and TabBarControllers. But since my NavigationControllers and TabBarControllers are placed at the very start of the project this will set the rules for the whole project. My ReferredViewController is placed at the end or in the middle of the projects "storyboard". I have tried to set the rules by code aswell for the single ReferredViewController without any success.
My best shot is to change the event between FirstViewController and ReferredViewController from "push" to "modal". ReferredViewController can then rotate both portrait/landscape and the rest of the project is locked in portrait. BUT, as you may know all navigations (NavigationBar) will be lost and the user will become stuck at that single slide.
So I am trying to enable the NavigationBar with the following code example in the ReferredViewController.m file:
ShowTaskViewController *detailViewController = [[ShowTaskViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc]     initWithRootViewController:detailViewController];

navController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self.navigationController presentModalViewController:navController animated:YES  completion:nil];
[navController release];
[detailViewController release];

But ofc nothing happens and I am back to square one again :O. FML!

A:

you have to over ride UITaBarController because it is you base view controller. I have done this for my navigation controller. Tell me if this helped.
@interface UINavigationController (Autorotation)

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation;
- (BOOL) shouldAutorotate;
- (NSUInteger) supportedInterfaceOrientations;
@end

@implementation UINavigationController (Autorotation)

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{

if ([self.visibleViewController isKindOfClass:[MWPhotoBrowser class]] || [self.visibleViewController isKindOfClass:[ZoomPictureViewController class]]) {
    return YES;
}
return  (toInterfaceOrientation == UIInterfaceOrientationPortrait);
}

-(BOOL) shouldAutorotate{
    return YES;
}

-(NSUInteger) supportedInterfaceOrientations{

    if ([self.visibleViewController isKindOfClass:[MWPhotoBrowser class]] ||     [self.visibleViewController isKindOfClass:[ZoomPictureViewController class]]) {
    return UIInterfaceOrientationMaskAll;
}

return UIInterfaceOrientationMaskPortrait;
 }


Q:

Best practice to store constants for file names and property list names

What would you consider best practice to store constants (like file names for property lists) in objective-c?
I would like to improve the hard coded "Config.plist" in the following code:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
NSDictionary *rows = [[NSDictionary alloc]initWithContentsOfFile:plistPath];

A:

The best solution usually is to move this kind of logic into a model object like MYConfiguration. That way you can query MYConfiguration with explicit methods, and never directly access the NSDictionary.
Regarding the name of that file, there are many approaches to abstracting it, depending on how much reuse you really need (it is possible to go overboard here).
First is the constant. In MYConfiguration.m, you can put a private constant like this:
static NSString * const kConfigurationFileBaseName = @"Config";

You can also have a method that returns the path:
- (NSString *)pathToConfigurationFile {
  return [[NSBundle mainBundle] pathForResource:kConfigurationFileBaseName ofType:@"plist"];
}

It's not uncommon to hard-code the name of the file directly in pathToConfigurationFile rather than having a constant. Constants often are only needed in cases where the value is used more than once. If a given constant only appears one time, then moving the value elsewhere can sometimes make the code harder to understand. These are just guidelines, not rules.
If you need the constant itself to be publicly available, then you declare it this way in MYConfiguration.h:
extern NSString * const kMYConfigurationFileBaseName;

and then define it in .m:
NSString * const kMYConfigurationFileBaseName = @"Config";

But the key in all of this is that you define these constants in a header related to the use of the constant. You don't create some central "MYGlobals" dumping ground for everything.


Q:

Apply bootstrap grid to a part of the page

I want to make a sidebar with a fixed width, and use bootstrap grid to the rest of the page. The following code (JSBin) does not work: we see that the bootstrap grid is applied to the entire page.
Does anyone know if it is achievable?
<!DOCTYPE html>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

Overview (current)

Reports

          abcsfdsqdfdqfdqsdfdqfdsqdfssd

          efg

A:

Fixed and absolute positioned elements are no longer part of the document flow, so they don't reserve the space they normally would. In your example, that means the sidebar doesn't push the rest of the content over, which is why you see it overlap the main content.
What I find normally works is to use the fluid container (so the page content spans the whole viewport) and then add padding to the "main" section to clear the horizontal space the sidebar would otherwise overlap.
Here's an example based off of a project I've built recently:
CSS
/* Hide for mobile, show later */
.sidebar
{
    display: none;
}

@media (min-width: 768px)
{
    .sidebar
    {
        position: fixed;
        top: 55px;
        bottom: 0;
        left: 0;
        z-index: 1000;
        display: block;
        padding: 0;
        overflow-x: hidden;
        overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
        width: 175px;
    }

        .sidebar.student
        {
            background-color: #71B1D1;
            color: #fff;
            border-right: 1px solid #eee;
        }
}

/*
 * Main content
 */

.main
{
    padding: 20px;
}

@media (min-width: 768px)
{
    .main
    {
        padding-left: 215px;
        padding-right: 40px;
    }
}

Markup

Overview (current)

Reports

Analytics

Export

Nav item

Nav item again

One more nav

Another nav item

More navigation

Nav item again

One more nav

Another nav item

Content Header

Some content here...

                © 2017

Demo: https://jsbin.com/giwozanavi
Code: https://jsbin.com/giwozanavi/edit?html,css,output


Q:

Overriding __eq__ and comparing two objects

I have two unique Temperature objects that I need to compare to each other, however, since the objects can be equal but have different units, I'm running into trouble comparing them.
For example
t1 = Temperature(32.0, 'F')
t2 = Temperature(0.0, 'C')
These two objects are equal, but I can't seem to get the correct implementation of __eq__ to compare them
Here's what I have tried
class Temperature():

    def __init__(self, temp = 0.0, unit = 'C'):
        if float(temp) == str(temp):
            raise ValueError('could not convert string to float: ' + "'" + str(temp) + "'")
        else:
            self.t = float(temp)
        if unit.upper() not in 'CF':
            raise UnitError('Unrecognized temperature unit ' + "'" + str(unit) + "'")
        else:
            self.u = unit.upper()

    def __repr__(self):
        return "Temperature({},'{}')".format(self.t, self.u)

    def __str__(self):
        return str(self.t) + '°' + self.u.upper()

    def __eq__(self, other):
        t1 = Temperature(self.t, self.u)
        t2 = Temperature(other.t, other.u)
        other.convert()

        if t1.t == t2.t and t1.u == t2.u:
            return True
        return False

    def convert(self):
        t = Temperature(self.t, self.u)
        if t.u.upper() == 'C':
            t.t *= 1.8
            t.t += 32
            t.u = 'F'
            return t
        else:
            t.t -= 32
            t.t /= 1.8
            t.u = 'C'
            return t

Notice that I do have a method to convert temperatures from one unit to another. Again, I can't seem to figure out how to compare the two objects, when they are in different units.

A:

To compare the temperatures there is no need to always convert other. You only need to convert when self and other has different units. Once they are converted to same unit then temperature values can be compared.
Also you have returned new object from convert() method. So you need to assign the return value. And you should use the absolute value of the difference to avoid floating point errors.
This should work:
def __eq__(self, other):
    if self.u != other.u:
        other = other.convert()

    return math.fabs(self.t - other.t) < 1e-6


Q:

Best practice to reset angular 7 form

I am using Angular 7. In my project I've used Template Driven form. I'm resetting form using <input type="reset"> and it works fine. But I'm confused on which is better- <input type="reset" or form reset()?

A:

Better way is to use reset() of form as it resets the states of the form controls so any validation styling and errors reset also to the original pristine condition.


Q:

jquery file tree - folder open by default?

I was wondering if anyone could help me out with jQuery file tree (jQuery File Tree)
I was wondering if/how it would be possible to set some kind of variable that will tell the file tree to have a certain folder open on load. (eg. folder /images/fruit/ to be open by default)
Here's the code to call the filetree:
$('#container_id').fileTree({
  root: '/images/'
}, function(file) {
  alert(file);
});

And here's the filetree.js file:
// jQuery File Tree Plugin
//
// Version 1.01
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 24 March 2008
//
// Visit http://abeautifulsite.net/notebook.php?article=58 for more information
//
// Usage: $('.fileTreeDemo').fileTree( options, callback )
//
// Options:  root           - root folder to display; default = /
//           script         - location of the serverside AJAX file to use; default = jqueryFileTree.php
//           folderEvent    - event to trigger expand/collapse; default = click
//           expandSpeed    - default = 500 (ms); use -1 for no animation
//           collapseSpeed  - default = 500 (ms); use -1 for no animation
//           expandEasing   - easing function to use on expand (optional)
//           collapseEasing - easing function to use on collapse (optional)
//           multiFolder    - whether or not to limit the browser to one subfolder at a time
//           loadMessage    - Message to display while initial tree loads (can be HTML)
//
// History:
//
// 1.01 - updated to work with foreign characters in directory/file names (12 april 2008)
// 1.00 - released (24 March 2008)
//
// TERMS OF USE
//
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 a Beautiful Site, LLC.
//
if(jQuery) (function($){

    $.extend($.fn, {
        fileTree: function(o, h) {
            // Defaults
            if( !o ) var o = {};
            if( o.root == undefined ) o.root = '/';
            if( o.script == undefined ) o.script = 'jqueryFileTree.php';
            if( o.folderEvent == undefined ) o.folderEvent = 'click';
            if( o.expandSpeed == undefined ) o.expandSpeed= 500;
            if( o.collapseSpeed == undefined ) o.collapseSpeed= 500;
            if( o.expandEasing == undefined ) o.expandEasing = null;
            if( o.collapseEasing == undefined ) o.collapseEasing = null;
            if( o.multiFolder == undefined ) o.multiFolder = true;
            if( o.loadMessage == undefined ) o.loadMessage = 'Loading...';

            $(this).each( function() {

                function showTree(c, t) {
                    $(c).addClass('wait');
                    $(".jqueryFileTree.start").remove();
                    $.post(o.script, { dir: t }, function(data) {
                        $(c).find('.start').html('');
                        $(c).removeClass('wait').append(data);
                        if( o.root == t ) $(c).find('ul:hidden').show(); else $(c).find('ul:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
                        bindTree(c);
                    });
                }
                function bindTree(t) {
                    $(t).find('li a').bind(o.folderEvent, function() {
                        if( $(this).parent().hasClass('directory') ) {
                            if( $(this).parent().hasClass('collapsed') ) {
                                // Expand
                                if( !o.multiFolder ) {
                                    $(this).parent().parent().find('ul').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
                                    $(this).parent().parent().find('li.directory').removeClass('expanded').addClass('collapsed');
                                }
                                $(this).parent().find('ul').remove(); // cleanup
                                showTree( $(this).parent(), escape($(this).attr('rel').match( /.*\// )) );
                                $(this).parent().removeClass('collapsed').addClass('expanded');
                            } else {
                                // Collapse
                                $(this).parent().find('ul').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
                                $(this).parent().removeClass('expanded').addClass('collapsed');
                            }
                        } else {
                            h($(this).attr('rel'), $(this).attr('name'), $(this).attr('title'), $(this).attr('id'));
                        }
                        return false;
                    });
                    // Prevent a from triggering the # on non-click events
                    if( o.folderEvent.toLowerCase != 'click' ) $(t).find('li a').bind('click', function() { return false; });
                }
                // Loading message
                $(this).html('

' + o.loadMessage + '

');
                // Get the initial file list
                showTree( $(this), escape(o.root) );
            });
        }
    });

})(jQuery);

Every time I've tried to mess around with it, I keep killing it, as my javascript isn't that great. Any help would be appreciated! :)

A:

Add an extra default property to jqueryFileTree.js for folders to expand:
if (o.expandedFolders == undefined) o.expandedFolders = [];

Update the code to call the filetree to include the default folders to expand:
$(document).ready(function () {
        $('#container_id').fileTree({
             root: '/',
             expandedFolders: ['/images/','/images/fruit/']
            }, function (file) {
            alert(file);
        });
    });

Then add the following jquery code directly after the bindTree(c); line to the showTree(c, t) function in jqueryFileTree.js:
if (o.expandedFolders != null) {
    $(c).find(".directory.collapsed").each(function (i,f) {
       if ($.inArray($(f).children().attr('rel'), $(o.expandedFolders)) != -1) {
           showTree($(f), escape($(f).children().attr('rel').match(/.*\//)));
           $(f).removeClass('collapsed').addClass('expanded');
       }
    });
}

A:

There's an easier way to expand predefined folder without having to use array of folders.
I've modified Bermo's awesome hack so you don't have to write each parent folder (folders below the one you want to see opened) in array, instead it uses regular expression to find parent folders automatically:
jqueryFileTree.js
Line 47, after if( o.loadMessage == undefined ) o.loadMessage = 'Loading...';:
if(o.expanded == undefined) o.expanded = '';

Line 58, after bindTree(c);:
if (o.expanded != null) {
    $(c).find('.directory.collapsed').each(function (i, f) {
        if ((o.expanded).match($(f).children().attr('rel'))) {
            showTree($(f), escape($(f).children().attr('rel').match(/.*\//)));
            $(f).removeClass('collapsed').addClass('expanded');
        };
    });
}

yourpage.htm
$(document).ready(function () {
    $('#container_id').fileTree({
         root: '/',
         expanded: '/images/fruit/'
        }, function (file) {
        alert(file);
    });
});


Q:

How to restrict login view after user logged in?

I want to open my login view only to non logged in users. means once user is logged in, he/she can not access login view by hitting /login/ url manually.
Thanks in advance :)

A:

You can use @user_passes_test:
from django.contrib.auth.decorators import user_passes_test

def user_is_not_logged_in(user):
    return not user.is_authenticated()

@user_passes_test(user_is_not_logged_in)
def my_view(request):
    ...

You can use @user_passes_test(user_is_not_logged_in, login_url='/') to redirect to another URL and avoid server errors.


Q:

MbUnit and Resharper integration not working in Visual Studio 2010

I set up a new machine this week. It is running Windows 7, 64 bit.
I installed Visual Studio 2010 Professional, then Resharper 5.0, rapidly followed by Resharper 5.1  when it came out soon after.
Since I have a project with tests in MbUnit, I have installed MbUnit/Gallio, using the 3.1.397 version x64 msi installer from here.
I was expecting to see the green gutter icons that Reshaper puts next to my tests, but I do not. I tried removing Gallio and installing the 32 bit version. No change. I re-installed both Resharper as Gallio as per this question, but this produced no change. In this procedure, %APPDATA% is set to C:\Users\Me\AppData\Roaming, so I deleted C:\Users\Me\AppData\Roaming\JetBrains. I have also tried unstalling both Reshaper and gallio, deleting all Resharper and Gallio data from AppData\Roaming, AppData\Local, and C:\Program Files (x86), and then installing again from a cmd running as admin, but again, no change.
Resharper has no plugins listed in the Plugins dialog, and in the Resharper|Options|Unit testing item the "unit testing providers" listed are MSTest and nUnit.
Visual studio has two other Add-ins listed: ".Net Reflector" and "Visual Git".
What do I have to do to get MBUnit working in Resharper?
Which of these two tools provides the integration? Should I install Resharper or Gallio first?
Where do the integration files or settings go? It has been suggested that I should have a "resharper plugins directory" in C:\Program Files (x86)\JetBrains\ReSharper\v5.1\Plugins or similar but this is not present at all.

A:

R# 5.1 RTW is supported by Gallio/MbUnit starting from v3.2.512. You can download the latest binaries of the Gallio bundle in the daily builds repository. v3.2 is not officially released yet but it is very stable already.
UPDATE 1: R#5.1 officially supported.
UPDATE 2: Gallio v3.2 RC with R# 5.0 and 5.1 support.


Q:

use Pointer address in Java using Bridj and JNAerator

I have this code in C and I would like to write the same in Java:
static u_int32_t print_pkt (struct nfq_data *tb){
    unsigned char *data;
    ret = nfq_get_payload(tb, &data);
    if (ret >= 0)
        printf("payload_len=%d ", ret);
    printf("data: ");
    for(i=0;i<ret;i++){
        printf("%c",data[i]);
    }
    fputc('\n', stdout);
    return ret;
}

I used JNAerator to create the fonctions in Java that will call the C fonction nfq_get_payload using Bridj (Mylib Class):
public static int nfq_get_payload(Pointer<Netfilter_queueLibrary.nfq_data > nfad, Pointer<Pointer<Byte > > data) {
    return nfq_get_payload(Pointer.getPeer(nfad), Pointer.getPeer(data));
}
protected native static int nfq_get_payload(@Ptr long nfad, @Ptr long data);

My "equivalent" Java code is:
static int print_pkt (Pointer< nfq_data > tb)
{
    int ret;
    Pointer<Byte> data =null;
    ret = MyLib.nfq_get_payload(tb, Pointer.pointerToPointer(data));
    if (ret >= 0){
        System.out.println(String.format(" payload_len=%d ", ret));
        System.out.print("data: ");
        for(int i=0;i<ret;i++){
            System.out.print(data.get(i));
        }
    }
    System.out.println();

    return ret;
}

I should mention that the ret value is the same when using c code and java code, but when I try to access data, a NullPointerException is raised when using Java (in C code I get something else that I excepect).
When I do Pointer<Byte> data =Pointer.allocateBytes(4096); I get zeros instead of the null pointer Exception, but since I don't allocate memory in C code I think I shouldn't do it also in Java code.
Thank you for your time and your help
Cheers

A:

I finnaly found a fix this way, and still don't know why the first one doesn't work:
val data2 = Pointer.pointerToPointer(data);
ret = Netfilter_queueLibrary.nfq_get_payload(tb, data2)
if (ret >= 0) {
  println(String.format(" payload_len=%d ", ret));
  println("data: ");
  for (i <- 0 until ret) {
    printf("%02x", (data2.get().getBytes(ret)(i)));
  }

hope it will help someone


Q:

VBA Alternatives to workbook.open to pull data from a single cell

I wanted to find out if anyone can recommend an alternative way to query data in an excel file from an MS Access module.
If I have a data organised in a typical "Table" format e.g rows and columns with headers, then I have been connecting to the workbook using a DAO connection as below
Dim db as DAO.Database
Dim rsUsers as DAO.Recordset

Set db = OpenDatabase("C:\SaleLog.xls", False, True, "Excel 8.0;HDR=Yes;")
Set rsUsers = db.OpenRecordset("SELECT userID FROM [Sales$]")

I find this preferable to using
Dim xlApp As Excel.Application
Set xlApp = CreateObject("Excel.Application")

xlApp.Workbooks.Open "C:\SaleLog.xls", True, False

As it does not physically open an instance of an excel session and therefore runs a bit more quickly.
The only problem is when the data is not laid out like a table (e.g if I just wanted to get the value of 1 particular cell).
Does anyone know if there is a way to check the value of a cell in VBA without using Workbook.Open?

A:

There may be a simpler way to achieve this but I have found 3 methods which can be used to pull data into MS Access from a single cell in a closed Excel workbook relatively efficiently (Many thanks to John Muggins for his help with this).
Firstly, the workbooks.open method can be used and will run more quickly if you set the read-only parameter to true (I'm unsure if this technically 'Opens' the workbook but it definitely seems to run more quickly while read-only). This requires you to set a reference to the Excel library.
Dim xlApp As Excel.Application
Dim src As Workbook

Set xlApp = CreateObject("Excel.Application")
Set src = xlApp.Workbooks.Open "C:\SaleLog.xls", True, True

You can then get data from specific cells using normal Excel VBA syntax like so
strUser = src.Worksheets("Sales").Range("B8")

src.Close False  'false doesn't save changes
Set src = Nothing

Another method is to use the DoCmd.Transferspreadsheet method to link or import a single cell, in this case you would need to set the HasFieldNames parameter to false as shown
path = "C:\SaleLog.xls"
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, "tblTemp", path, False, "Sales!B8:B8"

This will create a table with a single field called F1. You can get the value stored in this table using a DLookup or a recordset (You may then wish to delete the temp table e.g. DoCmd.DeleteObject acTable, "tblTemp").
Lastly you can use a DAO connection as mentioned in the original question. You can specify a specific cell like so
Dim db as DAO.Database
Dim rsUsers as DAO.Recordset

Set db = OpenDatabase("C:\SaleLog.xls", False, True, "Excel 8.0;HDR=Yes;")
Set rsUsers = db.OpenRecordset("SELECT * FROM [Sales$B8:B8]")

Again this will create a recordset with a single field called F1. You can get the value of this field by using rsUsers.Fields("F1")
Each of the above methods can be (and usually are) used to pull data from an entire worksheet or range of cells but for the purpose of this question I wanted to show how they can be used to pull data from a single cell. I haven't tested them for efficiency although I doubt there is much difference in speed between them so probably best to go with the method that you find simplest.
If anyone knows how to tweak any of these methods to make them more efficient or has another approach altogether please feel free to comment or add a new answer :)


Q:

launching an external application

I'm trying to launch another application from my app, specifically the splashtop remote streamer app. Here's what I have so far:
string packageName = "com.splashtop.remote.FirstActivity";
Intent splash = new Intent();
splash.SetAction(packageName);
StartActivity(splash);

And in my Android Manifest:
<activity   android:name="com.splashtop.remote.FirstActivity" android:label="@string/app_name">
     <intent-filter>
        <action android:name="com.splashtop.remote.FirstActivity" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

And I get this error in the application output and the app forcecloses:
Didn't find class "com.splashtop.remote.FirstActivity" on path: /data/app/roughapp.roughapp-1.apk

So how exactly do I change the path it is referring to here
on path: /data/app/roughapp.roughapp-1.apk

A:

A better solution is to use the PackageManager and its method getLaunchIntentForPackage(String packageName);
http://developer.android.com/reference/android/content/pm/PackageManager.html#getLaunchIntentForPackage%28java.lang.String%29
This method will return a usable intent or null if the Application is not installed or does not have such an intent.
The PackageManager can be retrieve from any Context via getPackageManager();
Good luck.


Q:

How to find files whose names contain any of 2 strings?

I'd like to find files whose name contain "Mar" or "Jun", how can I do this?

A:

Your first approach (find . -type f -name "Mar" -name "Jun") had two problems:

find combines different rules using a logical "and" by default
You did an exact name match

So the only possible matches were files that were named exactly "Jun" and "Mar", i.e. none.

Instead, do the following:

You can use wildcards in the name search (* means any possibly empty sequence of characters), wrapped in quotation marks to prevent interpretation by the shell
combine the two rules with an -o (or) — this requires you two wrap the alternative rules in parentheses to override usual operator precedence, or to repeat the common -type f rule

Example:
$ ls -1
1st-of-June
January
March
$ find . -type f -name '*Mar*' -o -type f -name '*Jun*'
./1st-of-June
./March

A:

Use find and its regex option:
find -regex '.*\(Mar\|Jun\).*'


Q:

An Acrostiholic Riddle

The answer to this riddle is a single English word.

Likely you'll find me when lending support
  Or shedding some knots by a slip of some sort
  Or adding the silver before fitting the frame
  Keep calm and breathe is the key to this game.

If you have doubts about your answer, it is not correct.
Hint:

 question_asker was absolutely right. The the second line is boaty.

Hint:

 The answer is a very common English word. The clues refer to less common meanings of this word. Nothing really obscure, but definitely not the most common meanings.

Hint:

 Trust the last line.

Hint:

 Trust the title.

Hint:

 Trust me to be a pain in the posterior.

A:

I may be off base because I'm not very good at these but I looked at the title and

 Took the first letter of each line LOOK

So I was staring at that and a thought hit me.

 An acrosticolic won't stop at one, right?

I'm keep staring. Right before it says it's  the key?

 Keep Calm And Breathe is BACK backwards in acronym plus it meets with the K in LOOK

I think this fits. To support something can be

 To BACK it

The hint says the next line is boats. I googled the word and

 BACKING is a way to slow a sail boat.
 Knots is the speed of a boat so if you're slowing down you are shedding knots in a way and a slip is the place in a marina where you anchor

And also to

 Put something on the back of to decorate or protect and the example in the Google def was a MIRROR

So it can't be a coincidence. The answer has to be

 BACK

A:

Answer:

 Eyes?

Likely you'll find me when lending support

 A friendly gaze

Or shedding some knots by a slip of some sort

 Running thread through the EYE of a needle, securing via SLIP-KNOT

Or adding the silver before fitting the frame

 You make a mirror, you're going to see your eyes

LOOK

 yup. With your eyes.

A:

Answer

 Luck

Explanation

 Title suggests that it is an acrostic, which would lead to the answer being LOOK. The 'rhyme' tag suggests that the alternate spelling LUCK would be more correct, and it also fits the riddle more


Q:

Validate User Information on Registration Page

I want to create a registration page for my web site.
I have three Text Boxes, one for user name, another for password and third for repeat password.
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:TextBox ID="PassWord" runat="server"></asp:TextBox>
<asp:TextBox ID="RE-Pass" runat="server"></asp:TextBox>

Now I want to check these three Text Box's values.
For the first Text Box, I should check it's value by connecting to a database to check it's unique. For the two other text boxes, I should check their values are the same.
I used on blur event but it is a client side (javascript) event not a server side event.
How can I check these value using on blur event or any other way?

A:

Just use ASP.net validator controls.
For the password textboxes, use the CompareValidator control.
From MSDN:

Compares the value entered by the user in an input control with the
  value entered in another input control, or with a constant value.

You'd need something along the lines of:
<asp:textbox ID="Textbox1" runat="server" TextMode="Password"></asp:textbox>
<asp:textbox ID="Textbox2" runat="server" TextMode="Password"></asp:textbox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="No Match." ControlToValidate="Textbox1" ControlToCompare="Textbox2"></asp:CompareValidator>

For the username textbox you could use a Custom Validator control.
You'll need something along the lines of:
ASPX Page
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Invalid User     Name" ControlToValidate="TextBox3"
OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>

Code Behind
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
     bool userNameIsValid = true; // Database check here.

     if (userNameIsValid)
         args.IsValid = true
     else
         args.IsValid = false;
   }

Here's a tutorial on MSDN which describes using this control to validate user input against a database.


Q:

UITableViewAutomaticDimension not working for UIImageView

I'm using UITableViewAutomaticDimension for adjusting the cell height which has a dynamic label and an image.
tableView.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = 80.0;

I want to resize the cell as the content of the label increases and it is working perfectly.
I want to keep a minimum height for the cell(say 80) for the image to fit in always even if the label has no content at all. I've applied autolayout and set constant height, width, top space and leading space constraints to the imageview. But the cell height is going lower than the constraint height when the label content is less.
What should I do to make the cells to keep a minimum height to fit the imageView while using the 'UITableViewAutomaticDimension' feature.
Thanks in advance.

A:

Try to create an assistant hidden view, which set its top、bottom constraint to the contentView of cell, any width and x position, and then set its height Greater Than or Equal to 80.


Q:

Correct use of Syntax in if statement using && Operator and 2 variables

I have a quick question regarding proper use of syntax, basically i am trying to summarise these two if statements into one if statement.
if (sc.LastCallToFunction) {
    if (p_LowRectanglesList != NULL) {
        free(p_LowRectanglesList);
        sc.PersistVars->i1 = 0;
    }
    if (p_HighRectanglesList != NULL) {
        free(p_HighRectanglesList);
        sc.PersistVars->i2 = 0;
    }
    return;

Would it be syntactically correct to rewrite this as:
if (sc.LastCallToFunction) {
    if (p_LowRectanglesList || p_HighrectangleList != NULL) {
        free(p_LowRectanglesList && p_HighRectanglesList);
        sc.PersistVars->i1 && sc.PersistVars->i2 = 0;
    }
    return;

Or would the compiler not accept this / Is my Logic faulty?

A:

you can't do it the way you have given
if (p_LowRectanglesList || p_HighrectangleList != NULL)

this logically ORs the first pointer ( treats it as true or false ) with the comparison of the seond pointer to NULL
free(p_LowRectanglesList && p_HighRectanglesList);

this logically &&s the pointers together and then tries to free the result of that operation.  ie, you are trying to free "true" or "false"
sc.PersistVars->i1 && sc.PersistVars->i2 = 0;

this logically ands the two things together, which will result in true or false and then trys to assign 0 to it..... doesn't make any sense at all.
Also, in your original code....after the free, you should put p_LowRectanglesList=NULL;


Q:

Use Interface as __constructor() parameter

I am trying to pass an Interface as a constructor parameter
into a class that implements it and calls its method .
file: growth.php
<?php
   interface Growth {

        public function growPlants():array;

        }

file: forest.php
<?php
class Forest  implements Growth {

        private $growth;

        public function __construct(Growth $growth) {
                       $this->growth = $growth;
                    }

          public   function otherFunction():array {
            $this->growth->growPlants();
        }

    }

file: deepforest.php
<?php
class DeepForest implements Growth {

      public   function growPlants():array {
             /* Actions */
       }
  }

file: test.php
<?php
 include "deepforest.php";
 include "forest.php";

$deeforest = new DeepForest();
$forest = new Forest($deeforest);

Uncaught Error: Call to undefined method deepForest::otherFunction()

A:

According to the error, the variable you're passing to the Forest constructor is an array, and not an instance of Growth.
Can you post more code, or confirm what class instance you're passing in and whether it itself extends Growth?


Q:

Sorting a dictionary which is exported to excel?

Ok, So I have a dictionary with values which are contained as lists, which is what I've been looking for...  I was wondering if there was a way to sort this which will also display the values of the lists in separate columns... I have used this code to split the values into different columns:
        writer = csv.writer(csvfile, delimiter=',')
        for key, value in finaldict.iteritems():
                writer.writerow([key] + value)

Is there any way to make this sort the keys before writing it? Anything I seem to try either doesn't sort it, generates an error, or breaks the part where it changes the list into separate columns... So if you don't understand what I am saying for example lets say I have a dictionary
finaldict = {'A': [2 , 1], 'C' [3, 3], 'B' [4, 3]}
I'm looking for this in the excel file:
Parameter  Val1   Val2
A          2      1

B          4      3

C          3      3

But currently I get this:
Parameter  Val1   Val2
A          2      1

C          3      3

B          4      3

I'm grateful for the replies guys thank you!

A:

An alternative to the other answer (a bit cleaner, imho):
for key in sorted(finaldict.keys()):
    writer.writerow([key] + finaldict[key])


Q:

How to overlay a line for an lm object on a ggplot2 scatterplot

I have some data,
calvarbyruno.1<-structure(list(Nominal = c(1, 3, 6, 10, 30, 50, 150, 250), Run = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1", "2", "3"), class = "factor"),
    PAR = c(1.25000000000000e-05, 0.000960333333333333, 0.00205833333333334,
    0.00423333333333333, 0.0322333333333334, 0.614433333333334,
    1.24333333333333, 1.86333333333333), PredLin = c(-0.0119152187070942,
    0.00375925114245899, 0.0272709559167888, 0.0586198956158952,
    0.215364594111427, 0.372109292606959, 1.15583278508462, 1.93955627756228
    ), PredQuad = c(-0.0615895732702735, -0.0501563307416599,
    -0.0330831368244257, -0.0104619953693943, 0.100190275883806,
    0.20675348710041, 0.6782336426345, 1.04748729725370)), .Names = c("Nominal",
"Run", "PAR", "PredLin", "PredQuad"), row.names = c(NA, 8L), class = "data.frame")
calweight <- -2

for which I've created both a linear and a quadratic lm model
callin.1<-lm(PAR~Nominal,data=calvarbyruno.1,weight=Nominal^calweight)
calquad.1<-lm(PAR~Nominal+I(Nominal^2),data=calvarbyruno.1,weight=Nominal^calweight)

I can then plot my data values using ggplot2
qplot(PAR,Nominal,data=calvarbyruno.1)

But can't work out how to overlay a line representing the two lm objects... Any ideas ?

A:

The easiest option is to use geom_smooth() and let ggplot2 fit the model for you.
ggplot(calvarbyruno.1, aes(y = PAR, x = Nominal, weight=Nominal^calweight)) +
    geom_smooth(method = "lm") +
    geom_smooth(method = "lm", formula = y ~ poly(x, 2), colour = "red") +
    geom_point() +
    coord_flip()

Or you can create a new dataset with the predicted values.
newdata <- data.frame(Nominal = pretty(calvarbyruno.1$Nominal, 100))
newdata$Linear <- predict(callin.1, newdata = newdata)
newdata$Quadratic <- predict(calquad.1, newdata = newdata)
require(reshape2)
newdata <- melt(newdata, id.vars = "Nominal", variable.name = "Model")
ggplot(calvarbyruno.1, aes(x = PAR, y = Nominal, weight=Nominal^calweight)) +
    geom_line(data = newdata, aes(x = value, colour = Model)) +
    geom_point()

A:

Earlier I asked a related question and Hadley had this good answer.  Using the predict function from that post you can add two columns to your data. One for each model:
calvarbyruno.1$calQuad <- predict(calquad.1)
calvarbyruno.1$callin <- predict(callin.1)

Then it's a matter of plotting the point and adding each model in as a line:
ggplot() +
geom_point(data=calvarbyruno.1, aes(PAR, Nominal), colour="green") +
geom_line(data=calvarbyruno.1, aes(calQuad, Nominal), colour="red" ) +
geom_line(data=calvarbyruno.1, aes(callin, Nominal), colour="blue" ) +
opts(aspect.ratio = 1)

And that results in this nice picture (yeah the colors could use some work):

(source: cerebralmastication.com)


Q:

Do things for all tibbles in environment

I have 110 tibbles in my environement. These tibbles are among other objects, but all tibbles have a common pattern. I know how to list them with ls(pattern = MyPattern).
Now i need to do some basic work on each tibble. I have no idea at all how to handle this, as I will in fact work with a list of charcaters, not tibbles.
I tried to assign these tibbles in a new env, but wasn't successful when reading them. I got lots of errors.
Anyone with a solution to apply some work to my selected tibbles?

A:

You can use get and mget to access things by name. So this, for example, should work:
lapply(mget(ls(, pattern=MyPattern)), nrow)


Q:

Hierarchy is no problem and susy is a mathematical tool for data fitting

I saw this paper in the arXiv: http://arxiv.org/abs/1206.4711. The author seems well-known and has many very well cited papers. But what he says sounds very strange.
What I get from this paper are the claims that: There's no naturalness or fine-tuning problem in the Standard Model. And that Susy is mathematics that is presented as physics, so we should deal with it as a tool and not to expect to see real sparticles.
My questions are,
1) What does it mean that: "perturbation theory is not designed to handle problems with widely separated time or energy scales?" And how accurate is this statement?
2) How valid is the conclusion that the naturalness and fine-tuning concerns over energy hierarchies do not exist?
3) How valid are the statements on Susy?
4) What I really what to know from our experts here, does this paper have any merit at all!

A:

This paper has some interesting observations and the Lanczos trick is very nice, but the conclusion is no good.
I will paraphrase the argument in the paper as follows:
The naturalness and heirarchy problems are caused by perturbation theory diseases. If you have a heirarchy put in by hand, it doesn't matter if you add a high energy sector, you can keep the heirarchy stable even if perturbation theory says it is unstable.
The reason the author says this is because he estimates how perturbation theory shifts eigenvalues in an exactly diagonalizable matrix, where he knows the answer, and he shows that the shift is not reliably given by perturbation theory. This is absolutely correct, and it shows that the perturbative argument for the shift in the Higgs mass away from zero is not persuasive by itself. If this were the real argument for heirarchy, this paper would show you that there is no argument.
But this is not the real argument. The real argument is Wilsonian.
The Real Hierarchy Problem
consider any regulator for the standard model, like a lattice. The chiral fields (the fermions and quarks) are naturally massless, and have an infinite compton wavelength compared to the lattice, so they are always automatically tuned to their critical point. This is actually not so simple to understand, because it requires some crazy manipulations to get chiral fermions to naturally emerge with a lattice cutoff. But in this case, the lattice cutoff is just a stand-in for some sort of string-scale regularization, where chiral fermions emergy naturally.
The gauge fields are naturally massless, so they are also self-organized to their critical point, except that the SU(3) is confining, which picks out a confinement scale which is as the log of the lattice-scale coupling, so it is enormous even when the coupling is not terribly small. Anyway, everything is critical, and we would see a gravity-free version of something like our universe at long distances in this model.
Except there is no Higgs. Now if you introduce a lattice Higgs sector, if it is a fundamental scalar and not a composite of fermions, you get into trouble. The Higgs is not massless, and your lattice standard model will have a Higgs field correlation function which falls off order one with unit of length equal to the lattice spacing. It won't help to set the lattice mass term of the Higgs to zero. The quartic term means that the lattice mass has to be some negative specific value to reach the massless Higgs point, since the phase transition point is not at 0 when you have a quartic self-coupling.
The reason is that the Higgs itself is like the Ising model--- it has a tunable $m^2$ (which can be negative or positive, despite the name), and you need to make $m^2$ negative order 1 units on the lattice to reach the critical point in the Ising model. In the standard model, the critical point will be somewhere else, since it depends on the details of the fields you have in the theory, but it will not be at zero, it will be at some crazy value that depends both on the field content and on the regulator.
Yet we see that the Higgs is critical in terms of the regulator. This is the ridiculous fine-tuning which is called the Heirarchy problem--- why is the Higgs $m^2$ term fine tuned on the lattice scale to give a nearly massless Higgs? Why is the ising-like Higgs sector look like an Ising model at the critical point, rather than an Ising model at a generic point, where the SU(2) and U(1) fields would acquire lattice-scale masses from the Higgs VEV (or else remain unbroken, if the Higgs is stable at zero field)?
This order 1 shift at the lattice scale is what is nonperturbatively tantamount to a quadratically divergent perturbative divergent shift in the Higgs mass. An order 1 shift at the lattice scale is an order $\Lambda^2$ shift when you are looking at the thing in units appropriate for the low-energy theory. This shift is absolutely real--- you can see it by lattice simulating, and it is not fixed in the standard model. There is always an order 1 shift.
In SUSY models, the Higgs mass is partnered with a chiral fermion mass. So keeping one SUSY unbroken means that you only get as much Higgs mass as there is SUSY breaking. This has nothing to do with perturbation theory. It's the location of the phase transition point in the Wilsonian point of view.
If you say "The Higgs is just fine tuned to the phase transition point on the lattice", you are being absurd. Such a fine-tuning to a critical point screams for a dynamical mechanism. You might say "it's anthropic", but even after you tune the Higgs, as far as we can see, you need anthropic to tune the cosmological constant, and it is a little ridiculous to claim two parameters are turned anthropically to be so much smaller than Planckian, especially when there are coincidences that need to be explained:

The Higgs scale is only 3 orders of magnitude bigger than the QCD scale, but 14 orders of magnitude less than the Planck/GUT scale. Why is there a QCD Higgs near coincidence? This would be explained by technicolor, if the couplings start off the same for some other gauge group, and the confinement just happens a little sooner because of quicker running.
The cosmological constant scale is as far lower than the Higgs scale as the Higgs scale is lower than the Planck scale. This could be a coincidence, but it feels like a clue.

It is not reasonable to claim that this kind structure is a random anthropic coincidence. There is more information there than in a random anthropic tuning.
But the paper is right that the arguments for SUSY are extremely weak. Stabilizing the Higgs can be done in a variety of ways, and SUSY is only preferred because it is the one that is suggested by string theory. The fact that strings were out when SUSY was formulated meant that people made up other reasons to like SUSY, but really, the only thing that suggests SUSY is strings.
But even though we know that the fundamental theory is SUSY, that doesn't mean that the low-energy theory has to be SUSY, but it does allow the low-energy theory to be SUSY, and this does stabilize the heirarchy problem, which is a real problem.


Q:

Presenting the ViewController in full screen

I am presenting a view controller in a button action as follows,
PromptController *obj = [[[PromptController alloc]initWithNibName:@"PromptController" bundle:nil]autorelease];
UINavigationController *navigation = [[[UINavigationController alloc]initWithRootViewController:obj]autorelease];
[self presentViewController:navigation animated:YES completion:nil];
[AVSession stopRunning];

But it is not presenting on the full screen of the phone. It is presenting as follows

How to present it on the full screen. Any help is really appreciated

A:

In iOS 13 the default presentation style has changed. If you want iOS 12 presentation style, you can change the modalPresentationStyle to .fullScreen.
Swift Version
navigation.modalPresentationStyle = .fullScreen

Objective C
navigation.modalPresentationStyle = UIModalPresentationOverFullScreen;


Q:

Animate jQuery method of swapping classes of a navbar div

I have a bootstrap navbar defined in HTML/CSS as below. When the user scrolls up and down, I have the below jQuery method that changes the class of the navbar, thus making it transparent/non-transparent depending on the position of the scroll. If the user is at the top of the page, the navbar is set to be transparent.
HTML:

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

            </button>
            @Html.ActionLink("Marcus Jacobsson", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("About", "About", "Home")

@Html.ActionLink("Contact", "Contact", "Home")

@Html.ActionLink("Projects", "Projects", "Home")

            @Html.Partial("_LoginPartial")

CSS:
.navbar.transparent.navbar-inverse {
    border-width: 0px;
    -webkit-box-shadow: 0px 0px;
    box-shadow: 0px 0px;
    background-color: rgba(0,0,0,0.0);
    background-image: -webkit-gradient(linear, 50.00% 0.00%, 50.00% 100.00%, color-stop( 0%, rgba(0,0,0,0.00)),color-stop( 100%, rgba(0,0,0,0.00)));
    background-image: -webkit-linear-gradient(270deg,rgba(0,0,0,0.00) 0%,rgba(0,0,0,0.00) 100%);
    background-image: linear-gradient(180deg,rgba(0,0,0,0.00) 0%,rgba(0,0,0,0.00) 100%);
}

jQuery method:
$(window).scroll(function () {
    var height = $(window).scrollTop();

    if (height == 0) {
        //Use transparent navbar class
        $("#navbar").attr("class", "navbar transparent navbar-inverse navbar-fixed-top");
    } else {
        //Use default bootstrap class (non-transparent)
        $("#navbar").attr("class", "navbar navbar-inverse navbar-fixed-top");
    }
});

Question
I would like to add an animation effect when the jQuery script swap the navbar classes from transparent to non-transparent. Is there an easy way to add this animation?
As an example of what I would like to achieve, have a look at this page navigation bar. When you scroll up and down, there's an animation effect in place.

A:

Sorry for the late answer.
I would go about this the following way:
Add a new class to your jquery for when the navigation bar should become non-transparent:
$("#navbar").attr("class", "navbar navbar-inverse navbar-fixed-top navbar-transition");

Now add the transistion for the navbar:
.navbar.transparent.navbar-inverse {
    -webkit-transition:background-color 0.5s linear;
}

.navbar-transition {
    -webkit-transition:background-color 0.5s linear;
}

Here is a fiddle to show how it works:
http://jsfiddle.net/3urgjsbd/
Please note that -webkit-transistion only works for Chrome-based Browser, you'll need to add the other prefixes:
-webkit-transition
-moz-transition
-o-transition
transition

See here: https://css-tricks.com/almanac/properties/t/transition/
Hope it helps.


Q:

Smallest value of n

Let $X$ have a binomial distribution with parameters $n$ and $p=1/3$. determine the smallest integer n can be such that $P(X\ge1)\ge0.85$. In this problem  I am stuck with $\frac{2^n (2^{-1}n+1)}{3^n}\ge0.15$

A:

$\Pr(X \ge 1)=1-\Pr(X=0)=1-\left(\frac23\right)^n$.
If this is greater than or equal to $0.85$ then  $\left(\frac23\right)^n \le 0.15$, i.e. $n \log(2/3) \le \log(0.15)$.
Note the negative logarithms and you get $n \ge \dfrac{\log(20)-\log(3)}{\log(3)-\log(2)}$.
Calculate and round up to an integer.


Q:

How to use Perl to write the contents of a C struct to a file

I have a C structure like this
struct _RxMsg {
    int index;
    int status;
    unsigned char packet[1024];
} rx_msg;

I can access this structure in Perl using the Convert::Binary::C module. The element packet[1024] is populated with some binary data that has arrived over the network (assume the contents of a text file).
If I dump the element I can see the contents.
open $fp, '>>', "file.txt" or die $!;
binmode $fp;      /* I set binmode but still no good */
for ($rx_msg->{packet}) {
  print $fp @$_;  /* This is writing the binary content as hex into the file. */
}

But the contents that are written to the file are in hex, when I want to write the simple binary contents of rx_msg->{packet}

A:

You're actually printing the decimal representation the char values, not their hex representation. What you want to do is print each number as a byte. chr and pack 'C' can be used to convert numbers to bytes.
open(my $fh, '>>:raw', 'file.txt') or die $!;

# Same thing:
#open(my $fh, '>>', 'file.dat') or die $!;
#binmode($fh);

print($fh, pack('C*', @{ $rx_msg->{packet} }));


Q:

What are some good mobile web app frameworks for touch events?

Are their any good mobile web app frameworks for touch events?
Sencha Touch?

A:

jQuery Mobile would be one of my favorites
It supports all major browsers including Android.


Q:

How can I draw diagrams using Google Web Toolkit?

I am considering solutions for drawing diagrams using Google Web Toolkit (GWT).
Up until now I have found only the gwt-diagrams project but it seems abandoned.
Are there any suggestions about diagramming with GWT?

A:

I'm also looking into this, for drawing family trees. I'm currently prototyping with gwt-graphics, which looks to be actively developed and is nearing version 1.0.
There is also the Raphael javascript library, and a couple of thorough blog posts about wrapping GWT around them here and here. The guys in the first article actually released their code for as raphaelgwt.
I can't comment on any of the raphael stuff yet since I haven't used it, I just found this in my own research for drawing components.


Q:

Bootstrap CSS messing with image (border-image)

I did a splicing of image and tried to increase / decrease the width of image based on certain dimensions.
This works perfectly.
When I included this image inside bootstrap, then the image height is overridden by bootstrap and the image appears reduced in height. Try removing bootstrap and run the fiddle. The output will have original image height.

14'12''

Any pointers on how to fix this would help.
Here is link to bootstrap 3 CDN
http://getbootstrap.com/getting-started/
Here is the fiddle
https://jsfiddle.net/haribalaji/3oqsyxrq/

A:

Your solution is dependent on the default content-box value of box-sizing. Bootstrap's grid system requires all columns to have box-sizing:border-box, so that columns with a set border do not break the grid, being wider than the rest.
In fact, a lot of elements have the potential to break Bootstrap's grid system if their width was calculated excluding borders, so they simply applied box-sizing:border-box to everything *.
In short,
.tireImageFirst {
    box-sizing: content-box;
}

... will fix your problem. Updated fidlle.


Q:

Removing parts of a multidimensional array in PHP

I have this array $data :
Array
(
    [0] => 86086
    [1] => Arnel
    [2] => Paras
)
Array
(
    [0] => 86085
    [1] => Arnely
    [2] => Para
)
Array
(
    [0] =>

)

How do i remove the bottom array that contains no values totally so it only contains :
Array
(
    [0] => 86086
    [1] => Arnel
    [2] => Paras
)
Array
(
    [0] => 86085
    [1] => Arnely
    [2] => Para
)

I have tried using array_filter($data, strlen) and it just does this :
Array
(

)

A:

array_pop() pops and returns the value of the last element of array, shortening the array by one element and will do exactly what you describe. A.
array_shift() does the opposite (removes first element from array and returns the value)
array_pop() on PHP.net
So you can either do:
$firstVal = array_pop($data)

or just
array_pop($data)

depending on if you want the value back or not.


Q:

What exactly did Mr. Peggoty and the Yarmouth boatmen do by "putting off?"

The following is an excerpt from Dickens' David Copperfield Chapter XXIII when Steerforth was explaining to Copperfield what a proctor is:

You shall go there one day, and find them blundering through half the nautical terms in Young's Dictionary, apropos of the "Nancy" having run down the "Sarah Jane", or Mr. Peggotty and the Yarmouth boatmen having put off in a gale of wind with an anchor and cable to the "Nelson" Indiaman in distress;

I wonder what exactly was Mr. Peggoty and the Yarmouth boatmen's action: refusing to help "Nelson" or helped 'Nelson" in spite of the dangers? What exactly does "put off" mean here?
Thanks.

A:

There are nautical dictionaries online. However I didn't immediately find one with 'to put off'.
A meaning of 'to put' in ordinary dictionaries is 'to change location'.  Thus 'to put to sea' is common parlance in the sailing world. It means to leave the land and move out to sea.
To my knowledge (as someone who has done a certain amount of sailing) 'to put off' means to leave your mooring but specifically a harbourside or dockside or quay. EDIT Note: You first 'cast off' which refers to undoing any ropes or cables that are holding you in place and then you may 'push off' (in a small boat, this can be with your hands or feet) in order to gain distance from whatever you were attached to. To 'put off' is a more general term that covers the other aspects.
P.S. It means that they set out to sea in order to help. My guess is that they were carrying the cable and anchor so that the Nelson could anchor itself and thus avoid being blown ashore and wrecked.


Q:

Find two vectors and angle between them

I have a vehicle and a dot representing pedestrian, I was able to find both vectors a and b (see picture below) and then I tried to calculate the angle between them
I use known formula that cos(Angle) = magnitude(vector_a)*magnitude(vector_a))/dot_product(vector_a,vector_b) but when I calculate the cosine it is much bigger than one so it is impossible to calculate the angle... What am I doing wrong?
    def detect_pedestrian(car,pedestrian):
        #Find a vector which connects pedestrian with a car
        pedestrian_position = pedestrian.body.position
        car_position = car.body.position

        #Find vectors a and b
        car_vector = Box2D.b2Body.__GetTransform(car.body).R.GetYAxis()
        pedestrian_vector = pedestrian_position - car_position

        #Calculate magnitudes of both vector
        pedestrian_vector_magnitude = np.linalg.norm(pedestrian_vector)
        car_vector_magnitude = np.linalg.norm(car_vector)

        #Normalize both vectors
        pedestrian_vector_normalized = pedestrian_vector/pedestrian_vector_magnitude
        car_vector_normalized = car_vector/car_vector_magnitude

        #Calculate angle
        magnitudes = pedestrian_vector_magnitude * car_vector_magnitude
        dot_product = b2Dot(pedestrian_vector_normalized, car_vector_normalized)
        cosine = magnitudes/dot_product
        arccos = np.arccos(cosine)

        print(cosine)

Thank you very much

A:

You need the car's heading and the position of the pedestrian relative to the car. If you have the positions of the pedestrian and the car in world coordinates (i.e. absolute position) and the velocity of the car, the code is straightforward:
import numpy as np

def detect_pedestrian(car_vector, pedestrian_vector, car_velocity):
    pedestrian_relative = pedestrian_vector - car_vector
    pedestrian_length = np.linalg.norm(pedestrian_relative)
    velocity_length = np.linalg.norm(car_velocity)
    dot_product = np.dot(pedestrian_relative, car_velocity)
    cosine = dot_product / (pedestrian_length * velocity_length)
    return(np.arccos(cosine))

car = np.array([5, 2])
pedestrian = np.array([2, 3])
v = np.array([0, 2])

angle_rad = detect_pedestrian(car, pedestrian, v)
print(f"Pedestrian angle: {np.degrees(angle_rad)}°")
# Pedestrian angle: 71.56505117707799°


Q:

C# passing data between forms without "Form1 frm=new Form1();"

I have an Order_Form with a button that takes you to Client_form to choose there a client name. I wanted to pass the client name back to the Order_Form  (by clicking a button) but without using
Order_Form  frm1 = New Order_Form();

cause I will be lost all the data in the Order_Form.
How can I do that?

A:

You just need to pass the instance of the Order_Form to your Client_Form:
public class Order_Form : Form
{
    public Order_Form()
    {
        // ...
    }

    public string clientName = String.Empty;

    public void GetClientName()
    {
        // Pass the instance of the Order_Form
        Client_form cform = new Client_form(this);
        cform.Show();
    }
}

public class Client_form
{
    public Client_form(Order_Form instance)
    {
        // Use the passed instance to access your clientName
        instance.clientName = "your string back";
    }
}


Q:

What does it mean by word size in computer?

I have tried to get a grasp of what "word" means and I have looked in the wiki and the definition is vague. So my question is what is "word size"? Is it the length of the data bus, address bus?

A:

"Word size" refers to the number of bits processed by a computer's CPU in one go (these days, typically 32 bits or 64 bits). Data bus size, instruction size, address size are usually multiples of the word size.
Just to confuse matters, for backwards compatibility, Microsoft Windows API defines a WORD as being 16 bits, a DWORD as 32 bits and a QWORD as 64 bits, regardless of the processor.

A:

One answer is -- not as much as it used to.  Way back when, computers could only load/store full "words" of memory, which would be 16/24/32/36/48 bits each (depending on the particular machine).  One would have to carefully structure their program design around the word size of the target machine.
But any more computers can access individual bytes or can access strings of data dozens of bytes long, with one relatively seamless operation.  Much more significant than the technical word size is the memory buss width, which determines how many bytes can be transferred between CPU and memory in one memory "cycle".
So "word size" is somewhat meaningless, and (as another answer suggests) companies like Microsoft will often define it in an arbitrary manner, with no real relationship to anything.

A:

Consider the following:
CPU (processor), RAM (main memory), I/O devices (mouse, keyboard, printer), Bus (data transfer component).
How would you like these computer parts to communicate and transfer data?
you definitely need a fixed size of bits to be considered a single unit of data.
For that, Computer scientists agreed to standardize this unit to be 32 bits or 64 bits (depending on the manufacturer choice).
They gave this unit a name and called it a Word.
So a Word is nothing but a unit of data (bunch of bits (signal charges of zeros and ones)) that moves around from a computer component to another.
For instance buses are built with 32 bits (4 bytes) and some with 64 bits (8 bytes). Likewise with the CPU (hardware) and operating systems (software) are built with either 32 bits or 64 bits.
It just happened to be the standard unit named Word and sized 32 bits or 64 bits.
Ps: Word is one of the many data size units that move around inside the computer, different computer components use different sizes to transport data (signals charges that represent zeros and ones), for instance  RAM can use size of 64 bits while Buses can use 32 bits. Hardware designers design the architecture of components taking into account these size differences to either implement Word size of 32 bits on only CPU but 64 bits on RAM, or implement the same size on all components, ...etc. Word size used to be 8 bits (1 byte), but nowadays the most comment unit size is 64 bits on most computer components such as CPU or RAM, or Bus, ...etc.


Q:

Equal command between wget and cURL (with options)?

I usually use wget to download remote file, the command I use:
wget --timeout=5 --tries=1 --referer=http://www.example.com 'http://www.example.com/abcdefg123.jpg' -O image.jpg
As you can see, there are 3 options: --timeout, --tries, and --referer.
I wonder what is the proper / equal command in cURL that has similar options in wget?

A:

I don't think there is an exact equivalent to the last detail, but something like this might work:
curl -L --connect-timeout 5 --retry 1 --referer http://www.example.com -o image.jpg http://www.example.com/abcdefg123.jpg


Q:

How to show/ hide windowActionBar programatically in Android?

I am applying one style to two activities. MainActivity.java has toolbar setup instead of action bar, therefore, I have following line in theme style to hide action bar:
<item name="windowActionBar">false</item>

And in the another activity I have action bar enabled:
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);

But this returns NOException error.
I tried following but didn't help either:
actionBar.show();

Style:
<style name="BrownTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/brown</item>
    <item name="colorPrimaryDark">@color/dark_brown</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="buttonStyle">@color/brown</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

Elaboration:
I am using style for two activities. The first activity has it's own toolbar instead of default action bar and the second activity has action bar. If I remove from style then I cannot run the first activity and if I put, then I cannot run the second activity. I want to enable it programatically in second activity.
Is there any possibility to change the style item attributes programatically? or any override method to bypass what I have in style item attributes?

A:

I fixed this using custom toolbar for both activities.
The style.xml now has the following theme:
<style name="BrownTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/brown</item>
    <item name="colorPrimaryDark">@color/dark_brown</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="buttonStyle">@color/brown</item>
</style>

And in the second activity (or all other activities):
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And the toolbar layout (app_bar_main.xml):
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

And the activity layout:
<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />


Q:

Use VB.NET DLL in VB.NET

I would like to use a Class Library project in a Windows Forms project. Here's what I did:

Make a Class Library project.
Code it.
Go to BUILD on the menu bar, then do Build.

Now that I've done that, I don't see an option to use the DLL in my other project.

A:

You need a reference to the library project to use it.
In the project where you want to use the library, right click on the "References" node in the solution explorer, and select "Add Reference...".
It will open the reference manager, there you select the "Solution" tab. It will show you the projects in your solution, and you can check the checkbox in front of your library project.


Q:

Angular 2 Currency Pipe

I am using currency pipe in angular2, current I am using
{{price | currency:'USD':true:'1.2-2'}}

which outputs $480,000.00 But The result I want is $480k, is this possible to achieve?

A:

I end up creating my own custom pipe
@Pipe({
name: 'salePrice'
})

export class PricePipe implements PipeTransform {
    transform(input: number): any {

    let price: number = input;

        if (price > 3000000) {
            return '3m+';
        }

        if (price / 1000 > 1) {
            if (price / 1000000 >= 1) {
                return parseFloat((price / 1000000).toFixed(3)) + "m";
            } else {
                return parseFloat((price / 1000).toFixed(2)) + "k";
            }
        } else {
            return price;
        }
    }
}


Q:

Spark : Use map and reduce with SparkSql

I shouldnot be asking this question and I really don't want to ask, but I am lost. I see lots of tutorials that uses wordcount as example. But I am having problem to understand how to use it with sparkSql
for example, I have following query
Dataset<Row> totalItem = spark.sql(" select icode from bigmart.o_sales");

It gives me Dataset? now I can iterate over totalItem and print result but I want to count how many times the item occurs. This can be done with map and reduce , but I don't know how to do.
Also, if anyone knows sparkSql using java where we can store result in variable rather than using show(), I would be really gratefull

A:

If you want to count how many times a item occur you can do it using sparksql query itself  as follows:
spark.sql("select icode,count(icode) from bigmart.o_sales group by icode")
or you can use api as follows:
val df=spark.table("bigmart.o_sales").groupBy($"icode").count.show

Hope it answers your questions


Q:

Why wont my footer stick ?

I want to stick my footer to the very bottom of the page without spacing so it show the same on every screen.
This is how it looks currently:
http://www.slyfiles.com/login.php
Footer code:

 © 2012 SlyFiles  About  &nbspTOS  &nbspDMCA

and the CSS:
.footer {
background: #1d1d1d;
width: 100%;
height: 32px;
border-top: solid 10px #017cc5;
margin-top: 5px;
}

Why won't it stick to bottom?
Thanks!

A:

Add this to your CSS for .footer:
position: fixed;
bottom: 0;


Q:

Why my transition does not work?

I have this component with transition effect
import React, { Component } from 'react';
import '../css/App.css';
import Transition from 'react-transition-group/Transition';

class TransitionComp extends Component{

    state = {
      show: true
    }

    showDiv = () => {
        this.setState({show: !this.state.show ? true : false})
    }

    render(){
        return(

                <Transition in={this.state.show} timeout={2000}>
                    {state =>

{state}

                    }
                </Transition>

Show or Hide

        )
    }
}

export default TransitionComp;

When I press on show or hide I dont see ease animation just the sate changes so why is that ?

A:

Your code is correct, there are some type mistakes instead of existed should be exited and existing should be exiting.
   <Transition in={this.state.show} timeout={2000}>
      {state =>

{state}

      }
    </Transition>


Q:

jquery add tag around unnested text

This is a really hard question to find a title for, but here is it.
I got this HTML, that I can't change

        First part of the list

item 1

item 2

        Second part of the list

item 3

And I'd like to apply things to the "first part of the list" and "Second part of the list" part, but not the nested ul part, like CSS transform scaleY, and a custom Jquery onClick method.
So, the solution I'd like would be a way to JQueryly add  around those.
Is this possible?
Thank you a lot

A:

To achieve this you can filter() the li contents() to retrieve the text nodes within it, then wrap that in a span and apply the needed CSS rules. Something like this:

$('#container > ul > li').each(function() {
  var foo = $(this).contents().filter(function() {
    return this.nodeType == 3 && this.textContent
  }).wrap('');
});
#container > ul > li > span {
  color: red;
  display: inline-block;
  transform: scaleY(2);
  margin: 0 0 10px;
}

      First part of the list

item 1

item 2

      Second part of the list

item 3


Q:

WCF WebHttpServiceHostFactory vs. WebServiceHostFactory

What is the difference between WCF's WebHttpServiceHostFactory and  WebServiceHostFactoryhosting?

A:

Assuming that you're talking about the HttpServiceHostFactory from the new WCF Web API - http://wcf.codeplex.com/SourceControl/changeset/view/44d95f912edf#WCFWebApi%2fHttp%2fSrc%2fMicrosoft.ApplicationServer.Http%2fmicrosoft%2fApplicationServer%2fHttp%2fActivation%2fHttpServiceHostFactory.cs - this factory sets up the service / endpoint using the new HTTP pipeline for WCF (which is on codeplex). The WebServiceHostFactory sets up a service / endpoint using the "traditional" WCF REST style API (i.e., the one which was released with .NET Framework 3.5 and improved in 4.0).


Q:

モデルのリレーションに関して[UserモデルとOneToOneで紐づけたモデルからデータを取得したい]

タイトルに関してお伺いしたいです。宜しくお願い致します。
環境

Python 3.6.8 :: Anaconda, Inc.
Django              2.1.7
django-allauth      0.39.1

djangoの作成目的：日報管理を行うアプリを構築
⬛プロジェクトの構成
Report
 |
  --accounts_app
 |
  --result_app
⬛モデルの構成
accounts_app.models
 ・Region
 ・Department
 ・UserProfile(OneToOne=>User)
　  - (department)=ForeignKey(Department)
result_app.models
 ・ResultReport
    - (owner) = ForeignKey(User)
    - (department)= ForeignKey(Department)
この、ResultReport内のdepartmentフィールドのdefaultを、UserProfileのdepartmentに設定したいのですが、adminサイトでデータの追加を見るとうまくいっていません。
⬛現在試していること
(report.models)
from accounts.models import Region, Department, UserProfile
class ResultReport(models.Model):
owner = models.ForeignKey(User, default=User.username, ・・・・省略)
department = models.ForeignKey(Department, default=str(UserProfile.user_region, ・・・・省略)

◆　コードは動くのですが、、（最初、makemigrationsすると、下記のエラーを吐き、
ValueError: Cannot serialize：django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x105de3e10、取り合えずstr()で囲んだらmigrateできたのですが、、）
反映されていません。
ひとまず動くので手動でもいいとは思うのですが、、どこをどうすれば良いかわからず質問させていただきます。
※　appを分けているのはall-authを使ってみたくてtutorialをすすめて、accountsappを作成しただけなので特に理由はありません。
※　User.usernameも拾わないので、、何か勘違いがあるのだと思っています。ご教示いただければ幸いです。
何卒宜しくお願い致します。

A:

models.py と admin.py の実際のコードを見ないと確かなことはわかりませんが、 default はそのような使い方はできないのではないでしょうか。
そのようなことをしたい場合は ResultReport の save() メソッドを上書きしてコードで設定するようにする必要があるものと思います。


Q:

Push Language Skills

Based on this:

link
  May wanted to push her language skills, so before joining Davis Polk, she did an intensive Mandarin study in Beijing for two months.

what does "push her language skills" mean?

A:

The connotation of "push" in this context is that May wants to challenge herself. If you read further down in the paragraph from the article you linked, you see May quoted as saying, "Davis Polk is a great place to be challenged." The author of the sentence you quote is probably trying to find a way to reinforce this theme of "being challenged" that May brought up in her interview without using the same word repeatedly.
The way this sentence is framed--"push [a skill]"--is a bit unusual and may sound awkward to the English-speaking ear. You will more commonly see "push [him/her/my/yourself]" or "push [a person]", e.g.:

"May had taken Mandarin classes in America for several years, but she really wanted to push herself, so she traveled to Beijing for a language-immersion experience."
"The runner was exhausted, but he pushed himself to complete the last few miles of the marathon."
The teacher pushed his students to do their best work.

"Push" may also carry the connotation of "force," even when physical pushing is not involved, depending on the context, e.g.:

The mine shaft had failed a safety inspection, but the supervisor pushed the miners to enter it by threatening to dock their pay.


Q:

Display UIAlertViewController in Gamescene?

So apparently GameScene cannot .presentViewController, so here's what I did.
let msg="Congrats... You died!\n"+"Score: "+String(score)
                let myAlert: UIAlertController = UIAlertController(title: msg, message: "Try Again?", preferredStyle: .Alert)
                let okAction = UIAlertAction(title: "Play Again", style: UIAlertActionStyle.Default) {
                    UIAlertAction in
                    self.timer.invalidate() //timer is not properly invalidating... it multple bacteria spawn... eevery 10 seconds with t difference ~0.5 seconds <-- FIXED as of 2/29/16
                    self.timer=NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: Selector("spawnBacteria"), userInfo: nil, repeats: true)
                    self.spawnBacteria()
                    score=0
                  //  print("FIRE")
                }
                myAlert.addAction(okAction)
                // _______________

                self.view?.window?.rootViewController?.presentViewController(myAlert, animated: true, completion: nil)

However, it appears that this does not work for multiple views, and I would like to add another view for the menu of my game. So, how can I create this UIAlertViewController and add it onto the GameScene? Any help is much appreciated.
NOTE: I am aware that an identical question was asked, however I do not understand the answer, and I don't know where to place the pieces of code provided in the answer, so please don't dismiss this question. Thanks

A:

You can use JSAlertView which display alert using old/new API depending on running iOS version. This displays alert over window, so you need not to worry about the view/navigation hierarchy.
Hope this will help.


Q:

Change calendar view's layout

I have a calendar list with about 8 views created by filtering on Location. Is it possible to have these views appear differently than the default? I've selected "Week" as the scope for all the views. Here's what I need:

The calendar is shaded to indicate the workweek from Monday - Friday, 8 - 5. Can this be changed? So the workweek would be from Sunday - Thursday, 8 - 5:30 p.m.
Can the full day name appear at the top instead of the one letter abbreviation?
Can we set the display time range for the days of the week? It currently defaults to 7 a.m. - 7 p.m. for the calendar. We'd like it to go from 6 a.m. to 10 p.m.
Can the calendar display area be scrollable vertically? This way, we limit its height to a set value and let the user scroll inside.

The calendar is based on a custom content type, which is based on the Event type. I have access to jQuery so if these changes require it, that's no problem. Thank you :)

A:

You can define your work week and time range by changing your site Regional settings under Site Settings > Site Administration > Regional Settings > Define Your Work Week.
By applying different work week and time range your calendar will render differently (maybe not exactly as you require).
To make other desired changes you will need to use jQuery and/or css.


Q:

AWS API Gateway: User anonymous is not authorized to execute API

Trying to post to an API I've created in API gateway:
{
    "Message": "User: anonymous is not authorized to perform: execute-api:Invoke on resource: arn:aws:execute-api:us-west-2:***********:jrr7u1ekrr/v0/POST/user"
}

How can I update the policy in CloudFormation to make publicly available the POST endpoint? I'm declaring the API with the AWS::ApiGateway::RestApi resource type.
the API policy property is:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "execute-api:/*/POST/user"
        }
    ]
}

A:

Something that tripped me up:  "If the API has been deployed previously in the API Gateway console, you'll need to redeploy it for the resource policy to take effect."
https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-resource-policies-create-attach.html


Q:

How to make child Tree Items checked/un-checked if parent Tree was made checked/un-checked

I'm having a Check-box Tree View structure, consisting of parent and child nodes.
I want to make all the child nodes [of the parent node] appear as checked if parent Tree is checked. Similarly, if parent Tree is unchecked then its childrens should be unchecked.

A:

The best way to achieve this would be using the JFace CheckboxTreeViewer as it has the following predefined methods to simplify the task.

setSubtreeChecked -  Sets the child elements checked on selecting the parent node
getCheckedElements - Gets all the checked tree elements
final CheckboxTreeViewer treeViewer = new CheckboxTreeViewer(parent);

// When user checks a checkbox in the tree, check all its children
treeViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
    // If the item is checked . . .
    if (event.getChecked()) {
      // . . . check all its children
      treeViewer.setSubtreeChecked(event.getElement(), true);
    }
  }
});

// Get the selected elements from the tree
Object[] actuallyChecked = treeViewer.getCheckedElements();


Q:

Querying elasticsearch returns all documents

i wonder why a search for a specific term returns all documents of an index and not the documents containing the requested term.
Here's the index and how i set it up:
(using the elasticsearch head-plugin browser-interface)
{
  "settings": {
    "number_of_replicas": 1,
    "number_of_shards": 1,
    "analysis": {
      "filter": {
        "dutch_stemmer": {
          "type": "dictionary_decompounder",
          "word_list": [
            "koud",
            "plaat",
            "staal",
            "fabriek"
          ]
        },
        "snowball_nl": {
          "type": "snowball",
          "language": "dutch"
        }
      },
      "analyzer": {
        "dutch": {
          "tokenizer": "standard",
          "filter": [
            "length",
            "lowercase",
            "asciifolding",
            "dutch_stemmer",
            "snowball_nl"
          ]
        }
      }
    }
  }
}

{
  "properties": {
    "test": {
      "type": "string",
      "fields": {
        "dutch": {
          "type": "string",
          "analyzer": "dutch"
        }
      }
    }
  }
}

Then i added some docs:
{"test": "ijskoud"}
{"test": "plaatstaal"}
{"test": "kristalfabriek"}

So now when firing a search for "plaat" somehow one would expect the search would come back with the document containing "plaatstaal".
{
  "match": {
    "test": "plaat"
  }
}

However saving me further searches elasticsearch retuns all documents regardless of its text content.
Is there anything I am missing here?
Funny enough: there is a difference when using GET or POST. While using the latter brings back no hits, GET returns all documents.
Any help is much appreciated.

A:

You need to configure your index to use your custom analyzer:
PUT /some_index
{
  "settings": {
     ...
  },
  "mappings": {
    "doc": {
      "properties": {
        "test": {
          "type": "string",
          "analyzer": "dutch"
        }
      }
    }
  }
}

If you have more fields that use this analyzer and don't want to specify for each the analyzer, you can do it like this for a specific type in that index:
  "mappings": {
    "doc": {
      "analyzer": "dutch"
    }
  }

If you want ALL your types in that index to use your custom analyzer:
  "mappings": {
    "_default_": {
      "analyzer": "dutch"
    }
  }

To test your analyzer in a simple way:
GET /some_index/_analyze?text=plaatstaal&analyzer=dutch

This would be the full list of steps to perform:
DELETE /some_index

PUT /some_index
{
  "settings": {
    "number_of_replicas": 1,
    "number_of_shards": 1,
    "analysis": {
      "filter": {
        "dutch_stemmer": {
          "type": "dictionary_decompounder",
          "word_list": [
            "koud",
            "plaat",
            "staal",
            "fabriek"
          ]
        },
        "snowball_nl": {
          "type": "snowball",
          "language": "dutch"
        }
      },
      "analyzer": {
        "dutch": {
          "tokenizer": "standard",
          "filter": [
            "length",
            "lowercase",
            "asciifolding",
            "dutch_stemmer",
            "snowball_nl"
          ]
        }
      }
    }
  },
  "mappings": {
    "doc": {
      "properties": {
        "test": {
          "type": "string",
          "analyzer": "dutch"
        }
      }
    }
  }
}

POST /some_index/doc/_bulk
{"index":{}}
{"test": "ijskoud"}
{"index":{}}
{"test": "plaatstaal"}
{"index":{}}
{"test": "kristalfabriek"}

GET /some_index/doc/_search
{
  "query": {
    "match": {
      "test": "plaat"
    }
  }
}

And the result of the search:
{
   "took": 1,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 1.987628,
      "hits": [
         {
            "_index": "some_index",
            "_type": "doc",
            "_id": "jlGkoJWoQfiVGiuT_TUCpg",
            "_score": 1.987628,
            "_source": {
               "test": "plaatstaal"
            }
         }
      ]
   }
}


Q:

Mockito ArgumentCaptor with lambda (Chronicle Queue)

I have implemented following Chronicle Queue and for this I want to write unit test case. How do I capture ArgumentCaptor arguments while using lambda. I want to get writeBuffer in test case to verify the data.
public class Persister  {

public Persister(SingleChronicleQueue chronicle) {
    this.chronicle = chronicle;
}
public void write(int outBufferOffset) throws IOException {
       ExcerptAppender appender = chronicle.acquireAppender();
       appender.writeBytes(b -> {
               b.writeInt(outBufferOffset);
               b.write(writeBuffer, 0 , outBufferOffset);
       });}
}

Test case:
@Mock
SingleChronicleQueue chronicle;
@Mock
ExcerptAppender appender;
@Captor
ArgumentCaptor<WriteBytesMarshallable> argumentCaptorLambda;

Persister persister = new Persister();
@Test
public void shouldPersistByteMessage() throws IOException {
    persister.write(MESSAGEBYTES);

    verify(appender).writeBytes(argumentCaptorLambda.capture());
    WriteBytesMarshallable lastValue =  argumentCaptorLambda.getValue();

    //final byte[] persistedBytes = ?? how to get writeBuffer here ??
    //assertThat(readPersistedMessage(persistedBytes), is(MESSAGE));
}

Thanks

A:

I have used the doAnswer for this implementation
@Captor
ArgumentCaptor<WriteBytesMarshallable> argumentCaptorLambda;
@Mock private BytesOut bytesOut;

public void shouldPersistReliableMessage() throws IOException {
        doAnswer(invocationOnMock -> {
            WriteBytesMarshallable marshallable = (WriteBytesMarshallable) invocationOnMock.getArguments()[0];
            marshallable.writeMarshallable(bytesOut);
            return null;
        }).when(appender).writeBytes((WriteBytesMarshallable)any());

        persister.persist(MESSAGEBYTES);

        verify(bytesOut).writeInt(84);
        verify(bytesOut).write(argumentCaptor.capture(), eq(0), eq(84));

        assertThat(readPersistedMessage(argumentCaptor.getValue()), is(MESSAGE));

    }