text:
Q: Clock Widget Seconds hand i am making a clock widget with seconds hand.i got a code from another website and have implemented to my project.i found that the seconds needle works well but quiet after some time it gets force close.log cat has been posted below for your kind reference
11-25 11:11:39.040: E/AndroidRuntime(23673): FATAL EXCEPTION: main
11-25 11:11:39.040: E/AndroidRuntime(23673): java.lang.RuntimeException: Unable to start service com.themebowl.christmaswinterclockfree.WidgetService@41ded6e8 with null: java.lang.NullPointerException
11-25 11:11:39.040: E/AndroidRuntime(23673):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2571)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at android.app.ActivityThread.access$2000(ActivityThread.java:140)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1334)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at android.os.Looper.loop(Looper.java:137)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at android.app.ActivityThread.main(ActivityThread.java:4921)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at java.lang.reflect.Method.invokeNative(Native Method)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at java.lang.reflect.Method.invoke(Method.java:511)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at dalvik.system.NativeStart.main(Native Method)
11-25 11:11:39.040: E/AndroidRuntime(23673): Caused by: java.lang.NullPointerException
11-25 11:11:39.040: E/AndroidRuntime(23673):    at com.themebowl.christmaswinterclockfree.ClockWidgetProvider.onDrawClock(ClockWidgetProvider.java:192)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at com.themebowl.christmaswinterclockfree.WidgetService.onStartCommand(WidgetService.java:64)
11-25 11:11:39.040: E/AndroidRuntime(23673):    at  android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2554)
11-25 11:11:39.040: E/AndroidRuntime(23673):    ... 10 more

I need a helping hand.hope you will help me.
ClockWidgetProvider.class
package com.themebowl.christmaswinterclockfree;

import com.themebowl.christmaswinterclockfree.R.drawable;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.PowerManager;
import android.text.format.Time;
import android.util.Log;
import android.widget.RemoteViews;

public class ClockWidgetProvider extends AppWidgetProvider {

public static String THEMEVALUE = "DEFAULT";
public static String SKINVALUE = "CYAN";

public static int DISPLAYWIDTH;
public static int DISPLAYHEIGHT;
private static Canvas dial_Canvas;
private static Drawable dial_drawable, hour_drawable, minute_drawable,
        second_drawable
        ;
private static boolean mChanged = false;
protected static Time mCalendar = new Time();
private static float mMinutes;
private static float mHour;
private static float mSecond;
private static RemoteViews views;
private static Bitmap b;
private static AppWidgetManager widgetManager;
private static int widgetId;

public static boolean hasBackground = false;
public static boolean hasNumbers = false;
public static boolean hasMarkers = false;
public static boolean isWidgetCredated = false;

private PowerManager.WakeLock wl;
private PowerManager pm;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    // TODO Auto-generated method stub
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    Log.e("onUpdate", "Inside onUpdate");

    final int N = appWidgetIds.length;
    for (int i = 0; i < N; i++) {
        int appWidgetId = appWidgetIds[i];
        updateAppWidget(context, appWidgetManager, appWidgetId);

    }

}

public static void updateAppWidget(Context context,
        AppWidgetManager appWidgetManager, int appWidgetId) {

    widgetManager = appWidgetManager;
    widgetId = appWidgetId;

    Intent intent = new Intent(context, ClockWidgetConfig.class);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); // Identifies
                                                                        // the
                                                                        // particular
                                                                        // widget...
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
    PendingIntent pendIntent = PendingIntent.getActivity(context, 0,
            intent, PendingIntent.FLAG_UPDATE_CURRENT);

    views = new RemoteViews(context.getPackageName(),
            R.layout.clockwidget_layout);

     if (THEMEVALUE.equalsIgnoreCase("NEON")) {

             //             second_drawable = context.getResources().getDrawable(
           //                       drawable.neon_blue_markers);

        dial_drawable = context.getResources().getDrawable(
                drawable.xclockb);
        hour_drawable = context.getResources().getDrawable(
                drawable.clock_hand_hour);
        minute_drawable = context.getResources().getDrawable(
                drawable.clock_hand_minute);

        second_drawable = context.getResources().getDrawable(
                drawable.xclocks);

    DISPLAYWIDTH = dial_drawable.getIntrinsicWidth();
    DISPLAYHEIGHT = dial_drawable.getIntrinsicHeight();

    b = Bitmap.createBitmap(DISPLAYWIDTH, DISPLAYHEIGHT,
            Bitmap.Config.ARGB_8888);
    dial_Canvas = new Canvas(b);
    onTimeChanged();

    views.setOnClickPendingIntent(R.id.Widget, pendIntent);
    appWidgetManager.updateAppWidget(appWidgetId, views);
     }
}

public void onReceive(Context context, Intent intent) {

    Log.e("onReceive", "Inside onReceive");

    if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(intent)) {
        AppWidgetManager amgr = AppWidgetManager.getInstance(context);
        int length = amgr.getAppWidgetIds(intent.getComponent()).length;
        if (length == 0)// WidgetService.StopService(context);
            context.stopService(new Intent(context, WidgetService.class));
        isWidgetCredated = false;
        WidgetService.timer.cancel();
        WidgetService.timer.purge();
    }

    pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AnalogClock");
    //am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

//  setAlarm(context);

    RemoteViews views = new RemoteViews(context.getPackageName(),
            R.layout.clockwidget_layout);

    Intent AlarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(
            Intent.CATEGORY_LAUNCHER).setComponent(
            new ComponentName("com.android.alarmclock",
                    "com.android.alarmclock.AlarmClock"));
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            AlarmClockIntent, 0);
    views.setOnClickPendingIntent(R.id.Widget, pendingIntent);

    AppWidgetManager.getInstance(context).updateAppWidget(
            intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS),
            views);

}

protected static void onDrawClock() {

    boolean changed = mChanged;
    if (changed) {
        mChanged = false;
    }

    Log.e("Inside onDraw", "Inside onDraw");

    int availableWidth = DISPLAYWIDTH;
    int availableHeight = DISPLAYHEIGHT;

    int x = availableWidth / 2;
    int y = availableHeight / 2;

    final Drawable dial = dial_drawable;
    int w = dial.getIntrinsicWidth();
    int h = dial.getIntrinsicHeight();

    boolean scaled = false;

    // //////////////////////

    // ////////////////////////////////
    if (availableWidth < w || availableHeight < h) {
        scaled = true;
        float scale = Math.min((float) availableWidth / (float) w,
                (float) availableHeight / (float) h);
        dial_Canvas.save();
        dial_Canvas.scale(scale, scale, x, y);
    }

    if (changed) {
        dial.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
    }
    dial.draw(dial_Canvas);

    dial_Canvas.save();
    dial_Canvas.rotate(mHour / 12.0f * 360.0f, x, y);

    final Drawable hourHand = hour_drawable;
    if (changed) {
        w = hourHand.getIntrinsicWidth();
        h = hourHand.getIntrinsicHeight();
        hourHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y
                + (h / 2));
    }
    hourHand.draw(dial_Canvas);
    dial_Canvas.restore();

    dial_Canvas.save();
    dial_Canvas.rotate(mMinutes / 60.0f * 360.0f, x, y);

    final Drawable minuteHand = minute_drawable;
    if (changed) {
        w = minuteHand.getIntrinsicWidth();
        h = minuteHand.getIntrinsicHeight();
        minuteHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y
                + (h / 2));
    }
    minuteHand.draw(dial_Canvas);
   //edited

    //dial_Canvas.restore();

    if (WidgetService.hasSecondsHand) {
        // /////////
        dial_Canvas.restore();

        dial_Canvas.save();
        // dial_Canvas.rotate(mSecond / 30.0f * 360.0f, x, y);

        dial_Canvas.rotate(mSecond / 60.0f * 60.0f * 360.0f, x, y);

        Log.e("second onTimeChanged", mSecond / 30.0f * 360.0f + "");

        final Drawable secondHand = second_drawable;
        if (changed) {
            w = secondHand.getIntrinsicWidth();
            h = secondHand.getIntrinsicHeight();
            secondHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y
                    + (h / 2));
        }
        secondHand.draw(dial_Canvas);
        // ////////////
    }

    dial_Canvas.restore();
    //edited
    //dial_Canvas.save();

    if (scaled) {
        dial_Canvas.restore();
        //dial_Canvas.save();

    }

    isWidgetCredated = true;
}

protected static void onTimeChanged() {

    mCalendar.setToNow();
    int hour = mCalendar.hour;
    int minute = mCalendar.minute;
    int second = mCalendar.second;

    mSecond = second / 60.0f;
    mMinutes = minute + second / 60.0f;
    mHour = hour + mMinutes / 60.0f;
    mChanged = true;

    b.eraseColor(Color.TRANSPARENT);

    onDrawClock();

    views.setImageViewBitmap(R.id.dialimg, b);
     widgetManager.updateAppWidget(widgetId, views);

}

protected static void broadcastTimeChanging() {
    mCalendar.setToNow();
    int hour = mCalendar.hour;
    int minute = mCalendar.minute;
    int second = mCalendar.second;

    mSecond = second / 60.0f;
    mMinutes = minute + second / 60.0f;
    mHour = hour + mMinutes / 60.0f;
    mChanged = true;
}

   }


text:
Q: react material-ui styled-components I have built an app which shows orders that are fetched from my api. orders have some properties as shown here:
id(pin): 22
open(pin): "3.60000000"
high(pin): "4.50000000"
low(pin): "3.20000000"
close(pin): "4.10000000"
time(pin): "2022-07-30T15:12:00+04:30"
active(pin): false
staged(pin): "OFFTRACK"

and I use styled components to show these as follow:
const StyledTableRow = styled(TableRow)(({ theme }) => ({
  '&:nth-of-type(odd)': {
    backgroundColor: theme.palette.action.hover,
  },
  // hide last border
  '&:last-child td, &:last-child th': {
    border: 0,
  },
}));

actually my orders has three different values in respect to staged property of the order; namely: ontrack, offtrack and staged. I wanted to apply this logic in a way those StyledTableRows could have different styles according to the staged property.
and the part I placed the component:
{orders.map((order, index) => {
  return (
    <StyledTableRow key={index}>
      <StyledTableCell align="center">{order.open}</StyledTableCell>
      <StyledTableCell align="center">{order.high}</StyledTableCell>
      <StyledTableCell align="center">{order.low}</StyledTableCell>
      <StyledTableCell align="center">{order.close}</StyledTableCell>
    </StyledTableRow>
  )
})}

I'm not that new to @mui but about styled components totally confused. thanks.

A: morganney's comment is correct, but could use some illustration:
Pass order.staged as a prop on your styled components
<StyledTableCell align="center" staged={ order.staged }>{order.high}</StyledTableCell>

read it in as another parameter along with theme
const StyledTableRow = styled(TableRow)(({ theme, ...props }) => ({
  '&:nth-of-type(odd)': {
    backgroundColor: theme.palette.action.hover,
  },
  // hide last border
  '&:last-child td, &:last-child th': {
    border: 0,
  },

  // Style according to the value of the passed prop. For example...
  [<selector>]: {
    <CSS_property>: props.staged == "OFFTRACK"
      ? <CSS_property_value_for_offtrack>
      : props.staged == "ONTRACK"
        ? <CSS_property_value_for_ontrack>
        : <CSS_property_value_for_staged> // "STAGED"
  }
  ...
}));

redpajama_set_name: RedPajamaStackExchange


text:
Q: fetch in redux action does nothing I am trying to refactor my app so that it works with redux. I have a redux action where the first console.log produces output (line 3 below which shows the api url). No other output seen. Also catch seems not to be called (I tested it).
fetch seems to do nothing. The fetch code snipped worked however when it was on its original place (before refactoring) within componentWillMount.
What's wrong with my fetch? Thank you for any help!

export function getPlatzBelegungen(court, day1, day2) {
  const url = HOSTNAME + "/intern/api/platz.php?op=ra&p=" + court + "&ds=" + day1 + "&de=" + day2;
  console.log(url);

  return function(dispatch) {
    return fetch(url)
    .then(result => {
      if (result.ok) {
        console.log("###>>> result.ok");
          return result.json();
        } else {
          throw new Error('Fehler beim Laden der Platzbuchungsdaten');
        }
    })
    .then(result => {
        console.log("###>>> courtData berechnen");
        let courtData = result.records.map ( r => {
        let k = r.id;
        let cn = computeBelClasses (r.starts_at, r.ends_at);
        console.log("PLATZ:" + r.court)
        let spieler =
            r.p1
          + (r.p2 ? ', ' + r.p2 : ' ')
          + (r.p3 ? ', ' + r.p3 : ' ')
          + (r.p4 ? ', ' + r.p4 : ' ');
        return (
          <Link key={k} to={'/belegungsdetails/' + r.id}>
            <div key={k} className={cn}>
              <strong>{r.starts_at.substring(11,16)} </strong>
              {spieler}
            </div>
          </Link>
        )
      })
      dispatch({ type: BELEGUNGEN_LOADED, payload: courtData });
    })
    .catch(
      dispatch({ type: BELEGUNGEN_LOAD_FAILED, payload: [] }));
  };

};

A: I guess you might have some errors for the fetch. Your catch part needs to pass a function into it. Like
.catch(error => {
    dispatch({ type: BELEGUNGEN_LOADED, payload: courtData });
});


text:
Q: Campaign Member Activity VS Object Activity I would like to double check what is the best practice that applies to the next use case:

In a journey, I would like to check if a customer already exists as a
  record in the Campaign Member object (Find and Update using the
  Campaign Member Activity). If not, the record has to be created.

In case this record doesnt exist, I see the only option is using the Object Activity and 'Create new record'. See screenshot below. Is this the best way to do it?

A: The Campaign Member Activity is limited to one basic usecase, simply injecting newly added members to a campaign into a journey. If that's all you need, go for it.
Anything more "sophisticated" including duplicate checks can be achieved with the Object activity. In other words, you can always do more with the Object activity, thus you can consider Campaign Member Activity as a shorthand path to one particular usecase.


text:
Q: Cannot easy_install readline for Python 2.7.3 on Mac Os Lion I am trying to install the python readline module. I have already installed readline via homebrew.
If I type
easy_install readline

I get
Downloading http://pypi.python.org/packages/source/r/readline/readline-6.2.2.tar.gz#md5=ad9d4a5a3af37d31daf36ea917b08c77
Processing readline-6.2.2.tar.gz
Writing /var/folders/44/dhrdb5sx53s243j4w03063vh0000gn/T/easy_install-64FbG8/readline-6.2.2/setup.cfg
Running readline-6.2.2/setup.py -q bdist_egg --dist-dir /var/folders/44/dhrdb5sx53s243j4w03063vh0000gn/T/easy_install-64FbG8/readline-6.2.2/egg-dist-tmp-NOmStB
clang: error: no such file or directory: 'readline/libreadline.a'
clang: error: no such file or directory: 'readline/libhistory.a'
error: Setup script exited with error: command '/usr/bin/clang' failed with exit status 1

Any ideas about how I could fix this ?
Thanks

A: This bug should be fixed in readline version 6.2.4 released last week.
Also note that you do not need to install the readline library itself via homebrew. It is already included within the python readline module.
Anyone having problems with the python-readline module is welcome to open an issue on the GitHub page of the module. This will ensure that the problem is permanently solved for everyone.

A: I had this same problem in OS X Lion 10.8, and fixed it by renaming my /Developer to /Developer-old. See this issue.

A: There is a new solution to this problem in Pypi, pip install gnureadline.
https://pypi.python.org/pypi/gnureadline
The root issue is libedit (BSD-licensed) vs. Gnu Readline (GPL-licensed) . Apple would rather provide incompatible BSD code, than provide compatible code that has GPL restrictions.

A: None of the above worked from me.
After uninstall ipython and readline, I ran the following that finally worked
easy_install http://pypi.python.org/packages/source/r/readline/readline-6.1.0.tar.gz
pip install ipython

And yes, readline 6.1.0 is an old one, but 6.2.x or other would not work (in sept 2013).

A: Try installing the binary egg directly:
$ easy_install http://pypi.python.org/packages/2.7/r/readline/readline-6.2.2-py2.7-macosx-10.7-intel.egg#md5=25383d860632d4a1521961ba68a52fe2

A: Make sure you have gcc installed.
which gcc

should return
/usr/bin/gcc

I was getting the same error when trying to easy_install readline. It wasn't until I downloaded the tar and tried to manually build it that I noticed it said
checking whether make sets $(MAKE)... no
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/Users/roneill/readline-6.2.4.1/rl/readline-lib':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details.

that I realized what the actual problem was. I had not used this particular laptop in a while and had not used Xcode to install the command line tools. Once I did, things worked properly.


text:
Q: Non-exhaustive patterns in function checkStr when counting number of nondigits in string I made a program that is counting number of nondigits in string. It returns value based on how many nondigits were found. When I run my code Ghci says that " Non-exhaustive patterns in function checkStr". What's the problem?
checkStr:: String -> Int

digits = ['0'..'9']

checkStr_ _ [] = 0

checkStr (str:ss)
   | str `elem` digits = checkStr ss
   | otherwise = 1 + checkStr ss

A: You here defined two functions checkStr_ and checkStr. The last one only covers the patter (str:ss). So eventually the list will be exhausted, and the it will be called with []. You do not have any logic for that.
You can implement this with:
checkStr :: String -> Int
checkStr [] = 0
checkStr (str:ss)
   | str `elem` digits = checkStr ss
   | otherwise = 1 + checkStr ss
That being said, we can make the above by filtering on the isDigit function, and then calculate the length:
import Data.Char(isDigit)

checkStr :: String -> Int
checkStr = length . filter (not . isDigit)


text:
Q: I am trying to send facebook custom app-events in node js using facebook graph api basically I am doing a post request at  https://graph.facebook.com/{app_id}/activities . As mentioned in docs.
The event is getting displayed in facebook analytics events dashboard , but the unique Users and count field is getting displayed as 1.(not getting updated with each post request) . Is this the usual behaviour or can someone please help me where I might be going wrong ?
Thanks in advance :)


text:
Q: SQL Server : select distinct until the value is changed I have a table of tasks (each task can has a few rows) that looks something like this:
TaskID | DateCreated | Status
-------+-------------+------------
  1    | 01-01-2017  | Started
  2    | 02-02-2017  | InProgress
  1    | 02-02-2017  | Started
  1    | 03-03-2017  | InProgress
  2    | 03-03-2017  | InProgress
  1    | 04-04-2017  | InProgress
  2    | 04-04-2017  | Done
  1    | 05-05-2017  | Done

I have more columns which are not relevant for this requirement.
What I need here is to select the actual status flow that a specific task has passed.
For example, for task with TaskID = 1, I want to get the following result:
TaskID | Status
-------+-------------
  1    | Started
  1    | InProgress
  1    | Done

Notes:

*

*The rows may be not sorted

*A status can repeat itself, e.g. there can be a task that its' status flow was:
Started ==> InProgress ==> Break ==> InProgress ==> Done

so will not help me to get for each task the unique status from each status type it passed

A: In SQL 2012+ you could use LAG
  DECLARE @SampleData AS TABLE
  (
    TaskID int,
    DateCreated date,
    Status varchar(20)
  )

  INSERT INTO @SampleData
  VALUES
  (1, '2017-01-01', 'Started'),
  (2, '2017-02-02', 'InProgress'),
  (1, '2017-02-02', 'Started'),
  (1, '2017-03-03', 'InProgress'),
  (2, '2017-03-03', 'InProgress'),
  (1, '2017-04-04', 'InProgress'),
  (2, '2017-04-04', 'Done'),
  (1, '2017-05-05', 'Done')

  ;with temp as
  (
     SELECT  *,
             lag(sd.Status,1,'') OVER(PARTITION BY sd.TaskID ORDER BY sd.DateCreated)  AS PreviousRowStatus
     FROM @SampleData sd
  )
  SELECT t.TaskID, t.DateCreated, t.Status
  FROM temp t
  WHERE t.Status != t.PreviousRowStatus
  ORDER BY t.TaskID

Returns
TaskID  DateCreated Status
--------------------------
1       2017-01-01  Started
1       2017-03-03  InProgress
1       2017-05-05  Done
2       2017-02-02  InProgress
2       2017-04-04  Done

For older version you could use Row_number and APPLY

A: Below is the query where in partition by will fetch you the desired result.
select taskid,status(select taskid,status
,row_number()over(partition by taskid,status order by taskid)rownum
from [yourtablename])tmp
where rownum = 1

A: Try Query (select distinct ):
SELECT DISTINCT TaskID, Status
FROM            (SELECT   TaskID, Status
                          FROM            task
                          ORDER BY TaskID) AS task_1
WHERE        (TaskID = 1)
ORDER BY Status DESC

Or Simply :
SELECT DISTINCT TaskID, Status
FROM            task
WHERE        (TaskID = 1)
ORDER BY TaskID, Status DESC

Result for your demo content:


text:
Q: Why does pickle __getstate__ accept as a return value the very instance it required __getstate__ to pickle in the first place? I was going to ask "How to pickle a class that inherits from dict and defines __slots__". Then I realized the utterly mind-wrenching solution in class B below actually works...
import pickle

class A(dict):
    __slots__ = ["porridge"]
    def __init__(self, porridge): self.porridge = porridge

class B(A):
    __slots__ = ["porridge"]
    def __getstate__(self):
        # Returning the very item being pickled in 'self'??
        return self, self.porridge
    def __setstate__(self, state):
        print "__setstate__(%s) type(%s, %s)" % (state, type(state[0]),
                                                type(state[1]))
        self.update(state[0])
        self.porridge = state[1]

Here is some output:
>>> saved = pickle.dumps(A(10))
TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled
>>> b = B('delicious')
>>> b['butter'] = 'yes please'
>>> loaded = pickle.loads(pickle.dumps(b))
__setstate__(({'butter': 'yes please'}, 'delicious')) type(<class '__main__.B'>, <type 'str'>)
>>> b
{'butter': 'yes please'}
>>> b.porridge
'delicious'

So basically, pickle cannot pickle a class that defines __slots__ without also defining __getstate__. Which is a problem if the class inherits from dict - because how do you return the content of the instance without returning self, which is the very instance pickle is already trying to pickle, and can't do so without calling __getstate__. Notice how __setstate__ is actually receiving an instance B as part of the state.
Well, it works... but can someone explain why? Is it a feature or a bug?

A: Here's the thinking as I understand it. If your class uses __slots__, it's a way to gaurantee that there aren't any unexpected attributes. Unlike a regular Python object, one that's implemented with slots cannot have attributes dynamically added to it.
When Python unserializes an object with __slots__, it doesn't want to just make an assumption that whatever attributes were in the serialized version are compatible with your runtime class. So it punts that off to you, and you can implement __getstate__ and __setstate__.
But the way you implemented your __getstate__ and__setstate__, you appear to be circumventing that check. Here's the code that's raising that exception:
try:
    getstate = self.__getstate__
except AttributeError:
    if getattr(self, "__slots__", None):
        raise TypeError("a class that defines __slots__ without "
                        "defining __getstate__ cannot be pickled")
    try:
        dict = self.__dict__
    except AttributeError:
        dict = None
else:
    dict = getstate()

In a round about way, you're telling the Pickle module to set its objections aside and serialize and unserialize your objects as normal.
That may or may not be a good idea -- I'm not sure. But I think that could come back to bite you if, for example, you change your class definition and then unserialize an object with a different set of attributes than what your runtime class expects.
That's why, when using slots especially, your __getstate__ and __getstate__ should be more explicit. I would be explicit and be clear that you're just sending the dictionary key/values back and forth, like this:
class B(A):
    __slots__ = ["porridge"]
    def __getstate__(self):
        return dict(self), self.porridge
    def __setstate__(self, state):
        self.update(state[0])
        self.porridge = state[1]

Notice the dict(self) -- that casts your object to a dict, which should make sure that the first element in your state tuple is only your dictionary data.

A: Maybe I'm a bit late to the party, but this question didn't get an answer that actually explains what's happening, so here we go.
Here's a quick summary for those who don't want to read this whole post (it got a bit  long...):

*

*You don't need to take care of the contained dict instance in __getstate__() -- pickle will do this for you.

*If you include self in the state anyway, pickle's cycle detection will prevent an infinite loop.
Writing __getstate__() and __setstate__() methods for custom classes derived from dict
Let's start with the right way to write the __getstate__() and __setstate__() methods of your class.  You don't need to take care of pickling the contents of the dict instance contained in B instances -- pickle knows how to deal with dictionaries and will do this for you.  So this implementation will be enough:
class B(A):
    __slots__ = ["porridge"]
    def __getstate__(self):
        return self.porridge
    def __setstate__(self, state):
        self.porridge = state

Example:
>>> a = B("oats")
>>> a[42] = "answer"
>>> b = pickle.loads(pickle.dumps(a))
>>> b
{42: 'answer'}
>>> b.porridge
'oats'

What's happening in your implementation?
Why does your implementation work as well, and what's happening under the hood?  That's a bit more involved, but -- once we know that the dictionary gets pickled anyway -- not too hard to figure out.  If the pickle module encounters an instance of a user-defined class, it calls the __reduce__() method of this class, which in turn calls __getstate__() (actually, it usually calls the __reduce_ex__() method, but that does not matter here).  Let's define B again as you originally did, i.e. using the "recurisve" definition of __getstate__(), and let's see what we get when calling __reduce__() for an instance of B now:
>>> a = B("oats")
>>> a[42] = "answer"
>>> a.__reduce__()
(<function _reconstructor at 0xb7478454>,
 (<class '__main__.B'>, <type 'dict'>, {42: 'answer'}),
 ({42: 'answer'}, 'oats'))

As we can see from the documentation of __reduce__(), the method returns a tuple of 2 to 5 elements.  The first element is a function that will be called to reconstruct the instance when unpickling, the second element is the tuple of arguments that will be passed to this function, and the third element is the return value of __getstate__().  We can already see that the dictionary information is included twice. The function _reconstructor() is an internal function of the copy_reg module that reconstructs the base class before __setstate__() is called when unpickling.  (Have a look at the source code of this function if you like -- it's short!)
Now the pickler needs to pickle the return value of a.__reduce__().  It basically pickles the three elements of this tuple one after the other.  The second element is a tuple again, and its items are also pickled one after the other.  The third item of this inner tuple (i.e. a.__reduce__()[1][2]) is of type dict and is pickled using the internal pickler for dictionaries.  The third element of the outer tuple (i.e. a.__reduce__()[2]) is also a tuple again, consisting of the B instance itself and a string.  When pickling the B instance, the cycle detection of the pickle module kicks in:  pickle realises this exact instance has already been dealt with, and only stores a reference to its id() instead of really pickling it -- this is why no infinte loop occurs.
When unpickling this mess again, the unpickler first reads the reconstruction function and its arguments from the stream.  The function is called, resulting in an B instance with the dictionary part already initialised.  Next, the unpickler reads the state.  It encounters a tuple consisting of a reference to an already unpickled object -- namely our instance of B -- and a string, "oats".  This tuple now is passed to B.__setstate__().  The first element of state and self are the same object now, as can be seen by adding the line
print self is state[0]

to your __setstate__() implementation (it prints True!).  The line
self.update(state[0])

consequently simply updates the instance with itself.


text:
Q: PDO search query, make it like Android contacts search I have tried to implement search in my gadget using LIKE query.
Now I have a new requirement where I have to make this search like the Android Search..
Query:
$stmt = $conn->prepare("SELECT ROOM, GUEST_NAME, GUEST_FIRST_NAME, CONFIRMATION_NO, DEPARTURE, PWD FROM RESERVATION_GENERAL_2 WHERE LOWER(GUEST_FIRST_NAME) LIKE ? OR LOWER(GUEST_NAME) LIKE ?");
$stmt->execute(array('%'.strtolower($searchFilter).'%','%'.strtolower($searchFilter).'%' ));

Let's suppose I have a string Syed Haider Hassan in database
and if I search san in the database table using the given query, it will find me this above string. Hence if I put anything that matches inside or anywhere in string it will get me this string.
But what I want is that when I search in database Hai or Has or Sy it should get me this string, but if  search san or even assan, the query should not show me the this string.
Means if search it must do search with startwith,  not from middle.
I think it might be possible if I remove % from start, but problem is then query will only see startwith on Syed, I want it apply startwith on every word as words are separated by space. Search Syed Haider Hassan differently.
But in simple words if you have Android Mobile, I have Galaxy S4, search any name in your contacts book. If you search from middle of word it will not search but if you search from start of word it will search, but that's just not it. If your contact name is combination of two words separated by space then it will also check for first Alphabet of second word.
How can I update my query to this new search criteria?
Update
I tried the match against as suggested in one of answer using try catch, I get this error:

Here is the code I tried:
$search_words = "+" . str_replace (" ", "* +", $searchFilter )."*";
        try {
            $stmt = $conn->prepare("SELECT ROOM, GUEST_NAME, GUEST_FIRST_NAME, CONFIRMATION_NO, DEPARTURE, PWD FROM RESERVATION_GENERAL_2 WHERE MATCH (GUEST_FIRST_NAME, GUEST_NAME) against (:SEARCH in boolean mode)");
            $stmt->bindValue(':SEARCH', $search_words, PDO::PARAM_STR);
            $stmt->execute();

        }
        catch(PDOException $e){
            echo 'ERROR: ' . $e->getMessage();
        }

How can I solve it?
Update 2
Simply I put the facts here. Here is my table structure:

If I use like with wildcard %%, it will search for even from middle of name.
Let's see the highlighted name in screenshot, the highlighted name is Lukasz Henryk.
If I search with wild card using like %enry%, it will find me this row.
but I don't want that, I want search should word with start of name.
e-g if I search Luk or Hen or He or even H, it should find me this row. Means starting alphabet is important, if starting alphabet don't match then don't give me the row.
I also tried a wildcard like query like this Henr% but it doesn't work because like this it only works for Luk%, it consider whole column as single string.
Is there a way to tell query to search for starting alphabet after space?

A: As other said the fulltext index is the way to go this is what you want your query to look like, the + makes all words required leave it out for looking up any words.  You cannot use the " double quote, with the * wildcard, which is reasonable because the double quote means exact word.  Which it cannot be when using the wild card. ( or at least I have yet to find a way to do it )
SELECT
    ROOM,
    GUEST_NAME,
    GUEST_FIRST_NAME,
    CONFIRMATION_NO,
    DEPARTURE,
    PWD
FROM
    RESERVATION_GENERAL_2
WHERE
    MATCH(GUEST_NAME, GUEST_FIRST_NAME)
AGAINST
    ( '+word* +word2*' IN BOOLEAN MODE )

Basically
  $search_words = '';
 foreach( explode(' ', $search) as $words ){
       $search_words .= '+'.$word.'* ';
 }

AND
...
WHERE
    MATCH(GUEST_NAME, GUEST_FIRST_NAME)
AGAINST
    ( :search_words IN BOOLEAN MODE )

 $stmt->bindValue(':search_words', $search_words, PDO::PARAM_STR);

Etc...
But you have to have a full text index, in this case a composite one on GUEST_NAME, GUEST_FIRST_NAME.
See also this
MySQL Full Text Search Mystery

A: You could use MySQL:s MATCH AGAINST. Remember that you have to make a FULLTEXT index containing the GUEST_FIRST_NAME and GUEST_NAME (in this order).
Just an example:
$string = "syed haider";
$search_words = "+" . str_replace (" ", "* +", $string )."*";

$query = "SELECT ROOM, GUEST_NAME, GUEST_FIRST_NAME, CONFIRMATION_NO, DEPARTURE, PWD FROM RESERVATION_GENERAL_2 WHERE MATCH (GUEST_FIRST_NAME) against ('$search_words' in boolean mode) OR MATCH (GUEST_NAME) against ('$search_words' in boolean mode)";

// SELECT ROOM, GUEST_NAME, GUEST_FIRST_NAME, CONFIRMATION_NO, DEPARTURE, PWD FROM RESERVATION_GENERAL_2 WHERE MATCH (GUEST_FIRST_NAME) against ('+syed* +haider*' in boolean mode) OR MATCH (GUEST_NAME) against ('+syed* +haider*' in boolean mode)

A: have you tried mysql regexp (rlike)?
table setup:
CREATE TABLE `user` (
  `name` varchar(50) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `user` (`name`)
VALUES
    ('Syed Haider Hassan');

query:
select * from user where name rlike '[[:<:]]Hass'

returns:
name
Syed Haider Hassan

not matching query:
select * from user where name rlike '[[:<:]]san'

returns:
name

A: Your issue comes from search string ($search_words = "+" . str_replace (" ", "* +", $searchFilter )."*";), cause relational operator is "+,-,< >, etc.", that's why you need first see your complete query.
Make this steps:

*

*echo your sql query and try to execute in some MySql GUI (e.g. Navicat) for be sure that your query haven't errors.

*Be sure GUEST_FIRST_NAME, GUEST_NAME fields index is "Full Text". For that you need to execute "ALTER TABLE RESERVATION_GENERAL_2
ADD FULLTEXT INDEX name_index (GUEST_FIRST_NAME, GUEST_NAME) ;"

Try this steps and let me know.


text:
Q: Convert output from command or file to json My script delivers the following outout which i need to convert into json structure. Convert via Perl or other on AIX is part of the path I suppose. Now im reading lots of docs and doing trials (=no success so far)..
Any help/direction is appreciated :-)
TEST                            STATUS          FAIL REASON
----                            ------          -----------
Security Profile                PASS
Group Check                     FAIL            Errors detected in group definition files
User Check                      FAIL            Errors detected in user definition files
Service hostmibd                FAIL            Active
Service aixmibd                 FAIL            Active
Subserver shell                 FAIL            Active
Subserver kshell                FAIL            Active
Subserver login                 FAIL            Active
Subserver exec                  FAIL            Active
Subserver bootps                FAIL            Active
Subserver tftp                  FAIL            Active
Subserver ntalk                 FAIL            Active
SNMP version                    FAIL            snmpdv3ne
SNMP community                  PASS
SSHD status                     PASS

A: This program reads your sample data from the DATA file handle and builds a JSON data structure from it.
The position of the data in each column is established by examining the line of hyphens beneath the headers. The fields are extracted from each line using unpack together with a template derived from those positions.
The JSON module is used to test the result by converting it into a Perl data structure, the result of which is dumped using Data::Dump.
Double quotes embedded within the data is supported.
Hopefully you will be able to amend this code to read from your desired input file instead of from DATA, and do whatever you want with the resulting JSON data.
use strict;
use warnings;
use 5.014;    # For non-destructive tr/// and s///

my $headers = <DATA>;
my $dashes = <DATA>;
my @offsets;
push @offsets, $-[0] while $dashes =~ /-+/g;

my @widths = map { $offsets[$_]-$offsets[$_-1] } 1 .. $#offsets;
push @widths, '*';
my $unpack = join ' ', map "A$_", @widths;

my @headers = map { lc =~ tr/ /_/r } unpack $unpack, $headers;

my @lines;

while (<DATA>) {
  next unless /\S/;
  my @fields = map s/"/\\"/gr, unpack $unpack, $_;
  push @lines, '  {' . join(', ', map qq{"$headers[$_]":"$fields[$_]"}, 0 .. $#fields). '}';
}

my $json = "[\n" . join(",\n", @lines) . "\n]\n";

print $json, "\n\n";

use JSON;
use Data::Dump;
dd from_json $json;

__DATA__
TEST                            STATUS          FAIL REASON
----                            ------          -----------
Security Profile                PASS
Group Check                     FAIL            Errors detected in group definition files
User Check                      FAIL            Errors detected in user definition files
Service hostmibd                FAIL            Active
Service aixmibd                 FAIL            Active
Subserver shell                 FAIL            Active
Subserver kshell                FAIL            Active
Subserver login                 FAIL            Active
Subserver exec                  FAIL            Active
Subserver bootps                FAIL            Active
Subserver tftp                  FAIL            Active
Subserver ntalk                 FAIL            Active
SNMP version                    FAIL            snmpdv3ne
SNMP community                  PASS
SSHD status                     PASS

output JSON
[
  {"test":"Security Profile", "status":" PASS", "fail_reason":""},
  {"test":"Group Check", "status":"FAIL", "fail_reason":"Errors detected in group definition files"},
  {"test":"User Check", "status":"FAIL", "fail_reason":"Errors detected in user definition files"},
  {"test":"Service hostmibd", "status":"FAIL", "fail_reason":"Active"},
  {"test":"Service aixmibd", "status":"FAIL", "fail_reason":"Active"},
  {"test":"Subserver shell", "status":"FAIL", "fail_reason":"Active"},
  {"test":"Subserver kshell", "status":"FAIL", "fail_reason":"Active"},
  {"test":"Subserver login", "status":"FAIL", "fail_reason":"Active"},
  {"test":"Subserver exec", "status":"FAIL", "fail_reason":"Active"},
  {"test":"Subserver bootps", "status":"FAIL", "fail_reason":"Active"},
  {"test":"Subserver tftp", "status":"FAIL", "fail_reason":"Active"},
  {"test":"Subserver ntalk", "status":"FAIL", "fail_reason":"Active"},
  {"test":"SNMP version", "status":"FAIL", "fail_reason":"snmpdv3ne"},
  {"test":"SNMP community", "status":"PASS", "fail_reason":""},
  {"test":"SSHD status", "status":"PASS", "fail_reason":""}
]

output Perl data
[
  { fail_reason => "", status => " PASS", test => "Security Profile" },
  {
    fail_reason => "Errors detected in group definition files",
    status => "FAIL",
    test => "Group Check",
  },
  {
    fail_reason => "Errors detected in user definition files",
    status => "FAIL",
    test => "User Check",
  },
  { fail_reason => "Active", status => "FAIL", test => "Service hostmibd" },
  { fail_reason => "Active", status => "FAIL", test => "Service aixmibd" },
  { fail_reason => "Active", status => "FAIL", test => "Subserver shell" },
  { fail_reason => "Active", status => "FAIL", test => "Subserver kshell" },
  { fail_reason => "Active", status => "FAIL", test => "Subserver login" },
  { fail_reason => "Active", status => "FAIL", test => "Subserver exec" },
  { fail_reason => "Active", status => "FAIL", test => "Subserver bootps" },
  { fail_reason => "Active", status => "FAIL", test => "Subserver tftp" },
  { fail_reason => "Active", status => "FAIL", test => "Subserver ntalk" },
  { fail_reason => "snmpdv3ne", status => "FAIL", test => "SNMP version" },
  { fail_reason => "", status => "PASS", test => "SNMP community" },
  { fail_reason => "", status => "PASS", test => "SSHD status" },
]

A: Fixed length data is always a good sign for unpack.
You'll need the JSON module for the conversion. This program reads from STDIN and takes files as arguments.
#!/usr/bin/env perl
use warnings;
use strict;
use JSON;

my @names = qw<test status fail_reason>;
my @return;
while(<>){
  next if $. < 3;     # skip the header
  chomp;
  my (%obj);
  @obj{@names} = grep {$_} unpack 'A32A16A*';
  push @return, \%obj;
}

print encode_json \@return;

output:
[{"status":"PASS","fail_reason":null,"test":"Security Profile"},{"status":"FAIL","test":"Group Check","fail_reason":"Errors detected in group definition files"},{"test":"User Check","fail_reason":"Errors detected in user definition files","status":"FAIL"},{"test":"Service hostmibd","fail_reason":"Active","status":"FAIL"},{"status":"FAIL","test":"Service aixmibd","fail_reason":"Active"},{"test":"Subserver shell","fail_reason":"Active","status":"FAIL"},{"status":"FAIL","fail_reason":"Active","test":"Subserver kshell"},{"status":"FAIL","test":"Subserver login","fail_reason":"Active"},{"fail_reason":"Active","test":"Subserver exec","status":"FAIL"},{"status":"FAIL","test":"Subserver bootps","fail_reason":"Active"},{"fail_reason":"Active","test":"Subserver tftp","status":"FAIL"},{"fail_reason":"Active","test":"Subserver ntalk","status":"FAIL"},{"fail_reason":"snmpdv3ne","test":"SNMP version","status":"FAIL"},{"test":"SNMP community","fail_reason":null,"status":"PASS"},{"test":"SSHD status","fail_reason":null,"status":"PASS"}]

Edits:
with this line you can exlude empty fields (if the status is pass, there will be no fail reason).
    delete $obj{$_} foreach grep {$obj{$_} eq '' or not defined $obj{$_} keys %obj;

If you have more files like this with different field sizes, here is a version that extracts the length of the fields itself:
my (@return, @names, $head_line, $pack_template);
while (<>) {
  chomp;
  if ($. == 1) {      # set the header line
    $head_line = $_;
  }
  elsif($. == 2){
                        # extract the lengths from the second line
    my @lengths = map(length, (/(-+\s*)/g));
    $lengths[-1]= '*';  # replace the last length with * as a catch rest
    $pack_template = join '', map {"A$_"} @lengths;
    @names = unpack $pack_template, $head_line;
  } else {
    my (%obj);
    @obj{@names} = unpack $pack_template;
    push @return, \%obj;
  }
}


text:
Q: Only some embedded YouTube videos fetched from SpaceX API do not load in browser I have a webpage where I'm displaying data pulled from a SpaceX API: SpaceX API
Published site: Gatsby SpaceX data
I'm trying to display a youtube embed for each of the launches in the pastLaunches component. I'm receiving the following error in the browser: 'Refused to display '' in a frame because it set 'X-Frame-Options' to 'sameorigin'.' I've tried adjusting my configuration file (netlify.toml) but nothing has worked so far. I'm also only receiving this error for the videos that refuse to load. Again, some of the videos DO load. It also looks like the videos that aren't working are not converting from watch/ to embed/. I'm somewhat new to React and haven't dealt with this level of functionality yet, any tips while I continue to research are helpful!
Here is the section where I'm using the youtube link:
{links.video_link
                ?
          :
Sorry, no Youtube video is available

            }

Here is the full component:
import React, { useState, useEffect }  from 'react'
import moment from "moment"
import "../styles/tailwind.css"

const getPastLaunches = () => {
  return fetch('https://api.spacexdata.com/v3/launches/past?limit=50&sort=flight_number&order=desc')
  .then((res) => res.json())
}

const PastLaunches = () => {
  const [launches, setLaunches] = useState(null)

  useEffect(() => {
    getPastLaunches()
      .then(setLaunches)
  }, [])

  if (launches === null) {
    return
Loading past launches...

  }

  return (
    <>

Recent Launches

                <svg width="20" height="20" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="#ffffff">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={4} d="M19 14l-7 7m0 0l-7-7m7 7V3"  />
        </svg>

    {launches.map(launch => {
        const {flight_number, details, mission_name, launch_date_local, links, rocket, launch_site} = launch;

      return (

            {links.video_link
                ?
          :
Sorry, no Youtube video is available

            }

Rocket: {rocket.rocket_name}

              Flight # {flight_number}

Mission: {mission_name}

Location: {launch_site.site_name_long}

Launch Date: {moment(launch_date_local).format("dddd, MMMM Do YYYY, h:mm:ss a")}

              {details
                ?
{details}

          : I'm sorry, no details are available for this launch
            }

      );
    })}

</>

  )
}

export default PastLaunches

And my current netlify.toml:
[build]
  functions = "/root"

[[headers]]
  # Define which paths this specific [[headers]] block will cover.
  for = "/*"
    [headers.values]
    Access-Control-Allow-Origin = "*"
    cache-control = '''
    max-age=0,
    no-cache,
    no-store,
    must-revalidate'''

Here are is a screenshot for the error:

Error message for broken video:

Successful video:

A: I suspect SpaceX has disabled embedding for some of their videos. The X-Frame-Options HTTP header tells the browser where the content can be embedded via framing. The sameorigin value prevents embedding on domain names other than the one the content is being retrieved from.


text:
Q: Failed to build EGG files for matplotlib with error of freetype and libpng

I'm trying to build EGG files for matplotlib on Windows 7
==> Get "matplotlib-2.1.0rc1.tar.gz" from "https://pypi.python.org/pypi/matplotlib/"
==> Unzip and enter the root folder "matplotlib-2.1.0rc1" by CMD window
==> Run command "python setup.py bdist_egg"

But there are some errors, it is failed to create EGG files for matplotlib
Error messages:
...
...
freetype: no  [The C/C++ header for freetype (freetype2\ft2build.h) could not be found.  You may need to install the development package.]
...
...
png: no  [The C/C++ header for png (png.h) could not be found.  You may need to install the development package.]
...
...
The following required packages can not be built: freetype, png
Please check http: //gnuwin32.sourc eforge.net/packages/freetype.htm for instructions to install freetype
Please check http: //gnuwin32 .sourceforge.net/packages/libpng.htm for instructions to install png

I've tried many ways (with the tips of error messages, or some other sharing on internet) to install freetpye and libpng, but it's still failed

It seems the "setup.py" of matplotlib cannot recognize the path of freetype and libpng for "ft2build.h" and "png.h"

How should I install freetype and libpng to make matplotlib correctly built?
Is there any other settings wrong in my EGG building steps?
Thanks!


text:
Q: Why can't you have a non-const char* in C++? Why does this work:
char foo[6] = "shock";`

while this does not work:
char* bar = "shock"; //error

Why does bar have to be const while foo doesn't? Arrays in C decay to pointers, so don't foo and bar technically have the same types?

A: Literals are held in reserved areas of memory that are not supposed to be changed by code. Changing the value held at the address storing that literal would mean that every time any other code tried to use that literal, it would find the wrong value in that memory. So it is illegal to modify that memory, and hence illegal to treat it as not constant.
Source

A: With this declaration:
char foo[6] = "shock";

Variable foo is type array of char and it containes 6 non-const chars. The string literal contains const chars which are copied into the array on initialization.
While with this declaration:
char* bar = "shock"; //error

Variable bar is type pointer to char. You are trying to make it point to the address of "shock" which is a string literal containing const char.
You can't point a pointer to non-const char at a const char.
So you must do this:
const char* bar = "shock";`

A: because "shock" is a constant, so a pointer to it must be const
for historical reasons C allows this (and causes many errors that lead to SO posts)

A: char* bar = "shock";

is roughly equivalent to
const char anonymousArray[6] = "shock";
char *bar = anonymousArray;

Arrays decays to pointers. That's not the same as actually being pointers.


text:
Q: custom Rxjs filterNullish operator that takes array of values and changes each return type I have this custom operator that filters out nullish values (undefined and null) and also changes the return type to indicate that undefined or null is no longer a possible value.
Now I would like to expand this operator to not only take a single typed value but also support an array of typed values and filter if any of the arrays values are nullish and use the correct return type, such that it can be used in merge operator chain like combineLatest
export function filterNullish<T>(): UnaryFunction<Observable<T | null | undefined>, Observable<T>> {
  return pipe(filter(notNullish));
}

function notNullish<T>(value?: T | null | undefined): value is T {
  return value != null && value != undefined;
}

Current usage, this works:
  obs$ = this.store.select(selectSomething).pipe(
    // type of something is possibly null
    filterNullish(),
    // type of something is not null anymore
    map((something) => this.createOtherThing(something))
  );

Desired usage:
combineLatest([this.something$, this.otherthing$]).pipe(
  filterNullish(),
  // I want typescript to know EACH of the arrays elements types are not nullish anymore
  tap(([something, otherthing]) => {
    // do stuff knowing something and otherthing can not be nullish anymore
  })
)

A: fixed by constructing new array by filterNullish per element and passing tuple type:
export const filterNullishAll: <T>() => OperatorFunction<Array<any>, T> = <
  T
>() =>
  pipe(
    map((collection: any[]): T | null =>
      collection.every(notNullish) ? ([...collection] as T) : null
    ),
    filter(notNullish)
  );

Usage:
combineLatest([this.something$, this.otherthing$]).pipe(
  filterNullishAll<[SomethingType, OtherThingType]>(),
  tap(([something, otherthing]) => {
    // do stuff knowing something and otherthing can not be nullish anymore
  })
)


text:
Q: How to configure ajax request with jquery in django? So I was doing a django project by following a youtube video. And I got this error:
"Forbidden (403) CSRF verification failed. Request aborted."

everytime when I submit any  data in my sign-up.html file.
Then I realize I did not configure ajax correctly. So I search online and saw the django documentation of ajax. I made some changes in my html code. still, it did not solve my problem.
I am still getting the same result. What is my mistake here. Did I made any mistake while configuring ajax?
"assets/js/django-ajax.js"
This is where i save the jquery file.
Its been a while since I am stuck in this problem.
Thank you for your time
My sign-up.html file:
 {% load static %}
    <!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Instapic</title>
        <link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}">
        <link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}">
        <link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">

            <form method="post">
                {% csrf_token %}

Login Form

                    <input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4">

                    <input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6">

                    <input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6">

                    <button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button>

Already got an account? Login here ...</form>

My ajax configureation:
    // using jQuery
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function sameOrigin(url) {
        // test that a given url is a same-origin URL
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

A: Your click handler does not prevent the event from propagating. When your event handler has run the event will propagate and will eventually submit the form as a regular browser POST. You need to prevent this from happening
$('#go').click(function(event) {
    event.stopPropagation();

A: I would suggest, add your csrf_token in every ajax.post for test, to be sure that generated token in cookies is correct.
Example:
$.ajax({
    type: 'POST',
    url: "",
    data: {
        username: $("#username").val(),
        email: $("#email").val(),
        password: $("#password").val(),
        'csrfmiddlewaretoken': getCookie('csrftoken')
    }
})

In your code. you defined method getCookie in JS, create variable csrf_token and implement this variable in ajaxSetup. Well, token is changing, but your script does not reload it.
If you want to use ajax.setup, put inside there the method getCookie, to be sure that ajax before send retakes correct token.


text:
Q: Use envars on swagger for dynamic configuration this may be trivial question, but I am having problems understanding server variables and how to modify them on swagger.
My objective is to create a server using the specs below (5G 3gpp definitions for of its interfaces).
https://www.3gpp.org/ftp/Specs/archive/OpenAPI/Rel-16/TS29122_PfdManagement.yaml.
As you can see at the top of this file we have a server variable called apiRoot which defines the root of the url of the server. That is set up to default value of example.com. That url will later be used by swagger-ui to provide a graphic interface to the API.
servers:
  - url: '{apiRoot}/nnef-eventexposure/v1'
    variables:
      apiRoot:
        default: https://example.com
        description: apiRoot as defined in clause 4.4 of 3GPP TS 29.501

I am trying to generate the server with the swagger-codegen which generates a consolidated file with all the elements this spec needs (since the original yaml file contains references to other files)
swagger-codegen generate -i  https://www.3gpp.org/ftp/Specs/archive/OpenAPI/Rel-16/TS29122_PfdManagement.yaml   -l go-server -o server

The problem is the file embeds the default value. So I can not use that file on multiple hosts.
Is there any way to modify variable apiRoot when executing swagger-codegen? Or even better, is there any way to change the value of the default using some kind of envar? Or is there any way to pass swagger the value of apiRoot
The idea is we can use the same specs in different servers without having to modify the original spec file or the generated one. The problem with modifying the yaml files is that there will be more versions comming from 3gpp which will include apiRoot variable, so we don't wang to keep modifying every single time. We would like to overwrite it somehow on runtime.


text:
Q: Passing Values from datagridview to listview Please help me. How can I pass values form data grid view to list view using C# object oriented?
please help me convert to C# .Thanks in advance.
        Dim i As Integer
        i = dtgShift.CurrentRow.Index
        shiftID = dtgShift.Item(0, i).Value
        txtShiftName.Text = dtgShift.Item(1, i).Value
        dblInputShiftHrs.Text = dtgShift.Item(2, i).Value
        Dim lvitem As ListViewItem
        If dtgShift.Item(3, i).Value.ToString <> "" Then
            chkMon.Checked = True
            lvitem = lvSched.Items.Add("Monday")
            lvitem.SubItems.Add(dtgShift.Item(3, i).Value.ToString)
            lvitem.SubItems.Add(dtgShift.Item(4, i).Value.ToString)
        End If

A: According to your VB code given this is how C# lloks like;
int i = dtgShift.CurrentRow.Index;
shiftID = dtgShift[0, i].Value;
txtShiftName.Text = dtgShift[1, i].Value.ToString();
dblInputShiftHrs.Text = dtgShift[2, i].Value.ToString();
ListViewItem lvitem = default(ListViewItem);

if (!string.IsNullOrWhiteSpace(dtgShift[3, i].Value.ToString()))
{
     chkMon.Checked = true;
     lvitem = lvSched.Items.Add("Monday");
     lvitem.SubItems.Add(dtgShift[3, i].Value.ToString());
     lvitem.SubItems.Add(dtgShift[4, i].Value.ToString());
}

A: thanks sir @Irshad
. I made it
        ListViewItem listview;
        if(_schedule.MondayFrom != "")
        {
            checkBoxMon.Checked = true;
            listview = listViewEditSchedule.Items.Add("Monday");
            listview.SubItems.Add(_schedule.MondayFrom);
            listview.SubItems.Add(_schedule.MondayTo);
        }


text:
Q: Is TensorFlow XLA deprecated? I just read (here):

Deprecating XLA_CPU and XLA_GPU devices with this release. (TF 2.2.0)

Is XLA deprecated now? It is not used anymore? Is there an alternative?
Or is this all automatically handled internally? What does this deprecation mean?

A: No, XLA is not being deprecated, in fact there are other release notes about it:

*

*XLA

*

*XLA now builds and works on windows. All prebuilt packages come with XLA available.

*XLA can be enabled for a tf.function with "compile or throw exception" semantics on CPU and GPU.

This note is actually related to the deprecation that you mention. What is being deprecated is using the strings XLA_CPU and XLA_GPU with tf.device. See the deprecation warning message:
XLA_GPU and XLA_CPU devices are deprecated and will be
removed in subsequent releases. Instead, use either
@tf.function(experimental_compile=True) for must-compile
semantics, or run with TF_XLA_FLAGS=--tf_xla_auto_jit=2
for auto-clustering best-effort compilation.

That is what the other release note was talking about, which is mentioned in the XLA guide under Explicit compilation with tf.function.


text:
Q: column "invited_by_id" cannot be cast automatically to type uuid I am trying to use devise_invitable. But the thing is it will generate a column invited_by_id automatically for us to reference to the parent model. But the problem is invited_by_id is integer, but the parent model id is of type uuid.
Now I wrote a migration to convert id to uuid
class ChangeInvitedById < ActiveRecord::Migration
  def change
    change_column :employees, :invited_by_id, :uuid, default: 'uuid_generate_v4()'
  end
end

But this giving me this error
PG::DatatypeMismatch: ERROR:  column "invited_by_id" cannot be cast automatically to type uuid
HINT:  You might need to specify "USING invited_by_id::uuid".

I already have a migration which has this enable_extension 'uuid-ossp'


text:
Q: Error during VSTS Account creation Azure using Azure Arm templates I am trying to create VSTS account on Azure using Arm Template.
I am using msrestazure python module for deploying the templates.
But i am getting the following error :

Azure Error: DeploymentFailed
          Message: At least one resource deployment operation failed. Please list deployment operations for details. Please see
  https://aka.ms/arm-debug for usage details.
          Exception Details:
                  Error Code: BadRequest
                  Message: {
            "code": "BadArgument",
            "message": "The string must have at least one character.\r\nParameter name: accountName",
            "target": "LegacyGetOrCreateBindPendingIdentity"
          }
                  Target: None

I am providing the value for parameter accountName but still it says that the string must have at least one character.Also i am able to create account using UI. Please help :)

A: The message is not clear, but it could be that your user doesn't have enough permission; no guests are allowed to create Account.
You can validate that you are a member by going to the Users and groups section


text:
Q: How to distribute a content of File into several nodes? I need to distribute the content of a file (upto 5 GB) over a Network such that each distributed node(XML or Simple File) of a file won't have replicate data and get synced with each other.
On a bigger note there could be more than 1000 of Big Files which needs to be take place in Distribution process.
Can i use Hadoop HDFS for Storing Big Files and use cluster Nodes for Distributed data?

A: Well yes, that's exactly what HDFS is used for.  You can control the replication factor easily if you don't want any duplication, but a replication factor of 2+ is usually recommended to allow for some high availability.


text:
Q: Load textures while playing For my 2D game :
While playing, I have to load some large texture2D (2000x2500 pixels) and Unload some others.
Of course I want to Load and Unload texture2D without game/draw freeze (or the lesser...) :x
I don't know if it's possible.
I already use a thread to load some texture while drawing the "Loading screen"
//thread Loading
ThreadStart th_loadingScreen = delegate { DisplayLoading(LoadingScreen); };
new Thread(th_loadingScreen).Start();

But I think it's pretty different.
Of course, I tried something :
private void LoadUnload()
{
    for (int j = 0; j <= NbrRow; j++)
        for (int i = 0; i <= NbrCol; i++)
        {
            if(somethingTrue)
            {
                ThreadStart th_LoadInGame = delegate
                    {
                        LoadInGame(i, j, TextureStringPathToLoad);
                    };
                new Thread(th_LoadInGame).Start();
            }
        }
}

But I have a little freeze.
And, I know how to unload the content, but I don't know how to unload a single loaded texture :x

A: There's no way to unload individual elements within a ContentManager object. So, what I do is make multiple ContentManagers and split up what I need to among them. That way I can Unload one, for example, and keep others in memory still.
As for the little freeze you're seeing, threading by itself does not guarantee an absence of hiccups or the like. I would mess around with the Thread's Priority property; perhaps try setting it lower and see what happens. Even this is no guarantee however. From the article:

Operating systems are not required to honor the priority of a thread.


text:
Q: Cassandra - how can search by range in 2 key columns? How would I search by range on multiple key columns?
The way I see we cannot have a query which might go to multiple partitions.
Any possible solutions to achieve the same query results???
CREATE TABLE RangeSearch (segment TEXT, date TIMESTAMP, dec decimal, value text, PRIMARY KEY (segment,date,dec));

SELECT * FROM decimalrangeck
WHERE segment='SEG1'
AND date>='2015-01-01' AND date<='2015-12-12';
AND dec>=100 AND dec<=200;

A: Short answer: there is no way to have an efficient range query for two or more clustering columns in Cassandra.
Long answer: to understand the core reasons for this limitation, you should consider the way how Cassandra stores columns inside a single partition.
All rows inside partition in a single SSTable file are sorted according to their clustering keys, like for your schema:
2015-01-01 100
2015-01-01 200
2015-01-01 300
2015-01-02 100
2015-01-02 200
2015-01-02 300
2015-01-03 100

There is a way to read a single slice of data (by using range query like SELECT * FROM decimalrangeck WHERE segment='SEG1' AND date>='2015-01-01' AND date<'2015-01-03';). For this query Cassandra will issue a single disk seek for rows because it definitely knows where the required data starts and ends (as it's sorted on disk).
You can even have a two-column slice query like SELECT * FROM decimalrangeck WHERE segment='SEG1' AND date>='2015-01-01' AND date<'2015-01-03' AND dec>=100 AND dec<=200. I believe you'll expect these results:
2015-01-01 100
2015-01-01 200
2015-01-02 100
2015-01-02 200

But you'll get a slightly surprising output:
2015-01-01 100
2015-01-01 200
2015-01-01 300
2015-01-02 100
2015-01-02 200

The difference is a row 2015-01-01 300. It appears in output for a reason: your query is split into two parts: the start of the slice (2015-01-01,100) and the end of the slice (2015-03-01, 100). After that Cassandra reads all the data in between these data points in a single disk seek.
The original range query for 2 clustering columns will require too many disk reads to complete. Such queries typically are considered too performance-unfriendly.

A: Yes, you can do it by using spark with scala and spark-cassandra-connector!
Then you could use something like:
val conf = new SparkConf().setAppName(appName)
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
val cc = new CassandraSQLContext(sc)

def getDays(startDate: String, endDate: String) : scala.Array[String] = {
    var dates = scala.Array[String]()

    var sDate = sdfDay.parseDateTime(startDate)
    var eDate = sdfDay.parseDateTime(endDate)

    var date = ""

    while(sDate.isBefore(eDate.plusDays(1)) == true){
        var sDay = sDate.getDayOfMonth()
        var sMonth = sDate.getMonthOfYear()
        var sYear = sDate.getYear()

        date = "" + sYear + "-" + sMonth + "-" + sDay
        println(date)
        dates :+= date

        sDate = sDate.plusDays(1)
    }

    dates //return
}

def preaperQuery(wereElement: String, andDateElement: String, andDecElement: String, tableName: String, days: scala.Array[String], decs: scala.Array[String]) : String = {
    var q = "select * from " + tableName + "where " + wereElement + " and "
    for (day <- days) {
        q = q + andDateElement + " = '" + day + "' or "
    }

    for (dec <- decs) {
        q = q + andDecElement + " = '" + dec + "' or "
    }
    //remove last " or " 4 chars
    q = q.dropRight(4)
    q //return
}

val days = Utils.getDays(startDate, endDate)
val decs = Array("100", "200", "300", "400") //or any function

var q = Utils.preaperQuery(wereElement="segment='SEG1'", andDateElement="date", andDecElement="ec", tableName="RangeSearch", days=days, decs=decs)

val selected_data = cc.sql(q).map(row => (row(0).toString, row(1).toString,row(2).toString,row(3).toString))

And there you have your selected data rdd that you could collect:
val data = selected_data.collect

I had similar problem...


text:
Q: ¿Por qué me queda denegado, el permiso para archivo adjunto, usando Android? últimamente que querido implementar en mi aplicación, la opción de adjuntar una imagen a un correo electrónico mediante código de Java para Android, utilizando "Intent", pero al momento de crear el correo, la aplicación de Gmail, me dice: Se denegó el permiso para el archivo adjunto.
La imagen la obtengo desde mi ImageView, lo guardo en canche, obtengo la ruta de donde se guardo, y le paso el Uri al Intent. Pues quería saber que mas le falta el código, para que pueda funcionar, por que ya intente varias formas.
-Gracias
Obtención de la imagen del ImageView:
 mImageProduct = (ImageView)findViewById(R.id.product_image_view_order_editor);
 mImageProduct.buildDrawingCache();
 Bitmap imageProduct = mImageProduct.getDrawingCache();

Código del Intent:
private void composeEmail(String[] emailProvider, String quantityCurrent, String currentDay, String nameProduct, Bitmap imageProduct) {

    File file = new File(getCacheDir(), imageProduct + ".png");

    try {
        FileOutputStream outputStream = new FileOutputStream(file);
        imageProduct.compress(Bitmap.CompressFormat.PNG, 100, outputStream);

        outputStream.flush();
        outputStream.close();
        Log.e(OrderEditorActivity.class.getSimpleName(), file.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
        file = null;
    }

    String subject = getString(R.string.msg_subject);

    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, emailProvider);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, createdOrder(quantityCurrent, currentDay, nameProduct));
    if(file != null) {
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
    }
    intent.setType("*/*");

    if(intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    } else {
        Toast.makeText(this, getString(R.string.msg_error_email), Toast.LENGTH_SHORT).show();
    }
}

Error que se muestra en pantalla al momento de ejecutar el botón de enviar:

A: Gmail agregó algunas comprobaciones de seguridad a los archivos adjuntos que se reciben de un intent, cambia startActivity por startActivityForResult. Debería funcionar. Y no olvides los permisos en el Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

A: El problema es que al crear el archivo, estas usando getCacheDir()
 File file = new File(getCacheDir(), imageProduct + ".png");

getCacheDir() Devuelve una instancia de File que representa un
  directorio interno de los archivos temporales de caché de tu app.
  Asegúrate de eliminar cada archivo cuando ya no sea necesario y de
  implementar un límite razonable para la cantidad de memoria que se
  utiliza en un momento determinado, por ejemplo, 1MB. Si el sistema
  comienza a quedarse sin espacio de almacenamiento, es posible que
  elimine tus archivos de caché sin previo aviso.

El archivo lo generas en el directorio interno, para que se pueda anexar a tu email, debes realizar una copia al externo o bien generarlo en el directorio externo mediante  getExternalCacheDir():
File file = new File(getExternalCacheDir(), imageProduct + ".png");

getExternalCacheDir(): Devuelve la ruta absoluta al directorio
  específico de la aplicación en el dispositivo de almacenamiento
  compartido / externo principal donde la aplicación puede colocar los
  archivos de caché que posee. Estos archivos son internos a la
  aplicación y normalmente no son visibles para el usuario como medios.

Obviamente necesitas los permisos :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


text:
Q: How do I use a type with the same name of another type in another referenced assembly? I have the absurd situation (don't blame me, it is third party software) where I need to have two references (Erp.Contracts.BO.Quote and Erp.Contracts.BO.SalesOrder), but the type Erp.Tablesets.QuoteQtyRow is defined in both assemblies!
How do I use them in code?
void Absurdity()
{
    Erp.Tablesets.QuoteQtyRow qqr_Quote = null; //<-- my intention is to use the one from the quote assembly here.
    Erp.Tablesets.QuoteQtyRow qqr_SO = null; //<-- my intention is to use the one from the sales order assembly here.
}

The compiler throws an error. Namely: "The type 'Erp.Tablesets.QuoteQtyRow' exists in both assemblies."
EDIT: LIMITATIONS:

*

*I do not have the flexibility of using an extern alias as provided in this answer Class with same name in two assemblies (intentionally). I am limited by the environment supplied by the third party software. I essentially need a way to make the distinction within the body of a method.

*I understand I can avoid this problem altogether by using the dynamic keyword, but I am looking for a possible strongly typed solution.

*There may not be a solution, but I want to exhaust all my resources before I give up on the problem.

A: Epicor ERP uses a tool to put together tables from the DB into datasets, and then on into Business objects. This business object is described in the contract assembly, but as you have found when you use two business object that references the same table you run into problems. This is more commonly an issue with the SerialNumber tables.
I understand from your notes that you are providing method body code in a Method Directive or data Directive within the Epicor ERP application. This is entered on the client and stored in the database but generates code on the server in the Deployment\Server\BPM\Sources\BO folder and is compiled to the Deployment\Server\Customization\BO folder.
There is no way to specify an alias for the referenced DLL in the "Execute Custom Code" workflow item of the BPM designer. The fix is requested in SCR 148549.  There is no project file for you to edit, and even if there was every time the BPM was enabled and disabled it would be regenerated.
However, if you use the "Invoke External Method" workflow item, then you can build your own dll and put it in the Deployment\Server\Customization\Externals folder. To do that:

*

*Click Actions > Create Programming Interfaces for your method in Method Directive Maintenance for your BPM and copy the code.

*Create a new Class library project in Visual Studio

*Paste the copied code into the .cs file

*Add Assemblies - Framework references:

*

*System.Data.Entity

*System.ServiceModel

*System.Transactions

*Add file references to

*

*Bin\Epicor.ServiceModel.dll

*Assemblies\Epicor.Ice.dll

*Assemblies\Epicor.System.dll

*Assemblies\Ice.Data.Model.dll

*Assemblies\Erp.Data.910100.dll

*And add a reference for the BPM's BO i.e.

*

*Assemblies\Erp.Contracts.BO.Quote.dll

*Ensure all the references have Copy Local set to false.

*Inherit from Ice.ContextBoundBase<Erp.ErpContext>

*Add a constructor that takes a context public MyQuote (Erp.ErpContext ctx) : base(ctx){ }
You can't quite copy and paste the "Execute Custom Code" body in as you won't have access to the tt row variables, these are all in the ds.


text:
Q: Replacing NAs with zeros only in non-empty groups I have a problem that should be easy to solve but I simply cannot figure it out. I have a huge dataset with groups and a variable. Some groups are empty for this variable (filled only with NAs) and some contains values but also NAs.
For example:
ID <- c("A1","A1","A1","A1","B1","B1","B1","B1", "B1", "C1", "C1", "C1")
Value1 <- c(0,2,1,1,NA,1,1,NA,1,NA,NA,NA)
data <- data.frame(ID, Value1)

I would like to change all NAs to zeros but only in groups that otherwise contain information.
So like this:
ID <- c("A1","A1","A1","A1","B1","B1","B1","B1","B1","C1","C1","C1")
Value1 <- c(0,2,1,1,0,1,1,0,1,NA,NA,NA)

I tried to use group_by(ID) and "replace" with the condition max(Value1)>=0 but either max() doesn't work as a condition or it doesn't work with NAs. Unfortunately I would need this kind of conditioning often in my work so I would also appreciate any suggestions on which are the best packages to treat groups selectively.

A: You can use a simple if` statement, i.e.
library(dplyr)
library(tidyr)

data %>%
 group_by(ID) %>%
 mutate(Value1 = if (all(is.na(Value1))){Value1}else{replace_na(Value1, 0)})

which gives,

# A tibble: 12 x 2
# Groups:   ID [3]
   ID    Value1
   <fct>  <dbl>
 1 A1         0
 2 A1         2
 3 A1         1
 4 A1         1
 5 B1         0
 6 B1         1
 7 B1         1
 8 B1         0
 9 B1         1
10 C1        NA
11 C1        NA
12 C1        NA

A: Here is a base R solution
dfout <- Reduce(rbind,
                lapply(split(data,data$ID),
                       function(v) {if (!all(is.na(v$Value1))) v$Value1[is.na(v$Value1)]<- 0; v}))

such that
> dfout
   ID Value1
1  A1      0
2  A1      2
3  A1      1
4  A1      1
5  B1      0
6  B1      1
7  B1      1
8  B1      0
9  B1      1
10 C1     NA
11 C1     NA
12 C1     NA

A: With dplyr:
data %>%
  group_by(ID) %>%
  mutate(Value1 = ifelse(any(!is.na(Value1)) & is.na(Value1), 0, Value1))

# A tibble: 12 x 2
# Groups:   ID [3]
   ID    Value1
   <fct>  <dbl>
 1 A1         0
 2 A1         2
 3 A1         1
 4 A1         1
 5 B1         0
 6 B1         1
 7 B1         1
 8 B1         0
 9 B1         1
10 C1        NA
11 C1        NA
12 C1        NA

A: Using data.table
setDT(data)
data[, Value1 := if (all(is.na(Value1))) NA else replace(Value1, is.na(Value1), 0), by = ID]

    ID Value1
 1: A1      0
 2: A1      2
 3: A1      1
 4: A1      1
 5: B1      0
 6: B1      1
 7: B1      1
 8: B1      0
 9: B1      1
10: C1     NA
11: C1     NA
12: C1     NA


text:
Q: Laravel nested array validation message I have a nested array of json that I need to validate. I'm trying to give the custom validation messages for the fields in the array. I've look through the docs and some posts but I still cant figure this out. The rules that I specified is:
    return [
        'member_id'                 => 'required|exists:member,id',
        'payment_method'            => 'required',
        'items.*.products.*.id'       => 'required|exists:product,id',
        'items.*.products.*.quantity' => 'required|integer|min:1',
        'items.*.packages.*.id'       => 'required|exists:package,id',
        'items.*.packages.*.quantity' => 'required|integer|min:1'
    ];

In my messages function
   public function messages(){
        return [
            'custom' => [
                'items.*.products.*.id' => [
                    'required'  => 'Product ID is required.',
                    'exists' => 'Selected product invalid.',
                ],
            ],
        ];
   }

However my validation message is still:
The selected items.0.products.0.id is invalid.

A: Have you tried using without custom key like this :
public function messages(){
    return [
         'items.*.products.*.id' => [
                'required'  => 'Product ID is required.',
                'exists'    => 'Selected product invalid.',
         ]
    ];
}

A: Try this:
   public function messages(){
        return [
            'items.*.products.*.id.required' => 'your message here',
            'items.*.products.*.id.exists' => 'your message here',
            'items.*.products.*.id.exists' => 'your message here',
            'items.*.products.*.quantity.required' => 'your message here',
            'items.*.products.*.quantity.integer' => 'your message here',
            'items.*.products.*.quantity.min' => 'your message here',
            // etc... you get the idea
        ];
   }

See: https://laravel.com/docs/5.7/validation#custom-error-messages
  Specifying A Custom Message For A Given Attribute

A: You can define just custom attribute names instead of a lot of custom messages!
public function attributes()
{
    return [
        'items.*.products.*.id' => 'product',
        'items.*.products.*.quantity' => 'product quantity',
        'items.*.packages.*.id' => 'package',
        'items.*.packages.*.quantity' => 'package quantity',
    ];
}

Your validation message would be: The selected product is invalid.

See: https://laravel.com/docs/5.8/validation#customizing-the-validation-attributes


text:
Q: Function IsEmpty() for Array I would like test if my array is empty or not.
I tried to use the function IsEmpty(), but the function returns always False. And don't enter in the if condition.
My code below :
Sub Freeze()

    Dim tab_freeze() as variant

    If IsEmpty(tab_freeze) Then
        ReDim tab_freeze(0)
    Else
        ReDim Preserve tab_freeze(UBound(tab_freeze) + 1)
        tab_freeze(UBound(tab_freeze)) = "As you want here"
     End If

End Sub

I would like function to know if my array tab_freeze is empty or not.
Or understand why IsEmpty(tab_freeze) returns False the first time.

A: IsEmpty is a standard library function that returns True when a variable of type Variant has an Empty subtype (Variant/Empty), which happens to be the case for Range.Value when there is no content in a cell.
In your case, you are not dealing with a Variant, you are dealing with an dynamic array of Variants.  Dynamic means that you first have to allocate space for a specific number of elements using the command ReDim. You could use IsEmpty(tab_freeze(1)) to check if  the first element was initialized - but that's probably not what you want.
Unfortunately, there is no build-in function on VBA that checks if a dynamic array is already allocated. There are quite some suggestions how to check, see for example How to check for empty array in vba macro. Personally, I use the following routine. It checks if a variable is declared as Array and its bounds. If an array is not allocated, LBound and UBound return a runtime error (and therefore the function will not get True). But it also handle the return-Value of split("") - which will give an LBound of 0 and UBound of -1
Function IsArrayAllocated(arr As Variant) As Boolean
    On Error Resume Next
    IsArrayAllocated = isArray(arr) _
                   And Not IsError(LBound(arr, 1)) _
                   And LBound(arr, 1) <= UBound(arr, 1)
End Function

A: Depending on what you understand under "empty array", there could be different answers. If you consider Dim tab_freeze() as variant as an empty array, as far as it has no dimensions in it, then this could work:
Public Function IsArrayEmpty(myArray As Variant) As Boolean

    On Error GoTo IsArrayEmpty_Error

    Dim tempVar As Variant
    tempVar = myArray(0)

    IsArrayEmpty = False

    On Error GoTo 0
    Exit Function

IsArrayEmpty_Error:

    IsArrayEmpty = True

End Function

There will be problems, if someone is using Option Base 1, thus the first element is not a 0, but 1. In general, this is considered, undimensionised array, but you may call it as you like (if you program alone, which is probably the case in VBA :) ).
If you consider Dim testArray(10) as Variant as an "Empty" array, then this would work:
Public Function IsArrayWithValuesAtAll(myArray As Variant) As Boolean
    IsArrayWithValuesAtAll = IsError(Application.Match("*", (myArray), 0))
End Function

A: For testing whether or not an array is empty, I usually Join() it with no delimiter and test its length.
Sub Freeze()

    Dim tab_freeze() As Variant

    Dim jArr As String

    jArr = Join(tab_freeze, "")

    If Len(jArr) = 0 Then
        ReDim tab_freeze(0)
    Else
        ReDim Preserve tab_freeze(UBound(tab_freeze) + 1)
        tab_freeze(UBound(tab_freeze)) = "As you want here"
    End If

End Sub

Although, it's good to note that this would return the same for an Empty array as it would an undimensioned one.

A: Thanks for all answers.
But I found the solution. Vba consider that for Dim tab_freeze() As Variant the tab_freeze is not empty, but UBound(tab_freeze) call an error.
So I just removed the parenthesis in the Dim :
Sub Freeze()

    Dim tab_freeze as variant

    If IsEmpty(tab_freeze) Then
        ReDim tab_freeze(0)
    Else
        ReDim Preserve tab_freeze(UBound(tab_freeze) + 1)
        tab_freeze(UBound(tab_freeze)) = "As you want here"
     End If

End Sub

A: Why not use a little VB magic the user Merri talked about in this vbforums thread instead of using a Variant to replace an Array of type Variant.

One of the common problems when dealing with arrays is to know when the array has been initialized and when it isn't. Luckily there is an easy native VB code solution:
Not Not ArrayName
What this does is to take the 32-bit pointer value in the array variable, mirror the bits, and then mirror them again. You now effectively know the pointer to the safe array structure. As a side effect you also know whether you can access the array with LBound and UBound.

Private Sub ArrayTest()
    Dim testArr() as Variant
    ' Prints False
    Debug.Print Not Not testArr

    ReDim testArr(0)
    ' This prints True
    Debug.Print Not Not testArr
End Sub

Merri also talked about problems that could occur, which I haven't stumbled upon yet, and we have to keep in mind that the post is about Visual Basic and not Visual Basic for Applications. (Mind you, I'm paraphrasing)
Apparently in some situations an error will be raised when using this method, which can be circumvented by running a simple Dim IDEbug() As Long: Debug.Assert Not IDEbug Or App.hInstance once before in the VB IDE.
Quoting again:

What happens here is that first we make a call to push up the possible error condition. Then we make a call to App.hInstance: we could make a call pretty much to any VB method, but since hInstance returns a Long number we use that. This, for whatever reason, makes all the following Not ArrayName calls work flawlessly. After the line has once executed in the IDE you can even comment the line and it's effects still remain. Only closing VB and opening it again will reset the condition so that you need to make the call again.

I want to emphasize that I did not come up with this solution, but it helped me tremendously. I also want to point out that I never executed the Debug.Assert Not someArray Or Application.Hinstance and have yet to encounter any issues. This might obviously be related to the fact that VBA is a tiny bit different from VB, but I can't say that for sure.


text:
Q: How to install PyDev 2.8.2 in Eclipse I want to install PyDev 2.8.2 in Eclipse because my Eclipse version is too old for 3.x.x compatibility. However by using the update site http://pydev.org/updates and having unchecked the box "Show only the latest versions ...", only 3.4.1 is showing up and I can't seen any 2.8.2.
I use Ubuntu and would like to know how to install 2.8.2.
I do not currenlty have any version installed.

A: The pydeve.org/updates URL/site only hosts the newest version of pydev. If you need to install a different version you need to change the URL to one from  http://www.pydev.org/update_sites/.
they are structured like http://www.pydev.org/update_sites/#.#.#

A: The link http://pydev.org/updates is just a re-direction to where the update site is now hosted, it appears.
Try with http://update-production-pydev.s3.amazonaws.com/pydev/updates
Also, make sure 'Show only latest version...' option is unchecked in the Install New Software wizard.

A: First download Pydev 2.8.2 version and put pydev 2.8.2 in eclipse-home/Addons.Next Restart your eclipse.Go to window---> preference you see pydev software.


text:
Q: Add to wishlist button not redirecting to login page while not logged in I have used "Magento ver. 1.9.2.1" in my website.
On product list and view page wishlist button working while customer logged in but if any customer not logged in then on click wishlist button it is not redirecting me to login page and showing error in log as shown in below figure :

I have checked it more than three PC but same issue occur.
Is there any setting in magento to remove this error and redirect to login page?


text:
Q: PDO wrong bindings with Laravel I have a search query that works perfect (I stripped some unimportant code):
$posts = new Post;

if(Input::has('query')) {
    // Search for posts with title or tags matching the given criteria
    $posts = $posts
        ->addSelect(DB::raw("MATCH(posts.title) AGAINST (?) as post_score"))
        ->addSelect(DB::raw("MATCH(tags.title) AGAINST (?) as tag_score"))
        ->where(function($query) {
            return $query
                ->whereRaw('MATCH(posts.title) AGAINST (?)')
                ->orWhereRaw('MATCH(tags.title) AGAINST (?)');
        })
        ->orderBy(DB::raw('post_score+tag_score'), 'desc')
        ->setBindings([ $input['query'], $input['query'], $input['query'], $input['query'] ]);
}

But as soon as I add this piece of code before the above if() statement:
if(Input::has('filter')) {
    $posts = $posts->whereType($input['filter']); //Filter type by either 'article' or 'question'
}

... I get this error:
[2014-11-04 19:28:18] production.ERROR: PDO error: SQLSTATE[HY093]: Invalid parameter number (SQL: select `posts`.*, COALESCE(SUM(post_votes.rating), 0) as rating, MATCH(posts.title) AGAINST (css) as post_score, MATCH(tags.title) AGAINST (css) as tag_score from `posts` left join `post_tags` on `post_tags`.`post_id` = `posts`.`id` left join `tags` on `tags`.`id` = `post_tags`.`tag_id` left join `post_votes` on `post_votes`.`post_id` = `posts`.`id` where `type` = css and (MATCH(posts.title) AGAINST (css) or MATCH(tags.title) AGAINST (?)) group by `posts`.`id` order by post_score+tag_score desc, `views` desc) [] []

I entered css as search query, the type should be filtered on question. As you can see the variables aren't binded right (don't know the right word for this). How could this be? I also tried this which doesn't work:
->where(function($query) use ($input) {
    return $query
        ->whereRaw('MATCH(posts.title) AGAINST (?)', [$input['query']])
        ->orWhereRaw('MATCH(tags.title) AGAINST (?)', [$input['query']]);
})

Thanks in advance.

A: This is what you need:
if(Input::has('filter')) {
  $posts->whereType($input['filter']); //Filter type by either 'article' or 'question'
}

if(Input::has('query')) {
  // no need for this:
  // $posts = $posts
  // just:
  $posts
    ->addSelect(DB::raw("MATCH(posts.title) AGAINST (?) as post_score"))
    ->addBinding($input['query'], 'select')
    ->addSelect(DB::raw("MATCH(tags.title) AGAINST (?) as tag_score"))
    ->addBinding($input['query'], 'select')
    ->where(function($query) use ($input) {
       $query
         ->whereRaw('MATCH(posts.title) AGAINST (?)', [$input['query']])
         ->orWhereRaw('MATCH(tags.title) AGAINST (?)', [$input['query']]);
    })
    ->orderBy(DB::raw('post_score+tag_score'), 'desc')
}


text:
Q: Can I determine memory consumption allocation with XCode's Debugging I have a program on XCode's written with C++.
Some builds my memory consumption skyrockets out of nowhere, while other builds the memory stays constant and works as expected.
Are there any built in debugging features with XCodes that will allow me to view memory consumption on a per variable or per object basis?
Thanks in advance.

A: You should first look into using Instruments (wiki). You can run Instruments in Xcode using ⌘+I. It is built on top of DTrace.
DTrace background
Why is that important?  DTrace lets you ask really interesting, specific questions about the runtime behaviors of your application, whether during debugging or in production.
The beauty of DTrace is in the providers, as well as the scripts (written in the D scripting language - not the same thing as dlang). Many languages have DTrace providers that allow you to probe into their standard libraries. There is also a syscall provider that lets you see when applications are hitting lower level system calls. Some third party applications have their own application-specific DTrace providers, often along with handy scripts you can use. Or you can create your own (see below).
Objc/C++ refresher
Keep in mind that both Objective-C and C++ essentially coexist with and extend C.  So your new and delete in C++ are really just malloc and free with some size calculations done for you based on the class you're working with.  In Objective-C, it's more or less the same story under the hood - things must be malloc'd onto the heap.   So whether you're writing C, C++, or Objective-C code (or even Swift code!) there is some common ground we can rely on.
Instruments
Getting back to the issue at hand, Instruments simplifies using DTrace by offering a GUI with shortcuts to handy, pre-made scripts. You don't even have to see the scripts. For example, you can launch Instruments and tell it to monitor memory allocations or leaks, and suddenly you get a rolling graph of memory usage in your application.
Once you launch Instruments and start recording a session with the Memory Allocation tool, you should be looking at the "persistent bytes" column (used to be "live bytes"). This is a good starting point. This number will increase and decrease. You'll typically see a net increase over time, but you should see it decrease whenever you're expecting a deallocation to occur - the larger the deallocation, the easier it is to notice. If you are not seeing decreases at those moments, then you'll want to explore your code for bad memory management.
Taking It Further
You can even create custom probes.
Here's another in-depth article that describes what you're talking about, with tracking malloc/free usage from specific lines of your code.


text:
Q: WCF Service 404 Error on server but works fine locally I have read a number of other threads on SO, including this one and this but I have been unable to figure out the issue.
Both of my WCF services work fine locally, but give a 404 error when on the server:

Here is the Javascript code:
  $("#starRating").on('rating.change', function (event, value, caption) {
    var walkID = getUrlVars()["WalkID"];

    var score = $('#starRating').val();
    alert(walkID + " " + score);
    window.UserID = '<%=HttpUtility.JavaScriptStringEncode(this.User.Identity.GetUserId())%>';
    SaveRatingService.Save(score, walkID, window.UserID);

Here is my service:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SaveRatingService
{
  [OperationContract]
  public void Save(string score, string walkID, string loggedInUser)
  {
    ....
    return;
  }
}

Here is how I've registered it (MasterPage):
    <asp:ScriptManager runat="server">
        <Scripts>...</Scripts>
      <Services>
        <asp:ServiceReference Path="~/WebServices/SaveRatingService.svc" />
      </Services>
    </asp:ScriptManager>

Originally, I did have it on the page with the Javascript page in a ScriptManagerProxy but I moved it to see if that would solve the issue.
And finally here is my master page service configuration:
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="DogWalks.WebServices.SaveRatingServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
        <behavior name="DogWalks.WebServices.PostcodeFillAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="DogWalks.WebServices.SaveRatingService">
        <endpoint address="" behaviorConfiguration="DogWalks.WebServices.SaveRatingServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="DogWalks.WebServices.SaveRatingService"  />
      </service>
      <service name="DogWalks.WebServices.PostcodeFill">
        <endpoint address="" behaviorConfiguration="DogWalks.WebServices.PostcodeFillAspNetAjaxBehavior" binding="webHttpBinding" contract="DogWalks.WebServices.PostcodeFill" />
      </service>
    </services>
  </system.serviceModel>

AS mentioned, it runs fine locally. When I try and follow the path to the service (first screenshot), the path indeed leads to a 404 error.
On investigation of the file, I see that a script is added:

But, as mentioned in the 404 error it's not found. Why does the script add /js, which indeed is a directory that does not exist.