text:
Q: leetcode - number of islands, RecursionError I'm trying to solve the famous problem of "number of islands" from leetcode. (link : https://leetcode.com/problems/number-of-islands/)
I solved this solution using BFS, but I got this error :
"RecursionError: maximum recursion depth exceeded in comparison"
Why I get this error?
I cant figure why.
Here is my code:
def numIslands(grid):
    islands = 0
    for i in range(0, len(grid)):
        for j in range(0, len(grid[0])):
            if(grid[i][j] == "1"):
                islands += 1
                marksZero(grid, i, j)

    print(islands)
    return islands

def marksZero(grid, i, j):

    if(grid[i][j] == "0"):
        return

    grid[i][j] = 0
    if(i - 1 >= 0):
        marksZero(grid, i - 1, j)
    if(i + 1 < len(grid)):
        marksZero(grid, i + 1, j)
    if(j - 1 >= 0):
        marksZero(grid, i, j - 1)
    if(j + 1 < len(grid[0])):
        marksZero(grid, i, j + 1)

numIslands([["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]])

A: You are assigning int instead of string to your grid,therefore condition creates infinite loop.
Change grid[i][j] = "0"
def numIslands(grid):
    islands = 0
    for i in range(0, len(grid)):
        for j in range(0, len(grid[0])):
            if(grid[i][j] == "1"):
                islands += 1
                marksZero(grid, i, j)

    print(islands)
    return islands

def marksZero(grid, i, j):

    if(grid[i][j] == "0"):
        return

    grid[i][j] = "0"
    if(i - 1 >= 0):
        marksZero(grid, i - 1, j)
    if(i + 1 < len(grid)):
        marksZero(grid, i + 1, j)
    if(j - 1 >= 0):
        marksZero(grid, i, j - 1)
    if(j + 1 < len(grid[0])):
        marksZero(grid, i, j + 1)

numIslands([["1", "1", "1", "1", "0"],
            ["1", "1", "0", "1", "0"],
            ["1", "1", "0", "0", "0"],
            ["0", "0", "0", "0", "0"]])

A: you need to add some visit matrix to make sure you are in each cell only once
something like that
visit = [[False ]* 5 ]* 4

def marksZero(grid, i, j):
    if visit[i][j]:
        return
    visit[i][j]=True


text:
Q: Upper bounded wildcard as a Map Value - how to provide a default Value with getOrDefault() I have the following map
Map<Integer, ? extends Collection<Integer>> map

Sometimes there is a List and sometimes there is a Set as a value. Now I'd like to get value, but there is a problem, it does not compile.
Collection<Integer> value = map.getOrDefault(1, Collections.emptyList())

I know I can do something like this:
Collection<Integer> value = map.get(1);
if (value == null) {
     value = Collections.emptyList();
}

But I want to understand how getOrDefault() method is supposed to work with wild-card generics.

A: It's a very vied case - in short, you can't make getOrDefalt() working with an upper bounded Value.
default V getOrDefault(Object key, V defaultValue)

As the second argument, getOrDefalt() expects an instance of type V. That means that the argument should match exactly the type of the Value how it was declared, and in this case it's ? extends Collection<Integer>.
We can not perform type casting using wild cards. This code will be syntactically invalid:
Collection<Integer> value =
    m.getOrDefault(1, (? extends Collection<Integer>) Collections.emptyList()); // will not compile

There's no way to provide the default value of the type that's required.

A: The short of it: You cannot use getOrDefault, at all, with any map whose 'V' is declared to be ? or ? extends Anything. There is no fixing this short of cloning the JDK sources or making a utility method with your own take on getOrDefault.
A getOrDefault implementation is imaginable that would not have this problem. Unfortunately, the OpenJDK sources simply didn't write it properly, or there is some tradeoff I'm not seeing. Unfortunately, 'fixing it' is backwards incompatible, so it's probably never going to happen; we're stuck with the broken getOrDefault. Thank you for this question - by thinking about it, it made me realize it is broken. I now feel bad for not having given feedback on amber-dev when feedback was asked :)
The explanation for why is a bit detailed and requires good intuition and knowledge about how generics work. Put on your thinking cap and read on if you are intrigued!
So, why?

Map<Integer, ? extends Collection<Integer>> map

Okay: This means that this map variable could point at, for example, a new HashMap<Integer, List<Integer>>(). Or, it could point at a new HashMap<Integer, Set<Integer>>() or even a new HashMap<Integer, Collection<Integer>>().

map.getOrDefault(....)

Uhoh. This is not possible. You need to provide a default value, and this default value must 'work' regardless of what the map is actually pointing at - it needs to be the same type as the values in this map are. Imagine you have a Map<Integer, Set<Integer>> - what would work? Well, new HashSet<Integer>() would work. But what would work for all 3 (Set<Integer>, List<Integer>, and Collection<Integer>, and of course any other collection type - there are an infinite amount of them)?
The answer is nothing.
You can't do this. You can't use getOrDefault, at all, here. Well, except if you trivially pass null, literally, which is the only value that is 'all types', but then you should just write .get(k) instead of .getOrDefault(k, null) of course.
The fixed version
This is the implementation of getOrDefault, pasted straight from the OpenJDK sources:
  default V getOrDefault(Object key, V defaultValue) {
     V v;
     return (((v = get(key)) != null) || containsKey(key))
       ? v
       : defaultValue;
  }

This fundamentally is never going to work for you - you can have no V if V is ? anything - that ? means: We do not know what the type is, and there is no typevar that represents it either, so no expression could ever fit. This take on getOrDefault would work fine here:
default <Z super V> getOrDefault(Object key, Z defaultValue) {
  Z z;
  return (((z = get(key) != null) || containsKey(key))
    ? z
    : defaultValue;
}

What's happening here is that in this case, whilst the map is perhaps a Set, or List, etc - you just want it as Collection<Integer>, you don't actually 'care', and you're fine if the default value is not, in fact, a 'V' (If your map is actually a Map<Integer, List<Integer>>, you don't mind if calling getOrDefault ends up giving you an object that is not a List<Integer> - Collections.empty() would not be).
Thus, we need to establish that there is some new type Z which is a supertype of V (thus guaranteeing that if the key is in the map, you get a V, which is definitely a kind of Z, given that Z is a supertype of V as per declaration), and there is a default value that is also definitely of type Z, thus guaranteeing that in either 'branch' (key is found, and key is not found), the returned value is at least Z.
But, map does not work that way, and thus you can't use .getOrDefault, at all.
I don't think modifying getOrDefault at this point would be backwards compatible, so I don't think there is any point filing a feature request with the openjdk core team: They'll just reject it, we're stuck with getOrDefault as written. But, you can make a static utility method if you must have it that does the above. Note that you may want to write it differently - cast to raw, do the work in raw mode, ignore the warnings, and clean up afterwards. In theory some Map implementations could have a different impl of getOrDefault, though I'm having a hard time to imagine what that would look like (unlike, say, computeIfAbsent which absolutely has crucial custom implementations, e.g. in ConcurrentHashMap).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Join Maps in Rdd of tuples I have one single RDD in the form of:
nameResolvedFromHashes: RDD[(Node, String, Option[String], Option[String], Map[String, String])]
My RDD's sample data looks like this:
(<MyXml1>,{MyJson1},Some(1),Some(2),Map(hash1 -> value1))
(<MyXml1>,{MyJson1},Some(1),Some(2),Map(hash2 -> value2))
(<MyXml2>,{MyJson2},Some(3),Some(4),Map(hash3 -> value3))

I want to get something like this,i.e. join the tuples _5 element's maps if the 1st 4 elements are the same.
Output:
(<MyXml1>,{MyJson1},Some(1),Some(2),Map(hash1 -> value1,hash2 -> value2))
(<MyXml2>,{MyJson2},Some(3),Some(4),Map(hash3 -> value3))

I tried:
nameResolvedFromHashes.map(tup => ((tup._1,tup._2,tup._3,tup._4), tup._5)).reduceByKey { case (a, _) => a }.map(_._2)

But it gave only line 2 and 3 of my input as output. Please help.

A: I don't understand the logic of your reduceByKey -> map step. Using a single reduceByKey to sum the maps seems to accomplish your goal. Is there something I'm missing?
scala> val in = Seq(("a", "b", 1, 2, Map((1 -> "c"))),("a", "b", 1, 2, Map((2 -> "d"))),("e", "f", 1, 2, Map((1 -> "g"))))
in: Seq[(String, String, Int, Int, scala.collection.immutable.Map[Int,String])] = List((a,b,1,2,Map(1 -> c)), (a,b,1,2,Map(2 -> d)), (e,f,1,2,Map(1 -> g)))

scala> val rdd = spark.sparkContext.parallelize(in)
rdd: org.apache.spark.rdd.RDD[(String, String, Int, Int, scala.collection.immutable.Map[Int,String])] = ParallelCollectionRDD[14] at parallelize at <console>:25

scala> val done = rdd.map(tup => ((tup._1,tup._2,tup._3,tup._4), tup._5)).reduceByKey { _ ++ _ }.map(tup => (tup._1._1, tup._1._2, tup._1._3, tup._1._4, tup._2)).map{case ((a, b, c, d), e) => (a,b,c,d,e)}`
done: org.apache.spark.rdd.RDD[(String, String, Int, Int, scala.collection.immutable.Map[Int,String])] = ShuffledRDD[16] at reduceByKey at <console>:25

scala> done foreach println
(a,b,1,2,Map(1 -> c, 2 -> d))
(e,f,1,2,Map(1 -> g))


text:
Q: Controlling op amp gain with an mcu, would this work? I need to be able to control the gain of an op amp with an mcu.
I know the obvious way is to use a digital potentiometer or an op amp which was already designed for this purpose.
I am wondering if this will do the trick:

simulate this circuit – Schematic created using CircuitLab
basically the mcu can use the mosfet to switch another resistor in parallel to R2 which would increase the gain from 2 to about 27 in this example.
So i'm thinking to have an array of mosfets, maybe 3 in total or so.
Would that work ?
I realize this would effect the high pass filter of C2-R2.
Another way of doing the same thing is putting R4 in series under R2 and shorting it out with the mosfet.
Which way is preferable ?
Thanks in advance !

A: Since you've run a simulation, go and do an AC sweep to see where the MOSFET capacitance starts to increase the gain (should be MHz, looking at it).
Also, for high signal levels (greater than a few hundred mV input), with the MOSFET off, the MOSFET body diode will cause huge distortion on the negative half cycles. A change in bias could prevent that, but watch out for 'click' effects on gain change  if that is important to you.

A: A good second opinion would be to breadboard it and feed in your expected signal. You have hinted that you are inputting a low frequency signal, thus the change in your filter characteristics should not be an issue. But, the only way to be sure is to break out some parts and give it a try!
I can tell you that I tried to use the second circuit you described to provide adjustable gain on a per sensor basis, and it worked perfectly. I felt it was easier to get the gain steps I wanted while keeping to common resistor values. It's possible to do the Same when the resistors are in parallel but harder to get the balance between the steps you want and the price of the resistors. The sample rate was only about 500Hz, though, so the mosfet capacitance did not mess things up for me.
One thing I should note about your circuit if you do intend to breadboard it, that pull down resistor R5 is going to sink quite a bit of current. If you intend to drive that input with a microcontroller pin, it will have trouble pulling that input high.


text:
Q: Alleviating the Password Explosion Problem Don't you just hate it when your password explodes, letting the magic smoke out of your server, and setting lp0 ablaze?
In all seriousness, the number of places a person needs a username and password is increasing dramatically.  It looks like OpenID won't be solving the problem in the near future, and Single Sign-On seems more like a goal than a reality internally, even disregarding the great big net out there.
I just came from a meeting wherein I was told that we've paid for access to several external sites, and want to lower the bar and increase the likelihood that staff (and students) will make use of these resources.  Those speaking felt that our top five- to ten-percent of users might make use of the sites, but if we could provide a way to log people in to the sites (and give them a launching-off page) that the uptake might increase dramatically (and that we could save tech support money but not having to help people when they forget their passwords.)
What are you doing about this problem in your organization?  Are there any sensible approaches?

A: Kerberos gets you 90% there.  Then you've got to get your browsers passing kerberos tokens to internal websites (look in about:config on Mozilla variants, search for "nego" to see the preferences).
After that, RADIUS-type authentication for the things that require passwords, or LDAP.

A: We're making extensive use of the Central Authentication Service (wikipedia entry). It has plug-ins for a lot of things, and we've managed to use it for services that have separate identity information per-user. I believe it can also be used for services where there is a generic login to a site.

A: There is the keepass option. Keepass can open a website, tab to the correct login fields, type in your username and password and press enter all in one easy click. Put a pre-filled keepass DB on a pendrive and give them to your users, they can store their own passwords in there too.
It might not be good enough for a web-based login system for thousands of users, but it might make users more comfortable that their passwords are secure (and is still a great solution for individual users).

A: Have a look at Sun's Identity Management package OpenSSO.  I believe there is a piece that allows you to create an internal SSO infrastructure that will sign users onto extranet apps.  I'm not 100% positive, but it looks to be open source and maybe free.

A: If the various tools/sites/services support LDAP, while logins may be required, at least they'll be authenticating back to you OpenLDAP or Active Directory infrastructure, so the username and password won't be "new".


text:
Q: How to use opencv::highgui::get_trackbar_position I just posted so recently but I'm new to rust and keep hitting walls with what I imagine is elementary for someone more documentation-literate than I am.
I have been recreating my python code listed here

while True:

    cv2.namedWindow("HSV")
    cv2.resizeWindow("HSV",640,480)
    cv2.createTrackbar("HUE MIN","HSV",0,179,empty)
    cv2.createTrackbar("HUE MAX","HSV",0,179,empty)
    cv2.createTrackbar("SAT MIN","HSV",0,255,empty)
    cv2.createTrackbar("SAT MAX","HSV",0,255,empty)
    cv2.createTrackbar("VAL MIN","HSV",0,255,empty)
    cv2.createTrackbar("VAL MAX","HSV",0,255,empty)

    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret==True:

            hsvframe = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

            h_min = cv2.getTrackbarPos("HUE MIN","HSV")
            h_max = cv2.getTrackbarPos("HUE MAX","HSV")
            s_min = cv2.getTrackbarPos("SAT MIN","HSV")
            s_max = cv2.getTrackbarPos("SAT MAX","HSV")
            v_min = cv2.getTrackbarPos("VAL MIN","HSV")
            v_max = cv2.getTrackbarPos("VAL MAX","HSV")

            lower = np.array([h_min,s_min,v_min])
            upper = np.array([h_max,s_max,v_max])
            mask = cv2.inRange(hsvframe,lower,upper)
            result = cv2.bitwise_and(frame,frame,mask=mask)

            print(lower,upper)

            out.write(mask)
            cv2.imshow('mask',mask)
            pass
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break

I have been trying to recreate this while loop in rust and cant seem to understand how to call the position with opencv::highgui::get_trackbar_pos like cv2.getTrackbarPos
I also dont necessarily understand loop {} and its nuances so im not sure what the equivalent ret, frame = cap.read, if ret==True: would be because it seems like rust's cvt_color handles that so I dont know if it affects where my get_trackbar_pos should be

Lastly I'm really not sure how I should be writing to a lower and upper set of arrays so any advice there would be helpful.
use std::f32::MAX;

use opencv::{ highgui::{self, WINDOW_AUTOSIZE}, imgproc, prelude::*, videoio, Result};

fn run() -> Result<()> {

    let window = "video capture";
    let hsv = "HSV";

    highgui::named_window(window, 1)?;
    highgui::named_window(hsv, 1)?;

    highgui::named_window(hsv, WINDOW_AUTOSIZE)?;
    highgui::create_trackbar("HUE MAX", hsv, None, 179, None)?;
    highgui::create_trackbar("HUE MIN", hsv, None, 179, None)?;
    highgui::create_trackbar("SAT MAX", hsv, None, 179, None)?;
    highgui::create_trackbar("SAT MIN", hsv, None, 179, None)?;
    highgui::create_trackbar("VAL MAX", hsv, None, 179, None)?;
    highgui::create_trackbar("VAL MIN", hsv, None, 179, None)?;

    opencv::opencv_branch_32! {
        let mut cam = videoio::VideoCapture::new_default(0)?; // 0 is the default camera
    }
    opencv::not_opencv_branch_32! {
        let mut cam = videoio::VideoCapture::new(0, videoio::CAP_ANY)?; // 0 is the default camera
    }
    let opened = videoio::VideoCapture::is_opened(&cam)?;
    if !opened {
        panic!("Unable to open default camera!");
    }

    loop {
        let mut frame = Mat::default();
        cam.read(&mut frame)?;
        if frame.size()?.width > 0 {
            let mut gray = Mat::default();

            let h_max = opencv::highgui::get_trackbar_pos("HUE MAX", hsv)?;
            let h_min = opencv::highgui::get_trackbar_pos("HUE MIN", hsv)?;
            let s_max = opencv::highgui::get_trackbar_pos("SAT MAX", hsv)?;
            let s_min = opencv::highgui::get_trackbar_pos("SAT MIN", hsv)?;
            let v_max = opencv::highgui::get_trackbar_pos("VAL MAX", hsv)?;
            let v_min = opencv::highgui::get_trackbar_pos("VAL MIN", hsv)?;

            let _lower = [h_min, s_min, v_min];
            let _upper = [h_max, s_max, v_max];

            imgproc::cvt_color(&frame, &mut gray, imgproc::COLOR_BGR2HSV, 0)?;
            highgui::imshow(window, &gray)?;
        }
        if highgui::wait_key(10)? > 0 {
            break;
        }
    }
    Ok(())

}

fn main() {

    run().unwrap()

}

Here is my main.rs
You can see at the bottom my loop and arrays.
The Rust OpenCV Documentation seems really simple and clear, I'm just fairly rust illiterate and even reading the rust book I'm having trouble.


text:
Q: Python: how to implement copy for base class which works for inherited with new attributes How to implement copy for base class which works for inherited with new attributes w/o implementing __copy__ for inherited class (implying dumb copy for new attributes)?
I.e. we have class with one user-defined and one calculated (or external reference, should not be copied) fields. So copy should create instance, based only on user-defined field:
class A(object):
    def __init__(self, a):
        self.a = a
        self.b = a+1

    def __copy__(self):
        return A(self.a)

At this moment copy works fine.
Then we introduce inherited class, and it's constructor calculates args for base constructor based on it's own args, and also introduce new field, so signature of inherited constructor is completely different and unknown (in common) for base class:
class B(A):
    def __init__(self, c):
        A.__init__(self, c+100)
        self.c=c

At this moment copy obviously works not fine, returning A instance. Of cause we can implement own __copy__ for inherited class, but it's extremely inconvenient, when we introduce some attributes, which should be copied in just ordinary manner. So what I'd like to achieve, is to copy "A part" of inherited class B by A.__copy__, but remains by standard copy, w/o re-implementing __copy__ for all inherited classes. So are there any 'design pattern' for such situations?
UPD:
I'd like to reformulate example from copy to deepcopy, which is more close to real case. So the idea is the same - we have to manage deepcoping of class A, which contains reference which should not bee deepcopied (i.e. link to container, in which object contains). But we don't want to manage deepcoping of inherited classes.
from copy import deepcopy

class A:

    def __init__(self, content, container):
        self.content = content
        self.container = container

    def __deepcopy__(self, memo):
        return A(deepcopy(self.content, memo), self.container)

class B(A):

    def __init__(self, attr):
        A.__init__(self, [1,2,3], self)
        self.attr = attr

b = B(123)
b1=deepcopy(b) # wrong!

Looks like I found the pattern which is suitable in my particular case (thx @mhawke): copy everything first, and then deepcopy only necessary fields.
class A:
    def __deepcopy__(self, memo):
        o = copy(self)
        o.content = deepcopy(self.content)
        return o

But it not solve problem in common case: for deepcopy I'd like to deepcopy inherited attributes, not copy it, and manage deepcoping for overrides only if necessary.

A: For your example, this would work - you "only" have to override _copyattrs -, now I'm not sure this is any better than just overriding __copy__.
class A(object):
    _copyattrs = ["a"]

    def __copy__(self):
        args = [getattr(self, attrname) for attrname in self._copyattrs]
        return type(self)(*args)

class B(A):
    _copyattrs = ["c"]


text:
Q: How to set a recurring AlarmManager to execute code on a scheduled date? I am making a medicine reminder app which reminds people to take their medicine on a scheduled date-time.
For example, if my  start-date is 08-APR-2013 and the end-date is 12-APR-2013 and time is 11.30 am  then the alarm should fire till 12-APR-2013 at 11.30 am.
Please help with how I can achieve this. I know how to set an alarm manager and the normal alarm is fired. But when I have a start-date and end-date at that time I become confused about how I should use the alarmManager.setRepeating() method.

A: this code for repeating alarm for every day
Date dateobj=new Date(Year,month,day,hour,min);
setRepeating(AlarmManager.RTC_WAKEUP, dateobj.getTime(), (24*60*60*1000), pendingIntent);

A: you can do this by setting the alarm at the time you want by using the setReapting() method.
1.Use a table to insert your entries.
2.query the table for every minute or for the time interval you want using a broadcast receiver.
3.In the onReceive() callback compare the current time with the insert time and fire the alarm.
4.if there is no record then cancel the pending intent.

if you have any doubt in this go through this link
.


text:
Q: WCF service is deadlocking Below, I have outlined my WCF service/client setup. When a single client calls IWCFService.Process multiple times in succession the service deadlocks between WCFService.Process and the line in WCFService.Run that executes this.Subscribers.ProcessingCompleted.
An instance of the class WCFService is passed into the ServiceHost constructor and WCFService's Run API is called back from a thread created using QueueUserWorkItem. I am guessing the conflict originates between the thread WCF uses to call into WCFService.Process and the thread WCFService.Run is running under.
I have already added a ServiceThrottlingBehavior to allow 1000 MaxConcurrentSessions and 1000 MaxConcurrentCalls. Can I add attributes on the service or client classes that will prevent this deadlock?
[ServiceContract(Name = "IWCFClient")]
public interface IWCFClient
{
  [OperationContract]
  void ProcessingCompleted(Guid guid);
}

[ServiceContract(Name = "IWCFService", CallbackContract = typeof(IWCFClient))]
public interface IWCFService
{
  [OperationContract]
  Guid Process(string filename);
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class WCFService : IWCFService, WFGenericThread<WFProcessingResult>,
{
  public Dictionary<Guid, IWCFClient> Subscribers { get; set; }
  public override void Run(WFProcessingResult queueobj)
  {
    if(this.Subscribers.ContainsKey(queueobj.Guid))
      this.Subscribers.ProcessingCompleted(queueobj.Guid);
  }

  public Guid Process(string filename)
  {
    Subscribers.Add(guid, (IWCFClient)OperationContext.Current.GetCallbackChannel<IWCFClient>());
    // send filename off to be processed
  }
}

A: Your server is not thread safe.
The InstanceContextMode = InstanceContextMode.Single means WCF is properly preventing multi-threaded access, but your use of the thread pool behind the scenes is not subject to the same restrictions.
You need to make your server thread-safe or don't use the thread pool.
Here's a good introductory article on multi-threading.


text:
Q: writing the composition of map and fold_left as a fold_left Given
f : A -> B -> A
g : A -> A
l : list B
acc : list A

how can I write (map g (fold_left f l acc)) as a fold_left ?
I tried writing something like (fold_left (fun x => (g (f x)) l (map g acc)), but it does not seem to type-check....

A: You write fold_left f l acc, but the arguments of a left fold are supposed to be fold_left f acc l. This could be your problem.


text:
Q: Set height for color input How do I set the height for a color input? I can set the width, but height doesn't work at all.

input {
  border        : #0f0 2px solid;
  border-radius : 5px;
  font-size     : 12px;
  height        : 20px !important;
  width         : 30%;
  background    : #0000;
}
<input type="color" id="color">
<input type="text" value="this one works but not the other">

A: use box-sizing : border-box; first

input {
  box-sizing     : border-box;
  vertical-align : top;
  border         : #0f0 2px solid;
  border-radius  : 5px;
  font-size      : 12px;
  height         : 20px;
  background     : #0000;
  width          : 20em;
  }
  <input type="color" id="color" >

  <input type="text" value="this one works but not the other">


text:
Q: Gtkmm compiling error OS: Windows 7
Compiler: MinGW
IDE: Code::Blocks
I just installed Gtkmm on my computer in the folder C:/gtkmm/ and set up an example program. When I compiled it, it gave the error "gtkmm.h: No such file or directory"
I tried setting the PATH variable to C:/gtkmm/include and C:/gtkmm/gtkmm-2.4, but neither worked. Then I tried using #include "C:/gtkmm/include/gtkmm-2.4/gtkmm.h" and that just gave a ton of errors saying that it doesn't know where a few dozen files are.
I've also heard that you need to put pkg-config gtkmm-2.4 --cflags --libs in the compiler options, but that didn't work either.
What am I doing wrong and how do I fix it?

A: What do you mean with PATH variable? The global windows search PATH for executables? That would be wrong.
You need to look in your IDE for Include search path or header search path or something like that.
Does that pkg-config command work for you when you execute it on the command line? Such a pkg-config when used on a unix system is enclosed in backticks ` which causes it to be substituted by it's output. Don't know if your IDE can do that but if it works from the command line you have at least a list of all includes needed.

A: pkg-config is a helper function for adding cflags and lib paths to the compiler line.
What you will need to do is add the libraries and cflags path to the compiler line. I am not 100% sure how to do that in code::blocks., though
In ubuntu 11.04, you need all these to compile even a simple gtkmm program:
Libs (pkg-config --libs gtkmm-2.4:
-pthread -lgtkmm-2.4 -latkmm-1.6 -lgdkmm-2.4 -lgiomm-2.4 -lpangomm-1.4 -lgtk-x11-2.0 -lglibmm-2.4 -lcairomm-1.0 -lsigc-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lm -lcairo -lpango-1.0 -lfreetype -lfontconfig -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lrt -lglib-2.0
cflags paths (pkg-config --clfags gtkmm-2.4):
-I/usr/include/atk-1.0 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pango-1.0 -I/usr/include/freetype2 -I/usr/include/libpng12 -I/usr/include/gio-unix-2.0/ -I/usr/include/gtkmm-2.4 -I/usr/lib/gtkmm-2.4/include -I/usr/include/atkmm-1.6 -I/usr/include/giomm-2.4 -I/usr/lib/giomm-2.4/include -I/usr/include/pangomm-1.4 -I/usr/lib/pangomm-1.4/include -I/usr/include/gtk-2.0 -I/usr/include/gtk-unix-print-2.0 -I/usr/include/gdkmm-2.4 -I/usr/lib/gdkmm-2.4/include -I/usr/include/glibmm-2.4 -I/usr/lib/glibmm-2.4/include -I/usr/include/sigc++-2.0 -I/usr/lib/sigc++-2.0/include -I/usr/include/cairomm-1.0 -I/usr/lib/cairomm-1.0/include -I/usr/include/cairo -I/usr/include/pixman-1 -I/usr/lib/gtk-2.0/include -I/usr/include/gdk-pixbuf-2.0
Basically you would have to change every instance of /usr/include/ and /usr/lib/ to c:\path-to-library\
I am not sure how much of the above you need with MinGW, but with GCC on Linux, dropping any of them makes gtkmm programs not compile. Hope that at least puts you on the right path.

A: Use autotools C++ project. You need only edit two files configure.ac and Makefile.am.
Add this line to configure.ac
PKG_CHECK_MODULES([GTKMM], [gtkmm-3.0])

and these lines to Makefile.am
program_CPPFLAGS = $(GTKMM_CFLAGS)

program_LDADD = $(GTKMM_LIBS)


text:
Q: Why does this give me an error "must be valid ipv4 cidr"? If I set up an AWS VPC with CIDR of 10.0.0.0/20 then the range is 10.0.0.0 to 10.0.15.255
I make a subnet now. Why does 10.0.15.15/28 give an error. Isn't it's range 10.0.15.15 to 10.0.15.30 which is within the VPC?

A: See this site for some help.  10.0.15.15/28 is 10.0.15.0 to 10.0.15.15.  Perhaps you wanted 10.0.15.15/27 which goes to 10.0.15.31.


text:
Q: Fitness function in a Genetic Algorithm in Python I'm trying to code a proper fitness function for a problem that we've choose to solve with a GA.
The problem consists in identifying the start dates of production for different items and minimize the occurrences of conflicts in available hours of the machines used in each step of transforming raw material into a final product.
The problem is that I'm little lost in the fitness function and I don't know how to proceed.
I've calculated for each machine the total load for each production day in a range, finally, I've calculated the total sum of overload days and I'm using this as my "note" for every possible solution in my GA.
Right now is quite simple, is returning the values and I think problably is wrong in the concept of the fitness function.
    def evaluate(self, scenario):
        sum_overload = calculate_load_machine(self.reference_date, scenario).to_numpy().sum()
        self.evaluation_note = sum_overload

For example:
I've a table for machines as index and production days as columns, for each day the production load is calculated and if it surpass 1.00 (100% of load capacity) the machine is considered overloaded.

Machines
20/02/2023
21/02/2023
22/02/2023
23/02/2023

mA
0.86
0.80
0.74
0.90

mB
0.90
0.51
0.86
1.10

mC
0.33
0.25
0.24
0.50

mD
1.20
1.15
0.99
0.95

The overload table is presented as:

Machines
20/02/2023
21/02/2023
22/02/2023
23/02/2023

mA
0.00
0.00
0.00
0.00

mB
0.00
0.00
0.00
1.00

mC
0.00
0.00
0.00
0.00

mD
1.00
1.00
0.00
0.00

The result of calculate_load_machine for the overload table is 3.
I am thinking about changing the fitness function to be based in the total number of items I can do in a day, like, for each machin mN, I've a composition of different products that are contributing to the load capacity of a machine, therefore, I should choose which product I would do in order to not overcharge the machine.
Any review, advice or comment is valid, thank you for your help!

A: I think that your approach is a good one. However, you may want to to complete penalization for ovrload rewarding solutions that have efficient use of machine time. Assign a higher fitness score to solutions that make use of available machine capacity without overloading, and penalize solutions that leave machine time unused.
An approach is the following. Here you can adjust the conflict penalty (conflict_penalty = 0.5 ) and the machine overload (machine_overload = df/4-1. Here I assume 4 items per machine per day)
import pandas as pd

class FitnessEvaluator:
    def __init__(self, reference_date):
        self.reference_date = reference_date
        self.evaluation_note = None

    def evaluate(self, scenario):
        total_overload = calculate_load_machine(self.reference_date, scenario).to_numpy().sum()
        items_per_day = calculate_items_per_day(scenario)
        total_items = items_per_day.to_numpy().sum()
        conflict_penalty = calculate_conflict_penalty(scenario)
        fitness = total_items - total_overload - conflict_penalty
        self.evaluation_note = fitness
        return fitness

def calculate_load_machine(reference_date, df):
    reference_day = pd.to_datetime(reference_date, format='%d/%m/%Y')
    days = (pd.to_datetime(df.columns, format='%d/%m/%Y') - reference_day).days
    machine_overload = df/4-1
    for day in days:
        if day > 0:
            machine_overload.iloc[:, day] += machine_overload.iloc[:, day-1]
    return machine_overload

def calculate_items_per_day(df):
    return df.sum()

def calculate_conflict_penalty(df):
    machines = df.index
    items = df.columns
    conflict_penalty = 0.5
    for item in items:
        machines_with_item = df.loc[df[item] > 0].index
        if len(machines_with_item) > 1:
            conflict_penalty += len(machines_with_item) - 1
    return conflict_penalty

items_data = {'20/02/2023': [0.86,0.80,0.74,0.90],
              '21/02/2023': [0.90,0.51,0.86,1.10],
              '22/02/2023': [0.33,0.25,0.24,0.50],
              '23/02/2023': [1.20,1.15,0.99,0.95]}
items_per_day = pd.DataFrame(items_data, index=['m1', 'm2', 'm3', 'm4'])

overload_data = {'20/02/2023': [0, 0, 0, 1],
                 '21/02/2023': [0, 0, 0, 1],
                 '22/02/2023': [0, 0, 0, 0],
                 '23/02/2023': [0, 1, 0, 0]}
total_overload = pd.DataFrame(overload_data, index=['mA', 'mB', 'mC', 'mD'])

fitness_evaluator = FitnessEvaluator(reference_date='20/02/2023')

items_per_day_fitness = fitness_evaluator.evaluate(items_per_day)
print(f'Fitness of items_per_day: {items_per_day_fitness}')

total_overload_fitness = fitness_evaluator.evaluate(total_overload)
print(f'Fitness of total_overload: {total_overload_fitness}')

which retunrs:
Fitness of items_per_day: 32.220000000000006
Fitness of total_overload: 40.5


text:
Q: Android widget installation I have a problem with the widget. This is a simple widget counting down to a fixed date. The problem is that some devices do not want to install the widget. On the emulator in eclipse is the same one to another does not work. Does not have any errors.
What is the cause?

A: You can get all the information on the cause for this by deploying your application through an IDE such as IntelliJ Idea, or Eclipse.
In IntelliJ Idea, after building all files, during deployment the Run dialog shows you the status of the install. In case of a failure it would display the reason too.
Generally during debugging it's reasons like installations from different machines (which would show something like [INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES]). It might be  due to the keystore from where the certs are installed has changed.


text:
Q: Vb.net sum identical array elements I have an array with elements 10,11,11,11,17,17,20.
I want to add elements which are the same (ie. 11 and 17), so that the array now has elements 10,33,34,20.
How can I do that?

A: This should do it:
var arr = new[]{ 10,11,11,11,17,17,20 };
arr = arr.GroupBy (x => x).Select (x => x.Sum()).ToArray();


text:
Q: Need to increase Timeout for URLFetch.Fetch(url) I have a Keynote API that I use to provide metrics for Week to Date, Month to Date, and Year to Date performance Metrics.  The Week to date responds quickly, Month to Date sometimes Times out, and Year to Date always times out due to server side calculations.
Is there any way to increase the Timeout for my Google Script?
var prods = Utilities.jsonParse(UrlFetchApp.fetch(json_api_url).getContentText());

A: There are ways to get Google Apps Script to handle time-outs when performing repeated operations, but they don't apply in this case. You've got a single operation that just takes a long time.
You have no way to increase the timeout values for your google scripts.


text:
Q: Authentication user to web application from desktop application I am a novice programmer. I need write desktop application, where user enters the username and password. After clicked on button calls the method Start class Process. Unfortunately, appears in an error message System.ComponentModel.Win32Exception, username or password is incorrect.
My code:
//Download data
String user = this.textBoxUser.Text;
String pass = this.textBoxPassword.Text;

//Password
 SecureString secret = SecureStringConverter.ConvertToSecureString(pass);
//Webbrowser
string file = "chrome.exe";
string domain = @"http://localhost:62074/";
//Process start
Process proc = new Process();

Microsoft.Win32.RegistryKey subKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"http\shell\open\command");
String DefaultBrowser = subKey.GetValue(null).ToString();

if (DefaultBrowser != null)
{
   int startIndex = DefaultBrowser.IndexOf("\"") + 1;
   int endIndex = DefaultBrowser.IndexOf("\"", startIndex);
   string RegDefaultBrowserPath = DefaultBrowser.Substring(startIndex, endIndex - startIndex);

   proc.StartInfo.FileName = RegDefaultBrowserPath;
   proc.StartInfo.Arguments = domain;
   proc.StartInfo.UseShellExecute = false;
   proc.StartInfo.LoadUserProfile = false;
   proc.StartInfo.UserName = user;
   proc.StartInfo.Password = secret;
   proc.Start();
}

And this method to convert string to SecureString
public static class SecureStringConverter
{
   public static SecureString ConvertToSecureString(string password)
   {
      if (password == null)
         throw new ArgumentNullException("password");

      unsafe
      {
         fixed (char* passwordChars = password)
         {
            var securePassword = new SecureString(passwordChars, password.Length);
            securePassword.MakeReadOnly();
            return securePassword;
         }
      }
   }
}

A: I don't think your approach will work. At least not as simple as you might expect it to happen. You may get it working by launching Internet Explorer with explicit credentials to authenticate against applications hosted in IIS, as they may be configured to use domain account for authentication. This scenario essentially is for Intranet web applications. With Crome it is a completely different story.
Merits of your approach are completely not obvious. It is expected that credentials of user logged in to Windows are used for authentication. With your idea, it sounds more like someone else signs in to Windows for me, and I use my own credentials to run web app, but still use remaining windows apps with someone else's credentials.
The following article should give you an idea that it will depend on infrastructure support, and specific sign in process, not just as simple as forwarding explicit credentials to get it working with external web applications who knows nothing about your domain:
https://support.google.com/a/answer/60224?hl=en


text:
Q: How to revert Application.Volatile? When I started to code my Excel tool, I defined a function as Application.Volatile because I wanted it to recalculate each time a value was changed in the spreadsheet :
Function myFunction()
    Application.Volatile
    'body of my function
End Function

Once my code got complex, I realized that this function being volatile was called millions of times when executing, slowing down violently the performance of the tool.
I hence decided to take it down and make it not volatile.
However, I've tried:

*

*To just remove the Application.Volatile from the function, and still when I was changing one parameter the function was recalculating --> this was probably expected as described here, once I say Application.Volatile I give a True value by default in parameter.

*As described on the documentation above, I tried to explicitly write in the body of my function Application.Volatile False. Still, no chance.

I have tried to close down Excel, re-compile the code, no chance: my function doesn't want to stop being Volatile.
Can anyone please help me to understand where the problem is?


text:
Q: update facebook graph API to v2.7 I need to update Facebook graph API to use the latest one i.e. v2.7. In previous implementation I don't see any version number implemented in code. Could you please help me how do we implement latest version for facebook graph API.
Thank You
Harish Singh

A: API Upgrade Tool
: https://developers.facebook.com/tools/api_versioning/
...or just add the version tag in your API calls/paths, which is explained in the changelog: https://developers.facebook.com/docs/apps/changelog
Example:
https://graph.facebook.com/v2.7/me?access_token=xxx

A: For facebook version update, here is the latest guide I found (to facebook lib version 2.8): https://developers.facebook.com/docs/apps/changelog

*

*You need go to the facebook "API updated tool" (an online page), and upgrade the API version you facebook app use. Facebook will track whether you call need be updated using the newest API

*May be you also need to update the sdk for your script: (for example for the python in ubuntu)

sudo pip install -U facebook

The above cmd may not work because the pip repository not have a new version yet, then you need to download the source code of the new API in the git page, unzip the code, in the folder where you unzip the code, run the install cmd yourself :

sudo python setup.py install

see latest facebook python API guide page https://github.com/facebook/facebook-python-ads-sdk
Zhihong


text:
Q: Magento admin login page is blank also the product category pages when i try to enter my magento admin loign page like (domain.nl/admin), it gives me blank page. I am using magento 1.9. also when i click in my website category page or any other product page is blank. Please help me .. please

A: If magento admin is showing a blank page then first you need to enable display_errors from index.php. Simply uncomment the line like below:
Replace #ini_set('display_errors', 1);
With ini_set('display_errors', 1);
Now you can see the exact error and resolve it accordingly.


text:
Q: RegOpenKeyEx function returns access denied error code 5 for reg key path containing'{ }' I am trying to call RegOpenKeyEx function on reg key path for an app with Read permission in registry. I tested the call with another Reg key without the '{ }' in path and that works.
What am I missing ?
Edit
I have also tried requesting different security descriptor: KEY_READ,  KEY_QUERY_VALUE. Adding code snippet below.
I receive a return code 5. I am able to read other RegKeys from the same process which don't have a {}(receive error code SUCCESS i.e. 0).
LONG retCode = ::RegOpenKeyExW(
        hKeyParent,
        subKey.c_str(),
        REG_NONE,
        STANDARD_RIGHTS_READ,
        &hKey);

    if (retCode != SUCCESS)
    {
        return false;
    }

    Close();

    m_hKey = hKey;

    _ASSERTE(retCode == SUCCESS);
    return retCode == SUCCESS; code here


text:
Q: Redirect user to a specific page if he acesses a conference with id that dont exist I have this route:
Route::get('conference/admin/{id}',
[ 'uses' => 'ConferenceController@admin',
'as'=>'conference.admin']);

So when the user acesses "http://proj.test/conference/manage/1" it acesses the page homepage of the conference admin area.
But if this specific conference is removed if the user acessses "http://proj.test/conference/admin/1" it appears a page with this message:
Sorry, the page you are looking for could not be found.
But, if the conference dont exist and the user acesses  "http://proj.test/conference/admin/1" what should happen is the user be redirected to the homepage ('/').
Do you know how to achieve that?
I already have in the AuthServiceProvider the code below to allow only the user that is the creator of the conference to acess the admin area of that conference. I dont know if this can be used also to redirect the user to ('/') if he acesses a conference that dont exist.
// auth service provider gate
 public function boot(GateContract $gate)
    {
        $this->registerPolicies();

        $gate->define('access-management-area', function($user, $conference)
        {
            return $user->id == $conference->organizer_id;
        });
    }

Then in the admin() the gate is used:
   public function admin($id){
        $conference = Conference::findOrFail($id);
        if(Gate::allows('access-management-area', $conference)) {
            return view('conference.admin')->with('conference',$conference);
        } else {
            return redirect('/');
        }
    }

A: You are performing a findOrFail lookup, this will always return a 404 when it fails to find a record.
You could do the following:
 public function admin($id){
    $conference = Conference::find($id);

    if(!$conference){
      return redirect('/');
    }

    if(Gate::allows('access-management-area', $conference)) {
        return view('conference.admin')->with('conference',$conference);
    }
    else{
        abort(403);
    }
 }


text:
Q: Cocoapods/git 'detached HEAD' state have an issue with cocoapods/git.
I'm trying to add new pod to the project and get the following issue. The point is a team member didnt get the issue when he tried to add the Pod to the project.
Tried to reinstall/update cocoapods, git, delete and re-clone a repo.
I've installed previous SDK version and everything fine, but the latest is failed
Installing RescueSDK 4.0.1

[!] Error installing RescueSDK
[!] /usr/local/bin/git clone https://github.com/LogmeinRescue/iOS-SDK.git /var/folders/sp/59sclxxd21590rgz5bvwf8zw0000gn/T/d20190313-28582-12gul24 --template= --single-branch --depth 1 --branch 4.0.1

Cloning into '/var/folders/sp/59sclxxd21590rgz5bvwf8zw0000gn/T/d20190313-28582-12gul24'...
Note: checking out '913aeaa7da9a1b2140525154bfc2beefde5f4214'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

git-lfs filter-process: git-lfs: command not found
fatal: the remote end hung up unexpectedly
warning: Clone succeeded, but checkout failed.
You can inspect what was checked out with 'git status'
and retry the checkout with 'git checkout -f HEAD'

A: The problem has been solved with following steps:

*

*uninstall git

*remove git config file

*install git

*....

*Profit


text:
Q: Value of type '' cannot be converted to  I'm working on a project that uses the testing tool built into VS 2008.
Periodically I will see an error comparable to:
Value of type 'AcademyPro.Code.BLL.Appearance' cannot be converted to 'AcademyPro.Code.BLL.Appearance'. Type mismatch could be due to the mixing of a file reference with a project reference to assembly 'AcademyPro'. Try replacing the file reference to 'academypro.dll' in project 'AcademyPro' with a project reference to 'AcademyPro'.
Now, on one level the error is correct, there is a project reference (required for the code to compile) and a file reference (in a file called AcademyPro.accessor)
If I remove either of these references then the test project fails to compile. I have tried removing both references, cleaning the build and adding them back in. this doesn't seem to help.
It seems I'm in a lose lose situaltion, I need the project reference to compile and I need the accessor reference so that the private object accessors are built, which I need to be able to compile.
What do I need to do to get this compiling again?

A: After much digging around I discovered that the project I was trying to test (not the unit test project) has a project reference to itself. I don't know why or how it would have a reference to itself, but it did. I removed this reference and now everything compiles properly.

A: I also got the same problem, i fixed it by remove all the references of the project, reopened solution again and then added the references, it worked for me. (Got this solution from google)


text:
Q: How to update an object key value based on other key value in Array of object in React? I need to understand how we can update an object key value based on other key value in Array of object in React. Let' assume I have two different input field which is somehow link with the below formatted object, this object basically responsible for changing behavior of graph whenever I type something in input field. The below object passed into Graph component to show the changes whenever we type something in 2 input field.
import React, {useState} from "react";
import ReactDOM from "react-dom";
import { GaugeChart } from "@carbon/charts-react";
import "@carbon/charts/styles.css";

// in the data object graph behavior will update based on
input provided in two input field and that will happen based on group key value

    const graphObj = {
        data: [
            {
                "group": "value",
                "value": 40
            },
            {
                "group": "delta",
                "value": 1000
            }
        ],
            options: {
            "resizable": true,
            "height": "250px",
            "width": "100%",
            "gauge": {
                "type": "semi",
                "status": "danger"
            }
        }
        };

const App = () => {

    const [graph, setGraph] = useState(graphObj);
    const [formData, setFormData]  = useState({
        min: 40,
        max: 1000
    })

    const handleChange = (e) => {

    }

 return (
        <>
        <GaugeChart
            data={graph.data}
            options={graph.options}>
        </GaugeChart>

        <form>
            <input value={formData.min} onChange={handleChange}  />
            <input value={formData.max} onChange={handleChange}/>
        </form>
        </>
    );
}

export default App;

ReactDOM.render(<App />, document.getElementById("root"));

A: Assuming that min in your state is value and max is delta, I would refactor a bit. Since your graphObj is a constant that we just want to add the formData to we can use useMemo that we remake the graphOptions object everytime form data updates.
import React, { useState, useMemo } from "react";
import ReactDOM from "react-dom";
import { GaugeChart } from "@carbon/charts-react";
import "@carbon/charts/styles.css";

const graphObj = {
  data: [
    {
      group: "value",
      value: 40,
    },
    {
      group: "delta",
      value: 1000,
    },
  ],
  options: {
    resizable: true,
    height: "250px",
    width: "100%",
    gauge: {
      type: "semi",
      status: "danger",
    },
  },
};

const App = () => {
  const [formData, setFormData] = useState({
    value: 40,
    delta: 1000,
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    // update the form data
    setFormData({ ...formData, [name]: value });
  };

  // add form data to graph object
  const graphData = useMemo(() => {
    // formdata to { group: key, value: value } type
    return Object.keys(formData).map((key) => ({
      group: key,
      value: formData[key],
    }));
  }, [formData]);

  return (
    <>
      <GaugeChart data={graphData} options={graphObj.options}></GaugeChart>

      <form>
        <input name={"value"} value={formData.value} onChange={handleChange} />
        <input name={"delta"} value={formData.delta} onChange={handleChange} />
      </form>
    </>
  );
};

export default App;


text:
Q: For iOS, has anyone created NSDate extensions for commonly used date-related operations? For iOS, has anyone created NSDate extensions for commonly used date-related operations?  What I've done so far is shown below.  I can imagine a lot more here.
#import <Foundation/Foundation.h>

@interface NSDate (Utilities)

// daysOffsetBy -- denotes how many days to offset the current date
// before calculating midnight.  Here are some examples of how this
// parameter works:
//
//   - if 0, then get the next immediate midnight.
//   - if -1, then get yesterday's midnight (ie, early morning today).
//   - if +1, then get tomorrow's mignight.

- (NSDate *)midnight:(NSInteger)daysOffsetBy;

// Use this method to transpose a time-of-day, specified in self,
// to an arbitrary reference date, specified in refDate.  For example,
// suppose the time-of-day in self is 10:30 AM, and the calendar date
// is 1995-07-21.  Suppose further that the calendar date for refDate
// is 2012-05-22, and that the time-of-day for refDate is 17:00 PM.
// This method creates a new date:  2012-05-22 10:30 AM.

- (NSDate *)transposeToDate:(NSDate *)refDate;

// Return YES if the

- (BOOL) occursInside:(NSDate *)fromTime throughTime:(NSDate *)toTime;

@end

with the corresponding implementation:
#import "NSDate+Utilities.h"

static double SECONDS_IN_DAY = 24*60*60;

@implementation NSDate (Utilities)

- (NSDate *)midnight:(NSInteger)daysOffsetBy {
    NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDate *refDate = [NSDate dateWithTimeInterval:(SECONDS_IN_DAY * daysOffsetBy) sinceDate:self];
    NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
                                                          NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:refDate];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];

    NSDate *retval = [gregorian dateFromComponents:components];
    return retval;
}

- (NSDate *)transposeToDate:(NSDate *)refDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:self];
    double secondsTranspiredInDay = [components second] + [components minute] * 60 + [components hour] * 60 * 60;

    NSDate *retDate = [NSDate dateWithTimeInterval:secondsTranspiredInDay sinceDate:[refDate midnight:0]];
    return retDate;
}

- (BOOL) occursInside:(NSDate *)fromTime throughTime:(NSDate *)toTime {
    BOOL retval = NO;
    NSComparisonResult c0 = [self compare:fromTime];
    NSComparisonResult c1 = [self compare:toTime];
    if ((c0 == NSOrderedSame || c0 == NSOrderedDescending) && (c1 == NSOrderedSame || c1 == NSOrderedAscending)) {
        retval = YES;
    }
    return retval;
}

@end

Some extras that come to mind are obvious:  addDays, addMinutes, addSeconds, etc.  Also helpful would be for NSDate-formatters to be integrated into this category.

A: Yes, quite a few people have built categories on NSDate.
You can find a number of them by searching github: https://github.com/search?langOverride=&q=nsdate&repo=&start_value=1&type=Repositories


text:
Q: How to organize OO js code in files? Local network application I'm currently developing an application that will be run on local network in B2B environment. So I can almost forget about micro(mini?) optimizations in terms of saving bandwidth because Hardware Is Cheap, Programmers Are Expensive.
We have a well structured Object oriented js code in the project and obviously lots of js classes. If all the classes will be stored in separated files then it will be quite easy to navigate through this code and hence maintain it.
But this will bring my browser to generate a couple dozens of HTTP requests to get all the js files/classes I need on the page. Even in local environment it is not super fast on first load(with empty cache), and later when you modify it and cache has to be invalidated.
Possible solutions:

*

*violate rule "one class per file"

*use YUI compressor all the time(in development & production) for generating one big js file.

But if we choose YUI compressor for this(no minify action in dev environment, and minify for production) - then we need to reload/recompile this big js file on every modification in any js file.
What would you recommend for solving this problem?

A: Keep all the .js files separate.  Keep your "one class per file" rule.
Then, use a server-side technology to aggregate the script into one request.
Options:

*

*Use an ASPX or PHP or whatevver server-side scripting thing you have, to aggregate all the JS into one request.   The request for a .js is no longer a static file, but with caching on the server it should be relatively cheap to serve.

*Use Server Side Includes in a consolidated .js file.
<!--#include virtual="/class1.js"-->
  <!--#include virtual="/class2.js"-->

A: Your approach of having separate files for each class is good - practices that make development easier are always good.
Here's some tips for making the loading faster:

*

*Compress your code. As you say, you could use YUICompressor, or the newly released Google Closure Compiler.

*When concatenating multiple files into one, think of what you need and when: If you only need files A, B and C when the app starts, but not Z and X, put only A, B and C into a single file. Load another file with Z and X concurrently after A/B/C.

*You can use Firefox plugins YSlow and Page Speed to test for load performance bottlenecks

As you mention, you would need to rerun the compressor each time you make a change. I don't think this is a big problem - on a decent machine, it should run pretty fast even with a lot of files. Alternatively, you could use a daily build process using some tool, which could build the latest revision from your source control (you do use scm, right?), and run unit tests and deploy if everything goes OK.
I would recommend using Ant or some other automation tool to create a build script. This will make it as simple as running one command to build your compressed script, reducing the repetitive work you would otherwise need to do. You could even have Ant deploy your code to the server.

A: You may have the best of both worlds - a development environment with one class per js file without the need to compile/deploy for every iteration AND one (or several) concatenated larger js files (minified if desired) in production.
Depending on your build environment this may be setup in a number of different ways, but using Ant may be the easiest way. Using Ant you can run tasks for both concatenation and minification (running YUICompressor through the Java task). This will produce the concatenated and minified large js file.
However, to maintain productivity you want to avoid doing this for every code iteration. Changing the  tags from one to several (for every class file) is out of the question.
So, you load your big js file as expected:
<script src="application.js"></script>

When deploying to production this file is the concatenated/minified version of all your js files.
However, during development this file is a bootstrap/loader file that simply loads all your individual js-files (illustrative example using jQuery).
$.getScript('/class1.js');
$.getScript('/class2.js');
$.getScript('/class3.js');
$.getScript('/class4.js');
$.getScript('/classn.js');
....

If you are using YUI 3 look into the module behavior and how to specify dependencies.
Using different Ant targets the generation and copying of these files to the correct location may easily be managed.
And now you may simply reload your browser whenever you need to test a change in a file, but get the performance benefit during production. All without sacrificing productivity or maintainability.


text:
Q: Finding Big Theta I am in a Data Structures and Algorithms class. I am trying to indicate if f(n) is Big Theta of g(n). I will also have to indicate Big O, small o, etc... but I am lost about the way to approach this particular pair.
f(n) = log* (log n)
g(n) = log( log* n )

From what I have currently learned, if this pair completes this statement
Θ(g(n))={f(n):there exists c_1, c_2 > 0 and n_0 <br>
 such that 0 ≤ c_1 g(n) ≤ f(n) ≤ c_2 g(n) for all n ≥ n_0}.

My problem is that I have no idea what log * is and how to use it.

A:
I have no idea what log * is

Well, look it up. Unfortunately, Google doesn't search for symbols too well, but Googling log star turns up the iterated logarithm immediately, and SymbolHound, a search engine that doesn't ignore symbols, turns up a StackOverflow post explaining it. It's also probably in your book or course notes somewhere.
The iterated logarithm, denoted log*(n), is the number of times you need to take the logarithm of n before you get a value less than or equal to 1.
To solve the problem, consider the following. If you need to take the logarithm of n log*(n) times before you get a value <= 1, how many times do you need to take the logarithm of log(n) to do the same thing?


text:
Q: MySQL column type "TIMESTAMP" implicitly includes "NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP" I've just spent a couple of hours tracking down this bug. Given the following SQL:
DROP DATABASE IF EXISTS db;
CREATE DATABASE db;
CREATE TABLE db.tbl (t1 TIMESTAMP) ENGINE=INNODB;
SHOW CREATE TABLE db.tbl;

The last line shows me:
'CREATE TABLE `tbl` (
  `t1` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1'

Where on earth does the NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP come from? I didn't write any of that, and I very much do not want any of that, and I'm kinda lost for words that MySQL would make such a presumption.
Do I have some insane obscure configuration option turned on/off? Is this default behavior? It is a bug? In any case, how do I make MySQL behave sanely?

A: Thos are default values which are being used even if not explicitly stated in the CREATE statement. If you want to avoid both, use t1 TIMESTAMP DEFAULT 0 or ts1 TIMESTAMP NULL DEFAULT NULL
Update
Prior to MySQL 5.6.5 you could only use TIMESTAMP in case you wanted to have column that is automatically updated when row is changed. Unfortunately this functionality was limited to MyISAM and isn't available on InnoDB tables.
MySQL 5.6.5 allows this with DATETIME as well. See other posts on this site for more details

A: In MySQL 5.6.5 there are several updates regarding this initialization, you can see on this link (Automatic Timestamp Properties Before MySQL 5.6.5).
If you're using MySQL <= 5.6.5, in order to ignore this initialization you need to set the DEFAULT value to 0 or NULL with NULL allowed.
CREATE TABLE tbl
(
    field1 TIMESTAMP DEFAULT 0,
    field2 TIMESTAMP NULL DEFAULT NULL
)

If you're using MySQL >= 5.6.6, there is parameter called explicit_defaults_for_timestamp which is disabled by default. You can enable this setting or set the DEFAULT value to 0 or NULL, same approach for previous MySQL versions.
If you're using MySQL >= 8.0.2, then explicit_defaults_for_timestamp is enabled by default. This disables the non-standard behaviour (thankfully). Also, MySQL generates a warning when you disable this setting. So, for instance, if you don't define DEFAULT value for a TIMESTAMP column, it is automatically set to NULL.


text:
Q: What is the time complexity of this program to calculate the binomial coefficient and in what ways can I improve it? #include<iostream>

using namespace std;

int n=10, k=4;
int ar[10];
void cof(int, int);

int main() {
    ar[0] = 1;
    cof(n,k);
    return 0;
}

void cof(int n, int k) {
    for (int i=1;i<n;i++) {
        ar[i] = (i+1)*ar[i-1];
    }
    int l = ar[n-1] / (ar[n-k-1]*ar[k-1]);
    cout << l;
}

The code uses the function cof() to calculate permutation values till n and then uses them for n and k to calculate the binomial cofficient.


text:
Q: Realistic data generator package available for Django I have created a dummy app. I want to insert some fake entries in my models.User models (fake entries should be valuable text, not be a random text). Is any Django package available for generating fake entries?
I have spent lots of my time searching for Django packages that generate fake entries. I found a Python library, fake-factory, for generating fake data, but with that we need to create every field manually, I don't want this. Is there any solution instead of this?

A: You may need to try Mixer. It Provides fakers tool to generate most of the useful items for database.
if this is you user model:
class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128), unique=True)
    email = db.Column(db.String(255), unique=True)
    city = db.Column(db.String(255))
    country = db.Column(db.String(255))

you query will be:
from mixer import fakers as f
from models import User

name = f.get_name()
country = f.get_country()
email = f.get_email()
city = f.get_city()

s = db.session
user = User(name=name, email=email, city=city, country=country)
s.add(user)
s.commit()
s.close()

You can more details Here :
https://mixer.readthedocs.org/en/latest/fakers.html


text:
Q: MobileConnect - No way to update mobile number, therefore deleting priority 2 numbers? According to Salesforce Support, there is no way to overwrite the existing number on subscribers in mobile connect. By uploading an existing subscriberkey with priority 1 and a new number, this will get added as the primary number - but the old one will still exist as part of me.
In the short run, this is not an issue. But in the long run, given that numbers are recycled, we need a maintenance job to clear out priority 2 numbers.
Does any of you have experience of this via the API ? (indicated by the support team). I cannot find a documented way, when investing the mobile connect apis https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/using-the-mobileconnect-api.htm

A: The support came back with a more definitive reply:
"I have checked your concerns with the team and they have explained that each MobileNumber associated with a particular contact would log the information about things sent to it under the MobileNumber that they had come from. As there can be multiple MobileNumbers per contact that information would just be MobileNumber specific but yes, at the contact level, it would be associated in a way with the same contact.
We (Support) are also aware of these flaws and limitations and all we can do is encourage customers to log these as Ideas in the IdeaExchange portal so they can be taken into consideration for future implementation.
https://success.salesforce.com/ideaSearch?filter=Marketing+Cloud"
So seems nothing can be done I'm afraid :(

A: I suspect you're trying to answer a question that doesn't need resolving. SFMC maintains these priority 2 addresses in order to suppress sends to stopped numbers. SFMC doesn't know who the ultimate individual that's got that SIM in their phone is. As you point out, this isn't an issue in the short run. Your customer's no longer using that number or that's what they've told you. But is it a problem worth expending many clock cycles over for the long run? If you consider your average consumer rotates their mobile number every five years and your market penetration in terms of what percentage of all mobile numbers in your market are in MobileConnect is something akin to 0.00001%... collisions will happen, but this is only Marketing. So, why are you bothered about deleting these records?

A: Mobile Connect data is stored in a 'hidden' data extension called _MobileAddress.
You can check the CustomerKey of it in ContactBuilder or using SOAP API to retrieve all data extensions.
The data extension has the contactId field which links to a given subscriberKey.
You can alter the DE using AMPScript or SSJS using the methods provided to interact with data extensions.


text:
Q: "Error #119: cast to type <..> is not allowed" when using armcc I'm trying to compile an existed project (which was designed for gcc) with armcc.
For some reason I get the #119 error for the following casting:
(keyCert)(pCertHeader->flags)

I find it very odd because the flags variable is from type uint32_t, and keyCert type is actually uint32_t.
typedef union {
        struct {
                uint32_t      a:4;
                uint32_t      b:28;
        }c;
        uint32_t      d;
} keyCert;

What could be the reason for this behavior?
Note that I was able to compile it with gcc.
Thanks!

A:
I find it very odd because the flags variable is from type uint32_t, and keyCert type is actually uint32_t.

Wrong, keyCert type is union {...}. Compiler doesn't know if you store struct c or uint32_t d in keyCert, so compiler cannot assume it is uint32_t. The reason GCC possibly doesn't throw any errors is because it is compiler extension. ISO C forbids this type of casting.
Even in GCC if you compile it using C99 strict mode, you will get the following message:

warning: ISO C forbids casts to union type [-Wpedantic]


text:
Q: Javascript weird parseFloat initializing a Google Map canvas, I have a weird zoom value being set ...
//Google Map
function initialize(){
  var mapCanvas = $('.map-canvas');

  mapCanvas.each(function () {
        var $this           = $(this),
                zoom            = 10,
                lat             = 45.426340,
                lng             = 0.085172,
                scrollwheel     = false,
                draggable       = true,
                title           = '',
                contentString   = '';

        if ($this.data('zoom')){
            zoom = parseFloat($this.data('zoom'));
            alert('zoom: ' + zoom);
        }
        ## will output :  zoom: 6 !!
        ## if a change to

        if ($this.data('zoom')){
            #zoom = parseFloat($this.data('zoom'));
            zoom = 10;
        }
        ## then I get my zoom at the value 10...

What could be wrong ? anything related with the parseFloat() ??

A: $this.data('zoom') has nothing to do with var zoom = 10;
You are actually referring to the attribute data-zoom of each mapcanvas element


text:
Q: Issues Using Dependency Injection with AccountController I'm cleaning up and old app using MVC 5 EF,Identity, Unity I'm having trouble figuring out how to register the DI for the AccountController.  in the
In the Below example I changed
the Empty Constructor from the following
      public AccountController()
    { }

To this
public AccountController(IDateTimeService dateTimeService, ILeagueLogic leagueLogic)
{
    _dateTimeService = dateTimeService;
    _leagueLogic = leagueLogic;
}

So in the full Controller I have the Following
  public class AccountController : Controller
{
    private ApplicationUserManager _userManager;
    private IDateTimeService _dateTimeService;
    private ILeagueLogic _leagueLogic;

         [InjectionConstructor] <-- Nailed it
    public AccountController(IDateTimeService dateTimeService, ILeagueLogic leagueLogic)
    {
        _dateTimeService = dateTimeService;
        _leagueLogic = leagueLogic;
    }

    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

  private ApplicationSignInManager _signInManager;
    public ApplicationSignInManager SignInManager
    {
        get
        {
            return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
        }
        private set { _signInManager = value; }
    }

    //
    // GET: /Account/Login
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

}
In the UnityConfig File I have the following
 public static void RegisterTypes(IUnityContainer container)
    {

        container.RegisterType<IDateTimeService, DateTimeService>();
        container.RegisterType<ILeagueLogic, LeagueLogic>();

        container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>();
        container.RegisterType<UserManager<ApplicationUser>>();
        container.RegisterType<DbContext, ApplicationDbContext>();
        container.RegisterType<ApplicationUserManager>();
       // container.RegisterType<AccountController>(new InjectionConstructor());  <-- Removed this line
    }

But I get

The type MyProgram.Controllers.AccountController does not have a constructor that takes the parameters ().

Kinda Stumped.,. I belive I need to  Register the controller somehow not sure.. exactly how

A: The last line
container.RegisterType<AccountController>(new InjectionConstructor());
explicitly tells Unity to create an AccountController instance using the new AccountController() constructor
Based on the docs the type registration should look like that:
    container.RegisterType<AccountController>(
               new InjectionConstructor(
                 container.Resolve< IDateTimeService>(),
                 container.Resolve< IDateTimeService >()));

UPD: if you have just one constructor in your AccountController class, you may try to remove the container.RegisterType<AccountController>(new InjectionConstructor()); line completely. Unity should be able to construct an instance without a hint.
UPD2:
In case you have more than one constructor, but only one is used to construct an instance by Unity (for example the second one might be used in unit-test project) you could decorate the new ctor with [InjectionConstructor] attribute
[InjectionConstructor]
public AccountController(IDateTimeService dateTimeService, ILeagueLogic leagueLogic)
{
    _dateTimeService = dateTimeService;
    _leagueLogic = leagueLogic;
}


text:
Q: How to fetch a method name from a list? Lets say I have a list of strings with different method names, lets consider one-element list:
list = [split]

Is there any way to fetch the method name from the list when I want to use it? I'll give an exmple below, which doesn't work for me:
string = 'This is a string'
splitted_string = string.list[0]()

When I run the code, it's giving me:
AttributeError: 'str' object has no attribute 'list'


text:
Q: Ajax, when response has some value i want to treat it as an ajax error Whats happening is ,
I am already working on a big application, the way that the team handles the server side errors that they send a Json response with error=true (its still 200 success) (its hard for me to change that to send different status codes), and in the ajax success they call the same function to alert using a dialog with an error message if error=true else execute the normal logic,
what i want is to use a single ajax event to hook in before any success happens and check first if the value has error=true then don't call its success handler and show the dialog

A: You could change the structure of your success and error handlers to run the same code if error=true.
For example you could do:
$.ajax(
   success: function(data){
      if (data.error){
         RunErrorCode();
         return;
      }
      //success code...
   },
   error: function(){
      RunErrorCode();
});

function RunErrorCode(){
   alert("An error has occurred");
}

A: A function to validate the response:
var hasErrors = function(response) {
  if(response.error) {
    //...
    return true;
  }
};

Then on each success callback, call hasErrors.
$.ajax({
  //...
  success: function(response) {
    if(hasErrors(response)) return;
    //...
  }
})


text:
Q: map to json serialization in lift I have these 2 case classes: Topic and Report (definitions below):
case class Topic(name:String, queryWords:Set[String])
case class Report(dateRange: org.joda.time.Interval, queryWord: String, topics: Map[Topic,Boolean], allOtherTopics: Map[Topic,Boolean])
I have a list of reports which I want to serialize: reports: List[Report] but it gives me a scala.MatchError
..
val writer = new BufferedWriter(new FileWriter(file))
Serialization.write(reports, writer)      <--error right here
..

beginning or stack trace:
scala.MatchError: (Topic(steam,Set(steam)),true) (of class scala.Tuple2)
        at net.liftweb.json.Extraction$$anonfun$decompose$1.apply(Extraction.sca
la:82) ~[lift-json_2.10-2.5-RC6.jar:2.5-RC6]
..

Q: What is wrong with my deserialization?
I serialize List[Topic] fine. Does lift/scala have problems serializing maps?


text:
Q: on the sum $ \sum _{n=1}^{\infty}J_{0} (2\pi nx) $ given the zeroeth order Bessel function.. is then possible to compute the sum
$ \sum _{n=1}^{\infty}J_{0} (2\pi nx) $ for every 'x' positive real number ?

A: To investigate convergence, perhaps use:
$$
J_0(2\pi n x) = \frac{1}{\pi\sqrt{nx}}\sin\left(2\pi n x + \frac{\pi}{4}\right) + O(n^{-3/2})\qquad\text{as } n \to +\infty
$$
and investigate convergence of
$$
\sum_{n=1}^\infty \frac{1}{\pi\sqrt{nx}}\sin\left(2\pi n x + \frac{\pi}{4}\right)
$$


text:
Q: osx ipv6 default routing I've got an imac that's been running static ipv6 for years; I'm working on deploying ipv6 out to customers, and have the lan side of a test router plugged into a usb ethernet interface on the imac, which is properly getting a delegated address from the test router and it's getting a link-local default route from it:
en5: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    options=4<VLAN_MTU>
    ether d0:37:45:b8:f3:64
    inet 192.168.1.10 netmask 0xffffff00 broadcast 192.168.1.255
    inet6 fe80::1427:aee3:e9e5:138%en5 prefixlen 64 secured scopeid 0xf
    inet6 2607:f678:2fff::843:5ec6:8b74:9785 prefixlen 64 autoconf secured

netstat -rn:
...
Internet6:
Destination                             Gateway                         Flags         Netif Expire
default                                 2607:f678:1::1                  UGSc            en0
default                                 fe80::%utun0                    UGcI          utun0
default                                 fe80::4a77:46ff:fef9:5bb3%en5   UGcI            en5
...

When I delete the real default route (en0), ipv6 accesses get "no route to host" immediately (i.e. not from upstream, but the very first hop):
# traceroute6 google.com
connect: No route to host

The gateway is pingable:
# ping6 fe80::4a77:46ff:fef9:5bb3%en5
PING6(56=40+8+8 bytes) fe80::1427:aee3:e9e5:138%en5 --> fe80::4a77:46ff:fef9:5bb3%en5
16 bytes from fe80::4a77:46ff:fef9:5bb3%en5, icmp_seq=0 hlim=64 time=0.708 ms
16 bytes from fe80::4a77:46ff:fef9:5bb3%en5, icmp_seq=1 hlim=64 time=0.638 ms
^C

I try deleting the utun0 route in case it's trying to use that, but get:
# route delete -inet6 default fe80::%utun0
route: writing to routing socket: not in table
delete net default: gateway fe80::%utun0: not in table

I'm not sure what's missing here...


text:
Q: Mutliple Has_Many relation to same model but different lists I am struggeling with setting up a a ONE TO MANY relation, in the way, that the parent object has 3 different relations to the child object.
The child can be in only 1 of these 3 relations to the parent.
I have the feeling, that I mixed it up a little, would be great full, if anybody can bring some light into this topic, what the best practice approach would be to setup these relations.
I am relatively new to rails. Cheers
My Migration
add_reference :child_elements, :child_list_a, foreign_key: { to_table: :parent_elements }

add_reference :child_elements, :child_list_b, foreign_key: { to_table: :parent_elements }

add_reference :child_elements, :child_list_c, foreign_key: { to_table: :parent_elements }

Classes:
Child:
belongs_to :child_list_a, class_name: "ParentElement"
belongs_to :child_list_b, class_name: "ParentElement"
belongs_to :child_list_c, class_name: "ParentElement"

Parent:

has_many :child_elements_a, inverse_of: "child_list_a"
has_many :child_elements_b, inverse_of: "child_list_b"
has_many :child_elements_c, inverse_of: "child_list_c"


text:
Q: High performing container for storing a high number of objects I am looking for an ideal data container for with following objectives:
The behavior of the container must be sort of like Queue, with the following specifications:
1) random access is not a must
2) iterating over the objects in two directions must be super fast ( contiguous data would be better)
3) high performing delete from the front of the list and insert in the back is a must ( a high number of deletes and appends are done at every time step )
4) items are not primitive types, they are objects.
I know double-linked lists are not high performing containers.
vectors (like std::vector in c++) are good, but it is not really optimized for deleting from the front, also I don't think vectorization is possible at all given the size of objects.
I was also looking at the possibility of Slot-Map container, but not sure if it is the best option.
I was wondering if there are better options available?

A: If we really care about the performance, the container should never allocate any memory dynamically, i.e. we should define an upper limit of objects in the container.
The interface requirements is queueish indeed, so it looks like the fastest option would be circular queue of pointers to objects. So the container should shave the following fields:

*

*OBJECT * ptrs[SIZE] -- fixed size array of pointers. Sure, we will waste SIZE * sizeof (OBJECT *) bytes here, but performance wise it could be a good trade.

*size_t head_idx -- head object index.

*size_t tail_idx -- tail object index.

iterating over the objects in two directions must be super fast

Next object is a next index in the ptrs[]:
if (cur_idx >= head_idx) return nullptr;
return ptrs[(cur_idx++) % SIZE]; // make sure SIZE is a power of 2 constant

Prev object is a prev index in the ptrs[]:
if (cur_idx <= tail_idx) return nullptr;
return ptrs[(cur_idx--) % SIZE]; // make sure SIZE is a power of 2 constant

high performing delete from the front of the list and insert in the back is a must

The pop_front() would be as simple as:
if (tail_idx == head_idx) ... // should not happen, through an error
head_idx++;

The push_back() would be as simple as:
if (tail_idx - head_idx >= SIZE) ... // should not happen, through an error
ptrs[(tail_idx++) % SIZE] = obj_ptr; // make sure SIZE if a power of 2 constant

items are not primitive types, they are objects

The most generic solution would be to simply store pointers in the cyclic queue, so the size of the object does not matter and you waste just SIZE times pointer, not SIZE times object. But sure, if you can afford to preallocate thousands of objects, it should be even faster...
Those are kind of speculations based on your performance requirements. I am not sure if you can afford to trade some memory for the performance, so I am sorry if it is not the case...

A: You might be able to get away with just a regular vector and a start index that tells you where the "real" beginning of your data is.

*

*to append to the back, use the regular method. This has an amortized constant-time complexity, which is probably fine for you given that you will be doing lots of pushing.

*to delete from the front, increment start.

*to access element i, use vector[start + i].

*whenever you delete from anywhere but the front, or insert anywhere except the back, go ahead and recreate the whole vector without any leading deleted entries and reset start to zero.

Pros:

*

*entries are in a contiguous chunk of memory

*fast delete from the front and (amortized) fast insert into the back

*fast random access and fast iteration

Cons:

*

*slow worst-case insertion behavior

*potentially lots of wasted space unless cleaned up periodically

*cleaning up on deletes changes delete's worst-case behavior to linear, slow.

Whatever you do, consider comparing to the natural approach: a doubly-linked list with the head and tail remembered.

*

*fast inserts/deletes from the front/back

*no wasted space

True, the items will not be contiguous in memory so there is a potential for more cache misses; however, you could combat this with occasional defragmentation:

*

*allocate enough contiguous space for all nodes in the list

*recreate nodes in order by traversing links

*release the original nodes and use the new set of nodes as the list

Depending on the pattern of deletes/inserts/traversals, this could be feasible.


text:
Q: Xbox one power adapter wiring - converting it to a 12 volt power supply Thanks for having a look at my question.
I know this may seem like an odd question but here is the history of it.
I have a Solidoodle 4 3D printer, Its powered by a knock off xbox 360 brick adapter modded from the factory with a standard looking round power plug. (similar to what you will find on any wall wart) Round with the hole in the middle.
I got a roof leak in my garage and the power adapter that came with my 3d printer got soaked and currently is no good. Tried to buy a new one from Solidoodle but they are now out of business.
The original adapter was 12 volt 12.5A output, I found a used Xbox one power adapter and its rated for 12 volt 17.9A. the printer is pretty flexible on its power supply needs but more amps is better.
Question - I have the dc end of the power cord moved into the xbox one adapter in the appropriate terminals, (12V and GND2) all is good so far, however my measured voltage is only 143.4 mv when plugged in.
There are 3 other terminals on the adapter , +5VUSB - obviously the 5 volt rail, the last 2 are marked PS_ON1 which I am assuming is the power switch on the Xbox and the last is RSENSE which I have no clue what that's about.
I am assuming to have the Xbox 1 adapter turn on I need to put PS_ON1 either to ground, +5V or to RSENSE can anyone help me out with the wiring schematics for this adapter? I have no issues leaving the power adapter on all the time, when its not in use I usually turn off the power bar its plugged into anyway.
update:
The connector appears to be wired straight, cannot identity any resistors or the like in the connector:

A: Typically for Xbox related power supplies, you need to tie PS_ON to the 5V standby rail. You could do directly, but I would use a 1kΩ resistor just in case.
R-Sense normally indicates a Remote Sensing option for a power regulator. It would normally be connected at the far end of the power supply's connector, to compensate for any voltage droop from the cable. Considering this supply can pump 17 Amps down these cables, it can lead to a not-insignificant voltage droop. The internal regulator would then adjust the output voltage at the PCB so that it senses the voltage at the far end to be 12 Volts. Logic dictates it should be connected to the 12V input on your 3D printer's input. Use a multimeter to test the old connector for continuity on the R-Sense wire to 12V. You may need to cut the old connector open to make sure there is no diode or resistor needed there.


text:
Q: How to notify JMS listener for 'no objects' message I need to sync some 'car' repositories (managed by different slave-servers) to one repository (managed by one master-server).
For that matter I'm using ActiveMQ.
I've defined a queue (master.car.queue) which the master will listen to and all slaves will post there their car repository (every 5 minutes).
I have a scenario where one slave has one car in its repository - so it publishes a corresponding message.
Couple of minutes later, this car is sold - so this slave's repository is empty now - how should it notify that to the master?
I thought of the following options:
1) Create another queue for that use-case.
2) Use the same master.car.queue - but send a new message type or set a some property on that message.
What is the best practice for this use-case?
Thank.

A: Depends on your queue consumer design and if it is able to treat these use cases and if from business point of view what you do with messages.
For example if received messages are just injected un a database you can create 2 consumers (one to insert and one to update or remove) for 2 queues for these 2 use cases and use your first proposition or use 1 queue and use a Message Router from the EIP patterns as messages receiver to route to differents consumers


text:
Q: Tensorflow error : unsupported callable I follow the tutorial https://www.tensorflow.org/tutorials/layers and I want use it to use my own dataset.
def train_input_fn_custom(filenames_array, labels_array, batch_size):
    # Reads an image from a file, decodes it into a dense tensor, and resizes it to a fixed shape.
    def _parse_function(filename, label):
        image_string = tf.read_file(filename)
        image_decoded = tf.image.decode_png(image_string, channels=1)
        image_resized = tf.image.resize_images(image_decoded, [40, 40])
        return image_resized, label

    filenames = tf.constant(filenames_array)
    labels = tf.constant(labels_array)

    dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
    dataset = dataset.map(_parse_function)
    dataset = dataset.shuffle(1000).repeat().batch(batch_size)

    return dataset.make_one_shot_iterator().get_next()

def main(self):
    tf.logging.set_verbosity(tf.logging.INFO)

    # Get data
    filenames_train = ['blackcorner-data/1.png', 'blackcorner-data/2.png']
    labels_train = [0, 1]

    # Create the Estimator
    classifier = tf.estimator.Estimator(model_fn=cnn_model_fn, model_dir="/tmp/test_convnet_model")

    # Set up logging for predictions
    tensors_to_log = {"probabilities": "softmax_tensor"}
    logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=50)

    # Train the model
    cust_train_input_fn = train_input_fn_custom(
            filenames_array=filenames_train,
            labels_array=labels_train,
            batch_size=3)

    classifier.train(
            input_fn=cust_train_input_fn,
            steps=2000,
            hooks=[logging_hook])

if __name__ == "__main__":
    tf.app.run()

But I have this error :
    Traceback (most recent call last):
      File "/usr/lib/python3.6/inspect.py", line 1119, in getfullargspec
        sigcls=Signature)
      File "/usr/lib/python3.6/inspect.py", line 2186, in _signature_from_callable
        raise TypeError('{!r} is not a callable object'.format(obj))
    TypeError: (<tf.Tensor 'IteratorGetNext:0' shape=(?, 40, 40, ?) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(?,) dtype=int32>) is not a callable object

    The above exception was the direct cause of the following exception:

    Traceback (most recent call last):
      File "cnn_mnist_for_stackoverflow.py", line 139, in <module>
        tf.app.run()
      File "/home/geo/Projet/ML/cnn_mnist/venv/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 126, in run
        _sys.exit(main(argv))
      File "cnn_mnist_for_stackoverflow.py", line 135, in main
        hooks=[logging_hook])
     ...
        raise TypeError('unsupported callable') from ex
    TypeError: unsupported callable

I don't understand this error, I just know it came from the train_input_fn_custom.
The tensorflow version is 1.6
if anyone has an idea.. Thanks !

A: The input_fn argument to classifier.train() must be a callable object (with no arguments), such as a function or a lambda. In your code, you are passing the results of calling train_input_fn_custom(), rather than a callable object that invokes train_input_fn_custom(). To fix this issue, replace the definition of cust_train_input_fn as follows:
# The `lambda:` creates a callable object with no arguments.
cust_train_input_fn = lambda: train_input_fn_custom(
    filenames_array=filenames_train, labels_array=labels_train, batch_size=3)


text:
Q: How to sync two sheets with =importrange() in two googlespreadsheet? I'm using =importrange() function to sync (echo sync) two sheets in two different spreadsheets (as described here). But, the importrange() it is not syncing to the second sheet when I make a change in the first sheet. Once imported, the cells stay static and do not alter as more changes are made in the first worksheet. Is there a way to fix it?

A: I don't think you'll be able to use the =importrange() function on two sheets because as soon as you add the function to the second sheet it will be importing the function you added to the first sheet with it's own ID as an argument.
You could use Google Apps Script, I have just answered a very similar question here. But I'll repeat what I wrote below.
One way you could accomplish this is by adding a script to both spreadsheets that copies it's contents to the other spreadsheet on a change trigger. For example if you were to add something like the below to both spreadsheets, swapping the source and destination information around.
var sourceSpreadsheetID = "ID HERE";
var sourceWorksheetName = "SHEET NAME HERE";
var destinationSpreadsheetID = "ID HERE";
var destinationWorksheetName = "SHEET NAME HERE";

function importData() {
  var thisSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetID);
  var thisWorksheet = thisSpreadsheet.getSheetByName(sourceWorksheetName);
  var thisData = thisWorksheet.getDataRange();
  var toSpreadsheet = SpreadsheetApp.openById(destinationSpreadsheetID);
  var toWorksheet = toSpreadsheet.getSheetByName(destinationWorksheetName);
  var toRange = toWorksheet.getRange(1, 1, thisData.getNumRows(), thisData.getNumColumns())
  toRange.setValues(thisData.getValues());
}

Just add a change trigger for the importData function and then when any changes are made to either document it will copy the contents to the other spreadsheet, thus keeping the both synced.
Obviously if both spreadsheets are being updated at the same time you will run into trouble.

A: That was pretty helpfull script . Have edited some changes , in your script so that even multiple sheets can be synchronized for a give column and row .the code is a bit slow but works good.
I am now thinking if there was a way to merge multiple sheets using the same method , if it does it should be awesome .
   // sync multiple sheets to a source sheet ( "sheet 1")
// change active sheet name to the designated sheet names.
function importData(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeSheet = ss.getActiveSheet();
  var activeSheetName = ss.getActiveSheet().getSheetName();
// set the sheet to copy from sheet 1 to sheet 2. sheet 1 active sheet.
  if( activeSheetName == "Daily report Counselling" )
  {
  var thisSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var thisWorksheet = thisSpreadsheet.getSheetByName("Sheet1");
  var thisData  = thisWorksheet.getRange("A5:H");
  var toSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  var toWorksheet = toSpreadsheet.getSheetByName("Sheet2");
    var toRange = toWorksheet.getRange("A7:H");
  toRange.setValues(thisData.getValues());
      }
// if sheet 1 has not the active sheet choose from sheet 2.
 if( activeSheetName == "Follow Up Needed Editable" )
  {
  var thisSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var thisWorksheet = thisSpreadsheet.getSheetByName("Sheet2");
    var thisData  = thisWorksheet.getRange("A7:H");
  var toSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var toWorksheet = toSpreadsheet.getSheetByName("Sheet1");
    var toRange = toWorksheet.getRange("A5:H");
  toRange.setValues(thisData.getValues());

  }
}

Please let me know if something interesting comes in the way .


text:
Q: Ionic Capacitor App fails at Android build I have an Ionic 5/React Project that I cannot create an Android production build with. When I run the build in Android studio, this is the error I receive. I cannot figure out anything that works, any help?
Gradle could not start your build.
> Cannot create service of type DefaultConfigurationCache using DefaultConfigurationCache constructor as there is a problem with parameter #10 of type ConfigurationCacheFingerprintController.
   > Cannot create service of type ConfigurationCacheFingerprintController using ConfigurationCacheFingerprintController constructor as there is a problem with parameter #5 of type FileCollectionFingerprinterRegistry.
      > Cannot create service of type FileCollectionFingerprinterRegistry using method VirtualFileSystemServices$BuildSessionServices.createFileCollectionFingerprinterRegistry() as there is a problem with parameter #1 of type List<FileCollectionFingerprinter>.
         > Could not create service of type CrossBuildFileHashCache using BuildSessionServices.createCrossBuildFileHashCache().
            > Failed to create parent directory '/.gradle' when creating directory '/.gradle/6.8/fileHashes'

Thanks!


text:
Q: Can you change the name of an element on an array without trying to set the names of the entire array? I was recently surprised to find that the following didn't work:
output<-array(1:10)
names(output[1])<-"Foo"

As far as I can tell, this does not changes the name of output[1]. Is it possible to modify the names of the individual elements of an array like this? Or am I forced to write code that modifies the entire array, like names(output)<-c("foo",rep(NA,9))?

A: You want to change the first name of an element, so [1] goes outside names(output):
output<-array(1:10)
names(output)[1]<-"Foo"
names(output)
#>  [1] "Foo" NA    NA    NA    NA    NA    NA    NA    NA    NA