text:
Q: Помогите разобраться с интерактивной анкетой Есть анкета подобного плана
Помогите сделать так чтобы определенные пункты появлялись и пропадали в зависимости от того какой "тип занятости выбран"
Не совсем понимаю как это реализовывается на JS (jquery). Помогите пожалуйста!

Занятость:

                                            Тип занятости:
                                            <select name="svedeniya_o_rabote" id="svedeniya_o_rabote" class="is-valid">
                                                <option value="Штатный работник" selected="">Штатный работник</option>
                                                <option value="Индивидуальный предприниматель">Индивидуальный предприниматель</option>
                                                <option value="Самозанятое лицо">Самозанятое лицо</option>
                                                <option value="Пенсионер">Пенсионер</option>
                                                <option value="Студент">Студент</option>
                                                <option value="Социальный бенифициар / В декретном отпуске">Социальный бенифициар / В декретном отпуске</option>
                                                <option value="Безработный">Безработный</option>
                                            </select>

                                            Сфера деятельности:
                                            <select name="sfera_deyatelnosti" id="sfera_deyatelnosti" class="is-valid">
                                                <option value="Не выбрано" selected="">Не выбрано</option>
                                                <option value="Добывающая промышленность">Добывающая промышленность</option>
                                                <option value="Здравоохранение">Здравоохранение</option>
                                                <option value="Информатика, телекоммуникации, IT">Информатика, телекоммуникации, IT</option>
                                                <option value="Легкая и пищевая промышленность">Легкая и пищевая промышленность</option>
                                                <option value="Наука и культура">Наука и культура</option>
                                                <option value="Общественное питание">Общественное питание (кафе, рестораны)</option>
                                                <option value="Охранное предприятие">Охранное предприятие (ЧОП, детективное агентство)</option>
                                                <option value="Реклама, маркетинг, PR, СМИ">Реклама, маркетинг, PR, СМИ</option>
                                                <option value="Сельское хозяйство">Сельское хозяйство</option>
                                                <option value="Силовые структуры">Силовые структуры (ВC, МЧС, МВД и т.п.)</option>
                                                <option value="Торговля оптовая, риелторская деятельность">Торговля оптовая, риелторская деятельность</option>
                                                <option value="Торговля розничная">Торговля розничная</option>
                                                <option value="Федеральное и муниципальное управление">Федеральное и муниципальное управление</option>
                                                <option value="Финансы, страхование, банковское дело">Финансы, страхование, банковское дело</option>
                                                <option value="Химия, парфюмерия, фармацевтика">Химия, парфюмерия, фармацевтика</option>
                                                <option value="Юридические и нотариальные услуги">Юридические и нотариальные услуги</option>
                                                <option value="Иное">Иное</option>
                                            </select>

                                        Место работы:
                                        <input type="text" name="mesto_raboty" id="mesto_raboty" placeholder="" />

                                        Адрес в свободной форме:
                                        <input type="text" name="adres_raboty" id="adres_raboty" placeholder="" />

                                        Телефон места работы:
                                        <input type="tel" name="phone_raboty" maxlength="12" id="phone_raboty" placeholder="+7(___) ___-__-__"  />

                                        Должность:
                                        <input type="text" name="doljnost" id="doljnost" placeholder="" />

                                        Источник дохода:
                                        <select name="istochnik_dohoda" id="istochnik_dohoda" class="is-valid">
                                            <option value="Не выбрано" selected="">Не выбрано</option>
                                            <option value="Заработная плата">Заработная плата</option>
                                            <option value="Доходы от предпринимательской деятельности">Доходы от предпринимательской деятельности</option>
                                            <option value="Пенсия">Пенсия</option>
                                            <option value="Стипендия">Стипендия</option>
                                            <option value="Пособие">Пособие</option>
                                            <option value="Другие доходы">Другие доходы</option>
                                        </select>

                                        Сумма среднемесячного дохода (руб):
                                        <input type="number" name="srednemesyachnii_dohod" id="srednemesyachnii_dohod" placeholder="" />

                                        Общая сумма ежемесячных обязательств (руб):
                                        <input type="number" name="ejemesyachnie_obyazatelstva" id="ejemesyachnie_obyazatelstva" placeholder="" />

                                        Сумма среднемесячных платежей по всем действующим потребительским кредитам и займам (руб):
                                        <input type="number" name="summa_po_kreditam" id="summa_po_kreditam" placeholder="" />

                                        Задолженность по всем кредитам (руб):
                                        <input type="number" name="zadoljennost_po_kreditam" id="zadoljennost_po_kreditam" placeholder="" />

                                        Цель займа:
                                        <select name="cel_zaima" id="cel_zaima" class="is-valid">
                                            <option value="Не выбрано" selected="">Не выбрано</option>
                                            <option value="Ремонт дома и автомобиля">Ремонт дома и автомобиля</option>
                                            <option value="Непредвиденные расходы">Непредвиденные расходы</option>
                                            <option value="Покупка бытовой техники и электроники">Покупка бытовой техники и электроники</option>
                                            <option value="Ежедневные расходы">Ежедневные расходы</option>
                                            <option value="Медицинские услуги">Медицинские услуги</option>
                                            <option value="Подарки">Подарки</option>
                                            <option value="Путешествия, отдых">Путешествия, отдых</option>
                                            <option value="Образование">Образование</option>
                                            <option value="Бизнес">Бизнес</option>
                                            <option value="Другое">Другое</option>
                                        </select>

Например когда выбрано "Пенсионер"  пропадает "Сфера деятельности:" "Место работы" "Адрес в свободной форме"  "Телефон места работы:" "Должность:"
select.addEventListener("change", function (e) {
    // Безработный
    if (select.value === "Безработный") {
      sfera.value = "Не выбрано";
      sfera.closest("div").style.display = "none";
      mesto.closest("div").style.display = "none";
      adres.closest("div").style.display = "none";
      phone.closest("div").style.display = "none";
      doljnost.closest("div").style.display = "none";
    } else {
      sfera.closest("div").style.display = "block";
      mesto.closest("div").style.display = "block";
      adres.closest("div").style.display = "block";
      phone.closest("div").style.display = "block";
      doljnost.closest("div").style.display = "block";
    }
    // Социальный бенифициар
    if (select.value === "Социальный бенифициар") {
      sfera.value = "Не выбрано";
      sfera.closest("div").style.display = "none";
      mesto.closest("div").style.display = "none";
      adres.closest("div").style.display = "none";
      phone.closest("div").style.display = "none";
      doljnost.closest("div").style.display = "none";
    } else {
      sfera.closest("div").style.display = "block";
      mesto.closest("div").style.display = "block";
      adres.closest("div").style.display = "block";
      phone.closest("div").style.display = "block";
      doljnost.closest("div").style.display = "block";
    }
    // Пенсионер
    if (select.value === "Пенсионер") {
      sfera.value = "Не выбрано";
      sfera.closest("div").style.display = "none";
      mesto.closest("div").style.display = "none";
      adres.closest("div").style.display = "none";
      phone.closest("div").style.display = "none";
      doljnost.closest("div").style.display = "none";
    } else {
      sfera.closest("div").style.display = "block";
      mesto.closest("div").style.display = "block";
      adres.closest("div").style.display = "block";
      phone.closest("div").style.display = "block";
      doljnost.closest("div").style.display = "block";
    }
    // Студент
    if (select.value === "Студент") {
      sfera.value = "Не выбрано";
      sfera.closest("div").style.display = "none";
      mesto.closest("div").style.display = "none";
      adres.closest("div").style.display = "none";
      phone.closest("div").style.display = "none";
      doljnost.closest("div").style.display = "none";
    } else {
      sfera.closest("div").style.display = "block";
      mesto.closest("div").style.display = "block";
      adres.closest("div").style.display = "block";
      phone.closest("div").style.display = "block";
      doljnost.closest("div").style.display = "block";
    }
    // Самозанятый
    if (select.value === "Самозанятый") {
      sfera.value = "Не выбрано";
      mesto.closest("div").style.display = "none";
      adres.closest("div").style.display = "none";
      phone.closest("div").style.display = "none";
      doljnost.closest("div").style.display = "none";
    } else {
      mesto.closest("div").style.display = "block";
      adres.closest("div").style.display = "block";
      phone.closest("div").style.display = "block";
      doljnost.closest("div").style.display = "block";
    }
    // Индивидуальный предприниматель
    if (select.value === "Предприниматель") {
      sfera.value = "Не выбрано";
      adres.closest("div").style.display = "none";
      phone.closest("div").style.display = "none";
      doljnost.closest("div").style.display = "none";
    } else {
      adres.closest("div").style.display = "block";
      phone.closest("div").style.display = "block";
      doljnost.closest("div").style.display = "block";
    }

  });

A: Можно просто скрывать блок и обнулять значение. Написал только для сферы деятельности, остальное по примеру.
var select = document.getElementById('svedeniya_o_rabote');
var sfera = document.getElementById('sfera_deyatelnosti');
select.addEventListener('change', function(e) {
    if(select.value === 'Пенсионер'){
        sfera.value = 'Не выбрано';
        sfera.closest('div').style.display = 'none';
    }else{
      sfera.closest('div').style.display = 'block';
    }
});


text:
Q: How to load Widget javascript + css files only if used? I'd like to keep the javascript and css styles used by my widget inside their own files (and not add them to the theme).
But i can't seem to get wordpress to add them when the widget is actually used on a sidebar.
I've tried this:
inside the Class declaration, i've added 2 functions
class EssentielleRubriquesPosts extends WP_Widget {

function addFrontendCss(){
    wp_enqueue_style('erw-frontend-css', ESSENTIELLE_RUBRIQUE_WIDGET_PLUGIN_PATH . 'css/EssentielleRubriqueWidget-frontend.css');
}
function addFrontendJavascript(){
    wp_register_script('jq-hoverintent', PLUGIN_PATH . 'js/jquery.hoverintent.js', array('jquery'), '1.0',true);
    wp_enqueue_script('jq-hoverintent');
    wp_enqueue_script('jq-tools', PLUGIN_PATH . 'js/jquery.tools.js', array('jquery'),'1.0',true);
    wp_enqueue_script('erw-frontend-js', PLUGIN_PATH . 'js/widget-frontend.js', array('jquery', 'jq-hoverintent', 'jq-tools'),'1.0',true);

}

and inside the widget() function:
function widget($args, $instance) {
        add_action( 'wp_print_scripts', 'addFrontendJavascript' );
        add_action( 'wp_print_styles', 'addFrontendCss' );
}

But that doesn't do anything...

A: wp_print_scripts and wp_print_styles hooks are fired way before your widget function so that is way it's not working.
A solution to that would be to include the scripts in the footer using wp_print_footer_scripts hook, take a look at Jan's answer to a similar question
Or a much nicer solution take a look at Sorich's answer to another similar question

A: Best solution is to register your assets first and then enqueue the CSS and JS inside the widget() function of your WP_Widget (directly enqueue, not by adding new hooks).
I have tested this solution and it does work in current WordPress version (4.5.3) - both the JS and the CSS are added in the page footer.
<?php
// Register your assets during `wp_enqueue_scripts` hook.
function custom_register_scripts() {
    wp_register_style('erw-frontend-css', '...frontend.css');
    wp_register_script('jq-hoverintent', '...hoverintent.js', ...);
    wp_register_script('jq-tools', '...tools.js', ...);
}
// Use wp_enqueue_scripts hook
add_action('wp_enqueue_scripts', 'custom_register_scripts');

class YourWidget extends WP_Widget {
    public function __construct() {
    }

    public function widget( $args, $instance ) {
        // Enqueue needed assets inside the `widget` function.
        wp_enqueue_style('erw-frontend-css');
        wp_enqueue_script('jq-hoverintent');
        wp_enqueue_script('jq-tools');

        // Output widget contents.
    }

    public function form( $instance ) {
    }

    public function update( $new_instance, $old_instance ) {
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: External CSS in React Typescript NPM package I have a React Typescript Storybook project that I have used to create some components. I am using Rollup to bundle these components up (the non-storybook files) up as a reusable NPM package.
I have this working apart from the fact that my components use bootstrap for the styling - how do I /what is the best way to bundle this into my package?

A: I got round this by using require JS. For example in my index.ts file i do the following:
import logo from "./stories/assets/scts-logo-sm.png";
require("bootstrap/dist/css/bootstrap.min.css");
require("bootstrap-icons/font/bootstrap-icons.css");

export { logo };
export * from "./stories/Button";
export * from "./stories/Footer";
export * from "./stories/Header";

Don't know if this is best practice - the storybook/rollup documentation isn't very good on this.... CSS Modules might be another way to do it


text:
Q: Line Break in Python not working kanye_quote = """My greatest pain\
 in life is that I will never be able to see myself perform live"""

I am trying to create a line break but not having any luck. I am using the """ method to allow for multiple lines. It was my understanding that \ would create a new line but when I run the script, I am not getting a new line. Any Help would be terrific in solving this little problem.

A: If you remove the \ you got a line break. The \ is telling python to ignore the line break. The triple quote method lets you enter string on multiple lines. If you want to enter the string on one line you can use \n to get line breaks.


text:
Q: Creating text in the center of a marker I've been playing with Google Map API for a few days now and it's pretty straight forward for the most part, but one thing that we need to do, I can't figure out.  I've played with the labels as you can see in the example below, but I'm unable to give them to look that I have in the image below.   Can someone point me to a reference so I can achieve my requirements?
If your looking for the makerwithlable.js, you can get it from here..  Its where I got it:
https://code.google.com/p/google-maps-utility-library-v3/source/browse/trunk/markerwithlabel/src/markerwithlabel.js?r=288
<!DOCTYPE html>

Example of what I'm trying to do.

A: Based on the value of size you may set the style(fontSize,width,height etc.) and the labelAnchor

{
  var showOnStartInfoWindows = true;
  //create locations..
  var arrayAll = [];
  var marker = [];
  var jax = new google.maps.LatLng(30.318028, -81.674474);
  var leesburg = new google.maps.LatLng(28.810750, -81.880056);
  var map = null;

  arrayAll[0] = {
    loc: jax,
    size: 5000,
    info: "Jacksonville, FL 32204"
  };
  arrayAll[1] = {
    loc: leesburg,
    size: 1000,
    info: "Leesburg, FL"
  };
  //EO create locations..
}

function initialize() {
  //center the map on Jacksonville
  var mapProp = {
    center: arrayAll[0].loc,
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  //set google's API and pass the DIV by ID.
  map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

  var bounds = new google.maps.LatLngBounds(leesburg, jax);
  map.fitBounds(bounds);

  var maxSize = 0;
  for (var i = 0; i < arrayAll.length; i++) {
    if (maxSize < arrayAll[i].size)
      maxSize = arrayAll[i].size;
  }

  for (var i = 0; i < arrayAll.length; i++) {
    var size = Math.round((arrayAll[i].size / maxSize) * 100);

    //create MarkerWithLabel
    marker[i] = new MarkerWithLabel({
      labelInBackground:false,
      position: arrayAll[i].loc,
      map: map,
      title: 'Right-Click to zoom all the way in.\nLeft-Click to zoom to a state level.',
      labelAnchor: new google.maps.Point((size * 1.8) / 2, (size / 3)),
      labelClass: "googleLabel", // the CSS class for the label
      labelStyle: {
        width: (size * 1.8) + 'px',

        height: (size / 1.5) + 'px',
        lineHeight: (size / 1.5) + 'px',
        fontSize: (size / 1.5) + 'px'
      },
      labelContent: arrayAll[i].size,
      icon: {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: 0.6,
        fillColor: 'gold',
        strokeOpacity: 1.0,
        strokeColor: '#0000ff',
        strokeWeight: 1.0,
        scale: size, //pixels
      }
    });

    marker[i].setMap(map);

  }
}

{
  google.maps.event.addDomListener(window, 'load', initialize);
}
html,
body,
#googleMap {
  margin: 0;
  padding: 0;
  height: 100%;
}
.googleLabel {
  color: #000;
  font-weight: bold;
  text-align: center;

}


text:
Q: Ubuntu 18.04 Boot hangs at PKCS#7 signature not signed with a trusted key I had a working 16.04 working perfectly (but no bumblebee) and then upgraded to 18.04. Gnome was very laggy so I installed Unity and lightdm but it was still laggy. So I thought something was wrong with video drivers. So I purged nvidia and installed nvidia-driver-390, but I also tried to install bumblebee.
Then I reboot and startup stops with a PKCS#7 signature not signed error. I got into recovery console and removed nvidia-driver-390, but I'm still getting that same error. Had trouble enabling networking, as it would just hang and not return to recovery menu.
Any ideas what's wrong and how I can fix it? I'm thinking about running Nvidia binary installs but my home directory was encrypted and I had to give up last night. Anything else I can do?


text:
Q: Variable not posting to what i believe is dynamic image? I have a very simple port check that i wish to post online/offline status's to what i believe is a dynamic image. Well it don't give me and error or nothing if it's online but it does not post offline or offline it post Resource id #1 Here's my code:
<?php
$ip      = $_GET["ip"];
$port    = $_GET["port"];
$online  = "Online";
$offline = "Offline";

$status = (fsockopen($ip, $port));
if ($status) {
    $online;
} else {
    $offline;
}

// Create a blank image and add some text
$im         = imagecreatetruecolor(215, 86);
$text_color = imagecolorallocate($im, 233, 14, 91);

// sets background to Light Blue
$LightBlue = imagecolorallocate($im, 95, 172, 230);
imagefill($im, 0, 0, $LightBlue);

//Server Information
imagestring($im, 7, 5, 5, '3Nerds1Site.com', $text_color);
imagestring($im, 2, 40, 30, $ip, $text_color);
imagestring($im, 2, 40, 40, $port, $text_color);
imagestring($im, 2, 40, 70, $status, $text_color);

// Set the content type header - in this case image/jpeg
header('Content-Type: image/png');

// Output the image
imagepng($im);

// Free up memory
imagedestroy($im);
?>

Can anyone give me helpful info about this?
Here is also my output:

A: This is meaningless:
$status = (fsockopen($ip, $port));
if ($status) {
    $online;
} else {
    $offline;
}

It is also the cause of the problem, because $status will never be something printable (the lines inside the conditionals do not change its value at all). It will either be false (in which case you will see nothing where you expect "offline") or a resource (in which case you will see something like "Resource id #1").
Replace all of the above code with
$status = fsockopen($ip, $port) ? $online : $offline;

A: Change
if ($status) {
    $online;
} else {
    $offline;
}

to
if ($status) {
    $status = $online;
} else {
    $status = $offline;
}

Just having $online in an if-block doesn't do anything by itself. You have to do something with it; that is, assign it to a variable to output later.

A: You are printing $status into the image which is the result of an fsockopen() call and not the string you specified at the top. Try this:
$status = (fsockopen($ip, $port));
if ($status) {
    $status = $online;
} else {
    $status = $offline;
}


text:
Q: odoo V8 coding error when load file, store it in a binary field and then try to parse it I have the transient object:
class new_import(models.TransientModel):
     _name = 'new.import'
     data_file = fields.Binary('File')

I call a wizard to load the file in the binary field and then i want to parse it.
In the function to parse the file i do:
data_file = base64.b64decode(self.data_file)
lines = data_file.split('\n')
for line in lines:
    result = line[6:11]

but when i read the lines if there is a special character the length of the line isn't the same in all lines,
the file is utf8 in the origin
this must be an error when save the file in binary and then decode back to string
If i read the file directly with python with out store it in a binary field i can read it correctly:
codecs.open(file, mode='r', encoding='utf-8')
result = line[6:11].encode('utf-8')

How can i avoid storing the file in base64 or how can i after decode correctly to string?
Thanks in advance


text:
Q: WP All Import plugins configuration for inserting posts? Good day. I'm having a csv file with the structure like this:
ID           ArticleID       Title      Content         LanguageID    LanguageCode       Createdby       DateCreated       DateModified

Since a post is translated into 2 languages, articleID will be repeated for 2 rows with title and content in different language : e.g
   ID           ArticleID       Title               Content         LanguageID    LanguageCode       Createdby       DateCreated       DateModified
    1              2            Adobe Patches       Adobe System...   0
    2              2           patchs adobe         système adobe...  1

How can I import each record for two languages? If I choose the key value for the plugin to be the articleID, it overrides all the content.

A: Are you using a plugin to handle the translations, such as qTranslate?
If not, personally this is how I would do it (assuming these are WordPress Posts you're adding):

*

*Create a meta box in your Posts section with the same main fields, but for the different language.  If you're unfamiliar with how to do this, Advanced Custom Fields will probably be the plugin you would need, since WP ALL Import works great with ACF.   Toolset is also easy to use if you don't like ACF.

*Modify/Create a new import, and set it to modify ONLY the new Meta box fields for the second language.
That way you'll have all the post data in one place, and the import will work simply.  For reference, you can either have two imports, one for each language, or set WP All Import to handle the filtering (which is more advanced).
Hope that makes sense to you.


text:
Q: Timeline, event listeners, cleanup If I have a button on the timeline for the first few frames, but then I remove it...
Do I have to worry about removing the event listener for the button (MovieClip) if the button has be removed from the stage?
I'm writing a Document Class even though I'm using objects on the timeline.

A: You could use the removedFromStage event to clear up any event listeners on your button instance:
package
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public class Button extends MovieClip
    {
        public function Button():void
        {
            addListeners();
        }

        private function addListeners():void
        {
            this.addEventListener(Event.ADDED_TO_STAGE, addedHandler);
            this.addEventListener(Event.REMOVED_FROM_STAGE, removedHandler);
            this.addEventListener(MouseEvent.CLICK, clickHandler);
        }

        private function addedHandler(event:Event):void
        {
            trace("button added");
        }

        private function removedHandler(event:Event):void
        {
            trace("button removed");
            removeListeners();
        }

        private function clickHandler(event:MouseEvent):void
        {
            trace("button clicked");
        }

        private function removeListeners():void
        {
            this.removeEventListener(Event.ADDED_TO_STAGE, addedHandler);
            this.removeEventListener(Event.REMOVED_FROM_STAGE, removedHandler);
            this.removeEventListener(MouseEvent.CLICK, clickHandler);

            trace("has added listener: " + this.hasEventListener(Event.ADDED_TO_STAGE));
            trace("has removed listener: " + this.hasEventListener(Event.REMOVED_FROM_STAGE));
            trace("has click listener: " + this.hasEventListener(MouseEvent.CLICK));
        }
    }
}


text:
Q: Mobile programming: how secure is SMS I am currently developing a web service that is configured to receive SMS text messages from different cell phones. Along with each message I also get the mobile number from which the SMS originated.
My question is it possible for someone to masquerade as a different phone number. That is it possible to send a SMS from phone (or other means) and make it look as if it came from a particular number?
I have read of SMS spoofing where it is possible to receive SMS intended for other numbers but I want to know if it is possible to send posing as someone else (send from phone or a web app etc).

A: Spoofing is pretty trivial with the right setup. For example, we send large numbers of SMS using a 3rd-party aggregator service, and each SMS has an "originator" field, which can be a phone number (specifically, a MSISDN), or a text value. We could, if we wanted, put anyone's number in there.
SMS is extremely insecure. It was designed as a back-channel for GSM engineers to test their networks, and turned out to be a nice revenue spinner, so they just left it as it is.
That's not to say you shouldn't send sensitive information over SMS, just be aware of the insecurity, and trust (or don't trust) messages accordingly. No channel is 100% secure, you need to decide if it's secure enough for what you want to send over it.

A: As I can send via GMX Webinterface - with my Phone number as Sender, I conclude that it is indeed possible.


text:
Q: Lumen 5.4 Auth viaRequest $request-input returning null For whatever reason, my AuthServiceProvider has stopped working. It looks like the $request parameter being passed to the closure for viaRequest is not seeing the request input. If I send JSON with a key of "access_token" to any of my endpoints and try and var_dump it in the closure - it only returns null. Here is the code for the boot method:
public function boot()
{
    $this->app['auth']->viaRequest('api', function ($request) {
        var_dump($request->input('access_token'));
    });
}

And here is my auth middlewares handle method:
public function handle($request, Closure $next, $guard = null)
{
    if ($this->auth->guard($guard)->guest()) {
        return response('Unauthorized.', 401);
    }

    return $next($request);
}

Any help is greatly appreciated since I am pulling my hair out right now.
EDIT Looks like the issue is with Sentry and their user_context setting be set to true. As soon as I set it to false, the requests come through perfectly

A: Issue turned out to be Sentry's user_context setting being set to true. Setting it to false fixed the issue.


text:
Q: Formatting a date like 2013-11-01T08:50:43.305Z Maybe a trivial question but I can't seem to figure this out. I need to format a date like 2013-11-01T08:50:43.305Z in PHP. I'm not sure how to add .305Z-part in the formatting. I've been looking at the docs (php's date-function documentation) but I must have overread it there... Any help is appreciated.

A: use this:
echo date("c");

For more reference see here: http://php.net/manual/en/function.date.php
Or you can use this format:
echo date("Y-m-dh:i:sz");

Here Z means the number of day in the current year.


text:
Q: Атомарные переменные в си Пишу под микроконтроллер в первый раз и так и не нагуглил такой вопрос.
Например, понятно что доступ к int_32 может быть атомарным на 32 битной машине, но на 16 битной скорее всего уже будет не атомарным. Но логика подсказывает, что меньше байта считать точно нельзя (по крайней мере я о таком никогда не слышал) и в теории volatile char может обеспечить эту самую атомарность.
Так ли это? Конечно я понимаю, что стандарт си ничего не говорит за это и в теории может быть какой нибудь 4х битный процессор, в котором даже char не атомарен. Но на практике, могу ли я использовать char в качестве, скажем, флага синхронизации между прерыванием и функции main?

A: Стандарт Си ни о какой атомарности ничего не знает, volatile не про это, тут же вам не Ява какая-нибудь. Все что вы описали это строго аппаратно зависимые вещи. Более того, нередко производитель вычислителя еще и свой компилятор поставляет, который тоже свою специфику и отклонения имеет. Все подобные вопросы только к производителю.
Вообще, аппаратная кроссплатформа это одна сплошная боль, более разумно писать отдельно под каждый камень.


text:
Q: Series about mutants and humans living and fighting around Richmond, VA As a teenager, I read a set of Scifi novels about mutants and humans that rode horses in and around Richmond, VA. I remember that they fought using swords and such. I also seem to remember some reference to a Sea of Grass.
Anyone remember the author/name of the series?

A: I'll take a stab at the Horseclans novels by Robert Adams
Wikipedia

The books mainly concern the doings of the "Horseclans", a nomadic people originating from the "Sea of Grass" —the Great Plains from present-day southern Canada to central Texas, and from the Mississippi River to the Rocky Mountains, post-apocalyptically. The Horseclansmen were portrayed as fierce, noble and often gifted with telepathy, which came in handy for their dealings with their horses and "cats"—sabertoothed tigers that had been revived by scientific means in the years before the nuclear war.


text:
Q: Tkinter: cannnot create messagebox in a thread I'm a beginner at Tkinter.
Yesterday, when I try to start a message box in a thread function, but it failed and stuck. I didn't find any useful information about this problem, so I asked here:
from tkinter import *
from threading import Thread

def func():
    messagebox.askyesno()

t = Thread(target=func)

Label(text='Hello').pack()

t.start()
mainloop()

No error. it just doesn't work. I also find that any dialog can not be created in the thread procedure.
Thanks for any help, or useful information.

A: You cannot call a tkinter widget method from any thread other than the one it was created in, and you can only ever create widgets in a single thread.


text:
Q: VBA: reading Excel range into an object array How do I read an Excel range into an object array?
To clarify, for this Excel range of 6 cells...
John    Roberts    56
Sam     Alito      52

and this class...
Class supremes
Public firstName
Public lastName
Public age
Dim supreme As New supremes

I'd like to read the Excel range into an array of supreme such that:
arr(1).firstName = "John"
arr(2).age = 52

For a standard array, this is done with a single assignment...
arr = range("supremes")

Is there a similar command to populate the object array?

A: There isn't any special way to read data into an array object. You just need to roll your own code.
dim i as long
dim rData as range
dim vData as variant

set rData=selection

vData=rData

for i=1 to ubound(vdata)
  arr(i).FirstName=vdata(i,1)
  arr(i).LastName=vdata(i,2)
  arr(i).Age=vdata(i,3)
next i


text:
Q: env with variable setting and python is stuck Not sure why but:
   /usr/bin/env IPYTHONDIR=/tmp/.ipython python

when running from command line works fine. But stuck as a shabang line:
   #!/usr/bin/env IPYTHONDIR=/tmp/.ipython python

Environment:
Debian 7.8 x86
Anybody has ideas why?

A: Unfortunately, #! passes IPYTHONDIR=/tmp/.ipython python as a single parameter to /usr/bin/env.
One thing I have used as a workaround is to have another script that sets up variables and then invokes my real program.  It is silly.
Here is some more information:
How to use multiple arguments with a shebang (i.e. #!)?


text:
Q: Edit M13checkbox in swift I need help with using this customizeable checkbox: https://github.com/Marxon13/M13Checkbox I have already linked m13checkbox.h and .m classes and wrote import in bridge-header file, but i don't know how to create checkbox on my tableview and manipulate it.
I need to place checkbox in every cell by my own UITableCell class.
UPD.
I have done with adding checkbox in cell, but now i need to control it in addiction by my data in UITableViewController. I need to set checkbox to checked/unchecked state depending on my dataArray. I also need to set label for every checkbox from dataArray


text:
Q: ASP.NET Core MVC Product Database with Multiple Prices I am upgrading one of my sites from WebForms to MVC Core. Would you please give me some advice on how to create their database? Here is some example code from the .VB file behind the Rabbit Bikes Products page. It is VERY messy because a lot of their products have two or more prices.
For Each prod As Product In myProducts
        'Beginning Layout
        temp &= "

"

        temp &= "
"
        temp &= "
" & prod.Name & "
"
        temp &= "

" & prod.Description & "

"
        If Not prod.Description.Contains("shuttle") And Not prod.Name = "Trail Pass" Then
            temp &= "
Call to reserve yours today!
"
        Else
            temp &= "
Call to purchase one today!
"
        End If
        temp &= "

"
        If prod.Description.Contains("shuttle") Or prod.Description.Contains("frequent rider") Then
            temp &= "One Person: " & prod.TwoHrPrice.ToString("c") & "
"
            temp &= "2 or More ppl.: " & prod.FourHrPrice.ToString("c") & "
"
        End If
        If prod.TwoHrPrice = 0 And Not prod.Description.Contains("shuttle") Then
            temp &= "
Free with purchase!
"
        End If
        If prod.FourHrPrice <> 0 And Not prod.Description.Contains("shuttle") And Not prod.Description.Contains("frequent rider") Then
            temp &= "
Half Day Price: " & prod.FourHrPrice.ToString("c") & "
"
        End If
        If prod.OneDayPrice <> 0 And Not prod.Description.Contains("shuttle") Then
            temp &= "One Day Price: " & prod.OneDayPrice.ToString("c") & "
"
        End If
        If prod.TwoDayPrice <> 0 And Not prod.Description.Contains("shuttle") Then
            temp &= "Two Day Price: " & prod.TwoDayPrice.ToString("c") & "
"
        End If
        If prod.WeekPrice <> 0 And Not prod.Description.Contains("shuttle") Then
            temp &= "Week Price: " & prod.WeekPrice.ToString("c") & "
"
        End If

        'End Layout
        temp &= "

"
    Next

Since switching to ASP.NET Core 1.1 and the Entity Framework, I've been trying to figure out how to check the number of prices for each item and labeling them appropriately. I tried using arrays, but they won't work because each variable type in an Entity Framework Model class is connected to a SQL Server data type. I don't want to use a bunch of if/else statements to count how many prices are associated with each product and label them appropriately again. My Product class isn't that different from the one in ASP.NET MVC with Entity Framework and CSS.
public class Product
{
    public int ID { get; set; }
    public string Image { get; set; }
    [Display(Name = "Product Name")]
    public string Name { get; set; }
    public string Description { get; set; }
    public string PriceLabels { get; set; }
    public decimal Prices { get; set; }
    //Add a third table to hold price information?
    //public int? PriceTableID { get; set; }
    public int? CategoryID { get; set; }
    [Display(Name = "Category Name")]
    public virtual Category Category { get; set; }
}

I would appreciate any insight you might have about this issue.

A: What is your question exactly?  Generic "advice" is off topic here.  You should ask a specific question to get specific answers.  If your question is how you count prices, you simply do a query and use the count method linq.  for instance, assuming your database context is called db, and your products table is Products.
var count = db.Products.Where(x => x.ProductId == yourproductid).Count();

In this scenario, you would have multiple entries for each product/price combination.  Another option would be to create a one-to-many of product to prices, and then you would query the prices separately.
This is really basic Linq functionality, and you seem to be very inexperienced, so I suggest reading some tutorials on entity framework.  EntityFramework core is quite a bit different in specifics, but generally works the same as far as queries are concerned as traditional entity framework.


text:
Q: Issue formatting XMLGregorianCalendar - IllegalArgumentException I am trying to format XMLGregorianCalendar using SimpleDateFormat. It works for "yyyy-MM-dd" but does not work for "MM-dd-yyyy". What should I do to format it in "MM-dd-yyyy"
This one works :
public static XMLGregorianCalendar convertToXMLGregorianCalendar(Date date)  {
    DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    try {
        return DatatypeFactory.newInstance().newXMLGregorianCalendar(simpleDateFormat.format(date));
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }
    return null;
}

But this one throws IllegalArgumentException:
public static XMLGregorianCalendar convertToXMLGregorianCalendar(Date date)  {
    DateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");
    try {
        return DatatypeFactory.newInstance().newXMLGregorianCalendar(simpleDateFormat.format(date));
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }
    return null;
}

The error log:
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:66)
Caused by: java.lang.IllegalArgumentException: 08-05-2021
    at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl$Parser.parseYear(XMLGregorianCalendarImpl.java:2910)
    at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl$Parser.parse(XMLGregorianCalendarImpl.java:2801)
    at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.<init>(XMLGregorianCalendarImpl.java:455)
    at com.sun.org.apache.xerces.internal.jaxp.datatype.DatatypeFactoryImpl.newXMLGregorianCalendar(DatatypeFactoryImpl.java:537)
    at com.usbank.mmc.transformation.pain002.utils.DateUtils.convertToXMLGregorianCalendar(DateUtils.java:16)
    at com.usbank.mmc.transformation.pain002.utils.DateUtils.main(DateUtils.java:24)
    ... 5 more

My Complete program
public final class DateUtils {

    public static XMLGregorianCalendar convertToXMLGregorianCalendar(Date date)  {
        DateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");
        try {
            return DatatypeFactory.newInstance().newXMLGregorianCalendar(simpleDateFormat.format(date));
        } catch (DatatypeConfigurationException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(DateUtils.convertToXMLGregorianCalendar(new Date()));
    }
}

A: Do not use String to convert from Date to XMLGregorianCalendar, instead, use:
public static XMLGregorianCalendar convertToXMLGregorianCalendar(Date date) throws DatatypeConfigurationException {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(new Date());
    return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
}

on the other hand, you can set empty certain fields, the closest to your question is
XMLGregorianCalendar xdate = convertToXMLGregorianCalendar(new Date());
System.out.println(xdate.toXMLFormat());

// NOT all combinations are implemented!
xdate.setYear(DatatypeConstants.FIELD_UNDEFINED);
xdate.setHour(DatatypeConstants.FIELD_UNDEFINED);
xdate.setMinute(DatatypeConstants.FIELD_UNDEFINED);
xdate.setSecond(DatatypeConstants.FIELD_UNDEFINED);
System.out.println(xdate.toXMLFormat());

with output
2021-08-05T16:51:35.642+02:00
--08-05+02:00

see the getXMLSchemaType implementation.


text:
Q: Setting Value of Previous Context [REACT] First of all let me apologize if my question does not make any sense but I am facing a very simple problem.
I am using context api from React. I am wrapping my App.js with the context provider let us Call it context1. Now in the deep I am using another context let us call it context2 and I am wrapping another component let us call it ComponentA with this context provider. Now from a component let us call it ComponentB which is the child of ComponentA I am accessing the values of context2. Now from ComponentB I want to access the value of Context1. Please let me know if it is possible. There is a bounding that I cannot change the context name. Both of my context have same name. Thankyou for your help and sorry again if my question does not make sense as I am new in React.
Edit
I am trying to make a Routing Library for React. I am using context Api for this purpose. Now I want to implement a functionality that from any component user can navigate to any path. I am using a Browser component to wrap my App.js in this Browser Component I am creating context. I am using the same Browser component to wrap my child components and from any Child component I want to access the context of App.js Browser component. If still it does not make sense please review my code on github. thanks
https://github.com/khuramhaf/Non-Polling-React-Routing

A: Welcome to StackOverflow. The general practice here is to include Minimal Reproductible Example into the question so others could get a better grip of the problem.
In your app, you are using Browser context multiple times, essentially overriding it. Therefore the thing you are describing is not possible in React
Following Official React Documentation:

Providers can be nested to override values deeper within the tree.


text:
Q: Is there a sql command I can use to manually start replication? The title pretty much says it all. I need a command or a script that will manually kick off SQL Server 2012 replication if it is beyond the time it scheduled to start but hasn't yet.
Is there such a thing?

A: Sample
-Publisher [ServerName] -PublisherDB [DatabaseName] -Distributor [ServerName] -Publication [PublicationName] -DistributorSecurityMode 1


text:
Q: Python vlc install problems alright so i am trying to install vlc with pip and its telling me successfully installed python-vlc ok good that's what i wanted but when i go to run the program im trying to use vlc in witch is here
import vlc
p = vlc.MediaPlayer("https://www.youtube.com/watch?v=jC1vtG3oyqg")
p.play()

i am told this
Traceback (most recent call last):
  File "C:\Users\Matt\Desktop\test2.py", line 1, in <module>
    import vlc
  File "C:\Python27\lib\site-packages\vlc.py", line 173, in <module>
    dll, plugin_path  = find_lib()
  File "C:\Python27\lib\site-packages\vlc.py", line 150, in find_lib
    dll = ctypes.CDLL('libvlc.dll')
  File "C:\Python27\lib\ctypes\__init__.py", line 365, in __init__
    self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] The specified module could not be found

im not sure what i am suppose to do since there are errors in the vlc program (  i think ) if you could help me out and get this working for me that would be amazing thank you so much!!

A: Your problem is that libvlc.dll is not in the PATH. There is 2 ways to correct that.
First (temporary):
set PATH=%PATH%;<path to your dll folder>

As explained in the second answer of this post:  Adding directory to PATH Environment Variable in Windows
Second (Forever):
This solution makes the variable stay in the path for every reboot of your machine but you need root privilege. As before you need to put the way to your dll folder in the Path variable as explained on this site. (It depends from your system version): https://www.computerhope.com/issues/ch000549.htm
Other problem that may occur
Oftenly, people download 32bits vlc's version. This may cause some trouble if you installed the 64 bits version of python. (Windows Error [193]). To fix that, you just need to reinstall the 64 bits vlc's version.

A: I had similar question. Here is my solution:
First I checked the code in the file __init__.py. Print some variables like self._name and mode to make sure the values are correct. And I looked up the function _dlopen, which is LoadLibrary from _ctypes, and found out the mode argument is optional. So I try to modified the file without breaking the structure of whole file. Here is the code:
the original codes are:
if handle is None:
    self._handle = _dlopen(self._name, mode)
else:
    self._handle = handle

I modified the codes as below:
if handle is None:
    if 'libvlc' not in self._name:
        self._handle = _dlopen(self._name, mode)
    else:  # libvlc.dll will hit
        self._handle = _dlopen(self._name)
else:
    self._handle = handle

And it worked for me. Hope this solution can help people with the same problem.

A: I changed my vlc player from 32 bit to 64 and it worked. Just download 64-bit version of vlc player and install it. The write
import vlc

It will work

A: Installing through pip does not install vlc itself, only the python wrapper for the libvlc bindings. To use them, you need to have a working VLC install. Please fetch VLC from www.videolan.org


text:
Q: TextView drawableStart wrap_content doesn't work well I want to display a textview with a compound drawable which wraps the content - the shape and the text. Here is my code:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text_category_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:drawableStart="@drawable/shape_circle"
android:drawablePadding="10dp"
android:padding="10dp"
android:textSize="16sp" />

drawableLeft works fine, it wraps the shape and and text, no problem. But drawableStart (and so I assume drawableEnd) seems to wrap the text, THEN add the image, and as such trim the text, so it looks like this:

I've tried removing the drawablePadding, padding, layout_marginStart - these don't have an effect on the text still being trimmed.
Is there a non-hacky way to fix this? I don't want to have to set a specific width, and I do want to use drawableStart and not drawableLeft if possible. I've had a look for existing answers, and all I can find so far is that it is a quirk of the RTL nature of drawableStart/End, but I can't see a clean solution.


text:
Q: Issue with consumer config 'session.timeout.ms' while processing long processing records I'm using spring-kafka '2.1.7.RELEASE' and here are my consumer settings.
    public Map<String, Object> setConsumerConfigs() {

           Map<String, Object> configs = = new HashMap<>();

           configs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
           configs.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");

           configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer2.class);
           configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer2.class);

           configs.put(ErrorHandlingDeserializer2.KEY_DESERIALIZER_CLASS, stringDeserializerClass);
           configs.put(ErrorHandlingDeserializer2.VALUE_DESERIALIZER_CLASS, kafkaAvroDeserializerClass.getName());

           configs.setPartitionAssignmentStrategyConfig(Collections.singletonList(RoundRobinAssignor.class));

           // Set this to true so that you will have consumer record value coming as your pre-defined contract instead of a generic record
           sapphireKafkaConsumerConfig.setSpecificAvroReader("true");
       }

and here are my factory settings
        @Bean
         public <K,V> ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
           ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
           factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(getConsumerConfigs));
           factory.getContainerProperties().setMissingTopicsFatal(false);

           factory.getContainerProperties().setAckMode(AckMode.RECORD);

           factory.setErrorHandler(myCustomKafkaSeekToCurrentErrorHandler);
           factory.setRetryTemplate(retryTemplate());
           factory.setRecoveryCallback(myCustomKafkaRecoveryCallback);
           factory.setStatefulRetry(true);
           return factory;
         }

         public RetryTemplate retryTemplate() {
            RetryTemplate retryTemplate = new RetryTemplate();
            retryTemplate.setListeners(new RetryListener[]{myCustomKafkaRetryListener});
            retryTemplate.setRetryPolicy(myCustomKafkaConsumerRetryPolicy);

            FixedBackOffPolicy backOff = new FixedBackOffPolicy();
            backOff.setBackOffPeriod(1000);
            retryTemplate.setBackOffPolicy(backOff);

            return retryTemplate;
          }

Here is my consumer where I've added a delay of 6 minutes which is greater than the default max.poll.interval.ms
@KafkaListener(topics = TestConsumerConstants.CONSUMER_LONGRUNNING_RECORDS_PROCESSSING_TEST_TOPIC
      , clientIdPrefix = "CONSUMER_LONGRUNNING_RECORDS_PROCESSSING"
      , groupId = "kafka-lib-comp-test-consumers")
  public void consumeLongRunningRecord(ConsumerRecord message) throws InterruptedException {
    System.out.println(String.format("\n \n Received message at %s offset %s of partition %s of topic %s with key %s \n\n", DateTime.now(),
        message.offset(), message.partition(), message.topic(), message.key()));

    TimeUnit.MINUTES.sleep(6);

    System.out.println(String.format("\n \n Processing done for the message at %s offset %s of partition %s of topic %s with key %s \n\n", DateTime.now(),
        message.offset(), message.partition(), message.topic(), message.key()));
  }

Now I'm getting below error and trying to process the same record again and again because it couldn't commit the offset (which is expected).
Caused by: org.apache.kafka.clients.consumer.CommitFailedException: Commit cannot be completed since the group has already rebalanced and assigned the partitions to another member. This means that the time between subsequent calls to poll() was longer than the configured max.poll.interval.ms, which typically implies that the poll loop is spending too much time message processing. You can address this either by increasing the session timeout or by reducing the maximum size of batches returned in poll() with max.poll.records.

And now, i tried with setting the 'session.timeout.ms' = 420000. Now I'm getting below error but I didn't set any values for group.min.session.timeout.ms and group.max.session.timeout.ms. And the the default values for group.min.session.timeout.ms and group.max.session.timeout.ms are 6000 and 1800000 respectively.So,  Can someone help me understand why am i getting this error?
Caused by: org.apache.kafka.common.errors.InvalidSessionTimeoutException: The session timeout is not within the range allowed by the broker (as configured by group.min.session.timeout.ms and group.max.session.timeout.ms).

A: I don't know why you are getting that error, but session timeout is no longer relevant; see KIP-62. Maybe the defaults have been changed and the docs not updated.
You need to increase max.poll.interval.ms to avoid the rebalance.


text:
Q: Snapshot from old baseline Can I create a snapshot view with an old baseline without creating a new stream from the source stream?   I have been creating a child stream and pointing it to the old baseline; then making a snapshot of the newly created stream with the old baseline.
Not really a big deal just curious if there is another way

A: If the baseline is a full baseline, then yes, you can create a base snapshot view with a config spec like:
 element * CHECKEDOUT
 element /Vob/Component/... YourBaselineId
 element * /main/0

See "What is the difference between Full baseline and Incremental baseline in Clearcase UCM?" to know more about the importance of using a full baseline for base ClearCase views.
Otherwise, your method (sub-stream, rebase, mkview) is the standard one, creating an UCM view based on the configuration of the sub-stream.


text:
Q: How to take inputs from array and input it into an equation in C++? My goal is to try and create a program that takes in grades in percents and multiply it with their weight value (either in decimal form or percent form). The equation is basically:
Overall grade = (grade1*weightInDecimal1)+(grade2*weightInDecimal2)+(grade3*weightInDecimal3)+...
or
Overall grade = (grade1*weight%1)+(grade2*weight%2)+(grade3*weight%3)+...

Is there a way to store the inputs and then recall it later in the code? Or possibly a more efficient way?
I also want to try and make a dynamic array. I want to make a program that asks the user for how many assignments they have and makes an array based on that. That way it's not stuck at 4 assignments
#include <string>
#include <iostream>
using namespace std;
int main() {
    int numbers[4][2];
    for(int i=0;i<4;i++)
    {
       cout<<"Grade #"<<i<<endl;
       cin>>numbers[i][0];
       cout<<"Weight for grade #"<<i<<":"<<endl;
       cin>>numbers[i][1];
    }

    for (int i = 0; i<4; i++)
    {
        cout << "|" << numbers[i][0]*numbers[i][1]<< "|";
    }
    system ("PAUSE");
return 0;
}

A: This is what structs are for
#include <string>
#include <iostream>
#include <array>
using namespace std;

struct entry {
    int grade;
    int weight;
    int gradeWeight; //grade*weight
};

int main() {
    array<entry,4> numbers;
    for(int i=0;i<numbers.max_size();i++)
    {
       cout<<"Grade #"<<i<<endl;
       cin>>numbers[i].grade;
       cout<<"Weight for grade #"<<i<<":"<<endl;
       cin>>numbers[i].weight;
    }

    for (int i = 0; i<numbers.max_size(); i++)
    {
        numbers[i].gradeWeight = numbers[i].grade*numbers[i].weight;
        cout << "|" << numbers[i].gradeWeight << "|";
    }
    system ("PAUSE");
    return 0;
}

This way you can also increase the amount of numbers by just increasing the array size.

A: There are many reasons to avoid using arrays (dynamic or otherwise).  See for example Stroustrup's FAQ entry What's wrong with arrays?  As Greg suggests in the comments you will most likely write better quality code if you use a container like std::vector.
If you can calculate or input the size of your container before allocating it you can (if you wish) pass that size to the constructor ...
auto syze{ 0 };
auto initialValue{ 0 };

// calculate or input syze
. . .

// dynamically allocate an "array"
// of ints and an "array" of floats
std::vector<int> grades(syze, initialValue);
std::vector<float> weights(syze, initialValue);

On the other hand if you prefer to use a container that dynamically grows to hold data as it arrives you can do that too...
// dynamically allocate an empty "array"
// of ints and an empty "array" of floats
std::vector<int> grades;
std::vector<float> weights;

while (...condition...)
{
    std::cin >> g;   // input a grade ...
    std::cin >> w;   // ... and a weight

    // grow the containers by adding
    // one item at the end of each
    grades.emplace_back(g);
    weights.emplace_back(w);
}

Update
I should have pointed out how to calculate the result from the two vectors.  You can calculate your overall grade with just one more line of code by using std::inner_product from the STL's <numeric> header.  Note that in the code below the last argument is 0.0 (rather than just 0) so that std::inner_product returns a double rather than an int.  That avoids any risk of float values being truncated to int (and avoids some pretty ugly warnings from the compiler).
auto overallGrade = std::inner_product(grades.begin(), grades.end(), weights.begin(), 0.0);

A: As pointed by others, if you ask the user for how many assignments they have, std::array is a wrong container because it's dimension is fixed at compile time.
As others, I discurage the use of direct memory allocation but the use of std::vector to manage it.
I just suggest the use of reserve() (method of std::vector), when you know how many assignments.
The following is a full example using, instead a couple of std::vector of int, a single std::vector of std::pair<int, int>
#include <utility>
#include <vector>
#include <iostream>

int main()
 {
   int                              valG, valW;
   std::size_t                      dim;
   std::vector<std::pair<int, int>> vec;

   std::cout << "How many grade/weight couples? ";
   std::cin  >> dim;

   vec.reserve(dim);

   for ( auto i = 0U ; i < dim ; ++i )
    {
      std::cout << "Grade #" << i << "? " << std::endl;
      std::cin  >> valG;
      std::cout << "Weight for grade #" << i << "? " << std::endl;
      std::cin  >> valW;

      vec.emplace_back(valG, valW);
    }

    for ( auto const & p : vec )
       std::cout << '|' << (p.first * p.second) << '|';

    std::cout << std::endl;

    return 0;
 }


text:
Q: Matrix computation without for loop I am trying to get faster computation for a piece of code and want to get rid of the for loop. I have three vectors roll, pitch and heading. I have to get the rotation matrix for each value of roll,pitch and heading. Right now, my code is
for i=1:size(roll,1)
    R1_r = [1 0 0; 0 cos(roll(i)) -sin(roll(i)); 0 sin(roll(i)) cos(roll(i))];
    R2_p = [cos(pitch(i)) 0 sin(pitch(i)); 0 1 0; -sin(pitch(i)) 0 cos(pitch(i))];
    R3_h = [cos(head(i)) sin(head(i)) 0; -sin(head(i)) cos(head(i)) 0; 0 0 1];
    R = R3_h*R2_p*R1_r;
    x1(i,2:4) = (R*x(i,2:4)')';
end

I want to replace the entire for loop. Is there a way to do that?

A: The following code will expand the last product for you:
syms roll pitch yaw x1 x2 x3

R1 = [1 0 0; 0 cos(roll) -sin(roll); 0 sin(roll) cos(roll)];
R2 = [cos(pitch) 0 sin(pitch); 0 1 0; -sin(pitch) 0 cos(pitch)];
R3 = [cos(yaw) sin(yaw) 0; -sin(yaw) cos(yaw) 0; 0 0 1];
R  = R3*R2*R1;
x  = [x1;x2;x3];

R*x

output:
 x2*(cos(roll)*sin(yaw) + cos(yaw)*sin(pitch)*sin(roll)) - x3*(sin(roll)*sin(yaw) - cos(roll)*cos(yaw)*sin(pitch)) + x1*cos(pitch)*cos(yaw)
 x2*(cos(roll)*cos(yaw) - sin(pitch)*sin(roll)*sin(yaw)) - x3*(cos(yaw)*sin(roll) + cos(roll)*sin(pitch)*sin(yaw)) - x1*cos(pitch)*sin(yaw)
                                                                          x3*cos(pitch)*cos(roll) - x1*sin(pitch) + x2*cos(pitch)*sin(roll)

Based on this, you should take the sines and cosines of your angles:
cp = cos(pitch); sp = sin(pitch);
cr = cos(roll);  sr = sin(roll);
cy = cos(yaw);   sy = sin(yaw);

and replace x1 -> x1(:,2), x2 -> x1(:,3) and x3 -> x1(:,4) in the above formula, changing the * signs with .* where needed.
The final code should look like this:
x1_new = x1(:,3).*(cr.*sy + cy.*sp.*sr) - x1(:,4).*(sr.*sy - cr.*cy.*sp) + x1(:,2).*cp.*cy;
x2_new = x1(:,3).*(cr.*cy - sp.*sr.*sy) - x1(:,4).*(cy.*sr + cr.*sp.*sy) - x1(:,2).*cp.*sy;
x3_new = x1(:,4).*cp.*cr - x1(:,2).*sp + x1(:,3).*cp.*sr;

Be careful not to replace the columns of x1 as you go; you need to store the results in new columns, otherwise you will corrupt the rest of the calculation. After these three lines you can replace safely the columns of x1.


text:
Q: Rails before_save callback In a before_save callback in the model:
self.field2 = self.field1
self.field2['word'] = 'something'

I would expect field1 and field2 not to be the same after save, but they are -- field1 becomes same as field2.
Do you know why?

Anwser
self.field2 = self.field1.clone

A: First, you assign self.field1 to self.field2. They now point to the same object. Then with
self.field2['word'] = 'something'

You modify the object they both point to.
If you want to copy field1 into field2, try something like self.field2 = self.field1.clone instead.


text:
Q: Linking OTF font with CSS I'm building a site locally and trying to link an OTF typeface on my site but I can't seem to get it to display in the browser. After inspecting the console, I can see that the fonts aren't being found, though I'm linking to the file path correctly.
Any help would be appreciated.

@font-face {
   font-family: ObjectSans;
   src: url("assets/fonts/ObjectSans-Heavy.otf") format("opentype");
   font-weight: bold;
}

@font-face {
   font-family: ObjectSans;
   src: url("assets/fonts/ObjectSans-Regular.otf") format("opentype");
   font-weight: normal;
}

h1 {
   font-family: ObjectSans;
   font-size: 3.8rem;
   font-weight: bold;
}

h2 {
   font-family: ObjectSans;
   font-size:2.4rem;
   font-weight: bold;
}

body {
   font-family: ObjectSans;
   font-weight: normal;
   font-size: 2rem;
   color: #FFF;
   background: rgb(0,0,0);
   background: linear-gradient(0deg, rgba(0,0,0,1) 0%, rgba(11,11,11,1) 50%, rgba(15,15,15,1) 100%);
   background-repeat: no-repeat;
   height: 100%;
   background-attachment: fixed;
}


text:
Q: How to add events in javascript fullCalendar I am trying this library for the first time
want to set events to my calendar, but instead of doing this:
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
    initialView: 'dayGridMonth',

    titleFormat:{
        year: 'numeric',
        month: 'short'
    },

    events: [{
        title: "February Outing",
        start: "2021-02-19",
        end: "2021-02-21"
    }]
});

calendar.render();

I Want to do it like this for some reason
    var calendarEl = document.getElementById('calendar');
    var calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',

        titleFormat:{
            year: 'numeric',
            month: 'short'
        },
   });

let myEvents = [
    {
        title: "February Outing",
        start: "2021-02-19",
        end: "2021-02-21"
    }
]

calendar.events = myEvents
calendar.render();

but it doesn't work
Thank you in advance:)

A: Use Calendar::addEvent. You can set events from your array myEvents as follows:
myEvents.forEach(event => calendar.addEvent(event))

A: Please use calendar.addEvent( event [, source ] ). Kindly refer https://fullcalendar.io/docs/Calendar-addEvent to get a detailed understanding about this.
They have shared https://fullcalendar.io/docs/Calendar-addEvent-demo on their documentation as well to give a demo about the issue you raised.


text:
Q: How to solve bootbox.dialog() running in the background? can't click anything I'm developing a web application for a client.
I use bootbox.js to display the error message to the user, but I faced a problem and I just don't know where to correct this problem.
This is click event:
$("#login").click(function() {
    var username = $("#login_username").val();
    var password = $("#login_password").val();

    if(username == "")
    {
        //alert("Please enter username");
        $("#login_username").focus();
    }
    else if(password == "")
    {
        //bootbox.alert("Please enter password");
        $("#login_password").focus();
    }
    else
    {
        var dataString = "username=" + username + "&password=" + password;
        $.ajax({
            type: "POST",
            url: "ajax/members/ajaxLogin.php",
            data: dataString,
            cache: false,
            beforeSend: function(){
                $("#login").val("Checking...");
            },
            success: function(response){
                var response_message = response.indexOf("members");
                if(response_message != -1)
                {
                    window.location.assign(getBaseURL() + response);
                }
                else
                {
                    bootbox.dialog({
                        message: response,
                        title: "Error",
                        buttons: {
                            success: {
                                label: "Error!",
                                className: "btn-warning",
                            },
                        }
                    });
                }
            }
        });
    }
});

but this dialog is seem as follow please follow this link to see the example image:

How to solve this problem please help
I use boostrap v.3.3.2 and JQuery 1.11.2


text:
Q: Div not inline when window gets smaller? I'm having a small issue with a couple divs. I have it set up with 5 divs all different colors, when the window size is shrunk the divs drop down under each other one by one. Is there a way I can make the space between them shrinks with it so they but up closer?
Thanks again guys

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}

Colour

A: Add a media query, so that after a certain width of screen the elements will get a margin-bottom that is a percentage instead of px.

A: Use media queries to make elements respond as the width of the viewport changes for example:
body {
background-color: lightgreen;
     }

@media only screen and (max-width: 500px) {
body {
    background-color: lightblue;
    }
}

This would make the background color change when the width of the viewport goes below 500 px. You can use this same concept with the width of your divs.
** Also, check out Bootstrap. Bootstrap makes it easy to define widths of elements using a grid system. You are trying to make your site "RESPONSIVE" which is a well-known concept in web dev. Bootstrap has an already created library for this problem. It use media queries to do it. It is worth understanding media queries deeply, but for a quick fix, research bootstrap.

A: You could put a rule in a media query that reduces the margins like in my example (last rule):

  p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 4%;
  margin-right: 4%;
  display: inline-block;
}

.center {
  text-align: center;
}

@media screen and (max-width: 760px) {
  .bg01Off,
  .bg02Off,
  .bg03Off,
  .bg04Off,
  .bg05Off {
    margin-left: 1%;
    margin-right: 1%;
  }

Colour

A: You can use a table instead of the .center div, and give it the following styles:
table {
  width: 100%;
  text-align: center;
}
td {
  width: 20%; /* This is 100/the number of 's you have in the table. */
}

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg02Off {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg03Off {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg04Off {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg05Off {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}
table {
  width: 100%;
  text-align: center;
}
td {
  width: 20%;
}

Colour

A: Change the container center to a flexbox with the following properties:
.center {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 0 4%
}

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bgOff {
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.bg01Off {
  background-color: #80b3ff;
}

.bg02Off {
  background-color: #afe9af;

}

.bg03Off {
  background-color: #ffb380;
}

.bg04Off {
  background-color: #ffaaaa;
}

.bg05Off {
  background-color: #eeaaff;
}

.center {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 0 4%
}

Colour

A: You can remove margin left & right and use flexbox on .center like this :

p {
  margin: 0;
}

.pageColourOn {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 155px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.pageColourOff {
  display: none;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

.bg01Off {
  background-color: #80b3ff;
}

.bg02Off {
  background-color: #afe9af;
}

.bg03Off {
  background-color: #ffb380;
}

.bg04Off {
  background-color: #ffaaaa;
}

.bg05Off {
  background-color: #eeaaff;
}

.bg05Off, .bg04Off, .bg03Off, .bg02Off, .bg01Off {
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  display: inline-block;
}

.center {
  display: flex;
  justify-content: space-around;
}

Colour


text:
Q: Understanding Area 51 limit on number questions created for proposal
You've already created 11 questions for this proposal!

But no, I've created 11 questions total, spread across 6 different proposals.

Update: The message has changed to

You've already created 5 questions for this proposal!

which is at least accurate. So now the question becomes, "is this the actual limit?"

A: This should be fixed now.  I can neither confirm nor deny the rumor that I hard-coded it to 11 and forgot to go back and implement the actual count.


text:
Q: how to get a bool from a variable of a different type in js I want to be able to return true into a const if another const is inequal to null.
Everything that I have tried on crashing react.
Most Promising:
const isActive = plugVal !== null

this keeps returning true even when plugVal is null.
With useState hook I tried:
const [isActive, setIsActive] = useState(false)

if(plugVal){
    setIsActive(true)
}
else{
    setIsActive(false)
}

this triggers to many re-renders

A: You can try the code of @Invizi using ternary operator. This other 2 cases also works fine.

const isActive = plugVal ? true : false

const isActive = Boolean(plugVal)

const isActive = !!plugVal

A: The !! pattern using the ! operator is specifically just for this..
This topic covers it more in-depth


text:
Q: Приветствие пользователя анимированным текстом  в приложении iOS Хочу сделать анимированное приветствие пользователя. Смотрю в сторону метода
[UIView animateWithDuration:3 delay:10 options: UIViewAnimationOptionOverrideInheritedCurve
animations:^{
        // code
}

Проблема в том, что если делать анимированные view, например, их движение или изменение фона, то, изменяя параметры, получается. Как сделать это для label (принимая во внимание, что он наследник view), делать так же, но текст появляется сразу (не через несколько секунд). И как сделать, чтобы появлялось по букве, как бы печатает машинкой.
Подскажите, в какую сторону смотреть?
A: Конечно, можно сделать так или так. Но я Вам этого не рекомендую.
YetiCharacterLabel
Рекомендую, очень хорошо смотрится. Особенно для YETIMotionLabel, при изменения текста с пустого на Ваш будет как раз эффект появления по букве.
Почитать о этом решении можно у них в блоге.
https://github.com/android1989/YetiCharacterLabelExample

Также неплохо смотрятся на экране приветствия:
RQShineLabel - https://github.com/zipme/RQShineLabel

Shimmer - https://github.com/facebook/Shimmer


text:
Q: Validation always fail in production but working in local in laravel I'm trying to test my API endpoints in production but it always return the required validation failure. But when I try in my local, it is working well. Please see details below.
PeriodsRequest.php
public function rules()
{
   return [
      'company_code' => 'required'
   ];
}

Validation response
{
    "message": "The company code field is required.",
    "errors": {
        "company_code": [
            "The company code field is required."
        ]
    }
}

api.php
Route::get('company', CompanyController::class);

Controller
public function __invoke(PeriodsRequest $request)
{
    return (new Company)->getPeriods($request->validated());
}

Postman screenshot

A: [Solution]
Needed to configure the nginx like so:
try_files $uri $uri/ /index.php?$query_string;
Reference:
https://laracasts.com/discuss/channels/laravel/request-all-returns-empty-array-for-get-method-laravel-55?page=1&replyId=476661


text:
Q: Does this limit exist? $\lim_{n\to\infty}\frac{φ(f(n))}{ψ(g(n))}$ EDİTED:
Is this statement true?

Suppose $\left\{f,g,\varphi, \psi \right\}:\mathbb{R^{+}} \rightarrow \mathbb{R^{+}}$ and for $n\to\infty$
$\left\{f(n),g(n),\varphi(n), \psi(n) \right\}\rightarrow \infty$
If $\lim_{n\to\infty}\frac{φ(n)}{ψ(n)}$ doesn't exist, then $\lim_{n\to\infty}\frac{φ(f(n))}{ψ(g(n))}$ doesn't exist too.

I want to know that, if the assumption is wrong, under what conditions is true?

A: The statement depends on the choice of $f$ and $g$ as mentioned in the comments. So as it stands now, the claim is not true.
Just consider sequences that satisfy
$$\frac{\phi(n) } {\psi(n) } = 2+ (-1)^n$$
The limit of that sequence is clearly non-existent. How can we get that? Well just set $\psi(n) =n$ and
$$\phi(n) =\psi(n) (2+ (-1)^n) $$
Now set $f(n) =g(n) =2n$ and see that they all satisfy the conditions mentioned by you. Let's see
$$\lim_{n\to\infty} \frac{\phi(f(n) ) } {\psi(g(n) ) }=\lim_{n\to\infty} 2+1=3$$
That proves your claim wrong.
Honestly, I can't think of assumptions that make your statement true.


text:
Q: FFImageLoading CircleTransformation not working with transparent image <StackLayout Grid.Row="1" Grid.Column="0" BackgroundColor="#57bcec" Padding="5" Orientation="Horizontal">
    <ContentView Padding="5,0,0,0">
        <ffimageloading:CachedImage DownsampleToViewSize="True" HorizontalOptions="Center" VerticalOptions="Center"
                                    ErrorPlaceholder="{Binding PlaceholderImage}" LoadingPlaceholder="{Binding PlaceholderImage}"
                                    Source="{Binding UserImage, Converter={Helper:ImageSourceConverter}}"
                                    Aspect="AspectFit">
            <ffimageloading:CachedImage.WidthRequest>
                <OnPlatform x:TypeArguments="x:Double" iOS="40" Android="40" WinPhone="40" />
            </ffimageloading:CachedImage.WidthRequest>
            <ffimageloading:CachedImage.HeightRequest>
                <OnPlatform x:TypeArguments="x:Double" iOS="40" Android="40" WinPhone="40" />
            </ffimageloading:CachedImage.HeightRequest>
            <ffimageloading:CachedImage.Transformations>
                <fftransformations:CircleTransformation BorderSize="3" BorderHexColor="#34C04E"/>
            </ffimageloading:CachedImage.Transformations>
        </ffimageloading:CachedImage>
    </ContentView>
    <ContentView Padding="10,0,0,0" VerticalOptions="FillAndExpand">
        <Label Text="Alan Parker" FontSize="14" FontFamily="{StaticResource Lato_Regular}" TextColor="White" VerticalOptions="Center" />
    </ContentView>
</StackLayout>

Image URL: https://images.app.goo.gl/ZLSN5x9VNeebTD6z8
Output: Notice that image get cut-off from the corners

Normal Image:

A: I found one way to do this.
I have used: https://github.com/daniel-luberda/DLToolkit.Forms.Controls/tree/master/ImageCropView
<imgcrop:ImageCropView HeightRequest="50" WidthRequest="50" x:Name="cropView"
        Source="https://anothercommonman.files.wordpress.com/2011/10/gandhiji.jpg">
        <imgcrop:ImageCropView.PreviewTransformations>
                <ffTransformations:CircleTransformation />
        </imgcrop:ImageCropView.PreviewTransformations>
</imgcrop:ImageCropView>


text:
Q: How to register a vue compoent correctly I am trying to port this snippet into a reusable vue component:
<template>

            React top expert of this week is
            <ejs-dropdownlist id='employee' :dataSource='data' :fields='fields' :popupHeight='height' :width='width' cssClass='ddl-inlinecss' :value='value' :popupWidth='popupWidth' :placeholder='watermark'>
            </ejs-dropdownlist>

</template>

I therefore put all of the code above into a file called "InlineDropdown.vue" (you can check the example here: https://ej2.syncfusion.com/vue/demos/#/material/drop-down-list/inline.html)
My projects hirachy looks like this:
|-- src
        |-- App.vue
        |-- main.js
        |-- router.js
        |-- assets
        |   |-- fonts
        |   |-- scss
        |-- components
        |-- directives
        |-- layout
        |-- pages
        |   |-- components
        |   |   |-- **InlineDropdown.vue**
        |   |-- **index.vue**
        |-- plugins

Within the index.vue file I am importing the InlineDropdown component via import InlineDropdown from "./components/InlineDropdown";
When runnin npm run serve I am getting presented with the text of the component ("React top expert of this week is"), but not with the content of the  <ejs-dropdownlist>.
The error log within my browsers terminal tells me that:
vue.runtime.esm.js?2b0e:619 [Vue warn]: Unknown custom element: <ejs-dropdownlist> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

found in

---> <InlineDropdown> at src/pages/components/InlineDropdown.vue
       <Index>
         <App> at src/App.vue
           <Root>

I can't see where I am declaring the component wrong. Can anybody help please?
The full code can be found here:
https://github.com/Shoxc/vue-now-ui-kit-master
This is the place where I want to add the component:
https://github.com/Shoxc/vue-now-ui-kit-master/blob/2155e6e5217d42da5829526a2c974d91051de3d3/src/pages/Index.vue#L14
This is the file for the component:
https://github.com/Shoxc/vue-now-ui-kit-master/blob/main/src/pages/components/InlineDropdown.vue

A: To register this component globally, you can import the .vue file into your main.js , then use
Vue.component() method to register it.
For example:
import Vue from 'vue'
import App from './App'
//...some code if any
//...some more code etc.
import inlineDropdown from "./pages/components/InlineDropdown"

//...
Vue.component('ejs-dropdownlist',inlineDropdown)

A: Part of the problem is the usage of Vue.use() from InlineDropdown.vue. Vue plugins should be installed before mounting the app so that the plugin's effects are available to the rest of the app. This particular plugin (MultiSelectPlugin) registers MultiSelectComponent globally.
So, the following code should be moved to main.js before the app mounts:
// InlineDropdown.vue
// REMOVE THIS:
//import { MultiSelectPlugin } from "@syncfusion/ej2-vue-dropdowns";
//Vue.use(MultiSelectPlugin);

// main.js
import { MultiSelectPlugin } from "@syncfusion/ej2-vue-dropdowns";
Vue.use(MultiSelectPlugin);

new Vue(/*...*/)

Alternatively, you could locally register the component in InlineDropdown.vue. However, be aware that ejs-dropdownlist is  actually defined in DropDownListComponent, not MultiSelectComponent:
// InlineDropdown.vue
import { DropDownListComponent } from "@syncfusion/ej2-vue-dropdowns";

export default {
  components: {
    DropDownListComponent,
  }
}

I also noticed that InlineDropdown.vue is imported, but not registered in the components option of Index.vue. Make sure to add InlineDropdown to components:
// Index.vue
export default {
  components: {
    InlineDropdown,
  }
}


text:
Q: Javascript always failing I am busy writing some javascript to take a list of selected documents and do some processing on a list with each document in Office365. I am getting a strange error when the code tries to load the document from the absolute URL. The document is guaranteed to be in the same SP.Web that the JS is in.
The error is

Value does not fall within the expected range.

Below is the JS I have:
function GetFile(attachment, item) {
   var fileContext = SP.ClientContext.get_current();

   var site = fileContext.get_site();
   fileContext.load(site);

   fileContext.executeQueryAsync(function() {
       var relUrl = attachment.Url.replace(_spPageContextInfo.siteAbsoluteUrl, '');

       var file = fileContext.get_web().getFileByServerRelativeUrl(relUrl);

       fileContext.load(file, 'ListItemAllFields');

       fileContext.executeQueryAsync(
           function () {
               var listItem = file.get_listItemAllFields();
           },
           function (sender, args) {
               console.log(args.get_message()); //errorhandling
           }
       );
   }, function(sender, args) {
       console.log(args.get_message());
   });
}

This is not a permissions thing as I can take the url of the documents being selected and open them fine from the browser.
I have noticed, that I can't seem to hit the client.svc service on the site in question when taking the url for the request from the request object.

A: The error Value does not fall within the expected range usually occurs when the file specified via serverRelativeUrl parameter in SP.Web.getFileByServerRelativeUrl Method  does not exists, so make sure the url has the following format:
/<site>/<list url>/Attachments/<item id>/<attachment name>

I guess (since it is not clear from question) attachment.Url stores the location of AttachmentFile. In that case SP.File.listItemAllFields property will be empty since attachment file is not associated with list item.

A: You suggestion of the "file doesn't exist" led me down the right road. The url I was using to grab the file was kissings /sites/ which was getting removed by the following:
var relUrl = attachment.Url.replace(_spPageContextInfo.siteAbsoluteUrl, '');

I have made some changes to it and it now loads the file as expected.


text:
Q: Print generates a cell with style "Print" The Wolfram documentation for "Print" says the following:

In a notebook, Print generates a cell with style "Print".

What does it mean by style "Print" since there is no style called "Print"?
Is there an implied meaning that is not obvious?
For example, the expression below creates a cell with style "Input".
Print["Dog"]

For the first picture, notice how when Dog is selected, the format says "Input".
I am still not clear what format style (Input?) it actually has.

For the second picture with Show Expression checked, I see "Print" which I assume is where the reference to "Print" is coming from?

The Wolfram documentation for "Cell" says the following:

In any given notebook, a collection of possible cell styles is defined, typically with names such as  "Title",  "Section",  "Input", and  "Output".

There is no mention of "Print" as a style. Where is that documented?

A: From the notebook menus, pick Format > Edit Stylesheet. Click on Default.nb, then click on Core.nb.  Open Styles for Input and Output Cells.  Select Local Definition for Style "Print" and toggle the cell display (Ctrl-Shift-E). hth.


text:
Q: Byte Code off-card verifier for cap file I need to verify a Java Card programme (a cap file) using an off-card byte code verifier.
I have manually modify the informations in the cap file and i want to verify if the new cap file is well type.
I try to use the com.sun.javacard.scriptgen.CAP.verifyCAP() methode. I send valid and invalid cap files but the result is always equal to 0.

A: I never post the solution. That day has finally arrived ;)
Download the JavaCard SDK. It contain a compiled version of the verifier. For that exemple that will be java_card_kit-2_2_1.
My files:
./
./java_card_kit-2_2_1/
./java2CAP.sh
./ValidApplet/
./ValidApplet/ValidApp.java
./verifyCAP.sh

java2CAP.sh:
#!/bin/bash
export JC_HOME=./java_card_kit-2_2_1
export CLASSPATH=$JC_HOME/lib/apduio.jar:$JC_HOME/lib/apdutool.jar:$JC_HOME/lib/jcwde.jar:$JC_HOME/lib/converter.jar:$JC_HOME/lib/scriptgen.jar:$JC_HOME/lib/offcardverifier.jar:$JC_HOME/lib/api.jar:$JC_HOME/lib/capdump.jar:$JC_HOME/lib/:$JC_HOME/samples/classes:$CLASSPATH
PACKAGE=ValidApplet
CLASS=ValidApp
APPLET=$CLASS.java
PACKAGE_AID=0x46:0x56:0x55:0x4c:0x4e:0x54:0x45:0x53:0x54:0x53
APPLET_AID=0x46:0x56:0x55:0x4c:0x4e:0x54:0x45:0x53:0x54:0x53:0x41:0x70:0x70
javac -g -source 1.3 -target 1.1  $PACKAGE/$APPLET
java com.sun.javacard.converter.Converter -nobanner -out CAP -exportpath $JC_HOME/api_export_files -applet $APPLET_AID $CLASS $PACKAGE $PACKAGE_AID 1.0 -i

verifyCAP.sh:
#!/bin/bash
export JC_HOME=./java_card_kit-2_2_1
export CLASSPATH=$JC_HOME/lib/apduio.jar:$JC_HOME/lib/apdutool.jar:$JC_HOME/lib/jcwde.jar:$JC_HOME/lib/converter.jar:$JC_HOME/lib/scriptgen.jar:$JC_HOME/lib/offcardverifier.jar:$JC_HOME/lib/api.jar:$JC_HOME/lib/capdump.jar:$JC_HOME/lib/:$JC_HOME/samples/classes:$CLASSPATH

export CAPP_PATH=./ValidApplet/javacard
export CAPP_NAME=ValidApplet.cap

java -classpath $JC_HOME/lib/offcardverifier.jar com.sun.javacard.offcardverifier.Verifier $JC_HOME/api_export_files/javacard/framework/javacard/framework.exp $JC_HOME/api_export_files/java/lang/javacard/lang.exp $JC_HOME/api_export_files/javacard/security/javacard/security.exp $CAPP_PATH/$CAPP_NAME

./ValidApplet/ValidApp.java:
package ValidApplet;

import javacard.framework.Applet;
import javacard.framework.APDU;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;

public class ValidApp extends Applet //implements PIN
{
    final static byte TEST_CLA = (byte)0x77;

    public static class TestClassStatic {};

    protected ValidApp()
    {
        register();
    }

    public static void install(byte[] bArray, short bOffset, byte bLength)
    {
        new ValidApp();
    }

    public void process(APDU apdu)
    {
        byte buffer[] = apdu.getBuffer();

        try {
            if (buffer[ISO7816.OFFSET_CLA] == TEST_CLA) {
                test((byte)4, (short)2);
            } else {
                ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
            }
        } catch (ISOException e) {

        }
    }
}


text:
Q: Add bulk credentials in bulk to Password Vault Overview:
I have created a vault that stores sensitive data, you can see my full sample code in this question:
PowerShell Password Vault
Goal:
I am attempting to make a function that would add credentials in bulk. I am not looking for particular method. However, I did attempt to run a loop that would add creds on each new line. But, my logic is off somewhere, meaning that when I attempt to use the following code, it begins to add credentials in an erroneous manner- please see table below. I am very open to new ideas or suggestions as well.
Exact Code:
function Add-BulkCreds{
  param(
    [string]$ID,
    [string]$Key,
    [string]$URL
  )
  $vaultAssembly
  do{
    Write-Host 'AddCreds)' -ForegroundColor Yellow -NoNewline
    $x = Read-Host
    $first,$second,$third = $x -split '\s',3
    $vault = New-Object Windows.Security.Credentials.PasswordVault
    $cred = New-Object Windows.Security.Credentials.PasswordCredential($second, $third, $first)
    $vault.Add($cred)
    }while($x)
}

Example input:
PS > Add-BulkCreds
AddCreds)test1c1 test1c2 test1c3
test2c1 test2c2 test2c3
test3c1 test3c2 test3c3
AddCreds)
New-Object : Exception calling ".ctor" with "3" argument(s): "The parameter is incorrect.
Cannot create credential"
At C:\Users\getcred.ps1:83 char:13
+     $cred = New-Object Windows.Security.Credentials.PasswordCredential($second,  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Output:
     ID                                              Key                                                Endpoint
--------                                           ------                                             -----------
test1c3...                                         test1c1                                            test1c2

Closer Look at ID column:
PS > $credexample.id | Where-Object {$_.key -eq 'test1c1'}
test1c3
test2c1 test2c2 test2c3
test3c1 test3c2 test3c3

Observation:
As you can see the following part of my input was added to my ID column:
test1c3
test2c1 test2c2 test2c3
test3c1 test3c2 test3c3

Whereas....
test1c1 was added to Key
test1c2 was added to endpoint
Question:
Given my goal and overview, how can I create a simple, yet efficient function for adding credentials in bulk? And, does my logic work?
Additionally:
I am realizing that the original parameters aren't even needed since I am splitting the variable below with $x.
  param(
    [string]$ID,
    [string]$Key,
    [string]$URL
  )