Q: Large react-redux form app I've been working on rewriting one of the modules in my company using react, the module is a single page composable of 4-5 different forms, selections made in each form are then determine the appeareance of the next form step.
There are a lot of "static" input fields which not affecting the visual ui state of the app, but are required to send to the server, other inputs are changing the ui state.
I'm looking for the right approach for this type of apps, since it seems attaching onChange event to every single input (there are more than 100 inputs total in the whole page). I've used react-redux-forms plugin, but it is too much of a blockbox for me, since I need to have direct access to the state and make decision based on it. I would preferer hacing more control over the state.
Is the right solution to bind onChange event for every input? Or is there a better approach.

A: We do this with redux-form quite easily. Because everything's maintained in the fields prop, you could do something like this:
const Form = ({
  fields,
  handleSubmit,
  saveForm
}) => (
  <form onSubmit={handleSubmit(saveForm)}>
    <fieldset>
      <input type="text" {...fields.hasAlternativeDelivery} />
    </fieldset>
    {fields.hasAlternativeDelivery.value === true &&
      <fieldset>
        {/* more fields go here */}
      </fieldset>
    }
  </form>
);

We then conditionally validate certain fieldsets like this.
So, to answer your question: you shouldn't rely on change events to hide / show certain fields, this goes against the very nature of React (React is declarative, what you're describing is an imperative way of doing things). Instead, figure out what state (/props) should lead to which UI.


Q: JQuery effect continues to iterate I have a div within a parent div, that is normally hidden. When you hover over the parent div the child is then visible. I am using JQuery .toggle() to get this effect. The problem is that if you MouseIn and MouseOut really fast, repeatedly over the parent, the child div is toggled that many times. Is there a way to prevent this from happening, it is slowing down my page?
JSFIDDLE: http://jsfiddle.net/vY59g/1/
My JQuery:
$(document).ready(function() {
    $(".result").hover(function() {
        $(this).find(".result-user-facts").toggle("slow");
    });
});

A: It is because the queuing nature of animations, every mouser enter and mouse leave operation queues a toggle operation. So if there are quick movement of mouse triggering the enter and leave events then even after the events are over the animations will keep happening.
The solution is to stop and clear previous animations before the toggle is called using .stop()
$(document).ready(function() {
    $(".result").hover(function() {
        $(this).find(".result-user-facts").stop(true, true).toggle("slow");
    });
});

Demo: Fiddle

A: If you want to make things better, just put div:.result-user-facts into an Variable if there only has one. Like this:
$(function (){
    var container = $(".result");
    var item = container.find(".result-user-facts").eq(0);
    $(".result").hover(function (){
        item.stop().toggle("slow");
    });
});

A: Use .stop(true,true)

Stop the currently-running animation on the matched elements.

Fiddle DEMO
$(document).ready(function() {
    $(".result").hover(function() {
        $(this).find(".result-user-facts").stop(true,true).toggle("slow");
    });
});


Q: what port tomcat7 use? how do I set AWS Security group? I run a tomcat7 in ubuntu in aws. not use apache.
and my site use default tomcat port 8080.
I don't want to open port except 8080 so I'm setting in aws security group.
inbound
8080 TCP anywhere
and outbound allTraffic.
but I try to rest call to
http://my_aws_ip:8080/test.do

but it doesn't work.
What should I open the port?
Does tomcat7 use a some port?

A: Tomcat uses whatever port or ports and protocols you configure it to use.  By default it listens for HTTP requests on tcp/8080, AJP requests on tcp/8009, and service management requests on tcp/8005.
This is configured in Connector elements in $CATALINA_HOME/conf/server.xml:
https://tomcat.apache.org/tomcat-7.0-doc/config/http.html
You should reconfigure Tomcat to listen on standard ports like tcp/80 for HTTP and tcp/443 for HTTPS.  Non-standard ports are a ready indication of a novice deployment.
The AWS Security Group should be configured to allow HTTP, HTTPS, pr both depending on your need.  I highly recommend using HTTPS unless the information being transferred is public domain or has no value.
You can check what ports Tomcat is using on your EC2 instance with netstat -anpt.  It will show all active and listen ports and the programs that have bound them (including java or tomcat for your Tomcat ports).
Unless you really need root access to the OS, you might want to consider using Amazon Elastic Beanstalk as it manages all that cruft for you.


Q: Setting size of inner region of Java SWT shell window In a Java SWT shell window, how do I set its inner size than its whole window frame size?
For instance, if I use shell.setSize(300, 250) this would make the whole window appearing as exactly 300x250. This 300x250 includes the size of the window frame.
How can I set the inner size, that is the content display region of the shell window to 300x250 instead? That's this 300x250 excludes the width of the window frame.
I tried to minus some offset values but the thing is different Operating Systems have different window frame sizes. So having a constant offset would not be accurate.
Thanks.

A: From your question what I understood is that you want to set the dimension of the Client Area. And in SWT lingo it is defined as a rectangle which describes the area of the receiver which is capable of displaying data (that is, not covered by the "trimmings").
You cannot directly set the dimension of Client Area because there is no API for it. Although you can achieve this by a little hack. In the below sample code I want my client area to be 300 by 250.  To achieve this I have used the shell.addShellListener() event listener. When the shell is completely active (see the public void shellActivated(ShellEvent e)) then I calculate the different margins and again set the size of my shell. The calculation and resetting of the shell size gives me the desired shell size.
>>Code:
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;

public class MenuTest {

    public static void main (String [] args)
    {
        Display display = new Display ();
        final Shell shell = new Shell (display);

        GridLayout layout = new GridLayout();
        layout.marginHeight = 0;
        layout.marginWidth = 0;
        layout.horizontalSpacing = 0;
        layout.verticalSpacing = 0;
        layout.numColumns = 1;
        shell.setLayout(layout);
        shell.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,true));
        final Menu bar = new Menu (shell, SWT.BAR);
        shell.setMenuBar (bar);

        shell.addShellListener(new ShellListener() {

            public void shellIconified(ShellEvent e) {
            }
            public void shellDeiconified(ShellEvent e) {
            }
            public void shellDeactivated(ShellEvent e) {
            }
            public void shellClosed(ShellEvent e) {
                System.out.println("Client Area: " + shell.getClientArea());
            }
            public void shellActivated(ShellEvent e) {
                int frameX = shell.getSize().x - shell.getClientArea().width;
                int frameY = shell.getSize().y - shell.getClientArea().height;
                shell.setSize(300 + frameX, 250 + frameY);
            }
        });

        shell.open ();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch ()) display.sleep ();
        }
        display.dispose ();
    }
}

A: If I get you right you should set the size of the inner component to the needed size and use the method pack() (of the frame).

A: import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;

public class SWTClientAreaTest
{
    Display display;
    Shell shell;
    final int DESIRED_CLIENT_AREA_WIDTH = 300;
    final int DESIRED_CLIENT_AREA_HEIGHT = 200;

    void render()
    {
        display = Display.getDefault();
        shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);

        Point shell_size = shell.getSize();
        Rectangle client_area = shell.getClientArea();

        shell.setSize
        (
            DESIRED_CLIENT_AREA_WIDTH + shell_size.x - client_area.width,
            DESIRED_CLIENT_AREA_HEIGHT + shell_size.y - client_area.height
        );

        shell.open();

        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }

        display.dispose();
    }

    public static void main(String[] args)
    {
        SWTClientAreaTest appl = new SWTClientAreaTest();
        appl.render();
    }
}

A: Use computeTrim to calculate the bounds that are necessary to display a given client area. The method returns a rectangle that describes the bounds that are needed to provide room for the client area specified in the arguments.
In this example the size of the shell is set so that it is capable to display a client area of 100 x 200 (width x height):
Rectangle bounds = shell.computeTrim(0, 0, 100, 200);
shell.setSize(bounds.width, bounds.height);

This article describes the terms used by SWT for widget dimensions:
https://www.eclipse.org/articles/Article-Understanding-Layouts/Understanding-Layouts.htm


Q: Android custom Drawable vs custom View I wanted to know what's the difference between creating a custom Drawable like in the Shelves project: http://code.google.com/p/shelves/ to creating a custom View?

A: Drawble only response for the draw operations, while view response for the draw and user interface like touch events and turning off screen and more.
View can contain many Drawbles.


Q: Android Timer is firing twice I am trying to update TextView content every second using Timer Class. Given below is my code. The problem is that the value is increasing by 2 not by 1. Please tell me what the problem is.
public class MainActivity extends ActionBarActivity {

    public void onButtonClick (View view) {
        // calendar
        OnDateSetListener datelistener = new OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int Year, int monthOfYear, int dayOfMonth) {
                                ....
                reScheduleTimer(); // starting the timer
            }
        };
    }

    public void reScheduleTimer(){
        timer = new Timer();
        timerTask = new myTimerTask();
        timer.schedule(timerTask, 1000, 1000);
    }
    public class myTimerTask extends TimerTask{
        @Override
        public void run() {
            elapsed = elapsed + 1;

            runOnUiThread(new Runnable(){
             public void run() {
                    TextView seconds = (TextView) findViewById(R.id.seconds);
                    seconds.setText("seconds so far "+elapsed);
                }
            });
        }
    }
}

A: Wouldn't hurt to check if timerTask is null at the beginning of reScheduleTimer and cancel it if it is not null.
At the beginning of reScheduleTimer:
    if(timerTask != null) {
        timerTask.cancel();
    }

A: I still don't know how the variable is increasing by more than 1, but I solved the problem by reading the system clock on every invocation of the function and displaying it.


Q: Is it possible to auto-start a WCF for only specific projects? I have a WCF project which several other projects depend on, but others, like unit testing projects and other support utilities which don't need the service.  It contains the following XML in the .csproj file:
<ProjectExtensions>
  <VisualStudio>
    <FlavorProperties GUID="{3D9AD99F-2412-4246-B90B-4EAA41C64699}">
      <WcfProjectProperties>
        <AutoStart>True</AutoStart>
      </WcfProjectProperties>
    </FlavorProperties>
  </VisualStudio>
</ProjectExtensions>

Is there a way to get the "auto-start service with project" functionality to only apply to specific projects in the solution?  Or is it all or nothing?  Is there anything I could add to the other projects to tell them they depend on this service to make it auto-start in the debugging session?  Or add some condition to the service's .csproj that depends on which project is the current startup project?
I tried experimenting with Condition="'$(Configuration)' == 'Debug'" in various places, but I couldn't get it to behave an different based on that Configuration variable.

A: To make the client applications debugable, create a new tiny project and set both the service and the client application as dependencies.  The only file it should contain is Program.cs, and its only function should look like this:
[STAThread]
static void Main(string[] args)
{
    new System.ServiceModel.ServiceHost(typeof(MyServiceClass)).Open();
    MyClientApplication.Program.Main(args);
}

And then merge the app.config for both into a single app.config for this tiny application.  But now the service is hosted inside the same process as the client, and they can both be debugged interchangeably.
This allows removing the AutoStart feature from the service, but still run the client application together with the service.


Q: rails how to display data or retrieve values after find I did a find on some model and got the following
>> @addy
=> [#<Address id: 3, street: "Some Street", houseNumber: nil, created_at: "2010-01-20 06:09:52", updated_at: "2010-01-20 06:09:52", address_id: 16>]

Now how do I retrieve the values?  what if i want the street?
@addy.street does not work netiher does @addy[:street]
what if i had a list of @addy's and wanted to loop through them to show street for each?

A: @addy.first.street should work, as it is list of Adress classes containing only one member.
For displaying each street for more adresses in list:
@addy.each do |address|
  puts address.street
end

or
list_of_streets = @addy.map { |address| address.street }

Edit:
When you have problem identifying what class you have, always check object.class. When you just use object in IRB, then you see output from object.inspect, which doesn't have to show class name or even can spoof some informations. You can also call object.methods, object.public_methods.
And remember that in Ruby some class is also an instance (of Class class). You can call @addr.methods to get instance methods and @addr.class.methods to get class methods.
Edit2:
In Rails #find can take as first parameter symbol, and if you pass :first of :last, then you'll get only one object. Same if you pass one integer (id of retrieved object). In other cases you get list as result, even if it contains only one object.


Q: How do I get the current size of the heap memory of a process in Linux using C/C++ system calls? I am working on a software library, which can constantly keep track of the size of the heap memory of programs written in C/C++.
What I would like to do is as follows.
void check_memory(){

  heap_size = get_process_heap_size(.....);

  if(heap_size>=upper_bound){

    //do something to reduce the heap size

    heap_size = get_process_heap_size(.....);
  }
}

Is there any system call in C/C++ that is equivalent to get_process_heap_size() in the code above?

A: I dont know if there is any direct system call that gives you memory details, but if you are on linux you can read and parse /proc/(pid of your process)/status file to get the needed memory usage counts


Q: JAVA HOME PATH correctly set in Environment but wrong when compiling via Node.js I received this isue: com.sun.tools.javac.Main is not on the classpath. Oerhaps JAVA_HOME does not point to the JDK. It is currently set to "C:\Program Files\Java\jre7"
However, my JAVA HOME is set as follows:
C:\Program Files\Java\jdk1.7.0_51

With PATH
C:\Program Files\Java\jdk1.7.0_51

Any recommendations?

A: When node.js spawns a forked environment, it doesn't copy over your user's environment variables. You will need to do that manually.
You will need to get JAVA_HOME from process.env and set it in your exec() call.
Something like this should work:
var config = {
    env: process.env
};
exec('javacmd', config,
    function() {
        console.log(arguments);
});

Or if you wanted to be more explicit, you could extract only the variables you needed (JAVA_HOME, etc) from process.env
See here for more details:
How to exec in NodeJS using the user's environment?

A: Just uninstall node js and re install node js. Its solve my problem.


Q: forcing overflow-x using percentage and float I have a small structure of
 inside a container and what i'm trying to make is to force the overflow-x appear instead of overflow-y, but i can't achieve this, i presume it is beacuse of properties float and the percentage that i'm using.
is there i way where i can reach this result ? show only the horizontal overflow ?
here is the code:
html

Box 1

Box 2

Box 3

Box 4

Box 5

Box 6

Box 7

and css
#CockpitCenter {
   height: 500px; /* set only here in jsFiddle */
   position: fixed;
   left: 0;
   border: solid 2px #ccc;
   border-bottom: none;
   overflow: auto;
}

div#CockpitCenter ul.CockpitContainerResult {
   float: left;
   width: 100%;
}

ul.CockpitContainerResult li {
   margin: 5px 0;
   height: 150px;
   width: 50%;
   float: left;
}

ul.CockpitContainerResult li:nth-child(even) {
    float: right;
}

ul.CockpitContainerResult li div.box {
    border: solid 1px #ccc;
    margin: 15px;
    border-radius: 20px;
    height: 150px;
    text-align: center;
}

here is a demo

A: Sounds like you are trying to make a carousel, which there are many handy jquery plugins for. Regardless, you cannot do this using percentages for widths, you have to give your main container a fixed width, then give the inner one (your ul) whatever larger width you want. You must force a width on the UL otherwise the LI elements will just wrap. Once thats done just add an 'overflow-x: auto' to the main container and you should be on your way.
Quick example, http://jsfiddle.net/ybJ6C/8/
I'm using my ipad right now, and didn't see the scroll bar but it does indeed scroll. You'll notice that the scroll continues well past the end, you can adjust that with the width if you know what you want. If its dynamic then you would need js to adjust the width for you based on the elements within. I also don't have the height correct, but its enough to get the idea. (again doing this from my ipad, coding ain't the greatest)


Q: remove all styles based on browser version I would like to know how i can remove all css styles based on checking if the browser is less than IE8.
So if it detects IE7 then remove all styles? I wonder if this is possible via some jquery?
Will this fix most IE7 issues:
<!--[if lt IE 7]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE7.js"></script>
<![endif]-->

A: I don't know why you want to remove all styles for a browser version. I suppose that you have some CSS problems with IE7, and often a good way of fixing it, rather than deleting all your CSS, is to use ie7.js: http://code.google.com/p/ie7-js/.
Here is a demo of what it can do.
Also, this script has a version for IE8 and IE9.

A: <!--[if lt IE 8]>
    <body class='oldIE'>
<![endif]-->
<!--[if gte IE 8]>
    <body class='ok'>
<![endif]-->
<!--[if !IE]>
    <body class='ok'>
<![endif]-->

here you would need to prefix all the styles you don't IE7 to apply with .ok
another method would be
<!--[if lt IE 8]>
    //include an old IE specific stylesheet or none at all
<![endif]-->
<!--[if gte IE 8]>
    //include your stylesheets
<![endif]-->
<!--[if !IE]>
    //include your stylesheets
<![endif]-->

A: The best solution is to remove a specific class name rather than wiping the entire CSS for an element:
// Identity browser and browser version

if($.browser.msie && parseInt($.browser.version) == 7) {

   // Remove class name
   $('.class').removeClass('class');

   // Or unset each CSS selectively
   $('.class').css({
      'background-color': '',
      'font-weight': ''
   });

}


Q: Why is a foreach data binding not creating a $parent context? In the following code, why is the remove handler accessible without $parent?
If I use data-bind="click: $parent.remove" I get an error saying that property remove of undefined doesn't exists, but being inside a foreach loop, shouldn't I get a $parent context?
Template:

 <button data-bind="click: remove">x</button>

ViewModel:
function ViewModel() {

    var self = this;

    this.list = ko.observableArray(['asd', 'lol', 'rofl']);

    this.remove = function(index){
        console.log('Clicked ' + index);
        self.list.splice(index, 1);
    };

};

ko.applyBindings(ViewModel);

https://jsfiddle.net/3d7nfbr3/3/

A: You are missing the new, when creating your viewmodel.
Your code should look like this:
ko.applyBindings(new ViewModel());

Without the new the this refers to the global window object so your remove function is declared globally, that is why the $parent is not working.
Demo JsFiddle.


Q: Want to update my old html css ,js site with React , $('some').owlCarousel, throws an error Type error , owlCarousel is not a function Want to update my old HTML, CSS ,js site with React.
I make the components for HTML and integrate js also, but when I am trying to import and run owl carousel in jquery, like $('some').owlCarousel, throws an error Type error,

owlCarousel is not a function


Q: How count objects with element value? I need your help.
I have for example such array:
  var array = [{
    "name": "Tony",
    "year": "2010"
}, {
    "name": "Helen",
    "year": "2010"
}, {
    "name": "Jack",
    "year": "2005"
}, {
    "name": "Tony",
    "year": "2008"
}, {
    "name": "Max",
    "year": "2005"
}];

How i can count them by year and get something like this:
2010 = 2 times;
2005 = 2 times;
2008 = 1 time;

Thank you

A: check this fiddle
var countObj = {};
for( var counter = 0; counter < array.length; counter++ )
{
   var yearValue = array [ counter ].year;
   if ( !countObj[ yearValue ] )
   {
      countObj[ yearValue ] = 0;
   }
   countObj[ yearValue ] ++;
}
console.log( countObj );

A: Try this:
var array = [{
    "name": "Tony",
    "year": "2010"
}, {
    "name": "Helen",
    "year": "2010"
}, {
    "name": "Jack",
    "year": "2005"
}, {
    "name": "Tony",
    "year": "2008"
}, {
    "name": "Max",
    "year": "2005"
}];
var map={}
for (var i = 0; i<array.length;i++){
   if ( !map[ array [ i ].year ] ){
      map[ array [ i ].year ] = 0;
   }
   map[ array [ i ].year] ++;
}
console.log( map );

Fiddle

A: Here arrange uses reduce to build an object using the years as keys. It accepts a prop argument so that you can build the object as you see fit.
function arrange(arr, prop) {
  return arr.reduce(function(p, c) {
    var key = c[prop];
    p[key] = p[key] || 0;
    p[key]++;
    return p;
  }, {});
}

You can then iterate over the key/values of that object and print out the results for year:
var obj = arrange(array, 'year');
for (var p in obj) {
  console.log(p + ' = ' + obj[p] + ' times');
}

Or even by name:
var obj = arrange(array, 'name');

DEMO

A: You are trying to re-invent the wheel.
This and many more methods are exposed by a third-party JS library, called "lodash"; old name was "underscore". All its methods or most of them are exposed like
_.methodName(listName, iteratorFunction)

You can download it at: https://lodash.com/
Once you download and include lodash your script in your html, go to your function and do:
_.groupBy(yourArrayVariable, function(item){
    return item.year;
});

WARNING
This method will not return an array. It will return a JSON, in which the keys are represented by the "item.year" through the whole original array, and the values will be an array for each year listed. Every such array is a list of objects having the same "year" value:
{
   "2010" : [
        { "name" : "Tony", "year" : "2010" },
        { "name" : "Helen", "year" : "2010" }
   ],
   "2011" : [ ..... ]
}

Lodash has lots of useful methods anyway.

A:

var array = [{
    "name": "Tony",
    "year": "2010"
}, {
    "name": "Helen",
    "year": "2010"
}, {
    "name": "Jack",
    "year": "2005"
}, {
    "name": "Tony",
    "year": "2008"
}, {
    "name": "Max",
    "year": "2005"
}];

var result = {};
array.forEach(function(data) {
    console.log(data.year);
    result[data.year] = result[data.year] ? ++result[data.year] : 1;
});

document.write(JSON.stringify(result));


Q: Split list of student according to their mark - haskell There is a list of students where
data Student = Student {
   name :: String,
   mark :: Mark
} deriving Show

data Mark = F|E|D|C|B|A deriving (Show, Eq, Ord)

I need to split it like that [(mark,[students with this mark])]
I made something like this:
splitToGroups :: [Student] -> [(Mark, [String])]
splitToGroups [] = []
splitToGroups students = foldr funct [] students where
    funct student [] = [(mark student,[name student])]
    funct student ((x,xs):xss) | mark student == x = ((x,(name student):xs):xss)
                               | otherwise = (mark student,[name student]):(x,xs):xss

but it works incorectly. Maybe someone knows how it could be done..

A: Don't manually recurse if you can use standard tools. You can do this with sorting and grouping, but IMO preferrable is to use the types to express that you're building an associative result, i.e. a map from marks to students.
import qualified Data.Map as Map

splitToGroups :: [Student] -> Map.Map Mark [String]
splitToGroups students = Map.fromListWith (<>)
     [ (sMark, [sName])
     | Student sName sMark <- students ]

(If you want a list in the end, just use Map.toList.)

A: If you view Student as a tupple, your function has this type: splitToGroups :: [(Mark,String)] -> [(Mark, [String])].
So you need a function with type: [(a,b)] -> [(a,[b])].
Using Hoogle: search results
I get the following functions:
groupSort :: Ord k => [(k, v)] -> [(k, [v])]
collectSndByFst :: Ord a => [(a, b)] -> [(a, [b])]
They should solve your problem, remember to import the modules listed in the link to make them work. You should make a funtion that maps from Student -> (Mark, String) first.


Q: Passing data to collectionViewCell I'm want to use some custom struct in my collection view cell. I get the data from my API service and trying to pass it to my custom collection view cell.
I found couple answers but I still couldn't figure out how to do
Here is where I get the actual data:
    func FetchFormData(linkUrl: String) {

    let parameters: [String: AnyObject] = [:]

    let postString = (parameters.flatMap({ (key, value) -> String in
        return "\(key)=\(value)"
    }) as Array).joined(separator: "&")

    let url = URL(string: linkUrl)!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)

        let contentData = responseString?.data(using: .utf8)
        do {
            let decoder = JSONDecoder()
            self.formData = try decoder.decode(FormModel.self, from: contentData!)

        } catch let err {
            print("Err", err)
        }

        DispatchQueue.main.async {
            //here is the where I reload Collection View
            self.collectionView.reloadData()
        }

    }
    task.resume()
}

Also here I'm trying to pass data to the cell:
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! BaseFormCollectionViewCell

    cell.backgroundColor = .green

    //Data could be print out here
    print(self.formData?.components?[indexPath.row])
    cell.formComponent = (self.formData?.components?[indexPath.row])!

    return cell
}

The actual problem is starting into my cell class
class BaseFormCollectionViewCell: UICollectionViewCell {

var formComponent: FormComponent!{
    didSet {
        //data can be print out here
        print("Passed value is: \(formComponent)")
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)

    //this part is always nill
    print(formComponent)

}

}
As you guys can see in the code It's going well until my collection view cell.
It should be a lot more simple but I couldn't figure out what's going on and Why its happening.

A: Modify your cell class as
class BaseFormCollectionViewCell: UICollectionViewCell {

var formComponent: FormComponent!{
    didSet {
        //this is unnecessary. You can achieve what u want with a bit more cleaner way using configure function as shown below
        //data can be print out here
        print("Passed value is: \(formComponent)")
    }
 }

 override init(frame: CGRect) {
    super.init(frame: frame)

    //this part is always nill
    print(formComponent)

 }

 func configure() {
    //configure your UI of cell using self.formComponent here
 }
}

finally
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! BaseFormCollectionViewCell

    cell.backgroundColor = .green

    //Data could be print out here
    print(self.formData?.components?[indexPath.row])
    cell.formComponent = (self.formData?.components?[indexPath.row])!
    (cell as! BaseFormCollectionViewCell).configure()
    return cell
}

Look for (cell as! BaseFormCollectionViewCell).configure() in cellForItemAt thats how u trigger the UI configuration of cell after passing data to cell in statement above it.
Quite frankly u can get rid of didSet and relay on configure as shown
Hope it helps


Q: android - rendering bitmaps from native code - nativeCreate bitmaps are not cleanedup from memory I am streaming a video in android and I decode frames in native code and then copy the pixels to a bitmap, then display the bitmap in Java using canvas.unlockandpost with a while loop for all the bitmaps.
Everything is fine, but the streaming of bitmaps is very slow and causes a crash. I only see a message on logcat saying that "low memory no more background processes".
I see on the allocation table from eclipse, that the bitmaps that I created are not getting deleted from memory, even though, I am overwritng the pixels everytime. Is there any way I can clean up the memory it is keeping.
My code is as follows.
C Code :
AndroidBitmapInfo  info;
void*              pixels;
int                ret;

if ((ret =AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) {
}

memcpy(pixels, pictureRGB, 480*320);

AndroidBitmap_unlockPixels(env, bitmap);

Java Code
     Bitmap mBitmap = Bitmap.createBitmap(480, 320, Bitmap.Config.RGB_565);
     renderbitmap(mBitmap, 0);
     canvas.drawBitmap(mBitmap, 0, 0, null);

A: The code shown in your question is missing some critical parts to fully understand your problem, but it sounds like you're creating a new bitmap for every frame.  Since Android only allows for about 16MB of allocations for each Java VM, your app will get killed after about 52 frames.  You can create a bitmap once and re-use it many times.  To be more precise, you are creating a bitmap (Bitmap.CreateBitmap), but not destroying it (Bitmap.recycle).  That would solve your memory leak, but still would not be the best way to handle it.  Since the bitmap size doesn't change, create it once when your activity starts and re-use it throughout the life of your activity.


Q: ASP.NET web pages code behind So does the new ASP.NET web pages (also called razor pages) framework using the Razor view engine (referring to this: http://www.asp.net/webmatrix/tutorials/1-getting-started-with-webmatrix-and-asp-net-web-pages) not actually have any code-behind file?  I looked on the samples and couldn't find an example.  I assume no, but maybe there is a header reference where you can link it that I might be missing?
Can anyone confirm?
Thanks.

A: According to this blog you can easily have code-behind. http://www.compiledthoughts.com/2011/01/aspnet-mvc3-creating-razor-view-engine.html
Do you need it or not this is for you to decide. I strongly resent answers which starts with "you dont need it..".
Every person in the world must have a choice whether to shoot for a moon or shoot himself in the foot. Thats what I think is right.

A: There are no code behind files for Razor Views because you don't need them. You are writing the presentation logic using the Razor syntax on the view itself.
Razor views simplifies the mixing of raw HTML with dynamic content rendered using Razor syntax so you don't need a separate file. Furthermore there are no such things as Controls or Components in razor views so you don't need to configure them in a separate file.


Q: Populate a JComboBox with file names of a specific directory I want to populate a JComboBox with file names of a directory. Then, if selected, each field has to show a JList. How can i implement this?
Thanks

A: You can use File>>listFiles()

http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html

to get the array of Files in a particular directory (the one you initialized the File-object with).
You can then use the individual File's getName() method to get the names, then use JComboBox's addItem() method to add those names:

http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JComboBox.html

Finally, to do something when the user clicks one of those names you have to install an item-listener using the JComboBox's addItemListener()-method. There are tutorials on how to do this last part and in general it just calls your ItemListener, giving it an ItemEvent, which you can then use to check which name was clicked.


Q: Specflow 2.0.0 What is the alternative to using ScenarioContext.Current? I have upgraded to Specflow 2.0.0. with NUnit 3 (also tried with XUnit) and I want to be able to execute test cases in parallel in an attempt to reduce the elapsed time it takes to run the tests.
On attempting to execute the tests in parallel an error is returned stating that I cannot use FeatureContext.Current and ScenarioContext.Current.
The tests use these to extract the names of the feature and scenario for the additional logging.
The tests also use the tags to be able to control the tests.
For Example:
I am aware that it is possible to put the tags in the attributes
[Binding]
public class SpecFlowHooks
{
    public ScenarioContext context;

    public SpecFlowHooks(ScenarioContext scenarioContext)
    {
        context = scenarioContext;
    }

    [BeforeScenario("SpecialCase")]
    public void BeforeScenario_SpecialCase() {
        do some stuff
    }

    [BeforeScenario]
    public void BeforeScenario() {
        do different stuff
    }
}

The problem with this is that BeforeScenario always runs.  I do not want it to run if the tag "SpecialCase"  is not present as the application will not be in the correct state.  I therefore extract the tags and do something different if the tag "SpecialCase" is present.
How can I find the list of tags without using
List<String> tags = ScenarioContext.Current.ScenarioInfo.Tags.ToList();

A: The alternative for parallel execution is to allow the dependency injection system which specflow uses to provide you with the ScenarioContext instance. To do that have your steps class accept an instance of the ScenarioContext and store it in a field:
[Binding]
public class StepsWithScenarioContext
{
    private readonly ScenarioContext scenarioContext;

    public StepsWithScenarioContext(ScenarioContext scenarioContext)
    {
        if (scenarioContext == null) throw new ArgumentNullException("scenarioContext");
        this.scenarioContext = scenarioContext;
    }

    [Given(@"I put something into the context")]
    public void GivenIPutSomethingIntoTheContext()
    {
        scenarioContext.Set("test-value", "test-key");
    }
}

A fuller explanation of how to use parallel execution can be found here
A similar approach needs to be taken to get the tags. Again add a constructor which takes a ScenarioContext to your class which holds your [BeforeScenario] method, and save the ScenarioContext in a field and use this filed instead of the ScenarioContext.Current


Q: SalesForce REST API INVALID_SESSION_ID error using v38.0 I am using SalesForce REST API For my PHP Application
But, when I send request at "instance_url/services/data/v38.0" along with the access token , I get this error:
[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]

I have a developer salesforce account and have API enabled true for every profile.
This is my Headers:
$headers = array(
          "Content-Type: application/x-www-form-urlencoded",
          "Accept:application/json",
          "Authorization: Bearer ".$access_token
          );

Used in CURL.


Q: Java: changing the order of lines with while-loop I am new to programming and I would like to ask what should I do so that the final value of k  will appear before the values of a, when I try to put it inside the loop it repeats the statement and when I put it before the loop, its value is 0.
    System.out.printf("Input an integer: ");
    int a = in.nextInt();
    int k = 0;

    System.out.print(a);
    while(a > 1)
    {
        if(a % 2 == 0)
            a = a / 2;
        else
            a = 3 * a + 1;
        System.out.printf(", " + a);
        k++;
    }
    System.out.println("\nk = " + k);

    Output:
    Input an integer: 10
    10, 5, 16, 8, 4, 2, 1
    k = 6

A: You could try:
    System.out.printf("Input an integer: ");
    int a = in.nextInt();
    int k = 0;
    String str_a = "";

    System.out.print(a);
    while(a > 1)
    {
        if(a % 2 == 0)
            a = a / 2;
        else
            a = 3 * a + 1;
        str_a += ", " + String.valueOf(a);
        k++;
    }
    System.out.println("k = " + k);
    System.out.println("a = " + str_a);


Q: javascript/jquery: focus() not working I want to focus a special id (in roundcube) by a keyboard shortcut. The html is
   ...

    ...

I tried the following:
 // Strg + Tab, um in Nachrichtenbereich zu kommen
 ...
 else if (event.keyCode == 9 && event.ctrlKey) {
 alert("taste erkannt");
 //document.getElementById("messagetoolbar").focus();
 //$("#messagetoolbar").focus();
 setTimeout(function() { $('#messagetoolbar').focus(); alert("zeit"); }, 3000);
 }
 ...

The first alert and the second alert is shown but no focus on id messagetoolbar. Does anybody have an idea?
Thank you very much.
Edit: I think I should describe it better: I want to mark the first line/email in the email-inbox in roundcube. The inbox is a table with a tr-tag...when I try your solution the first line is dotted, too, but with enter I can't open the mail and with other keys I can't MARK the first line/mail... I think I have to "simulate a left-klick" to get the first line marked...?
Now I tried to use jquery's .trigger. The html of the inbox-Table is

         16.04.2014 13:41

 ...

I tried to use...
 $('#messagelist tr').eq(1).addClass('message selected focused').removeClass('unfocused').trigger("click");

...but it doesn't work: It adds an removes the classes but doesn't really focus the line  :-( With "buttons" it works.
EDIT AGAIN: I think the file list.js of roundcube is important for that question. There I found the following:
/**
 * Set focus to the list
 */
focus: function(e)
{
  var n, id;
  this.focused = true;

  for (n in this.selection) {
    id = this.selection[n];
    if (this.rows[id] && this.rows[id].obj) {
      $(this.rows[id].obj).addClass('selected').removeClass('unfocused');
    }
  }

  // Un-focus already focused elements (#1487123, #1487316, #1488600, #1488620)
  // It looks that window.focus() does the job for all browsers, but not Firefox (#1489058)
  $('iframe,:focus:not(body)').blur();
  window.focus();

  if (e || (e = window.event))
    rcube_event.cancel(e);
},

Does anybody know how to modify or use referring to my question? Thank you!

A: Add tabindex=0 attribute to the div you want to foucs and you will be able to set focus on the div using .focus()

A: You can not focus controls like div, span etc. You can move to that div if required using book marks.

A: Do you want to highlight the div then you can use the jquery and following code to give highlight effect.
$("div").click(function () {
  $(this).effect("highlight", {}, 3000);
});

A: Good morning,
I've read a few times now, that one can't focus table rows but only can focus elements, which accepts input by the user. Otherwise I think there must be a way to simulate a click on a table row by jquery/javascript!  I tried the following:
document.onkeydown = function(event) {
  ...
  else if (event.keyCode == 9 && event.ctrlKey) {
   $('#messagelist tr').on('click', function () {
    alert('I was clicked');
    });
    $('#messagelist tr').eq(1).click();
  }
...
}

The alert is shown! But the row isn't "marked"!?


Q: remove code duplication in java with custom getter This question isnt about selenium, but java in general
I have the scenario below, while trying to setup an automation framework using selenium and page object model -
public class SigninPage {

    WebDriver driver;

    private By emailInputSelector = By.id("user_email");
    private By passwordInputSelector = By.id("user_password");
    private By signinBtnSelector = By.xpath("//input[@value='Log In']");
    private By errorDivSelector = By.xpath("//div[@role='alert']");
    private By headerLinksSelector = By.className("nav-link");

    public SigninPage(WebDriver driver) {
        this.driver = driver;
    }

    public WebElement emailInput() {
        return driver.findElement(emailInputSelector);
    }

    public WebElement passwordInput() {
        return driver.findElement(passwordInputSelector);
    }

    public WebElement signinBtn() {
        return driver.findElement(signinBtnSelector);
    }

    public WebElement errorDiv() {
        return driver.findElement(errorDivSelector);
    }

    public List<WebElement> headerElement() {
        return driver.findElements(headerLinksSelector);
    }

}

as you can see, all my methods like headerElement() etc are doing the same thing - driver.findElement(selector) or sometimes driver.findElements(selector)
I want to remove this code duplication, like lombok provides @Getter.
What is my best bet to achieve this?


Q: HTML5 Dynamic Video Background here is my code

$("body").prepend("
<video loop muted autoplay class='fullscreen-bg__video' ><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'></video>
")

and its working fine. but what i need is, I want to call a function say remove-pre-loader(), once the video is loaded.
i have a per-loader screen, i want to remove the pre-loader once the video is loaded.

A: You can use loadeddata or canplaythrough event to check whether the browser has loaded the current frame of the audio/video. See a full list of possible video events here

$("body").prepend(
  "
<video loop muted autoplay class='fullscreen-bg__video' ><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'><source src='https://www.iresearchservices.com/wp-content/uploads/2018/03/bgvideo.mp4' type='video/mp4'></video>
"
);
$(".fullscreen-bg__video").on("loadeddata", function () {
        alert("Video Loaded")
    });
.fullscreen-bg {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: -100;
}

.fullscreen-bg__video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

@media (min-aspect-ratio: 16/9) {
  .fullscreen-bg__video {
    width: 100%;
    height: auto;
  }
}

@media (max-aspect-ratio: 16/9) {
  .fullscreen-bg__video {
    width: auto;
    height: 100%;
  }
}
@media (min-aspect-ratio: 16/9) {
  .fullscreen-bg__video {
    height: 300%;
    top: -100%;
  }
}

@media (max-aspect-ratio: 16/9) {
  .fullscreen-bg__video {
    width: 300%;
    left: -100%;
  }
}


Q: How can I get a regex to check that a string only contains alpha characters [a-z] or [A-Z]? I'm trying to create a regex to verify that a given string only has alpha characters a-z or A-Z. The string can be up to 25 letters long. (I'm not sure if regex can check length of strings)
Examples:
1. "abcdef" = true;
2. "a2bdef" = false;
3. "333" = false;
4. "j" = true;
5. "aaaaaaaaaaaaaaaaaaaaaaaaaa" = false; //26 letters
Here is what I have so far... can't figure out what's wrong with it though
Regex alphaPattern = new Regex("[^a-z]|[^A-Z]");
I would think that would mean that the string could contain only upper or lower case letters from a-z, but when I match it to a string with all letters it returns false...
Also, any suggestions regarding efficiency of using regex vs. other verifying methods would be greatly appreciated.

A: /// <summary>
/// Checks if string contains only letters a-z and A-Z and should not be more than 25 characters in length
/// </summary>
/// <param name="value">String to be matched</param>
/// <returns>True if matches, false otherwise</returns>
public static bool IsValidString(string value)
{
    string pattern = @"^[a-zA-Z]{1,25}$";
    return Regex.IsMatch(value, pattern);
}

A:
The string can be up to 25 letters long.
  (I'm not sure if regex can check length of strings)

Regexes ceartanly can check length of a string - as can be seen from the answers posted by others.
However, when you are validating a user input (say, a username), I would advise doing that check separately.
The problem is, that regex can only tell you if a string matched it or not. It won't tell why it didn't match. Was the text too long or did it contain unallowed characters - you can't tell. It's far from friendly, when a program says: "The supplied username contained invalid characters or was too long". Instead you should provide separate error messages for different situations.

A: The regular expression you are using is an alternation of [^a-z] and [^A-Z]. And the expressions [^…] mean to match any character other than those described in the character set.
So overall your expression means to match either any single character other than a-z or other than A-Z.
But you rather need a regular expression that matches a-zA-Z only:
[a-zA-Z]

And to specify the length of that, anchor the expression with the start (^) and end ($) of the string and describe the length with the {n,m} quantifier, meaning at least n but not more than m repetitions:
^[a-zA-Z]{0,25}$

A: Regex lettersOnly = new Regex("^[a-zA-Z]{1,25}$");

*

*^ means "begin matching at start of string"

*[a-zA-Z] means "match lower case and upper case letters a-z"

*{1,25} means "match the previous item (the character class, see above) 1 to 25 times"

*$ means "only match if cursor is at end of string"

A:
I'm trying to create a regex to verify that a given string only has alpha
  characters a-z or A-Z.

Easily done as many of the others have indicated using what are known as "character classes".  Essentially, these allow us to specifiy a range of values to use for matching:
(NOTE: for simplification, I am assuming implict ^ and $ anchors which are explained later in this post)
[a-z]   Match any single lower-case letter.
ex: a matches, 8 doesn't match
[A-Z]   Match any single upper-case letter.
ex: A matches, a doesn't match
[0-9]   Match any single digit zero to nine
ex: 8 matches, a doesn't match
[aeiou] Match only on a or e or i or o or u.
ex: o matches, z doesn't match
[a-zA-Z]  Match any single lower-case OR upper-case letter.
ex:  A matches, a matches, 3 doesn't match
These can, naturally, be negated as well:
[^a-z]  Match anything that is NOT an lower-case letter
ex: 5 matches, A matches, a doesn't match
[^A-Z]  Match anything that is NOT an upper-case letter
ex: 5 matches, A doesn't matche, a matches
[^0-9]  Match anything that is NOT a number
ex: 5 doesn't match, A matches, a matches
[^Aa69] Match anything as long as it is not A or a or 6 or 9
ex: 5 matches, A doesn't match, a doesn't match, 3 matches
To see some common character classes, go to:
http://www.regular-expressions.info/reference.html

The string can be up to 25 letters long.
  (I'm not sure if regex can check length of strings)

You can absolutely check "length" but not in the way you might imagine.  We measure repetition, NOT length strictly speaking using {}:
a{2}  Match two a's together.
ex:  a doesn't match, aa matches, aca doesn't match
4{3}  Match three 4's together.
ex:  4 doesn't match, 44 doesn't match, 444 matches, 4434 doesn't match
Repetition has values we can set to have lower and upper limits:
a{2,}  Match on two or more a's together.
ex:  a doesn't match, aa matches, aaa matches, aba doesn't match, aaaaaaaaa matches
a{2,5} Match on two to five a's together.
ex:  a doesn't match, aa matches, aaa matches, aba doesn't match, aaaaaaaaa doesn't match
Repetition extends to character classes, so:
[a-z]{5}  Match any five lower-case characters together.
ex:  bubba matches, Bubba doesn't match, BUBBA doesn't match, asdjo matches
[A-Z]{2,5}  Match two to five upper-case characters together.
ex:  bubba doesn't match, Bubba doesn't match, BUBBA matches, BUBBETTE doesn't match
[0-9]{4,8}  Match four to eight numbers together.
ex:  bubba doesn't match, 15835 matches, 44 doesn't match, 3456876353456 doesn't match
[a3g]{2}  Match an a OR 3 OR g if they show up twice together.
ex:  aa matches, ba doesn't match, 33 matches, 38 doesn't match, a3 DOESN'T match
Now let's look at your regex:
[^a-z]|[^A-Z]
Translation:  Match anything as long as it is NOT a lowercase letter OR an upper-case letter.
To fix it so it meets your needs, we would rewrite it like this:
Step 1:  Remove the negation
[a-z]|[A-Z]
Translation: Find any lowercase letter OR uppercase letter.
Step 2:  While not stricly needed, let's clean up the OR logic a bit
[a-zA-Z]
Translation: Find any lowercase letter OR uppercase letter.  Same as above but now using only a single set of [].
Step 3:  Now let's indicate "length"
[a-zA-Z]{1,25}
Translation: Find any lowercase letter OR uppercase letter repeated one to twenty-five times.
This is where things get funky.  You might think you were done here and you may well be depending on the technology you are using.
Strictly speaking the regex [a-zA-Z]{1,25} will match one to twenty-five upper or lower-case letters ANYWHERE on a line:
[a-zA-Z]{1,25}
a matches, aZgD matches, BUBBA matches, 243242hello242552 MATCHES
In fact, every example I have given so far will do the same.  If that is what you want then you are in good shape but based on your question, I'm guessing you ONLY want one to twenty-five upper or lower-case letters on the entire line.  For that we turn to anchors.  Anchors allow us to specify those pesky details:
^ beginning of a line
(I know, we just used this for negation earlier, don't get me started)
$ end of a line
We can use them like this:
^a{3}  From the beginning of the line match a three times together
ex:  aaa matches, 123aaa doesn't match, aaa123 matches
a{3}$  Match a three times together at the end of a line
ex:  aaa matches, 123aaa matches, aaa123 doesn't match
^a{3}$  Match a three times together for the ENTIRE line
ex:  aaa matches, 123aaa doesn't match, aaa123 doesn't match
Notice that aaa matches in all cases because it has three a's at the beginning and end of the line technically speaking.
So the final, technically correct solution, for finding a "word" that is "up to five characters long" on a line would be:
^[a-zA-Z]{1,25}$
The funky part is that some technologies implicitly put anchors in the regex for you and some don't.  You just have to test your regex or read the docs to see if you have implicit anchors.

A: Do I understand correctly that it can only contain either uppercase or lowercase letters?
new Regex("^([a-z]{1,25}|[A-Z]{1,25})$")

A regular expression seems to be the right thing to use for this case.
By the way, the caret ("^") at the first place inside a character class means "not", so your "[^a-z]|[^A-Z]" would mean "not any lowercase letter, or not any uppercase letter" (disregarding that a-z are not all letters).


Q: How to set unique for specific field from specific table? I have this where i have all features from database:
$features = Feature::all();

User can add new additional feature that will be added in this table, but i want to validate so if user enter something that is already in databse to get a message. So name need to be unique. Any suggestion how can i do that?
I tried this but it save it anyway.
 $this->validate($request, [
        'name' => 'unique:features',
    ]);

A: From the docs

unique:table,column,except,idColumn
The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.
Specifying A Custom Column Name:
'email' => 'unique:users,email_address'

You may need to specify the column to be checked against.

A:  $feauturescheck= Feauture::where('Columname', '=',Input::get('input'))->count();


Q: is there Material increment/decrement Button implementation for Android? is there by any chance a Material design implementation for increment/decrement button ? image for illustration

A: No, but it's quite simple to implement, you only need a linear layout with horizontal orientation, containing a button, a textview and another button.
Have an internal value to count and then associate a callback to your buttons, where you add/substract your counter and update the textview, like this:
substractButton.setOnClickListener(v -> {
  count--;
  countTextView.setText(count);
});
sumButton.setOnClickListener(v -> {
  count++;
  countTextView.setText(count);
});


Q: JSOUP parse for android force closes I am trying to use JSOUP to get the menu data from a website (http://hdh.ucsd.edu/mobile/dining/locationdetails.aspx?l=11) but whenever I try to fetch the links, my android app crashes. What is the reason? This is the code I have
public class SixthFragment extends Fragment {

String url = "http://hdh.ucsd.edu/mobile/dining/locationdetails.aspx?l=11";
ProgressDialog mProgressDialog;
String MENU;
String HOURS;
TextView textview;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_sixth, container, false);
    textview = (TextView) rootView.findViewById(R.id.textView10);

    new JSOUP().execute();
    return rootView;

}

public class JSOUP extends AsyncTask<Void, Void, Void>{
    ProgressDialog dialog;

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        dialog = new ProgressDialog(getActivity());
        dialog.setMessage("loading...");
        dialog.show();

    }

    @Override
    protected Void doInBackground(Void... params){
        try{

            Document document = Jsoup.connect(url).get();
            Elements elements = document.select("a[href]");
            //HOURS = elements.text();
            System.out.println(elements.size());
            for(int i = 0; i<elements.size(); i++){

                MENU += "\n" + elements.get(i).text();
                System.out.println(i);

            }

        }

        catch (Exception e){

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result){
        dialog.dismiss();

        textview.setText(MENU);
        super.onPostExecute(result);
    }

}

}

And my error shows up as this
11-28 13:48:59.175 23230-23230/com.lamdevs.tritonbites E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.lamdevs.tritonbites, PID: 23230
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.lamdevs.tritonbites.fragments.SixthFragment$JSOUP.onPostExecute(SixthFragment.java:82)
at com.lamdevs.tritonbites.fragments.SixthFragment$JSOUP.onPostExecute(SixthFragment.java:43)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Which I don't understand because elements has a size of 61 when I output the size of elements. Also, is there a way to get the breakfast, lunch, and dinner separately? Thank you

A: Please post your layout XML R.layout.fragment_sixth. Probably you're referring to a wrong id, which causes de NullPointerException.

To get each "Breakfast", "Lunch" and "Dinner" separately, you can simply iterate through the last three <div> tags inside the HTML element with id MainContent_divDailySpecials (I did find that id looking at the website DOM structure through Chrome Developer Tools inspector).
So, as a start, simply grab that element with
Document document = Jsoup.connect(url).get();
Element parentDiv = document.getElementById("MainContent_divDailySpecials");

and from there on you can iterate backwards to get the last three children of that div. (Please keep in mind that if, in any point in time, the structure of that page changes your code will break).

A: Looking at the error log you attached ..
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.lamdevs.tritonbites.fragments.SixthFragment$JSOUP.onPostExecute(SixthFragment.java:82)

It talks about a NullPointerException on a TextView in SixthFragment Line 82 i.e. textview.setText(MENU);
The textview is initialized (textview = (TextView) rootView.findViewById(R.id.textView10);) which looks okay.
So, make sure you have a TextView with id textView10 in your layout fragment_sixth.


Q: How to change Ruby and Rails version for the Rails base Docker image? Docker base image rails provides a full environment for Ruby on Rails. It pulls from the ruby upstream image. The rails base image specifies Ruby and Ruby on Rails versions.
What if we want to use different Ruby and Ruby on Rails versions?
Do we edit our Dockerfile in our project folder? Or, do we ssh into the machine, and install the ruby version we want and then build our own image?
Further details:
The rails base image documentation says that your doc file can simply be one line of code:
FROM rails:onbuild

This line of code pulls from the rails image on Docker Hub. This image has its own Dockerfile. The first line of this Dockerfile is FROM ruby:2.2.
Just to restate the question, what is the best way to create a container based off of the rails image, with different Ruby and Ruby on Rails versions? If possible, some sample code might be helpful for understanding how to do this.

A: I assume you want a docker image that is suiteable for plenty of rails apps.
I do not know docker at all, but maybe ignore what Docker offers to you, and do it yourself:
Create an image with all great ruby versions, maybe 1.9 and 2.3,
but i think you should just stick with latest ruby.

Use https://github.com/rbenv/rbenv to provide a ruby env

Every Rails applications usually ships with a Gemfile.
In production releases, the gem versions are locked in the Gemfile.lock file.
In case the gems need an update, you will need to update the app code and then the gems with
bundle install

So i think it´s not possible to have a docker "one-fits-all" image for plenty of rails apps nicely.
Something i do when installing productive rails apps is to install their gems in the app folder.
bundle install --path vendor/bundle

This puts the gem apps inside their vendor directory. I see no big chance here either to make update life easier.

As i never tried docker, or even visited their website, my post might be useless (sry)
I hope i understood your intentions, at least.


Q: How can I download the oldest file of an FTP server? How can I download the oldest file of an FTP server?
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://192.168.47.1/DocXML");
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential("Igor", "");

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);

string names = reader.ReadLine();

textBox12.Text = names;

A:
How can I download the oldest file of an FTP server?

Using WebRequestMethods.Ftp.ListDirectoryDetails
This will issue an FTP LIST command with a request to get the details on the files in a single request. This does not make things easy though because you will have to parse those lines, and there is no standard format for them.
Depending on the ftp server, it may return lines in a format like this:
08-10-11  12:02PM       <DIR>          Version2
06-25-09  02:41PM            144700153 image34.gif
06-25-09  02:51PM            144700153 updates.txt
11-04-10  02:45PM            144700214 digger.tif

Or
d--x--x--x    2 ftp      ftp          4096 Mar 07  2002 bin
-rw-r--r--    1 ftp      ftp        659450 Jun 15 05:07 TEST.TXT
-rw-r--r--    1 ftp      ftp     101786380 Sep 08  2008 TEST03-05.TXT
drwxrwxr-x    2 ftp      ftp          4096 May 06 12:24 dropoff

Or even another format.
This blog post "Sample code for parsing FtpwebRequest response for ListDirectoryDetails" provides an example of handling several formats.
If you know what the format is, just create a custom minimal line parser for it.
Using WebRequestMethods.Ftp.ListDirectory with WebRequestMethods.Ftp.GetDateTimestamp
This is easier, but the downside is that it requires you to submit several requests to find out the last modification dates for the directory entries.
This will get you a list of file and directory entries with names only, that is easier to parse.
public static IEnumerable<string> ListDirectory(string uri, NetworkCredential credentials)
{
    var request = FtpWebRequest.Create(uri);
    request.Method = WebRequestMethods.Ftp.ListDirectory;
    request.Credentials = credentials;
    using (var response = (FtpWebResponse)request.GetResponse())
    using (var stream = response.GetResponseStream())
    using (var reader = new StreamReader(stream, true))
    {
        while (!reader.EndOfStream)
            yield return reader.ReadLine();
    }
}

Then for each file you can get the last modification date by issuing a request per file:
public static DateTime GetLastModified(string fileUri, NetworkCredential credentials)
{
    // error checking omitted
    var request = FtpWebRequest.Create(fileUri);
    request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
    request.Credentials = credentials;
    using (var response = (FtpWebResponse)request.GetResponse())
        return response.LastModified;
}

Now you can simply do the following to get a list of files with their last modification date.
var credentials = new NetworkCredential("Igor", "");
var filesAndDates = ListDirectory("ftp://192.168.47.1/DocXML", credentials)
    .Select(fileName => new {
        FileName = fileName,
        LastModified = GetLastModified("ftp://192.168.47.1/DocXML/" + fileName, credentials)
    })
    .ToList();
// find the oldest entry.
var oldest = filesAndDates.OrderBy(x => x.LastModified).FirstOrDefault();


Q: is SICP still recommended? I have some experience with python, I asked for a new language, and said that i am having a hard time implementing what I have learned. they suggested I learn SICP. Saying it uses a great language and teaches great programming fundamentals.
But I notice it was published in 1984. Do you guys recommend it, or have I been trolled? :p
Thanks.

A: Yes, SICP is still a great book! The second edition, which is available online, as of 1996. Although, if you just want to learn Scheme instead of fundamental computer science, you might be better off with Teach Yourself Scheme in Fixnum Days.

A: I strongly encourage you to check out the book How to Design Programs.  It focuses on the fundamentals of programming, not on the specific language, but it also uses Scheme as its language.  It's also available free online.
You can also check out the current release of the second edition, which is in preparation (or the less-stable but more up-to-date current draft).

A: Firstly, you're loooking at the first edition. The second edition is from 1996.
You should VERY MUCH tackle the book. I've gone through about half and my mind is blown. I can't begin to explain how amazing it is. Not only will you develop an appreciation for elegance in programming, but you'll see the line blurred between coding and computer science.
Don't approach this book like a programming book. Approach it as if you want to learn the fundamentals of computation and computer science using programming as a means of expression.

A: SICP is one of the best books I've read for learning how to write programs well.  I never used scheme outside of the work I did in that book, but it's well worth your time.


Q: Normalize samples with ffmpeg I am writing application for music analysis. I wrote resampling module relying on ffmpeg. Currently, I have AV_SAMPLE_FMT_S16 but later I have converting to float, which can be time consuming.
Because I need samples to be in some reasonable interval I need to do some kind of normalization, for AV_SAMPLE_FMT_FLT samples.
So, how I can normalize samples which I get when I select AV_SAMPLE_FMT_FLT. Ideal interval would be -n to n, where n is greater than equal of 1.f

A: Given that AV_SAMPLE_FMT_FLT is already normalised to the -1 .. 1 range, we can multiply each sample by your 'n' value to have it scaled between -n .. n


Q: error on string literal jsp So I want to create charts from jsp using fusioncharts. I'd choose fusioncharts then JFree, canvasjs or any other because I'd experiences using it in php language. It should be no problem in jsp because jsp and php are literally same, mapping above html, with only differences is their syntax. However, as I've done the code, it return String literal is not properly closed by a double-quote error on sql statement. Please help me because I am a beginner to jsp and java environment. Thank you.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<%@page import="java.util.*" %>
<%@page import="com.google.gson.*" %>
<%@page import="readConfig.readConfig" %>

<%
String hostdb = readConfig.getProperties("conUrl");              // MySQl host
String userdb = readConfig.getProperties("dbUser");              // MySQL username
String passdb = readConfig.getProperties("dbPass");                 // MySQL password
String driver = readConfig.getProperties("dbDriver");           // MySQL driver

DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection con = DriverManager.getConnection(hostdb , userdb , passdb);

%>

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Creating Charts with Data from a Database - fusioncharts.com</title>

    <%@page import="fusioncharts.FusionCharts" %>

    <%
        Gson gson = new Gson();

        String sql= "SELECT m.month,IFNULL(x.cnt, 0) AS cnt FROM
(SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m
LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS cnt FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month
ORDER BY m.month DESC";

        PreparedStatement pt=con.prepareStatement(sql);
        ResultSet rs=pt.executeQuery();

        Map<String, String> chartobj = new HashMap<String, String>();

        chartobj.put("caption", "Top 10 most populous countries");
        chartobj.put("showValues", "0");
        chartobj.put("theme", "zune");

        ArrayList arrData = new ArrayList();
        while(rs.next()) {
            Map<String, String> lv = new HashMap<String, String>();
            lv.put("label", rs.getString("Monthly"));
            lv.put("value", rs.getString("New Demand"));
            arrData.add(lv);
        }

        rs.close();

         Map<String, String> dataMap = new LinkedHashMap<String, String>();

         dataMap.put("chart", gson.toJson(chartobj));
         dataMap.put("data", gson.toJson(arrData));

        FusionCharts columnChart= new FusionCharts(
                    "column2d",
                    "chart1",
                    "500","300",
                    "chart",
                    "json",
                    gson.toJson(dataMap)
                );

        %>

        <%=columnChart.render()%>

error on eclipse terminal
Mar 27, 2018 2:07:17 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/registration] threw exception [Unable to compile class for JSP:

An error occurred at line: 78 in the jsp file: /dashboard.jsp
String literal is not properly closed by a double-quote
75:
76:
77:             // Form the SQL query that returns the number of sales in 2017
78:             String sql= "SELECT m.month, IFNULL(x.cnt, 0) AS cnt FROM
79:     (SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m
80:     LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS cnt FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month
81: ORDER BY m.month DESC";

Stacktrace:] with root cause
org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 78 in the jsp file: /dashboard.jsp
String literal is not properly closed by a double-quote
75:
76:
77:             // Form the SQL query that returns the number of sales in 2017
78:             String sql= "SELECT m.month, IFNULL(x.cnt, 0) AS cnt FROM
79:     (SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m
80:     LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS cnt FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month
81: ORDER BY m.month DESC";

A: in Java String literals are not allowed  more than one line .
so you can do using '+' like
String sql= "SELECT m.month,IFNULL(x.cnt, 0) AS cnt FROM "+
" (SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m "+
" LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS cnt FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month "+
" ORDER BY m.month DESC";

or write it in one line
String sql="SELECT m.month,IFNULL(x.cnt, 0) AS cnt FROM (SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12) AS m LEFT JOIN (SELECT DATE_FORMAT(date, '%c') as month, COUNT(*) AS cnt FROM ssl_sales where YEAR(date)=2017 AND status_ssl='new' GROUP BY month) AS x ON m.month = x.month ORDER BY m.month DESC";


Q: Python: Modify the internal behavior of a function by using decorator I'm learning to use python decorator.
def my_dcrtr(fun):
    def new_fun():
        return fun()
    return new_fun

I realize the decorated function 'fun' acts like a black box inside the decorator. I can choose to use fun() or not at all inside new_fun. However, I don't know whether I can break into 'fun' and interact with fun's local scope inside the new_fun?
e.g. I'm trying to make a toy Remote Procedural Call (RPC) with python.
def return_locals_rpc_decorator(fun):
    def decorated_fun(*args, **kw):
        local_args = fun(*args, **kw)
        # pickle the local_args and send it to server
        # server unpickle and doing the RPC
        # fetch back server results and unpickle to results
        return rpc_results

    return decorated_fun

@return_locals_rpc_decorator
def rpc_fun(a, b, c=3):
    return locals() # This looks weird. how can I make this part of the decorator?

print(rpc_fun(2, 1, 6))

In this example, I try to get rpc_fun's argument list at runtime with the 'locals()' command. Then send it to server to execute. Instead of letting rpc_fun returns its locals(), is it possible to use the decorator to retrieve decorated function's argument space?

A: You can use function annotations for Python3:
def return_locals_rpc_decorator(fun):
   def decorated_fun(*args, **kw):
      local_args = fun(*args, **kw)
      print(local_args)
      fun_parameters = fun.__annotations__
      final_parameters = {a:list(args)[int(b[-1])-1] for a, b in fun_parameters.items() if a != 'return'}
      return final_parameters
   return decorated_fun

@return_locals_rpc_decorator
def my_funct(a:"val1", b:"val2", c:"val3") -> int:
    return a + b + c

print(my_funct(10, 20, 30))

Output:
60
{'a': 10, 'b': 20, 'c': 30}

In this way, you are using the wrapper function decorated_fun to access the decorated function's parameters and further information specified by the annotation. I changed the parameter descriptions in the annotations so that each string value would end in a digit that could be used to index args. However, if you do not want to change the parameter descriptions in the annotations, you can sort via ending character.
Edit: the code in the body of my_funct is executed when called in the wrapper function (decorated_fun), since the args, declared in the scope of decorated_fun is passed to and unpacked in local_args.


Q: Balance between use of Ajax on $.ready() and loading data already I have a page which has several independent sections. Data is to be populated in each section by different queries to the database.
In order to lower the page load time, I have ajaxified the loading of each section (following the Amazon.com philosophy).
In order to load each section of the page, I make an ajax call on $.ready() method in my page which in turn fetches data from the database.
In all 6 requests are made to the (same) server which completely generate the sections.
Now, I'm not sure if I am overburdening the server by making 6 requests each time the page is requested. Any suggestions?
(I use Struts/Hibernate/Jsp/jQuery)

A: You can always queue your ajax calls so they happen 1 at a time.  There are jquery plugins to help with this:
http://www.protofunc.com/scripts/jquery/ajaxManager/
To me however, 6 calls does not seem too bad, as long as they dont generate a lot of server activity (hard db queries, file handling, etc...)

A: alternatively, you can start all your queries as soon as the page is requested, and save the results up for the ajax calls. This needs asynchronous execution on the server, and you need to make sure that the ajax response program can wait for the sql completion too.
If you query the same data in several of your 6 queries, this might be worth it. If tables are different for each, this might be really counterproductive (depending on your database engine, and cluster architecture).
However, if database stress and response time is a concern, caching techniques and other optimisations usually work better (memcache by example). But again this depends strongly on your database engine.


Q: Constructor parameter in configuration class required a bean of type 'StratusAuthenticationEntryPoint' that could not be found Parameter 0 of constructor in ResourceServerConfiguration required a bean of type 'StratusAuthenticationEntryPoint' that could not be found.
I am using spring boot 2.6.6
Here is the code:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(100)
//@Import({ApiPermissionEvaluator.class})
public class ResourceServerConfiguration extends WebSecurityConfigurerAdapter {

    private final StratusAuthenticationEntryPoint securityAuthenticationEntryPoint;

    public ResourceServerConfiguration(StratusAuthenticationEntryPoint securityAuthenticationEntryPoint) {
        super();
        this.securityAuthenticationEntryPoint = securityAuthenticationEntryPoint;
    }
}

error message:
            ***************************
        APPLICATION FAILED TO START
        ***************************

        Description:

        Parameter 0 of constructor in com.stratus.security.config.ResourceServerConfiguration required a bean of type 'com.stratus.security.config.StratusAuthenticationEntryPoint' that c
        ould not be found.

        Action:

        Consider defining a bean of type 'com.stratus.security.config.StratusAuthenticationEntryPoint' in your configuration.

A: *

*Add @Component over Class of StratusAuthenticationEntryPoint that a bean created by spring ioc

*verify if the ComponentScan path contains Class of StratusAuthenticationEntryPoint


Q: Maven build war doesn't work properly on Tomcat 7 I've been working on a web app that and here's me configuration before I get started telling my story.
Configuration: IntelliJ IDEA 11 + Java 7 + (Maven + Jetty 8.0.1).
When I clean and build my app on intelliJ, everything works as expected and nothing goes wrong; pages load, rendering are perfectly fine. Then I use -mvn clean package command to build my project so I'll test my app on Tomcat 7.
However, when I deploy my application to Tomcat, some pages aren't as I saw on my maven build: renderings doesn't work properly, styling is a little bit deprecated and so on...
Even some pages doesn't load fully when I check on firebug.
I wish someone encountered a similar issue; this thing is making me crazy... If you need any logs or anything just name it.
Thank you.

A: Apperently, there's always nuances that you miss sometimes and browsers keep extensive data of the pages you browser. I've just cleared all of my browsers caches and now everything works perfectly!.. So if you encounter something similar, be sure to clear your browser cache.


Q: How do I determine the start and end of instructions in an object file? So, I've been trying to write an emulator, or at least understand how stuff works. I have a decent grasp of assembly, particularly z80 and x86, but I've never really understood how an object file (or in my case, a .gb ROM file) indicates the start and end of an instruction.
I'm trying to parse out the opcode for each instruction, but it occurred to me that it's not like there's a line break after every instruction. So how does this happen? To me, it just looks like a bunch of bytes, with no way to tell the difference between an opcode and its operands.

A: For most CPUs - and I believe Z80 falls in this category - the length of an instruction is implicit.
That is, you must decode the instruction in order to figure out how long it is.

A: If you're writing an emulator you don't really ever need to be able to obtain a full disassembly. You know what the program counter is now, you know whether you're expecting a fresh opcode, an address, a CB page opcode or whatever and you just deal with it. What people end up writing, in effect, is usually a per-opcode recursive descent parser.
To get to a full disassembler, most people impute some mild simulation, recursively tracking flow. Instructions are found, data is then left by deduction.
Not so much on the GB where storage was plentiful (by comparison) and piracy had a physical barrier, but on other platforms it was reasonably common to save space or to effect disassembly-proof code by writing code where a branch into the middle of an opcode would create a multiplexed second stream of operations, or where the same thing might be achieved by suddenly reusing valid data as valid code. One of Orlando's 6502 efforts even re-used some of the loader text — regular ASCII — as decrypting code. That sort of stuff is very hard to crack because there's no simple assembly for it and a disassembler therefore usually won't be able to figure out what to do heuristically. Conversely, on a suitably accurate emulator such code should just work exactly as it did originally.


Q: What does QFE_Richmond actually mean? I am developing a VBA add-in for Excel that uses the RefEdit control.
One of my testers pointed out that he couldn't use keyboard shortcuts while selecting cells. And I found the solution to this problem here: http://support.microsoft.com/kb/291110
Set the magical value QFE_Richmond to 1 in the Excel section of HKEY_CURRENT_USER.
This solution works great.
My question is why?
What is the significance of the "QFE_Richmond" variable? Where did it come from? Why do you need this obscure flag to fix a simple glitch that has persisted at least through Excel 2010 and at least as far back as 2003?  Does this flag do anything else?
And is it safe to automatically make this change for the users of my add-in, even though it globally affects their Excel settings?

A: The obvious answer seems to be that they either forgot to apply it in each version or they don't consider it important enough to make default because it is on the border of being considered a bug or a usability preference because it has an easy workaround(i.e. using the GUI instead of shortcuts). I wouldn't think applying the hotfix would hurt anything - they wouldn't make it available if that were the case.
Changing QFE_Richmond registry key to 1 is a to enable a hotfix.
http://support.microsoft.com/?kbid=291110
"Typically, hotfixes are made to address a specific customer situation and may not be distributed outside the customer organization."
In addition, the RefEdit control seems to have alternatives:
http://peltiertech.com/WordPress/refedit-control-alternative/
Which have been recommended because it has compatability issues:
http://peltiertech.com/WordPress/unspecified-painfully-frustrating-error/
So you could probably presume that MS has some gaps in their quality control for the RefEdit feature.
Good Luck.
EDIT/ADDITION:
By the way,
QFE stands for Quick Fix Engineering


Q: Assign a new column in pandas in a similar way as in pyspark I have the following dataframe:
df = pd.DataFrame([['A', 1],['B', 2],['C', 3]], columns=['index', 'result'])

index
result

A
1

B
2

C
3

I would like to create a new column, for example multiply the column 'result' by two, and I am just curious to know if there is a way to do it in pandas as pyspark does it.
In pyspark:
df = df\
.withColumn("result_multiplied", F.col("result")*2)

I don't like the fact of writing the name of the dataframe everytime I have to perform an operation as it is done in pandas such as:
In pandas:
df['result_multiplied'] = df['result']*2

A: Use DataFrame.assign:
df = df.assign(result_multiplied = df['result']*2)

Or if column result is processing in code before is necessary lambda function for processing counted values in column result:
df = df.assign(result_multiplied = lambda x: x['result']*2)

Sample for see difference column result_multiplied is count by multiple original df['result'], for result_multiplied1 is used multiplied column after mul(2):
df = df.mul(2).assign(result_multiplied = df['result']*2,
                      result_multiplied1 = lambda x: x['result']*2)
print (df)
  index  result  result_multiplied  result_multiplied1
0    AA       2                  2                   4
1    BB       4                  4                   8
2    CC       6                  6                  12


Q: Python dictionary printing first word behaviour I'm learning python and am on the topic of dictionaries. I wrote the following dictionary:
Team={
    ('projectmanager','Asma'): 'Sara',
    ('ba','Richard'): 'Steve',
    ('tester','Asma'): 'Rob',
    'developer1': 'Misbah',
    'developer2': 'Mariam'
}

I then wrote the following code:
for k,v in Team.items():
    profile=type(k)
    print('engTeam => {1} {0}'.format(k[0][0],profile))

The output I get is:
Team => <class 'str'> e
Team => <class 'str'> d
Team => <class 'tuple'> i
Team => <class 'str'> m
Team => <class 'tuple'> b
Team => <class 'str'> s
Team => <class 'tuple'> p
Team => <class 'str'> e
Team => <class 'str'> a

I don't understand why the first character of all non-tuple entries are being printed. If I think about it k[0][0] in my mind means get me the first element of the dictionary then the first sub element. But the non-tuple words don't have a sub element so the output should be blank, shouldn't it? Also k[0][0] should be printing the whole first word in the tuple e.g. 'projectmanager' instead of the first character of the first tuple word. What am I missing in understanding what k[0][0] means and what it is doing?

A:
If I think about it k[0][0] in my mind means get me the first element of the dictionary then the first sub element.

No, k is the key of a given key-value pair. You are iterating over the items, which are those pairs:
for k,v in Team.items():

Each key-value pair is assigned to the names k and v there.
Given that you have two different types of keys in your dictionary, strings and tuples, your type() information shows you exactly that; you print a series of <class 'str'> and <class 'type'> for those keys.
So if k is a tuple, then k[0] is the first element in that tuple and k[0][0] is the first character of that first element:
>>> k = ('projectmanager', 'Asma')
>>> type(k)
<class 'tuple'>
>>> k[0]
'projectmanager'
>>> k[0][0]
'p'

For strings, k[0] would be the first character. But a single character is a string too. A string of length 1, so getting the first element of that string is still a string, again of length 1:
>>> k = 'developer1'
>>> type(k)
<class 'str'>
>>> k[0]
'd'
>>> type(k[0])
<class 'str'>
>>> len(k[0])
1
>>> k[0][0]
'd'

You wouldn't get an empty value here.

A: Consider,
First case- key, k is set to be a to be tuple. For instance ('projectmanager','Asma'). Hence obviously k[0][0] will print out p
Second case (the more tricky one) when k is set to be a string, k[0] is the first element of string. k[0] is hence a string of length 1. Doing
k[0][0] would access the first element of k[0] which is inturn the same as k[0] is a string of length 1.For example when k  is 'developer1' ,k[0] is'd' and k[0][0]  is hence 'd'
Hope this helps, good luck


Q: How to detect if a particular command has executed in terminal I need to detect if a particular command has run. for example if I do a git push I need to execute a build script in my fedora machine. Is there any way to do this.? we can use any facility in linux. Any help will be greatly appreciated.

A: You can try using "alias", try this link http://www.cyberciti.biz/tips/bash-aliases-mac-centos-linux-unix.html


Q: pkg-config file openmp dependency I want to write a pkg-config for a library that uses openmp internally.
My .pc file reads
prefix=/usr/local
exec_prefix=/usr/local
libdir=${exec_prefix}/lib
includedir=${prefix}/include

Name: LightFEM
Description:
Version: 1.0.0

Requires: openmp
Libs: -L${libdir} -lLightFEM
Cflags: -I${includedir}

However pkg-config returns the following error
Package openmp was not found in the pkg-config search path.
Perhaps you should add the directory containing `openmp.pc'
to the PKG_CONFIG_PATH environment variable
Package 'openmp', required by 'LightFEM', not found

How sould I write my .pc file ?


Q: Google Spreadsheet node.js move a row or sort table Edit: I saw that I am not using the official google api. This is a package based on v3 of the google api. Here is the npm that I currently use.
I saw that google api v4 exists and has many more features than the npm package I currently use, would it be possible with the official v4 api? What would I need to change to use this api?

Is it possible to move a row to a specific row (number)?
If not, can I custom sort the entire table again?
This is how I access the table:
const GoogleSpreadsheet = require("google-spreadsheet");
const { promisify } = require("util");
const creds = require("./client_secret.json");
const doc = new GoogleSpreadsheet("XXXXXXXXXXXXXXXX");
const tt = promisify(doc.useServiceAccountAuth)(creds);
const info = await promisify(doc.getInfo)();
const sheet = info.worksheets[0];

And now I want to edit/update a row, and because the order should be different now if I change the column cell where my table is sorted by, I want to move the row somewhere else. this is how I modify a row:
var row = await promisify(sheet.getRows)({
        offset: 1,
        query: 'id = ' + userId
});

//This row has now a different value and should have a different row number
row[0].role= "value";

//This will update the row, but only on its current position.
promisify(row[0].save)();

Pseudo code (how it should look like, row[0] has no attribute that indicates the position):
//row[0] role was "" and now "member", the row should be where the other member rows are
row[0].index = IndexOf(AllRows.where(x => x.role == "member")) + 1


Q: How do I change the width of a ScrollBar? I would like to change a TFrame's ScrollingBar width.
I know I could change all ScrollingBars in the system by:
SystemParametersInfo(SPI_SETNONCLIENTMETRICS,....

But how do I do it for a specific WinControl?

A: A lot of the code within Delphi depends on the width of scrollbars to be the fixed system setting so you can't alter the width without breaking the control. (Not without rewriting the TControlScrollBar and related controls in the VCL.)
You could, of course, hide the default scrollbars of the control and add your own TScrollbar components next to it.The standard TScrollBar class is a WinControl itself, where the scrollbar is taking the whole width and height of the control. The TControlScrollBar class is linked to other WinControl to manage the default scrollbars that are assigned to Windowed controls. While the raw API could make it possible to use a more flexible width, you'd always have the problem that the VCL will just assume the default system-defined width for these controls.

This also shows the biggest difference between both scrollbar types: TScrollBar has it's own Windows handle while TControlScrollBar borrows it from the related control.

A: You can try something like this:
  your_frame.HorzScrollBar.Size := 50;
  your_frame.HorzScrollBar.ButtonSize := your_frame.HorzScrollBar.Size;

A: procedure TForm1.FormCreate(Sender: TObject);
var NCMet: TNonClientMetrics;
begin
     FillChar(NCMet, SizeOf(NCMet), 0);
     NCMet.cbSize:=SizeOf(NCMet);
     // get the current metrics
     SystemParametersInfo(SPI_GETNONCLIENTMETRICS, SizeOf(NCMet), @NCMet, 0);
     // set the new metrics
     NCMet.iScrollWidth:=50;
     SystemParametersInfo(SPI_SETNONCLIENTMETRICS, SizeOf(NCMet), @NCMet, SPIF_SENDCHANGE);
end;


Q: NullPointerException in Silk4J Object Map Editor when pressing the Tab key After creating a new Silk4J Object Map entry manually (right click, "Insert new") and enter the item name, I press the Tab key to move to the Locator path input field.
In this case, a series of "Object not set to an instance of an object" error messages appear. Eventually, Eclipse crashes. Doing some debugging, I found out that Eclipse crashes due to a StackOverflowException.
I can move to the locator path column using the mouse, but since I'm used to do things by keyboard, I'd really like to find a fix. How can I make the Tab key work as expected?
I am using Silk4J 16 Hotfix 2.

A: Doing some more debugging, I found out that Silk4J for Eclipse (Java) actually uses a WPF user interface (.NET).
While preinstalled by Windows, I never needed .NET on my machine, so I never installed any updates for it.
Installing the latest .NET updates, the problem was gone. In my case I updated to .NET 4.5.2.


Q: functional usage of IDS Camera (pyueye) I am using IDS camera functions which I need to capture some images whenever the camera receives an external trigger.
"ueye.is_SetExternalTrigger(hcam, ueye.IS_SET_TRIGGER_HI_LO)"
I can able to connect the camera while it was triggering but I could not save the images to my local memory. The documentation explains to us that images were saved to a memory buffer for every trigger change (HI_LO/LO_HI, etc..)
Does anybody can explain how to use "ueye.is_WaitForNextImage" & "ueye.is_CameraStatus" functions.
Can anybody have experience in these modules? just help me to use them.
I am defining the memory pointer as just "mem_ptr = ueye.c_mem_p()". Does anyone know how to define a specific memory pointer in any particular way and how to access it??
Thank You.
I have tried this one and some other ways also, but I cannot write everything here.
hCam = ueye.HIDS(0)             #0: first available camera;  1-254: The camera with the specified camera ID
sInfo = ueye.SENSORINFO()
cInfo = ueye.CAMINFO()
pcImageMemory = ueye.c_mem_p()
MemID = ueye.int()
rectAOI = ueye.IS_RECT()
pitch = ueye.INT()
nBitsPerPixel = ueye.INT(24)    #24: bits per pixel for color mode; take 8 bits per pixel for monochrome
channels = 3                    #3: channels for color mode(RGB); take 1 channel for monochrome
m_nColorMode = ueye.INT()       # Y8/RGB16/RGB24/REG32
bytes_per_pixel = int(nBitsPerPixel / 8)
nRet = ueye.is_InitCamera(hCam, None)
nRet = ueye.is_SetExternalTrigger(hCam, ueye.IS_SET_TRIGGER_HI_LO)
nRet = ueye.is_SetDisplayMode(hCam, ueye.IS_SET_DM_DIB)
nRet = ueye.is_AOI(hCam, ueye.IS_AOI_IMAGE_GET_AOI, rectAOI, ueye.sizeof(rectAOI))
width = rectAOI.s32Width
height = rectAOI.s32Height
nRet = ueye.is_AllocImageMem(hCam, width, height, nBitsPerPixel, pcImageMemory, MemID)
nRet = ueye.is_CaptureVideo(hCam, ueye.IS_DONT_WAIT)
d=0
while(nRet == ueye.IS_SUCCESS):
    ueye.is_WaitForNextImage(hCam, 500, pcImageMemory, MemID)
    array = ueye.get_data(pcImageMemory, width, height, nBitsPerPixel, pitch, copy=False)
    frame = np.reshape(array,(height.value, width.value, bytes_per_pixel))
    frame = cv2.resize(frame,(0,0),fx=0.5, fy=0.5)
    cv2.imshow("SimpleLive_Python_uEye_OpenCV", frame)
    filename = "images/file_%d.jpg"%d
    cv2.imwrite(filename, img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()
ret = ueye.is_StopLiveVideo(hcam, ueye.IS_FORCE_VIDEO_STOP)
ret = ueye.is_ExitCamera(hcam)


Q: Angular Service to Express API Route + Posting Data I am in the process of converting one of my sites (http://maskedarmory.com) from LAMP (using Laravel 4 MVC) over to the MEAN stack and it has been quite a journey thus far.
I have managed to get the landing page up and running and the input POSTing to Angular controller that I have it routed to.
Now, the problem I am having is getting the service to send over the POSTed data that is in Angular over to the Express API.  I keep keeping a 404 Not Found error on the /api/character URL path.
Also, how do I access the 'characterData' variable that is on the Angular side that is being passed over by the factory?  Because I am trying to do a console.log on the 'characterData' variable on the server side and I am sure that that is out of scope.
app/routes.js (Express Routing)
// public/js/services/ArmoryService.js
angular.module('ArmoryService', []).
    factory('Armory', function($http) {

    return {
        // Get the specified character by its profile ID.
        get : function(id) {
            return $http.get('/api/character/' + id);
        },

        // call to POST and create a new character armory.
        create : function(characterData) {
            return $http.post('/api/character', characterData);
        }
    }
});

app/routes.js (Express Routing)
module.exports = function(app) {

    app.post('/api/character', function(req, res) {
          console.log(characterData);
    });

    app.get('/', function(req, res) {
        res.sendfile('./public/index.html'); // load our public/index.html file
    });

};

If I do a console.log before the $http.post to the API, 'characterData' has all of the information it should.
I am sure that this is a routing issue of some type, but I will be damned if I can figure it out.
Thanks in advance for your help!

A: Try this:
app.post('/api/character', function(req, res) {
  console.log(JSON.stringify(req.body));
  res.status(200).send('whatever you want to send back to angular side');
});

app.get('/api/character/:id', function(req, res) {
  console.log(req.params.id);
  res.status(200).send('whatever you want to send back to angular side'');
});