text:
Q: App sometimes crashes with "Background start not allowed: service Intent" I only do Android development part time (which seems challenging considering the many subtleties and low-levelness of the APIs) and have a problem with receiving notifications while my app is in the background. I am targeting Android 8.1. My app happens to use Azure and Xamarin, but I do not know if those details are inherent to the problem.
If my app is in the background sometimes notifications can be displayed, other times my app crashes with this error:
2019-03-06 09:12:24.486 9495-9702/? D/tyresense.azurelistenerservice: OnMessage() done
2019-03-06 09:12:28.278 1548-3232/? W/ActivityManager: Background start not allowed: service Intent { act=com.google.android.c2dm.intent.RECEIVE flg=0x1000010 pkg=com.rimex.tyresense cmp=com.rimex.tyresense/md5bf34da605c12d097dc5a495af95e9376.AzureListenerService (has extras) } to com.rimex.tyresense/md5bf34da605c12d097dc5a495af95e9376.AzureListenerService from pid=9495 uid=10173 pkg=com.rimex.tyresense
2019-03-06 09:12:28.341 9495-9495/? I/MonoDroid: Java.Lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.RECEIVE flg=0x1000010 pkg=com.rimex.tyresense cmp=com.rimex.tyresense/md5bf34da605c12d097dc5a495af95e9376.AzureListenerService (has extras) }: app is in background uid UidRecord{d582ba5 u0a173 RCVR bg:+1m0s848ms idle procs:1 seq(0,0,0)}
2019-03-06 09:12:28.342 9495-9495/? I/MonoDroid: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.RECEIVE flg=0x1000010 pkg=com.rimex.tyresense cmp=com.rimex.tyresense/md5bf34da605c12d097dc5a495af95e9376.AzureListenerService (has extras) }: app is in background uid UidRecord{d582ba5 u0a173 RCVR bg:+1m0s848ms idle procs:1 seq(0,0,0)}
2019-03-06 09:12:28.347 9495-9495/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.rimex.tyresense, PID: 9495
    java.lang.RuntimeException: Unable to start receiver md5bf34da605c12d097dc5a495af95e9376.TyreSenseBroadcastReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.RECEIVE flg=0x1000010 pkg=com.rimex.tyresense cmp=com.rimex.tyresense/md5bf34da605c12d097dc5a495af95e9376.AzureListenerService (has extras) }: app is in background uid UidRecord{d582ba5 u0a173 RCVR bg:+1m0s848ms idle procs:1 seq(0,0,0)}
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:3285)
        at android.app.ActivityThread.-wrap17(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1713)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6626)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
     Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.RECEIVE flg=0x1000010 pkg=com.rimex.tyresense cmp=com.rimex.tyresense/md5bf34da605c12d097dc5a495af95e9376.AzureListenerService (has extras) }: app is in background uid UidRecord{d582ba5 u0a173 RCVR bg:+1m0s848ms idle procs:1 seq(0,0,0)}
        at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1536)
        at android.app.ContextImpl.startService(ContextImpl.java:1492)
        at android.content.ContextWrapper.startService(ContextWrapper.java:650)
        at android.content.ContextWrapper.startService(ContextWrapper.java:650)
        at md513d040a829b3f298fbeeee5a6e2c042a.GcmBroadcastReceiverBase_1.n_onReceive(Native Method)
        at md513d040a829b3f298fbeeee5a6e2c042a.GcmBroadcastReceiverBase_1.onReceive(GcmBroadcastReceiverBase_1.java:29)
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:3278)
        at android.app.ActivityThread.-wrap17(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1713)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6626)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
2019-03-06 09:12:28.348 2761-2761/? W/GCM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE pkg=com.rimex.tyresense (has extras) }
2019-03-06 09:12:28.353 9495-9495/? E/tyresense.splashscreen: System.UnhandledExceptionEventArgs
2019-03-06 09:12:28.357 1548-7265/? W/ActivityManager:   Force finishing activity com.rimex.tyresense/md5bf34da605c12d097dc5a495af95e9376.MainActivity
2019-03-06 09:12:28.363 1548-1632/? I/ActivityManager: Showing crash dialog for package com.rimex.tyresense u0

I see articles like this one: https://blog.xamarin.com/replacing-services-jobs-android-oreo-8-0/
But it is not clear to me what exactly is the problem, so I do not know if that will solve it.
Maybe here?
using System;
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.Util;
using Gcm.Client;
using WindowsAzure.Messaging;
using SharedMobile; // keep it simple, the app might not be running
using MyApp.Android; // we need to reference ourselves...
using Android.Support.V4.App;
using Android.Content.PM;
using System.Threading.Tasks;

[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
[assembly: Xamarin.Forms.Dependency(typeof(DependencyListener))]
namespace MyApp.Android
{
    [BroadcastReceiver(Permission = Constants.PERMISSION_GCM_INTENTS)]
    [IntentFilter(new string[] { Constants.INTENT_FROM_GCM_MESSAGE }, Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, Categories = new string[] { "@PACKAGE_NAME@" })]
    public class MyAppBroadcastReceiver : GcmBroadcastReceiverBase<AzureListenerService>
    {
        // this declaration somehow enables messages
    }

    [Service]
    public class AzureListenerService : GcmServiceBase // this service might be started at system boot, when the app is otherwise not active
    {
        const string TAG = "MyApp.azurelistenerservice";
        const string HUBNAME = "myhubname";
        const string CONNECTION =
               "Endpoint=sb://MyApp.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=secretstuff...";

        public const string GcmProjectNumber = "1234567890";
        private static NotificationHub noteHub = null;

        public AzureListenerService() : base(GcmProjectNumber)
        {
        }

        // need client and area ids before this is called. Application.Context is not available if called from system boot
        public static void InitializeAzure(Context context = null)
        {
            try
            {
                if (context == null)
                    context = Application.Context;
                var enabled = NotificationManagerCompat.From(context).AreNotificationsEnabled();
                SharedMobile.API.ApiService.Instance.NotificationsEnabled(enabled);
                if (enabled)
                {
                    GcmClient.CheckDevice(context);
                    GcmClient.CheckManifest(context);
                    GcmClient.Register(context, GcmProjectNumber);
                }
            }
            catch (Exception ex)
            {
                Log.Error(TAG, ex.Message);
                Messenger.SendException(ex.Message);
            }
        }

        // incoming GCM registration
        protected override void OnRegistered(Context context, string token)
        {
            try
            {
                noteHub = new NotificationHub(HUBNAME, CONNECTION, context);
                var customerId = Int32.Parse(PropertyHelper.ClientId);
                var tags = BuildTagList(customerId, PropertyHelper.AreaIds);
                noteHub.Register(token, tags.ToArray());
                Messenger.RegisterDevice(token);
            }
            catch (Exception ex)
            {
                Log.Error(TAG, "OnRegistered() " + ex.Message); // ignore register failure when using the Android emulator
            }
        }

        protected override void OnMessage(Context context, Intent intent)
        {
            try
            {
                var areaIds = PropertyHelper.AreaIds;
                if (string.IsNullOrWhiteSpace(areaIds)) // in case the user logged out
                    return;
                new Notifications().CreateEventNotification(intent);
            }
            catch (Exception ex)
            {
                Log.Error(TAG, "OnMessage() " + ex.Message);
            }
        }

        protected List<string> BuildTagList(int clientId, string areaIds)
        {
            var list = new List<string>();
            list.Add($"client_{clientId}");
            foreach (var id in areaIds.Split(','))
                list.Add($"area_{id}");
            return list;
        }

        protected override void OnUnRegistered(Context context, string registrationId)
        {
            Log.Error(TAG, "OnUnRegistered(): " + registrationId);
        }

        protected override bool OnRecoverableError(Context context, string errorId)
        {
            Log.Error(TAG, "OnRecoverableError(): " + errorId);
            return base.OnRecoverableError(context, errorId);
        }

        protected override void OnError(Context context, string errorId)
        {
            Log.Error(TAG, "OnError(): " + errorId);
        }
    }
}

using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android.Util;
using Exception = System.Exception;

namespace My.Android
{
    internal class Notifications
    {
        const string TAG = "My.notifications";
        const string TITLE = "Application is running";
        const string DESC = "Tap to view";
        const int MainProgramNotificationId = 775566;

        // unique ID for our notification:
        static readonly string CHANNEL_ID = "My_channel_23";
        static readonly string CHANNEL_NAME = "[My_channel]";

        internal void CreateProgramIcon_on_hold(Intent intent)
        {
            var extras = new Bundle();
            extras.PutString("scopeDescription", TITLE);
            extras.PutString("stateDescription", DESC);
            intent.PutExtras(extras);

            ShowNotification(intent.Extras, false);
        }

        internal void CreateEventNotification(Intent extra)
        {
            if (extra.Extras != null && !extra.Extras.IsEmpty)
                ShowNotification(extra.Extras, true);

            var notificationId = extra?.Extras?.GetString("notification-id", null);
            if (notificationId != null && notificationId.Length > 0)
                SharedMobile.API.ApiService.NotificationConfirmation(notificationId);
        }

        private void ShowNotification(Bundle extras, bool autoCancel)
        {
            try
            {
                string title = TITLE;
                string description = DESC;
                if (extras != null && !extras.IsEmpty)
                {
                    title = extras.GetString("scopeDescription", null);
                    description = extras.GetString("stateDescription", "");
                }

                Intent intent = new Intent(Application.Context, typeof(SplashScreen));
                BuildNotification(intent, extras, title, description, autoCancel);

            }
            catch (Exception ex)
            {
                Log.Debug(TAG, ex.Message);
            }
        }

        private void BuildNotification(Intent intent, Bundle extras, string title, string description, bool autoCancel)
        {
            bool onGoing = !autoCancel;
            int icon = IconId(null, null); // code not shown
            intent.AddFlags(ActivityFlags.ReorderToFront);
            var pendingIntent = PendingIntent.GetActivity(Application.Context, 0, intent, PendingIntentFlags.UpdateCurrent);

            CreateNotificationChannel(autoCancel);

            var notificationManager = Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;
            NotificationCompat.Builder builder = new NotificationCompat.Builder(Application.Context, CHANNEL_ID);

            builder.SetSmallIcon(icon)
                .SetContentTitle(title)
                .SetContentText(description)
                .SetSmallIcon(Resource.Drawable.notification_icon)
                .SetAutoCancel(autoCancel)
                .SetOngoing(onGoing)
                .SetContentIntent(pendingIntent);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                builder.SetColor(ContextCompat.GetColor(Application.Context, Resource.Color.exBackgroundColor));

            string utcTicks = null;
            if (extras != null)
                utcTicks = extras.GetString("utcTicks", null);
            if (utcTicks != null)
            {
                var ticks = Int64.Parse(utcTicks);
                DateTimeOffset dto = new DateTimeOffset(ticks, TimeSpan.Zero);
                builder.SetWhen(dto.ToUnixTimeMilliseconds());
            }
            else
                builder.SetShowWhen(true);

            notificationManager?.Notify(MainProgramNotificationId, builder.Build());
        }

        private void CreateNotificationChannel(bool evnt)
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                // There is no need to create a notification channel on older versions of Android.
                return;
            }
            NotificationImportance ni;
            if (evnt)
                ni = NotificationImportance.Default;
            else
                ni = NotificationImportance.Low;
            var channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, ni)
            {
                Description = "My App",
                LockscreenVisibility = NotificationVisibility.Private,
            };
            var notificationManager = Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;
            notificationManager.CreateNotificationChannel(channel);
        }

        string FormatTimeStamp(string utcTicks)
        {
            try
            {
                var ticks = Int64.Parse(utcTicks);
                DateTimeOffset dto = new DateTimeOffset(ticks, TimeSpan.Zero);
                return dto.ToLocalTime().ToString("MM/dd HH:mm:ss");
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        bool IgnoreActionProcess(string actionProcessId, int ackedProcessId)
        {
            try
            {
                if (int.Parse(actionProcessId) == ackedProcessId)
                    return true;
            }
            catch (Exception ex)
            {
                Log.Debug(TAG, $"int parse: {actionProcessId} {ex.Message}");
            }
            return false;
        }

    }
}

Update:
I change the OnMessage in public class AzureListenerService : GcmServiceBase to do nothing and it still crashes:
Unhandled Exception:
Java.Lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.c2dm.intent.RECEIVE flg=0x1000010 pkg=com.mycompany.myapp cmp=com.mycompany.myapp/md5bf34da605c12d097dc5a495af95e9376.AzureListenerService (has extras) }: app is in background uid UidRecord{d45626f u0a173 RCVR bg:+1m29s589ms idle change:uncached procs:1 seq(0,0,0)} occurred
Update
I implemented the JobScheduler, that made no difference. Also, the app has to be in the background for "some time" and the problem will then always occur. I also changed my app to do nothing at all (but log) when a notification arrives, and it still crashes.
Update
I got this working: https://developer.xamarin.com/samples/monodroid/Firebase/FCMNotifications/
By adding it "as is" to my firebase account, downloading the google-services.json and testing with http://pushtry.com/. No luck with Azure portal test send yet. Hope to merge code from FCMNotifications into my app, if I can get Azure working...

A: Android 8.0 (API level 26) and above have limitation with respect to background service. It includes the following changes to specific methods:
The startService() method now throws an IllegalStateException if an app targeting Android 8.0 tries to use that method in a situation when it isn't permitted to create background services.
The new Context.startForegroundService() method starts a foreground service. The system allows apps to call Context.startForegroundService() even while the app is in the background. However, the app must call that service's startForeground() method within five seconds after the service is created.


text:
Q: Which is better as a switch? The offset voltage of a saturated transistor, makes bjt less attractive as a switch than mosfet. Why? Is there any other logics aside this?

A: What you say is true only for low to moderate currents, up to, say, 100 A or so.
The VCE(SAT) of a BJT is more or less constant, regardless of current, assuming of course, that the transistor is robust enought to handle the current in the first place.
On the other hand, the channel of a full-on MOSFET functions as a constant resistance. This resistance can be very low (miiliohms), but at high currents, it can still result in a higher voltage drop — and higher power dissipation — than the equivalent BJT.
This is why the IGBT, which combines the best features of a MOSFET and a BJT, is so popular in the highest-power applications.

A: Having a higher "offset voltage" (Vce(sat) for BJT and VDS(on) for MOSFETs) is undesirable for two main reasons:

*

*Power losses.  The power lost at the transistor at its output stage is proportional to the current and the voltage drop.  Higher losses means decreased efficiency and increased heat dissipation.  This could meant that batteries don't last as long, and increased thermal management costs.

*Reduced dynamic voltage range.  In certain applications you need to maximize your voltage range, and some of it will be gobbled up by the drop at the switch, and it is worse if you have both high and low side switches.

Like another answer already mentioned, the assumption of VDS(on) < Vce(sat) is contested for high currents.

redpajama_set_name: RedPajamaStackExchange


text:
Q: GCP response says MalformedSecurityHeader content-type is not in the request but it is First of all I'm sorry for pasting so much code here, but as there's a lot of things that could go wrong in each step of this process, I'm trying to make sure that every error that I faced and was able to fix is recorded here so there's no back and forth in comunication.
Im trying to create a signed upload url to send some files from the browser to a gcp bucket.
I have a backend in go creating the signed upload url like this
func generateV4PutObjectSignedURL(bucket, object string) (string, error) {
  ctx := context.Background()
  client, err := storage.NewClient(ctx)
  if err != nil {
      return "", fmt.Errorf("storage.NewClient: %v", err)
  }
  defer client.Close()

  pkey, err := ioutil.ReadFile("key.pem")
  check(err)

  opts := &storage.SignedURLOptions{
      PrivateKey:  pkey,
      Scheme:      storage.SigningSchemeV4,
      Method:      "PUT",
      ContentType: "video/wav",
      Expires:     time.Now().Add(20 * time.Hour),
  }

  u, err := client.Bucket(bucket).SignedURL(object, opts)
  if err != nil {
      return "", fmt.Errorf("Bucket(%q).SignedURL: %v", bucket, err)
  }

  return u, nil
}

key.pem has every permission possible.
I'm sending the file like this
const reader = new FileReader();
  console.log(file);
  reader.onabort = () => console.log("file reading was aborted");
  reader.onerror = () => console.log("file reading has failed");
  reader.onload = () => {
    const binaryFile = reader.result;
    const blob = new Blob([binaryFile], { type: file.type });
    var request = new XMLHttpRequest();
    request.open("PUT", uploadUrl, true);
    request.setRequestHeader("Content-Type", file.type);
    request.onload = (e) => {
      if (request.status === 200) {
        poll();
      }
    };
    request.send(blob);
  };
  reader.readAsArrayBuffer(file);

And I'm receiving this error
Access to XMLHttpRequest at {THE_SIGNED_URL} from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

CORS configuration in the bucket is like this
[{"maxAgeSeconds": 86400, "method": ["*"], "origin": ["*"], "responseHeader": ["*"]}]

And the XML error I'm getting is this
<Error>
  MalformedSecurityHeader
  <Message>Your request has a malformed header.</Message>
  <ParameterName>content-type</ParameterName>
  Header was included in signedheaders, but not in the request.
</Error>

But chrome developers network tab says that the Content-Type header is present in the request and is exactly what I said it would be in the backend.
What am I doing wrong?

A: GCP makes you receive CORS error even if you have configured CORS correctly!
I ended up solving the problem by removing the content type header from the request.
After I did this the CORS problem returned and I ended up finding out it actually wasn't a CORS problem but a GCS problem.
I don't know what happens exactly but I suppose google does something with your OPTIONS preflight request before adding the CORS headers that says you're good to go (Access-Control-Allow-Origin). If something in this process breaks, it returns your answer without this header so your browser understands you've failed CORS validation.
Using some tool that automatically adds this header to every request you receive allows you to view the body of the request and the real problem with your request. There are some chrome extensions that do this.
In my case the problem was that I needed to use a service account email when signing the upload signed request but yours may be different.


text:
Q: How is model Meta class different from model form Meta class? I wanted to understand the metaclasses we use in the model. I found about it in docs. I remember adding metaclass in model forms as well. It seems like model metaclass and model form metaclass is different. How are they different and what are the meta options in the model form.

A: In Epistemology, meta is a (ancient) Greek word means about. It is thus a class that says something about the model, or the ModelForm. The name is basically the only thing they have in common.
The Meta class of a model will specify the verbose name, etc. of a model, constraints and indexes defined in the corresponding database table, etc. The Django documentation has a section that lists all the Meta options for a model.
The Meta of a ModelForm on the other hand will explain to the ModelForm how it should construct a form for the given model. Normally it the Meta one defines the model for which the ModelForm is constructed together with the fields or exclude that specify what fields to include/exclude respectively. Furthermore the Overriding default fields section of the documentation lists all other Meta options, where a user can (slightly) alter the way how the fields are defined in the ModelForm. The source code [GitHub] also lists all the options for the Meta of ModelForm:

class ModelFormOptions:
    def __init__(self, options=None):
        self.model = getattr(options, 'model', None)
        self.fields = getattr(options, 'fields', None)
        self.exclude = getattr(options, 'exclude', None)
        self.widgets = getattr(options, 'widgets', None)
        self.localized_fields = getattr(options, 'localized_fields', None)
        self.labels = getattr(options, 'labels', None)
        self.help_texts = getattr(options, 'help_texts', None)
        self.error_messages = getattr(options, 'error_messages', None)
        self.field_classes = getattr(options, 'field_classes', None)


text:
Q: working 'java -cp' not working all of a sudden in ubuntu We have the below java command which was running and stopped working all of a sudden,
java –cp "classes:lib/*" xxx.yyy.ppp
The jar is within lib directory and the jar contains the class.
It stopped working all of a sudden and gived the below error,
"Error: Could not find or load main class –cp"
Why is it considering '-cp' as the main class, even though ppp (example) has the main class. Please help me out with this...

A: You are not using a default hypen before cp  as java –cp "classes:lib/*" xxx.yyy.ppp
Use this instead : java -cp "classes:lib/*" xxx.yyy.ppp


text:
Q: Connecting to external chip (device) I want to create mobile app that will control some external simple mechanical device. I want to use bada wave s8500 for this purpose so have access to Bluetooth and WI-Fi. Now I'm looking for advice related to chip (that will translate command from phone) on my mechanical device. Of course it should be something simple, small and cheap if it is possible.
Has somebody any experience with this? I will be pleasure for any advice or idea.

A: For a beginner I would suggest Arduino - A company in china has just created a cool and cheap x-bee compatible device that has an ATMega chip (compatible with Arduino IDE) and Bluetooth in a single PCB called the Bluetooth Bee with Arduino. And here is a schematic.

Description
  Save that extra Arduino you have lying around for another project,
  this two-for-one device has the Arduino built-in.  Bluetooth Bee with
  Arduino is an enhanced version of the Bluetooth Bee.  We added an
  onboard ATMEGA168 to it to make it a full-featured Arduino while
  maintaining the same footprint and instruction set as the Bluetooth
  Bee.  Plus, it still allows you to stack it on XBee Carrier,  XBee®
  Shield, and UartSBee for expansion or reprogramming

You can also buy the original development board from Arduino that allows you access to more input and output pins.

The Arduino BT is a microcontroller board originally was based on the
  ATmega168, but now is supplied with the 328. and the
  Bluegiga WT11 bluetooth module. It
  supports wireless serial communication over bluetooth (but is not
  compatible with Bluetooth headsets or other audio devices). It has 14
  digital input/output pins (of which 6 can be used as PWM outputs and
  one can be used to reset the WT11 module), 6 analog inputs, a 16 MHz
  crystal oscillator, screw terminals for power, an ICSP header, and a
  reset button.

You pair to the device and you will get a transparent communications port where you can send and receive plain text messages. Thanks to this it is easy to develop code for both devices because they already have libraries to help you.(except iPhone and WP7- So that leaves Android and WP8 (possibly iPhone5))
You will still need other circuits to control your devices so you should do some more reseach into what you will need. The Arduino(or similar MCU's) simply cannot switch or drive heavy equipment.


text:
Q: opening jpg image after saving from ffmpeg not working In my project I am saving videos, converting formats to .swf using ffmpeg. Converting and saving the videos is working fine, but I have a problem with creating the thumbnails. It saves a "picture.jpg" but there is no image. looking at the thumbnail its only got the normal photoviewer sign which is fine, but when I try to open the image it gives a message of
Windows photo viewer: Windows photo viewer cant open this picture because the file appears to be damaged, corrupted, or is too large. (this image is 2.7MB) - Photos taken from my camera is about 5MB and that opens.
PictureViewer: couldn't display "image.jpg" because a suitable graphics importer could not be found.
Paint: Paint cannot read this file. This is not a valid bitmap file or its format is currently not supported.
 The images won't open in any I done to save the image:
    protected void btnUploadVideo_Click(object sender, EventArgs e)
    {
        string dtMonth = DateTime.Now.ToString("MMM");
        string dtYear = DateTime.Now.ToString("yyyy");
        lblMsg.Visible = false;

        lblMsg.Visible = true;

        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (fuPath.HasFile)
        {
            // Get the size in bytes of the file to upload.
            int fileSize = fuPath.PostedFile.ContentLength;

            // Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded.
            if (fileSize < 10497717)
            {
                // Call a helper method routine to save the file.
                SaveFile2();
            }
        }
        else
            // Notify the user that a file was not uploaded.
            lblMsg.Text = "You did not specify a file to upload.";
    }

    private void SaveFile2()
    {
        string dtMonth = DateTime.Now.ToString("MMM");
        string dtYear = DateTime.Now.ToString("yyyy");

        if (fuPath != null || fuPath.PostedFile != null)
        {
            postedfilename = fuPath.PostedFile.FileName;
            SavePath = Server.MapPath("~\\Video\\");
            string NewFName = postedfilename;
            NewFName = NewFName.Substring(NewFName.LastIndexOf("\\") + 1, NewFName.Length - NewFName.LastIndexOf(".")) + "." + NewFName.Substring(NewFName.LastIndexOf(".") + 1);
            Filenamewithpath = SavePath + NewFName;
            string outputPath = Server.MapPath("~\\uploads\\" + dtYear + "\\" + dtMonth + "\\SWF\\");
            CreateDirectoryIfNotExists(SavePath);
            CreateDirectoryIfNotExists(outputPath);

            //Save The file
            fuPath.PostedFile.SaveAs(Filenamewithpath);

            //Start Converting
            string inputfile, outputfile, filargs;
            string withoutext;

            //Get the file name without Extension
            withoutext = Path.GetFileNameWithoutExtension(Filenamewithpath);

            //Input file path of uploaded image
            inputfile = SavePath + NewFName;

            //output file format in swf

            outputfile = outputPath + withoutext + ".swf";
            Session["outputfile"] = withoutext + ".swf";
            //file orguments for FFMEPG

            // Create the path and file name to check for duplicates.
            string pathToCheck = outputfile;

            // Create a temporary file name to use for checking duplicates.
            string tempfileName = "";

            // Check to see if a file already exists with the
            // same name as the file to upload.
            if (System.IO.File.Exists(pathToCheck))
            {
                int counter = 2;
                while (System.IO.File.Exists(pathToCheck))
                {
                    // if a file with this name already exists,
                    // prefix the filename with a number.
                    tempfileName = outputPath + counter.ToString() + withoutext + ".swf";
                    pathToCheck = tempfileName;
                    counter++;
                }

                outputfile = tempfileName;
                // Notify the user that the file name was changed.
                lblMsg.Text = "A file with the same name already exists." +
                    "
Your file was saved as " + counter.ToString() + withoutext + ".swf";
            }

            filargs = "-i " + inputfile + " -ar 22050 " + outputfile;

            string spath;
            spath = Server.MapPath(".");
            Process proc;
            proc = new Process();
            proc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe";
            proc.StartInfo.Arguments = filargs;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow = false;
            proc.StartInfo.RedirectStandardOutput = false;
            try
            {

                proc.Start();
                fuPath.PostedFile.SaveAs(outputfile);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            proc.WaitForExit();
            proc.Close();

            //Create Thumbs

            string thumbPath, thumbName;
            string thumbargs;

            thumbPath = Server.MapPath("~\\uploads\\" + dtYear + "\\" + dtMonth + "\\Thumb\\");
            CreateDirectoryIfNotExists(thumbPath);

            thumbName = thumbPath + withoutext + ".jpg";

            // Create the path and file name to check for duplicates.
            string thumbPathToCheck = thumbName;

            // Create a temporary file name to use for checking duplicates.
            string thumbTempfileName = "";

            // Check to see if a file already exists with the
            // same name as the file to upload.
            if (System.IO.File.Exists(thumbPathToCheck))
            {
                int counter = 2;
                while (System.IO.File.Exists(thumbPathToCheck))
                {
                    // if a file with this name already exists,
                    // prefix the filename with a number.
                    thumbTempfileName = thumbPath + counter.ToString() + withoutext + ".jpg";
                    thumbPathToCheck = thumbTempfileName;
                    counter++;
                }

                thumbName = thumbTempfileName;
                // Notify the user that the file name was changed.
                lblMsg.Text = "A file with the same name already exists." +
                    "
Your file was saved as " + counter.ToString() + withoutext + ".jpg";
            }

            //thumbargs = "-i " + inputfile + " -an -ss 00:00:03 -s 120×90 -vframes 1 -f mjpeg " + thumbName;
           // thumbargs = "-i " + inputfile + "-f image2 -ss 1.000 -vframes 1 " + thumbName;
            thumbargs = "-i " + inputfile + " -vframes 1 -ss 00:00:10 -s 150x150 " + thumbName;

            //  thumbargs = "ffmpeg -i" + inputfile + " -ss 0:00:01.000 -sameq -vframes 1 " + withoutext + ".jpg";
            //  thumbargs = "-i " + inputfile + " -vframes 1 -ss 00:00:07 -s 150x150 " + thumbName;
            Process thumbproc = new Process();
            thumbproc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe";
            thumbproc.StartInfo.Arguments = thumbargs;
            thumbproc.StartInfo.UseShellExecute = false;
            thumbproc.StartInfo.CreateNoWindow = true;
            thumbproc.StartInfo.RedirectStandardOutput = false;

            string data = "";

            try
            {
                fuPath.PostedFile.SaveAs(thumbName);
                thumbproc.Start();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }

            thumbproc.WaitForExit();
            thumbproc.Close();
            File.Delete(inputfile);
            lblMsg.Text = "Video Uploaded Successfully";
            hyp.Visible = true;
            hyp.NavigateUrl = "WatchVideo.aspx";

            SaveToDB(outputfile, thumbName);
        }
    }

EDIT:
If it is the thumbargs, I have tried a few ways, but with no success:
     //thumbargs = "-i " + inputfile + " -an -ss 00:00:03 -s 120×90 -vframes 1 -f mjpeg " + thumbName;
     // thumbargs = "-i " + inputfile + "-f image2 -ss 1.000 -vframes 1 " + thumbName;
      thumbargs = "-i " + inputfile + " -vframes 1 -ss 00:00:10 -s 150x150 " + thumbName;
     //  thumbargs = "ffmpeg -i" + inputfile + " -ss 0:00:01.000 -sameq -vframes 1 " + withoutext + ".jpg";

This is how it looks when saved, but can't open....

EDIT:
I tried adding the argument to the command prompt to see if it works there but it gave me a message of : [NULL @ 000000000025f7a0] Unable to find a suitable output format for 'vframes'
vframes: invalid argument
The line I used:
    ffmpeg -i VID2012.3GP vframes 1 VID2012.jpg

If it is that it is not set correctly in IIS how do I set it?
EDIT:
I changed a bit of my code. Debugging through my code there is no exception that is thrown, but if I point the mouse over the process (after it started) it "shows an exception of type System.InvalidOperationException"
    thumbargs = "-i " + postedfilename + " vframes 1" + thumbName;
            ProcessStartInfo thumbProcstartIfo = new ProcessStartInfo();
            thumbProcstartIfo.FileName = @"\ffmpeg\ffmpeg.exe";
            thumbProcstartIfo.Arguments = thumbargs;
            thumbProcstartIfo.UseShellExecute = false;
            thumbProcstartIfo.CreateNoWindow = true;
            thumbProcstartIfo.RedirectStandardOutput = false;

            try
            {
                using (var process = new Process())
                {
                    process.StartInfo = thumbProcstartIfo;
                    process.Start();
                    process.WaitForExit();
                }
            }
            catch (InvalidOperationException ex)
            {
                lblMsg.Text = ex.ToString();
            }

A: I think it has to do with these lines:
thumbproc.Start();
fuPath.PostedFile.SaveAs(thumbname);

I expect that the second line saves the uploaded file to your data directory and the first line starts processing the file. Shouldn't these line be swapped?
fuPath.PostedFile.SaveAs(thumbname);
thumbproc.Start();


text:
Q: Is there any rule in CQRS which doesn't allow to use a query and a command in the same controller action? For example: I want to delete an item or return 404 if it doesn't exist from a controller action. Am I breaking any rules? Commands are still separated from queries.
[ApiController]
public class PostsController : ControllerBase
{
    [HttpDelete("/posts/{postId}")]
    public async Task<IActionResult> DeletePost(Guid postId)
    {
        var postDTO = await _mediator.Send(new GetPostByIdQuery(postId)); // query
        if (postDTO == null)
        {
            return NotFound();
        }

        await _mediator.Send(new DeletePostCommand(postId)); // command

        return NoContent();
    }
}

A:
Am I breaking any rules?

Not really specific to CQRS, but maybe?
If you are in the context of a controller, then you are in a world where we can reasonably expect that lots of different requests are being handled concurrently.
So we have to be aware that unlocked data can change out from under us while our process is running.
var postDTO = await _mediator.Send(new GetPostByIdQuery(postId)); // query

// now some other thread comes along, and does work that
// changes the result we would get from GetPostByIdQuery
// when we resume, our if test takes the wrong branch....

if (postDTO == null)
{
    return NotFound();
}

await _mediator.Send(new DeletePostCommand(postId)); // command

For something like a Delete, where we suspect that interest in a given postId is only happening in one place, then concurrency collisions are going to be rare, and maybe we don't need to worry about it.
In general... there's the potential for a real problem here.

Part of the problem here: your design here violates Tell, don't ask

you should endeavor to tell objects what you want them to do; do not ask them questions about their state, make a decision, and then tell them what to do.

Better might be a design that looks like:
var deleteResult = await _mediator.Send(new DeletePostCommand(postId)); // command

if (deleteResult == null)
{
    return NotFound();
}

return NoContent();

This allows you to ensure that the read and the write are happening within the same transaction, which means you get the locking right.

A: Are CQRS principles violated ?
CQRS is Command Query Responsibility Segregation. It means that your system should segregate commands and queries in two different subsystems, and clients should either interact with one or another, but not both at the same time. Now, there are two cases here :
CQRS as internal API architecture
If CQRS is implemented inside your API, then you are not violating any CQRS principles proper. Your API controller is the CQRS client, and it either interacts with the query subsystem or the command subsystem. However, if you do not want state integrity problems, your command subsystem must verify the post existence himself and not rely on the client having checked for post existence prior. Also this validation should not depend on your query subsystem (see below).
CQRS as external API architecture
Yes, you are breaking a rule here.
Whether you segregate your queries and commands at controller level or controller action level is an implementation details, but clients should atomically interact, either with your command subsystem, or your query subsystem. If your client sends a single HTTP request which results in execution of code in both subsystems, then commands and queries are not segregated and your system violates CQRS principles.
Whether this is good or bad, relevant or not, is up to you, no judgement.
Why using your query subsystem is bad
What does the user wants the system to do ? Does it want to know about the post existence ? No. It wants to delete a post. This means your user wants to alter the system's state. A CQRS client can perfectly query the system prior to sending commands in order to limit stress on the command subsystem, this is a good way to secure performance. However, your system MUST NOT rely on the query subsystem to ensure state integrity. Why ?
One idea behind CQRS was that, if you validate application state on every write operation, you do not need to validate application state for read operations. This allowed to design application with three subsystems :

*

*A command subsystem, designed for integrity first and write performance second

*A query subsystem, designed for read performance only

*An eventual consistency subsystem, which propagates application state changes to the query model

In a CQRS applications, the query subsystem does not need to know about the application state, business rules, or anything integrity-related. It has a persistence storage which holds a query-state, and everything in that system is optimized for read performance. Since you don't require integrity in that subsystem, you can accept violations in the query-model, as long as consistency with application state can be enforced eventually. This also means the query-model is updated after the command subsystem.
Since application state changes at different times on both subsystem, you need to decide which change is considered the source of truth for your application state. Since application state integrity is enforced by the command subsystem, and query subsystem does not know about integrity, this cannot be the latter. That is why the command subsystem model is considered the source of truth regarding application state in a CQRS application. This means, you cannot trust the query subsystem to make decisions about the application state.
How to do it properly
Your command subsystem is the part of your CQRS system that is responsible for application state integrity and business rules enforcement. This means this subsystem is responsible to maintain knowledge of the application state so it can validate commands, and should persist that model for continuity purposes. There are two classic approaches of modeling your command persistence schema:
You can use a traditional persistence design, using a technology such as an ORM to store your object modeled application state to database / disk. Command subsystems usually use RDBMS for persistence since this is the most secure way to do so, integrity wise. This storage can be easily read from or written to, like any classic layered application. The reads are not considered queries in the sense of CQRS terminology, simply a domain model rehydration. You would implement this like that:
using(var tx = new context.Database.BeginTransaction());
var entity = context.Posts.Find(postId);
if(entity == null) { return NotFound(); }
context.Posts.Remove(entity);
context.SaveChanges();
NotifyEventualConsistency();
tx.Commit();
return NoContent();

An alternative is to use event sourcing, which consists of storing events rather than state. However, the command subsystem is still responsible for rehydrating the application state and ensuring business integrity. With event sourcing, you can have a "classic" object domain model, which usually involves a lot of "translation" between the persistence layer and the domain model. Or you can also rewrite your business rules based on events invariants. In that case, you could imagine implementing your business rule like this:
using(var tx = new context.Database.BeginTransaction());
if(PostStatus.Created != context.PostStatusChanged.AsNoTracking()
  .OrderByDesc(event => event.Date)
  .Where(event => event.PostId == postId)
  .Select(event => event.NewState)
  .FirstOrDefault())
{
  return NotFound();
}

context.PostStatusChanged.Add(new PostStatusChanged {
  PostId = postId,
  NewState = PostStatus.Deleted
});

context.SaveChanges();
NotifyEventualConsistency();
tx.Commit();

return NoContent();


text:
Q: Defining PATH_MAX for a filesystem? I'm presently writing a filesystem. The statvfs (and even the statfs) structs contain a field specifying the maximum length of a name in that path. As PATH_MAX is defined in the pathconf manpage (getconf), this means it is defined on a per-directory basis (and thus, determined by the underlying filesystem). How does one specify this value?

A: PATH_MAX mostly behaves as a property of the file system function call interface, so I don't think it makes much sense to have it vary across directories.
For example, renaming or moving a directory with large directory trees in it may make the longest absolute pathname longer and it would be complicated and inefficient to limit that.
Instead, PATH_MAX serves to allow the kernel to copy passed pathnames to temporary unpaged memory, which can then be processed without needing to allow for a page fault at each access. Allocating huge amounts of such memory may block most other things the kernel is doing or even cause kernel panics.

A: On Linux, glibc's implementation of pathconf returns a compile-time constant value of PATH_MAX so there is no runtime magic FUSE or anyone else can perform to adjust it.  (See sysdeps/unix/sysv/linux/pathconf.c which falls through to sysdeps/posix/pathconf.c.)  The answer to your question "How do I specify my filesystem's PATH_MAX?" is "You can't.  glibc doesn't let you and FUSE is just the messenger."
The end result is a sticky situation.  Here's a blog post that discusses the code that does and does not care about PATH_MAX.  Software that relies on paths no longer than PATH_MAX was broken long ago by other filesystems so it's safe for you to ignore PATH_MAX.
On MacOS X (and probably other BSDs):  The implementation of pathconf is entirely in the kernel and can be swapped out per filesystem.  OSXFUSE includes a NOOP version of pathconf which should return the usual compile-time constants.  However, in my tests it seems to be catching another NOOP function along the way which returns an ENXIO and I can't get pathconf to work.
Bonus: for NAME_MAX, implement statfs and set f_namemax.

A: POSIX allows _PC_PATH_MAX to vary based on the current directory, but that doesn't mean that systems which don't vary it aren't compliant.
The real reason for PATH_MAX existing is that the kernel copies the pathname into kernelspace before doing any actual work with it.
Your assertion that there is a PATH_MAX-related field in statvfs is just wrong. That's related to NAME_MAX, which is a different thing.

A: Since this question is tagged "FUSE" ...
I just ran into this issue while working on a FUSE filesystem. I wrote an e-mail to the FUSE developers, seeking clarification. Reply from the current libfuse maintainer (January 2018): There is not a way to specify the maximum path length in a FUSE filesystem [driver].

Is there a way for a FUSE filesystem to inform software running on top
    of it about the correct maximum path length?

Not at the moment, no.

If not, should there be?

Probably yes. Patches welcome :-)

For reference: Full e-mail thread

A: I do not enough about other OSes but imho this is a system-wide setting in at least FreeBSD 5.2.1
PATH_MAX is found in #62 sys/syslimits.h
Because static int ufs_pathconf() which returns the PATHCONF information for UFS FS, uses this variable in the manner you specified.
/*
 * Return POSIX pathconf information applicable to ufs filesystems.
 */
int
ufs_pathconf(ap)
    struct vop_pathconf_args /* {
        struct vnode *a_vp;
        int a_name;
        int *a_retval;
    } */ *ap;
{

    switch (ap->a_name) {
    .
    .
    .
    .
    case _PC_PATH_MAX:
        *ap->a_retval = PATH_MAX;
        return (0);
    .
    .
    .
    .

    default:
        return (EINVAL);
    }
    /* NOTREACHED */
}

A: PATH_MAX is a system wide setting and is usually defined in pathmax.h as:
define PATH_MAX (pathconf ("/", _PC_PATH_MAX) < 1 ? 1024 \
            : pathconf ("/", _PC_PATH_MAX))


text:
Q: No content in TabNavigator What could be the reason that content in Tab is not displayed?
I Receive a blank white box.
When I have only export const TopNavTabs without the class App it works but I need this as a component.
import React, { Component } from 'react'
import { Platform, View } from 'react-native'
import { TabNavigator } from 'react-navigation'

import General from './components/tabs/General'
import Help from './components/tabs/Help'
import Tips from './components/tabs/Tips'

export const TopNavTabs = TabNavigator({
  General: { screen: General },
  Help: { screen: Help },
  Tips: { screen: Tips },
},
{
  animationEnabled:true
});

export default class App extends Component{

  render(){
      return(
          <View>
            <TopNavTabs />
          </View>
      )
  }
}

index.js
import React, {Component} from 'react';
import {AppRegistry, Text, View} from 'react-native';
import App from './src/App';

export default class Test extends Component {
    render() {
      return (
        <App />
      );
    }
  }

AppRegistry.registerComponent('test', () => Test);


text:
Q: Is there a way to get LibGit2Sharp to work on AlmaLinux 8 in an application built on Windows? I have an ASP.NET Core application (.net core 2.1) built on Windows that uses LibGit2Sharp (version 0.26.2).
It works fine when running on Windows, but I have not been able to get it to work properly when running on an AlmaLinux 8 server.
I copied the libgit2-106a5f2.so file from the linux-x64 native runtime publish output to the same folder that contains LibGit2Sharp.dll on the AlmaLinux 8 machine.
This is the error I see:
System.TypeInitializationException: The type initializer for 'LibGit2Sharp.Core.NativeMethods' threw an exception. ---> System.DllNotFoundException: Unable to load shared library 'git2-106a5f2' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libgit2-106a5f2: cannot open shared object file: No such file or directory
   at LibGit2Sharp.Core.NativeMethods.git_libgit2_init()
   at LibGit2Sharp.Core.NativeMethods.InitializeNativeLibrary()
   at LibGit2Sharp.Core.NativeMethods..cctor()
   --- End of inner exception stack trace ---
   at LibGit2Sharp.Core.NativeMethods.git_repository_open_ext(git_repository*& repository, FilePath path, RepositoryOpenFlags flags, FilePath ceilingDirs)
   at LibGit2Sharp.Core.Proxy.git_repository_open_ext(String path, RepositoryOpenFlags flags, String ceilingDirs)
   at LibGit2Sharp.Repository.IsValid(String path)
...

Edit:
I set the LD_DEBUG and LD_LIBRARY_PATH variables, and got this output when it tried to load the libgit2 library:
   1413948:     file=libgit2-106a5f2 [0];  dynamically loaded by /usr/share/dotnet/shared/Microsoft.NETCore.App/2.1.30/libcoreclr.so [0]
   1413948:     find library=libgit2-106a5f2 [0]; searching
   1413948:      search path=/path/to/application/runtimes/linux-x64/native                (LD_LIBRARY_PATH)
   1413948:       trying file=/path/to/application/runtimes/linux-x64/native/libgit2-106a5f2
   1413948:      search cache=/etc/ld.so.cache
   1413948:      search path=/lib64/tls:/lib64:/usr/lib64/tls:/usr/lib64                (system search path)
   1413948:       trying file=/lib64/tls/libgit2-106a5f2
   1413948:       trying file=/lib64/libgit2-106a5f2
   1413948:       trying file=/usr/lib64/tls/libgit2-106a5f2
   1413948:       trying file=/usr/lib64/libgit2-106a5f2

This file exists:
/path/to/application/runtimes/linux-x64/native/libgit2-106a5f2.so
But it appears that it is looking for the file without the ".so" extension?


text:
Q: Como selecionar todas as imagens existentes e adicionar um atributo a elas Então estou tentando selecionar todas as imagens existentes e cheguei a desenvolver esse código
(function ($) {

    var elementsImg = document.getElementsByTagName('img'), len, i;

    for (i=0, len=elementsImg.length; i<len; i++) {
       elementsImg[i].setAttribute('loading','lazy');
    }

})(jQuery);

Contudo, no console do devtools ele aparece como

Gostaria de saber uma possível de solução e o que estou fazendo de errado.

A: O código aparentemente está correto. Você não recebe um valor de retorno no console do seu navegador por conta do comportamento do método setAttribute, que não retorna valor algum. Quando nenhum valor é retornado de uma expressão, exibirá undefined no console; inclusive a própria chamada da função console.log exibirá o valor que foi passado como argumento e undefined logo em seguida, dado que console.log não retorna valor algum:
console.log(1)

1
undefined

Para verificar se os atributos foram inseridos nas imagens você pode utilizar o método getAttribute como no exemplo:
elementsImg[i].getAttribute('loading');

Retornando o valor do atributo. Caso o método não encontre o atributo retornará null.


text:
Q: Node.js - Pegar parâmetro de URL via Jade Tenho a seguinte url http://localhost:3000/user/index/1, gostaria de conseguir pegar o último parâmetro. Tentei com - var name = window.location.pathname; colocando no arquivo .jade e não funcionou, mas se for possível fazer um redirect com envio de parâmetros como no .render().

A: Solução:
notification: request.params.message

Este modo está em desuso:
notification: request.param('message','')


text:
Q: Do I need both bootstrap.js and bootstrap.min.js or is one of them enough? Alright so after working with bootstrap in school it seems like a really good alternative to the other ways of creating responsive sites. I know that both files are put together differently, like one is like a wall of text and the other is more "user friendly" put up, but is there anything else different about them or do I just need one of them?

A: It's not necessary to have both. You can use only bootstrap.min.js or bootstrap.js. The thing is to reduce the script size that has to be rendered by the browser. so only we have minified versions.


text:
Q: Stackoverflow.com is showing in text-only on Firefox, why? or whatever reason, my Firefox browser on this computer is displaying stackoverflow.com in basic HTML format (text and links). No images, no formatting, nothing.
This used to be fine. Its been like this a few days now.
I've:

*

*Deleted cookies - no luck.

*Deleted all of firefox's cache, history, cookies, site preference settings etc - no luck.

*Restarted firefox, rebooted - no luck.

All other sites I usually use are working fine, I don't think its an issue with firefox.
I've also:

*

*Checked the site it on IE - its working fine.

*Checked other stackexchange sites on firefox - they're working fine.

*Opened cdn.sstatic.net/stackoverflow/all.css in my browser with no problems.. its a wall of ugly css text but its there. [SOLVED: I should have done this in firefox instead of IE - would have noticed the cause of the problem sooner]

What gives?

A: Anna Lear gave a good hint.
I had browsed to cdn.sstatic.net/stackoverflow/all.css on IE. I needed to do it on firefox to see where it took me. I ended up in a 'certificate exception' page and needed to add a security exception for that site.
Once I did that, it solved the problem and now stackoverflow.com loads properly on firefox.
I also found good help in:
CSS for Stack Overflow didn't load
Everyone's hints helped solve this, thanks all.

A: Had a customer with a similar issue on a different site. Just wanted to add that this worked for us as well. Stylesheet was on a different certificate than the page, and an exception had to be created for that. Since I got here from a Google search, I'll ad the steps I took in case anyone else ends up here.
Simplified instructions:

*

*right-click anywhere on the page and choose "inspect element"

*look between the  tags for  tags. The one we are looking for will have: type="text/css" rel="stylesheet"

*it will also have a URL ending in .css after the 'href' like: href="www.someURL.com/stylesheet.css"

*Copy the address after the href and paste them into the address bar on a new tab

*You will get a security certificate warning. Click Add Exception.

*Reload the original page and everything should be working now


text:
Q: Interact with OutputCacheAttribute Given a controller action that is decorated with an OutputCacheAttribute, is it possible for the action itself to interact with the properties of the OutputCacheAttribute?
This would be useful if, for example, the action were to dynamically:

*

*Determine the CacheItemPriority and have that be set before returning the ActionResult.

*Determine that caching should be disabled for this particular request, and thus the NoStore property is set to true.

Yes, no?  If the answer is no, then what would be my fallback for output-caching in MVC with this kind of action-based dynamic behavior?

A: CacheItemPriority is not part of the OutputCacheAttribute so you'll either need to subclass OutputCacheAttribute and modify from there or roll-your-own (likely by subclassing ActionFilterAttribute).
The following article shows examples of what you are trying to do.  It looks like it was written before the standard MVC OutputCacheAttribute had any parameters available on it, so the majority of the article is showing what you want or things very close to what you want.
http://blog.maartenballiauw.be/post/2008/06/26/Creating-an-ASPNET-MVC-OutputCache-ActionFilterAttribute.aspx


text:
Q: Disable selectbox options using Angularstrap I am using angular strap select box. But, I want to disable all the options of the selectbox, how do I achieve this?
$scope.itemsPerPageList = ['All','10','20','30','40'];

<select class="span2"
     ng-init="itemsPerPage = itemsPerPageList[0]"
     ng-model="itemsPerPage" ng-change="changePager()"
     ng-options="obj as obj for obj in itemsPerPageList"
     data-style="btn-primary" bs-select>
</select>

I tried using ng-disabled=true, but no luck.

A: It seems you are using AngularStrap v1.x, which is outdated and not supported anymore. In AngularStrap v2.x, select is done this way:
<button type="button" class="btn btn-default"
    ng-model="selectedIcon"
    data-html="1"
    ng-options="icon.value as icon.label for icon in icons"
    bs-select>
  Action
</button>

And ng-disabled=true works with it. Take a look at the doc.


text:
Q: CSV: how to add columns to list and find best match (closest value) from another list? I have a code that reads a column in a CSV file with 3 columns: Zone, Offnet calls, and Traffic.

I need the code that will create a list from rows: for example line 3 will have a list of [421, 30167] and it will search the best match (closest value) from the list provided from the code:
tp_usp15 = [10, 200]
tp_usp23 = [15, 250]
tp_usp27 = [20, 300]
list_usp = [tp_usp15,tp_usp23, tp_usp27]

tp_bsnspls_s = [1,30]
tp_bsnspls_steel = [13,250]
tp_bsnspls_chrome = [18,350]
list_bsnspls = [tp_bsnspls_s,tp_bsnspls_steel,tp_bsnspls_chrome]

tp_bsnsrshn10 = [10,200]
tp_bsnsrshn15 = [15,300]
tp_bsnsrshn20 = [20,400]
list_bsnsrshn = [tp_bsnsrshn10,tp_bsnsrshn15,tp_bsnsrshn20]

common_list = list_usp + list_bsnspls + list_bsnsrshn

So, I need a code that will compare rows from CSV to this list. For example, I have a code that works with the close concept but it works with inputs provided by the user.
client_traffic = int(input("Enter the expected monthly traffic: "))
client_offnet = int(input("Enter monthly offnet calls: "))
list_client = [client_payment, client_offnet]

from functools import partial
def distance_squared(x, y):
    return (x[0] - y[0])**2 + (x[1] - y[1])**2
best_match_overall = min(common_list, key=partial(distance_squared, list_client))
name_best_match_overall = [k for k,v in locals().items() if v == best_match_overall][0]

How can I update this code to work with every row from the CSV file? Please, help.


text:
Q: session invalidated with iOS 8 share extension I have two targets in my workspace an iOS App (Bundle id: com.gotit.iphone.gotit, App Group: group.com.gotit.iphone.gotit) and an share extension (Bundle id: group.com.gotit.iphone.gotit.Got-it, App Group: group.com.gotit.iphone.gotit).
I can use my share extension without problem but sometimes (not all the time) when I directly come back to my iOS app I have this error and my app crashes :
Attempted to create a task in a session that has been invalidated
2015-07-22 16:31:21.999 iphone[6095:717111] *** Assertion failure in -[BDBOAuth1SessionManager setDelegate:forTask:], /Users/gautier/Documents/Dev/gotit/iOS/iPhone/trunk/iphone/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m:449
2015-07-22 16:31:22.001 iphone[6095:717111] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: task'
*** First throw call stack:
(0x1865a02d8 0x1982140e4 0x1865a0198 0x187454ed4 0x100547340 0x1005476d8 0x100549190 0x100522084 0x100520a38 0x1000c94a8 0x1000d9f9c 0x1000d9d8c 0x18b02ff08 0x18b1bb2bc 0x18b0cde84 0x18b0cdc50 0x18b0cdbd0 0x18b0156f4 0x18a951db8 0x18a94c820 0x18a94c6c4 0x18a94be58 0x18a94bbd8 0x18a945300 0x1865582a4 0x186555230 0x186555610 0x1864812d4 0x18fedf6fc 0x18b07ef40 0x1000d6fac 0x1988bea08)
libc++abi.dylib: terminating with uncaught exception of type NSException

I use AFNetworking (with BDBOAuth1SessionManager) and this is how I create my networkManager :
+ (instancetype)create {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[[self class] alloc] init];
    });
    return _sharedClient;
}

+ (instancetype)sharedClient {
    if (!_sharedClient) {
        [GotItClient create];
    }
    return _sharedClient;
}

- (id)init {
    self = [super init];
    if (self) {
        NSURL *baseURL = [NSURL URLWithString:kSCGotItClientAPIURL];
        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"group.com.gotit.iphone.gotit"];
        sessionConfiguration.sharedContainerIdentifier = @"group.com.gotit.iphone.gotit";

        _networkManager = [[BDBOAuth1SessionManager alloc]
                           initWithBaseURL:baseURL
                           sessionConfiguration:sessionConfiguration
                           consumerKey:kSCGotItClientKey
                           consumerSecret:kSCGotItClientSecret
                           shareDefaultGroupId:@"group.com.gotit.iphone.gotit"];
        _networkManager.responseSerializer = [[AFJSONResponseSerializer alloc] init];
        //4 operations at same time
        [[_networkManager operationQueue] setMaxConcurrentOperationCount:20];
    }
    return self;
}

Tell me if you need more code


text:
Q: Подсказки для функций в IntelliSense Использую XML-документацию в коде проекта, пример:
/// <summary>
/// Archive file or folder from target path
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool CreateZipFile(string path)
{
    ...
}

При работе внутри данного проекта подсказки IntelliSense отображаются нормально, но если проект скомпилировать отдельно и подключать в виде dll - подсказок нет.
Как исправить?

A: Нужно включить опцию XML documentation file в настройках проекта и следить чтобы сформированный XML-файл лежал рядом с библиотекой.


text:
Q: Internet traffic when connected to a SonicWALL VPN We have a new VPN to let all users connect to the company's applications through it (inside the company net).
We have a lot of users using the SonicWALL Client and we want to allow them use Internet.
The problem is that we don't want them to use the VPN for this traffic (I mean they should go out to Internet throught their own Internet provider at home).
I supose this is a client configuration but I can't realize what it is... Thanks in advance!!

A: On the Sonicwall router, browse to VPN and edit the "Group VPN" policy.   You want to make sure that "Allow Connections to:" is set to "Split Tunnels" and that the "Default Gateway" box is unchecked:

A: I had the same problem as zapico. I already changed "Allow connections to" to "Split tunnels" and disabled "Set default route as this gateway", but the SonicWALL VPN client still used the VPN connection as the default gateway.
After some trying I found out that it depends on the "VPN Client Access Networks" configured in User -> Local users -> Edit user -> VPN access. I just chose one internal network and it worked fine.
Internal network traffic goes through VPN and all internet traffic uses the internet connection.
Hope this helps.

A: Using camouflageX's answer and my suspicions that user config was at fault, I just removed all previous settings for the users and allowed "All MGMT IP". All works fine now.

A: I tried the configuration -
1) Virtual Adapter settings (allow connection to split tunnels)
2) not-tick the set default route as this gateway
3) "VPN Client Access Networks" configured in User -> Local users -> Edit user -> VPN access. Basically set only X0 subnet as the allowed address in the VPN assigned local user group
my outgoing WAN connection after establishing an L2TP connection persists to utilize the WAN IP of my remote network.
I had to configure the dial-up connection properties, IPv4 settings, and untick the set default route on remote gateway, to allow route of traffic via local internet.
Previously, without the above configuration, removing the tick on the setting for allow route will cause the VPN connection to not be established. However, the settings above (1,2,3) seems to have allowed me to disable the default route.


text:
Q: Input field must not be empty I have an input field where the field can't let you search unless you type/select something. How would I go about doing this?
<input type="text" class="form-control pg-csr-customer-search CSRinputBut" aria-label="" id="CustomerSearchText" name="CustomerSearchText" value="" placeholder="Search Customer" required>

I need to show this warning when the user just clicks or hits enter.
displayCustomerSearchMessage('<i class=\"fa fa-exclamation-circle pull-left\"></i> Sorry, missing selected Customer Id. Please make a selection from the results listing.', 'warning');

A: <input type="text" name="CustomerSearchText" id="CustomerSearchText" onblur="checkTextField(this);" />

//modify following code as your need
function checkTextField(field) {
    if (field.value == '') {
        alert("empty!!!");
    }
}

update
<form onsubmit="return checkTextField(this)">

function checkTextField(form) {
  var text = form.CustomerSearchText.value;

    if (text == '') {
            return false
        }

  return true;
}


text:
Q: Send SOCKS proxy credentials over SSL/TLS OpenVPN client config file has a socks-proxy rule which allows connecting to a SOCKS proxy before connecting to a VPN.
I installed Dante SOCKS proxy but it looks like it does not support SSL/TLS so credentials will be sent in clear text and someone on the same local network could do a man-in-the-middle attack by sniffing the network and see the credentials (https://security.stackexchange.com/questions/183146/are-socks5-credentials-safe-during-authentication-on-proxy-server).
Isn't it possible to add SSL/TLS support to Dante SOCKS proxy like it can be done with an FTP server?
If it is not possible officially, I think we need to use stunnel to create an SSL/TLS tunnel. But since the VPN only allows connections through UDP, I think we also need to use udptunnel (https://manpages.ubuntu.com/manpages/xenial/man1/udptunnel.1.html) because stunnel and SSL/TLS only work with TCP (https://www.stunnel.org/faq.html).
Here is my Dante SOCKS proxy configuration file /etc/sockd.conf on my VPS Linux server:
internal: venet0:0 port = 8088
external: venet0:0
socksmethod: username #none #rfc931
clientmethod: none
user.privileged: root
user.notprivileged: nobody
user.libwrap: nobody
client pass {
        from: 0.0.0.0/0 to: 0.0.0.0/0
        log: connect disconnect error
}
socks pass {
        from: 0.0.0.0/0 to: 0.0.0.0/0
        protocol: tcp udp
}

After starting sockd Dante SOCKS proxy, I start udptunnel on the same server, which should connect to the proxy:
udptunnel -s 8080 127.0.0.1:8088
Then I start stunnel on the same server, which should connect to udptunnel, with this configuration file /etc/stunnel/stunnel.conf:
client = no
[udptunnel]
accept = 8888
connect = 127.0.0.1:8080
cert = /etc/stunnel/stunnel.pem

And then I connect using OpenVPN on my computer, with this rule in the client config file:
socks-proxy PROXY_IP_ADDRESS 8888 stdin
However I did not get it working. I can only connect to the proxy and VPN if I am sending proxy credentials in clear text, which is not secure. Currently if I want to connect securely from a different IP address to a VPN, I have to connect from another VPN before connecting to the VPN, which works great but I would be interested to know if it is possible using a SOCKS proxy with SSL/TLS.


text:
Q: Network access virtualbox linux guest from linux host I've tried countless settings, read Virtualbox forums and googled for more hours than I'd like to admit.
What I want to accomplish is simply to be able to ssh into the guest and be able to view websites hosted on the guest. I do not care how I access the guest, whether its a bridged connection, host-only, NAT with port forwarding or anything else.
So what I need to know
Within Virtulabox manager > Preferences > Network > vboxnet0
--What should my 'Adapter' and, if needed, 'DHCP Server' settings be? An example of this would be great.
Within Virtualbox machine > Settings > Network
--What should I have for Settings? Specifically 'Attached to' 'Name' 'Adapter type' 'Promiscuous mode' 'Port Forwarding'
Or if you can link me to a solution that I may not have seen/tried already it would be greatly appreciated.

A: You probably have the VMs set up with NAT adapters to give them access to your host's network connection. You can't communicate between the host and the guest using the NAT adapter. You have to set up a host-only network and add a a host-only network adapter to the VM. The host and guest can communicate through this network, and two VMs can also communicate with each other.

*

*As you said, go to Virtualbox manager > File > Preferences > Network and
set up a host-only network. Enable the DHCP server. In my case, the
host adapter address is 192.168.56.1, the DHCP server address is
192.168.56.100, both masks are 255.255.255.0, and the server address range is 192.168.56.101-192.168.56.254, but I believe these were all
filled in by Virtualbox as defaults.

*After setting up this network, you should see a virtual interface on
your host system with the correct IP address (the one assigned to
the adapter).

*Now, go to network settings for the VM. Add a new network adapter.
Set "attached to" to the "host-only adapter", and the name to the
host-only network that you set up earlier.

*Start the VM. It should see the host-only adapter in addition to whatever adapters
it was using before. If it's a modern operating system, it'll probably query the
DHCP server and set up the interface on its own.

You can assign a host-only adapter to the VM in addition to a NAT adapter. I have a windows VM and an Ubuntu Linux VM set up this way. Both VMs have no trouble communicating with each other as well as the Internet.


text:
Q: matplotlib bar with asymmetrical error bars I need to plot a bar graph with asymmetrical error bars...
The documentation of the matplotlib.pyplot.bar function says:

Detail: xerr and yerr are passed directly to
  errorbar(), so they can also have shape 2xN for independent
  specification of lower and upper errors.

But, I can not give an 2xN array to the yerr...
import numpy as np
import matplotlib.pyplot as plt

plt.bar(xrange(5), [2,5,3,4,7], yerr=[[1,4,2,3,6],[4,10,6,8,14]]) #DO NOT work!

And show me the following error:
Traceback (most recent call last):
  File "bar_stacked.py", line 9, in <module>
    plt.bar(xrange(5), [2,5,3,4,7], yerr=[[1,4,2,3,6],[4,10,6,8,14]])
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 1742, in bar
    ret = ax.bar(left, height, width, bottom, color, edgecolor, linewidth, yerr, xerr, ecolor, capsize, align, orientation, log, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 4253, in bar
    "incompatible sizes: bar() argument 'yerr' must be len(%s) or scalar" % nbars)
ValueError: incompatible sizes: bar() argument 'yerr' must be len(5) or scalar

But, instead this function:
import numpy as np
import matplotlib.pyplot as plt

plt.errorbar(xrange(5), [2,5,3,4,7], yerr=[[1,4,2,3,6],[4,10,6,8,14]])

Works fine.
Does the matplotlib.pyplot.bar no longer support the 2xN arrays for yerr?
If the answere is yes... How can I plot a bar graph with asymmetrical error bars?
Thanks for your time!

A: Which version of matplotlib are you using?
With the 1.1.1 (latest stable) version your code work flawlessly.


text:
Q: vb.net - Multiple dialog forms push Main form behind other apps We have a VB.Net Application with a Main form that should always be visible. However, we want to be able to display a succession of two dialog windows where we can close the first dialog as the second one appears. However, when doing that, the Main form gets sent behind whatever other applications are open and does not re-appear until the second dialog window closes.
We can correct this issue by keeping the first dialog window open behind the second one, but it's not ideal. What are we doing incorrectly?

A: Try using dialog1.owner = mainform


text:
Q: I'm entitled to a cheese board? Really? I'm sure you know about all the cheesy happenings here on Meta. I understood that only the top 25 answers would receive a cheese board. Mine did not come close to the top 25.
Yesterday I received an email from JNat saying

Hello there!
You're receiving this because your answer on this Meta post entitled you to receive a cheese board! \o/

I thought that maybe everyone would receive one in the end (as the SE people are very generous :) ), but the update to the question gives a very different impression:

UPDATE: JNat will be sending out emails to collect addresses from the lucky users getting a cheese board — be on the lookout for those! :)

So the question is: was my email an error?
Please don't say yes!

A: If you got an email, then it wasn't in error, no. We originally said we'd award the top 25 answers, but then we decided, as you guessed, we'd be a bit more generous than that! :)
Hope you enjoy it, when it gets to you ;)


text:
Q: Find limit of $a_{n+1} = \frac{2a_n}{a_n+1}$.
Determine if the following sequence $(a_n)_{n \in \mathbb{N}}$ converges and if so, find the limit. $a_1 \geq 0$, $a_{n+1} = \frac{2a_n}{a_n+1}$.

What I've done so far:
First we can notice that if $a_1 = 0 \Rightarrow a_n = 0, n \in \mathbb{N}$ and thus $\lim\limits_{n \to \infty} a_n=0$.
If $a_1 > 0, a_n > 0$ by induction and $a_{n+1} = 2 - \frac{2}{a_n + 1}$ which gives $a_{n+1}a_n + a_{n+1}-2a_n = 0$. I'm not familiar with recurrence equations, but WolframAlpha gives an equation such that a limit of it is easy to evaluate and equals $1, n \rightarrow \infty$.
Is there another way to find the limit of this sequence?

A: Let $f(x) = \frac{2x}{x+1}$ for $x\geq 0$, so that $a_{n+1}= f(a_n)$.
Then, we have :
$$\forall x\geq 0, f(x)-x = \frac{x(1-x)}{x+1}$$
Therefore $1>f(x) > x$ when $x\in (0,1)$ and $1<f(x)<x$ when $x>1$.

*

*If $a_1$ is equal to $0$ or $1$, then $f(a_0) = a_0$ and the sequence is constant.

*If $a_1 \in (0,1)$, then you can show by induction that for all $n\in \mathbb N$,
$$0<a_n<a_{n+1}<1$$
Therefore, $(a_n)$ converges to some $\ell \in (0,1]$. Taking the limit in $a_{n+1} = f(a_n)$, we find $\ell = f(\ell)$, whose only solution on $(0,1]$ is $\ell = 1$.

*If $a_1 \in (1,+\infty)$, then by induction :
$$\forall n\in\mathbb N, 1<a_{n+1}<a_n $$
Therefore $a_n \to \ell \geq 1$. Again we have $f(\ell) = \ell$ which implies $\ell =1$.
Conclusion

If $a_1 = 0$, then $(a_n)$ converges to $0$. If $a_1>0$, then $(a_n)$ converges to $1$.

A: If $a_1\neq 0$, then $a_n\neq 0$ for all $n$ (prove this), so we have $\dfrac{1}{a_{n+1}} = \dfrac{1}{2}\dfrac{1}{a_n} + \dfrac{1}{2}$, or $\dfrac{1}{a_{n+1}} - 1 = \dfrac{1}{2}\Big(\dfrac{1}{a_n} -1\Big)$. Hence $\dfrac{1}{a_n} - 1 = \dfrac{1}{2^{n-1}}\Big(\dfrac{1}{a_1} -1\Big)$. Now what can you say about $\displaystyle{\lim_{n\to\infty}} a_n$?
Remark: the recurrence $x_{n+1} = \dfrac{a x_n+b}{c x_n+d}$ (where $a,b,c,d\in\mathbb{C}$ satisfy $ad-bc\neq 0$, this is called a Mobius transformation) always implies that $\{x_n\}$ has an elementary general formula.

A: There's a related proof to above using Fixed Points. Let $f(x)=2x/(x+1)=2-2/(x+1)$.
A Fixed Point is by definition a solution of $f(x)=x$.
Solving $x=2x/(x+1)=0=x^2-x \implies x=1$ or $x=0$.
$f'(x)=\frac{2}{(1+x)^2}$. In particular $f'(1)=1/2$.
Let $0<x<y$.
$f(x)-f(y)=2(\frac{1}{y+1}-\frac{1}{x+1})=2\frac{(x-y)}{(x+1)(y+1)}\implies |f(x)-f(y)|<|x-y|$
So if $f(y)=y$, then $|f(x)-y|<|x-y|$, so $x_n\to y$ for each iteration.
Further, for differentiable functions, $|f'(y)|<1$ also implies iterations get closer together and converge to y.
This provides a way to find limits: convert $a_{n+1}=f(a_n)$ to $f(x)=x$. Solve for $x$ and choose from those solutions where $f'(x)\le 1$.


text:
Q: Force 'Shared User Defaults Controller' to save to disk immediately? I have a preferences pane that uses the Shared User Defaults Controller, which reading and saving preferences a piece of cake.   It seems though that when changes are made to the fields, they aren't immediately saved to the plist fie.  This creates a problem when my application needs to re-read the file immediately after the change has been made and the plist still hasn't been updated.
How can I force the preferences pane to update the preferences file immediately?

A: This will automatically save any change you do right away to disk:
NSUserDefaultsController *controller = [NSUserDefaultsController sharedUserDefaultsController];
[controller setAppliesImmediately:YES];

If you need this only in specific cases, you can also use and save some of the expensive I/O (you really should try to let the cache mechanism cache as much as possible instead of writing everything right away to disk):
NSUserDefaultsController *controller = [NSUserDefaultsController sharedUserDefaultsController];
[controller save:self];

Also, are you sure that you are trying to solve the right problem? You can always get the up to date version of the user defaults by querying NSUserDefaults where you don't need to care about wether the current version is cached in RAM or already written to disk.

A: Per the docs:
[userDefaults save:self];

or
[userDefaults setAppliesImmediately:YES];


text:
Q: how to figure image size to fit below header and above footer I want to center an image in the available space below the page header and above the page footer.
It needs to be responsive, so I want the picture to be as large as possible but not overlap the header and footer.
The ID of the image is #nMapImg.
I have these values:
var dh=$(document).height();
var dw=$(document).width();
var hh=$("#header").height();
var fh=$("#footer").height();
var w=$("#nMapImg").width();
var availHeight=h-hh-fh;

I think this is just math to figure the max size I can have and then I'll center it. I just can't wrap my head around it.

A: using flexbox, you can achieve this with pure css

body {
  margin: 0;
  padding: 0;
}
html, body, .app {
  height: 100%;
}
header {
  background: red;
}
footer {
  background: blue;
}
footer, header {
  height: 400px;
}

img {
  max-width: 100%;
  max-height: 100%;
}
.app {
  display: flex;
  flex-direction: column;
}
.content {
  flex: 1 1 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

  header

  footer

A: Since you said it is allowed to place a div between the header and footer the easiest way to have the largest image possible is:

You can also add background-position: center center; when needed

A: Using flexbox and setting a height on a div where the image lies

*{margin: 0;}
header{
  background: green;
  height: 100px;
}

footer{
  background: green;
  height: 100px;
}

.main{
  height: 1000px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.main img{
  width: 100%;
}

HEADER

FOOTER


text:
Q: Getting the activeLayer() in Eclipse I've been working on a plugin in python for qgis. I'm using Eclipse-pydev with remote-debug.
I believe I'm set up correctly; I've followedthe Cookbook instructions completely. When starting remote-debug, I get the blue banner with "Debugging connection activated", and Pydev Debug creates a branch named "unknown". The qgis API's path is also set in Eclipse.
From the debug I launch :
from qgis.utils import iface
layer = iface.activeLayer()
print "layername:", layer.name()

Doing this I get the following: AttributeError:'Nonetype' object has no attribute 'activeLayer'
Of course I've made sure to actually have a layer selected before running.
This means that the connection between qgis and eclipse isn't exactly working, but I've redone the instructions a few times now and pretty sure I've completed them word for word.
Here's a screencap of the debug branchings that I get:

And this is the correct debug branching as shown in pydev.org/

As you can see, the correct one branches the .py file
under 'unkown', whereas mine creates a new, probably disconnected branch.
How do I change that?


text:
Q: Match any word that starts with a character, Regex I am writing an extension for vscode and I am using regular expressions for the grammers. I am currently trying to find every word that beings with * but if there is a solution that expands to any character feel free to suggest it.
Any suggestions so far that I have seen have not worked. I think how TextMatte processes these expressions are a bit different so I think that is why.
Example of what I want.
This is a *star word. Here is another *word with a star.

*start *word

A: From what I know of TextMate, escaping characters works as normal, so matching to:
\*\w+

should give you the words you're looking for, that begin with a *.

A: (?<!\b)\*[a-zA-Z0-9_]+ if you want *first_name to be a word
(?<!\b)\*[a-zA-Z0-9]+ if you don't
Could also throw in other symbols
the (?<!\b) is a negative look ahead to avoid stuff like not*me
[a-zA-Z0-9] is a common way to select all numbers and letters
+ tells it 1 or more
https://regex101.com/r/epX4R9/1

I'm not familiar with TextMatte so apologies if this is unhelpful

per comments, TextMatte accepts the regex from json so the slashes needed to be escaped:
(?<!\\b)\\*[a-zA-Z0-9_]+


text:
Q: How to attach database file in Visual Studio 2015 I am trying to attach a SQL Server database file in Visual Studio but with no luck, I'm stuck with a message that says:

Cannot open user default database. Login failed.

I even try to take the database offline, copied it into the project folder that I'm working on but still, nothing happens. Any help will gladly be appreciated...


text:
Q: How to store/save Ids and Passwords in webview? I have a WebView app which opens up my Blog,
My blog has options to share posts via F.B, Twitter etc..
My problem is, Everytime a user wishes to share a post, he should Login everytime!
What should I do so that the Webview saves the id/pass so that the User doesn't need to Login each time...

A: you need to save cookies in order to save username password in web-view .
But its deprecated in API 18. although you can use java script interfaces to save username passwords.


text:
Q: Swipe View in Android/MonoAndroid? I am wondering is there a view in android that you can swipe and it goes to another view? I am using mono Android but can't seem to find anything on how to do this. I expanded my search to android but can't find anything as well.
Does anyone know a sample project that has this that I can look at and use?

A: There is currently no View that comes with Android that does this. There are however several 3rd party ones.
@Commonsguy extended ViewFlipper to make it recognize swipe touch events and flip views accordingly.
Check out the ViewSwiper source code
Edit: I am not familiar with monodroid, so I am afraid I am of no help there. And the difference between them is that ViewSwiper has extended ViewFlipper and adds support for switching views via a swipe or "fling" gesture on the screen. View flipper has no such support by default.

A: Google released the compatibility pack with some new UI Elements, which you can download via SDK Manager.

*

*put the .jar file located in sdkfolder/extras/compatibility in your build path.

*now you can use a class called ViewPager which behaves like the Android Homescreen.
Or, if you are using Eclipse and ADT plugin v12 or higher, just right click your project, choose "Android Tools" and then "add compatibility package".


text:
Q: Sort the content of a DataTable according to a TextBox I would like to select my DataGridView's Rows by putting the value I'm looking for in a textbox. Also I would like the most identical value to be focused on / selected.
I already tried using the rowfilter function, which gave me this:
(dgv_DetailComptes.DataSource as DataTable).DefaultView.RowFilter = string.Format("Champ LIKE '%{0}%'", tbx_champ_Cpt.Text);

However, it filters the rows, meaning the other rows disapear when their content isn't the one I'm looking for. I would like to keep the rows in my table, and select the rows containing the value I'm looking for.
Also, my DGV takes it's Rows / Columns / values from a data Table so that might prevent me from using my DataGridView's row's index to search for the row containing the value.
Is there a way to select my rows this way ?
Thank you for your answers.

A: In the end I managed to find, doing maybe some useless stuff I don't know.
here's the code:
        private void tbx_champ_Cpt_TextChanged(object sender, EventArgs e)
    {
        if (tbx_champ_Cpt.Text.ToString() == "")
        {
            for (int i = 0; i < dgv_DetailComptes.Rows.Count - 1; i++)
            {
                dgv_DetailComptes.Rows[i].Selected = false;
            }
        }
        else
        {
            tbx_champ_Cpt.SelectionStart = tbx_champ_Cpt.Text.Length;
            tbx_champ_Cpt.Text = tbx_champ_Cpt.Text.ToString().ToUpper();
            DataTable d = (DataTable)dgv_DetailComptes.DataSource;
            String text = tbx_champ_Cpt.Text.ToString();
            DataRow[] row = d.Select("Champ like '%" + text + "%'");
            List<int> listeIndex = new List<int>();
            for (int i = 0; i < dgv_DetailComptes.Rows.Count - 1; i++)
            {
                foreach (DataRow r in row)
                {
                    if (((DataRowView)dgv_DetailComptes.Rows[i].DataBoundItem).Row == r)
                    {
                        dgv_DetailComptes.Rows[i].Selected = true;
                        listeIndex.Add(i);
                    }
                    else if (!listeIndex.Contains(i))
                    {
                        dgv_DetailComptes.Rows[i].Selected = false;
                    }
                }

            }
        }
        if (dgv_DetailComptes.SelectedRows.Count != 0)
        {
        dgv_DetailComptes.FirstDisplayedScrollingRowIndex = dgv_DetailComptes.SelectedRows[0].Index;
        }
    }


text:
Q: Set background color to PARAGRAPH using itextSharp version 4 neither CHUNK nor entire pages only for paragraph using C# I have tried to apply background color on paragraph using C# and iTextSharp version 4 not able to do. While applying background to CHUNK, it is applying only for text's background but not paragraph background.
Please check below snapshots and suggest.


text:
Q: WiLINQ: TFS 2012 I'd like to use a LINQ to TFS Provider, and it seems like WiLINQ is the way to go.
The Problem: We have TFS 2013 on the Server and only VS 2010 and 2013 on the Development-Clients.
Since the WiLinq is only obtainable for TFS 2012, my questions:

*

*Is it still possible to work with it with the DataStructure of TFS
2013?

*How Do I get the VS 2012 SDK (or the needed DLLs) to the local
Computers to get the reference going?

Or would you say, on this Environment, there is no "right" way to make this work?
Thanks in advance
Matthias

A: You will need to have the 2012 API's available to be able to run a tool that depends on that version. There is a redistributable for the API's alone however on local workstations it can be easier to install Team Explorer.

*

*TFS 2012 Update 4 Object Model


text:
Q: C++ comparing bunch of values with a given one I need to compare one given value with a retrieved values. I do this several times in the code. I am not satisfied with how it looks and I am seeking for a some sort of an util function. Anyone wrote one?
Number of values I am comparing with is known at the compile time.
Update: I'd like to get rid of containers as I know exact amount of values ( often not more then 3 ) I want to compare with. And it is not so convenient to put items to the container every time.
I don't love if neither because it is not obvious as "find".
#include <algorithm>
#include <string>
#include <vector>

std::string getValue1()
{
    return "test";
}

std::string getValue2()
{
    return "the";
}

std::string getValue3()
{
    return "world";
}

int main()
{
    const std::string value = "the";

    // simple if
    if ( value == getValue1() ||
         value == getValue2() ||
         value == getValue3() )
        return 1;

    // using collections like vector, set
    std::vector<std::string> values;
    values.push_back( getValue1() );
    values.push_back( getValue2() );
    values.push_back( getValue3() );
    if ( values.end() != std::find( values.begin(), values.end(), value ) )
        return 1;

    // third option I'd use instead
    //

    return 0;
}

A: If the values you're looking for are Comparable with operator< (like ints, float and std::strings), then it's faster to use an std::set to put the values there and then check set.find(value) == set.end(). This is because the set will store the values with a certain order that allows for faster lookups. Using an hash table will be even faster. However, for less than 50 values or so you might not notice any difference :) So my rule of thumb would be:

*

*Less then 5 items: if with multiple ||

*5 or more: put in a set or hash table

A: you can write a set of template functions which will help you through with this, for example:
template <typename T>
bool InSet(const T & item, const T & i1, const T & i2) {
  return item==i1 || item==i2;
}

template <typename T>
bool InSet(const T & item, const T & i1, const T & i2, const T & i3) {
  return item==i1 || item==i2 || item==i3;
}

Note that you can make InSet to work like it took a variable number of arguments by creating multiple templates with different number of arguments.
And then:
int i;
if (InSet(i, 3, 4, 5)) { ... }
string s;
if (InSet(s, "foobar", "zap", "garblex")) { ... }

etc.

A: You don't need a std::set or a std::vector.  Just use std::set_intersection()...
Code is best...
#include <set>
#include <iostream>
#include <iterator>
using namespace std;

#define COUNT(TYPE,ARRAY)  ( sizeof(ARRAY) / sizeof(TYPE) )

inline bool CaseInsensitiveCompare (const char * a, const char * b)
  {  return strcasecmp( a, b ) < 0;  }

int  main()
{
  const char * setA[] = { "the", "world", "is", "flat" };
  const char * setB[] = { "the", "empty", "set", "is", "boring" };

  stable_sort( setA,  setA + COUNT( const char *, setA ),
               CaseInsensitiveCompare );

  stable_sort( setB,  setB + COUNT( const char *, setB ),
               CaseInsensitiveCompare );

  cout << "Intersection of sets:  ";
  set_intersection( setA, setA + COUNT( const char *, setA ),
                    setB, setB + COUNT( const char *, setB ),
                    ostream_iterator<const char *>(cout, " "),
                    CaseInsensitiveCompare );
  cout << endl << endl;
}

Or perhaps, given your 1-N lookup problem:
(Note: Use binary_search() AFTER sorting!)
if ( binary_search( setA, setA + COUNT( const char *, setA ),
            "is", CaseInsensitiveCompare ) )
  ...

if ( binary_search( setA, setA + COUNT( const char *, setA ),
            "set", CaseInsensitiveCompare ) )
  ...

A: For your request to do
if (InSet(value)(GetValue1(), GetValue2(), GetValue3()))
{
   // Do something here...
}

Try this:
template <typename T>
class InSetHelper
{
     const T &Value;
     void operator=(const InSetHelper &);
public:
     InSetHelper(const T &value) : Value(value) {}

     template<class Other, class Another>
     bool operator()(const Other &value1, const Another &value2) const
     {
         return Value == value1 || Value == value2;
     }
     template<class Other, class Another, class AThird>
     bool operator()(const Other &value1, const Another &value2, const AThird &value3) const
     {
         return Value == value1 || Value == value2 || Value == value3;
     }
};

template <typename T>
InSetHelper<T> InSet(const T &value) { return InSetHelper<T>(value); }

This syntax might be more clear though:
if (MakeSet(GetValue1(), GetValue2(), GetValue3()).Contains(value))
{
   // Do something here...
}

template <typename T, typename U, typename V>
class Set3
{
    const T& V1;
    const U& V2;
    const V& V3;
    void operator=(const Set3 &);
public:
    Set3(const T &v1, const U &v2, const V &v3) : V1(v1), V2(v2), V3(v3) {}

    template <typename W>
    bool Contains(const W &v) const
    {
        return V1 == v || V2 == v || V3 == v;
    }
};

template <typename T, typename U>
class Set2
{
     // as above
};

template <typename T, typename U, typename V>
Set3<T, U, V> MakeSet(const T &v1, const U &v2, const V &v3)
{
    return Set3<T, U, V>(v1, v2, v3);
}

template <typename T, typename U>
Set3<T, U> MakeSet(const T &v1, const U &v23)
{
    return Set3<T, U, V>(v1, v2);
}

If those values are really part of a tree or a linked list, then you have your set/container already, and your best bet is to just use some recursion:
parent.ThisOrDescendantHasValue(value);

You'd just add this to whatever class parent and child belong to:
class Node
{
public:
    Value GetValue();
    Node *GetChild();
    bool ThisOrDescendantHasValue(const Value &value)
    {
        return GetValue() == value
           || (GetChild() && GetChild->ThisOrDescendantHasValue(value));
    }
};

A: Which changes more, the 'value' or the values returned by 'getValueX()'?  You can insert everything into a hash_map/map and then do a search that way, as you've suggested with the containers.

A: std::find_first_of.
Of course, if you only care about finding a single value, you can create your own wrapper around std::find.

A: I would recommend your method 2, using a std::vector or other container and looking for membership. Since the order of elements that you're checking against is probably not relevant, you may want to use a std::set or std::map. If you have very many items in your set of values, then using a set or a map will be a faster, while if you have only a few a vector may be faster.
The advantage of any of these approaches is that you can then store the set/map somewhere common, and avoid having to build the set of matching responses every time.

A: i like the collections approach, maybe use a hash_set instead of a vector. store the values in a property file and have a method to populat the hash_set from the file, and another one to return a boolean if the value is in the hash_set. then you can get down to one 2 lines in the main code.

A: It depends on the source of the retrieved values, if you're reading in from a file or stream then you'd do something different but if your source is a series of functions then the following is a different way to do it, not perfect but may suit your needs:
const int count = 3;
std::string value = "world";
boost::function<std::string(void)> funcArray[count];
funcArray[0] = &getValue1;
funcArray[1] = &getValue2;
funcArray[2] = &getValue3;

for( int i = 0; i < count; ++i )
{
    if( funcArray[i]() == value )
        return 1;
}

If you know which functions are the source (as well as the count of objects) I expect you could assemble the function pointer array using the preprocessor.

A: How about using a boost::array (or std::tr1::array) and creating a simple function like this:
template <typename ValueType, size_t arraySize>
bool contains(const boost::array<ValueType, arraySize>& arr, const ValueType& val)
{
    return std::find(arr.begin(), arr.end(), val)!=arr.end();
}

You could then reuse that pretty easily:
#include <string>
#include <iostream>

#include <boost\array.hpp>

template <typename ValueType, size_t arraySize>
bool contains(const boost::array<ValueType, arraySize>& arr, const ValueType& val)
{
    return std::find(arr.begin(), arr.end(), val)!=arr.end();
}

int _tmain(int argc, _TCHAR* argv[])
{
    boost::array<std::string, 3> arr = {"HI", "there", "world"};

    std::cout << std::boolalpha
        << "arr contains HI: " << contains(arr, std::string("HI")) << std::endl
        << "arr contains blag: " << contains(arr, std::string("blag") ) << std::endl
        << "arr contains there: " << contains(arr, std::string("there") ) << std::endl;

    return 0;
}

Edit: So boost is out. It's pretty easy to adapt this to a regular array:
template <typename ValueType, size_t arraySize>
bool contains(ValueType (&arr)[arraySize], const ValueType& val)
{
    return std::find(&arr[0], &arr[arraySize], val)!=&arr[arraySize];
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::string arr[3] = {"HI", "there", "world"};

    std::cout << std::boolalpha << "arr contains HI: " << contains(arr, std::string("HI")) << std::endl
        << "arr contains blag: " << contains(arr, std::string("blag") ) << std::endl
        << "arr contains there: " << contains(arr, std::string("there") ) << std::endl;

    return 0;
}