text:
Q: How to pass an object with an unknown type to a Class with an unknown type I am currently working on a homework assignment for a Java programming course I am taking.  I am not asking for an exact answer, but for some guidance.
The problem I'm working on is this:
I have a filter class that implements a Filter interface.  This interface has just one method - matches(T element)
I have configured my filter method to check an Integer that is being passed in for prime-ness.
There is also a decorator class that decorates a collection class to only display objects that pass the filter.
I'm having problems getting the contains(Object o) method to work correctly.
Basically the contains(Obj o) method in the  FilteredCollection class should first check to see if the object passes the filter, and then if it does, call the undecorated contains() method on that object.
Assuming I want to be able to use this FilteredCollection class with many different types of filters, How can I determine what type of object is being passed in, and then be able to pass that object to the current Filter that's being implemented.
Here is my PrimeNumberFilter Class:
public class PrimeNumberFilter implements Filter<Integer> {

public boolean matches(Integer e) {
    int n = e.intValue();
    if (n != 2 && n % 2 == 0) {
        return false;
    }

    for (int i = 3; i * i <= n; i += 2) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

}

Then here is my shortened FilteredCollection Class:
class FilteredCollection<T> implements Collection<T> {

Collection<T> fc;
Filter<T> currentFilter;

private FilteredCollection(Collection<T> coll, Filter<T> filter) {

    this.fc = coll;
    this.currentFilter = filter;

}

public static <T> FilteredCollection<T> decorate(Collection<T> coll,
    Filter<T> filter) {

    return new FilteredCollection<T>(coll, filter);
}

public boolean contains(Object o) {

    //What do I do here?
    return fc.contains(o);
}

The object being passed in to the contains method has to pass the filter, in this case a PrimeNumberFilter.
The error I'm getting is it keeps wanting to cast the object to type T, and I know that this will never work because of erasure.
I've done a ton of research, and I've boiled it down to needing to use reflection.
The only hint my instructor will give me is that object only has a few methods I can use, and I should use one of those.
Thanks for your help!
EDIT:  One of the requirements of the project is to NOT cast an object to T in any method.  So while these answers are great, I am not able to use any of them.

A: There is nothing wrong with your code.
The problem is due to the java.util.Collection.contains(Object o) interface method not being generically typed. This is outside of your control.
Option 1: Simple approach
In your implementation of that method you can cast:
public boolean contains(Object o) {
    return o != null && currentFilter.matches((T)o) && fc.contains(o);
}

Option 2: Add a getParameterType() method to the Filter interface
This method would return the generic type of the filter as implemented in the various subclasses.
interface Filter<T> {
    boolean matches(T parameter);
    Class<T> getParameterType();
}

Then...
public boolean contains(Object o) {
    return o != null && currentFilter.getParameterType().isAssignableFrom(o.getClass()) && currentFilter.matches((T)o) && fc.contains(o);
}

Option 3: Determine generic type via reflection
Technically the generic type of your filter will not actually be erased at runtime. Type erasure does not apply here because PrimeNumberFilter is an actual class which implements a generically typed interface.
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
    Class<?> genericTypeOfFilter = getGenericTypeOfFilter(currentFilter);
    return o != null && genericTypeOfFilter.isAssignableFrom(o.getClass()) && currentFilter.matches((T)o) && fc.contains(o);
}

static <T> Class<T> getGenericTypeOfFilter(Filter<T> filter) {
    try {
        @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
        Class<T> type = (Class<T>) ((ParameterizedType)filter.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0];
        return type;
    }
   catch (Exception e) {
        throw new IllegalStateException("Unexpectedly failed to read generic type of filter: " + filter, e);
    }
}

If it was my code I'd go with Option 2 in this case, it is more robust than relying on reflection.

A: The method to use is Object.equals(Object). You can iterate the collection fc and check if it contains an element wich equals(o). If so, continue on with said element (which is of type T).
for(T e : fc) {
    if(o.equals(e)) {
        // carry on with e
    }
}

You might also want to cover o == null.

A: The type cast to T will work, you just need to be careful to catch ClassCastExceptions because you can't check the type prior to the cast due to erasure.
This will leave you with something like:
public boolean contains(Object other)
{
  try
  {
    return currentFilter.matches((T)other) && fc.contains(other);
  }
  catch (ClassCastException e)
  {
    //Add some logging.
    return false;
  }
}

Using exceptions in this way is generally frowned upon, but in this instance, you don't have much choice.

A: Since the contains method makes use of .equals, and .equals is qn overridden version of the one in Object, I would think about making a new Collection with the Object parameter type, so for example ArrayList then use it's addAll method to add everything from your T type collection - this will work because all classes inherit from Object. Then when it uses the equals method, it will still be the one from class T (assuming T has overridden it). It's not perhaps the perfect approach, but I think it is simpler and neater than trying to check if the Object can be cast to T.
public boolean contains(Object o) {

    Collection<Object> temp = new ArrayList<Object>();
    temp.addAll(fc);
    return temp.contains(o);
}


text:
Q: Do I need to repost the question if I don't get the answer?
Possible Duplicate:
How do I get attention for my old, unanswered questions?

I posted a question on Stack Exchange but I did not get answer even after a day. What am I supposed to do? Do I need to repost the question? Or shall I post new question by linking to the old question?

A: Don't repost...ever!
A day is not a very long time to pass. You might instead want to have a good look at your question. Is it clearly phrased? Can it be answered with the information there? Etc. Added bonus is that, should you update/improve it, it will be bumped up again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: U-Boot: how to load U-Boot from SD card, but have it load its Environment from QSPI Flash? I'm having some difficulty configuring U-Boot, in particular setting it up so that it can load from an SD card, but access its Environment from QSPI Flash.
First of all, is this even possible? Can the U-Boot environment be stored in a different location from where U-Boot was loaded?
Currently, I have a U-Boot image running from QSPI Flash on a Xilinx MPSoC ARM64 platform. I'm using Xilinx
PetaLinux however I think I understand how this configures U-Boot "under the hood" so I'll try to refer to
uboot.cfg as much as I can.
Along with all the defaults, I have set:
#define CONFIG_ENV_OFFSET 0x2E00000
#define CONFIG_ENV_OVERWRITE 1
#define CONFIG_CMD_ERASEENV 1

On this particular platform, there is a physical switch to switch the Xilinx first-stage bootloader (and ARM
Trusted Firmware) between QSPI Flash and SD card modes. This platform also requires a so-called "BOOT.BIN", which
is an aggregation of the u-boot binary, the Xilinx FSBL, ARM Trusted Firmware, an FPGA image and
other things, to be written to QSPI Flash, which I have done. This is all working correctly, and the serial console
looks like this at reset or power-on:
Xilinx Zynq MP First Stage Boot Loader
Release 2021.2   Oct 13 2021  -  07:15:53
NOTICE:  BL31: v2.4(release):xlnx_rebase_v2.4_2021.1_update1-23-g9188496b9
NOTICE:  BL31: Built : 07:41:24, Oct 13 2021

U-Boot 2021.01 (Oct 12 2021 - 09:28:42 +0000)

CPU:   ZynqMP
Silicon: v3
Model: ZynqMP ZCU208 RevA
Board: Xilinx ZynqMP
DRAM:  4 GiB
PMUFW:  v1.1
EL Level:       EL2
Chip ID:        zu48dr
NAND:  0 MiB
MMC:   mmc@ff170000: 0
Loading Environment from SPIFlash... SF: Detected mt25qu02g with page size 512 Bytes, erase size 128 KiB, total 512 MiB
...

As you can see, U-Boot loads from QSPI Flash and the Environment is also loaded from QSPI Flash. All good.
What I want to do is modify the system so that the First Stage Boot Loader loads U-Boot from the SD card. In my config I
already have CONFIG_ENV_IS_IN_FAT set to 1. When I copy BOOT.BIN to the first, FAT partition on an SD card, and set my
platform's boot mode to "SD Card" via the physical switch, the unit loads U-Boot from the SD card successfully, and the
serial console shows output similar to the above but with:
Loading Environment from FAT... *** Warning - bad CRC, using default environment

It works, although this warning is expected because there is no Environment saved on the SD card yet.
It does show that the SD card is being checked for the Environment though, so that's good.
Note that this is the same build that I used for the QSPI flash boot earlier, but it's looking for the config on FAT, so I'm currently under the impression that
U-Boot only looks for its Environment based on where it was loaded from, even if other locations are enabled. I also tried in QEMU and it seemed to think that the config came from "nowhere", but that may be a distraction.

The issue is that I would like to configure U-Boot to be loaded from the SD card (for ease of upgrade / development), but to use QSPI for its Environment,
so that I can store persistent U-Boot configuration on the board itself.
In particular, the MAC address for the board is not readable via software so must be manually configured in U-Boot, and I'd like that to follow around the board, not the SD card. There are a few other options I'd like to set per-board also.
According to the U-Boot documentation I've read, disabling FAT as the default should be achievable by unsetting the
following in u-boot.cfg:
CONFIG_ENV_IS_IN_FAT
CONFIG_SYS_MMC_ENV_DEV
CONFIG_ENV_FAT_DEVICE_AND_PART
CONFIG_ENV_IS_IN_FAT
CONFIG_ENV_FAT_FILE
CONFIG_SYS_MMC_ENV_PART
CONFIG_ENV_FAT_INTERFACE

Performing the same installation steps as above, to have this new U-Boot loaded from the SD card, results in the
following output:
Xilinx Zynq MP First Stage Boot Loader
Release 2021.2   Oct 13 2021  -  07:15:53
NOTICE:  BL31: v2.4(release):xlnx_rebase_v2.4_2021.1_update1-23-g9188496b9
NOTICE:  BL31: Built : 07:41:24, Oct 13 2021

And that's it! No more output. There is an LED on the board that goes from red to green, which I think indicates that
the FPGA image within BOOT.BIN has been loaded into the gate array successfully, so I think the earlier boot loader
has found BOOT.BIN. I have no reason therefore to think that U-Boot has not also been loaded, but if it has, it is
generating no output. I tried increasing the debug level of U-Boot to 7 (DEBUG) in the hope of seeing something
from U-Boot, but that makes no difference. It's also not booting Linux, which would normally happen next.
Can anyone shed any light on why making this change might result in this behaviour? Is there some other
configuration option I need to set to ensure that U-Boot can run from the SD card when CONFIG_ENV_IS_IN_FAT
and friends are not set? Or perhaps I can keep CONFIG_ENV_IS_IN_FAT etc. and there's some other way to instruct
U-Boot to use the QSPI Flash for its environment, even though it was loaded from SD card?
Note: I've also enabled ATF debugging, which produces the following output, but it still hangs with no sign of U-Boot:
INFO:    PSCI Power Domain Map:
INFO:      Domain Node : Level 1, parent_node -1, State ON (0x0)
INFO:      Domain Node : Level 0, parent_node 0, State ON (0x0)
INFO:      Domain Node : Level 0, parent_node 0, State ON (0x0)
INFO:      Domain Node : Level 0, parent_node 0, State ON (0x0)
INFO:      CPU Node : MPID 0x0, parent_node 0, State ON (0x0)
INFO:      CPU Node : MPID 0x1, parent_node 0, State ON (0x0)
INFO:      CPU Node : MPID 0x2, parent_node 0, State ON (0x0)
INFO:      CPU Node : MPID 0x3, parent_node 0, State ON (0x0)
Xilinx Zynq MP First Stage Boot Loader
Release 2021.2   Oct 13 2021  -  07:15:53
WARNING: BL31: invalid exception level (3)
NOTICE:  BL31: v2.4(debug):xlnx_rebase_v2.4_2021.1_update1-23-g9188496b9
NOTICE:  BL31: Built : 07:41:24, Oct 13 2021
INFO:    ARM GICv2 driver initialized
INFO:    BL31: Initializing runtime services
INFO:    BL31: PM Service Init Complete: API v1.1
INFO:    BL31: cortex_a53: CPU workaround for 855873 was applied
WARNING: BL31: cortex_a53: CPU workaround for 1530924 was missing!
INFO:    BL31: Preparing for EL3 exit to normal world
INFO:    Entry point address = 0x8000000
INFO:    SPSR = 0x3c9

A: Answering my own question:
I do not know why the console remains blank/dead in this case, but the related code is this function here:
https://github.com/u-boot/u-boot/blob/master/board/xilinx/zynqmp/zynqmp.c#L850
According to this switch statement, when the boot mode is SD_MODE, the case does not consider CONFIG_ENV_IS_IN_SPI_FLASH at all, and therefore the function returns ENVL_NOWHERE when booted from SD with CONFIG_ENV_IS_IN_FAT disabled.
Modifying this function to return ENVL_SPI_FLASH in this case enables U-Boot access to the Environment in the QSPI Flash:
    case SD_MODE1:
        if (IS_ENABLED(CONFIG_ENV_IS_IN_FAT))
            return ENVL_FAT;
        if (IS_ENABLED(CONFIG_ENV_IS_IN_EXT4))
            return ENVL_EXT4;
++      if (IS_ENABLED(CONFIG_ENV_IS_IN_SPI_FLASH))
++          return ENVL_SPI_FLASH;
        return ENVL_NOWHERE;


text:
Q: Swift function not drawing circle in updated view I have a stepper in my View Controller that updates variables(redd1,  greenn1, bluee1) in my UIView. drawRect draws an initial circle and updateColor is meant to draw a new circle on top of it with an updated color.  The variables get updated when I call updateColor and I know that they get passed through because when i have their values printed out in updateColor they are correct. updateColor won't draw a new circle.
class UIView1: UIView {

    var redd1 = 0.0;
    var greenn1 = 0.0;
    var bluee1 = 0.0;

    override init(frame: CGRect)
    {
        super.init(frame: frame)
    }
    required init?(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }

    override func drawRect(rect: CGRect)
    {
        let circle2 = UIView(frame: CGRect(x: -25.0, y: 10.0, width: 100.0, height:100.0))
        circle2.layer.cornerRadius = 50.0
        let startingColor2 = UIColor(red: (CGFloat(redd1))/255, green: (CGFloat (greenn1))/255, blue: (CGFloat(bluee1))/255, alpha: 1.0)
        circle2.backgroundColor = startingColor2;
        addSubview(circle2);
    }

    func updateColor()
    {
        let circle = UIView(frame: CGRect(x: -25.0, y: 10.0, width: 100.0, height: 100.0))
        circle.layer.cornerRadius = 50.0;
        let startingColor = UIColor(red: (CGFloat(redd1))/255, green: (CGFloat(greenn1))/255, blue: (CGFloat(bluee1))/255, alpha: 1.0)
        circle.backgroundColor = startingColor;
        addSubview(circle);
    }
}

A: Do not call addSubview in drawRect. Only use drawRect if you were going to draw a circle yourself (e.g. by calling stroke of a UIBezierPath). Or if you're going to add circles as subviews (as CAShapeLayer sublayers to the view's layer), the retire drawRect altogether.
But by calling addSubview in updateColor, you're not changing the color, but rather you're adding another subview every time. Likewise, by calling addSubview in drawRect, you're adding another subview there, too, every time the OS calls drawRect. For example, I ran your code, changing the color from black to red, to green, to blue, and triggered drawRect to be called again a few more times, and when I look at the view hierarchy in the view debugger, you can see all of the views in the view hierarchy:

This is a dangerous practice, because those subviews will add up over time, taking up memory.
If you're going to add subviews, I would suggest (a) drawRect is not the right place to be adding subviews; and (b) if you're determined to go the addSubview approach, decide whether you can remove the previous subviews before adding new ones.
Personally, if I wanted drawRect to draw circles of different colors, I would just stroke the UIBezierPath. For example:
class CircleView: UIView {

    var redd1: CGFloat = 0.0 {
        didSet {
            setNeedsDisplay()
        }
    }

    var greenn1 : CGFloat = 0.0 {
        didSet {
            setNeedsDisplay()
        }
    }

    var bluee1: CGFloat = 0.0 {
        didSet {
            setNeedsDisplay()
        }
    }

    override func drawRect(rect: CGRect) {
        let color = UIColor(red: redd1 / 255.0, green: greenn1 / 255.0, blue: bluee1 / 255.0, alpha: 1.0)
        color.setStroke()

        let path = UIBezierPath(arcCenter: CGPoint(x: 75, y: 75), radius: 50, startAngle: 0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
        path.lineWidth = 2
        path.lineCapStyle = .Round

        path.stroke()
    }

}

By the way, you notice that we can retire updateColor entirely. With the above code, if you set either red, green, or blue, it will call setNeedsDisplay, which will trigger the view being redrawn automatically.

You report that the above isn't working. Well, I tried it with this code:
class ViewController: UIViewController {
    @IBOutlet weak var circleView: CircleView!
    @IBOutlet weak var redSlider: UISlider!
    @IBOutlet weak var greenSlider: UISlider!
    @IBOutlet weak var blueSlider: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()

        redSlider.value = Float(circleView.redd1) / 255.0
        greenSlider.value = Float(circleView.greenn1) / 255.0
        blueSlider.value = Float(circleView.bluee1) / 255.0
    }

    @IBAction func valueChangedForSlider(sender: UISlider) {
        circleView.redd1 = 255.0 * CGFloat(redSlider.value)
        circleView.greenn1 = 255.0 * CGFloat(greenSlider.value)
        circleView.bluee1 = 255.0 * CGFloat(blueSlider.value)
    }
}

And it worked fine:

A: As you mentioned that the both have the values which they should have.
The two circles which you are drawing are exactly on the same postion and both have exactly the same color according to your code snippet. How should they differ? Of course you can't see the two circles when they are having the same color and same position. They are overlayed.


text:
Q: visibility of objects in multi-dimensional space based on a specific perspective I'm working on a data mining algorithm that considers features in their n-dimensional feature-space and allows surrounding training examples to block the 'visibility' of other training examples effectively taking them out of the effective training set for this particular query.
I've been trying to find an efficient way to determine which points are 'visible' to the query.  I though the realm of computer graphics might offer some insight but there is a lot of information to peruse and much of it either can't be generalized to multiple dimensions or is only efficient when the number of dimensions is low.
I was hoping I could get some pointers from those of you who are more intimately knowledgeable in the domain.

A: The solution I found is to convert the euclidean coordinates into 'hyper-spherical' coordinates.  Its similar to the spherical coordinate system except you add an additional angle with a range [0, pi) for each additional dimension beyond three.
After that I can sort the list of points based on their distance from the origin and iterate through comparing each point in the list to the first item looking for angles that overlap.  after each iteration you remove the first item in the list and any items that were discovered to have been blocked.  then start over with the new first item (closest item).
Don't know if anyone will ever find this useful but I thought I should put the answer up anyways.


text:
Q: Localhost on Windows 7 I want to enable a localhost on Windows 7 to be able to build websites with Chrome without a distant server. I would like to not install anything, and be able to, for example, navigate to http://localhost/something/somethingElse/index.html.
Anyone knows how?

A: There is a simple chrome extension "200 OK". Which runs a web server on localhost.

*

*Custom port settings

*Choose your project folder and start the server

A: In order to activate localhost server on Windows 7 navigate to:
-> Control Panel -> Programs and Features -> Turn Windows features on or off

Then search for Internet Information Services and check its checkbox.
Wait for Windows to make the changes, no need for immediate restart, the server will be enabled.
You can now navigate to
127.0.0.1

or
http://localhost


text:
Q: GWT request factory - how to get locator working I have a working "request factory" example and i want to refactor it, so that i can move the generic methods like "persist()" and "remove()" out of the domain object into a generic locator. Currently i have the following (working) code:
A generic super class that holds the id and the version for all domain objects:
@MappedSuperclass
public class EntityBase {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Version
    @Column(name = "version")
    private Integer version;

    // setter & getter

}

A domain object. It has the persist() and remove()-methods, which i want to refactore out of the class:
@Entity
@Table(name = "article")
public class Article extends EntityBase{

    public static Article findArticle(Long id) {
        //find article
    }

    public void persist() {
        // persist
    }

    public void remove() {
        // remove
    }

}

A proxy object for the domain object:
@ProxyFor(value = Article.class)
public interface ArticleProxy extends EntityProxy {

    // some getter and setters

}

The request object for my domain object:
@Service(value = Article.class)
public interface ArticleRequest extends RequestContext {

    Request<ArticleProxy> findArticle(Long id);

    InstanceRequest<ArticleProxy, Void> persist();

    InstanceRequest<ArticleProxy, Void> remove();
}

My request factory:
public interface MyRequestFactory extends RequestFactory {

  ArticleRequest articleRequest();

}

---------------------------------------
Now my refactored code that is not working anymore:
I removed the persist() and remove()-method out of my domain object:
@Entity
@Table(name = "article")
public class Article extends EntityBase{

    public static Article findArticle(Long id) {
        //find article
    }

}

I created my locator like this and added the methods "remove()" and "persist()" here (alongside the other default methods):
public class EntityLocator extends Locator<EntityBase, Long> {

    @Override
    public EntityBase create(Class<? extends EntityBase> clazz) {
        try {
            return clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public EntityBase find(Class<? extends EntityBase> clazz, Long id) {
        return null;
    }

    @Override
    public Class<EntityBase> getDomainType() {
        return null;
    }

    @Override
    public Long getId(EntityBase domainObject) {
        return null;
    }

    @Override
    public Class<Long> getIdType() {
        return null;
    }

    @Override
    public Object getVersion(EntityBase domainObject) {
        return null;
    }

    public void persist(EntityBase domainObject){
        // persist something
    }

    public void remove(EntityBase domainObject){
        // remove
    }

}

My proxy object is linked to the locator (locator=EntityLocator.class):
@ProxyFor(value = Article.class, locator=EntityLocator.class)
public interface ArticleProxy extends EntityProxy {

    // getter and setters here

}

My new Request object looks like this. I made the "InstanceRequests" to "Requests", changed return types and parameter according to my new methods in the locator:
@Service(value = Article.class)
public interface ArticleRequest extends RequestContext {

    Request<ArticleProxy> findArticle(Long id);

    Request<Void> persist(ArticleProxy article);

    Request<Void> remove(ArticleProxy article);

}

But now i get the error "Could not find domain method similar to java.lang.Void persist()" for the persist() and remove()-method. Why doesn't the lookup in the EntityLocator work? Do i need a ServiceLocator? I did not fully understand the google tutorial and the linked example is not available anymore.

A: I had the same question as you. The guide on GWTProject.org (http://www.gwtproject.org/doc/latest/DevGuideRequestFactory.html) is not very clear on how to correctly implement this, although it is written between the lines.
The following tutorial made the solution clear to me: http://cleancodematters.com/2011/06/04/tutorial-gwt-request-factory-part-i/
For me the use of the term DAO obfuscated things. I'm not going to use the DAO pattern. That's what my transparent persistence layer is for. However, the use of the Locator requires an extra class to put the persist, remove and findX methods in. They call it a Data Access Object (which it is, actually), I'd rather call it the Manager.
tl;dr
The methods you're trying to put in the Locator don't go there. You need an extra class (call it a DAO or a Manager).
Use the DAO/Manager as service in your RequestContext

A: I don't think you can place the persist and remove methods in the locator. The documentation doesn't suggest you can add arbitrary methods to the locator interface and reference them from the client. If you just want to avoid duplicating the persist and remove methods in every entity class then you can put them in your EntityBase class. I've done this and it works nicely.
If you also want to avoid repeating the functions in each of your request interfaces, you can make a generic base class Request like so:
@SkipInterfaceValidation
public interface BaseEntityRequest<P extends EntityProxy> extends RequestContext {
    InstanceRequest<P, Void> persist();
    InstanceRequest<P, Void> remove();
}

and use it like so:
public interface ArticleRequest extends BaseEntityRequest<ArticleRequest> {
    ...
}

A: Although it makes sense that persist() and remove() were in the Locator, so as the entity was completely agnostic about the persistence layer, this is not supported by current RF api. As consequence you have to deal with that adding those methods to your BaseEntity and figuring out a way to call the persist method in your locator.
I think you could open a gwt issue requiring this feature though.
Another way to avoid having certain methods in your entities, is to use ValueProxy insteadof EntityProxy, but in this case you have to provide methods to save/delete those objects from the client.

A: Your interface ArticleRequest isn't configured properly. You need correct it like this.
@Service(value = SentenceServiceImpl.class, locator = SpringServiceLocator.class)
public interface SentenceServiceRequest extends RequestContext {

    Request<List<SentenceProxy>> getSentences();

    Request<Void> saveOrUpdate(SentenceProxy sentence);

}

Locator:
public class SpringServiceLocator implements ServiceLocator {

    public Object getInstance(Class<?> clazz) {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(RequestFactoryServlet.getThreadLocalServletContext());
        return context.getBean(clazz);
    }

}


text:
Q: How to compile additional source files in cmake after the build process I have a project in cmake for windows which contains a Pro*C source file called database.proc, my goal is to generate a C source file from the .proc file and add it to the project to be linked along the other source files, I've tried to add a custom command to achieve this without success
add_custom_command(TARGET myproj OUTPUT PRE_LINK
    COMMAND ${PROC} iname=${PROJECT_SOURCE_DIR}/connection.proc SQLCHECK=SYNTAX
        MODE=ANSI IRECLEN=255 ORECLEN=255
        ONAME=${PROJECT_SOURCE_DIR}/connection.c
    COMMAND ${CMAKE_C_COMPILER} ${CMAKE_C_FLAGS}
            ${PROJECT_SOURCE_DIR}/connection.c )

Is there some way to do this?

A: I'm not familiar with Pro*C, but it looks like you're mixing together the two different versions of add_custom_command.
The first version add_custom_command(OUTPUT ...) is used to generate a file which is then added as a dependency of another CMake target.  When that target is built, the custom command is executed first in order to generate the output file.
The second version add_custom_command(TARGET ...) is used to define a pre-build, pre-link or post-build command; one which does not necessarily create a file, but which executes in conjunction with building the associated target.
If you only have one target which depends on the output of Pro*C, then the first version is probably your best bet:
add_custom_command(OUTPUT ${PROJECT_SOURCE_DIR}/connection.c
    COMMAND ${PROC} iname=${PROJECT_SOURCE_DIR}/connection.proc SQLCHECK=SYNTAX
        MODE=ANSI IRECLEN=255 ORECLEN=255
        ONAME=${PROJECT_SOURCE_DIR}/connection.c)
add_executable(myproj ${PROJECT_SOURCE_DIR}/connection.c <other sources>)


text:
Q: Get specific part of querySelector(x).innerText So I'm trying to automate a task in Puppeteer, and one of the things I want to do involves getting the time as text. I found the original way too complicated so I opted for this method as the Date and Time is already there, just have to isolate the time.
Running this in the web console:
document.querySelector('div[class="h1 text-success"]').innerText;

gets me this (for this time, next time I go through the process, it'll show a different time assuming I refill out the form and the time updates).
'Tuesday, October 19, 2021 5:48 PM'

The Question: Is there any way to specifically isolate the 5:48 PM part no matter what comes before the time?
EDIT: The two methods posted do work (technically, assuming you're entering it into the web console yourself.) but Puppeteer's having issues (or I just have no clue how to implement it in Puppeteer, probably the latter).
Update 2 (because somehow I couldn't put 1 and 1 together quickly): instead of declaring the const TimeRX, I just removed it and just substituted TimeRX for the RegExp. This was what that line ended up as:
const time = await page.evaluate(()=>document.querySelector("div.h1.text-success").textContent.match(/\d{1,2}:\d{2} (AM|PM)/i)?.[0]);

I'll probably end up changing the RegExp for the other recommended one.

A: Capture it with a regex?

const twelveHourTimeRx = /(1[0-2]|(?<!\d)[1-9]):[0-5]\d ?(AM|PM)/i
// or the much simpler but less valid /\d{1,2}:\d{2} (AM|PM)/i

const time = document.querySelector("div.h1.text-success")
  .textContent.match(twelveHourTimeRx)?.[0]

console.log("time", time)

  Tuesday, October 19, 2021 5:48 PM

Note that I've used a much more forgiving selector to locate your
. Your original one requires the class attribute to be exactly "h1 text-success" but using .h1.text-success means that there can be other classes and in any order.

A: You can split the string by a space and get the last two items:

const str = document.querySelector('.h1.text-success').textContent
const res = str.split(' ').slice(-2).join(' ')

console.log(res)

Tuesday, October 19, 2021 5:48 PM


text:
Q: Query Chatter Feed, Topics, and Groups First off, my end goal is lofty and time-consuming, but we need metrics and this is the best way to do it (that I can think of). Originally, a chatter post was created on the quote, case, or where making a request and the end user marked it with a topic. An answer would be given and then done. Now, we've moved to a group. So my question: What is the best/most efficient way to query FeedItem, FeedComment, Topic, and CollaborationGroup? I would like to see all posts with a certain topic and their comments. Then I'd like to see all posts from the group with their comments. I'll then use the createddate to gather metrics. I've been able to do individual queries in the developer console, but I'd like to send these all to a .csv (I have the apex code to do that) and possibly insert into a local SQL db. I just can't find the relationships between feeditem and topic, feedcomment and topic. Here are my queries so far:
ChatterActivity
0ca
select Id, CommentCount, CommentReceivedCount, InfluenceRawRank, LikeReceivedCount, ParentId, PostCount from ChatterActivity limit 100

FeedComment
0D7
SELECT Id, CommentBody, CreatedDate, CreatedById, FeedItemId, ParentId FROM FeedComment

FeedItem
0D5
select Id, Body, CommentCount, CreatedDate, LikeCount, LinkUrl, ParentId, RelatedRecordId, Title, Type from FeedItem WHERE Type = 'TextPost'

Topic
0TO
select Id, Name, CreatedById, CreatedDate, Description, SystemModstamp from Topic

CollaborationGroup
0F9
select Id, Name, Description, InformationBody, InformationTitle from CollaborationGroup

CollaborationGroupFeed
0D5
select Id, Body, CommentCount, CreatedById, CreatedDate, LikeCount, LinkUrl, ParentId, RelatedRecordId, Title, Type from CollaborationGroupFeed

Update: TopicAssignment Query
select id, topicid, entityid, entitykeyprefix, entitytype, createddate, createdbyid from TopicAssignment

Update: My Solution
Here is the beginning framework for my solution, and how to get it to display in debug. Obviously record count will get too high, but that's the nth step down the road.
List<FeedItem> chatFeed = [SELECT  Id, Body, CommentCount, CreatedDate, LikeCount, LinkUrl, ParentId, RelatedRecordId, Title, Type,
    (SELECT Id, CommentBody, CreatedDate, CreatedById, FeedItemId, ParentId FROM FeedComments)
FROM FeedItem
WHERE Id IN (
    SELECT EntityId FROM TopicAssignment
    WHERE EntityType = 'FeedItem'
    AND TopicId = '<TOPIC_ID_HERE>'
) LIMIT 100
];

For(FeedItem fi : chatFeed) {
    System.debug(fi);
    For (FeedComment fc : fi.FeedComments) {
        System.debug(fc);
    }
}

A: Trusty old ChildRelationship to the rescue:
for (ChildRelationship relation : SObjectType.Topic.getChildRelationships())
    system.debug(relation);

Relevant relationships and properties:

[getChildSObject=FeedComment;getField=ParentId;getRelationshipName=null;]
  [getChildSObject=FeedItem;getField=ParentId;getRelationshipName=null;]

You should just be able to do:
SELECT Body, BestCommentId, CommentCount, LikeCount, Type,
    (SELECT CommentBody FROM FeedComments)
FROM FeedItem WHERE ParentId = '<topic_id_here>'

If you want to filter on multiple Topic parents, you could change your WHERE clause to:
ParentId IN ('<topic1_id>', '<topic2_id>', 'etc.')

You can also do a Left Inner Join to see which records have a relevant TopicAssignment:
SELECT ... FROM FeedItem WHERE Id IN (
    SELECT EntityId FROM TopicAssignment
    WHERE EntityType = 'FeedItem'
    AND TopicId IN ('<id1>', 'etc.')
)

A: Following up on Adrian's answer, if you want to use this in SOQL you need the API Name of the relation.  Here is a generalized implementation of his solution:
DescribeSObjectResult type = SobjectType.Account;
String filter = 'Feed';
  for (ChildRelationship relation : type.getChildRelationships()) {
  if (String.valueOf(relation).contains(filter))
    system.debug('* ' + relation.getChildSObject() + ' = ' + relation.getRelationshipName());
}

Results:
12:49:03.23 (77283325)|USER_DEBUG|[5]|DEBUG|* AccountFeed = Feeds
12:49:03.23 (90082901)|USER_DEBUG|[5]|DEBUG|* EntitySubscription = FeedSubscriptionsForEntity
12:49:03.23 (91856038)|USER_DEBUG|[5]|DEBUG|* FeedComment = null
12:49:03.23 (92184455)|USER_DEBUG|[5]|DEBUG|* FeedItem = null
12:49:03.23 (116801566)|USER_DEBUG|[5]|DEBUG|* WorkFeedbackRequest = RelatedObjects


text:
Q: Gracefully handle uncaught exception in forked process with a socket I'm not able to find a way of how to properly handle a situation when a forked process that has a socket sent to it fails.
Here is example of server.js:
'use strict';

var http = require('http');
var fork = require('child_process').fork;

var srv = http.createServer(function (req, res) {
  var f = fork('./client.js');
  f.send('socket', res.socket);
});

srv.listen(7331, 'localhost', function () {
  console.log('server started');

  var req = http.request({
    port: 7331,
    path: '/'
  }, function (res) {
    res.setEncoding('utf8');
    var body = '';
    res.on('data', function (chunk) {
      body += chunk;
    });
    res.on('end', function () {
      console.log('RESPONSE', res.statusCode, res.headers, body);
    });
  });
  req.on('error', function (e) {
    console.log('REQUEST ERROR', e.stack);
  });
  req.end();
});

and of client.js:
throw new Error('Client error');

I get the following output:
    server started
client.js:1
(function (exports, require, module, __filename, __dirname) { throw new Error('Client Error');
                                                              ^

Error: Client Error
    at Object.<anonymous> (client.js:1:69)
    at Module._compile (module.js:425:26)
    at Object.Module._extensions..js (module.js:432:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:457:10)
    at startup (node.js:136:18)
    at node.js:972:3
REQUEST ERROR Error: socket hang up
    at createHangUpError (_http_client.js:209:15)
    at Socket.socketOnEnd (_http_client.js:294:23)
    at emitNone (events.js:72:20)
    at Socket.emit (events.js:166:7)
    at endReadableNT (_stream_readable.js:905:12)
    at doNTCallback2 (node.js:450:9)
    at process._tickCallback (node.js:364:17)

Is it possible to handle an uncaught exception in a forked process in given situation and generate a friendly response with status code and the error description in body?
What I've tried:

*

*subscribed to child's close event in server.js and sent response from there with no luck - This socket is closed. is thrown

*did some preparation in client.js before throwing an error: subscribed to uncaughtException and sent to socket some response data - still socket hang up and no response

A: Due to absence of activity here, I posted the question in nodejs repo https://github.com/nodejs/node/issues/4745, where it got attention from nodejs contributors.
To sum up: that is not possible to use socket in parent process that was sent to child because it get's destroyed as soon as send() is called.
So the only way to solve the problem is to do some preparation in client.js before error happens. I pointent out in try #2 that I did that, but maybe I was doing it wrong... With the following client.js code, everything works good:
'use strict';

let socket;

process.on('uncaughtException', function (e) {
  socket.write(`HTTP/1.1 500 OK\nContent-Type: text/html\nContent-Length: ${e.message.length}\n\n${e.message}`);
});

process.on('message', function (type, s) {
  socket = s;
  routine();
});

function routine() {
  throw new Error('Client error');
}


text:
Q: Compare strings with trailing spaces in Firebird SQL? I have an existing database with a table with a string[16] key field.
There are rows whose key ends with a space: "16 ".
I need to allow user to change from "16 " to e.g. "16" but also do a unique key check (i.e. the table does not have already a record with key="16").
I run the following query:
select * from plu__ where store=100 and plu_num = '16'

It returns the row with key="16 "!
How do I check for unique key so that keys with trailing spaces are not included?

EDIT: The DDL and the char_length
CREATE TABLE PLU__
(
  PLU_NUM Varchar(16),
  CAPTION Varchar(50),
...

A: *

*string[16] - there is no such datatype in Firebird. There are CHAR(16) and VARCHAR(16) (and BLOB SUBTYPE TEXT, but it is improbable here).  So you omit some crucial points about your system. You do not work with Firebird, but with some undisclosed intermediate layer, that is no one knows how opaque or transparent.

I suspect you or your system chose CHAR datatype instead of VARCHAR where all data is right-padded with space to the max. OR maybe the COLLATION of the column/table/database is so that trailing spaces do not matter.
Additionally, you may be just wrong. You claim that the row being Selected does contain the trailing blank, but I do not see it. For example, add CHAR_LENGTH(plu_num) to the columns in your SELECT and see what is there.
Additionally, if plu_num is number - should it not be integer or int64 rather than text?

*Bottom of your screenshot shows "(NONE)". I suspect that is the "connection charset". This is allowed for backward compatibility with programs made 20 years ago, but it is quite dangerous today. You have to consult your system documentation, how to set the connection charset to URF-8 or Windows-1250 or something meaningful.

*"How do I check for unique key so that keys with trailing spaces are not included?" you do not. You just can not do it reliably, because of different transactions and different programs making simultaneous connections. You would check it, decide you are clear, but right before you would insert your row - some other computer would insert it too. That gap can not be crossed that way, between your two commands of checking and inserting - anyone else can do it too. It is called race conditions.
You have to ask the server to do the checks.
For example, you have to introduce UNIQUE CONSTRAINT on the pair of columns (store, plu_num). That way the server would refuse to store two rows with the same values in those columns, visible in the same transaction.
Additionally, is it even normal to have values with spaces? Convert the field to integer datatype and be safe.
Or if you want to keep it textual and non-numeric you still can

*Introduce CHECK CONSTRAINT that trim(plu_num) is not distinct from plu_num (or if plu_num is declared as a NOT NULL column to the server, then trim(plu_num) = plu_num). That way the server would refuse storing any value with spaces before or after the text.

In a case the datatype or the collation of the column makes no difference for comparing texts with and without trailing spaces (and in case you can not change that datatype or collation), you may try adding tokens, like ('+' || trim(plu_num) || '+') = ('+' || plu_num || '+')

*Or instead of that CHECK CONSTRAINT, you can have proactively remove those spaces: set new before update or insert TRIGGER on the table, that would do like NEW.plu_num = TRIM(NEW.plu_num)
Documentation:

*

*https://www.firebirdsql.org/refdocs/langrefupd20-distinct.html

*http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-tbl.html#fblangref25-ddl-tbl-constraints

*http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-tbl.html#fblangref25-ddl-tbl-altradd

*http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-ddl-trgr.html

*http://www.firebirdtest.com/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-datatypes-chartypes.html
Also, via http://www.translate.ru a bit more verbose:

*

*http://firebirdsql.su/doku.php?id=constraint

*http://firebirdsql.su/doku.php?id=alter_table
You may also check http://www.firebirdfaq.org/cat3/
Additionally, if you add the constraints onto existing table with non-valid data entered earlier before you introduced those checks, you might trap yourself into "non-restorable backup" situation. You would have to check for it, and sanitize your old data to abide by newly introduced constraints.

Option #4 explained in detail is below. Just this seems be a bad idea of database design! One should not just "let people edit number to remove trailing blanks", one should make the database design so that there would be no any numbers with trailing blank and would be no any way to insert them into the database.
CREATE TABLE "_NEW_TABLE" (
    ID   INTEGER NOT NULL,
    TXT  VARCHAR(10)
);

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"

ID  TXT CONCATENATION   CHAR_LENGTH
1   1   _1_ 1
2   2   _2_ 1
4   1   _1 _    2
5   2   _2 _    2
7    1  _ 1_    2
8    2  _ 2_    2

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"
where txt = '2'

ID  TXT CONCATENATION   CHAR_LENGTH
2   2   _2_     1
5   2   _2 _    2

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"
where txt || '+' = '2+' -- WARNING - this PROHIBITS index use on txt column, if there is any

ID  TXT CONCATENATION   CHAR_LENGTH
2   2   _2_     1

Select id, txt, '_'||txt||'_', char_length(txt) from "_NEW_TABLE"
where txt = '2' and char_length(txt) = char_length('2')


text:
Q: How to assign a new var based on a disabled/enabled button? Let's say I have a button that is disabled when the condition is false (opacity: 0.3), and enabled when the condition is true (opacity: 1).
Let's forget about the actual condition for now -- I would like to actually check when the button is disabled (opacity: 0.3) and assign a value to a new variable based on that.
For example,
if the button is disabled (opacity: 0.3), then newVar = false.
if the button is enabled (opacity: 1), then newVar = true.
How can I achieve that? Below is the code of my current button
<NextBtn
    orange
    withIcon
    iconStyle={{ width: '9px', height: 'auto' }}
    icon={t.image.icon.bottomChevron_orange}
    event={() => checkForError('next')}
    className="buttonNextClass"
    style={
        checkEmptyField() === true
        ? { opacity: 0.3, pointerEvents: 'none' }
        : { opacity: 1 }
    }
    >
    {c('form.content.next')}
</NextBtn>

A: Maybe by creating a setter to set the value of newVar:
const setNewVar = (param)=>{
 newVar = param;
}
<NextBtn
    orange
    withIcon
    iconStyle={{ width: '9px', height: 'auto' }}
    icon={t.image.icon.bottomChevron_orange}
    event={() => checkForError('next')}
    className="buttonNextClass"
    style={
        checkEmptyField() === true
        ? setNewVar(false) && { opacity: 0.3, pointerEvents: 'none' }
        : setNewVar(true) &&  { opacity: 1 }
    }
    >
    {c('form.content.next')}
</NextBtn>


text:
Q: I accidentally replace vanilla Sequin Dress with a mod. Is there any way to get it back without reinstalling the game? I recently installed ZGC Mary Dress using NMM, and somehow I downloaded and installed the replacer version of Sequin Dress. I tried to uninstall the mod and resulting in my character being naked. Is there anyway to get it back without reinstalling the game?

A: If you installed the mod via NMM, simply deactivating it in the NMM interface should already restore the original file. NMM never deletes or overwrites existing files without backing them up first.
If that is not the case, you - somehow - overwrote the existing file permanently, resulting in it being lost. However, if you run the game on steam, you can check the gamefiles via properties. If something is missing, steam will redownload it, that should fix your issue.
If you're not on steam, you might be out of luck, I'm not sure if the bethesda client offers such a feature. In that case you can only reinstall it. I would not recommend to try and fix the issue manually by copy-pasting the game file from somewhere. That will only lead to even more issues.


text:
Q: Accessing DispHTMLElementCollection properties I need to iterate through the elements of an object that (as the debugger states) is a DispHTMLElementCollection.
Can't seem to be able to access the properties of a DispHTMLElementCollection as there is a table with 50 td tags on this page, and when I print out the length of this object it returns 0.
Any light about this is appreciated.
Thanks.
EDIT:
Using this snippet, you still need to break the code to press the search button to show some results, but after that, still returns zero as length...
Dim objHTML As HTMLDocument

Set ie = New InternetExplorer
With ie
    .navigate "https://www.oeko-tex.com/en/manufacturers/certified_products/certified_products.html"
    .Visible = True
    While .Busy Or .readyState <> READYSTATE_COMPLETE
       DoEvents
    Wend
    Set objHTML = .document
    DoEvents
End With
Set elementONE = objHTML.getElementsByTagName("td")
Debug.Print TypeName(elementONE)
Debug.Print elementONE.Length

A: Using the feedback from Tim Williams
Sub test()

    Dim objHTML As HTMLDocument
    Dim ie As InternetExplorer
    Dim oElemets As Object
    Dim oElement As Object

        Dim h As HTMLOptionElementFactory
    Set ie = New InternetExplorer
    With ie
        .navigate "https://www.oeko-tex.com/en/manufacturers/certified_products/certified_products.html"
        .Visible = True
        While .Busy Or .readyState <> READYSTATE_COMPLETE
            DoEvents
        Wend
        Set objHTML = .document
        DoEvents
    End With

    ' As per the suggestion Tim Williams proposed
    Set objHTML = objHTML.getElementById("customer-profile")
    Set oElemets = objHTML.getElementsByTagName("td")

    For Each oElement In oElemets
        Debug.Print oElement.nodeName
    Next

End Sub

Thanks


text:
Q: Is it mandatory to name view and action mehod same in mvc? I have a view name EmployeeForm.cshtml and inside EmployeeController I have two action method MyView() and RandomView(). MyView() returns object of Employee Model while RandomView() method returns the object of EmployeeViewModel.
But the URl request goes as like: http://localhost:port/Employee/EmployeeForm i.e. MVC expects an EmployeeForm() method inside EmployeeController.
How can i correct this error ?

A: No it's not.
You view form should point to the name desired, whatever it's the current MyView() or another custom name by decorating the controller action with attribute.
No matter what you choose, the view form must match the action name(or attribute name).
[ActionName("EmployeeForm")]
public ActionResult MyView()
{
    // You code here
    return View(); // Will use MyView page
    return View("SomeViewName"); // Will use SomeViewName page
}

Concerning View page, this is almost not related. You can set the controller action to return whatever View page you want using View("SomeViewName", myModel).
Note: When using BeginForm without passing the desired action, it will use the current View file page as the target form Url action name.

A: No You don't have to use same name view and action.
code:
public ActionResult EmployeForm()
{
    return ViewResult("AnotherViewName");
}


text:
Q: Caching issue when deployed flask app with SQLite on google App engine I'm newborn on Google cloud App engine :), I'm deploying my flask web app to Google App Engine, and everything from GAE looks fine,
but when the user accesses the app the faced an issue. looks like a caching issue for me so far.(hope someone help me im going to be crazy)
Issue description:
Any action user takes required to retrieve data from the server-side. the user have to refresh the page to reload the changes (this sometimes the user press refresh more than 3 times.)
Also, after the object ex.(table) loaded with the data retrieved from the server, if the user press again refreshes the page. the page loaded as before any action taken.
And so on page reload showing the latest another page load showing the old content.
What I did till the moment:
I update my app.yaml to be as below:
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT main:app

default_expiration: "2s"

env_variables:
  GOOGLE_APPLICATION_CREDENTIALS: 'vizionflow-5b8735ce1d20.json'

handlers:
- url: /static/css
  static_dir: static/css/
  expiration: '10s'

- url: /static/js
  static_dir: static/js/
  expiration: '5m'

error_handlers:
  - file: error_nopage.html

Also, I tried to add on the
@app.after_request
def add_header(r):
    """
    Add headers to both force latest IE rendering engine or Chrome Frame,
    and also to cache the rendered page for 10 minutes.
    """
    r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    r.headers["Pragma"] = "no-cache"
    r.headers["Expires"] = "0"
    r.headers['Cache-Control'] = 'public, max-age=0'
    return r

Thanks for everyone how could help even with Ideas :)

A: Did you check if the response really returns the headers you're setting in Python? IIRC it was not working for me, as AppEngine is somehow overriding them, so I had to set them in app.yaml instead, eg:
handlers:
  - url: /my/route
    script: auto
    secure: always
    http_headers:
      Cache-Control: no-cache


text:
Q: How can i intercept a component to check for permission I have lots of static forms which i show the user when he clicks on the main menu and goes to a specific route, what i want to do now is to check when going to a route if that component has permission to be visited, i can do this by doing a simple post to server but i am confused and i don't know where should be the place to do this check or post.
Here are some of the solutions i thought of:
1- Writing a Higher order component and wrapping each static component with it
2- creating a base class and making each static form to inherit it while doing this check in the parent class
3- Or maybe using the routes as a solution since i am using the react-router ?
I will appreciate any help or tips.
Thanks.

A: Create a custom hook like so:-
const useAdmin = (url:string) => {
    const [admin, setAdmin] = React.useState(false);

    React.useEffect(() => {
        post(url, {some: body}).then(res => {
            setAdmin(res.admin);
        }).catch(err => {
            setAdmin(false);
        });
    }, [])

    return [admin];
}

Then use it anywhere:-
const mycomponent = props => {
    const [admin] = useAdmin('https://foobar.com/checkPermission');

    //Rest of the logic according to the variable 'admin'
    return (
        <div>
            {
                admin? <div/>:null
            }
        </div>
    )
}

Or think of admin as permission. Pass it some url for different routes and it will handle it.

A: I do something similar using react-router as well. I made my own route component that wraps around react-router's route that checks permissions and conditionally renders the route or redirects.
If you're doing the api call each time, then it would look something close to this.
class AppRoute extends Component {
  state = {
    validCredentials: null
  }

  componentDidMount() {
    // api call here + response
    if (ok) {
      this.setState({validCredentials: true})
    } else {
      this.setState({ validCredentials: false})
    }
  }

  render() {
    const { validCredentials } = this.state
    if (validCredentials) {
      return <Route {...this.props} />
    } else if (validCredentials === false) {
      return <Redirect to="somewhere"/>
    }
    return null
  }
}

A: You can definitely accomplish this using a Higher Order Component. Just set a state for the user on login like "admin" or "basic_user." According to this state some buttons or forms are going to be available for the user to access. You can also save these access permissions to your backend and call it in the HOC whenever the user logs in.


text:
Q: Kalman Filter Parameter Definition for Vehicle Position Estimation in Python I'm relatively new to Kalman filter concepts and I would like to use it for estimating and tracking the accuracy of the position of a vehicle with GPS measurements (As a first step). However, I am not sure of the assumptions and parameter values that I have considered , and would like to know by other users if I'm headed in the right direction.
Thanks!!
I've considered a standard motion model: Constant Velocity (Assuming that acceleration plays no effect on this vehicle's position estimation) and therefore, my states consist of only position and velocity.
+1 =  + ˙ Δ
 ˙+1 = ˙
Therefore, the state transition matrix would be (Considering 2D positioning (x,y) with latitude and longitude coordinates):
A = [[1.0, 0.0, Δ, 0.0],
     [0.0, 1.0, 0.0, Δ],
     [0.0, 0.0, 1.0, 0.0],
     [0.0, 0.0, 0.0, 1.0]]

Since we only have position measurement data available, we can correspondingly write the measurement matrix as:
H = [[1.0, 0.0, 0.0, 0.0],
     [0.0, 1.0, 0.0, 0.0]]

Initial Conditions:
For the initial starting vehicle state x0, I assumed all zeroes for the position and velocity (I did read a couple of implementations where they've entered a non-zero value for the position (Usually set to 100), but am not sure about the reason for this)
For the initial uncertainty P0, I assumed an identity matrix with diagonals set to 100 since we are uncertain about the initial position and velocity. Should this value be set higher? What exactly does it mean when the initial position and velocity are known perfectly with respect to the model? Is it the world coordinates or just some arbitrary position?
Time Step ( Δ ):
Since GPS updates at 1 Hz or every 1 second, I have correspondingly assumed the same for the time step of the filter
Noise Values:
Process Noise: I just assumed an identity matrix for the process noise of the model. But in other implementations, it is also assumed that process noise is zero. Does that mean, there are no random fluctuations of the system states?
Measurement Noise:
Since GPS is the measurement under consideration, the standard deviation for a GPS reading is approximately 6 metres and is considered to be the measurement noise for the system.
Measurement:
I'm using a GPX file exported from an app (Strava) that gives the positioning for latitude and longitude. Should this be converted to metres or can I directly use the positioning data from the GPX file?
Please let me know if the above assumptions and implementations are correct :)
UPDATE
I directly considered the Lat Long data given by the GPS as a measurement input to the Kalman without first converting it to Cartesian. In the below code implementation, the data is now first converted to UTM before given as a measurement Input. As suggested by Kani, I will check the calculation conversion given for latitude and longitude and the difference obtained between the 2 techniques.
import gpxpy
import pandas as pd
import numpy as np
import utm
import matplotlib.pyplot as plt

with open('test3.gpx') as fh:
    gpx_file = gpxpy.parse(fh)
segment = gpx_file.tracks[0].segments[0]
coords = pd.DataFrame([
    {'lat': p.latitude,
     'lon': p.longitude,
     'ele': p.elevation,
     'time': p.time} for p in segment.points])
coords.head(3)
plt.plot(coords.lon[::18], coords.lat[::18],'ro')
plt.show()
#plt.plot(coords.lon, coords.lat)

def lat_log_posx_posy(coords):

     px, py = [], []
     for i in range(len(coords.lat)):
         dx = utm.from_latlon(coords.lat[i], coords.lon[i])
         px.append(dx[0])
         py.append(dx[1])
     return px, py

def kalman_xy(x, P, measurement, R,
              Q = np.array(np.eye(4))):

    return kalman(x, P, measurement, R, Q,
                  F=np.array([[1.0, 0.0, 1.0, 0.0],
                              [0.0, 1.0, 0.0, 1.0],
                              [0.0, 0.0, 1.0, 0.0],
                              [0.0, 0.0, 0.0, 1.0]]),
                  H=np.array([[1.0, 0.0, 0.0, 0.0],
                              [0.0, 1.0, 0.0, 0.0]]))

def kalman(x, P, measurement, R, Q, F, H):

    y = np.array(measurement).T - np.dot(H,x)
    S = H.dot(P).dot(H.T) + R  # residual convariance
    K = np.dot((P.dot(H.T)), np.linalg.pinv(S))
    x = x + K.dot(y)
    I = np.array(np.eye(F.shape[0]))  # identity matrix
    P = np.dot((I - np.dot(K,H)),P)

    # PREDICT x, P
    x = np.dot(F,x)
    P = F.dot(P).dot(F.T) + Q

    return x, P

def demo_kalman_xy():

    px, py = lat_log_posx_posy(coords)
    plt.plot(px[::18], py[::18], 'ro')
    plt.show()

    x = np.array([px[0], py[0], 0.01, 0.01]).T
    P = np.array(np.eye(4))*1000 # initial uncertainty
    result = []
    R = 0.01**2
    for meas in zip(px, py):
        x, P = kalman_xy(x, P, meas, R)
        result.append((x[:2]).tolist())
    kalman_x, kalman_y = zip(*result)
    plt.plot(px[::18], py[::18], 'ro')
    plt.plot(kalman_x, kalman_y, 'g-')
    plt.show()

demo_kalman_xy()

A: For the Kalman filter, as with any physics related porblem, the unit of the measurement matters. If you are using velocity as meters per second, the position should not be in latitude/longitude. You must convert them to meters.
One way you can do that is by selecting the first latitude/longitude pair as the base point and treating all the other points as a distance traveled from the base point. This is not a simple calculation as it is a function of multiple things.
For really short distances, you can approximate the relative position in meters using the following equations with r being the radius of the earth:

*

*distance along latitude = r * deg_to_rad(latitude - base latitude)

*distance along longitude = 2 * r * asin(cos(base latitude)) * sin(pi / 180 / 2)) * deg_to_rad(longitude - base longitude)
This is tricky for two main reasons though.

*

*This is only valid for short distances.

*Earth's radius changes with latitude.

A: Setting Q - process noise covariance matrix, R - measurement noise covariance matrix and P - error covariance matrix depends on what you are trying to track and its conditions and its quite difficult. Especially error covariance matrix (P).
I suggest that you take a look at the jupyter notebook the creator of filterpy library has created to explain how correctly implement Kalman filters.


text:
Q: In HTML5, can you save an image to cache programmatically? I love that in HTML5 you can save text data out to a local database, and can even use SQL to do it. (http://webkit.org/blog/126/webkit-does-html5-client-side-database-storage/)
I've got an app that I've written for the iPhone's MObile Safari that caches everything offline except for images.  The images still have to be downloaded from the server, and I don't know how to ensure that they will stay cached.  Ideally, I'd like to write them out to the localStorage database.
I was thinking of writing an image to the canvas, and then serializing that as text... any ideas?  Is there any easier way to do this?
Ideally, I'd like to do this all with HTML and JavaScript, no native apps/objective-C.

A: You could do what Google does in Mobile GMail and implement as a data Url. This means that following would be cached as part of the page (if included in cache.manifest), as they are not external. Either:
<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7"
width="16" height="14" alt="embedded folder icon">

Or:
<style type="text/css">
.Jd{background:#fff;width:100%;border-width:7px;-webkit-box-sizing:border-box;-webkit-border-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAWCAYAAAAvg9c4AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAUlJREFUeNpi/P//P4O+VwcfAwODGxDLATGITSr4BMSPgHjXxW0Vnxj1PNtFmBgZU/79/38MKHgBqoAoADQATEMdZQA0xwpozlwWEUFu7zfvvx4ACp5gIBOAXAekDgEN/yEqzOPD9P3nHwWoC6kBLnz99kue6eu3n4xAzg8Civ8jYXwu/vXt+y8GJgYagBFuKAuOSCEUabD0CYsgxmHifVjWQwYwb+KSJ2go0ABGAuHISMiCkZ5OBfm5mN9//MaBr1BBDjvkSMMSH2z8vBzMLI4Wqjzrdl7UA4qdwqOYkUhHGjhbqfOwxAaafjh0+q7fm3dfQK49B8RfSPUu0FIeIGUkIsTjBjKPEVhHyQO93zV96ZFXR8/c+/zkxYdfpBoqIyHAZm2ixJsZbSMGDM4ykKEgcREgzgRibSAWIiNu3gHxVSCeDsRvAAIMAK29e2M9JZVZAAAAAElFTkSuQmCCCg==") 9 7 8 7}
</style>

Read more on the subject here: http://www.websiteoptimization.com/speed/tweak/inline-images/

A: You could store the images using the Data UI scheme in the HTML5 database.

A: Look at the application cache in html5, that does basically exactly what you want (it's also what you want to use if you want to support completely offline web applications).
Alternatively you could (somewhat ugly)daw the image to canvas, then to canvas.toDataURL() to get a data url for the image, which you can then store in the normal database or offline storage apis.

A: see also:
http://www.w3.org/TR/offline-webapps/


text:
Q: Testing a method that loads JSON config files in Golang In the Golang project under test, there's a method that loads a JSON config file into a variable. Its code is like this:
// Load the JSON config file
func Load(configFile string, outputObj interface{}) *errors.ErrorSt {
    var err error
    // Read the config file
    jsonBytes, err := ioutil.ReadFile(configFile)
    if err != nil {
        fmt.Println(err.Error())
        return errors.File().AddDetails(err.Error())
    }

    // Parse the config
    if err := json.Unmarshal(jsonBytes, outputObj); err != nil {
        return errors.JSON().AddDetails("Could not parse" + configFile + ": " + err.Error())
    }
    return nil

}

I wish to test it but I don't know if I should create fake JSON file for the test cases, or just mock the whole function. My Java background has me leaning towards the latter.
Exploring that, I found the testify framework I'm using has a package for mocking methods, but what I'm attempting to mock doesn't belong to interfaces (the pitfalls of non-OOP languages!!)

A: There's a couple ways to do it. It's certainly not unusual to have a sample data file to test loading & parsing a file (you'll find this in places in the standard library). It's also a pretty common practice for a function like this to take in an io.Reader rather than a file path, so that in testing you can just pass in e.g. a bytes.Reader to effectively "mock" the file while testing everything else. Which method to use (or both, if you choose) depends on your use case and design objectives; switching to an io.Reader gives you more flexibility, but only you know if that flexibility has any value in context. If not, just keep a test file along with your tests and read that.


text:
Q: Is there a way to pickle a PriorityQueue? This is Python 3.10. I use a PriorityQueue as a way to track Actors' turn order in my game. It's just a simple roguelike. I don't use the synchronization features of the PriorityQueue. My code:
import pickle
from queue import PriorityQueue

class GameEngine():
    def __init__(self):
        self.pqueue = PriorityQueue()

    def save_to_file(self):
        with open('save.pkl', 'wb') as file:
            pickle.dump(self, file, pickle.HIGHEST_PROTOCOL)

class Monster():
    pass

engine = GameEngine()
orc1 = Monster()
orc2 = Monster()

engine.pqueue.put((20,orc1))
engine.pqueue.put((10,orc2))

engine.save_to_file()

It returns TypeError: cannot pickle '_thread.lock' object. From what I understand PriorityQueue is not pickle-able. I've read here that Queue.Queue has a pickle-able alternative of collections.deque if the synchronization stuff is not necessary. Is there such an alternative to PriorityQueue, or is there a way to pickle it anyway? Other than implementing my own simplified version of PriorityQueue?

A: As you don't need the synchronisation features of PriorityQueue, just use the light-weight heapq module. It provides functions (not methods) to work on a plain list:
import pickle
from heapq import heappush, heappop

class GameEngine():
    def __init__(self):
        self.pqueue = []

    def save_to_file(self):
        with open('save.pkl', 'wb') as file:
            pickle.dump(self, file, pickle.HIGHEST_PROTOCOL)

class Monster():
    pass

engine = GameEngine()
orc1 = Monster()
orc2 = Monster()

heappush(engine.pqueue, (20,orc1))
heappush(engine.pqueue, (10,orc2))

engine.save_to_file()


text:
Q: Calculating Ranges of Data Types in C I'm working through K&R Second Edition, and can't figure out why I'm getting a certain result. The problem I'm solving is calculating upper and lower limits for data types. Specifically:

"Write a program to determine the ranges of char , short , int , and long variables, both  signed and unsigned , by printing appropriate values from standard headers and by direct computation. Harder if you compute them: determine the ranges of the various floating-point types."

I've learned about bitwise operators and two's compliment, and have a solution I think should work for signed data types, but instead it's working for unsigned data types which doesn't make any sense to me. Here's the code:
#include <stdio.h>

main()
{
    signed int i;

    i = ~0;
    i >>= 1;
    printf("Upper limit: %d\n", i);
    printf("Lower limit: %d\n", -i -1);
}

This will result in -1 being printed for the upper limit, and 0 printed for the lower limit. However, if I change i to an unsigned int, I get the result I was expecting (2147483647 and -2147483648). I can't wrap my head around this, because my understanding is that an unsigned int can never be less than 0, and a signed int should work using these bitwise operators, ie, if it's a 32 bit system,
~0 == 11111111111111111111111111111111

, and
~0 >> 1 == 011111111111111111111111111111111,
           or 2147483647.

Any idea where I'm going wrong?

A: by using %d you treat your value as signed to proceed by printf.
you may use %u instead.
added
As  Magn3s1um pointed out you don't need to specify signed and unsigned for your particular task printf will make all job for you.

A: Output:

*

*Note:
"In the expression i >>= 1, a negative value is shifted right. The C standard says this is an implementation-defined operation, and many implementations define it to be arithmetic shift. In an arithmetic shift, the most significant bit is unchanged (keeps MSB (signed bit) = 1)".
(you can read: Right shifting negative numbers in C that >> is compiler dependent whether its singed or unsinfed shift, but probably in your case its doing an Arithmetic Shift.)
For this reason after code:
 i = ~0;
 i >>= 1;

i remains ~0. that is in binary == 11111111111111111111111111111111.
And because ~0 == 11111111111111111111111111111111 is == 2'c complement of 1  that is -1.
So when you prints with format string %d it print -1. You should use %u to print max unsigned value that is == ~0.
Important to note here:

§6.2.6.2 Language 45, ©ISO/IEC ISO/IEC 9899:201x
(ones' complement).    Which of these applies is
  implementation-defined, as is whether the value with sign bit 1    and
  all value bits zero (for the first two), or with sign bit and all value
  bits 1 (for ones'    complement), is a trap representation or a normal
  value. In the case of sign and    magnitude and ones' complement, if
  this representation is a normal value it is called a   negative zero.

Your understanding  that :
~0 >> 1 == 011111111111111111111111111111111 is wrong! (it may be but not happening in your system, according to output)
~0 >> 1 == 111111111111111111111111111111111, note MSB(signed bit)  is 1.
For unsigned shift, try following:
~0U >> 1 == 011111111111111111111111111111111
Notice Suffix U for unsigned.

*Second printf:
Because i is  -1, So in second expression -i - 1 ==  - (-1) - 1 == 1 - 1 == 0 so output is zero : 0.

A: Your compiler implements >> as arithmetic shift. Therefore, the MSB keeps it value of 1 and the shift does nothing.
That is, ~0 >> 1 is still ~0 because the shift sign-extends.
See here: https://stackoverflow.com/a/7632/1974021

A: You may be interested in constant in limits.h and float.h header files
From limits.h:
+------------+------------------------------------------------------------------+--------------------------------+
| CHAR_BIT   | Number of bits in a char object (byte)                           | 8 or greater                   |
| SCHAR_MIN  | Minimum value for an object of type signed char                  | -127 (-2^7+1) or less          |
| SCHAR_MAX  | Maximum value for an object of type signed char                  | 127 (2^7-1) or greater         |
| UCHAR_MAX  | Maximum value for an object of type unsigned char                | 255 (2^8-1) or greater         |
| CHAR_MIN   | Minimum value for an object of type char                         | either SCHAR_MIN or 0          |
| CHAR_MAX   | Maximum value for an object of type char                         | either SCHAR_MAX or UCHAR_MAX  |
| MB_LEN_MAX | Maximum number of bytes in a multibyte character, for any locale | 1 or greater                   |
| SHRT_MIN   | Minimum value for an object of type short int                    | -32767 (-2^15+1) or less       |
| SHRT_MAX   | Maximum value for an object of type short int                    | 32767 (2^15-1) or greater      |
| USHRT_MAX  | Maximum value for an object of type unsigned short int           | 65535 (2^16-1) or greater      |
| INT_MIN    | Minimum value for an object of type int                          | -32767 (-2^15+1) or less       |
| INT_MAX    | Maximum value for an object of type int                          | 32767 (2^15-1) or greater      |
| UINT_MAX   | Maximum value for an object of type unsigned int                 | 65535 (2^16-1) or greater      |
| LONG_MIN   | Minimum value for an object of type long int                     | -2147483647 (-2^31+1) or less  |
| LONG_MAX   | Maximum value for an object of type long int                     | 2147483647 (2^31-1) or greater |
| ULONG_MAX  | Maximum value for an object of type unsigned long int            | 4294967295 (2^32-1) or greater |
+------------+------------------------------------------------------------------+--------------------------------+

A: When you perform the bit shift on i, the compiler sees that i is a signed quantity, and performs an arithmetic right shift.  It seems like you want that line of code to perform a logical right shift.
Change the line
i >>= 1;
to
i = ((unsigned int)i) >> 1;
Then it works!
Output:
Upper limit: 2147483647
Lower limit: -2147483648


text:
Q: I'm having trouble taking averages while passing by address in C So below is the main portion of my code. There are a few external files that I am working with.  In function 3.6, I am having trouble taking the average of my (in this case) total payrate(pr) and my total employees(empCount).  Is there something that I am missing here? When I compile it, I get an error that says invalid operands. When I fix those, my output is 0. I am very new with programming, so bear with me while I try to answer any questions. The function I am having trouble with is the second to last function in the code(3.6 AddDetailToAccumulator).  Thanks much.
#include <stdio.h>
#include <stdlib.h>
#include "EmployeeRecord.h"
#include "CalcTaxes.o"
#define ADDR(var) &var
#define REPORTCOLUMNHEADINGS1 "Employee           Pay    Reg Hrs  Gross    Fed     SSI     Net\n"
#define REPORTCOLUMNHEADINGS2 "Name               Rate   OVT Hrs  Pay      State   Defr    Pay\n"
#define BARS                  "========           =====  =======  =======  ======  ======  =======\n\n"
#define REPORTCOLUMN1         "%s, %s\t%8.2f%8.2f%10.2f%8.2f%8.2f%9.2f\n"
#define REPORTCOLUMN2         "%32.2f%18.2f%8.2f\n\n"

void PrintReportHeadings(FILE * ReportFile); //3.1
void InputEmployeeData(int count,char * lastname,char * firstname,float * hours,float * payrate,float * defr); //3.3
float CalculateGross(float hours, float payrate, float reghours, float ovthours); //3.4 CalculateGross
extern void CalculateTaxes(float gross, float defr, float *ft, float *st, float *ssit); //3.5 CalculateTaxes
void AddDetailToAccumulator(int count,int *empCount,float *pr,float *payrate,float *reg,float *reghours,float *ovt,float *ovthours,float *gp,
                                float *gross,float *fedt,float *ft,float *stt,float *st,float *sst,float *ssit,float *def,
                                float *defr,float *np,float *net,float *avgpr);//3.6 AddDetailToAccumulator
void PrintSummaryReport(float pr,float reg,float ovt,float gp,float fedt,float stt,float sst,float def,float np,float *avgpr,float avgreg,float avgovt,
                        float avggp,float avgfedt,float avgstt,float avgsst,float avgdef,float avgnp,FILE * ReportFile); //3.7

int main()
    {
     EmployeeRecord r; // Call Employee Record Definitions
     float reghours,ovthours;
     float ft,st,ssit;
     float pr,reg,ovt,gp,fedt,stt,sst,def,np;
     float avgpr,avgreg,avgovt,avggp,avgfedt,avgstt,avgsst,avgdef,avgnp;
     char answer;
     int empCount,count;
     FILE * ReportFile;

     PrintReportHeadings(ReportFile); //Call 3.1 PrintReportHeadings

     empCount = 0;// count initializations
     pr = reg = ovt = gp = fedt = stt = def = sst = np = 0;
     avgpr = avgreg = avgovt = avggp = avgfedt = avgstt = avgsst = avgdef = avgnp = 0;
     do
       {
         InputEmployeeData(count,r.firstname,r.lastname,&r.payrate,&r.defr,&r.hours);//Call 3.3 InputEmployeeData
         if (r.hours > 40)//Check for Overtime Hours
           {
             reghours = 40;
             ovthours = r.hours - 40;
           }
         else {
             reghours = r.hours;
             ovthours = 0;
         }
          r.gross = CalculateGross(r.hours,r.payrate,reghours,ovthours); //3.4 CalculateGross
          CalculateTaxes(r.gross,r.defr,&ft,&st,&ssit);//Call 3.5 CalculateTaxes

          r.net = r.gross - ft - st - ssit;// Calculate Net Earnings

          printf(REPORTCOLUMNHEADINGS1);
          printf(REPORTCOLUMNHEADINGS2);
          printf(BARS);
          printf(REPORTCOLUMN1,r.lastname,r.firstname,r.payrate,reghours,r.gross,ft,ssit,r.net);
          printf(REPORTCOLUMN2,ovthours,st,r.defr);
          ReportFile = fopen("report.txt", "a");
          fprintf(ReportFile,REPORTCOLUMN1,r.lastname,r.firstname,r.payrate,reghours,r.gross,ft,ssit,r.net);
          fprintf(ReportFile,REPORTCOLUMN2,ovthours,st,r.defr);
          fclose(ReportFile);

          AddDetailToAccumulator(count,&empCount,&pr,&r.payrate,&reg,&reghours,&ovt,&ovthours,&gp,&r.gross,&fedt,&ft,&stt,&st,&sst,&ssit,
                                 &def,&r.defr,&np,&r.net,&avgpr);//3.6

              while (getchar() != '\n');
              printf(" Repeat (Y/N)? : ");
              scanf("%c",ADDR(answer));
        } while (answer == 'Y' || answer == 'y');
            printf("\n"); // print one line for spacing
       printf("\nTotals %17.2f%8.2f%10.2f%8.2f%8.2f%9.2f\n",pr,reg,gp,fedt,sst,np);
       printf("%32.2f%18.2f%8.2f\n",ovt,stt,def);

       printf("%d",count);

       printf("\nAverages %15.2f%8.2f%10.2f%8.2f%8.2f%9.2f\n",avgpr,avgreg,avggp,avgfedt,avgstt,avgnp);
       printf("%32.2f%18.2f%8.2f\n",avgovt,avgsst,avgdef);

       PrintSummaryReport(pr,reg,ovt,gp,fedt,stt,sst,def,np,&avgpr,avgreg,avgovt,
                        avggp,avgfedt,avgstt,avgsst,avgdef,avgnp,ReportFile); //Call 3.7 PrintSummaryReport

        fflush(stdin);
        getchar();
        return 0;
}

void PrintReportHeadings(FILE * ReportFile) //3.1
{
    ReportFile = fopen("report.txt", "w");
    fprintf(ReportFile,REPORTCOLUMNHEADINGS1);
    fprintf(ReportFile,REPORTCOLUMNHEADINGS2);
    fprintf(ReportFile,BARS);
    fclose(ReportFile);
}

void InputEmployeeData(int count,char * lastname,char * firstname, float * payrate, float * defr, float * hours) //3.3
{
     printf("Enter employee's name: ");  // input section
     scanf("%s%s",firstname,lastname);
     printf("Enter hourly pay rate: ");
     scanf("%f",payrate);
     printf("Enter deferred amount: ");
     scanf("%f",defr);
     printf("Enter hours worked this pay period: ");
     scanf("%f",hours);
}

float CalculateGross(float hours, float payrate, float reghours, float ovthours) // 3.4
{
    return (reghours * payrate)+(ovthours * payrate * 1.5);
}

void AddDetailToAccumulator(int *empCount,float *pr,float *payrate,float *reg,float *reghours,float *ovt,float *ovthours,float *gp,
                                float *gross,float *fedt,float *ft,float *stt,float *st,float *sst,float *ssit,float *def,
                                float *defr,float *np,float *net,float *avgpr)//3.6
{
         empCount = empCount +1;
         *pr = *pr + *payrate;
         *reg = *reg + *reghours;
         *ovt = *ovt + *ovthours;
         *gp = *gp + *gross;
         *fedt = *fedt + *ft;
         *stt = *stt + *st;
         *sst = *sst + *ssit;
         *def = *def + *defr;
         *np = *np + *net;

         *avgpr = *pr / empCount;
}

void PrintSummaryReport(float pr,float reg,float ovt,float gp,float fedt,float stt,float sst,float def,float np,float * avgpr,float avgreg,float avgovt,
                        float avggp,float avgfedt,float avgstt,float avgsst,float avgdef,float avgnp,FILE * ReportFile) //3.7
{
     ReportFile = fopen("report.txt", "a");
     fprintf(ReportFile,"\nTotals %17.2f%8.2f%10.2f%8.2f%8.2f%9.2f\n",pr,reg,gp,fedt,sst,np);
     fprintf(ReportFile,"%32.2f%18.2f%8.2f\n",ovt,stt,def);
     fprintf(ReportFile,"\nAverages %15.2f%8.2f%10.2f%8.2f%8.2f%9.2f\n",&avgpr,avgreg,avggp,avgfedt,avgsst,avgnp);
     fprintf(ReportFile,"%32.2f%18.2f%8.2f\n",avgovt,avgstt,avgdef);
     fclose(ReportFile);
}

A: You're missing the * on the empcount variable here:

empCount = empCount +1;

and here

*avgpr = *pr / empCount
  ;

A: As the previous answer pointed out, you were missing the * operator. This is known as the dereference operator.
What you were doing:
empCount = empCount +1;
// or
empCount++;     // Same assignment

Here, you were performing pointer arithmetic. This assignment is advancing the pointer to the next integer.
What you needed to do:
(*empcount)++;

Dereferencing the pointer will increment the value that the pointer  points to. In other words, if the value of the pointer had address 0x01, the above line would access the integer at memory location 0x01 and add one to it. The original code would just increment the pointer to the next integer (Would increment to 0x05 for a 32-bit integer).


text:
Q: mongo client error operation users find one buffering hello I am using the mongo database and I want to save my files to the database but I keep getting this error this is the error

MongoClient.connect('mongodb://localhost:27017/database', {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
    .then(client => {
        console.log('Mongo Connected!!!');
        const db = client.db('database');
        const collection = db.collection('files');
        app.locals.fileCollection = collection;
    });

thank you

A: Problem -you're trying to query MongoDB before connection is established to the database.
Read - https://mongoosejs.com/docs/connections.html#buffering

Mongoose lets you start using your models immediately, without waiting
for mongoose to establish a connection to MongoDB.

That's because mongoose buffers model function calls internally. This buffering is convenient, but also a common source of confusion. Mongoose will not throw any errors by default if you use a model without connecting.

Solution - Wait for mongoose to connect before you start doing db queries.
Read - https://javascript.info/async-await


text:
Q: C++ - Escaping or disabling backslash on string I am writing a C++ program to solve a common problem of message decoding. Part of the problem requires me to get a bunch of random characters, including '\', and map them to a key, one by one.
My program works fine in most cases, except that when I read characters such as '\' from a string, I obviously get a completely different character representation (e.g. '\0' yields a null character, or '\' simply escapes itself when it needs to be treated as a character).
Since I am not supposed to have any control on what character keys are included, I have been desperately trying to find a way to treat special control characters such as the backslash as the character itself.
My questions are basically these:

*

*Is there a way to turn all special characters off within the scope of my program?

*Is there a way to override current digraphs definitions of special characters and define   them as something else (like digraphs using very rare keys)?

*Is there some obscure method on the String class that I missed which can force the actual character on the string to be read instead of the pre-defined constant?
I have been trying to look for a solution for hours now but all possible fixes I've found are for other languages.
Any help is greatly appreciate.

A: If you read in a string like "\0" from stdin or a file, it will be treated as two separate characters: '\\' and '0'. There is no additional processing that you have to do.
Escaping characters is only used for string/character literals. That is to say, when you want to hard-code something into your source code.


text:
Q: Curl FTP Upload only Modified / Changed Files i wrote a bash script to deploy the relevant files to my web server.
I use curl for the upload mainly because it was pre installed on my mac.
It works fine but i don't want to upload all the files with the deployment because every file is transferred one by one. I did some research in the API documentation of the curl program and on google as well but i did not find any information about an option which let me set curl to only upload modified files.
Has anyone an idea how i can archive this with curl?
#!/bin/bash
recurse() {
 if [ -z ${var+x} ]; then
    dir=$1
 fi
 for i in "$1"/*;do
    if [ -d "$i" ];then
        echo "dir: $i"
        dir=$i
        recurse "$i"
    elif [ -f "$i" ]; then
        curl --ftp-create-dirs -T $i ftp://server/$dir/ --user username:password
        echo "file: $i"
    fi
 done
}

recurse stylesheets
recurse js
recurse bower_components
curl --ftp-create-dirs -T index.html ftp://server/$dir/ --user username:password

This code loops through my stylesheets / js / bower_components folders and creates all subfolders and uploads all files.


text:
Q: CreateComponent stopped working I created an aura component which dynamically inserts components based on component names passed to it and several similar component have been working fine till very recently when they stop. When the execution reaches the $A.createComponent line, the code just stops. The callback is not entered. No errors.  The strangest part is a very impractical workaround i have found. If i copy the component i want to insert directly into a div in the html and make that div display:none;, then the component is inserted by the controller.  The execution enters the callback and the component is inserted. If i remove display:none; then the component appears twice.
Below is a two simplified versions, one that does not work and one that does work but is not workable nor does it make any sense why it works.
Code that does not work:
<aura:component implements="lightning:availableForFlowScreens,flexipage:availableForRecordHome,force:hasRecordId"
                access="global">
    <aura:attribute name="utilityContainer" type="Aura.Component[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <aura:attribute name="recordId" type="String" />
    <aura:attribute name="caseId" type="String" />

        {!v.utilityContainer}

    </aura:component>
<aura:component

({
    init : function(component, event, helper) {
        var caseId = component.get("v.caseId");
            $A.createComponent(
                "c:meshSupport",
                    {
                        "recordId": caseId,
                    },
                    function(utility, status, errorMessage){
                        if (status === "SUCCESS") {
                            var container = component.get("v.utilityContainer");
                            container.push(utility);
                            component.set("v.utilityContainer", container);
                        }
                    }
            );
        }

    },})

If I change the cmp. file to the following, it works:
<aura:component implements="lightning:availableForFlowScreens,flexipage:availableForRecordHome,force:hasRecordId"
                access="global">
    <aura:attribute name="utilityContainer" type="Aura.Component[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <aura:attribute name="recordId" type="String" />
    <aura:attribute name="caseId" type="String" />

        {!v.utilityContainer}

        <c:meshSupport recordId="{!v.caseId}"  />

    </aura:component>
<aura:component

I have tried inserting it from afterrender in the componentrenderer.js and i have tried using the after render event thinking it might have something to do with order of rendering.
I have tried inserting a simple input box into the container first followed by the component. The input was successfully inserted.
Does anyone have any idea at all what is going on?

A: Dane, I have tried to run ur code version 2.
It seems that the error is that, It is unable to create component as if you check for status === "ERROR" and log the error you will get No COMPONENT named markup://c:meshSupport found
And also if possible please put some more info. about the question asked.

A: Since i see that this question has been visited a number of times since I posted it, I'd like to let you know the workaround i use.
So this is regarding the scenario in which you want to be able to pass a component name into an aura component so that the component of that name is truely added dynamically.
According to SF documentation simply adding a dependency tag should provide the frontend with the resources to render the component to be added.
<aura:dependency resource="markup://c:myComponent" type="COMPONENT"/>

This does not work for me.
To ensure that markup is definitely available to the frontend I put the components in an aura:if tag with the variable permanently set to false.
<aura:if isTrue="{!v.library}">
    <c:myComponent1" />
    <c:myComponent2"/>
    <c:myComponent3"/>
</aura:if>

Originally i had this in a div set to display:none; but this a bad option because the components are actually in the mark up, not just available. They exist then in a div with display:none; obviously and in this case then the component JS is also run. When you use an aura if, the component does not appear in the markup and the js is not run accept in the event that you dynamically add it.
I hope this is useful.


text:
Q: Get a struct based on member values I have a huge struct array and I created different function to get the struct pointer based on a member's value:
typedef struct {
    uint32_t a;
    uint32_t b;
    uint32_t c;
    uint32_t d;
} test_t;

test_t test[10]; // Initialized somewhere else

static test_t* __get_struct_by_a(uint_32_t a) {
    for (uint32_t i = 0; i < 10; i++) {
        if (test[i].a == a)
            return &test[i];
    }
    return NULL;
}

static test_t* __get_struct_by_b(uint_32_t b) {
    ...
}

Is there an easy way to tackle this in C instead of create a lookup function for every member?

A: Following is one way to write a general function to get (find) your first matching struct member.
I tried to keep consistent with your sample code, adding a few #include directives that may be necessary, and a typical fixed-array size #define for TEST_SIZE so that you don't use hard-coded values for the loop indices.
#include <stddef.h>
#include <stdio.h>
#include <string.h>

typedef struct {
    uint32_t a;
    uint32_t b;
    uint32_t c;
    uint32_t d;
} test_t;

test_t test[10]; // Initialized somewhere else
#define TEST_SIZE (sizeof(test)/sizeof(test[0]))

static test_t* __get_struct_by_offset(const void* value_ptr, const size_t offset, const size_t field_size)
{
    for (uint32_t i = 0; i < TEST_SIZE; i++)
    {
        if (0 == memcmp(value_ptr, ((unsigned char*)&test[i])+offset, field_size))
        {
            return &test[i];
        }
    }
    return NULL;
}

You would use it like this:
    uint32_t a_value_to_find = 5; /* example field "a" value to find */
    uint32_t b_value_to_find = 10; /* example field "b" value to find */
    test_t* test_ptr;

    /* find specified value for field "a" */
    test_ptr = __get_struct_by_offset(&a_value_to_find, offsetof(test_t, a), sizeof(a_value_to_find));

    /* find specified value for field "b" */
    test_ptr = __get_struct_by_offset(&b_value_to_find, offsetof(test_t, b), sizeof(b_value_to_find));

It's your responsibility to ensure that the data types for *value_ptr and the field at the specified offset are identical, and therefore of the same size (field_size).
To simplify the usage, you could write some macros as shorthand for these calls.  For example:
#define GET_A(value) __get_struct_by_offset(&value, offsetof(test_t, a), sizeof(value))
#define GET_B(value) __get_struct_by_offset(&value, offsetof(test_t, b), sizeof(value))

The queries for "a" and "b" are then simplified to:
    /* find specified value for field "a" */
    test_ptr = GET_A(a_value_to_find);

    /* find specified value for field "b" */
    test_ptr = GET_B(b_value_to_find);


text:
Q: How to set different Value for each loop in IF statement I'm trying to setValue for each cell separately while loop is running.
for (var i = 5; i <= lastRow; i++) { // Start from row 5

  var pos = sheet.getRange([i], 1); // 1 == column A, A=1,B=2,C=3 etc.
  var posValue = (pos.isPartOfMerge() ? pos.getMergedRanges()[0].getCell(1, 1) : pos).getValue(); // get value of marged cell
  var animalColor = sheet.getRange([i], 9); // 9 == column I

  if (posValue == 'Cat') {
    animalColor.setValue('brown');
  } else if (posValue == 'Dog') {
    animalColor.setValue('black');
  } else if {
    animalColor.setValue('none');
  }
}

I want to go from this:

To this:

I tried to write additional IF statements but that just felt dumb and code will get heavier.

A: Create an array of colors for each animal. Then you can get the next value from the appropriate animal's array.

const colors = {
  Dog: {
    colors: ['white', 'black', 'red', 'grey'],
    index: 0
  },
  Cat: {
    colors: ['brown', 'black', 'white', 'gray'],
    index: 0
  },
  Bird: {
    colors: ['yellow', 'red', 'blue', 'purple'],
    index: 0
  }
};

for (var i = 5; i <= lastRow; i++) { // Start from row 5

  var pos = sheet.getRange([i], 1); // 1 == column A, A=1,B=2,C=3 etc.
  var posValue = (pos.isPartOfMerge() ? pos.getMergedRanges()[0].getCell(1, 1) : pos).getValue(); // get value of marged cell
  var animalColor = sheet.getRange([i], 9); // 9 == column I
  if (posValue in colors) {
    animalColor.setValue(colors[posValue].colors[colors[posValue].index++]);
  }
}

A: Alternate solution
You can use the includes,map and setValues methods in getting the desired output. You may use the script below as a guide.
Script:
const colors = {
    "Cat": ["brown", "black", "white", "gray"],
    "Dog": ["white", "black", "red", "gray"],
    "Bird": ["yellow", "red", "blue", "purple"]
  };

function transformTable() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // Get the active sheet
  var range = sheet.getRange("A1:A"); // Get the range of the data
  var values = range.getValues().flat().filter(x => x); // Get the values of the data
  var animalsInData = Object.keys(colors);
  var output = [];

  values.map(x => (animalsInData.includes(x))? colors[x].map(y=>output.push([y])) : output.push([""]));
  sheet.getRange(1,3,output.length,1).setValues(output); // edit the range accordingly
}

Output:

Please note that I have added snake as a test case to see if the script will run even if there is an additional animal outside the colors object.
References:
setValues method
JavaScript Array map
JavaScript String includes


text:
Q: Highchart not showing from JSON data I'm trying to display a line chart with json data, but with there, $_GET from the json I have the chart doesn't appear, here's my code :
$(function () {
            var chart;
            $(document).ready(function() {
                $.getJSON("master/proyek/s-curve.php", function(json) {

                    chart = new Highcharts.Chart({
                        chart: {
                            renderTo: 'scurve',
                            type: 'line'
                        },
                        credits: {
                             enabled: false
                        },
                        title: {
                            text: 'S-Curve Balai'

                        },
                        subtitle: {
                            text: ''

                        },
                        xAxis: {
                            categories: ['M1', 'M2', 'M3', 'M4']
                        },
                        yAxis: {
                            title: {
                                text: ''
                            },
                            plotLines: [{
                                value: 1,
                                width: 1,
                                color: '#808080'
                            }]
                        },
                        tooltip: {
                            formatter: function() {
                                    return ''+ this.series.name +'
'+
                                    this.x +': '+ this.y;
                            }
                        },
                        legend: {
                             layout: 'horizontal',
                        },
                        plotOptions: {
                            line: {
                                dataLabels: {
                                    enabled: true,
                                       distance: 100,
                                }
                            }
                        },
                        series: json,
                    });
                });

            });

        });

and this my s-curve.php :
<?php
header("Content-type: application/json");
require_once "config/database.php";
$db = new database();
$mysqli = $db->connect();
$balai = mysqli_real_escape_string($mysqli, $_GET['balai']);
if ($balai == 'bl-1') {
    $sql = "SELECT plan, actual FROM scurve1 ORDER BY id ASC";
} else if ($balai == 'bl-2') {
    $sql = "SELECT plan, actual FROM scurve2 ORDER BY id ASC";
} else if ($balai == 'bl-3') {
    $sql = "SELECT plan, actual FROM scurve3 ORDER BY id ASC";
}
$hasil = array();
$hasil['name'] = 'Plan';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
    $hasil['data'][] = $data['plan'];
}

$hasil1 = array();
$hasil1['name'] = 'Actual';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
    $hasil1['data'][] = $data['actual'];
}

$nilai = array();
array_push($nilai, $hasil);
array_push($nilai, $hasil1);
print json_encode($nilai, JSON_NUMERIC_CHECK);
$mysqli->close();

display my json from localhost/master/proyek/s-curve.php?balai=bl-1 :
Display Json Data
from my case above, can someone tell what error I can fix to be able to display the chart.