text:
Q: Cadenas dinámicas a veces no guardan el contenido correspondiente Estoy realizando un codigo más grande en el que implemento algo parecido a esto. El problema que me sucede es que cuando la cadena dinamica copia el contenido correspondiente  del arreglo de cadenas, parece no copiarlo o copiar un espacio en algunas ocasiones. Ya que al mandar a imprimir
generalmente hace lo que espero, pero a veces no imprime nada y no entiendo el por qué. ¿Alguien podría ayudarme?
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX 30

int main()
{

int c = 0;
srand(time(NULL));

    do
    {
    int i;
    int mv = rand()%7;

    char *movimiento = (char *) calloc (MAX, sizeof(char));
        if(movimiento == NULL){
            printf("\nEspacio de memoria insuficiente...\n");
        exit (0);
        }

    char mb [7][MAX] = {"Deposito","Retiro","Pago con tarjeta","Pago servicios","Consulta saldo","Aclaraciones", {0}};
        for (i=0; i<mv; i++){
            strcpy(movimiento, mb[i]);
        }
        c++;

        printf("%i:%s\n", c, movimiento);
        fflush(stdout);

        free(movimiento);
        movimiento = NULL;

    } while (c<30);

return 0;

}

A: mv es un numero al azar:
int mv = rand()%7;

Cuando mv vale 0, nota que en el for:
for (i=0; i<mv; i++){
    strcpy(movimiento, mb[i]);
}

No se copiara nada a movimiento.
Por eso es que algunos salen vacios.


text:
Q: Is it possible to instantiate a generic type's property through reflection? I am trying to create an abstract class that initializes T class properties by iterating a json-style object passed in constructor.
 abstract class JSONClass<T> {
  // Receive a JSON object implementing all T properties
  constructor(json: JSONClassDictionary<T>) {
    this.fromJSON(json);
  }

  fromJSON(json: JSONClassDictionary<T>) {
    for (let key in json){
      let prop = this[key];
      if (prop is not a class) {  <// -- 1) Determine whether it's a class
        this[key] = prop;
      }
      else{
        const constructor = getConstructorOf(T[key]) // <-- 2) Get constructor of T[Key] property. This is no-sense to compiler
        this[key] = new constructor(prop)
      }
    }
  }
}

The problem is that T may have some properties which are not primitive types, and require initialization.
Example of real case scenario and invocation:
class UserRole extends JSONClass<UserRole> {
  id;
  name;
  permissionGroup: PermissionGroup;

}

const role = UserRole({
  id: 1,
  name: "Admin",
  permissionGroup: {// <-- This will be converted to PermissionGroup() in fromJSON
    id: 1,
    action: ".."
  }
})

This means that when fromJSON is iterating through the property permissionGroup, it should not perform this[key] = prop; but this[key] = new PermissionGroup(prop).
I am having issues in Point (1) and Point (2) as shown in code comments, specifically in:

*

*Being able to determine whether the key I'm iterating in json is an instantiable class property of T, instead of a primitive type;

*If true, the initialize property of T.
Is this achievable?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert binary fraction into hexadecimal in Java? How can i convert a binary fraction or a decimal fraction into hex in Java?
What is the  algorithm to do that?
for example i want (11.110)2 be converted into (3.C)16
and which data type do I need to hold the hex fraction ?
plz help.
Thanks.

A: This answer is not meant to be a complete guide on how to make a fully working program that converts from one radix to another, but it mentions most of the steps you'd have to do if you want to use the built-in methods that are available.
There are no built-in methods for converting floating-point numbers, but there are built-in methods for converting integers from/to any radix between 2-36. If you only need to convert between binary and hexadecimal and nothing else, you could also do it manually (see below the line further down), but I recommend using these methods otherwise.
If you remove the radix point . from the number (in its String-representation), you get a whole number, but keep track of how many digits were to the right of the radix point.
Here are three ways to convert a whole number from a String with any radix:

*

*Integer.parseInt(String val, int radix) will convert to int.

*Long.parseLong(String val, int radix) will convert to long.

*new BigInteger(String val, int radix) will convert to BigInteger.

You should then convert the number to a double or BigDecimal, and make sure you get the radix point back in place, by dividing by the correct number. For instance, you can turn (1234)6 into (12.34)6 by dividing it by 6².
Now you are halfway done, and basically go backwards to convert the number back to a String (but with some other radix).
At the step where you want to convert from int/long/BigInteger to a String, use toString:

*

*Integer.toString(int val, int radix) will convert from int.

*Long.toString(long val, int radix) will convert from long.

*val.toString(int radix) will convert from BigInteger.

Remember to insert the radix point again, and you're done.

To convert from binary to hex manually, you do the same as you would do if they were whole numbers, with few differences.
Divide the binary number into sets of 4 consecutive digits, starting at the radix point, going both left and right. Add leading/trailing zeros as needed. The rest is as explained in the link.
For instance: 101011.011 is divided into 0010 1011 . 0110 which becomes 2B.6 after converting each set to hexadecimal.


text:
Q: Vulkan front face winding order I configure Vulkan VkPipelineRasterizationStateCreateInfo  to use CCW winding order:
 VkPipelineRasterizationStateCreateInfo rasterizer = {};
 rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
 rasterizer.depthClampEnable = VK_FALSE;
 rasterizer.rasterizerDiscardEnable = VK_FALSE;
 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
 rasterizer.lineWidth = 1.0f;
 rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
 rasterizer.depthBiasEnable = VK_FALSE;

My assembly state uses triangle fan to draw a quad:
  VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
 inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
 inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN;
 inputAssembly.primitiveRestartEnable = VK_FALSE;

Here is my vertex buffer:
 const  VertexPos2Col3 vertices[4] = {
{{0.5f,  0.5f}, {1.0f, 1.0f, 1.0f}},
{{-0.5f, 0.5f}, {0.0f, 1.0f, 0.0f}},
{{-0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}},
{{ 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}}
};

The order of the vertices is counter-clock wise. But the primitive shows up only if I set rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
Why is that?
System info:
Windows 10, NVIDIA RTX3000, Driver: 431.86

A: That's because Vulkan uses a different coordinate system than e.g. OpenGL. The origin for Vulkan is top-left.
So you have to cope for that either by changing the vertex/index ordering, by flipping the viewport, or by changing the sing of gl_position.y in your vertex shader. If your target supports the VK_KHR_maintenance1 extensions, then the easiest way would be to use a negative height to flip the viewport.


text:
Q: MSP430 RTC_B Back up Battery Supply I plan on using MSP430F5636IPZ from Texas Instruments as my microcontroller in a project which I am currently working on. The MCU comes with a RTC_B (Real Time Clock) with Battery Backup capability.
According to this article : "" https://www.ti.com/lit/an/slaa665b/slaa665b.pdf "" which I found for hardware implementation considers the usage of MSPTS430PZ100USB target board and  MSP-EXP430F5529LP LaunchPad kit interface, which I believe is a beginners kit which I don't need since MSP430F5636IPZ is a single chip MCU which I am trying to design on a PCB board.
Can somebody help me to understand the hardware design listed in the article and how I  can implement it in my design?
From reading the datasheet, I figured out that pin 87(Vbat) and pin 88(Vbak) are used to implement the battery backup along with RTC_B module (including a 32.768 KHz crystal oscillator).
Please Help!!

A: You need a programmer/debugger. The MSP-EXP430F5529LP LaunchPad kit has a debugger built in, it is the top portion of the board. To use a different target, remove the row of jumpers and connect to your custom target. The USB connector at the top left connects to you PC. This is how I do it.
https://www.ti.com/lit/ug/slau533d/slau533d.pdf

Or, you can use a dedicated debugger such as the MSP-FET. This is more expensive, and I have never seen the advantage to this method.
Or, you can use the MSP-TS430PZ100USB with a socket for your MCU. If TI doesn't have a Launchpad development kit for your exact MCU, then this is what you use until you have a custom board.


text:
Q: could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException SQL [n/a]; constraint [PRIMARY];
I created a CRUD RESTful API application using Java/Spring Boot. I have a MariaDB with a list of employees and relevant data inside. I am using MySQL Workbench as my SQL Client.
There are no errors when running the Spring Boot application. No errors in my database. No errors when I get the API of all Engineers in my database.
My "GET" requests work fine; however, "POST" does not. I am unable to create a new employee without having to directly insert into the database with MySQL WB.
I want to be able to create a new employee using APIs via Postman.
As you can see there is a ConstraintViolationException being thrown. The contraint is my Primary Key, which is "id." I've set that to auto-increment in MySQL WB.
Here is the code for my Engineer class:
package engineermanagement.model;

import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;

@Entity
@Table(name = "Engineers")
@EntityListeners(AuditingEntityListener.class)
public class Engineer {

    private Long id;
    private String firstName;
    private String lastName;
    private String sid;
    private String email;
    private String manager;
    private Boolean teamLead;
    private String groupName;
    private String shift;
    private int startTime;
    private int endTime;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "first_name", nullable = false)
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Column(name = "last_name", nullable = false)
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Column(name = "eid", nullable = false)
    public String getEid() {
        return eid;
    }
    public void setEid(String eid) {
        this.sid = eid;
    }

    @Column(name = "email", nullable = false)
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

    @Column(name = "manager", nullable = false)
    public String getManager() {
        return manager;
    }
    public void setManager(String manager) {
        this.manager = manager;
    }

    @Column(name = "teamlead", nullable = false)
    public Boolean getTeamLead() {
        return teamLead;
    }
    public void setTeamLead(Boolean teamLead) {
        this.teamLead = teamLead;
    }

    @Column(name = "group_name", nullable = false)
    public String getGroupName() {
        return groupName;
    }
    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    @Column(name = "shift", nullable = false)
    public String getShift() {
        return shift;
    }
    public void setShift(String shift) {
        this.shift = shift;
    }

    @Column(name = "start_time", nullable = false)
    public int getStartTime() {
        return startTime;
    }
    public void setStartTime(int startTime) {
        this.startTime = startTime;
    }

    @Column(name = "end_time", nullable = false)
    public int getEndTime() {
        return endTime;
    }
    public void setEndTime(int endTime) {
        this.endTime = endTime;
    }
}

This is the code for my EngineerController class:
package jpmchase.controller;

import jpmchase.exception.*;
import jpmchase.model.Engineer;
import jpmchase.repository.EngineerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1")
public class EngineerController {

    @Autowired
    private EngineerRepository engineerRepository;

    @GetMapping("/engineers")
    public List<Engineer> getAllEngineers() {
        return engineerRepository.findAll();
    }

    @GetMapping("/engineers/{id}")
    public ResponseEntity<Engineer> getEngineerById(
            @PathVariable(value = "id") Long engineerId) throws ResourceNotFoundException {
        Engineer engineer = engineerRepository.findById(engineerId)
                .orElseThrow(() -> new ResourceNotFoundException("Engineer not found on :: "+ engineerId));
        return ResponseEntity.ok().body(engineer);
    }

    @PostMapping("/engineers")
    public Engineer createEngineer(@Valid @RequestBody Engineer engineer) {
        return engineerRepository.save(engineer);
    }

    @PutMapping("/engineers/{id}")
    public ResponseEntity<Engineer> updateEngineer(
            @PathVariable(value = "id") Long engineerId,
            @Valid @RequestBody Engineer engineerDetails) throws ResourceNotFoundException {
        Engineer engineer = engineerRepository.findById(engineerId)
                .orElseThrow(() -> new ResourceNotFoundException("Engineer not found on :: "+ engineerId));
        engineer.setId(engineerDetails.getId());
        engineer.setFirstName(engineerDetails.getFirstName());
        engineer.setLastName(engineerDetails.getLastName());
        engineer.setSid(engineerDetails.getSid());
        engineer.setEmail(engineerDetails.getEmail());
        engineer.setTeamLead(engineerDetails.getTeamLead());
        engineer.setManager(engineerDetails.getManager());
        engineer.setShift(engineerDetails.getShift());
        engineer.setStartTime(engineerDetails.getStartTime());
        engineer.setEndTime(engineerDetails.getEndTime());

//      engineer.setUpdatedAt(new Date());
        final Engineer updatedEngineer = engineerRepository.save(engineer);
        return ResponseEntity.ok(updatedEngineer);
    }

    @DeleteMapping("/engineers/{id}")
    public Map<String, Boolean> deleteEngineer(
            @PathVariable(value = "id") Long engineerId) throws Exception {
        Engineer engineer = engineerRepository.findById(engineerId)
                .orElseThrow(() -> new ResourceNotFoundException("Engineer not found on :: "+ engineerId));

        engineerRepository.delete(engineer);
        Map<String, Boolean> response = new HashMap<>();
        response.put("deleted", Boolean.TRUE);
        return response;
    }
}

Using Postman, I am trying to "POST" a new "test" employee but fails due to the aforementioned constraint. Any help will be appreciated...
Full stack trace:
2019-01-11 15:26:50.605  WARN 15276 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1062, SQLState: 23000
2019-01-11 15:26:50.606 ERROR 15276 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry '68' for key 'PRIMARY'
2019-01-11 15:26:50.606 ERROR 15276 --- [nio-8080-exec-6] o.h.i.ExceptionMapperStandardImpl        : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2019-01-11 15:26:50.657  WARN 15276 --- [nio-8080-exec-6] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

A: org.hibernate.exception.ConstraintViolationException,

The Exception constraint violation means you set database fields with non-null, unique, etc. The database checks the data before inserting it into the table. If any one of the conditions not matching you will get a ConstraintViolationException.
In your case you have a PRIMARY key violation. so check your database table Engineer with "id=68" exists or not. If it is there kindly remove the row.

A: I had this same issue and the reason is this
o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry '68' for key 'PRIMARY'.
Hibernate is trying to generate an Id for the new Engineer, but when it tries to follow the generation strategy specified by  @GeneratedValue(strategy = GenerationType.AUTO) It gets an Id that already exists.
Most likely this happens because you manually added new rows to the Engineer table that collapses with the next generated Id values by Hibernate.
Also if you keep trying to insert a new Engineer multiple times you will end up succeeding since Hibernate increments the Id for the next insertion request until it finds an Id that doesn't already exist.
To solve the issue you can change the Id generation strategy to @GeneratedValue(strategy = GenerationType.IDENTITY) or keep trying to insert until Hibernate get to a non used Id value (If you want to keep the same generation strategy)


text:
Q: JS dispatch event I am trying to focus on a link with a given index using js dispatch event:
var link = document.querySelector(".navbar-nav > li:nth-child(" + index + ") > a");
var event = new Event("focus");
link.dispatchEvent(event);

The code above won't work whereas the jQuery version works OK:
$(".navbar-nav > li:nth-child(" + index + ") > a").focus();

I am testing in the latest Chrome. What is wrong with the JS version?

A: If you want to set the focus, then just call the focus method of the dom element

function setFocus(index) {
  var link = document.querySelector(".navbar-nav > li:nth-child(" + index + ") > a");
  link.focus()
}

1

2

3

4

<button onclick="setFocus(1)">1</button>
<button onclick="setFocus(2)">2</button>
<button onclick="setFocus(3)">3</button>
<button onclick="setFocus(4)">4</button>

Dispatching the event will not set the focus, that will just trigger the attached event handlers.
In jQuery calling the focus() method will trigger the event and will also call the native behavior method if needed that is why that is working


text:
Q: Check if URL has valid page I want to check if URL has valid page (not 404, just 200).
Code I've tried:
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(myurl), HttpWebRequest)
request.KeepAlive = True
Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
If response.StatusCode = HttpStatusCode.OK Then
    MsgBox("OK")
End If

Yet every URL that I enter leaves OK response, even if I enter http://mywebsite.com/blahblah.
It's not same on all websites (works fine with example.com), but it doesn't work on my website. Why?
In my browser I see 404 page, but code says it's OK.
Edit: Just to mention that my website has Cloudflare on.

A: Try this out and see if it work's for you... As mentioned above in my comment's:

A 404 just means the page isn't found on the server, status will return ok even if a page isn't found and the server was reached and responded

Public Class WebPage
        Public Property PageSource As String = String.Empty
        Public Property Status As HttpStatusCode = HttpStatusCode.NotFound
        Public Property WebError As String = String.Empty
    End Class

    Public Shared Function GetWebPage(ByVal Website As String) As WebPage
    Dim web As New WebPage() With {.Status = HttpStatusCode.OK}
    Try
        Using source As New System.Net.WebClient()
            web.PageSource = source.DownloadString(Website)
        End Using

        Return web
    Catch exweb As WebException
        If exweb.Status = WebExceptionStatus.ProtocolError AndAlso exweb.Message.Contains("404") Then
            web.Status = HttpStatusCode.NotFound
        Else
            web.Status = HttpStatusCode.BadRequest
        End If
        web.WebError = exweb.Message
    Catch ex As Exception
        web.Status = HttpStatusCode.NotFound
        web.WebError = ex.Message
    End Try

    Return web
End Function

Usage Example
Dim webObj As WebPage = GetWebPage("THESITE")
If Not String.IsNullOrEmpty(webObj.WebError) Then
   MessageBox.Show(webObj.WebError)
ElseIf webObj.Status = HttpStatusCode.OK Then
   MessageBox.Show("OK")
End If

A: This will do what you want.
Function URLExists(url As String) As Boolean
    Dim Request As Object
    Dim ff As Integer
    Dim rc As Variant

    On Error GoTo EndNow
    Set Request = CreateObject("WinHttp.WinHttpRequest.5.1")

    With Request
      .Open "GET", url, False
      .send
      rc = .StatusText
    End With
    Set Request = Nothing
    If rc = "OK" Then URLExists = True

    Exit Function
EndNow:
End Function


text:
Q: I have 2 identically structured beans and 2 identically structured getter statements, yet only one works I have two beans that are structured exactly the same.  I pull both those beans into the same java class the exact same way.  Yet only one of them has a problem.
Here is the error when I try to build it:

cannot find symbol
  symbol  : constructor BalanceBean(java.lang.String)
  location: class HWpackage.BalanceBean

Here is the working bean, UserBean2
package HWpackage;

public class UserBean2 {
  private String id;

  public UserBean2(String id) {
    setUsername(id);
  }

  public String getUsername() {
    return(id);
  }

  public void setUsername(String id) {
    if (!isMissing(id)) {
      this.id = id;
    }
  }

  private boolean isMissing(String value) {
    return((value == null) || (value.trim().equals("")));
  }
}

And here is the working getter statements:
  UserBean2 userBean2 = (UserBean2)session.getAttribute("userBean2");
  String un = request.getParameter("id");
  userBean2 = new UserBean2(un);
  session.setAttribute("userBean2", userBean2);

Now compare that to the non-working code.
BalanceBean:
package HWpackage;

public class BalanceBean {
  private String balance, id;

  public BalanceBean (String balance, String id) {
    setBalance(balance);
    setID(id);
  }

  public String getBalance() {
    return(balance);
  }

  public void setBalance(String balance)
  {
      this.balance = balance;
  }

  public String getID() {
    return(id);
  }

  public void setID(String id)
  {
      this.id = id;
  }
}

And its getter statements:
BalanceBean balanceBean = (BalanceBean)session.getAttribute("balanceBean");
String balance = request.getParameter("balance");
balanceBean = new BalanceBean(balance);
session.setAttribute("balanceBean", balanceBean);

For what ever reason, the BalanceBean in the line: balanceBean = new BalanceBean(balance);
is causing all the problems.
Can someone please tell me why?
UPDATED:
OK, if I change my BalanceBean to:
package HWpackage;

public class BalanceBean {
  private String balance, id;

  public BalanceBean (String balance) {
    setBalance(balance);
  }

  public String getBalance() {
    return(balance);
  }

  public void setBalance(String balance)
  {
      this.balance = balance;
  }

  public String getID() {
    return(id);
  }

  public void setID(String id)
  {
      this.id = id;
  }
}

How do I add back my String id?

A: They're not identical, and the error is telling you exactly what is wrong:
cannot find symbol symbol : constructor BalanceBean(java.lang.String)

You do not have a constructor in BalanceBean that takes a String as the only argument.
You have:
public BalanceBean (String balance, String id)

And are trying to call:
balanceBean = new BalanceBean(balance);

Edit: If you want to add a second constructor, you are more than able to:
public BalanceBean (String balance) {
    setBalance(balance);
}

A: BalanceBean has a two arg constructor. public BalanceBean (String balance, String id). You are passing only one argument new BalanceBean(balance)

A: Have a look at the BalanceBean class constructors, it appears you haven't define a constructor with only one parameter.

A: The constructor BalanceBeam(String, String) expects 2 parameters, and you're only providing it one parameter.  Therefore a new constructor of type BalanceBeam(String) is needed


text:
Q: Using ApiControllerAttribute without using RouteAttribute In ASP.NET Core (v 2.1.5) you can create controllers without having them inherit from Controller class (as you know). And if you do, you have to use RouteAttribute to define your routes. But, I'm interested if we can use implicit routing (and not attribute routing) along with ApiController attribute together. Example: Having this implicit routing in Startup.cs:
app.UseMvc(routeBuilder =>
{
    routeBuilder.MapRoute("api_default", "{controller}/{action}/{id?}");
});

And this Cotroller
[ApiController]
public class ValuesController
{
    [HttpGet]
    public string Get(int id) => id.ToString();
}

Will throw this exception:

InvalidOperationException: Action
  'TestApi.Controllers.ValuesController.Get' does not have an attribute
  route. Action methods on controllers annotated with
  ApiControllerAttribute must be attribute routed.

Is there a way to avoid the exception?

A:
But, I'm interested if we can use implicit routing (and not attribute routing) along with ApiController attribute together.

According to official documentation

Attribute routing becomes a requirement. For example:
[Route("api/[controller]")]
[ApiController]
public class ValuesController

Actions are inaccessible via conventional routes defined in UseMvc or
  by UseMvcWithDefaultRoute in Startup.Configure.

Note: emphasis mine
Reference Build web APIs with ASP.NET Core: Attribute routing requirement

A: Also use the
[Route("api/VillaAPI")]
in Controller Name hard


text:
Q: Why is ReactJS returning my images as an object? I am learning Reactjs by hacking around with the tutorial. I am trying to add Image upload functionality to it but I can't quite figure it out. If I do this:
var CommentList = React.createClass({
  render: function() {
    var commentNodes = this.props.data.map(function(comment) {
        return(
          <Comment author={comment.author} key={comment.id}>
            {comment.text}

          </Comment>
        );
    });
    return (

        {commentNodes}

    );
  }
});

React returns the image as [object Object].
I think it has something to do with how ReactJS renders HTML but I cannot figure it out. The comment.image is a url path loaded from a json file. The app can be scrutinized here: https://polar-caverns-82946.herokuapp.com/ and all the code can be seen here: https://github.com/MickyCook/react-app

A: First, looking at
return(
  <Comment author={comment.author} key={comment.id}>
    {comment.text}

  </Comment>
);

You want to return components (Comment) without a closing tag.
return (

    <Comment author={comment.author} key={comment.id}/>

{comment.text}

)

you need to wrap everything in a single element, hence the extra
. You may also have to dangerously set the image src, but I'm not sure.

A: in the Comment component you have
var Comment = React.createClass({
rawMarkup: function() {
  var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
  return { __html: rawMarkup };
},

But you can not do that to convert children components to string.
you should use react-dom
var Comment = React.createClass({
rawMarkup: function() {
  var rawMarkup = marked(ReactDOM.renderToString(this.props.children), {sanitize: true});
  return { __html: rawMarkup };
},


text:
Q: Change the frame of a ViewController set in AppDelegate I am using a controller to replace the traditional UITabBarController.
The one I am using is AKTabBarController.
Now All is working, but there is one stage where I want to remove it using a Gesture.
The gesture is correct since I am removing the UINavigationBar just fine.
The only difference I can point out is that the UINavigationController is initiated within the relevant UIViewController and the TabBar is initialized in the AppDelegate.
So the problem lies here I think:
I cannot seem to manipulate the frame of the TabBarController from the ViewController.
-(void)goFull
{
    JWKAppDelegate *appdel = [[JWKAppDelegate alloc] init];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    self.webView.frame = CGRectMake(0, 0, 320, 411); // (00,00 : -20, -94)
    _navBar.frame = CGRectMake(0, 0, 320, 0);
    appdel.tabBarController.view.frame = CGRectMake(0, 0, 320, 0);

    NSLog(@"My view frame: %@", NSStringFromCGRect(appdel.tabBarController.view.frame));

    [UIView commitAnimations];
}

As you can see in the code I am initializing the App Delegate in the method and I am trying to access the tabBarController. This code provides no warnings or errors, but somehow does not work when the app is running.
I am not sure if I need to do something else, because it is a custom control. Also this control is subclassed from a UIViewController not a UITabBarController.
It is added to the project with this line in the app delegate: [_window setRootViewController:_tabBarController];
Let me know if I need to provide any more details, but I am a bit lost here.

A: You are creating the instance of AppDelegate in a wrong way , replace it with the following :-
JWKAppDelegate *appdel = (JWKAppDelegate  *)[[UIApplication sharedApplication] delegate];

Hope it will help you.

A: -(void)goFull
{

 JWKAppDelegate *appdel = (JWKAppDelegate  *)[[UIApplication sharedApplication] delegate];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];

self.webView.frame = CGRectMake(0, 0, 320, 411); // (00,00 : -20, -94)
_navBar.frame = CGRectMake(0, 0, 320, 0);
appdel.tabBarController.view.frame = CGRectMake(0, 0, 320, 0);

NSLog(@"My view frame: %@", NSStringFromCGRect(appdel.tabBarController.view.frame));

[UIView commitAnimations];
}

Try this it may help you.....


text:
Q: Get Directory Path to 12 Hive programmatically Is there any way to get the directory path of the 12 Hive programmatically?
I am creating a feature which delivers a file to the XML directory in the 12 hive, and I don't want to hardcode the directory path in my code.
Is there any Object Model property which exposes the 12 Hive directory path string as a property?

A: Why would you need to put xml files in the 12 hive? That way you are working "unsupported" Wouldn't it be easier to just deploy to the TEMPLATE\XML folder?

A: You can use the Microsoft.SharePoint.Utilities.SPUtility.GetGenericSetupPath() method. See for more information the WSS SDK: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.utilities.sputility.getgenericsetuppath.aspx

A: Have you ever seen a SharePoint installation where the 12-hive was not in the same place as usual? I don't think Microsoft even supports having it somewhere else..
Even so you can probably do a MapPath to the "/_layouts" directory to get the value.

A: 32bit vs. 64bit shouldn't matter because in either case Program Files is c:\Program Files.
What does matter is OS language which can change the literal text of c:\Program Files\Common Files.  The right way to get that directory is:
System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonProgramFiles);
Then you can use that folder and then concatenate the rest of the items...I don't think those items are language specific.

A: Just want to add that if you use MapPath() in Sharepoint, you receive a path that points to the location of the website, by default 'Inetpub', such as:
C:\Inetpub\wwwroot\wss\VirtualDirectories\12345\myFolder
The path doesn't point to the 12-hive.


text:
Q: Swift optional type issue so I'm new at swift and iOS programming. I'm trying to record the accelerometer and gyroscope date and display this on screen. With some tutorials I managed to finish my code and kind of understand the code.
But I keep getting errors. And If I follow the suggestion that xcode gives me I only get more errors..
So this is my code:
import UIKit
import CoreMotion

class ViewController: UIViewController {

    //instance variables

    var currentMaxAccelX: Double = 0.0
    var currentMaxAccelY: Double = 0.0
    var currentMaxAccelZ: Double = 0.0

    var currentMaxRotX: Double = 0.0
    var currentMaxRotY: Double = 0.0
    var currentMaxRotZ: Double = 0.0

    var motionManager = CMMotionManager()

    //outlets

    @IBOutlet var accX: UILabel?
    @IBOutlet var accY: UILabel?
    @IBOutlet var accZ: UILabel?
    @IBOutlet var maxAccX: UILabel?
    @IBOutlet var maxAccY: UILabel?
    @IBOutlet var maxAccZ: UILabel?
    @IBOutlet var rotX: UILabel?
    @IBOutlet var rotY: UILabel?
    @IBOutlet var rotZ: UILabel?
    @IBOutlet var maxRotX: UILabel?
    @IBOutlet var maxRotY: UILabel?
    @IBOutlet var maxRotZ: UILabel?

    //functions

    @IBAction func resetMaxValues() {
        currentMaxAccelX = 0
        currentMaxAccelY = 0
        currentMaxAccelZ = 0

        currentMaxRotX = 0
        currentMaxRotY = 0
        currentMaxRotZ = 0
    }

    override func viewDidLoad() {

        self.resetMaxValues()

        motionManager.accelerometerUpdateInterval = 0.2
        motionManager.gyroUpdateInterval = 0.2

        //start recording data

        motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {(accelerometerData: CMAccelerometerData!, error: NSError!) -> Void in
            self.outputAccelerometerData(accelerometerData.acceleration)
            if (error != nil) {
                print("\(error)")
            }
        })

        motionManager.startGyroUpdatesToQueue((NSOperationQueue.currentQueue()), withHandler: {(gyroData: CMGyroData!, error: NSError!) -> Void in
            self.outputRotationData(gyroData.rotationRate)
            if (error! = nil) {
                print("\(error)")
            }
        })

        super.viewDidLoad()

    }

    func outputAccelerometerData(acceleration: CMAcceleration) {

        accX?.text = "\(acceleration.x).2fg"

        if fabs(acceleration.x) > fabs(currentMaxAccelX) {
            currentMaxAccelX = acceleration.x
        }

        accY?.text = "\(acceleration.y).2fg"

        if fabs(acceleration.y) > fabs(currentMaxAccelY) {
            currentMaxAccelY = acceleration.y
        }

        accZ?.text = "\(acceleration.z).2fg"

        if fabs(acceleration.z) > fabs(currentMaxAccelZ) {
            currentMaxAccelZ = acceleration.z
        }

        maxAccX?.text = "\(currentMaxAccelX) .2f"
        maxAccY?.text = "\(currentMaxAccelY) .2f"
        maxAccZ?.text = "\(currentMaxAccelZ) .2f"

    }

    func outputRotationData(rotation: CMRotationRate) {

        rotX?.text = "\(rotation.x).2fr/s"

        if fabs(rotation.x) > fabs(currentMaxRotX) {
            currentMaxRotX = rotation.x
        }

        rotY?.text = "\(rotation.y).2fr/s"

        if fabs(rotation.y) > fabs(currentMaxRotY) {
            currentMaxRotY = rotation.y
        }

        rotZ?.text = "\(rotation.z).2fr/s"

        if fabs(rotation.z) > fabs(currentMaxRotZ) {
            currentMaxRotZ = rotation.z
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

And this is the error that I keep getting where I want to start recording data; Value of optional type 'NSOperationQueue?' not unwrapped; did you mean to use "!" or "?"?
Sorry if this is a stupid question but I really want to understand this stuff!
Thanks in advance!!

A: Since NSOperationQueue is optional, you need force unwrap it using !.
So, replace your NSOperationQueue.currentQueue() with NSOperationQueue.currentQueue()!.
You can go through this Apple Documentation and this blog for understanding Swift optionals.

A: The issue is
NSOperationQueue.currentQueue()

Returns an optional value (Refer NSOperationQueue Class Reference). But the,
startAccelerometerUpdatesToQueue:withHandler:
startGyroUpdatesToQueue: withHandler:

expects an unwrapped NSOperationQueue object (Refer : CMMotionManager Class Reference), but in your code you are passing an optional value, that's the reason why you are getting those errors.
For fixing it change those method calls to:
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: {(accelerometerData: CMAccelerometerData!, error: NSError!) -> Void in
{
})

motionManager.startGyroUpdatesToQueue((NSOperationQueue.currentQueue()!), withHandler: {(gyroData: CMGyroData!, error: NSError!) -> Void in
{
})


text:
Q: Difference between openfire users and roster Users I have gone through many documentation but still I am not able to clarify the difference between user created in openfire and that in roster. I simply need to get all user list from openfire in my android application so that I can do one to one chat with other users. Also please explain difference between Roster user and Simple user.
Any help will be appreciated.

A: You are an User when you register yourself and you'll choose user and password.
If you get as example Skype (it's not Jabber as I know), when you register yourself with an email to Skype service you'll be an User.
Roster it's the equivalent of Skype's CONTACT LIST.
In XMPP you can meet and talk with any user if they are in a groupchat, while you can chat 1-1 only with people of your Roster.
It's possible to skip the Roster by configurations, groupchat or simply developing a shared all-inclusive Roster as your needs.
In Roster you can assign a nickname to your contact (your contact it's an User) that can be different between Rosters because it's a kind of personal configuration.
Roster can handle groups (family - frinds - clan...), can handle personal users Message of the Day ("hello world") or simply status (offline - online - away - busy...).
Roster handles Presence stanzas.
I suggest to setup the chat with a standard behaviour so in future will be easy to upgrade server and client or extend functionalities.


text:
Q: iOS SpriteKit animation not working I am new to the iOS native game development. I am trying to create animation using some frames for Ideal state for the character. I am following tutorial from the Ray's Website. Look like I am doing everything fine but I can't see animation in working. Only first frame (default) is visible all the time. I debug the code & it's indeed visiting blinking player method where all 3 frames are also present, but nothing happening on screen.
It will be great if someone can guide/help me identify the issue.
@implementation GameScene
{
    NSArray *_playerBlinkFrames;
}

// Player
SKNode *_player;

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {

        [self createPlayer];
}
    return self;
}

- (void) createPlayer
{
    SKTextureAtlas *playerAnimatedAtlas = [SKTextureAtlas atlasNamed:@"Assets"];
    _player = [SKNode node];
    SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"Idle"];
    [_player addChild:sprite];

    [sprite setName:@"Ball"];

    NSMutableArray *blinkFrames = [NSMutableArray array];

    SKTexture *temp = [playerAnimatedAtlas textureNamed:@"Idle.png"];
    SKTexture *temp2 = [playerAnimatedAtlas textureNamed:@"Blink.png"];
    SKTexture *temp3 = [playerAnimatedAtlas textureNamed:@"LookRight.png"];

    [blinkFrames addObject:temp];
    [blinkFrames addObject:temp2];
    [blinkFrames addObject:temp3];

    _playerBlinkFrames = blinkFrames;
    _player.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
    [self addChild:_player];
    [self blinkingPlayer];
}

-(void)blinkingPlayer
{
    [_player runAction:[SKAction repeatActionForever:
                      [SKAction animateWithTextures:_playerBlinkFrames
                                       timePerFrame:0.3f
                                             resize:NO
                                            restore:YES]] withKey:@"blinkingInPlacePlayer"];

    return;
}

Thanks.

A: Try this:
// Player
SKSpriteNode *_player;

//..//
SKTextureAtlas *playerAnimatedAtlas = [SKTextureAtlas atlasNamed:@"Assets"];

NSMutableArray *blinkFrames = [NSMutableArray array];

SKTexture *temp = [playerAnimatedAtlas textureNamed:@"Idle.png"];
SKTexture *temp2 = [playerAnimatedAtlas textureNamed:@"Blink.png"];
SKTexture *temp3 = [playerAnimatedAtlas textureNamed:@"LookRight.png"];

[blinkFrames addObject:temp];
[blinkFrames addObject:temp2];
[blinkFrames addObject:temp3];

_playerBlinkFrames = blinkFrames;

SKTexture *tempSprite = _playerBlinkFrames[0];
_player = [SKSpriteNode spriteNodeWithTexture:tempSprite];

I've not tested it, but i think you have create a SKNode player covered by a spritenode.
let me know


text:
Q: Reverse for 'viewpost' with arguments '(1,)' not found. 1 pattern(s) tried: ['int:post\\.id$']. Why am I getting this error? I am trying to learn django and while making a viewport view, I came up with this error saying Reverse for 'viewpost' with arguments '(1,)' not found. 1 pattern(s) tried: ['int:post\\.id$'] I don't understand what is the mistake I am doing
Views.py
from django.shortcuts import render
from .models import Post

# Create your views here.
def main(request):
    return render(request, "blog/index.html", {"Posts":Post.objects.all()})

def viewpost(request):

    return render(request, "blog/viewpost.html")

urls.py
from django.urls import path, include
from . import views

urlpatterns = [
    path('',views.main, name = 'main'),
    path('viewpost/int:pk/', views.viewpost, name = 'viewpost')

]

index.html
{% extends 'blog/layout.html' %}

{% block body %}

Physics Blog

    {% for post in Posts %}
        <fieldset>

{{ post.Title }}

{{ post.Description }}

{{ post.Author }}

        </fieldset>

    {% endfor %}

{% endblock %}

viewpost.html
{% extends 'blog/layout.html' %}
{% block body %}

{{ post.Title }}

{{ post.Description }}

{{ post.Author }}

{% endblock %}

A: The problem is this line:
path('viewpost/int:pk/', views.viewpost, name = 'viewpost')

int:pk is missing the angular brackets. Change it to
path('viewpost/<int:pk>/', views.viewpost, name='viewpost')

The path() in your question doesn't seem to match 'int:post\\.id$ in the error message. So make sure you have saved the file and restarted runserver.
You'll also have to change viewpost so that it accepts the pk.
def viewpost(request, pk):


text:
Q: Given a function $f: X \to Y$, if $X$ is compact, prove the graph $g = (x, f(x))$ is compact in $X\times Y$ Given a function $f: X \to Y$, and graph of $f, g = \{(x, f(x)): x\in X\}$ in metric space $X\times Y$
(a) Suppose that $X$ is compact. Prove that $f$ is continuous if and only if $g$ is a compact subset of $X\times Y$.
I know that if $f$ is continuous, then $f(X)$ has to be compact, but $g$ is not a union of the set of $x$ and $f(x)$ so I'm not sure how to prove that $g$ is compact.
(b) If f is continuous, prove g is a closed subset of XxY.
If f is continuous I know it maps closed subsets to closed subsets, so is that why g is closed?

A: Initial observation: A function $h: X \rightarrow Y \times Z$ is continuous (in the product topology) iff its coordinates are continuous.

Note that the graph is the image of the function $Id \times f: X \rightarrow X \times Y $, which is continuous, by the initial observation. Hence, the graph is compact.
Conversely, if the graph is compact, note that $\pi_1|_{g}:X \times Y \rightarrow X$ is a continuous, bijective function. Since $X$ is a metric space, it is Hausdorff. Therefore, $\pi_1|_g$ is a homeomorphism. But its inverse is precisely $Id \times f$. By the initial observation, $f$ is continuous.

A: By Tychonoff's Theorem $X\times f(X)$ is compact. Every closed subspace of a compact space is compact. So we will show $g$ is closed in $X\times f(X)$.
Actually this is obvious. Take $(x,y)\in\overline{g}$, then there exists a sequence $(x_n,f(x_n))\in g$ such that $(x_n,f(x_n))\to (x,y)$. Then $x_n\to x$ and by continuity $f(x_n)\to f(x)=y$. So $(x,y)=(x,f(x))\in g$.

A: Try the following approach:
$g$ is compact if every sequence $(z_n) = (x_n, f(x_n))$ on $g$ has a convergent subsequence  $(z_{n_k})$  that converges in $g$.
Pick an arbitrary sequence $(z_n) = (x_n, f(x_n))$ on $g$. We know that $X$ is compact, therefore given $(x_n)$, we know there exists subsequence $(x_{n_k})$ on $X$ that converges in $X$.
We know that the image of a convergent sequence under continuous function is also convergent, hence  $(f(x_{n_k}))$ on $f(X)$ converges in $f(X)$
Thus the sequence $(z_{n_k}) = (x_{n_k}, f(x_{n_k}))$ is a convergent subsequence of $(z_{n}) = (x_{n}, f(x_{n})) $ that converges in $g$. Since  $(z_n)$ is arbitrary, therefore $g$ is compact.


text:
Q: couldn't find or load main class I placed my Java code to    the binfolder and try to run the code.   The command javac Project.java terminated successfully, but the command java Project throws the error

couldn't find or load main class Project

This is my code:
Public class project {
    public static void main(String args[]) {
    }
}

A: You've got your error because of wrong syntax. Of course, java can't find Project class, there's no such thing declared. This is a correct declaration:
  public class Project {
        public static void main(String args[]) {
         System.out.println(args[0]);
        }
    }

Note, that in Java class names start with upper-case letter, and access modifiers - with lower, like public, private, etc. I strongly suggest you to read Java Naming Conventions before writing any code.
If you're getting error like

couldn't find or load main class Project

there is a chance that the "current" directory is not in your classpath ( where java looks for .class definitions ), so you need to put in on the classpath with -cp option (as it mentioned by @Nikhil B). Note, that doing

javac -classpath "c:\java\jdk1.7.0.45"\bin" Project.java

which you posted in comments to his answer isn't correct. You should tell java interpreter where to find .class files, not java compiler (+ as I see, you've compiled your .java file just fine).
So, put the directory which contains .class file to a classpath somehow like this:
[root@crmdev clarify]# pwd //shows current directory
/home/clarify
[root@crmdev clarify]# javac Project.java //compiles .java file
[root@crmdev clarify]# ls Project.*  //here are my test files for your case
Project.class  Project.java
[root@crmdev clarify]# java -cp . Project "hello, @user5779261" //executing test code
hello, @user5779261

A: Run the java command with classpath option and it should run. (and change the class name to project from Project)
java -classpath "path to bin directory in double quotes" project


text:
Q: RXJS - Filter appears to filter, but results still show unfiltered I am using RXJS 6.3.3.
I have the following code that should filter out the gizmos that were already selected.
So if I have:
Gizmos = "Red", "Blue", "Green"

And the user selects "Blue".
I should only see "Red" and "Green" as my available options.
However I am still seeing "Red", "Blue", "Green".
In debug it appears that the filter is working it the example it will print:
Red:true Blue:false Green:true

I am not sure what I am missing because the UI still shows all 3 values.
      <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
        <mat-option *ngFor="let gizmp of filterGizmos | async" [value]="gizmo.value" (onSelectionChange)="gizmoSelectionChange(gizmo)">
          {{gizmo.value}}
        </mat-option>
      </mat-autocomplete>

   filterGizmos: Observable<Gizmo[]>;
   this.filterGizmos = this.filterGizmoData(this.searchTerm.value);

   filterGizmoData(searchString?: string): Observable<Gizmo[]> {
    let tfp = new GizmoFindParameters();

    if (searchString == undefined) {
      tfp.value = "";
    } else {
      tfp.value = searchString.trim();
    }

    return this.gizmoService.find<Gizmo[]>(tfp)
      .pipe(tap(x =>
        x.filter((y) => {
          console.log(y.value);
          console.log(!this.selectedGizmos.includes(y.value));
          return !this.selectedGizmos.includes(y.value);
        })
      )
      );
  };

A: tap does not modify the stream. It is often used for debugging and for side effects (operations that don't affect the stream).
Use map instead.
This is from the documentation for tap:

Perform a side effect for every emission on the source Observable, but
  return an Observable that is identical to the source.


text:
Q: JW Player with Youtube link don't work on IE9 Please help me!
I have code such as! This code good working on Firefox and Chrome, but when run on IE then the page is blank.

A: Tools>ActiveX Filtering (turns ActiveX filtering on/off) - Active X filtering can block Flash which uses ActiveX technology on MSIE browsers (Netscape plugin on other browsers).
Tools>Manage Addons>Show All Addons.... locate Adobe Flash in your Addons list and ensure it is enabled and you have installed both x86 and x64 versions... (if your machine cpu is x64)
File>Properties to determine which IE Security zone your site maps to (Internet Expected)...
Tools>Internet Options>Security tab, click "Reset all zones to default".... depending on the IE Security zone there are security settings in IE for scripting of ActiveX controls and Java applets.
For testing purposes make sure that your site/localhost is mapping to the Internet Zone and that you are accepting the default IE Security zone settings.
If possible include a link to your website or a mashup with your questions so that we can visit the site to investigate.
Regards.


text:
Q: Truncating a mergefield in Microsoft Word for mailmerge I'm looking to create a formula and apply to a mergefield in Word 2013. I have no access to the db and only given merge fields. My goal is truncate/shorten certain mergefields. E.g. Full Name to just initial, Age [27 years] to short age [27].
Access and excel have the formula 'left' which i've tried to use with no success. There seems to be a low more options available for numbers.
{=left({ MERGEFIELD First_Name },1)}

However this gives a syntax error. Is there a list of formulas that work for mergefield?
Outcome
'Steven' -> 'S'
'27 Years' -> '27'

A: The short answer to your question is that there is nothing in the Word field language that can reliably do string manipulation such as left(), mid() and so on. The {=} field only has numeric functions such as SUM, ABS, PRODUCT and so on. There are unreliable approaches, and in some cases they may be reliable enough for your requirement, but that really depends on how sure you can be that the data source will always contain values formatted as you expect.
As a simple example, let's take the "27 years" thing.
If every value in the relevant data source column is in the same general format, which I will describe as "something that Word recognises as an individual number, followed by an alpha string", then you can in fact use
{ SET dat { MERGEFIELD age } }{ =dat }

Notice that in that case, if you are merging to a new document, { =dat } fields will remain in the output, and updating those fields will cause errors. You can avoid that by nesting  either the { =dat } field or the all the fields in a QUOTE field:
{ QUOTE "{ SET dat { MERGEFIELD age } }{ =dat }" }

{ SET dat { MERGEFIELD age } }{ QUOTE { =dat } }

However, if your data source field could contain a value such as
4 years 2 months

then this will not work because in that case { =dat } will evaluate to 6, not 2. Word will also evaluate anything that looks like an { = } field expression, e.g. if your data source contains
SUM(23,25)

then { =dat } will evaluate to 48. There are further oddities that I will not describe now.
The simplest unreliable approach to extracting the first letter from a field is to use a large number of IF fields to test for every possible initial letter, e.g.
{ IF "{ MERGEFIELD First_Name }" = "A*" "A" }{ IF "{ MERGEFIELD First_Name }" = "B*" "B" } etc.

If you don't need to distinguish between lower and upper case you can use
{ IF "{ MERGEFIELD First_Name \*Upper }" = "A*" "A" } etc.

That's OK if you know (for example) that the names can only start with A-Z,a-z (and you could obviously test for 0-9 etc. as well. But what if it could start with any Unicode letter? Not sure that inserting thousands of IF fields is a reliable approach.
There is a similarly "unreliable" - and resource-consuming - way to use functions such as left, mid etc., as long as you are using recent versions of Windows Word (not Mac Word).
What you can do is create a completely empty Access/Jet database .mdb (let's say it is at c:\i\i.mdb, then insert a DATABASE field nested in a QUOTE field like this
{ QUOTE { DATABASE \d "c:\\i\\i.mdb" \s "SELECT left('{ MERGEFIELD First_Name }',1)" } }

Normally, a DATABASE field inserts a Word table (unless the data source has more columns than a Word table can contain), but when you only insert a single value with no headings, Word does not put the value in a cell. Unfortunately, these days Word does add a paragraph mark, but nesting the DATABASE field inside a QUOTE field appears to remove that again.
So why is that "unreliable"? Well, the main reason is if the First_Name field contains any quotation marks (certainly single-quotation marks, and OTTOMH I think double quotation marks) then the query that Word sends to Jet will look like this like this
SELECT left('a name containing a ' mark'),1)

and Jet will return a syntax error.
There are other problems with the DATABASE field approach, including

*

*Word restricts the SELECT statement to 255 characters (I think). If
your data source filed causes the SLEECT statement length to exceed
that, Jet will return an error.

*You have to put the database somewhere. If you are just using this
merge yourself, that may not be a problem, but if you have to
distribute the Word document etc. for others to use, you also have to
ensure they have the .mdb and that it's at the specified location.

*Word sometimes gets confused between a Mail Merge data source and a
data source introduced via a DATABASE field.

*Even one DATABASE field will execute a query for every record in the data source. If you use this technique in several places, a very large number of queries will be issued. That could cause problems.

As far as "single letter extraction" is concerned, there is another approach, rather similar to the DATABASE one, that uses an external .XML file and a set of INCLUDETEXT fields to specify a node in the file and return its content. But there are also similar difficulties. I may modify this Answer to describe that approach at some point, but as far as I know it has never been used in a real-world scenario.
So what if you need something more reliable? Well, there are several approaches, but all of them suffer from shortcomings of one kind or another. The main approaches I know are:

*

*use Word VBA and the OpenDataSource method to open the data source.
That allows you to specify a query in the SQL dialect understood by
the data source.

*use a Query/View defined in an intermediate database to extract the
data items you need, and use that Query/View as your data source

*Use Word VBA's MailMerge Events to manipulate the data for each
record in the data source as Word processes the mailmerge

*use a manual intermediate step

*(more drastic) ditch Word MailMerge and find another approach
altogether, e.g. create a .docx using .NET, the relevant database
provider, and the Office Open XML SDK

If you are creating this merge for use by other people, two side-effects of all those approaches is that the overall process becomes more complicated or unfamiliar for the user, and in particular, they may not be able to use Word's facilities for data source record filtering and so on. Another issue that some people encounter is that if your database contains long text fields/memo fields longer than 255 characters, they have a tendency to be truncated by Jet whenever you do something much more complicated than the default "SELECT * FROM TABLE"
(1) requires that you can write a suitable query to get the columns you need from your data source. Because the query is executed using OLE DB you don't actually need to create any permanent objects in your database. So it may be a viable approach as long as the backend database allows you to execute external queries. But Word also imposes a 255 or 511 character limit on the query, so if you have to manipulate a lot of fields or the functions you need are complicated, you may find that you exceed the character limit quite quickly.
(2) is rather similar to (1) but may allow you to specify a much more complex query. For example, if your data source is a Jet .accdb, you may be able to create your own .accdb and define a query in that that accesses the tables in the .accdb that you are not allowed to modify. You might either used "linked tables" to achieve that, or in certain cases you can specify the locations of the underlying tables/queries in the SQL.
(3) means that you use VBA to intercept Word as it processes each data source record. I leave you to research that. You have to control the process from VBA to ensure that the MailMerge events are invoked. There have been reports of various unreliabilities. VBA can only access the first 255 characters of any memo fields.
(4), e.g. you create an Excel workbook and use it to query the database. In that case you may be able to issue a much longer SQL query than you can in Word, and you may be able to create new Excel columns that manipulate the data using excel formulas. (I have never tried that, though). Then use that as your data source.
Finally, a web search should reveal a list of functions recognised by Word's "=" field, but recent Microsoft documentation tends to omit the IF() function. The ISO29500 documents on the .docx standard omit it as well, but I think that was not the intention and may be fixed in a future version of the standard. The functions are:
ABS, AND, AVERAGE, COUNT, DEFINED, FALSE, IF, INT, MIN, MAX, MOD, NOT, OR, PRODUCT, ROUND, SUM, TRUE.


text:
Q: Inno Setup show directory copy progress bar and label on PrepareToInstall page I am trying to show a progress bar and label on the PrepareToInstall page whilst copying (migrating) a previous installation to a new location. I am using a slightly modified version of Martin Prikryl's DirectoryCopy procedure and this works as expected; the files and directories are copied to the new location and the operations are logged to file.
However, whilst copying the files, which could be quite a long running operation if there are many (I tested this with 2,500 files, totalling about 1.2GB), the GUI does not update and appears to freeze, without displaying any of my custom controls (i.e. no progress bar and no progress label). I managed to force these to display by calling either Refresh or Update, but the progress bar is not animated and it appears the whole GUI is unresponsive whilst the copy operation completes. I think the fact that Inno Setup only supports single-threaded operations is maybe what is causing the GUI to freeze and not update. Is there a way to copy the files and have the GUI update at the same time?
[Code]
var
  PrepareToInstallLabel: TNewStaticText;
  PrepareToInstallProgressBar: TNewProgressBar;

//Slightly modified Public Domain code to copy a directory recursively and update PrepareToInstall label progress
//Contributed by Martin Prikryl on Stack Overflow
procedure DirCopy(strSourcePath, strDestPath: String);
var
  FindRec: TFindRec;
  strSourceFilePath, strDestFilePath: String;
begin
  if FindFirst(strSourcePath + '\*', FindRec) then
    begin
      try
        repeat
          if (FindRec.Name <> '.') and (FindRec.Name <> '..') then
            begin
              strSourceFilePath := strSourcePath + '\' + FindRec.Name;
              strDestFilePath := strDestPath + '\' + FindRec.Name;
              if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = 0 then
                begin
                  PrepareToInstallLabel.Caption := 'Copying ' + strSourceFilePath + '...';
                  if FileCopy(strSourceFilePath, strDestFilePath, False) then
                    begin
                      Log(Format('Copied %s to %s', [strSourceFilePath, strDestFilePath]));
                    end
                  else
                    begin
                      SuppressibleMsgBox(Format('Failed to copy %s to %s', [strSourceFilePath, strDestFilePath]),
                        mbError, MB_OK, IDOK);
                    end;
                end
              else
                begin
                  if CreateDir(strDestFilePath) then
                    begin
                      Log(Format('Created %s', [strDestFilePath]));
                      DirCopy(strSourceFilePath, strDestFilePath);
                    end
                  else
                    begin
                      SuppressibleMsgBox(Format('Failed to create %s', [strDestFilePath]),
                        mbError, MB_OK, IDOK);
                    end;
                end;
            end;
        until
          not FindNext(FindRec);
      finally
        FindClose(FindRec);
      end;
    end
  else
    begin
      SuppressibleMsgBox(Format('Failed to list %s', [strSourcePath]),
        mbError, MB_OK, IDOK);
    end;
end;

//Show PrepareToInstall page GUI controls
procedure ShowPrepareToInstallGuiControls();
begin
  PrepareToInstallProgressBar.Visible := True;
  PrepareToInstallLabel.Visible := True;
end;

//Update PrepareToInstall page GUI controls; note this procedure should not be needed
procedure UpdatePrepareToInstallGuiControls();
begin
//Both lines below seem to be needed to force the Cancel button to disable,
//despite already disabling the button at the beginning of the PrepareToInstall event
  WizardForm.CancelButton.Enabled := False;
  WizardForm.CancelButton.Refresh;
//Both lines below seem to be needed to force display of the progress bar and label,
//despite already showing them in the PrepareToInstall event; without them no controls are shown on the page.
  PrepareToInstallLabel.Update;
  PrepareToInstallProgressBar.Update;
end;

//Hide PrepareToInstall page GUI controls
procedure HidePrepareToInstallGuiControls();
begin
  PrepareToInstallProgressBar.Visible := False;
  PrepareToInstallLabel.Visible := False;
end;

function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
  WizardForm.CancelButton.Enabled := False;
//Migrate installation
  if IsMigration then
    begin
      ShowPrepareToInstallGuiControls;
      PrepareToInstallLabel.Caption := 'Migrating installation...';
      UpdatePrepareToInstallGuiControls;
      Log('Installation migration started.');
      ForceDirectories(ExpandConstant('{app}\FolderToMigrate'));
      DirCopy(strExistingInstallPath + '\Database', ExpandConstant('{app}\FolderToMigrate'));
      Log('Installation migration finished.');
    end;
  HidePrepareToInstallGuiControls;
end;

procedure InitializeWizard();
//Define the label for the Preparing to Install page
  PrepareToInstallLabel := TNewStaticText.Create(WizardForm);
  with PrepareToInstallLabel do
    begin
      Visible := False;
      Parent := WizardForm.PreparingPage;
      Left := WizardForm.StatusLabel.Left;
      Top := WizardForm.StatusLabel.Top;
    end;
//Define Progress Bar for the Preparing to Install Page
  PrepareToInstallProgressBar := TNewProgressBar.Create(WizardForm);
  with PrepareToInstallProgressBar do
    begin
      Visible := False;
      Parent := WizardForm.PreparingPage;
      Left := WizardForm.ProgressGauge.Left;
      Top := WizardForm.ProgressGauge.Top;
      Width := WizardForm.ProgressGauge.Width;
      Height := WizardForm.ProgressGauge.Height;
      Min := 0;
      Max := 100;
      Style := npbstMarquee;
    end;
end;

Update: I added WizardForm.Refresh; under PrepareToInstallLabel.Caption := 'Copying ' + strSourceFilePath + '...'; and this seems to force the label to update, but there is still no progress bar animation. Also, calling WizardForm.Refresh thousands of times, after each file is copied, does not seem particularly efficient.

A: The easiest solution is to pump windows message queue in the repeat...until loop.
Or you can use TOutputProgressWizardPage to present an operation progress.
I have added more details, including links to example implementations to
Inno Setup: How to modify long running script so it will not freeze GUI?


text:
Q: JQuery selector - how to compare two element IDs I have multiple input elements that are very similar in look and feel. The only difference is each input will have a different type of input code (Hotel vendor codes or Car vendor codes). Instead of duplicating autocomplete JavaScript code, I would like to re-use the same code for each input element but I need a way to identify which input is currently in focus so that the return values are the correct codes. Below is the the basic concept. How would I structure the if condition to know if my current input in focus is "vendor-car" or "vendor-hotel"?
HTML:
Hotel Vendor Codes
<input type="text" class="form-control vendor-autocomplete vendor-hotel" id="Vendor_hotel" />

Car Vendor Codes
<input type="text" class="form-control vendor-autocomplete vendor-car" id="Vendor_car" />

TypeScript:
var vendorAutocompletes = $('.vendor-autocomplete');
var vendorCar = $('.vendor-car');

if (vendorAutocompletes.length > 0) {
    vendorAutocompletes
        .autocomplete({
            source: function (request, response) {

                if ($(this).attr("id") == vendorCar.attr("id")) {
                    console.log('This input is Car Vendors');
                    getVendors(request.term, VendorTypes.Car, response);
                } else {
                    console.log('This input is Hotel Vendors');
                    getVendors(request.term, VendorTypes.Hotel, response);
                }
            }

        });
}

Trying to determine if the event associated with the current input DOM element is of type "vendor-car" or "vendor-hotel". Instead of the current element, $(this).attr("id") is undefined.
if ($(this).attr("id") == vendorCar.attr("id")) {

A: It's been a while since I don't work with jQuery, but I'll do:

const vendors = $('.vendor-autocomplete')

for (const vendor of vendors) {
  switch (vendor.attr('data-vendor')) {
  case 'hotel':
    //do stuff
    break
  case 'car':
    // do some other stuff
    break
  default:
    // just in case
    break
  }
}
Hotel Vendor Codes
<input type="text" class="form-control vendor-autocomplete" data-vendor="hotel" />

Car Vendor Codes
<input type="text" class="form-control vendor-autocomplete" data-vendor="car" />

If this is your only use case, I don't think you require the id attr for that. Just use the same class for all the inputs and store the vendor type in a custom data attr.

A: Looks like this works:
Reference: api.jquery.com/focus-selector
if (vendorCar.is(":focus"))
    console.log("Input is Car Vendors");

A: The issue is $(this) is undefined.
But using an .each() loop would provide you the element that you need.
var vendorAutocompletes = $('.vendor-autocomplete');
var vendorCar = $('.vendor-car');

if (vendorAutocompletes.length > 0) {
    vendorAutocompletes.each(function(index, element) {
        $(element).autocomplete({
            source: function (request, response) {

                if ($(element).attr("id") == vendorCar.attr("id")) {
                    console.log('This input is Car Vendors');
                    return getVendors(request.term, VendorTypes.Car, response);
                } else {
                    console.log('This input is Hotel Vendors');
                    return getVendors(request.term, VendorTypes.Hotel, response);
                }
            }

        });
    })
}

I added the possibly missing return...


text:
Q: To remove duplicate records I have a query which returns duplicate records. I need to remove all duplicates from it and store all unique records in a list.
         I'm trying to assign non duplicate records including id to tempList.
         Please suggest a method to achieve this.
Thanks.
    Map<String,temp_object__c> tempMap = new Map<String,temp_object__c>([select id,name,string,string1,string2 from temp_object__c]);
         List<temp_object__c> tempList = new List<temp_object__c>();
         for(String key: tempMap.keyset()){
         //here i need to assign to tempList
}

A: Create a Set<String> as set contains only unique values and add the field string1 into unique set and check in the loop if the value doesn't exists in the set then only add the value in the tempList
Set<String> uniqueSet = new Set<String>();
Map<String,temp_object__c> tempMap = new Map<String,temp_object__c>([select id,name,string,string1,string2 from temp_object__c]);
List<temp_object__c> tempList = new List<temp_object__c>();
for(String key: tempMap.keyset()){
   //here i need to assign to tempList
   if(!uniqueSet.contains(tempMap.get(key).string1)){
      //FIRST ADD THE STRING TO SET AND ADD IN THE LIST
      uniqueSet.add(tempMap.get(key).string1);
      tempList.add(tempMap.get(key));
   }
}


text:
Q: Copying mysql table with ENUM fields I try to copy a whole table from one mysql database to another. This almost works with
INSERT INTO `new-db`.`table`
    SELECT * FROM `old-db`.`table`;

However, ENUM fields are not correctly transferred - they are always empty.
But running
INSERT INTO `new-db`.`table` (an_enum_field)
    SELECT an_enum_field FROM `old-db`.`table`;

works correctly.
Is there anything I can do to copy ENUM fields correctly with the first statement ?

A: Column order between both tables needs to be the same.
Otherwise the magic statement with * can't correctly map the values.
Naming all columns explicitly helps out (second example from question).


text:
Q: Fatal signal 11 SIGSEGV (RxCachedTreadS) when use RxJava with api, room, retrofit In my application I use RxJava, Some API, Retrofit and Room.
My application intermittently crashes after start process, somtimes it working 10~15 minute.
But it always force finishing showing this error.
A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x20 in tid 30800 (RxComputation)
I can't find which code evoke this error.
MyActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {

       GlobalScope.launch(Dispatchers.IO) {
            while (true) {
                viewModel.gatherChangeAfterLastLogin()
                delay(10000L)
            }
        }
}

viewModel.kt
class viewModel(application: Application) : AndroidViewModel(application) {

    fun gatherChangeAfterLastLogin() {
        var a = Observable.fromIterable(someObject...)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { }

        var b = Observable.fromIterable(someObject...)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { }

        var c = Observable.fromIterable(someObject...)
                .flatMap {
                    var one = Observable.fromIterable(someObject...).onErrorReturn{ Collections.emptyList() }
                    var two = Observable.fromIterable(someObject...).onErrorReturn{ Collections.emptyList() }
                    var three = Observable.fromIterable(someObject...).onErrorReturn{ Collections.emptyList() }
                    Observable.mergeDelayError(one, two, three)
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({

                }, {

                }, {

                })
    }
}

build.gradle
implementation "io.reactivex.rxjava2:rxkotlin:2.2.0"
implementation "io.reactivex.rxjava2:rxandroid:2.1.1"
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:retrofit-converters:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

In my opinion, var c Observable is suspicious, so even if I comment out and run it, the result is the same.
And, If i change Schedulers.io() to Schedulers.computation(),
The error details are as follows
A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x20 in tid 30800 (RxComputation)
I don't know where the problem occurred because the error comes out like that


text:
Q: Regex expression for masking SSN in java 8 import java.util.*;
import java.util.regex.*;

String input = "456-67-8901";

String pattern = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$";
String result = Regex.Replace(input, pattern, "XXX-XX-$1");

showing error at Regex.Replace (Regex cannot be resolved). Am using java 8. Please help. Thanks.

A: You want something like this, to put XXX-XX- in place of the first five digits. I modified your regex a bit with two capture groups such that the first five numbers would be returned by m.group(1). You're interested in m.group(2) though. See below:
    String input = "456-67-8901";

    Pattern p = Pattern.compile("^(\\d{3}[- ]?\\d{2}[- ]?)(\\d{4})$");
    Matcher m = p.matcher(input);
    if (m.matches()) {
        System.out.println("XXX-XX-" + m.group(2));
    } else {
        // bad input
    }


text:
Q: Problems with Raspian autostart via /etc/init.d (Sorry for bad English, I'm German)
I'm trying (without success) to make my own program start automatically after booting (on a raspberry with raspian).
This is my script: (Note: You have to run this program with root privileges) (Note#2: There must be an empty file called "/home/testLog.txt" with write privileges for every user):
rm /etc/init.d/RMStart
echo "
#! /bin/sh
### BEGIN INIT INFO
# Provides:          bla1
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: bla2
# Description:       bla3
### END INIT INFO

#Switch case for the first parameter
case \"\$1\" in
    start)
        echo \"Start\" >> /home/testLog.txt
        echo runlevel >> /home/testLog.txt
        ;;

    stop)
        echo \"Stop\" >> /home/testLog.txt
        echo runlevel >> /home/testLog.txt
        ;;

    restart)
        echo \"Restart\" >> /home/testLog.txt
        echo runlevel >> /home/testLog.txt
        ;;
    *)
        echo \"something else\" >> /home/testLog.txt
        ;;
esac

exit 0
" >> /etc/init.d/RMStart
chmod +x /etc/init.d/RMStart
update-rc.d RMStart remove #Remove older versions of this program ... in theory
update-rc.d RMStart defaults #Install new version of this program ... in theory

I've rebooted the raspberry, but the file /home/testLog.txt is still empty.
However, if I run the command: "/etc/init.d/RMStart" or "/etc/init.d/RMStart start" there is a new entry in /home/testLog.txt.
I would be thankful if anyone knows why the file /home/testLog.txt is still empty and how I could fix that.
Update:
I've tried a new installation script:
#RMS install script
chmod +x botComp.sh
rm /home/pi/RMS
pkill RMS
./botComp.sh
cp RMS /home/pi
chmod +x /home/pi/RMS
rm /etc/init.d/startRMS
sudo echo "#!/bin/sh
### BEGIN INIT INFO
# Provides:          fqew
# Required-Start:
# Required-Stop:
# Default-Start:     3 4 5
# Default-Stop:      0 1 6
# Short-Description: sfwef
# Description:       gfewf
### END INIT INFO

# Actions
case \"\$1\" in
    start)
    # START
    su pi sh -c \" /home/pi/RMS \"
        ;;
    stop)
        # STOP
    ;;
    restart)
        # RESTART
        ;;
esac

exit 0 " >> /etc/init.d/startRMS

chmod +x /etc/init.d/startRMS
update-rc.d startRMS remove
update-rc.d startRMS defaults

The only difference I can see is the name of the script (/etc/init.d/startRMS instead of /etc/init.d/RMStart).
The script works, RMS is running.
It's not really a problem, but the script outputs:

insserv: script RMStart: service F already provided!
insserv: script RMStart: service F already provided!

I've added the line system("runlevel >> /home/pi/runlevelLog.txt"); In the program (RMS) but the content of /home/pi/runlevelLog.txt is: "unknown".
Does RMS start at runlevel 3? How I can I verify this? (I think runlevel 3 is ideal, because RMS needs Network Connection.) Thank you for your help.

A: is /etc/init.d/RMStart definitely being executed on reboot? use ls -lu to check the last time the file was accessed, wait a minute before rebooting, and repeat the command once you're back up. If the access time hasn't moved on then your script isn't being run which would explain the empty file as your script looks Ok.
You should also double check that update-rc.d has created symbolic links to your script in the appropriate run level directives e.g.  does /etc/rc2.d/RMStart exist?
Another sanity check would be running your script using the  symbolic links in the above directory rather than from /etc/init.d e.g. does /etc/rc2.d/RMStart
generate output in /home/testLog.txt?
Let me know what you find and we'll take it from there.
EDIT: attempting to replicate..
Well I managed to find my PI; the good news is that neither of us are going mad because it worked perfectly first time as we both believed it should.
I took a copy of your file, and I wrote a quick script (x) to check the exit codes from update-rc.d just to make 100% sure it wasn't complaining about anything.

Hopefully you can follow what I did in the screen shot above - I replicated the steps you followed almost exactly with a bit of extra checking along the way. The script certainly works as designed when called directly.
I then rebooted immediately and checked testLog.txt as soon soon as the system was up. You can see two entries in the file which is expected behaviour as init would have run /etc/rc6.d/K01RMStart as the system went down for reboot, and /etc/rc5.d/S01RMStart as it came up again.

Unfortunately this doesn't help you much.....
The only significant differnce between our tests was that I ran everything as root rather than using sudo. This shouldn't make a difference but the next logical thing for you to try is probably copying my test exactly and seeing if it works for you?
Not that this should be at all significant but I'm running Raspbian 8 (kernel 4.1.13+).
EDIT2: awesome... great stuff. I'd still like to know what the problem was but the main thing in that it's working.
System V based distributions will usually start in either level 3 or level 5, the difference being that level 5 will start the GUI whereas level 3 will start in text mode, their default runlevel is controlled by a line in /etc/inittab.
Debian(Raspian) distros are a bit different - (https://www.debian.org/doc/debian-policy/ch-opersys.html#s-sysvinit). They make no distinction between run levels 2-5 and leave it up the user to configure them to suit their requirements by adding services using the mechanism that's been causing us pain for the last 24 hours. They always start in level 5 unless a "init=" kernel boot parameter has been set, which you can do either at boot time or with a tool like bum or raspi-config.
The command runlevel will tell you the current level on raspian.
You can change the runlevel on the fly with telinit new_runlevel if you need to, but whatever you do, don't set the default runlevel to 0 :-)


text:
Q: Magento Customer Wizard Registration I'm trying to create a simple registration for the magento visitors using custom steps. I need to create a wizard that helps the users to follow a path previously set in the administration panel.
At the moment I have created the extension but I am having some difficulties to create the front-end wizard form. What I'd like to achieve is a multi registration form where if the user go from the first form to the second one Magento has to save the data and wait if the user wants to go on the next new form and so on...
Here a mockup: http://minus.com/lF3krBVJG0WEM
How have I to create a multiform that follow this behaviour?
Regards


text:
Q: Open modal dialog box after saving list item data in a edit form I need to open a modal dialog pop up box when i click a button on the edit form but at the same time i need to save the data on the edit form.
Example:
I have a SPList say Report.
In the edit form of this List, I have a button, the onclick function of this button opens a modal dialog pop up, i need to save the list item before (or) during the time when modal dialog pop up opens up.

A: Yes it is possible. But when you save the form, page will postback and reload, meaning your pop up will go away.
Every asp button in sharepoint has a "hook" for javascript interception.
It is called "PreSaveItem()"
Just open your pop-up in that method and return true.
If you want to submit your form, you'll have to do it via javascript etc, to keep the page from reloading, and keeping your popup window open.

A: for opening a modal dialogue box you can make use of dialog widget from jQuery UI library.
I am sure there are multiple other samples in the internet in case you do not want to use jquery,


text:
Q: How do I resolve: TypeError: int() takes exactly 5 arguments (4 given) I am editing a part of conversation.py which is a part Jasper voice recognition software to add sound effects. The part of the code I am concerned with is init(). I am using code and trying to replicate self.speaker = speaker from mic.py
ORIGINAL CODE:
# -*- coding: utf-8-*-
import logging
from notifier import Notifier
from brain import Brain

class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")

EDITED CODE:
# -*- coding: utf-8-*-
import logging
from notifier import Notifier
from brain import Brain

class Conversation(object):

    def __init__(self, speaker, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.speaker = speaker  #ADDED LINE
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.speaker.play(jasperpath.data('audio', 'SpeechMis.wav')) #ADDED LINE
                self.mic.say("Pardon?")

When I run the Jasper software that includes this modified code I get the following error:
Traceback (most recent call last):
  File "/home/pi/jasper/jasper.py", line 151, in <module>
    app.run()
  File "/home/pi/jasper/jasper.py", line 120, in run
    conversation = Conversation("JASPER", self.mic, self.config)
TypeError: int() takes exactly 5 arguments (4 given)

I have looked at other TypeError questions and have read the code carefully. I still don't know what I'm doing wrong.

A: class Conversation(object):
    def __init__(self, speaker, persona, mic, profile):

...

conversation = Conversation("JASPER", self.mic, self.config)

You modified Conversation.__init__ signature and now it expects 4 arguments (speaker, persona, mic, profile), yet the calling code still provides values for only the first 3.
In order to modify the class while not breaking existing code, add the new argument to the end and use default value:
class Conversation(object):
    def __init__(self, persona, mic, profile, speaker=None):


text:
Q: Is it Possible To Use Both a Local NuGet Repository and Remote Repository I've been converting our library projects to NuGet packages and hosting them on an internal NuGet Feed.  This is working great and has cut down on developers re-creating helper classes and "reinventing the wheel".  Another huge plus is that other teams now can consume "released" libraries from our projects.  Basically it's been a huge win so far.
The only problem we're facing is local builds.  What we would like to do is is test libraries in our consuming projects before pushing a build to the NuGet feed.  We're running into a problem because the projects that are consuming these libraries are setup to use the local feed (package restore on the build server allows our main trunk to build with the latest "released" libraries).
Is there a way to have local builds pick up from a local repository?  I've begun working on an after build task for the libraries that creates local package files.  Using the NuGet.config I think I should be able to mask certain repositories and then mask the config files on the build server.  My theory is that when using a local build the local repository should be picked up and on the build server the feed would be used.
Is this possible?  Is there anyone else that has documented how to do this?
Here is the after build task I'm using for creating the local packages:
  <PropertyGroup>
    <PackOutputDir>$([System.IO.Path]::Combine($(SolutionDir), "..\Prerelease"))</PackOutputDir>
    <BuildSpecCommand>$(NuGetCommand) spec $(ProjectFileName) -force -NonInteractive -Verbosity detailed</BuildSpecCommand>
    <PackCommand>$(NuGetCommand) pack $(ProjectFileName) -OutputDirectory "$(PackOutputDir)"</PackCommand>
  </PropertyGroup>
  <Target Name="AfterBuild" Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <Exec Command="$(BuildSpecCommand)" LogStandardErrorAsError="true" Condition=" '$(OS)' == 'Windows_NT' " />
    <Exec Command="$(PackCommand)" LogStandardErrorAsError="true" Condition=" '$(OS)' == 'Windows_NT' " />
  </Target>

I placed this NuGet.config at the root of our team project.  This file is cloaked on the build server:
<configuration>
  <packageSources>
    <add key="NuGet official package source" value="https://nuget.org/api/v2/" />
    <add key="TestSource" value="Source\Prerelease" />
  </packageSources>
  <disabledPackageSources>
    <add key="LocalNuGetFeed" value="LocalNuGetFeed" />
  </disabledPackageSources>
  <activePackageSource>
    <add key="All" value="(Aggregate source)"  />
  </activePackageSource>
</configuration>

Here's the NuGet.config that I placed in a folder that should get picked up in the hierarchy on the build server:
<configuration>
  <packageSources>
    <add key="NuGet official package source" value="https://nuget.org/api/v2/" />
    <add key="LocalNuGetFeed" value="http://team2:12345/nuget" />
  </packageSources>
  <disabledPackageSources>
  </disabledPackageSources>
  <activePackageSource>
    <add key="All" value="(Aggregate source)"  />
  </activePackageSource>
</configuration>

Update
Based on a provided answer I changed the nuget.targets file.  Ideally I would not like to do this but if this is the best way to achieve what I'd like to accomplish then I am fine with this type of edit.
  <ItemGroup Condition=" '$(PackageSources)' == '' And '$Configuration' == 'Release'">
    <PackageSource Include="https://nuget.org/api/v2/" />
    <PackageSource Include="http://team2:12345/nuget/" />
  </ItemGroup>
  <ItemGroup Condition=" '$(PackageSources)' == '' And '$Configuration' != 'Release'">
    <PackageSource Include="https://nuget.org/api/v2/" />
    <PackageSource Include="C:\temp\NuGet\Prerelease" />
  </ItemGroup>

The idea here is to use the build task posted earlier for the library projects so that their packages are output to a temporary folder on disk.  The code immediately above should be in the nuget.targets file for those projects which we will be needing to have any changes to the library update immediately while developers do work on their local machines, however the build server will only talk to our local feed during the team build process.
Is this correct?
Another idea...
After discussing this with a co-worker we came up with another solution which may be more effective in practice.  We decided to model it on the AvalonDock project.  When you download sources and open the solution for that project you not only see the code to build the UI controls, but you also see an example project that uses all of the features of said controls.
His idea was that in our library projects where the code is just C# libraries that unit testing should be effective enough to cover any issues.  Also the builds that push these libraries are gated, meaning that only apply the checkins if the build (and tests) complete.
For the UI controls he pointed to the above example for AvalonDock.  Including a project that utilized all the controls should mitigate most issues.  Since unit testing on UI controls is limited it would still put the onus on the developer to check the controls within the test project before committing the code and starting the build process.
What is a general opinion of this approach?

A: You can definitely use multiple repositories at once. The important part here is that you need to define the order in which you want them to be used. When restoring/installing a package, NuGet will first look on the first repository, if not found it will scan the second repository, and so on.
If you need the local repository to get priority over the "released" repository, you'll need to ensure the local repository is the first one in the list.
Your approach looks OK on first sight, although you could also go for an MSBuild solution (without these config modifications) using the .nuget\NuGet.targets file that comes with NuGet package restore.
Define your feeds by adding them in the <PackageSources> element, and then (maybe based on Build configuration Debug | Release) you can switch the repo to be used in the <RestoreCommand>.


text:
Q: asp.net how to get image url file name If the user provides the url path to the image, i want to be able to try and download it with with a Webclient. I am using a httpresponse to check the file. Is there a way to grab the file name to make it easier to save? Thanks

A: Try using the Uri Class to load the path and pull the file name from the Segments collection:
Uri uri = new Uri("http://www.domain.com/image.jpg");
string fileName = uri.Segments.Last();

A: I would look into using System.IO.Path.GetFileName for this:
string fileName = Path.GetFileName("http://www.abc.com/myimage.jpg");


text:
Q: Linux: how do I tar to a specific location? I am currently backing up my system.  If I use
> tar cvpzf backup.tgz --exclude=/proc --exclude=/lost+found--exclude=/backup.tgz --exclude=/mnt --exclude=/sys /

It says the system doesn't have enought space.
Right now, I have mount a usb in directory
~/mnt/sdc1

How do I tar the backup.tgz to this specific location?

A: You will want to do two things. First insure that your drive is mounted, Then just provide the complete path to your backup location. E.g.
mount | grep -q ~/mnt/sdc1       # or just grep -q sdc1 (if it is the only sdc1)
if [ $? -eq 0 ]; then
    tar cvpzf ~/mnt/sdc1/backup.tgz ...
fi

note: the replace the ellipses with the rest of your tar command.