text:
Q: Remote server returned an error 500 - Error while calling a soap webservice I am trying to call a webservice by POST method. Input xml is rpc/literal soap message.
    Dim myRequest As Net.HttpWebRequest
    Dim objResponse As Net.HttpWebResponse
    Dim result As String
    Dim data As Byte()
    Dim newStream As System.IO.Stream

    Dim strURL As String = "https://abxxxx"
    strXml.Load("D:\MyXml.xml")

    data = System.Text.Encoding.ASCII.GetBytes(strXml.InnerXml)
    myRequest = WebRequest.Create(strURL)
    myRequest.Method = "POST"
    myRequest.ContentType = "application/x-www-form-urlencoded"
    myRequest.ContentLength = data.Length
    myRequest.Timeout = 125000
    newStream = myRequest.GetRequestStream()
    newStream.Write(data, 0, data.Length)
    newStream.Close()
    objResponse = myRequest.GetResponse()
    Dim sr As IO.StreamReader = New IO.StreamReader(objResponse.GetResponseStream())
    strOutput = sr.ReadToEnd()
    'Close connections
    sr.Close()
    objResponse.Close()

Code throws an exception of "Remote server returned an error : 500" on the line     objResponse = myRequest.GetResponse()
This is the actual soap response from web service:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Unmarshalling Error: unexpected element (uri:"", local:"CONTACT"). Expected elements are (none) </faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>

This is working perfectly when I add a reference to this web service using visual studio (proxy class) but I do not need to use this method.
Please suggest if I am missing something!

A: After spending some time on analysing and research of the wsdl of my service, I was able to find the fix for this issue.
We need to use CDATA (ie constant data) for all those xml nodes which are not direct exposed in WSDL and thus this tag should be sent as text to the service. This tag was under a parent tag which was defined in wsdl. I applied CDATA to send these information in my soap xml.
<PARENT><![CDATA[<CONTACT>abcd </CONTEXT>]]></PARENT>

I found some useful information about the error 500 - Remote server returned an error - This error is reproduced from  service and there could be many reasons behind this. To get the exact reason for the error we require actual response from the service as fault code and fault string.
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Unmarshalling Error: unexpected element (uri:"", local:"CONTACT"). Expected elements are (none) </faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>

<faultcode>soap:Client</faultcode> - Issue is from client ie client input.
<faultstring>Unmarshalling Error: unexpected element (uri:"", local:"CONTACT"). Expected elements are (none) </faultstring>

This error suggests that we are passing blank uri for the element <CONTACT>. uri here represents the namespace of the <CONTACT> tag which should be available in the service wsdl of the corresponding operation. This element is referred here as LOCAL and as service did not have information about this tag in wsdl, it was trying to find the  namespace for this element.
Hope this could help many more people facing this same problem.


text:
Q: MongoDb Spring boot ,User entity could not be found I am using MongoDb With my spring boot project here is my entity user
package com.logan.cricketbeting.entities;

import java.util.Date;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "users")
public class User {
    @Id
    private String id;
    private String username;
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }
    private String password;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}

And here is User repository
package com.logan.cricketbeting.repositories;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;

import com.logan.cricketbeting.entities.User;
//this is the repositiory for users
@Repository
public interface UserRepository extends MongoRepository<User, String> {
    @Query
    public User findByUsername(String username);

}

And here is Userservice
package com.logan.cricketbeting.Service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.logan.cricketbeting.entities.User;

@Service
public interface UserService {
    User saveUser(User User);
    User updateUser(User User);
    void deleteUser(User User);
    User getUserByusername(String username);
    List<User> getAllUsers();

}

And user service Impl
package com.logan.cricketbeting.Service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.logan.cricketbeting.entities.User;
import com.logan.cricketbeting.repositories.UserRepository;

public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Override
    public User saveUser(User User) {
        // TODO Auto-generated method stub
        return userRepository.save(User);

    }

    @Override
    public User updateUser(User User) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void deleteUser(User User) {
        // TODO Auto-generated method stub

    }

    @Override
    public User getUserByusername(String username) {
        // TODO Auto-generated method stub
        return userRepository.findByUsername(username);
    }

    @Override
    public List<User> getAllUsers() {
        // TODO Auto-generated method stub
        return null;
    }

}

And this is my index controller
package com.logan.cricketbeting.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.logan.cricketbeting.Service.UserServiceImpl;
import com.logan.cricketbeting.entities.User;

@Controller

public class IndexController {

    @Autowired
    private User user;

    @Autowired
    private UserServiceImpl userservice;

    @RequestMapping("/login")
    public String login()
    {
        return "user/login";
    }

    @RequestMapping("/home")
public String index() {
    return "user/home.html";
}
    @RequestMapping("/aboutus")
    public String aboutus()
    {
        return "user/about-us";
    }

    @RequestMapping("/faqs")
    public String faqs()
    {
        return "user/faqs";
    }
    @RequestMapping("/register")
    public String register()
    {
        return "user/register";
    }
    @RequestMapping("/contactus")
    public String contactus()
    {
        return "user/contact-us";
    }
    @RequestMapping("/extra-menu")
    public String extramenu()
    {
        return "extra-menu";
    }

    @RequestMapping("/register")
    @ResponseBody
    public String registers()
    {
        user.setUsername("logan");
        user.setPassword("password");
        userservice.saveUser(user);

        return "User registered";
    }
}

And this is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.logan.cricketbeting</groupId>
    <artifactId>cricketbettingspring</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>cricketbettingspring</name>
    <description>cricketbettingspring</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
<dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
  </dependency>
  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I am getting this error

Description:
Field user in com.logan.cricketbeting.controllers.IndexController
  required a bean of type 'com.logan.cricketbeting.entities.User' that
  could not be found.
Action:
Consider defining a bean of type
  'com.logan.cricketbeting.entities.User' in your configuration.

I have already created entity with @Document annotation but it is still giving me this error any idea how to solve it??

A: What you are trying to do, is to inject User in IndexController:
@Autowired
private User user;

User is not a bean managed by Spring IoC and therefore you're getting this error:
Field user in com.logan.cricketbeting.controllers.IndexController required a bean of type 'com.logan.cricketbeting.entities.User' that could not be found.

Solution:
Just instantiate your User in registers() method and anywhere where you need it:
@RequestMapping("/register")
@ResponseBody
public String registers() {
    User user = new User();
    user.setUsername("logan");
    user.setPassword("password");
    userservice.saveUser(user);

    return "User registered";
}

A: You can annotate your user entity with

@Component

,all you need is to make spring ApplicationContext find it. Like
@Component
@Document(collection = "users")
public class User {
    @Id
    private String id;
    private String username;
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }
    private String password;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: writing a closure in coffeescript with using "do" I am trying to set the property of my Backbone view class using a HTML select in Coffeescript and what I've realised is that I need to inject this(@) into the callback/handler via a javascript closure to maintain scope. But I can't seem to figure out how to do this as using "do" just executes the function on page load
dropdown = $('<select />') .on 'change', do(myView = @) -> myVieW.prop = @.value

thanks for your help!

A: The do notation does compile to an IIFE, yous still need the actual handler function:
dropdown = $('<select />') .on 'change', do(myView = @) -> (e) -> myVieW.prop = @.value

# or wrap the whole handler assignment:
do(myView = @) ->
  dropdown = $('<select />') .on 'change', (e) -> myVieW.prop = @.value

Or you just use lexical this:
dropdown = $('<select />') .on 'change', (e) => @.prop = e.target.value

dropdown = $('<select />') .on 'change', (e) => @.prop = dropdown.val()

A: The standard way of doing it in Backbone is the following:

class MyView extends Backbone.View
  events:
    'change select': 'onChange'

  onChange: (e) ->
    el = e.currentTarget
    @prop = el.value

Having said that, setting some properties on the view is also a smell, and hints on a missing model.
Setting some property outside of the view is a definite smell and invites re-assessment of the architecture.


text:
Q: Jms serializer annotations as yaml file I've been working on User class inherited from BaseUser of FOSUserBundle, so I've faced a problem. I need to set up serialization for my User but JMS serializer serializes all properties of BaseUser.
Solution that I found was to create my own annotation for BaseUser and store it in yaml file, but I don't know how exactly should I do this.

A: JMSSerializerBundle by default use your AcmeBundle/Resources/config/serializer directory to fetch all metadata that are declared in yml or xml files. You need to create file with name Entity.User.yml to point serializer to use your AcmeBundle/Entity/User entity.
If you need to define metadata for third party bundles (base entities) you can define custom path for fetching metadata in config.yml:
jms_serializer:
    metadata:
        directories:
            FOSUB:
                namespace_prefix: FOS\UserBundle
                path: %kernel.root_dir%/serializer/FOSUB

In this case you need to locate your metadata file in %kernel.root_dir%/serializer/FOSUB directory with name like Model.User.yml.


text:
Q: Bootstrap responsive layout does not work properly Using bootstrap 2.2 I've got the following problem:
When I narrow my firefox window with the responsive layout, the nav-bar disappears and I am getting a button in the right corner instead. But clicking on that button does not do anything (normally, the menu should pop out).
I copied this HTML:
http://www.w3resource.com/twitter-bootstrap/example-responsive-design-with-twitter-bootstrap.html
and I replaced the CSS and JS imports by the following:
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="bootstrap/css/bootstrap-responsive.css" rel="stylesheet">

which are the standard .css and js files which one gets when downloading Bootstrap. The CSS and the bootstrap.js are loaded properly.
The bootstrap.js does contain the collapse section (I've pasted that part below)
Has anyone got any idea, why clicking on the button after collapse does not have any effect?
I am using firefox 18.0.2, the responsive layout works when opening other sites.
Thanks a lot
Collapse section of bootstrap.js:
/* =============================================================
 * bootstrap-collapse.js v2.2.2
 * http://twitter.github.com/bootstrap/javascript.html#collapse
 * =============================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */

!function ($) {

  "use strict"; // jshint ;_;

 /* COLLAPSE PUBLIC CLASS DEFINITION
  * ================================ */

  var Collapse = function (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.collapse.defaults, options)

    if (this.options.parent) {
      this.$parent = $(this.options.parent)
    }

    this.options.toggle && this.toggle()
  }

  Collapse.prototype = {

    constructor: Collapse

  , dimension: function () {
      var hasWidth = this.$element.hasClass('width')
      return hasWidth ? 'width' : 'height'
    }

  , show: function () {
      var dimension
        , scroll
        , actives
        , hasData

      if (this.transitioning) return

      dimension = this.dimension()
      scroll = $.camelCase(['scroll', dimension].join('-'))
      actives = this.$parent && this.$parent.find('> .accordion-group > .in')

      if (actives && actives.length) {
        hasData = actives.data('collapse')
        if (hasData && hasData.transitioning) return
        actives.collapse('hide')
        hasData || actives.data('collapse', null)
      }

      this.$element[dimension](0)
      this.transition('addClass', $.Event('show'), 'shown')
      $.support.transition && this.$element[dimension](this.$element[0][scroll])
    }

  , hide: function () {
      var dimension
      if (this.transitioning) return
      dimension = this.dimension()
      this.reset(this.$element[dimension]())
      this.transition('removeClass', $.Event('hide'), 'hidden')
      this.$element[dimension](0)
    }

  , reset: function (size) {
      var dimension = this.dimension()

      this.$element
        .removeClass('collapse')
        [dimension](size || 'auto')
        [0].offsetWidth

      this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')

      return this
    }

  , transition: function (method, startEvent, completeEvent) {
      var that = this
        , complete = function () {
            if (startEvent.type == 'show') that.reset()
            that.transitioning = 0
            that.$element.trigger(completeEvent)
          }

      this.$element.trigger(startEvent)

      if (startEvent.isDefaultPrevented()) return

      this.transitioning = 1

      this.$element[method]('in')

      $.support.transition && this.$element.hasClass('collapse') ?
        this.$element.one($.support.transition.end, complete) :
        complete()
    }

  , toggle: function () {
      this[this.$element.hasClass('in') ? 'hide' : 'show']()
    }

  }

 /* COLLAPSE PLUGIN DEFINITION
  * ========================== */

  var old = $.fn.collapse

  $.fn.collapse = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('collapse')
        , options = typeof option == 'object' && option
      if (!data) $this.data('collapse', (data = new Collapse(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.collapse.defaults = {
    toggle: true
  }

  $.fn.collapse.Constructor = Collapse

 /* COLLAPSE NO CONFLICT
  * ==================== */

  $.fn.collapse.noConflict = function () {
    $.fn.collapse = old
    return this
  }

 /* COLLAPSE DATA-API
  * ================= */

  $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
    var $this = $(this), href
      , target = $this.attr('data-target')
        || e.preventDefault()
        || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
      , option = $(target).data('collapse') ? 'toggle' : $this.data()
    $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
    $(target).collapse(option)
  })

`

A: Create a responsive menu in bootstrap the following way : JSfiddle with nav Navigation bootstrap
Note : You have not included the jquery file into your html page, use the following way :
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">

<link href="bootstrap/css/bootstrap-responsive.css" rel="stylesheet">

New Icon Menu

 Home

About Us

Portfolio

Contact Us


text:
Q: Calculating frame index based on new frame rate for video generation My .NET application as a sequential list of images representing each frame of a video recorded at 30 frames per second.
00000001.png
00000002.png
00000003.png
...
99999999.png

Now I want to reorder this list so it can generate a video based on the following parameters:
Start Frame Index: 100
Direction:         Forward
Output Speed:      100 FPS
Duration:          10 seconds

So far I have something like this:
var originalFrameRate = 30D;
var originalFrameTime = 1D / originalFrameRate;
var originalStartFrameIndex = 100; // 00000100.png.
// Assume [originalFrames] will be filled with image file names from above.
var originalFrames = new List<string>
(new string [] { "0000003.png", "0000002.png", ..., "99999999.png", });

var targetFrameRate 100; // FPS.
var targetDuration = TimeSpan.FromSeconds(10);
var targetFrameCount = speed * targetDuration.Seconds;
var targetFrames = new List<string>();

for (int i = 0; i < targetFrameCount; i++)
{
    // How to map the original list from 30 FPS to 100 FPS?
    targetFrames.Add(originalFrames [originalStartFrameIndex + ???]);
}

In the above example, the output would be targetFrames being filled with the appropriate file name based on the variables names targetXXX.
Any suggestions on how to map this would be appreciated.
EDIT: I forgot to mention that the output video will always be generated at the original frame rate. The length of the target video will of course change. If the original FPS is lower than the target, we will repeat frames. Otherwise we will be skipping them.

A: targetFrames.Add(originalFrames [originalStartFrameIndex + (int)(i * targetFrameRate / originalFrameRate) ]
should do the trick. Add some error validation (check for divide by zero and exceeding the bounds of the array) :)

A: I started to expand upon Vincent's answer to fix a problem I noticed: when scaling from 30fps to 100fps, frame 0 is repeated a fourth time (a frame pattern of 0000 111 222 3333) when I was expecting 000 111 2222. Not a big deal since it's probably just a matter of preference (whether you want the fractional "adjustment" to happen on an even or odd frame), but then I went down the rabbit hole and built an iterator class that can handle just about any scenario, including fractional framerates.
(Using a generic iterator has the added bonus of not requiring the frames to be string - if you wanted to represent each frame as a class, you could do that, too.)
public sealed class FramerateScaler<T> : IEnumerable<T>
{
    private IEnumerable<T> _source;
    private readonly double _inputRate;
    private readonly double _outputRate;
    private readonly int _startIndex;

    public double InputRate { get { return _inputRate; } }
    public double OutputRate { get { return _outputRate; } }
    public int StartIndex { get { return _startIndex; } }

    public TimeSpan InputDuration {
        get { return TimeSpan.FromSeconds((1 / _inputRate) * (_source.Count() - StartIndex)); }
    }

    public TimeSpan OutputDuration {
        get { return TimeSpan.FromSeconds((1 / _outputRate) * this.Count()); }
    }

    public FramerateScaler(
        double inputRate, double outputRate,
        IEnumerable<T> source, int startIndex = 0)
    {
        _source = source;
        _inputRate = inputRate;
        _outputRate = outputRate;
        _startIndex = startIndex;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return new ScalingFrameEnumerator<T>(_inputRate, _outputRate, _source, _startIndex);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return (IEnumerator)GetEnumerator();
    }

    private sealed class ScalingFrameEnumerator<T> : IEnumerator<T>
    {
        internal readonly double _inputRate;
        internal readonly double _outputRate;
        internal readonly int _startIndex;

        private readonly List<T> _source;

        private readonly double _rateScaleFactor;
        private readonly int _totalOutputFrames;
        private int _currentOutputFrame = 0;

        public ScalingFrameEnumerator(
            double inputRate, double outputRate,
            IEnumerable<T> source, int startIndex)
        {
            _inputRate = inputRate;
            _outputRate = outputRate;
            _source = source.ToList();
            _startIndex = startIndex;

            _rateScaleFactor = _outputRate / _inputRate;
            // Calculate total output frames from input duration
            _totalOutputFrames = (int)Math.Round(
                (_source.Count - startIndex) * _rateScaleFactor, 0);
        }

        public T Current
        {
            get
            {
                return _source[_startIndex +
                    (int)Math.Ceiling(_currentOutputFrame / _rateScaleFactor) - 1];
            }
        }

        public void Dispose()
        {
            // Nothing unmanaged to dispose
        }

        object IEnumerator.Current
        {
            get { return Current; }
        }

        public bool MoveNext()
        {
            _currentOutputFrame++;
            return ((_currentOutputFrame - 1) < _totalOutputFrames);
        }

        public void Reset()
        {
            _currentOutputFrame = 0;
        }
    }
}

And a set of tests covering idempotence, scaling up, scaling down, and fractional framerates:
[TestClass]
public class Test
{
    private readonly List<string> _originalFrames = new List<string>();

    public Test()
    {
        // 30 FPS for 10 seconds
        for (int f = 0; f < 300; f++)
        {
            _originalFrames.Add(string.Format("{0:0000000}.png", f));
        }
    }

    [TestMethod]
    public void Should_set_default_values()
    {
        var scaler = new FramerateScaler<string>(30, 30, _originalFrames, 10);

        Assert.AreEqual(30, scaler.InputRate);
        Assert.AreEqual(30, scaler.OutputRate);
        Assert.AreEqual(10, scaler.StartIndex);
        Assert.AreEqual(_originalFrames.ElementAt(10), scaler.First());
    }

    [TestMethod]
    public void Scale_from_same_is_idempotent()
    {
        var scaler = new FramerateScaler<string>(30, 30, _originalFrames);

        Assert.AreEqual(scaler.InputDuration, scaler.OutputDuration);
        Assert.AreEqual(_originalFrames.Count, scaler.Count());
        Assert.IsTrue(_originalFrames.SequenceEqual(scaler));
    }

    [TestMethod]
    public void Scale_from_same_offset_by_half_is_idempotent()
    {
        var scaler = new FramerateScaler<string>(
            30, 30, _originalFrames, _originalFrames.Count / 2);

        Assert.AreEqual(150, scaler.Count());
        Assert.AreEqual(scaler.OutputDuration, scaler.InputDuration);
        Assert.IsTrue(_originalFrames
            .Skip(150)
            .SequenceEqual(scaler));
    }

    [TestMethod]
    public void Scale_from_30_to_60()
    {
        var scaler = new FramerateScaler<string>(30, 60, _originalFrames);

        Assert.AreEqual(600, scaler.Count());
        Assert.AreEqual(scaler.OutputDuration, scaler.InputDuration);
        var result = scaler.ToList();
        Assert.IsTrue(_originalFrames
            .Concat(_originalFrames)
            .OrderBy(x => x)
            .SequenceEqual(scaler));
    }

    [TestMethod]
    public void Scale_from_30_to_60_offset_by_half()
    {
        var scaler = new FramerateScaler<string>(
            30, 60, _originalFrames, _originalFrames.Count / 2);

        Assert.AreEqual(300, scaler.Count());
        Assert.AreEqual(scaler.OutputDuration, scaler.InputDuration);
        Assert.IsTrue(_originalFrames
            .Skip(150)
            .Concat(_originalFrames.Skip(150))
            .OrderBy(x => x)
            .SequenceEqual(scaler));
    }

    [TestMethod]
    public void Scale_from_30_to_100()
    {
        var scaler = new FramerateScaler<string>(30, 100, _originalFrames);

        Assert.AreEqual(1000, scaler.Count());
        Assert.AreEqual(scaler.OutputDuration, scaler.InputDuration);
        // 000 - 111 - 2222 ...
        Assert.IsTrue(scaler.PatternIs(0, 0, 0, 1, 1, 1, 2, 2, 2, 2));
    }

    [TestMethod]
    public void Scale_from_30_to_100_offset_by_half()
    {
        var scaler = new FramerateScaler<string>(
            30, 100, _originalFrames, _originalFrames.Count / 2);

        Assert.AreEqual(500, scaler.Count());
        Assert.AreEqual(scaler.OutputDuration, scaler.InputDuration);
        // 000 - 111 - 2222 ...
        Assert.IsTrue(scaler.PatternIs(0, 0, 0, 1, 1, 1, 2, 2, 2, 2));
    }

    [TestMethod]
    public void Scale_from_24p_to_ntsc()
    {
        var scaler = new FramerateScaler<string>(23.967, 29.97, _originalFrames);

        Assert.AreEqual(375, scaler.Count());
        Assert.AreEqual(
            scaler.OutputDuration.TotalMilliseconds,
            scaler.InputDuration.TotalMilliseconds, delta: 4);
        // 0 - 1 - 2 - 33 ...
        Assert.IsTrue(scaler.PatternIs(0, 1, 2, 3, 3));
    }

    [TestMethod]
    public void Scale_from_30_to_15()
    {
        var scaler = new FramerateScaler<string>(30, 15, _originalFrames);

        Assert.AreEqual(150, scaler.Count());
        Assert.AreEqual(scaler.OutputDuration, scaler.InputDuration);
        Assert.IsTrue(_originalFrames
            .Where((item, index) => index % 2 == 1)
            .SequenceEqual(scaler));
    }

    [TestMethod]
    public void Scale_from_30_to_15_offset_by_half()
    {
        var scaler = new FramerateScaler<string>(30, 15, _originalFrames, 150);

        Assert.AreEqual(75, scaler.Count());
        Assert.AreEqual(scaler.OutputDuration, scaler.InputDuration);
        Assert.IsTrue(_originalFrames
            .Skip(150)
            .Where((item, index) => index % 2 == 1)
            .SequenceEqual(scaler));
    }
}

static class Extensions
{
    public static bool PatternIs<T>(this IEnumerable<T> source, params int[] pattern)
    {
        foreach (var chunk in source.Chunkify(pattern.Length))
        {
            for (var i = 0; i < chunk.Length; i++)
                if (!chunk.ElementAt(i).Equals(
                    chunk.Distinct().ElementAt(pattern[i])))
                    return false;
        }

        return true;
    }

    // http://stackoverflow.com/a/3210961/3191599
    public static IEnumerable<T[]> Chunkify<T>(this IEnumerable<T> source, int size)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (size < 1) throw new ArgumentOutOfRangeException("size");
        using (var iter = source.GetEnumerator())
        {
            while (iter.MoveNext())
            {
                var chunk = new T[size];
                chunk[0] = iter.Current;
                for (int i = 1; i < size && iter.MoveNext(); i++)
                {
                    chunk[i] = iter.Current;
                }
                yield return chunk;
            }
        }
    }
}


text:
Q: how to create iPhone main menu screen with 2 tabbars subview? I made two applications that each one of them is tabbar based.
Now I want to combine them to one app that will be struct like that:
-Main menu with 2 buttones.
  - button 1: tab bar app no 1.
  - button 2: tab bar app no 2.
from each tab bar app, I want an Home button on the left side of the nav bar that will take me to the main menu.
I found this link http://www.pushplay.net/blog_detail.php?id=27 but it's not good to me..
I will be happy if you will able to post some simple code for my problem..
Thanks.

A: App's 1 & 2 need to be based around viewcontrollers, each of which has a tabbar. The root windows can then just alloc/init and then [self.navigationController pushViewController:viewController animated:YES]; to launch the tabbar controller.
If you have relied on IB to build your tabbar applications, its quite difficult to translate them into view controllers. I create my tabbars programatically (i just find it easier) like this

tabBarController = [[UITabBarController alloc] init];          // creates your tab bar so you can add everything else to it
searchTableViewController = [[SearchTableViewController alloc] init];
UINavigationController *searchTableNavController = [[[UINavigationController alloc] initWithRootViewController:searchTableViewController] autorelease];
[searchTableViewController release];
searchMapViewController = [[SearchMapViewController alloc] init];
UINavigationController *mapTableNavController = [[[UINavigationController alloc] initWithRootViewController:searchMapViewController] autorelease];
[searchMapViewController release];
atestViewController = [[AboutTableViewController alloc] init];
UINavigationController *AboutNavController = [[[UINavigationController alloc] initWithRootViewController:atestViewController] autorelease];
[atestViewController release];
tabBarController.viewControllers = [NSArray arrayWithObjects:searchTableNavController, mapTableNavController,  AboutNavController, nil];
[self.view addSubview:tabBarController.view];


text:
Q: How to change the gallery thumbnails from the dynamic id by using jquery function? I have been trying create a gallery for my website but i couldn't solve the problem with changing the thumbnails with the large one from the dynamic id's.
Here is what i would like to do:
I had two separated unordered lists. First one holds the large pictures the second one holds the thumbs. Both list items has the same id numbers but different id names. Large pictures' id's are preview-1, preview-2, etc. and the Thumbnails id's are thumbnail-1,thumbnail-2,etc.
I want to change the thumbnail pictures with the same id number of the large when the user click on it.
For example: If i click on the id="thumbnail-3" then the large img id="preview-3" should fadein immediately after the current large image fading out.
Here is my sample HTML

This is the large image box
And..

this is the thumbnail box.
I hope you guys help me on this one.
Thanks!
UPDATED

By the way, Is there any chance to add .current class to the selected thumbnail?  The previously selected ones should be disappear when the user clicked?

A: If both lists are in the same order, I mean thumbnail and it's corresponding preview are in the same place in their lists, then your problem can be solved even without using these ids at all.
Solution using id
$('ul.thumbnails > li').click(function() {
    var preview_id = 'preview-' + $(this).attr('id').split('-')[1];

    $('ul.previews > li:visible').fadeOut('normal', function() {
            $('#'+preview_id).fadeIn();
    });
});

Without using id
$('ul.thumbnails > li').click(function() {
    var thumb_number = $(this).index();

    $('ul.previews > li:visible').fadeOut('normal', function() {
            $('ul.previews > li').eq(thumb_number).fadeIn();
    });
});

Both solutions imply that there is always at least one preview visible at a time. Otherwise fadeIn function will not be called.


text:
Q: ¿Que hay que poner dentro de fgets()? Linux mi consulta es ¿ que tengo que poner dentro de fgets()?. Ya que estamos viendo strings en clases y el profesor usar gets(), ya que usa windows, pero como estoy en Linux me dijo que debia poner fgets(), pero  al compilarlo en GCC me muestra el siguiente error:

contarCaracteres.c:10:2: error: too few arguments to function 'fgets'

El algoritmo que estoy haciendo es simplemente para contar caracteres, y la palabra es leida por teclado:
#include <stdio.h>

int main() {

    char cadena[20];
    int i, contador=0;

    printf("\nIngrese la palabra: ");
    scanf("%s", cadena);
    fgets();

    for (i=0; i<20 && cadena[i]!='\0' ; i++)
        contador++;
}

Mi pregunta es ¿que debo poner dentro del fgets()?.
PD: No podemos usar funciones, ni tampoco librerias como string.h

A: Puedes hacer lo siguiente para usar fgets, Elimina el scanf y el código de fgets seria de esta manera:
fgets(cadena, 20, stdin);

O puedes seguir usando scanf removiendo el fgets de esta manera:
scanf("%[^\n]%*c", cadena);

Aqui puedes ver una explicación mas detallada: https://stackoverflow.com/questions/6282198/reading-string-from-input-with-space-character


text:
Q: Hide a pop message while downgrading using Installshield I was installing 3.2.0.2 version(older) over 3.2.0.3(latest) to verify downgrade.
However I get a pop-up message as The setup will perform an upgrade....,
and followed by another pop-up A later version of ....
After the second pop-up, install operation just terminated (which is expected behavior). However, the issue is with first pop-up which shouldn't be displayed while downgrading.
How can I get rid of this first pop-up?
I tried disabling prompt, don't prompt options, but no luck.
I have searched the  property manager through string editor as well, but unable to find where is that message is coming from.
Could anyone please help me to get rid of this one?
Thanks in advance

A: To be honest, how much of your users will perform a downgrade of your software?
Is it not better to block downgrades?
What I do is showing a message to the user that a newer version is already installed and if he wants to install the older version, he first needs to remove the installed version.


text:
Q: How to send hardware keyboard or mouse press using any programming language? I found a lot of answers about this question that works in notepad and other programs but doesn't work in a specific game!
it seems that the game block the inputs from my program.
here is the programs that I have tried.
1- using SendInput (c++)
#include <future>
#include<Windows.h>
using namespace std::chrono;
using namespace std::this_thread;
using namespace std;

UINT PressKeyScan(WORD scanCode)
{
    INPUT input[1] = { 0 };
    input[0].type = INPUT_KEYBOARD;
    input[0].ki.wVk = NULL;
    input[0].ki.wScan = scanCode;
    input[0].ki.dwFlags = KEYEVENTF_SCANCODE ;

    UINT ret = SendInput(1, input, sizeof(INPUT));

    return ret;
}

UINT ReleaseKeyScan(WORD scanCode)
{
    INPUT input[1] = { 0 };
    input[0].type = INPUT_KEYBOARD;
    input[0].ki.wVk = NULL;
    input[0].ki.wScan = scanCode;
    input[0].ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;

    UINT ret = SendInput(1, input, sizeof(INPUT));

    return ret;
}
int main()
{
    for (size_t i = 0; i < 100; i++)
    {
        PressKeyScan(0x39);
        sleep_for(milliseconds(100));
        ReleaseKeyScan(0x39);
        sleep_for(milliseconds(100));
    }

}

2- using SendKeys (C# winforms)
private void btnSendKeys_Click(object sender, EventArgs e)
{
    int iHandle = NativeWin32.FindWindow(null, txtTitle.Text);

    NativeWin32.SetForegroundWindow(iHandle);

    string keys = "";
    string space = " ";

    for (int i = 0; i < lbKeys.Items.Count; i++)
    {
        if (lbKeys.Items[i].Text.ToString() == "{SPACE}")
        {
            keys += space;
        }
        else
        {
            keys += lbKeys.Items[i].Text.ToString();
        }
    }

    System.Windows.Forms.SendKeys.Send(keys);

}

both worked in notepad and some other apps but didn't worked in specific game.

A: I have tried to run the program as administrator and it finally works :D


text:
Q: Matching conditions in columns I am trying to match conditions so that if text is present in both columns A and B and a 0 is in column C, the code should return 'new' in column C (overwriting the 0). Example dataframe below:
import pandas as pd
df = pd.DataFrame({"A":['something',None,'filled',None], "B":['test','test','test',None], "C":['rt','0','0','0']})

I have tried the following, however it only seems to accept the last condition so that any '0' entries in column C become 'new' regardless of None in columns A or B. (in this example I only expect 'new' to appear on row 2.
import numpy as np

conditions = [(df['A'] is not None) & (df['B'] is not None) & (df['C'] == '0')]

values = ['new']

df['C'] = np.select(conditions, values, default=df["C"])

Appreciate any help!

A: You will need to use .isna() and filter where it is not nan/none (using ~) as below:
conditions = [~(df['A'].isna()) & ~(df['B'].isna()) & (df['C'] == '0')]

output:
           A     B    C
0  something  test   rt
1       None  test    0
2     filled  test  new
3       None  None    0

A: Use Series.notna for test None or NaNs:
conditions = [df['A'].notna() & df['B'].notna() & (df['C'] == '0')]

Or:
conditions = [df[['A','B']].notna().all(axis=1) & (df['C'] == '0')]

values = ['new']

df['C'] = np.select(conditions, values, default=df["C"])
print (df)
           A     B    C
0  something  test   rt
1       None  test    0
2     filled  test  new
3       None  None    0

A: Use
mask = df[['A', 'B']].notna().all(1) & df['C'].eq('0')
df.loc[mask, 'C'] = 'new'


text:
Q: Using Custom SPItem Event Receiver in Leave Request Form I have a custom leave request form on SP 2016 On premise, There are three levels of approval. How do I manage the permissions on the list item through SharePoint object Model.
Please refer to this link as my leave request is similar to this: LeaveRequest


text:
Q: If 2 identically-sized rectangles overlap with another rectangle and are evenly divided by an axis, which overlap rectangle would be biggest? Suppose we have three rectangles, named 1, 2, and 3. 1 and 2 are identically sized, are axis-aligned, and overlap with 3, but not each other. 1's center is closer to 3's center than is 2's center. Is it safe to say, then, that the rectangle created by the overlap of 1 and 3 is bigger than the rectangle created by the overlap of 2 and 3? My intuition says "yes".

A: Suppose rectangle 3 is a square of side 2, centered at the origin, rectangle 1 is centered at $(0,1.1)$ and has height just over $1.1$, rectangle 2 is centered at $(.9,-.9)$. I think you'll find your hypotheses are satisfied, but not your conclusion.


text:
Q: Javascript and bookmarks Lets say that I am on a page that has a significantly long list of URLs and I want to make sure that I have all of them bookmarked.  I know that I already have many of them in my bookmarks list and would like to avoid duplications as much as possible.
With that in mind, I would like to be able to grab all of the links and then open into new tabs those that are not currently contained in my bookmarks list.  I can do all of the getting the links, and comparing the links, I just don't know how to access the bookmarks via javascript.
I can do this in whatever PC/mac browser that has a workable solution.  Does anyone have any ideas?

A: You will never be able to access the user's bookmarks via JavaScript. In fact, that would be a severe security hole.
JavaScript gets executed in a socalled sandbox. That means that, at least in theorey, a JavaScript never will have access to the resources of the client machine (in practice, the sandboxes have bugs that allow nasty things, but that is a different story).

A: You can also Check out Opera Link ;)
http://www.opera.com/link/
Filtering duplicates can be done on-line in your accout.


text:
Q: Would it be better to use media queries or create a JQuery function to add small amounts of CSS? In terms of performance and the speed loading the files for a browser, would it be better to use media queries to change a few things, or make a JQuery function that reads the screen size and change items using .CSS()?

A: In my opinion, current browser already have great support of css3. That's mean you almost can do anything related 'responsive' styling using css3 (such as media query, translatex, scale ttc)
A long time a go, people like me, are using jquery to center a div in vertical responsive way, no matter you resize the browser size the content should be in vertical center. Yes im using jquery that time, but just Because im forced to. And the drawback is, user see the content not in center vertical after the browser finish loading, because the js only invoked later in a while after loading.
Nowdays you can simply doing that using css3. And user will see the center vertical content right away as soon the browser finish loading
So the summary, in my opinion to use css3 as much as you can, because it faster and rendered before the browser finish the loading.
And only using jquery if you forced to. Again this is my opinion, i hopefully this help you in some way.
Have a nice day

A: Paul Lewis has a great article on rendering performance here: https://developers.google.com/web/fundamentals/performance/rendering/
In general, CSS is faster because it's farther down the pipeline than javascript.


text:
Q: Azure Blue/Green deployment - use same public IP across Load Balancers I'm currently using the standard blue/green deployment setup here:

I need to use the same public IP for both Load Balancers.
Currently it appears that a load balancer (LB) can only use a 'not used' frontend IP configuration. So, I could switch the load balancer off the public IP onto a temporary one then assign the public IP to the other LB. Not such a slick blue/green deployment though.
Is there a way to overcome this issue so I can switch the traffic manager over and the public IP remains the same?

A: You can try this:
https://learn.microsoft.com/en-us/rest/api/load-balancer/load-balancers/swap-public-ip-addresses
{
  "frontendIPConfigurations": [
    {
      "id": "/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/loadBalancers/lb1/frontendIPConfigurations/lbfe1",
      "properties": {
        "publicIPAddress": {
          "id": "/subscriptions/subid/resourceGroups/rg2/providers/Microsoft.Network/publicIPAddresses/pip2"
        }
      }
    },
    {
      "id": "/subscriptions/subid/resourceGroups/rg2/providers/Microsoft.Network/loadBalancers/lb2/frontendIPConfigurations/lbfe2",
      "properties": {
        "publicIPAddress": {
          "id": "/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/publicIPAddresses/pip1"
        }
      }
    }
  ]
}

I would probably still prefer a blue/green solution that does not depend on something like this, but it can be a start.


text:
Q: How to get file path of the file with the running-vba code I want to get the folder path from the file who is running the vba-code.
For example: the vba-code is in the file C:\myfolder\file.accdb and I want the vba-code to return C:\myfolder\
Is that possible?

A: You need
currentproject.Path


text:
Q: How to add SOAP header with spring-ws I created a web service endpoint with Spring-WS:
@Endpoint
public class MyEndpoint{

@PayloadRoot(namespace = NAMESPACE, localPart = "MyRequest"
@ResponsePayload
public final MyResponse MyService(@RequestPayload final MyRequest request, SoapHeader header) {

... implementation that creates the reponse ...

return response;
}

this creates me the service and generates the WSDL for the service.
But, the  section in my WSDL remains empty.
So, what do I have to do in order to 'populate' the header?

A: SoapHeader doesn't represent an individual header block, but the soap:Header element which contains all header blocks as children. This means that your service definition doesn't provide enough metadata to generate a WSDL with a message part bound to a header block. You would have to declare a SoapHeaderElement argument with a @SoapHeader annotation that specifies the name of the header block. In theory, that would provide enough metadata to generate the expected WSDL, but I believe that in practice Spring-WS doesn't support this. Note that that doesn't mean that the generated WSDL is incorrect. The reason is that it is not mandatory to declare header blocks in the WSDL.


text:
Q: Is there any easy way to extract h.264 raw stream in annexb format? When I extract video stream with ffmpeg using command-line:
ffmpeg -i {some file} -vcodec copy -an -f {rawvideo|h264|whatever} out.h264
with some media files produced by Adobe Media Encoder, only .m4v (encoded as h.264 blu-ray) files can produce some usable results.
Some other format(like .f4v) can produce h.264 stream, but without PPS/SPS, and each slice starts with size instead of 00 00 00 01 sequence.
I wish I can extract annexb format raw streams from as many as possible files that contains valid h.264 stream. I know I can add PPS/SPS and change size into 00 00 00 01 myself. But is there any existing software can do this?

Or can it be guaranteed that ffmpeg can always extract streams in annexb format from .m4v file, no matter with what software the file is encoded?

A: What you are probably looking for is the h264_mp4toannexb bitstream filter, invoked with the -bsf command line option:
ffmpeg -i {some file} -vcodec copy -bsf h264_mp4toannexb -an -f {rawvideo|h264|whatever} out.h264

Be advised that if your version of FFmpeg is a bit old, you may need to use -vbsf instead of -bsf (the option was renamed recently).


text:
Q: Wordpress: update_post_meta not working I am modifying an existing plugin and I want to add a new field to the form and then have that field be submitted along with the post. The post gets submitted to wp_posts. I have read on Google that to do this one simply needs to use update_post_meta. I am trying to insert data into a new column I made in PHPMyAdmin. I named the column post_amount. The field name is amount_field. Although I'm a beginner, something about "just use update_post_meta" that I've read seems too simple to be all that I need. But I might be wrong. Maybe I'm using it wrong?
Note - this whole attempt is due to me wanting to create a new column in the wp_posts table and add data to it with each posts. Is this even the correct way to do this? I see the words "meta_key" and "meta_value" and it makes me think that this will actually end up adding data in the wp_postmeta table....or is that the intended destination?
$question_array = array(
            'post_title'        =>  $fields['title'],
            'post_author'       =>  $user_id,
            'post_content'      =>  apply_filters('ap_form_contents_filter', $fields['description']),
            'post_type'         =>  'question',
            'post_status'       =>  $status,
            'comment_status'    =>  'open',
        );

        if(isset($fields['parent_id']))
            $question_array['post_parent'] = (int)$fields['parent_id'];

        $question_array = apply_filters('ap_pre_insert_question', $question_array );

        $post_id = wp_insert_post($question_array);

        $post_amount = $fields['amount_field']; //My code

        update_post_meta($post_id, 'post_amount', $post_amount); //My code

A: I think you made a mistake updating your post_id.
In update_post_meta($post_id, 'post_amount', $post_amount);
you don't have ID of the post or the ID you want to update.
$post_id parameter is declared to Insert Post in your above code.
$post_id = wp_insert_post($question_array); So, update post query didn't find the ID.
You need ID to update post meta. It didn't find any id so it didn't update meta_key. SORRY FOR MY ENGLISH.
Try using add_post_meta instead of update_post_meta.
See the Reference


text:
Q: Why My form submit button send ne to [httpget] action? I'm Using following Actions and trying to change the Url Of my browser, but when page loaded then first time get method works good. When i try to save (i.e try to post form) then it again sends me on GET action. What Should I do?
[Route("Edit-Admin-{id}"),HttpGet]
public ActionResult Edit(string id)
{
  // Some Code
}

[HttpPost]
public ActionResult Edit(AdminViewModel model)
{
   // Some Code
}

And in RouteConfig.cs
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
        );
    }
}


text:
Q: Laravel Stop SSL Redirect on FORM Helper I have a web form in Laravel that is behind an ip. Example:
127.0.0.1/posts/create

With a simple form helper:
{{ Form::open(array('url' => '/posts','files'=>'true')) }}
    @include('posts._form')

    {!! Form::submit('Create Post', ['class' => 'btn btn-primary']) !!}

{!! Form::close() !!}

When I inspect the html, https is added to the url. How can I stop this?

A: Found the problem, my nginx had the HTTPS variable set on. Laravel apparently reads that variables and adds the protocol + host_name to all redirect actions.


text:
Q: How do I fix Error: could not create the Java VM? Recently, i've been trying to set up forge on java minecraft. However, a problem popped up where, after installing java, I would get this message upon attempting to open the forge installer:
Error: could not create the Java Virtual Machine.
So, naturally, I googled the problem to see what I could do. After spending hours trying to fix this issue, and attempting seemingly every "solution", I felt exhausted. I would uninstall java, and reinstall it, even receiving the error during installation. I even tried different java versions.
Eventually, I decided to try and install forge without java, so I opened up the cmd prompt, and found this message.

Picked up _JAVA_OPTIONS: ûXmx512M
Unrecognized option: ûXmx512M
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

I toyed around with sysdm, because someone said that was where the _JAVA_OPTIONS issue lied, but it wasnt. The only java options that was there was the one I created, with 1024M instead of 512M. Even when I deleted it, the error remained the same. What do I do?
EDIT: it seems like nobody has both the virtual machine error and the java options error at the same time. how did i manage this

A: I Had the same error today. To fix it, I uninstalled the jdk and downloaded it again in https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html.
For some reason, reinstalling only fixes the problem when you download the jdk from this link.


text:
Q: Event handler throws error in delegate type? I've event for Copy Proses, but I have a problem error in line cp.OnCopying :

No overload for 'cp_copying' matches delegate
  System.EventHandler 'System.ComponentModel.ProgressChangedEventArgs'

in line cp.OnCopyingComplete :

Cannot implicitly convert type 'System.EventHandler'System.EventArgs''
  to 'CustomProses.Completedelegate'

code:
public void SalinMultipleFile1()
{
   cp.OnCopying += new EventHandler<ProgressChangedEventArgs>(cp_copying);
   cp.OnCopyingComplete += new EventHandler<EventArgs>(cp_CopySucces);
   cp.CustomCopy(DGVFile, tempFolder);
}

void cp_copying(object sender, ProgressEventArgs e)
{
   dfe.pbPerFile.Increment(e.PercentDelta);
}

void cp_CopySucces(object sender, EventArgs e)
{
    dfe.l_proses.Text = "Succes Copy";
}

class Custom Proses
Class CustomProses
{
   public delegate void ProgressChangeDelegate(double Persentage, ref bool Cancel);
   public delegate void Completedelegate();
   public event ProgressChangeDelegate OnCopying;
   public event Completedelegate OnCopyingComplete;
}

Does anyone know where the mistake lies?

A: You need to change your EventHandler assignments to something like this.
cp.OnCopying += cp_copying;
cp.OnCopyingComplete += cp_CopySucces;

Your eventhandlers also need to match the events exactly so change your eventhandlers to :
void cp_copying(double value, ref bool e)
{
    //dfe.pbPerFile.Increment(e.PercentDelta);
}

void cp_CopySucces()
{
   // dfe.l_proses.Text = "Succes Copy";
}

A: Your Completedelegate takes no parameter and returns void.But you are trying to attach it your cp_CopySucces wich takes two parameter.
Your ProgressChangeDelegate takes one double and one bool parameter,but you are trying to attach it to cp_copying method which takes an object and ProgressEventArgs as parameter.
Your method and delegate signatures should match.Errors are obvious by the way.I think you need to read Delegates Tutorial


text:
Q: Python Flask. Keep running the code even if the page from browser was closed Here is my problem. I want to use Flask framework with python in order to make the web page with the form. After user submits it via browser, he is redirected to another page. And after the page was loaded the specific task (piece of code) should be executed even if the user already closed the page. After code executed user gets email.
Why I need this? Because the code will be executing for long time. In order user doesn't need to wait, I need to solve this problem.
Can you suggest something? May be some other ways (prefferable with Flask)?

A: You should run background task after a user submits the form. One possible solution is use something like Celery.


text:
Q: jQuery .accordion() Doesn't Work because jQuery Not Loading into HTML I've read everything on the web as well as everything on Stack Overflow. I've modified my code many times and my code STILL doesn't work! I'm going crazy because jQuery shouldn't be this difficult!
Just to clarify, the accordion function does not even show up on the page. All my HTML and CSS work perfectly. All I see on the page is headings and paragraphs. The paragraphs are supposed to act as an accordion when the headings are clicked.
Here is my HTML:
<!DOCTYPE HTML>

        <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="SHORTCUT ICON" HREF="/favicon.png">
    <title>Services</title>
    <link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css">

Web Development

Text text text Text text text Text text text Text text text Text text text

Mobile Development

Text text text Text text text Text text text Text text text Text text text

SEO

Text text text Text text text Text text text Text text text Text text text

UPDATE
It appears that for some reason, jQuery is not loading into my HTML. How should I fix this?

A: Replace the jquery and jquery-ui scripts definition in your code with these:

It should work now.

A: The best thing is for the script to go underneath the html code. Another important thing is to use window.onload() instead of .ready(). This worked for me two days ago :)
This allows the code to run once the page has completely loaded:
http://www.w3schools.com/jsref/event_onload.asp
Hope it helps :)

A: try this:
$(function () {
    $('#accordion').accordion();
});

Could you please run this code:
My guess is, that one of those are not loaded:
if (window.jQuery) {
   alert("Jquery loaded");
} else {
    alert("not loaded");// jQuery is not loaded
}

A: Ok
I think that you searching this
I add
{ fillSpace: true, collapsible: true ,active: false}

Then the script is :

You can read the difference of collapsible and fillspace on accordion
Click on Collapse content and Fill Space in the right of the image for see the difference.

A: try this as jQuery library:

instead of those one:

source:Accordion


text:
Q: HMS Push Service Security Vulnerability Our security team found insecure functions that exist in Push Kit libraries and would like to know whether it would be fixed in upcoming versions or it will stay and we have to accept the risk or if there is any customization can be done to overcome the security concerns:
Improper Verification of Intent (CWE-925), App Permissions (MSTG-PLATFORM-1)
we are using the below sdk version:
implementation 'com.huawei.hms:hwid:5.0.1.300'
implementation 'com.huawei.hms:push:5.0.2.300'
and below are the details:
Service: com.huawei.hms.support.api.push.service.HmsMsgService
the service  in the SDK manifest file exists as below:
<service android:name="com.huawei.hms.support.api.push.service.HmsMsgService" android:enabled="true" android:exported="true" android:process=":pushservice" android:directBootAware="true">

<intent-filter>

<action android:name="com.huawei.push.msg.NOTIFY_MSG" />

<action android:name="com.huawei.push.msg.PASSBY_MSG" />

</intent-filter>

</service>

which means that this service is found to be shared with other apps on the device therefore leaving it accessible to any other application on the device.
so, we need your support to add protectionLevel: signatureOrSystem or protect it by protected permission android:permission="PermissionName".
Any feedback is highly appreciated.

A: Confirmed by relevant teams, the HmsMsgService is open to the HMS. After the HMS is started, the package name verification and other verification will be performed. In addition, the service is not a message receiving module of Huawei mobile phones and needs to be open to the HMS, and the HMS cannot set permissions for applications in advance. Besides, the service has two layers of verification, namely, source package name verification and HMS signature verification, which has no security risk.
Therefore, the HmsMsgService will not be used by other applications and will not cause security issues. There is no need to add protectionLevel: signatureOrSystem or android:permission="permissionName" to this service, which has no security risks. Please feel free to use.


text:
Q: ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when compiling a Job                DECLARE
               X           NUMBER := 960004;
               user_name   VARCHAR2 (30);
            BEGIN
               SELECT USER INTO user_name FROM DUAL;

               EXECUTE IMMEDIATE 'alter session set current_schema = EC_ADMIN';

               BEGIN
                  SYS.DBMS_JOB.iSUBMIT (
                     job         => X,
                     what        => 'DECLARE
               p_error_text                VARCHAR2 (4000);
               p_exec_status               VARCHAR2 (50);
               l_error_source_s   CONSTANT VARCHAR2 (30) := ''JOB# 960004'';
               l_sql_point_n               NUMBER;
               l_err_text_s                VARCHAR2 (4000);

---cursor to fetch the inventory_item_id, organization_id----

               CURSOR c_system_item
               IS
            SELECT inventory_item_id, organization_id
              FROM xx_mtl_system_items_b
            WHERE tc_processed_status = ''N''
            UNION
            SELECT xmic.inventory_item_id, xmic.organization_id
              FROM xx_mtl_item_categories xmic
            WHERE     EXISTS
                          (SELECT 1
                             FROM xx_mtl_system_items_b xmsib
                            WHERE     xmsib.organization_id = xmic.organization_id
                                  AND xmsib.inventory_item_id = xmic.inventory_item_id)
                   AND tc_processed_status = ''N''
            UNION
            SELECT xemsieb.inventory_item_id, 1 AS organization_id
              FROM xx_ego_mtl_sy_items_ext_b xemsieb
            WHERE     EXISTS
                          (SELECT 1
                             FROM xx_mtl_system_items_b xmsib
                            WHERE xmsib.inventory_item_id = xemsieb.inventory_item_id)
                   AND tc_processed_status = ''N''
                   AND attr_group_id = 591;

------------------cursor ends-----------

            BEGIN
               FOR system_item_rec IN c_system_item
               LOOP
                  BEGIN
                     l_sql_point_n := 10;
                     xx_mtl_system_items_b_proc (system_item_rec.inventory_item_id,
                                                 system_item_rec.organization_id,
                                                 p_error_text,
                                                 p_exec_status);
                     l_sql_point_n := 20;

                     IF p_exec_status = ''SUCCESS''
                     THEN
                        l_sql_point_n := 30;

                        UPDATE xx_mtl_system_items_b
                           SET tc_processed_status = ''Y'', tc_processed_date = SYSDATE
                         WHERE inventory_item_id = system_item_rec.inventory_item_id
                               AND organization_id = system_item_rec.organization_id;

                        l_sql_point_n := 40;

                        UPDATE xx_mtl_item_categories
                           SET tc_processed_status = ''Y'', tc_processed_date = SYSDATE
                         WHERE inventory_item_id = system_item_rec.inventory_item_id
                               AND organization_id = system_item_rec.organization_id;

                        l_sql_point_n := 41;

                        UPDATE XX_EGO_MTL_SY_ITEMS_EXT_B
                           SET tc_processed_status = ''Y'', tc_processed_date = SYSDATE
                         WHERE inventory_item_id = system_item_rec.inventory_item_id
                               AND attr_group_id = 591;

                     ELSIF p_exec_status = ''FAILURE''
                     THEN
                        l_sql_point_n := 50;

                        UPDATE xx_mtl_system_items_b
                           SET tc_processed_status = ''E'', tc_processed_date = SYSDATE
                         WHERE inventory_item_id = system_item_rec.inventory_item_id
                               AND organization_id = system_item_rec.organization_id;

                        l_sql_point_n := 60;

                        UPDATE xx_mtl_item_categories
                           SET tc_processed_status = ''E'', tc_processed_date = SYSDATE
                         WHERE inventory_item_id = system_item_rec.inventory_item_id
                               AND organization_id = system_item_rec.organization_id;

                        l_sql_point_n := 61;

                        UPDATE XX_EGO_MTL_SY_ITEMS_EXT_B
                           SET tc_processed_status = ''E'', tc_processed_date = SYSDATE
                         WHERE inventory_item_id = system_item_rec.inventory_item_id
                               AND attr_group_id = 591;

                     END IF;

                     l_sql_point_n := 70;
                     COMMIT;
                  EXCEPTION
                     WHEN OTHERS
                     THEN
                        ROLLBACK;
                        l_err_text_s :=
                              ''Error Ocured In : ''
                           || l_error_source_s
                           || '' At SQL Point : ''
                           || l_sql_point_n
                           || '' ERROR : ''
                           || SUBSTR (SQLERRM (SQLCODE), 1, 250);

                        xx_log_dbms_error (''E'',
                                           ''Inventory_Item_Id'',
                                           system_item_rec.inventory_item_id,
                                           NULL,
                                           l_err_text_s,
                                           USER,
                                           l_error_source_s);
                  END;
               END LOOP;
            END;',
                     next_date   => SYSDATE,
                     interval    => 'SYSDATE + 45/1440',
                     no_parse    => FALSE);
                  SYS.DBMS_OUTPUT.PUT_LINE ('Job Number is: ' || TO_CHAR (x));

                  EXECUTE IMMEDIATE 'alter session set current_schema = ' || user_name;
               EXCEPTION
                  WHEN OTHERS
                  THEN
                     EXECUTE IMMEDIATE 'alter session set current_schema = ' || user_name;

                     RAISE;
               END;

               COMMIT;
            END;
            /

Gives the Error
  [Error] Execution (26: 1): ORA-01461: can bind a LONG
  value only for insert into a LONG column ORA-06512: at line 142
inventory_item_id, organization_id both are of datatype number in
  xx_mtl_system_items_b & xx_mtl_item_categories
inventory_item_id is of datatype number in xx_ego_mtl_sy_items_ext_b
  and organization_id  is not present in xx_ego_mtl_sy_items_ext_b

A: You are submitting a 6300-character string to DBMS_JOB.SUBMIT.  Depending on the Oracle version, that can be too long.  Oracle sometimes sees a long string like that and does an automatic conversion to LONG, which is an abhominable beast of a data type.  The usual limit for a varchar2 is 4000.  I think that's what killed you.


text:
Q: Why is Array Merge Not Working in a For Loop In the for loop I am merging the arrays but only the last one is added at the end of the loop.
$result = json_decode($response['body']);

if(isset($result->{'items'})) {
    $count = count($result->{'items'});
} else {
   $count = 0;
}
$json = [];
if($count > 0) {
    for ($i=0; $i < $count; $i++) {
        if (isset($result->{'items'}[$i]->{'title'})) {
            $title = $result->{'items'}[$i]->{'title'};
            $title_array = array('title' => $title);
            $json = array_merge($json, $title_array);
        }
    }
}

A: Your problem is that you are attempting to merge an array which contains 'title' => 'x' with another which contains 'title' => 'y'. Since they both contain the same keys, the second overwrites the first. You need to change this line:
$json = array_merge($json, $title_array);

to
$json[] = $title_array;

Then you will get an array of arrays with titles e.g.
[['title' => 'x'], ['title' => 'y']]

A: Replace:
$json = array_merge($json, $title_array);

By the following:
array_push($json, $title_array); // it will push the the new array to `$json`


text:
Q: Trying to use ColdFusion to pass form data around for a post/redirect/get I have to fix a security vulnerability on a ColdFusion page containing a FORM where we do not want the user to be able to press back+reload on the browser, and see the fields filled in with what they had typed prior to submitting the form.
The site has a .cfm page which loads a template for another .cfm page. The 2nd .cfm page has the FORM object, which has as its ACTION the first .cfm page. It's a search criteria page basically which will return results.
I tried changing the ACTION for the FORM on the 2nd .cfm page to point to a temp.cfm page which had the following code
<cfheader statuscode="302" statustext="Moved Temporarily">
<cfheader name="Location" value="firstpage.cfm">
<cfabort>

so that the browser would not be able to use "back" to return to the original .cfm page with the values filled in...but this is not passing my FORM data past this temp.cfm page and my searches are always bringing up zero results.

A: After your action page processes the form, use CFLOCATION to redirect the browser to another page. This uses a 302 redirect.

A: Are you using cfform? if so, remove the PreserveData="true" attribute on your form.  Or you could optionally remove your value="#form.formfield#" from the form inputs.  If you could post a couple of lines of your form, we can probably provide better help.
Did you check to see if the form page is being cached?

A: Disable caching in the meta tag of the HTML would work.  Don't need to use redirect at all.
E.g. User clicked logout link, and when the user click back, it will be a new request, and by that time, you can check if the SESSION is logged in or not, if not, redirect to the login page.


text:
Q: Rxjs global task timer I am trying to create a global task timer on my app.
I am looking a solution for:
 - when I clicked start progress on task, the timer will count 60 s.
 - but when I change page (another component) and come back to previous one, the timer will be still counting.
Do you think that cold timer obserer it is good idea? I have problem with implement it. Or maybe RxJs has that solution by out of box?
I mean - how is the best idea for timer persist?
Thank you ford the advice.

A: You could store the timer Observable in a service, making sure to subscribe to it from within the service so that it doesn't lose all subscribers. Something along these lines:
private timer = interval(1000).pipe(take(60));
private timerStarted = false;

startTimer() {
  this.timer.pipe(
    tap(() => this.timerStarted = true),
    finalize(() => this.timerStarted = false)
  ).subscribe();
}

getTimer() {
  return this.timer;
}

getTimerStarted() {
  return this.timerStarted;
}

Then, in your component:
private destroy$ = new Subject<boolean>();

ngOnInit() {
  if (this.timerService.getTimerStarted()) {
    this.timerService.getTimer().pipe(
      takeUntil(this.destroy$),
      // handle timer stuff here
    ).subscribe();
  }
}

onStartTimer() {
  this.timerService.startTimer();
  this.timerService.getTimer().pipe(
    takeUntil(this.destroy$),
    // handle timer stuff here
  ).subscribe();
}

ngOnDestroy() {
  this.destroy$.next(true);
}

EDIT: moved the take(60) to the Observable itself, and not to the one inside the startTimer method. This should prevent it from counting beyond 60 seconds when subscribed to from outside.


text:
Q: Using mod_rewrite to prepend a directory name to relative path I'm trying to redirect clients requesting http://www.example.com to http://www.example.com/moodle.
This can be easily achieved by placing a html file in www root which redirects incoming requests to specified address. Though I want to get this going with mode_rewrite rules.
I've tried few simple configuration but have either ended up in a loop or some other problem.

A: Add it to your configuration:
Alias /moodle /var/www/moodle
<Directory /var/www/moodle>
    Order allow,deny
    allow from all
</Directory>

and fit the configuration between "Directory" to your needs.
Apache documentation for more information


text:
Q: Why am I getting java.lang.VerifyError when enhancing ebean scala entity I am new to ebean and scala/akka and am trying to persist a minimal case class as an ebean entity.  My dependencies are as follows:
scalaVersion := "2.11.5"

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-actor" % "2.3.9",
  "com.typesafe.akka" %% "akka-remote" % "2.3.9",
  "com.typesafe.akka" %% "akka-cluster" % "2.3.9",
  "com.typesafe.akka" %% "akka-testkit" % "2.3.9" % "test",
  "org.scalatest" %% "scalatest" % "2.2.4" % "test",
  "com.typesafe.slick" %% "slick" % "3.0.0",
  "com.typesafe.slick" %% "slick-codegen" % "3.0.0",
  "org.sorm-framework" % "sorm" % "0.3.18",
  "org.avaje.ebeanorm" % "avaje-ebeanorm" % "4.7.1",
  "org.avaje.ebeanorm" % "avaje-ebeanorm-agent" % "4.5.3",
  "org.avaje" % "avaje-agentloader" % "1.1.3",
  "org.apache.commons" % "commons-pool2" % "2.0")

and my entity:
package zw.co.esol.eswitch.model

import javax.persistence.Entity
import javax.persistence.Id
import com.avaje.ebean.Model

@Entity
case class Test(@Id id: Long, firstname: String) extends Model

and my main:
object ApplicationMain extends App {

  val system = ActorSystem("eswitch", ConfigFactory.load())

  //system.logConfiguration()

    // Load the agent into the running JVM process
    if (!AgentLoader.loadAgentFromClasspath("avaje-ebeanorm-agent","debug=1;packages=zw.co.esol.eswitch.model.*")) {
      println("avaje-ebeanorm-agent not found in classpath - not dynamically loaded");
    }

    EbeanDbServer.init
    //more code follows.......

and my ebean init code:
object EbeanDbServer {

  def init = {

    // programmatically build a EbeanServer instance
    // specify the configuration...

    println("@@ Starting EbeanServer...")

    var config = new ServerConfig();
    config.setName("pgtest");

    // Define DataSource parameters
    var postgresDb = new DataSourceConfig();
    postgresDb.setDriver("com.mysql.jdbc.Driver");
    postgresDb.setUsername("user");
    postgresDb.setPassword("password");
    postgresDb.setUrl("jdbc:mysql://127.0.0.1:3306/eswitch");
    postgresDb.setHeartbeatSql("select count(*) from message");

    config.setDataSourceConfig(postgresDb);

    // specify a JNDI DataSource
    // config.setDataSourceJndiName("someJndiDataSourceName");

    // set DDL options...
    config.setDdlGenerate(false);
    config.setDdlRun(false);

    config.setDefaultServer(false);
    config.setRegister(false);

    var test = Test(1, "stan")
    // automatically determine the DatabasePlatform
    // using the jdbc driver
    // config.setDatabasePlatform(new PostgresPlatform());

    // specify the entity classes (and listeners etc)
    // ... if these are not specified Ebean will search
    // ... the classpath looking for entity classes.

      config.addClass(classOf[Test]);

    // specify jars to search for entity beans
 //   config.addJar("someJarThatContainsEntityBeans.jar");

    // create the EbeanServer instance
    val server: EbeanServer = EbeanServerFactory.create(config);

    println("@@ EbeanServer started... : " + server.getName)

  }
}

But I get the output when running the app:
ebean-enhance> cls: zw/co/esol/eswitch/model/Test  msg: ... skipping add equals() ... already has equals() hashcode() methods
ebean-enhance> cls: zw/co/esol/eswitch/model/Test  msg: enhanced
[error] (run-main-0) java.lang.VerifyError: Bad type on operand stack
[error] Exception Details:
[error]   Location:
[error]     zw/co/esol/eswitch/model/Test.<init>(JLjava/lang/String;)V @2: invokevirtual
[error]   Reason:
[error]     Type uninitializedThis (current frame, stack[0]) is not assignable to 'zw/co/esol/eswitch/model/Test'
[error]   Current Frame:
[error]     bci: @2
[error]     flags: { flagThisUninit }
[error]     locals: { uninitializedThis, long, long_2nd, 'java/lang/String' }
[error]     stack: { uninitializedThis, long, long_2nd }
[error]   Bytecode:
[error]     0000000: 2a1f b600 932a 2db6 0096 2ab7 0099 2abb
[error]     0000010: 009b 592a b700 9eb5 00a0 2ab8 00a6 b1
java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    zw/co/esol/eswitch/model/Test.<init>(JLjava/lang/String;)V @2: invokevirtual
  Reason:
    Type uninitializedThis (current frame, stack[0]) is not assignable to 'zw/co/esol/eswitch/model/Test'
  Current Frame:
    bci: @2
    flags: { flagThisUninit }
    locals: { uninitializedThis, long, long_2nd, 'java/lang/String' }
    stack: { uninitializedThis, long, long_2nd }
  Bytecode:
    0000000: 2a1f b600 932a 2db6 0096 2ab7 0099 2abb
    0000010: 009b 592a b700 9eb5 00a0 2ab8 00a6 b1

        at zw.co.esol.eswitch.database.EbeanDbServer$.init(EbeanDbServer.scala:45)
        at zw.co.esol.eswitch.global.ApplicationMain$.delayedEndpoint$zw$co$esol$eswitch$global$ApplicationMain$1(ApplicationMain.scala:28)
        at zw.co.esol.eswitch.global.ApplicationMain$delayedInit$body.apply(ApplicationMain.scala:17)
        at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
        at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
        at scala.App$$anonfun$main$1.apply(App.scala:76)
        at scala.App$$anonfun$main$1.apply(App.scala:76)
        at scala.collection.immutable.List.foreach(List.scala:381)
        at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
        at scala.App$class.main(App.scala:76)
        at zw.co.esol.eswitch.global.ApplicationMain$.main(ApplicationMain.scala:17)
        at zw.co.esol.eswitch.global.ApplicationMain.main(ApplicationMain.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)

I am using java version "1.7.0_55" on Linux x86_64.
What could I be doing wrong? I have tried to search for a solution but all the threads I have seen so far are not helping.

A: For some folks who might be facing this error using ebean without playframework
In your model if you are returning a POJO class in any function and if this error occurs while running your unit test case or other scenario then add setter and getter methods in your POJO class or any unrelated model class and use those functions to deal with it. dont directly access member variables and manipulate them. that produces this error. when i generated all getter/setter it resolved issue for me


text:
Q: What is minimum .fbx file requirements for FBX-SDK I am coding a converter to convert 3D models to fbx for Unreal Engine.
A very simple v0.1.0 converter has been completed.
I can import it correctly in Blender, but the FBX-SDK (used in Unreal Engine) returns an error.
File is corrupted
I think I'm missing some necessary element, is there a minimum requirement for FBX-SDK written anywhere?
I have tried to write out empty fbx data using the SDK but there are too many elements.


text:
Q: Laravel array whereIn() I have a form to filter items:

and I'm looking for something similar to this in Laravel 5.3:
// some variables get from request()->input('...')
$mode = ['A'];
$type = ['a', 'b'];
$group = [0, 1];

// desirable query
$results = Item::whereIn([
    ['mode_id', $mode],
    ['type_id', $type],
    ['group_id', $group]
])->paginate(10);

I can do this
$results = Item::whereIn('mode_id', $mode)
               ->whereIn('type_id', $type)
               ->whereIn('group_id', $group)
               ->paginate(10);

but it's not a dynamic way. For example, if a user select nothing in mode, the query returns an empty array.

A: We can use conditional clauses:
$results = Item::
    when(!empty($mode), function ($query) use ($mode) {
        return $query->where('mode_id', $mode);
    })
    ->when(!empty($type), function ($query) use ($type) {
        return $query->where('type_id', $type);
    })
    ->when(!empty($group), function ($query) use ($group) {
        return $query->where('group_id', $group);
    })
    ->paginate(10);

A: You can do:
$qb = Item::newQuery();

if (!empty($mode))
{
    $qb->whereIn('mode_id', $mode);
}

if (!empty($type))
{
    $qb->whereIn('type_id', $type);
}

if (!empty($group))
{
    $qb->whereIn('group_id', $group);
}

$results = $qb->paginate(10);

Or build your whereIn associative array w/o empty where's before passing it on.


text:
Q: Fortran error #5082: Syntax error, found IDENTIFIER when expecting one of:  ; I am "making" a code.
The compilation with make fails producing this error
mpif90 -mkl -O3 -no-prec-div -fpp -openmp -xHost -DMPI -DEFTCOSMOMC -module ReleaseEFTMPI -IReleaseEFTMPI/ -c equations_EFT.f90 -o ReleaseEFTMPI/equations_EFT.o
equations_EFT.f90(267): error #5082: Syntax error, found IDENTIFIER 'EFTCAMBINITIALCONDITIONS' when expecting one of: <END-OF-STATEMENT> ;
        module subroutine EFTCAMBInitialConditions( y, EV, tau )
--------------------------^
equations_EFT.f90(267): error #5082: Syntax error, found END-OF-STATEMENT when expecting one of: ( % [ . = =>
        module subroutine EFTCAMBInitialConditions( y, EV, tau )
----------------------------------------------------------------^
equations_EFT.f90(271): error #6786: This is an invalid statement; an END [MODULE] statement is required.
        end subroutine EFTCAMBInitialConditions
--------^
equations_EFT.f90(271): error #6758: This name is invalid; if a name is present, it must match the corresponding interface body name.   [EFTCAMBINITIALCONDITIONS]
        end subroutine EFTCAMBInitialConditions
-----------------------^
equations_EFT.f90(268): error #6457: This derived type name has not been declared.   [EVOLUTIONVARS]
            type(EvolutionVars) EV
-----------------^
equations_EFT.f90(269): error #6683: A kind type parameter must be a compile-time constant.   [DL]
            real(dl) :: y(EV%nvar)
-----------------^
equations_EFT.f90(269): error #6535: This variable or component must be of a derived or structure type   [EV]
            real(dl) :: y(EV%nvar)
--------------------------^
equations_EFT.f90(269): error #6460: This is not a field name that is defined in the encompassing structure.   [NVAR]
            real(dl) :: y(EV%nvar)
-----------------------------^
equations_EFT.f90(269): error #6223: A specification expression is invalid.   [NVAR]
            real(dl) :: y(EV%nvar)
-----------------------------^
equations_EFT.f90(270): error #6683: A kind type parameter must be a compile-time constant.   [DL]
            real(dl) :: tau
-----------------^
equations_EFT.f90(269): error #6279: A specification expression object must be a dummy argument, a COMMON block object, or an object accessible through host or use association   [EV]
            real(dl) :: y(EV%nvar)
--------------------------^
compilation aborted for equations_EFT.f90 (code 1)

I attach the snippet from equations_EFT.f90
interface

        module subroutine EFTCAMBInitialConditions( y, EV, tau )
            type(EvolutionVars) EV
            real(dl) :: y(EV%nvar)
            real(dl) :: tau
        end subroutine EFTCAMBInitialConditions

    end interface

Is there something wrong in this snippet? It is strange because this is distributed software, but I have literally just followed the instruction to make the code.

A: The code of the question is an example of using submodules, a feature newly introduced into Fortran in the 2008 revision.  To compile this code you will need a compiler which understands this concept.
The GNU and Intel compilers are examples of such, but you will need an appropriate version.


text:
Q: How to get the machine Address when a miss in Emulated TLB happens? I am learning Virtualization and would like to know if anyone can explain in detail on how to get machine address once an emulated TLB miss occurs in x86. Also, how many memory access will happen in order to get the Machine address?
All the google search results gives very basic info. Please advice. Thanks.


text:
Q: Testing Emitter func with channel return value in go I am having a hard time getting my test for my emitter function which passes results through a channel for a data pipeline. This function will be triggered periodically and will pull records from the database. I compiled an stripped done version for this question the real code would more complex but would follow the same pattern. For testing I mocked the access to the database because I want to test the behavoir of the Emitter function.
I guess code is more than words:
This is the method I want to test:
//EmittRecord pull record from database
func EmittRecord(svc Service, count int) <-chan *Result {
    out := make(chan *Result)

    go func() {
        defer close(out)
        for i := 0; i < count; i++ {
            r, err := svc.Next()
            if err != nil {
                out <- &Result{Error: err}
                continue
            }
            out <- &Result{Payload: &Payload{
                Field1: r.Field1,
                Field2: r.Field2,
            }, Error: nil}
        }

    }()

    return out
}

I have a couple of types with an interface:
//Record is a Record from db
type Record struct {
    Field1 string
    Field2 string
}

//Payload is a record for the data pipeline
type Payload struct {
    Field1 string
    Field2 string
}

//Result is a type for the data pipeline
type Result struct {
    Payload *Payload
    Error   error
}

//Service is an abstraction to access the database
type Service interface {
    Next() (*Record, error)
}

This is my service Mock for testing:
//MockService is a struct to support testing for mocking the database
type MockService struct {
    NextMock func() (*Record, error)
}

//Next is an Implementation of the Service interface for the mock
func (m *MockService) Next() (*Record, error) {
    if m.NextMock != nil {
        return m.NextMock()
    }
    panic("Please set NextMock!")
}

And finally this is my test method which does not work. It does not hit the done case and das not hit the 1*time.Second timeout case either ... the test just times out. I guess I am missing something here.
 func TestEmitter(t *testing.T) {

    tt := []struct {
        name           string
        svc            runner.Service
        expectedResult runner.Result
    }{

        {name: "Database returns error",
            svc: &runner.MockService{
                NextMock: func() (*runner.Record, error) {
                    return nil, fmt.Errorf("YIKES")
                },
            },
            expectedResult: runner.Result{Payload: nil, Error: fmt.Errorf("RRRR")},
        },
        {name: "Database returns record",
            svc: &runner.MockService{
                NextMock: func() (*runner.Record, error) {
                    return &runner.Record{
                        Field1: "hello",
                        Field2: "world",
                    }, nil
                },
            },
        },
    }

    for _, tc := range tt {

        t.Run(tc.name, func(t *testing.T) {
            done := make(chan bool)
            defer close(done)

            var output <-chan *runner.Result
            go func() {
                output = runner.EmittRecord(tc.svc, 1)
                done <- true
            }()
            found := <-output
            <-done
            select {
            case <-done:
            case <-time.After(1 * time.Second):
                panic("timeout")
            }

            if found.Error.Error() != tc.expectedResult.Error.Error() {
                t.Errorf("FAIL: %s, expected: %s; but got %s", tc.name, tc.expectedResult.Error.Error(), found.Error.Error())

            } else if reflect.DeepEqual(found.Payload, tc.expectedResult.Payload) {
                t.Errorf("FAIL: %s, expected: %+v; got %+v", tc.name, tc.expectedResult.Payload, found.Payload)
            }

        })
    }

}

It would be great, if someone could give me an advice what I missing here and maybe some input how to verify the count of the EmittRecord function right now it is only set to 1
Thanks in advance
//Edited: the expectedResult as per Comment by @Lansana

A: Are you sure you have your expected results in the tests set to the proper value?
In the first slice in the test, you expect a fmt.Errorf("RRRR"), yet the mock returns a fmt.Errorf("YIKES").
And then later in the actual test conditionals, you do this:
if found.Error.Error() != "Hello" {
    t.Errorf("FAIL: %s, expected: %s; but got %s", tc.name, tc.expectedResult.Error.Error(), found.Error.Error())
}

You are checking "Hello". Shouldn't you be checking if it's an error with the message "YIKES"?
I think your logic is good, but your test is just not properly written. Check my Go Playground example here and run the code. You will see there is no output or panics when you run it. This is because the code passes my test conditions in main.
You are adding more complexity to your test by more channels, and if those extra channels are invalid then you may have some false positives that make you think your business logic is bad. In this case, it actually seems to be working as it should.
Here is the highlight of the code from my playground example . (the part that tests your logic):
func main() {
    svc1 := &MockService{
        NextMock: func() (*Record, error) {
            return nil, errors.New("foo")
        },
    }
    for item := range EmittRecord(svc1, 5) {
        if item.Payload != nil {
            panic("item.Payload should be nil")
        }
        if item.Error == nil {
            panic("item.Error should be an error")
        }
    }

    svc2 := &MockService{
        NextMock: func() (*Record, error) {
            return &Record{Field1: "Hello ", Field2: "World"}, nil
        },
    }
    for item := range EmittRecord(svc2, 5) {
        if item.Payload == nil {
            panic("item.Payload should have a value")
        }
        if item.Payload.Field1 + item.Payload.Field2 != "Hello World" {
            panic("item.Payload.Field1 and item.Payload.Field2 are invalid!")
        }
        if item.Error != nil {
            panic("item.Error should be nil")
        }
    }
}

The output from the above code is nothing. No panics. Thus, it succeeded.
Try simplifying your test to a working state, and then add more complexity from there. :)


text:
Q: Import variable in Process::Start I use Process::Start function to run an .exe from another program.
I 'm thinking storing the .exe in location where main program (vc++) is stored. That way I could via GetCurrentDir get always the location of .exe too and then import location in Process::Start, as a variable. Is this possible?
GetCurrentDir:
#include <stdio.h>  /* defines FILENAME_MAX */
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

 char cCurrentPath[FILENAME_MAX];

 if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
     {
     return errno;
     }

Location is stored in cCurrentPath variable. I tried with:
Process::Start("%s\\application.exe", cCurrentPath);

but didn't work out. How can I fix this?


text:
Q: Processing a queue of jobs via PHP, but faster than cron's 1-minute minimum? Many users upload photos to my site, and at peak times the load of resizing and saving the photos causes my server to run out of memory and MySQL to crash.
I figure I can detach the processing from the uploading, and instead of having many concurrent reloads happening I can just have one job doing them one-by-one, which should hugely reduce my memory needs.
But how best to implement this?
My first thought was just a cronjob that runs repeatedly and checks for any unprocessed files. But a cronjob can only (I think) run every minute, so sometimes there would be a large delay even if a user uploaded just one photo at a quiet time on the site.
I expect this is a fairly common problem, so what's the solution?
(I'd rather do this myself with minimal code rather than use a huge third party library, if possible.)
Thanks


text:
Q: Nullpointer Exception I've got the following MapOverlay. The following line is throwing a NullPointer but I don't understand why :S mapView.getProjection().toPixels(p, screenPts); could anyone help me out?
    public class Mapview extends MapActivity {
GeoPoint p;
MapView mapView;
MapController mc;

@Override
protected boolean isRouteDisplayed() {
 return false;
}
public int icount = 0;
MapController mapController;
MyPositionOverlay positionOverlay;
private LocationData tweets;
public int start = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

MapView myMapView = (MapView)findViewById(R.id.mapView);

myMapView.setSatellite(true);
myMapView.setStreetView(true);
myMapView.displayZoomControls(false);
mapController = myMapView.getController();

mapController.setZoom(17);
myMapView.setBuiltInZoomControls(true);

//Adding points here

//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = myMapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);

myMapView.invalidate();

// Add the MyPositionOverlay
positionOverlay = new MyPositionOverlay();
List<Overlay> overlays = myMapView.getOverlays();
overlays.add(positionOverlay);

LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);

locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);

}

private final LocationListener locationListener = new LocationListener() {
 public void onLocationChanged(Location location) {
  updateWithNewLocation(location);
}

public void onProviderDisabled(String provider){
  updateWithNewLocation(null);
}

public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
                            Bundle extras){ }
 };

private void updateWithNewLocation(Location location) {
String latLongString ="";
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "No address found";

if (location != null) {
     // Update my location marker
    positionOverlay.setLocation(location);

  // Update the map location.
  Double geoLat = location.getLatitude()*1E6;
  Double geoLng = location.getLongitude()*1E6;
  GeoPoint point = new GeoPoint(geoLat.intValue(),
                                geoLng.intValue());

  mapController.animateTo(point);

  double lat = location.getLatitude();
  double lng = location.getLongitude();
  latLongString = "Lat:" + lat + "\nLong:" + lng;
  Global.lat = lat;
  Global.lng = lng;
  double latitude = location.getLatitude();
  double longitude = location.getLongitude();

  Geocoder gc = new Geocoder(this, Locale.getDefault());
  try {
    List<Address> addresses = gc.getFromLocation(latitude,
                                                 longitude, 1);
    StringBuilder sb = new StringBuilder();
    if (addresses.size() > 0) {
      Address address = addresses.get(0);

      for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
        sb.append(address.getAddressLine(i)).append("\n");

        sb.append(address.getLocality()).append("\n");
        sb.append(address.getPostalCode()).append("\n");
        sb.append(address.getCountryName());
    }
    addressString = sb.toString();
  } catch (IOException e) {}
} else {
  latLongString = "No location found";
}
}

class MapOverlay extends com.google.android.maps.Overlay
{
  @Override
  public boolean draw(Canvas canvas, MapView mapView,
  boolean shadow, long when)
  {
      super.draw(canvas, mapView, shadow);

      //---translate the GeoPoint to screen pixels---
      Point screenPts = new Point();
      mapView.getProjection().toPixels(p, screenPts);

      //---add the marker---
      Bitmap bmp = BitmapFactory.decodeResource(
          getResources(), R.drawable.marker);
      canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
      return true;
 }

 }
}

A: I see a declaration of GeoPoint p but no expression where p is actually initialized. So passing null to the toPixels() method could be a cause for the NPE.
Try this code instead to check, if the NPE is gone:
  //---translate the GeoPoint to screen pixels---
  if (p == null) return false;
  Point screenPts = mapView.getProjection().toPixels(p, null);

(I don't like 'out' parameters in Java, toPixels will create the point object for you
and return it)

A: Ok it seems that the public attribute GeoPoint p is never referenced
thus pointint on null.
Maybe you wanted to define p in this line:
GeoPoint point = new GeoPoint(geoLat.intValue(),
                                geoLng.intValue());
You should find the corredt place to assign p, then the problem is fixed.

A: You need to retain a reference to the myMapView that you will use later. The way to do this is to declare it as a property, using the strong attribute.