text:
Q: Asp Net MVC with VM is this good practice? (Code Sample) I'm wondering if what I have here is good practice. Using Entity Framework Code First with MVC and View Models.
Below i have code for List, Create, Edit and Delete. Model name Page and 2 ViewModels name ContentViewModel and ContentListViewModel.
 private readonly IUserService _userService;
    //private readonly MembershipProvider _members;

    public ContentController()
    {
        // _members = Membership.Provider;
        _userService = new AspNetMembershipProviderWrapper();
    }

    //
    // GET: /Profile/Content/

    public ActionResult Index()
    {
        using (var db = new BlogContext())
        {
            IEnumerable<Page> pages;
            pages = db.ArticlePages.ToList();
            List<ContentListViewModel> model = new List<ContentListViewModel>();
            foreach (Page pg in pages)
            {
                MembershipUser user = _userService.Get(pg.authorId);
                model.Add(new ContentListViewModel()
                {
                    PageID = pg.pageID,
                    UserName = user.UserName,
                    UserID = (Guid)user.ProviderUserKey,
                    IsFrontPage = pg.frontpage,
                    isPublished = pg.published,
                    PageTitle = pg.titleHeading,
                    PageUrlName = pg.idName,
                    PublishedDate = pg.datentime
                });
            }

            return View(model);
        }
    }

    //
    // GET: /Profile/Content/Create

    public ActionResult Create()
    {
        return View();
    }

    //
    // POST: /Profile/Content/Create

    [HttpPost]
    public ActionResult Create(ContentViewModel page)
    {
        if (ModelState.IsValid)
        {
            using (var db = new BlogContext())
            {
                db.ArticlePages.Add(new Page()
                {
                    authorId = (Guid)Membership.GetUser().ProviderUserKey,
                    datentime = DateTime.Now,
                    frontpage = page.FrontPage,
                    published = page.Published,
                    titleHeading = page.TitleHeading,
                    pageContent = page.Content,
                    idName = page.IdName
                });
                db.SaveChanges();
                return RedirectToAction("Index").Success("Page added Successfully.");
            }
        }

        return View(page);
    }

    //
    // GET: /Profile/Content/Edit/5

    public ActionResult Edit(int id = 0)
    {
        if (id == 0)
        {
            return RedirectToAction("Index").Error("Page Not found.");
        }
        Page pg = new Page();
        using (var db = new BlogContext())
        {
            pg = (from m in db.ArticlePages where m.pageID == id select m).SingleOrDefault();
        }
        if (pg == null)
        {
            return RedirectToAction("Index").Error("Page Not found..");
        }
        return View(new ContentViewModel()
        {
            id = pg.pageID,
            Content = pg.pageContent,
            FrontPage = pg.frontpage,
            Published = pg.published,
            TitleHeading = pg.titleHeading,
            IdName = pg.idName
        });
    }

    // POST: /Profile/Content/Edit/5

    [HttpPost]
    public ActionResult Edit(ContentViewModel page)
    {
        if (ModelState.IsValid)
        {
            using (var db = new BlogContext())
            {
                var oPage = db.ArticlePages.Single(p => p.pageID == page.id);
                oPage.frontpage = page.FrontPage;
                oPage.idName = page.IdName;
                oPage.pageContent = page.Content;
                oPage.published = page.Published;
                oPage.titleHeading = page.TitleHeading;
                db.SaveChanges();
                return RedirectToAction("Index").Success("Page updated");
            }
        }
        return View(page);
    }

    //
    // POST: /Profile/Content/Delete/5

    [HttpPost]
    public ActionResult Delete(int id)
    {
        using (var db = new BlogContext())
        {
            Page page = db.ArticlePages.Find(id);
            db.ArticlePages.Remove(page);
            db.SaveChanges();
            return RedirectToAction("Index").Success("Page deleted");
        }
    }

I would like to know there are better ways of doing this?

A: While that method is certainly better than passing the entities directly to the view, I would suggest a number of improvements.
First, I would create a new business layer, and then create a facade class to retrieve your data.  Then move all database access to this layer.  Thus, you would end up with a call to the service layer rather than doing direct database access like you are doing above.
Second, you should look into using something like AutoMapper to map between your data entities and your view models.


text:
Q: How can I remove the [,] symbols from the result of ArrayList.toString()? I have a method which returns an ArrayList in my Android app. Everything works great, but one thing annoys the heck out of me. When I print out the ArrayList in my TextView it looks like this:
[firstValue
, secondValue
, thirdValue
]

How can I remove [ and , from the output?

A: You might want this:
public String formatList(List<?> list) {
    StringBuilder b = new StringBuilder();
    for(Object o : list) {
        b.append(o);
    }
    return b.toString();
}

The toString() method of the lists (and other collections) is mainly for debugging output.

A: This is coming from ArrayList's toString() method (or some underlying collection's toString()).  If it's bugging you that much, extend ArrayList and override toString().  But because it's just debugging output, I'd personally try and get over your anxiety.  ;)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How could I connect 2 computer via USB-Serial adapter (2x FT232) First time asking a question (if I'm not at the right place, feel free to point me to the right place) :)
I want to access PC2 with PC1 via two FT232 adapter.
Example:

I already tried to pass the console=ttyUSB0 argument to the kernel, mentioned here https://www.debian.org/releases/stable/i386/ch05s03.en.html (see grub config below) however it does not seem to work (I only get a blinking cursor on the monitor connected to PC2 and no output on the serial monitor on PC1, both are set at 9600 bps) (both PC are running Debian 11 with the kernel 5.10.0-15)
tldr: trying to get a shell on a client connected to a server via ft232 ttl serial adapter
content of: /etc/default/grub

GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="console=ttyUSB0,9600n8"
GRUB_CMDLINE_LINUX=""

A: The answer turned out to be super simple, all I had to do was to:

*

*setup /dev/ttyUSB0 on both computer

*Run the commands on the server

(Run with sudo or as root)
systemctl enable serial-getty@ttyUSB0.service
systemctl start serial-getty@ttyUSB0.service

*

*BOOM, you got a login prompt and a shell

Ps: thanks davigo for the help and have a good day :]


text:
Q: Why are lengths different when an object is curved?
In the above diagram ad is equal to bc. Likewise, ce should be equal to df (Since angle F and E are at 90 degree). My question is why when calculating length of ce and df using $2\pi r$ they are different?
If I was holding a ruler so it is vertical and then bent it a bit at the bottom. Wouldn't the length be the same?

A: imagine that df is a part of a circle, and ce is a part of another circle
is the circumference of the first circle equal to the circumference of the second one
or less  ?
i think it's clear now.


text:
Q: How to identify the change of value in a particular text field after submit button click I want to update marks of a particular student in particular subject out of eight subjects.
My question is how to identify that a particular text box value has been changed after clicking submit button, then the updation task is forwarded to the update.php. Please give me your valuable answer. Thanks in advance.

A: Since your button click event is occured on client side, you can identify it by client side scripting.
 <script lang='javascript'>
 $(document).ready(function(){
    $('#button_id').click(function(){
             /* Do whatever you want to do right here*/
    });
 });
 </script>

For identifying the change on text box after clicking submit button, first change the input type from submit to button as as soon as you click submit, it redirects the page.
<input type='button' onClick='your_function()' id='btn_submit' name='btn_submit' />
<input type='text' id='text_box' name='text_box' onchange='$('#flag_value_changes').val('1')' />
<input type='hidden' id='flag_value_changes' name='flag_value_changes' />
<script lang='javascript'>
function your_function()
{
         flag_value_changes = $('#flag_value_changes').val();
         if(flag_value_changes == 1)
            alert('Value has been changed');
         else
            alert('Value has not been changed');
}
</script>

A: the scripting language can help you in this situation.use javascript for the event of the submit button click.
do whatever you needed in that event..happy coding :)

A: As stated by hsuk. You can do it on the client side using javascript.
I've provided an example using textarea and no inline javascript.

HTML
<div>
  <textarea id= "math">Math</textarea>
  <textarea id= "english">English</textarea>
  <textarea id= "french">French</textarea>
  <textarea id= "spanish">Spanish</textarea>
  <input type="submit" value="submit"/>
</div>

And the following javascript(Using Jquery)
$(document).ready(function(){
    var initialValues = [];
    var i = 0;
   //Gets values on load
    $("div textarea").each(function(){
        initialValues[i] = this.id+" had "+$(this).val();
        i++;
    });

   //Checks values on click
    $("input").click(function(){
    i = 0;
    $("div textarea").each(function(){
        value = initialValues[i].split(" ");
        if($(this).val() != value[2]){
            alert(value[0] + " was Changed.");
        }
        i++;
        });
    });
});

DEMO


text:
Q: Kivy: Buildozer - How to Add Modular Packages and See them Actually Work? I realize adding sound to an kivy app based on kivy APIs leads to some serious frame rate breakage.  From what I can tell, sound is not buffered or anything it's just played in the raw.  For a moment, the thought of using python threads to create buffers for kivy sound entered my head, then I was like "nah..."  I'll just use pygames sound mods instead.
Under a virtual Linux Ubuntu 64 system, I type the command: sudo apt-get install python-pygame.
I already have python 2.7 on the system.  I could see where pygame 1.9.1 was added (which is what I needed).
In my buildozer.spec file I added pygame as a requirement along with kivy.
I then build a test apk, installed in on my android device and for some reason, the log file tells me the app could not find the "mixer" module, which is provided by pygame.
So what am I doing wrong?  Is there some other way to add pygame as a module which buildozer can processes into an available module at run-time?
Update====March 24 2017=====================================================
I decided to use a workaround for the SoundLoader issue.
            from kivy.core.audio import SoundLoader
            from kivy.core.audio.audio_sdl2 import SoundSDL2

            NewSound = SoundSDL2(source='path_to_sound.wav')

I'm hoping this approach will play on android as I am yet to test it.  I noticed mp3 files will not play with SoundSDL2 or when using just SoundLoader alone.  This worries me because mp3 files are common for an android device.  IDK about wave files....
Let me test it...


text:
Q: Uncaught TypeError: d.Wa is not a function I am trying to add a feature collection fetched from a server to the source of an empty vector layer, but I am getting this error (using OpenLayers 3):
Uncaught TypeError: d.Wa is not a function
I am not finding much online to describe this error.  IT is thrown at this point in my code:
segment.getSource().addFeatures(features);
the segment layer is initialized globally, with an empty source (I am using Backbone)
 window.globals.segment = new ol.layer.Vector({
      source: new ol.source.Vector({

            }),
      visible: true,
      style: new ol.style.Style({
          stroke: new ol.style.Stroke({
              color: '#022835',
              width: 4
          })
      })
  });

The features are fetched from a server then read into a geojson:
            if (response.length > 0) {

                   if (response[0][0].features[0].geometry.type === 'MultiLineString') {

                       _.map(respfeatures.features, function (feature) {
                        feature.properties.segmentid = feature.properties.f1;
                        feature.properties.street = feature.properties.f2;
                    });
                } else {
                       _.map(respfeatures.features, function (feature) {
                        feature.properties.nodeid = feature.properties.f1;
                    });
                }

                   return new ol.format.GeoJSON().readFeatures(respfeatures.features, {
                    dataProjection: 'EPSG:2263',
                    featureProjection: 'EPSG:3857', rightHanded; false
                   });

            }
        }).then(function (features) {

            console.log(features);

            window.globals.segment.getSource().addFeatures(features[0][0].features);
        });

The error is thrown at the last line..I can see in the console statements that I am getting a feature collection returned.
EDIT: I drilled down into the returned features, and now I do not get an error, but I still do not get any segments rendered on the screen:
 console.log("features : " + (JSON.stringify(newfeatures[0][0])));

returns (what appears to be) a valid geoJSON
now I am trying
window.globals.segment.getSource().addFeatures(newfeatures[0][0]);

..no errors, but no segments rendered either
Bewlow is the response from the server, which appears to me to be valid geoJSON
(below is returned from
  console.log('response: ' + JSON.stringify(response[0][0].features));

response: [{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[1024345.25673969,182382.254051775],[1024608.61874577,182429.714914858]]]},"properties":{"f1":51278,"f2":"151 AVENUE"}},{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[1024500.74855469,182994.720346525],[1024608.61874577,182429.714914858]]]},"properties":{"f1":51279,"f2":"80 STREET"}},{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[1024608.61874577,182429.714914858],[1024715.1477322,181869.545103431]]]},"properties":{"f1":51281,"f2":"80 STREET"}},{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[1024608.61874577,182429.714914858],[1024868.00470994,182478.149529263]]]},"properties":{"f1":51282,"f2":"151 AVENUE"}}]

I tried this as well, which does not throw an error, but does not result in the features being rendered either:
 window.globals.segment.getSource().getFeatures().push(newfeatures[0][0]);

EDIT 2:
I made a slight change to the scope of the empty aray in the save method, so now I am getting a FeatureCollection returned:
 {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[996193.689683363,207843.941317275],[996589.742040858,208151.906580597]]]},"properties":{"f1":35167,"f2":"COMMERCIAL STREET","segmentid":35167,"street":"COMMERCIAL STREET"}},{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[996603.364060864,207892.573109776],[996589.742040858,208151.906580597]]]},"properties":{"f1":35172,"f2":"MANHATTAN AVENUE","segmentid":35172,"street":"MANHATTAN AVENUE"}},{"type":"Feature","geometry":{"type":"MultiLineString","coordinates":[[[996603.364060864,207892.573109776],[997219.481595024,207967.464692265]]]},"properties":{"f1":35173,"f2":"BOX STREET","segmentid":35173,"street":"BOX STREET"}}]}

...this gives me a valid rendered layer in QGIS..but the features are still not rendered in my app.

A: I think it has something to do with the fact that your geojson data should be more like this :
{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
 // and here go all your features
 ]
 }

while I don't have a good solution to solve it using OL3, you can try a work-around by handling it as a string and adding the GeoJSON header below with the string1.concat(string2) in javascript
or you could review your data retrieving code from the server
the ol.source.Vector() takes a Features, so I guess your geoJSON data should be as a FeatureCollection


text:
Q: Is there an elegant way of checking in C++ if the library complex was included? I'm working on a C++ library, and I want to compile some functions only if the library complex was included, in the main file.
I'm considering using the macro the complex library defines to use as a guard, check if it was defined, and proceed if yes.
Checking the library complex header in the intel and GNU compilers I observed that they define different macros, namely INC_COMPLEX(intel) and _GLIBCXX_COMPLEX(GNU). Using this information I could write the following working example:
#include <complex>

#if ((defined(_INC_COMPLEX_) || defined(_GLIBCXX_COMPLEX)))
    #define _complex_probe 1
#endif

#include <iostream>

int main(int args, char** argv){

#if _complex_probe
        std::cout << " Library complex included. \n";
#endif

    return 0;
}

Is there a more elegant or portable way to implement this resource?


text:
Q: one-to-one NHibernate mapping I've been at this for the last 3 days and still can't figure it out. Conceptually I need to design an envelope object and its to and from addresses (object). I have the following database schema (which I cannot change):
Table Envelope

*

*EnvelopeId (PK)

*List item

*PostmarkDate

Table Address

*

*EnvelopeId (PK, FK in Envelope)

*AdressType (1 - for From addresses, 2 - for To addresses)

*Street

*State

*ZipCode

*unique contraint on (EnvelopeId, AdressType)
My classes are as follows:
public class Envelope
{
public virtual long EnvelopeId { get; set; }
public virtual DateTime PostmarkDate { get; set; }
public virtual Address FromAddress { get; set; }
public virtual Address ToAddress { get; set; }
}

public class Address
{
public virtual AddressId { get; set; }
public virtual Envelope Envelope { get; set; }
public virtual AdressType { get; set; }
public virtual Street { get; set; }
public virtual State { get; set; }
public virtual ZipCode { get; set; }
}

So, Envelope ends up having 2 corresponding Address entries (with it's primary key): one with AddressType 1 and one with AddressType 2. I haven't included my mapping files because that's where the problem lies. I attempted several solutions:

*

*a one-to-one relationship between Envelope and Address. I had 2 one-to-one tags in the Envelope mapping file, and  a one-to-one tag in the Address mapping file. The Address mapping file also had a foreign generator and a constrained="true" on Envelope. NHibernate complained that the one-to-one mappings between Envelope and Address was confusing.

*created 2 classes FromAddress and ToAddress, both derived from Address. Envelope class now had a FromAddress and a ToAddress (instead of 2 Address). I implemented table-per-class hierarchy for the inheritance. In my Address mapping I had: a foreign generator, 2 subclass tags, discriminator values and a one-to-one relationship to Envelope. But NHibernate complained about not liking the discriminator and the one-to-one together. So then I moved the one-to-one tag inside the subclass tags. Now NHibernate complained about not knowing what the Envelope property is ("Unable to resolve property: Envelope")
Any help would be appreciated.

A: Surely an envelope should be a one-to-many with address?  That is an envelope can have many addresses (this will future proof your code if you have more than two addresses in the future)
However I am not sure why  you can't get the  table-per-subclass (using a discriminator) to work as you haven't posted your mappings. You do not need the bi-directional reference from address back to envelope as address inherits from envelope.


text:
Q: Passwordless Login to Ubunto 20.04 with FIDO2 So i've setup passwordless thru FIDO2 by adding
auth sufficient pam_u2f.so authfile=/home/me/.config/FIDO2/u2f_keys
having followed the instructions on the yubico page to generate the u2f_keys code
It's working great as an additional factor of authentication but I'd like it to be the only one (ie, we are going passwordless) or at least the primary form of authentication. Right now logging in and sudo'ing results in it asking for a password and then asking to tap the key.


text:
Q: After new windows 10 update 1803 doesn't wont to send (HttpWebRequest,SecurityProtocolType.Tls12) After new windows 10 update (1803) I have problem with sending data.
MESSAGE:

the underlying connection was closed an unexpected error occurred on a send

If anyone has any idea I would be very grateful
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
request.Method = "POST";
request.Headers.Clear();
request.AllowAutoRedirect = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
request.Timeout = 10000; //1 sec = 1000 ms

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

byte[] byteStream = System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(potpisaniRacunString);

request.ContentLength = byteStream.LongLength;
request.ContentType = "text/xml";

using (Stream writer = request.GetRequestStream()) <---  BOOOM ! (The underlying connection was closed: An unexpected error occurred on a send.)
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}


text:
Q: Is it possible to make an MS access 2007 code patch file? I've been asked to make some changes to an access app, which looks easy enough to do. The data and the code reside in one file. The trouble is while I'm working on a copy of the file from some point in time the production file keeps changing, the plant operates 24/7. I'll need to make a patch to quickly apply to the production file so they can do an immediate switchover without shutting things down.
Is it possible to make a code patch this way in access, so I don't have to type my changes in all over again?
Otherwise, how can I best split the code and the data schema from the data, so I can work on as much code as possible that is independent of the data growth?
Thanks.

A: I found the wizard that splits a single access file into a front end and back end file. Now I can update the front end file whenever I want to without losing the latest data.
In my case, I had to hold the shift key when opening the database to bypass the macro hiding the menus from the production users.


text:
Q: adding a option to a combobox depending on a selection of the user in another combobox I see lots of posts on this but not using ints I have the line converting the int declaring the grade as the value which is chosen in the combo_grade but my if statment isnt working, im trying to have combo_sub show the message if the combo_grade is equal to 9.
private void combograde_SelectedIndexChanged(object sender, EventArgs e)
{
    if (combograde.SelectedValue == "9")
    {
        combosub.Items.Add("If this shows it works");
    }
}

A: tl;dr use combograde.SelectedItem instead of combograde.SelectedValue
I did a little digging around in VS and on MDSN. From the looks of it SelectedValue is only useful when using data binding. It displays the value of the field denoted by ValueMember which selects the value to be displayed by complex data.
MDSN seems to suggest that when ValueMember is null or nothing SelectedValue will be to the same as SelectedItem but that isn't what I observed.
**Previous Answer**
If combo_sub is to have the message shouldn't
combo_grade.Items.Add("If this shows it works");

be
combo_sub.Items.Add("If this shows it works");


text:
Q: Best way to replicate of a group of widgets into each cell? Tkinter I want to create a loop that I can use to populate each cell in a column with the same three widgets, stacked on top of each other and within the same cell. The best way I can think of doing this is to first create a frame for each cell (via a loop) then to populate each frame with three widgets (via a separate loop). The top & bottom widgets will be buttons, and the middle widget will be a label.
Would this be a good approach, or can you suggest something cleaner?
Simplified code:
import tkinter as tk
from tkinter import simpledialog,filedialog,colorchooser,messagebox,Frame,Button
from PIL import ImageTk, Image
import textwrap

root = tk.Tk()
root.state('zoomed')
rq = 10 # row quantity

canv_1 = tk.Canvas(root, bg="blue")
canv_1.pack(side="top", fill="both")#, fill="both", expand=True)

canv_2 = tk.Canvas(root, bg="gray")
canv_2.pack(fill="both", expand=True)

def onFrameConfigure(canvas):
    '''Reset the scroll region to encompass the inner frame'''
    canvas.configure(scrollregion=canvas.bbox("all"))

frame = tk.Frame(canv_2)

# create, bind & position scrollbar
vsb = tk.Scrollbar(canv_2, orient="vertical", command=canv_2.yview)
canv_2.configure(yscrollcommand=vsb.set)
vsb.pack(side="right", fill="y")

canv_2.pack(side="left", fill="both", expand=True)
canv_2.create_window((0,0), window=frame, anchor="nw")
frame.bind("<Configure>", lambda event, canv_2=canv_2: onFrameConfigure(canv_2))

labels = ["","Chapter Title", "Slide", "Instructions"]
ColWidths = [5, 15, 15, 40]
root.label_wid = []
font1 = ("arial", 15)

load1 = Image.open("StartingImage.jpg")
root.render1 = ImageTk.PhotoImage(load1)

ch_text = []

for i in range(len(labels)):
    root.label_wid.append(tk.Label(canv_1,
                                   font=font1,
                                   relief="raised",
                                   text=labels[i],
                                   width=ColWidths[i],
                                   ).grid(row=0, column=i, sticky="we"))

c1 = "#a9d08e"
c2 = "#8dd1bf"

Move_col = [
    tk.Entry(
        frame,
        bg = c1,
        width = ColWidths[0],
        font = font1)
    for y in range(0, rq)
]

Title_col = [
    tk.Entry(
        frame,
        bg = c1,
        width = ColWidths[1],
        font = font1)
    for y in range(0, rq)
]

Slide_col = [
    tk.Entry(
        frame,
        bg = c2,
        width = ColWidths[2],
        font = font1)
    for y in range(0, rq)
]

instruction_col = [
    tk.Text(
        frame,
        bg="white",
        wrap="word",
        font=font1, width = ColWidths[3], height=10)
    for y in range(0, rq)
]

for y in range(0, rq):
    Move_col[y].grid(row=y + 1, column=0, sticky='news')
    Title_col[y].grid(row=y + 1, column=1, sticky='news')
    Slide_col[y].grid(row=y + 1, column=2, sticky='news')
    instruction_col[y].grid(row=y+1, column=3, sticky='news')

bt1 = tk.Button(canv_1, text="Export", font=font1, bg="#f5b942")
bt1.grid(row=0, column=4)
load2 = Image.open("scroll-up-gray.png")
root.render2 = ImageTk.PhotoImage(load2)
load3 = Image.open("scroll-down.png")
root.render3 = ImageTk.PhotoImage(load3)

root.mainloop()

Output:

Desired Output:

A: I recommend creating a class that inherits from the Frame widget. You can then use instances of this class almost like any other widget. I say "almost" because it doesn't support all of the same options as the built-in widgets, but it behaves the same way: you can create it, destroy it, and call pack, place, or grid on it.
There are many ways to do it. The following example uses text instead of images for the button to keep the example simple:
class MoveWidget(tk.Frame):
    """
    Custom widget with buttons for moving up and down. When clicked,
    the button will call the given command with two parameters: the
    index and either "up" or "down"
    """
    def __init__(self, parent, bg, index, command):
        super().__init__(parent, background=bg)

        self.index = index
        self.command = command

        self.up_button = tk.Button(self, text="^", bg=bg, command=self.up)
        self.down_button = tk.Button(self, text="v", bg=bg, command=self.down)
        self.label = tk.Label(self, bg=bg, text=str(index))

        self.up_button.pack(side="top", fill="x")
        self.down_button.pack(side="bottom", fill="x")
        self.label.pack(side="top", fill="both", expand=True)

    def up(self):
        self.command(self.index, "up")

    def down(self):
        self.command(self.index, "down")

Before you can use this class you need to define a function to move the item. Have it accept an index and a direction. The actual implementation is up to you, this is good enough for this answer:
    def move(index, direction):
        if direction == "up":
            print(f"Moving index {index} up")
        else:
            print(f"Moving index {index} down")

Now you can create an instance of the class, giving it the parent widget, index, command, and color as parameters:
Move_col = [
    MoveWidget(
        frame,
        bg=c1,
        index=y,
        command=move)
    for y in range(0, rq)
]

You don't have to change the code that calls grid on this widget.


text:
Q: TalkBack announces "Double tap and hold to long press" on WebView Background:
When focused on a WebView control, TalkBack announces something to the effect of "Bing. WebView. Double tap and hold to long press" (note that focus is on the WebView control itself, not the content within the webview).  However, as best I can tell, double tap and long pressing doesn't seem to do anything other than pass TalkBack focus into a control within the WebView itself.  Our team has testers that specialize in accessibility which filed a bug on us for this "Double tap and hold to long press" announcement.  The rationale within the bug states that since this action doesn't appear to do anything, the announcement will only serve to confuse TalkBack users.
This announcement doesn't appear to be specific to our app as I was able to reproduce this behavior on a new, blank Android app with a WebView that points to Google (there it announces "Google. WebView. Double tap and hold to long press").  As I think it helps show what focus I'm talking about, I have added a screenshot of the prototype app I built with the green TalkBack focus indicator below:

Questions:

*

*Is there a reason for why Android insists on announcing the "double tap and hold to long press" piece for a WebView?  If there is a functional reason for this, then any attempt to fix this issue may be moot.

*Does anyone know of a way to stop TalkBack from reading the "double tap and long press"?  Alternatively, is there a way to hide the WebView control itself from TalkBack without hiding the html content within?

What I've tried:
Unfortunately saw no luck setting isLongClickable to false, setting empty onLongClickListeners, and worked with a few of the suggestions in the stackoverflows here, here, here, and here.  I tried all of the mentioned changes on a blank app to reduce the possibility that the complexities of our production app has interfered with the experiments I was running.  Setting the ImportantForAccessibility field to "No" hides all of the inner html of the webview from Talkback so that is not an option either.
Sidenote that I find interesting:  in my experimentation, I also tried setting the WebView's isClickable property to false and yet it was still clickable.  So I am wondering if I am possibly focusing on setting properties on the wrong control (or if Android just completely ignores those properties on a WebView control).


text:
Q: How to ask sbt to only fetch dependencies, without compiling? Is there a way to only download the dependencies but do not compile source.
I am asking because I am trying to build a Docker build environment for my bigger project.
The Idear is that during docker build I clone the project, download all dependencies and then delete the code.
Then use docker run -v to mount the frequently changing code into the docker container and start compiling the project.
Currently I just compile the code during build and then compile it again on run. The problem ist that when a dependencie changes I have to build from scratch and that takes a long time.

A: Run sbt's update command. Dependencies will be resolved and retrieved.


text:
Q: Convergence in $L^p$ with given properties Let $p\in [1,\infty[$, $(\Omega, \mathcal A, \mu)$ be a probability space and $(f_n)_{n\in \mathbb N}$ be a sequence of measurable functions $f_n : \Omega  \to \mathbb R$ and $f:\Omega \to \mathbb R$ with the following properties:
$\forall \omega \in \Omega: f_n(\omega) \to f(\omega)$ and
$\sup_{n\in \mathbb N}\left \lVert f_n 1_{\{\lvert f_n \rvert > m\}}\right \rVert_p \to 0$ as $m\to \infty.$
Show that $$\lVert f_n - f \rVert_p \to 0.$$
I was able to prove one inequality:
We have $$0 = \int \lvert f-f|^p d\mu = \int \liminf_{n\to \infty} |f_n - f|^p d\mu \leq \liminf_{n\to \infty}\int \lvert f_n - f \rvert ^p d\mu = \liminf_{n\to \infty} \lVert f_n -f\rVert_p^p$$
by Fatous lemma. But how to prove the other direction? The second property is hard for me to understand. I tried to get a bound involving the measure of a set since $\mu $ is finite but feel like I need a hint.

A: I'll take $p=1$ for simplicity. Claim: $\{f_n\}$ is uniformly integrable.
Proof: Let $\epsilon>0.$ Choose $m$ such that $\int_{|f_n|>m} |f_n| <\epsilon/2$ for all $n.$ Set $\delta = \epsilon/(2m).$ If $\mu(E) < \delta,$ then
$$\int_E |f_n| = \int_{E\cap \{|f_n|\le m\}} |f_n| + \int_{E\cap \{|f_n|> m\}} |f_n| \le m\cdot \delta + \epsilon/2 <\epsilon.$$
This proves the claim. Fatou's lemma then makes it clear that $\{f_n\}\cup \{f\}$ is uniformly integrable. Hence $\{ |f_n-f|\}$ is uniformly integrable.
Let $\epsilon>0$ again. Choose $\delta >0$ such that $\mu(E) < \delta$ implies $\int_E |f_n-f| < \epsilon$ for all $n.$ By Egorov, there exists a set $E, \mu(E) < \delta,$ such that $f_n\to f$ uniformly on $\Omega \setminus E.$ Thus
$$\int_{\Omega} |f_n-f| \le \int_{\Omega \setminus E} |f_n-f| + \int_E |f_n-f| < \epsilon.$$
The first integral on the right $\to 0$ by uniform convergence and the fact that we're on a finite measure space. Thus $\limsup \int_{\Omega} |f_n-f| \le \epsilon.$ Since $\epsilon$ was arbitrary, we have $\int_{\Omega} |f_n-f| \to 0$ as desired.

A: Suppose $M_0 \ge 0$ such that $\sup_{n\in \mathbb N}\left \lVert f_n 1_{\{\lvert f_n \rvert > M_0\}}\right \rVert_p \le 1$.

*

*$(||f_n||_p)_n$ is uniformly bounded.
$$\sup_{n\in \mathbb N}\left \lVert f_n \right \rVert_p \le \sup_{n\in \mathbb N}\left \lVert f_n 1_{\{\lvert f_n \rvert \le M\}}\right \rVert_p + \sup_{n\in \mathbb N} \left \lVert f_n 1_{\{\lvert f_n \rvert > M\}}\right \rVert_p \le M_0 + 1$$

*$f \in L^p(\Omega, \mathcal A, \mu)$: due to pointwise convergence $f_n \to f$, $|f| = \lim\limits_{n\to\infty}|f_n|$, so $|f| = \limsup_n |f| \le \sup_n |f_n|$.
$$||f||_p \le \sup ||f_n||_p \le M_0 + 1$$

*$f_n \to f$ in $L^p(\Omega, \mathcal A, \mu)$:  For any $M>0$,
\begin{align}
& ||f_n - f||_p \\
&\le ||(f_n - f) 1_{\{|f_n-f| \le \epsilon\}}||_p + ||(f_n - f) 1_{\{\epsilon < |f_n-f| \le 2M\}}||_p + ||(f_n - f) 1_{\{|f_n-f| > 2M\}}||_p \\
&\le \epsilon + 2M \mu \{|f_n-f|>\epsilon\} + || (|f_n| + |f|) 1_{\{|f_n| \vee |f| > M\}} ||_p \\
&\le \epsilon + 2M \mu \{|f_n-f|>\epsilon\}
+ 2 \underbrace{|||f_n| 1_{\{|f_n|>M\}}||_p}_{|f_n| \text{ is larger}}
+ 2 \underbrace{|||f| 1_{\{|f|>M\}}||_p}_{|f| \text{ is larger}} \\
&\le \epsilon
+ 2 \underbrace{M\mu \{|f_n-f|>\epsilon\}}_{\substack{\text{convergence a.e implies} \\ \text{convergence in measure} \\ \text{in probability space}}} +
2 \underbrace{\sup_{n\in \mathbb N}\left \lVert f_n 1_{\{\lvert f_n \rvert > M \}}\right \rVert_p }_{\substack{\text{given: no escape from} \\ \text{vertical infinity}}}
+ 2 \underbrace{|||f| 1_{\{|f|>M\}}||_p}_{f \in L^p(\Omega,\cal A, \mu)}
\end{align}
Let $M > 0$ be sufficiently large so that

*

*$\sup_{n\in \mathbb N}\left \lVert |f_n| 1_{\{\lvert f_n \rvert > M \}}\right \rVert_p < \epsilon$

*$|||f| 1_{\{|f|>M\}}||_p < \epsilon$
Let $N \in \Bbb{N}$ be sufficiently large so that for all $n \ge N$, $\mu\{|f_n-f|>\epsilon\} \le \dfrac{\epsilon}{M}$
Hence, $||f_n - f||_p \le 7 \epsilon$ for all $n \ge N$.  This shows $f_n \xrightarrow[n\to\infty]{L^p(\Omega,\cal A, \mu)} f$
Remarks:

*

*Terence Tao describes the second property in the question body
as "no escape to vertical infinity".

*I've skipped one step to simplify writings of indicator functions.  Please refer to my discussions with saz in the comments below.

*We have actually proven the result with a weaker assumpion: convergence in measure $f_n \stackrel{\mu}{\to} f$ instead of convergence almost everywhere, based on the assumption that $\mu(\Omega) < +\infty$.

*

*The advantage of this approach is that we don't need almost everywhere convergence, which is necessary in order to apply Egorov's theorem.

*Dropping the condition $\mu(\Omega) < +\infty$ invalidates this answer as the RHS of
$$||(f_n - f) 1_{\{|f_n-f| \le \epsilon\}}||_p \le \epsilon \mu(\Omega)$$
is no longer finite.


text:
Q: QDialog as Popup does not hide on Mac when clicking out of the main window I have a basic QDialog with it's WindowFlags set to Qt::Popup so that it appears as a typical popup overlay.
On Windows, everything works great and if you click outside the main window or really anywhere else it goes away. But on Mac OSX, if you click the menu bar at the top or resize the window, the popup just stays where it is.  I have absolutely no internal handling of the mouse enter/leave/move/press events for the popup, so the closing of it is not something I'm even handling... it's just automatic on Windows.
Any idea I can get it to close when the main application is no longer the current context on the system?

A: You may install native event filter and to close active popup dialog (QApplication::activePopupWidget()) when user will click out of main window. See the following answer for information how to install native filter.


text:
Q: C# Detect Localhost Port Usage In advance, thank you for your advice.
I am currently working on a program which uses Putty to create a SSH connection with a server that uses local port forwarding to enable a client, running my software, to access the service behind the SSH server via localhost.
IE: client:20100 -> Internet -> Remote SSH server exposed via router/firewall -> Local Intranet -> Intranet Web POP3 Server:110.
Cmd Line: "putty -ssh -2 -P 22 -C -L 20100:intranteIP:110 -pw sshpassword sshusername@sshserver"
Client would use putty to create a SSH connection with the SSH server specifying in the connection string that it would like to tie port 110 of the Intranet POP3 Server to port 20100 on the client system. Therefore the client would be able to open up a mail client to localhost:20100 and interact with the Internal POP3 server over the SSH tunnel. The above is a general description. I already know what I am trying to do will work without a problem so am not looking for debate on the above.
The question is this...How can I ensure the local port (I cannot use dynamic ports, so it must be static) on localhost is not being used or listened to by any other application?
I am currently executing this code in my C# app:
private bool checkPort(int port)
{
    try
    {
        //Create a socket on the current IPv4 address
        Socket TestSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // Create an IP end point
        IPEndPoint localIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);

        // Bind that port
        TestSocket.Bind(localIP);

        // Cleanup
        TestSocket.Close();

        return false;
    }
    catch (Exception e)
    {
        // Exception occurred. Port is already bound.
        return true;
    }
}

I am currently calling this function starting with a specific port in a for loop to get the 'false' return at the first available port. The first port I try is actually being listened to by uTorrent. The above code does not catch this and my connection fails.
What is the best method to ensure a port is truly free? I do understand some other program may grab the port during/after I have tested it. I just need to find something that will ensure it is not currently in use AT ALL when the test is executed.
If there is a way to truly reserve the localhost port during the test, I would love to hear about it.

A: Here's the answer how to check if local port is free.
I would recommend this way:
bool IsBusy(int port)
{
    IPGlobalProperties ipGP = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] endpoints = ipGP.GetActiveTcpListeners();
    if ( endpoints == null || endpoints.Length == 0 ) return false;
    for(int i = 0; i < endpoints.Length; i++)
        if ( endpoints[i].Port == port )
            return true;
    return false;
}


text:
Q: Nothing happens when running python script from cmd I recently made a program in Python that I need to launch from the command line.
However, when I run it with "python my_script.py", nothing happens, as if the program was ran but it was empty. Here is an illustration
The 'test.py' file is a basic Hello World program. I started it in my editor , and it worked just fine.
I added python in my PATH as follows :

Python version is 3.7.6, I'm running W10x64 updated.
Does anyone know what the problem is ?
Thanks for your help !

A: From the Microsoft Dev Blog adding Python to the App store - in order to remove the windows store trigger, you need to change the app execution alias by going to Settings, Apps & Features, Manage App Execution Aliases. There you can disable the Microsoft Store alias for Python.

A: Installed Python with the Windows Store, that solved my problem.
As I had already Python installed outside the windows Store, it would be great to find a solution to use the installed python instead of the Store python when using cmd.

A: just had this issue and the solution was very simple. I had just installed vscode and I forgot I didn't have auto-save enabled. If anyone runs into this issue make sure you save your file before running it

A: I had this happen because I was developing using Anaconda. That is, I did not have a straight copy of python installed on my machine. Instead, I needed to start up the appropriate Anaconda environment in the command line and then run the program from there.
(env) C:\Users\UserName>python filename.py

A: It appears that with recent versions of windows the file association is used to determine which program  to be used. So exclude "python" and it should work.
(env) C:\Users\UserName>filename.py

reference:
https://realpython.com/run-python-scripts/


text:
Q: Radio group in devexpress grid control I need to use a radio group (rdoChargeOn) in a devExpress grid control (grdDisb).
I am getting the rows from stored procedure.
The problem that I have always the selected index of the radio group = -1 with value = 0.
Also if I create a new row the value is 0 with no selected item after click enter.
What is the equivalent of rdochargeOn.SelectedIndex in this case? can you help me please?
Kindly Find attached a print screen of the grid.
    Private _DisbList As BindingList(Of PropertyDisbursementList)
 _DisbList = New BindingList(Of PropertyDisbursementList)(obj.DisbList)
 GrdDisb.DataSource = _DisbList
 GrdDisb.RefreshDataSource()

rivate Sub BindDisbGrid()
        If RecordId <> -1 Then '' Import the list of disbursement
            _DisbList = New BindingList(Of PropertyDisbursementList)(obj.DisbList)
        End If
        _DisbList.AllowNew = True
        GrdDisb.DataSource = _DisbList
        GrdDisb.RefreshDataSource()
    End Sub
    Public Sub SaveDisbList()
        Try
            Dim disb As New PropertyDisbursementList
            Dim indx As Int32 = 0
            Dim CategName As String = ""
            Dim objWCF As WCFReference.PropertiesServiceProvider = GetServiceProvider()
            For i As Integer = 0 To GridView1.DataRowCount - 1
                If GridView1.GetRowCellValue(i, "CategId").ToString <> 0 Then
                    disb = _DisbList(i)
                    If RecordId <> -1 Then
                        disb.PropertyId = RecordId
                        disb.CategName = objWCF.Service.GetCatPropertyDisbursement(disb.CategId)
                        disb.RecordInfo = GetRecordInfo()
                        disb.PropertyId = objWCF.Service.SavePropertyDisbursementList(disb)
                    Else
                        disb.PropertyId = ProId
                        disb.CategName = objWCF.Service.GetCatPropertyDisbursement(disb.CategId)
                        disb.RecordInfo = GetRecordInfo()
                        disb.PropertyId = objWCF.Service.SavePropertyDisbursementList(disb)
                    End If
                End If
            Next
        Catch ex As Exception
            iMessage.ShowError(Nothing, ex)
        End Try
    End Sub

thx in advance,
Regards,
Hadil

A: Go through this DevExpress thread - Radio Group as Repository Item not working for multiple rows
As I can suspect about this issue may be that you have not added items to the RadioGroup controls that match the value of current cell of the grid.
check this example -
List<int> uncheckedID = new List<int>();

public Form2()
{
    InitializeComponent();
    gridControl1.DataSource = CreateTable(10);

}
private static DataTable CreateTable(int RowCount)
{
    Random rnd = new Random();
    DataTable tbl = new DataTable();
    tbl.Columns.Add("Name", typeof(string));
    tbl.Columns.Add("ID", typeof(int));
    tbl.Columns.Add("Number", typeof(int));
    tbl.Columns.Add("Date", typeof(DateTime));
    for (int i = 0; i < RowCount; i++)
        tbl.Rows.Add(new object[] { String.Format("Name{0}", i), i, i % 3, DateTime.Now.AddHours(i) });
    return tbl;
}
private void gridView1_CustomDrawRowFooterCell(object sender, DevExpress.XtraGrid.Views.Grid.FooterCellCustomDrawEventArgs e)
{
    e.Info.DisplayText = "Total value for " + gridView1.GetGroupRowValue(e.RowHandle).ToString() + " = " + e.Info.Value;
}

private void gridView1_ShownEditor(object sender, EventArgs e)
{
    ColumnView view = (ColumnView)sender;
    if (view.FocusedColumn.FieldName == "Number" && view.ActiveEditor is RadioGroup)
    {
        RadioGroup edit = (RadioGroup)view.ActiveEditor;
        //You can add the items at run time.
        edit.Properties.Items.AddRange(new DevExpress.XtraEditors.Controls.RadioGroupItem[]
        {
            new DevExpress.XtraEditors.Controls.RadioGroupItem(0, "Item 1"),
            new DevExpress.XtraEditors.Controls.RadioGroupItem(1, "Item 2"),
            new DevExpress.XtraEditors.Controls.RadioGroupItem(2, "Item 3")
        });
    }
}

Bind the values in the editor control using ShownEditor event of the grid so that it will set the selected item in group..
Hope this help


text:
Q: Doesn't work macros for environment variables in Windows 7 I have set JAVA_HOME variable
And also I have set path variable:
C:\>set java_home
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_38

C:\>set path
Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\To
rtoiseSVN\bin;%JAVA_HOME%\bin;C:\Program Files\apach\apache-maven-3.2.3\bin
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

C:\>java -version
'java' is not recognized as an internal or external command,
operable program or batch file.

C:\>

At this way java is not recognized.
Lets change a bit(replace %JAVA_HOME%\bin with C:\Program Files\Java\jdk1.6.0_38\bin):
C:\>set java_home
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_38

C:\>set path
Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\To
rtoiseSVN\bin;C:\Program Files\Java\jdk1.6.0_38\bin;C:\Program Files\apach\apache-maven-3.2.3\bin
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

C:\>java -version
java version "1.6.0_38"
Java(TM) SE Runtime Environment (build 1.6.0_38-b05)
Java HotSpot(TM) 64-Bit Server VM (build 20.13-b02, mixed mode)

For this way it is working good.
What do I wrong?

A: "%JAVA_HOME%\bin" is a perfectly valid directory name. cmd would need to evaluate its value before it could be used.
call set path=%path%

should work for you.

Expansion
path is loaded with the system value, then merged with the 'user' value, when any %var% in the path is replaced by its then-current value. If you add another %var% into the path (like for instance, as a "user" variable) then you need to re-evaluate to resolve the value.
The upshot is: set the path as a system variable, not a user variable if it contains a value to be resolved.


text:
Q: Logic behind Pandas LOC selecting values I am trying to learn and UNDERSTAND the logic behind pandas LOC and I can not come around with an explanation for the following issue.
If I want to slice the dataframe with LOC I can do it in the following way
dates=pd.date_range('20130101',periods=6)
df=pd.DataFrame(np.random.rand(6,4),index=dates,columns=list('ABCD'))

print(df.loc['20130102':'20130104',['A','B']])  (*)

All fine.
What I don't understand is that if in the second part of LOC I can entry a list of columns headers ['A','B'] why can't I do the same for the rows?
i.e. the following would not work
print(df.loc[['20130102','20130104'],['A','B']])

What is the logic behind? I am giving LOC two row indexes, and two columns headers, but it would not work. For the columns part a list is fine, for the rows part it's not.
Moreover,
in the first part of the LOC (see *) the indexes of the rows can be accessed with ":" i.e. from index1 to index2 = 'index1':'index2' but I can not do the same in part 2 of the LOC function:
this would not work:
print(df.loc['20130102':'20130104',['A':'C']])

I would be glad to understand why those two showed lines of codes are not working.
Thanks.

A: You need convert values of list to datetimes because DatetimeIndex, it means is necessary same types of values of list and values of index/columns of DataFrame, else KeyError:
print(df.loc[pd.to_datetime(['20130102','20130104']),['A','B']])
                   A         B
2013-01-02  0.719469  0.423106
2013-01-04  0.438572  0.059678

Selecting by first and last value of index/columns
Converting to datetimes is not necessary, because partial string indexing.
For select by range remove only list [] for selecting columns:
print(df.loc['20130102':'20130104','A':'C'])
                   A         B         C
2013-01-02  0.719469  0.423106  0.980764
2013-01-03  0.480932  0.392118  0.343178
2013-01-04  0.438572  0.059678  0.398044

Similar solution for selecting of datetimes:
print(df.loc['2013-01-02':'2013-01-04','A':'C'])
                   A         B         C
2013-01-02  0.719469  0.423106  0.980764
2013-01-03  0.480932  0.392118  0.343178
2013-01-04  0.438572  0.059678  0.398044

Combinations:
#select betwen start/end datetime and only columns A,C
print(df.loc['20130102':'20130104',['A','C']])
                   A         C
2013-01-02  0.719469  0.980764
2013-01-03  0.480932  0.343178
2013-01-04  0.438572  0.398044

#select only 20130102, 20130104 index and columns between A and C
print(df.loc[pd.to_datetime(['20130102','20130104']),'A':'C'])
                   A         B         C
2013-01-02  0.719469  0.423106  0.980764
2013-01-04  0.438572  0.059678  0.398044

A: This code explains the different ways to access data (slicing) with LOC in pandas:
df=pd.DataFrame(np.random.rand(6,4),index=['row1','row2','row3','row4','row5','row6'],columns=list('ABCD'))
         A         B         C         D
row1  0.972614  0.193116  0.448413  0.731300
row2  0.135391  0.783295  0.959058  0.107872
row3  0.966703  0.742793  0.852716  0.710681
row4  0.976819  0.920898  0.665329  0.078999
row5  0.418717  0.122677  0.716004  0.977522
row6  0.101422  0.641862  0.157751  0.888720

row_range  column_range:
df.loc['row1':'row3', 'A':'C']

            A         B         C
row1  0.972614  0.193116  0.448413
row2  0.135391  0.783295  0.959058
row3  0.966703  0.742793  0.852716

values_rows column_range:
df.loc[['row1','row3'], 'A':'C']
             A         B         C
row1  0.972614  0.193116  0.448413
row3  0.966703  0.742793  0.852716

row_range  column_values:
df.loc['row1':'row3', ['A','C']]
            A         C
row1  0.972614  0.448413
row2  0.135391  0.959058
row3  0.966703  0.852716

Single value:
df.loc['row1','A'])

0.972614309371533

conclusion: when using a range don't put it between []
But use the [] to include a list of values.


text:
Q: Hot to set route specific "global" styles in Vue.js I've just bought two Vue.js themes and I'm trying to put them together (one is like a presentation theme and the other is a dashboard theme). I managed to do most of the merging except the styles part. When declaring the *.scss and *.css of both themes in main.js they end up conflicting.
I've tried go through the documentation trying everything I found, like declaring the style files with  but the components inherit the style of the parent view, so they end up looking even worse than before.
From main.js:
Vue.use(VueRouter);
Vue.use(Presentation);
Vue.use(Dashboard);

From the presentation plugin:
import "vue-material/dist/vue-material.min.css";
import "@/assets/surface/scss/material.scss";
import "@/assets/surface/main.css";

The Dashboard plug-in has the same imports but with different files.
What I'm trying to do is have two global styles that I can assign to the different sets of routes (the presentation and the dashboard) but if someone has a better workaround I'm open to change.


text:
Q: Running NSStream in background Thread I'm currently trying to run my whole network stuff in a background thread, as it currently blocks the main thread, when the server is not reachable (i.e.).
I'm currently creating the network connection through the following code. Is there a simple way to run this in a new background thread?
An how can I throw back the received message to the main thread? An how can I send messages through the background thread?
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ipAdress, port, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[inputStream open];
[outputStream open];

A: here is a tutorial that does exactly what you're talking about. although it focuses more on audio streaming, but the principles are exactly the same (ie in terms of spawning a worker thread, having it talk with the parent thread etc etc).
the idea is simple.. you create a new thread and have it handle the streaming work, and then you schedule the stream reader with the run loop that belongs to the thread you just created. The stream will have callbacks that will be fired when ceratain events happen (ie you get some data, the connect times out etc).. in the callback methods you can alert or communicate with the mainthread (which is the thread that handles the UI).
Here is some code to point you in the right direction, but if you download the code from the above tutorial and follow through.. you'll get it:
// create a new thread
internalThread =
                [[NSThread alloc]
                    initWithTarget:self
                    selector:@selector(startInternal)
                    object:nil];
            [internalThread start];

// creating a stream inside the 'startInternal' thread*
stream = CFReadStreamCreateForHTTPRequest(NULL, message);

// open stream
CFReadStreamOpen(stream)

// set callback functions
// ie say: if there are bites available in the stream, fire a callback etc
CFStreamClientContext context = {0, self, NULL, NULL, NULL};
CFReadStreamSetClient(
        stream,
        kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
        ASReadStreamCallBack,
        &context);

// schedule stream in current thread runloop, so that we DON'T block the mainthread
CFReadStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);

// create the callback function to handle reading from stream
// NOTE: see where else in the code this function is named (ie CFReadStreamSetClient)
static void ASReadStreamCallBack
(
   CFReadStreamRef aStream,
   CFStreamEventType eventType,
   void* inClientInfo
)
{
    //handle events you registered above
    // ie
    if (eventType == kCFStreamEventHasBytesAvailable) {
        // handle network data here..
        ..
        // if something goes wrong, create an alert and run it through the main thread:
        UIAlertView *alert = [
            [[UIAlertView alloc]
                initWithTitle:title
                message:message
                delegate:self
                cancelButtonTitle:NSLocalizedString(@"OK", @"")
                otherButtonTitles: nil]
            autorelease];
            [alert
                performSelector:@selector(show)
                onThread:[NSThread mainThread]
                withObject:nil
                waitUntilDone:NO];
    }
}


text:
Q: Timezone conversion mysql funtion to c# How to convert convert_tz() in mysql to a c# function

A: edit:
Use TimeZoneInfo and choose zone by it's id (here's why and how to check them)

IMPORTANT - This data is not static. New time zones are introduced into Windows as the governments of the world make changes. This is ultimately why there are not authoritative pages listing them in the docs. Do not rely on any hardcoded list, but call TimeZoneInfo.FindTimeZoneById() yourself, or use TZUTIL.EXE /L to list them. The answers below are only but a snapshot of the data at the time they were reported. DO NOT COPY FROM HERE TO HARDCODE INTO YOUR APPLICATION!

Example of code:
var exampleTime = DateTime.SpecifyKind(DateTime.Now,DateTimeKind.Unspecified);

DateTime result = TimeZoneInfo.ConvertTime(exampleTime,
TimeZoneInfo.FindSystemTimeZoneById("Europe/London"),
TimeZoneInfo.FindSystemTimeZoneById("America/Denver"));

Before changes in question:
There's not such an overload for this method with such parameters.
TimeZoneInfo.ConvertTime overloads - documentation screen
Source: Microsoft Documentation

A: There are probably cleaner methods, but I keep a helper function that uses TimeZoneInfo(search the MS documentation to find the particular ID you need) in a custom TimeUtils class
public static DateTime ConvertToMST(DateTime dt)
{
    DateTime utc = dt.ToUniversalTime();
    return TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"));
}


text:
Q: How do thread specific pointers work Recently I have discovered the magic of boost thread specific pointers. After some research on thread safety I would like to know how exactly boost thread specific pointers work.However, I can't seem to find this in the documentation. Can anyone provide some insight on this or some detailed documentation?

A: From the Boost docs on thread local storage:

boost::thread_specific_ptr provides a portable mechanism for thread-local storage that works on all compilers supported by Boost.Thread. Each instance of boost::thread_specific_ptr represents a pointer to an object (such as errno) where each thread must have a distinct value. The value for the current thread can be obtained using the get() member function, or by using the * and -> pointer deference operators. Initially the pointer has a value of NULL in each thread, but the value for the current thread can be set using the reset() member function.

And you can find the Boost source here.


text:
Q: D member function attributes Consider:
class B
{
public:
    int i = 4;
}

class A
{
public:
    B b;

    this()
    {
        b = new B;
    }

    ref B f()
    {
        return b;
    }
}

The ref storage class in front of member function f is redundant right? Class objects are always passed by reference, so returning B and ref B is equivalent?
Second: pure member functions? A pure function is to return only something that depends on the arguments. It should thus not depends on any data members of the class, since they might change the output of the function even for the same arguments passed in. So a pure member function is consequently also a static member function? (the reverse might not be true)
Third: what is the difference between a const and an immutable member class? To differentiate between member function calls of immutable and const class objects? Semantically it is equal in that we can't change data members with both attributes, right?
Fourth: should I add as many function attributes as possible? Like pure, const or immutable, nothrow and final?

Awesome, just discovered this works:
inout(B) f() inout
{
    return b;
}

A: ref B f() is a function that returns B by reference. B is a class reference. Ergo, it returns a class reference by reference. This is not nonsense in D, because class references can be rebound:
auto a = new A;
a.f() = new B; // rebinds a.b, possible due to return by ref

Similarly, you can also have pointers to class references in D:
class A
{
    B b;

    /* ... */

    B* f()
    {
        return &b;
    }
}

auto a = new A;
B* b = a.f(); // pointer to reference to instance of class B
*b = new B; // updates a.b

For pure member functions, the implicit this reference parameter is just that - another parameter. It is considered part of the input. With the same this object and the same regular parameters, the output is still always the same.

With a const member function, you don't know if the this object is mutable or immutable. It could be either - the const member function promises not to mutate it anyway. With an immutable member function, the this object is always immutable. The this reference can thus be passed as an immutable argument to another function, or assigned to immutable variables.

When deciding when to care about const, immutable, pure and nothrow, you must consider whether or not you actually need these various guarantees in the client code. If you're writing a library for general use, you probably don't know this, so in these cases it's best to provide as many guarantees as possible.
The situation is arguably different for final. Use it when you don't want client code to accidentally override a function that doesn't make sense to override or isn't otherwise meant to be overridden, or when you want to give the compiler more opportunities to optimize calls to that function. Final functions that don't override any functions (with override) and don't implement any interface functions don't have to be virtual functions, reducing the call overhead.

A:
The ref storage class in front of member function f is redundant right? Class objects are always passed by reference, so returning B and ref B is equivalent?

Adding ref allows you to change the b field (the actual reference, not just its contents) by writing: a.f() = new B();

Second: pure member functions?

I believe that pure methods treat this as just another argument.

Third: what is the difference between a const and an immutable member class? To differentiate between member function calls of immutable and const class objects? Semantically it is equal in that we can't change data members with both attributes, right?

Yes, but the immutable version has stronger guarantees.

Fourth: should I add as many function attributes as possible? Like pure, const or immutable, nothrow and final?

Add as many attributes as you expect will be useful when using the code you're writing. (Note that the current implementation isn't very good at detecting redundant attributes.)

A:
so returning B and ref B is equivalent?

No. ref makes the function returns an lvalue, thus allowing:
auto a = new A;
auto b = new B;
b.i = 55;
a.f() = b;
writeln(a.b.i); // 55

pure member functions?

A member function can be considered a free function taking the instance as one of the parameters.
   class A { pure void f(int others) immutable; }
<=>
   class A { ... }
   pure void f(immutable(A) this, int others);

Thus, a pure member function can still read and modify (for weakly pure ones) this, as it is just one of the parameters.

what is the difference between a const and an immutable member class?

Not sure what do you mean ☺

should I add as many function attributes as possible?

You should add function attributes that best describes your function. If the function will never be overridden, then add final. If it will never throw any exceptions, then add nothrow, etc.
(BTW, pure, nothrow and @safe can be inferred if the function is a template function.)


text:
Q: Plesk publish asp.net mvc file or directory not found error my solution is work on my localhost  and ı can contact my remote db on plesk my local host its working
ım start my solution relase mode and zip this file and upload my plesk  and under httpdoc ım unzip  my files after that ım add a new line my webconfig in system.web but my preview and my website is dont works now i try to go previer go right path http://188.121.43.19/Home/Listele its my right path ı was redirect my index page this actionview but this page return 404
  <system.web>
  <trust level ="Full"/>

what is wrong ı cant find ım try to search logs but logs looks like fine for me if you want to look logs or any file  please say which logs or file  and ı wıll publish here or somewhere and put link here.
I'm stuck at this point, and I'd appreciate it if you could help.

A: Solved
in web.config in     add this
and remove everythink in   this tags


text:
Q: How to secure ELK and Filebeat? I have a server A on which I installed ELK by following the instructions :
https://www.digitalocean.com/community/tutorials/how-to-install-elasticsearch-logstash-and-kibana-elastic-stack-on-ubuntu-18-04
ELK can be accessed from the IP address of my server and I have created Let's Encrypt certificates to secure my domain on Nginx.
server {
    listen 80;
    listen [::]:80;
    server_name monitoring.example.com;

    location / {
        return 301 https://monitoring.example.com$request_uri;
    }
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name monitoring.example.com;

    auth_basic "Restricted Access";
    auth_basic_user_file /var/www/monitoring-example-com/web/.htpasswd;

    ssl_certificate /etc/letsencrypt/live/monitoring.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/monitoring.example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location / {
        proxy_pass http://localhost:5601;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

I have a server B that I want to monitor and on which I install Filebeat.
How to secure exchanges between ELK and Filebeat ?
Do I need to create an OpenSSL certificate or use the certificates generated with Let's Encrypt for Nginx ?

A: Do you use logstash in your pipeline or does filebeat output data directly into elasticsearch? Depending on this the answer changes slightly. Other aspects of your cluster setup also matter.
I'll assume that you are outputting data directly into elasticsearch.
The method you described with putting nginx in front of elasticsearch and doing basic authentication is OK for developer/test environment setup with one node cluster. I suspect this is all you want since you are monitoring just one server. If this is all you need you can stop reading.
You should however never use one node setup in production. Elasticsearch is a distributed storage and you should always use at least three nodes in production environments.
Why this matters when it comes to security? In multiple node cluster you have to secure both communication on REST API (default port 9200) and transport layer (the inter-node traffic default port 9300-9400). You may also want to be sure only trusted nodes are connected to the cluster. Nginx is not sufficient for this. One solution is to put the inter-node traffic into full mesh VPN that is setup between the cluster nodes. I recommend using tinc for this. The second is to setup TLS with one of the several security plugins available.
The best is to use both, because you'll probably also want not just encryption but also user management, role separation, audit logging etc.
There are several plugins you can use. The most obvious is to setup X-Pack Security. In this case please refer to the X-Pack documentation. The whole process is described there.
X-Pack is quite expensive. Luckily there are several alternatives the most prominent is searchguard. Community edition has missing a few features like LDAP or Field-level security, but it should be sufficient for most common use-cases. The documentation is not always straight forward, so I recommend doing a few test deployments.
Other alternatives include ReadonlyREST which has both enterprise and free version. Or the newest Open Distro this one is maintaining compatibility only with the OSS version of elasticsearch (it may break the basic licence features).
Edit: 11/18/2019
X-Pack under basic license now offers free basic security features. Pretty much same as searchguard community with addition that you can manage roles and users from Kibana GUI. My personal opinion is that now searchguard community is obsolete because X-Pack provides better features and you have one less dependency in your cluster, which makes updates and administration easier. For commercial use cases searchguard may still be the more sensible option especially for large clusters.

A: Check the following page which describes how to configure TLS to keep all data private from Filebeat -> Logstash -> Elasticsearch -> Kibana -> your web browser:

*

*TLS for the Elastic Stack: Elasticsearch, Kibana, Beats, and Logstash
Elasticsearch
Basically on Elasticsearch enable transport SSL (in elasticsearch.yml) as follow:
# Enables security.
xpack.security.enabled: True
# Enables transport SSL.
xpack.security.transport.ssl.enabled: True
xpack.security.transport.ssl.keystore.path: "certs/elastic-certificates.p12"
xpack.security.transport.ssl.truststore.path: "certs/elastic-certificates.p12"
xpack.security.transport.ssl.verification_mode: certificate
# Enables SSL via HTTP.
xpack.security.http.ssl.client_authentication: optional
xpack.security.http.ssl.enabled: false
xpack.security.http.ssl.keystore.path: "certs/elastic-certificates.p12"
xpack.security.http.ssl.truststore.path: "certs/elastic-certificates.p12"

For more details, read: Encrypting communications in Elasticsearch.
Filebeat
And enable TLS on Filebeat hosts. Example filebeat.yml:
filebeat.prospectors:
- type: log
  paths:
    - logstash-tutorial-dataset
output.logstash:
  hosts: ["logstash.local:5044"]
  ssl.certificate_authorities:
    - certs/ca.crt

Read more:

*

*Secure communication with Elasticsearch (to secure communication between Filebeat and Elasticsearch)

*Secure communication with Logstash (to secure communication between Filebeat and Logstash)

Logstash
Then you need to enable TLS in Logstash (if in use), example logstash.yml:
node.name: logstash.local
xpack.monitoring.elasticsearch.username: logstash_system
xpack.monitoring.elasticsearch.password: 'CHANGEME'
xpack.monitoring.elasticsearch.url: https://node1.local:9200
xpack.monitoring.elasticsearch.ssl.ca: config/certs/ca.crt

Read more: Secure communication with Logstash.


text:
Q: Open CV Vs NDK for Image processing I am writing a program to manipulate images,ie change its color,brightness,contrast etc...
The DVM doesn't support the manipulation of images of size beyond a limit...Can any one tell me whether using Open CV will solve the issue(as this seems to be a better option than NDK)?
Or will I have to use NDK?
I have done  a lot of search and was not able to find answer..

A: First of all, there are different options for Image processing in Android, see here for a comparison of the most popular options: see Android Computer Vision JavaCV OpenCV FastCV comparison and Image processing library for Android and Java
Coming back to your question: If the images you deal are really very large so that they do not fit into the memory of the device, you need to process the images in small chunks called tiles.
If your images are not that big, I recommend you to use OpenCv, if you have to do anything more than very simple tasks such as brightness/contrast adjustment.


text:
Q: Entity Framework Core with undefined/dynamic columns I have a db with some tables in which items contains some localized string. The plan is to have an ID to a dedicated "Localization" table.
public class User
{
   public int Id {get; set; }
   public string Name { get; set; }
   public Localization Signature { get; set; }
}

public class Item
{
   public int Id {get; set; }
   ...
   public Localization Title { get; set; }

}

public class Localization
{
   public int Id { get; set; }
   public string En { get; set; }
   public string Fr { get; set; }
   public string De { get; set; }
}

This works. But the goal is now to have a "dynamic" list of languages, so we could easy extend the localization to other languages.
I can solve this with a JSON field in which I serialize the languages string, but it has the disadvantage to lose the readability in any DB Viewer. So if possible, I would like to have real columns.
Is there any way to solve this use case with EF Core ?

A: I'd approach this not by adding columns to the database (which requires a change to the DB structure) but by adding rows:
public class Item
{
   public int Id {get; set; }
   ...
   public string Title { get; set; }

}

public class Localization
{
   public int Id { get; set; }
   public int ItemId { get; set; }
   public string LanguageCode { get; set; }
   public string Text { get; set; }
}

Then load item's title along the lines of:
item.Title = context.Localizations
    .Where(l => l.ItemId == item.Id && l.LanguageCode == "en")
    .FirstOrDefault();

(You can also load Title in the same query where you load Item... that query is meant to be illustrative of the concept).


text:
Q: Do I need cookies to get this to work? I want to use something like this code for changing background-color and text-color of my webpage.
It is useful for changing your header bg-color, color, and your menu drop down background-color and color. but NOT the color of the menu, or the top bar of the menu. Just affects the boxes that drop down, so neat code.
But if I want to "remember" the choice for my entire webpage, like have a user have the option to change color cheme, not changing stylesheets however, as I have stylesheets for different widths and heigths etc.
Do I have to use cookies, to do what I want here?
Purple COLOR Js
function greenColor(){     document.getElementById("content").style.backgroundColor = "purple";
            document.getElementById("copyW").style.backgroundColor = "purple";
            document.getElementById("text").style.backgroundColor = "white";

                            var parentElement =     document.getElementById("text");
            var lis = parentElement.getElementsByTagName("p");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","color: black");

            }

        var parentElement = document.getElementById("cssmenu");
            var lis = parentElement.getElementsByTagName("ul");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","background-color: purple");

            }

                            var parentElement =
document.getElementById("webpage");
            var lis = parentElement.getElementsByTagName("a");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","color: black");

    }
    }

RED COLOR Js
    function redColor(){
            document.getElementById("content").style.backgroundColor = "red";
            document.getElementById("copyW").style.backgroundColor = "red";
            document.getElementById("text").style.backgroundColor = "white";

                            var parentElement =     document.getElementById("text");
            var lis = parentElement.getElementsByTagName("p");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","color: black");

            }

            var parentElement = document.getElementById("cssmenu");
            var lis = parentElement.getElementsByTagName("ul");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","background-color: red");

            }

                        var parentElement = document.getElementById("webpage");
            var lis = parentElement.getElementsByTagName("a");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","color: black");

            }
            }

High contrast Js
function contrastColor(){
            document.getElementById("content").style.backgroundColor = "black";
            document.getElementById("copyW").style.backgroundColor = "grey";
            document.getElementById("text").style.backgroundColor = "black";
                var parentElement = document.getElementById("text");
            var lis = parentElement.getElementsByTagName("p");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","color: white");

            }

            var parentElement = document.getElementById("cssmenu");
            var lis = parentElement.getElementsByTagName("ul");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","background-color: black");

            }
                var parentElement = document.getElementById("webpage");
            var lis = parentElement.getElementsByTagName("a");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","color: white");

            }

            }
            function normalColor(){
            document.getElementById("content").style.backgroundColor = "green";
            document.getElementById("copyW").style.backgroundColor = "green";
            document.getElementById("text").style.backgroundColor = "white";
                var parentElement = document.getElementById("text");
            var lis = parentElement.getElementsByTagName("p");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","color: black");

             }

            var parentElement = document.getElementById("cssmenu");
            var lis = parentElement.getElementsByTagName("ul");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","background-color: green");

            }
                var parentElement = document.getElementById("webpage");
            var lis = parentElement.getElementsByTagName("a");
            for (var i = 0; i < lis.length; i++) {

            lis[i].setAttribute("style","color: black");

            }

            }

Then this is the Css
#buttons{
z-index:1;
display:inline;
border: none;
height:1em;
top:7.5em;
position:absolute;
right:0em;
}
#normal {
background:#008000;
background-size:cover;
cursor:pointer;
}
#purple{
    background:purple;
    background-size:cover;
    cursor:pointer;
    }
#red {
    background:#FF0000;
    background-size:cover;
    cursor:pointer;
    }
#contrast{
    background:black;
    color:white;
    cursor:pointer;
    background-size:cover;
    }

My html is simply a header, and a footer that changes color of the background, and then a High contrast version also, wich changes text color also, therefore I set "fallbacks", or chose to change it to black text color in javascript naturally.
Is it then, possible to change for my entire webpage, and then if I have to use cookies to do this, How do I set up the cookiething to have a choice of saving the color-sheme, or not, when the user chooses the color?
In advance thank you for any help:)
And is it possible to change style of css3-animations, in javascript, like i am doing with background color?

A: You don't have to use cookies. I would recommend using localStorage instead if you don't need the server to get involved with the user's color setting.

A: Yes you can do this with cookies.  But this might be something better for localStorage.  A couple benefits to localStorage are:

*

*localStorage has no expiration as opposed to cookies

*localStorage has a 5mb storage capacity.  This is significantly larger than cookies ~4kb

*localStorage is served up on the client side which removes extra http requests.

A: Use local storage to store the user's selected color. As an example, here is a working jsFiddle
jQuery
// add a handeler to a color picker element
$('#myColor').change(function() {

    // get the color from the changed picker
    var colorCode = $(this).val();

    // set the color to our header
    $("#myHeader").css("background-color", colorCode );

    // save the color to the browser's `localstorage`
    localStorage.setItem("colorCode", colorCode) ;
});

// when page loads, check if user has a colorcode stored in local storage
if (localStorage.getItem("colorCode") !== null) {

    // if so, set the color to our header and the picker
    var colorCode = localStorage.getItem("colorCode");
    $('#myColor').val( colorCode );
    $("#myHeader").css("background-color", colorCode );
}

HTML

Pick a color: <input type="color" id="myColor" value="#cccccc" />

CSS
#myHeader{
  height:100px;
  width:100%;
  background-color:#cccccc;
}

A: localstorage seemed to be the way to go, thanks.
When constructing the webpage thou, I have tried to make it mobile friendly..
My first thought was to have hidden(display:none), links, at the bottom of the page, since I have a hover menu in my webpage version.
This I then hide, when in mobile, and vica versa.
Is this a bad practice?
var parentElement = document.getElementById("cssmenu");
var lis = parentElement.getElementsByTagName("ul");
for (var i = 0; i < lis.length; i++) {
lis[i].setAttribute("style","background-color: black");

I have now learned, that I can easily use javascript, to hide and show menu, this is a better solution, since most people do have javascript enabled nowadays, right?
But then I come to mobile, and not everyone here have js, is this correctly assumed, or is js implemented in their systems?
I am thinking, I can alter the above code, to hide and show my 'ul', but naturally not hide the first ul, the menu it self.
This way, I want to keep my hover function in my desktop, but have an onclick in my mobile, seems much better to only hide that onclick button in the desktop version...
Now, it seems that any hover action I set in my desktop stylesheet, also effects my mobile-stylesheet.. I understand this is because it render's it all into one stylesheet, and naturally, it finds hover, and uses this in my android as well..
Is there any good way to solve this problem, I have naturally considered removing the hover effect, and have a clickable menu all around, seems mobile's make the hover in css kinda old-time, and I have also looked at :focus, and :active, but not considered active as much..
Is active the way to go here, and in that case, would I have to implement this in my menu-items somewhere?
var parentElement = document.getElementById("cssmenu");
var lis = parentElement.getElementsByTagName("ul");
for (var i = 0; i < lis.length; i++) {
lis[i].setAttribute("style","display: inline");

something like this is probably what I am looking for, I will experiment a little with it and see how it goes, but some pointers to what is the best practice, also for future, would be greatly appreciated :)


text:
Q: Bash ` &` behaviour inconsistent when there's a loop at the end of the script When I start up Linux Mint 19, I like to launch a few things.  So I've been using a script (./get-to-work) in a MATE Terminal window to launch them all at once:
chromium-browser --start-maximized &
thunderbird &
code -n path/to/my/workspace &

That works great.  I launch the script, close the terminal window, and the three programs continue running.
However, I recently added a line to open a big yellow window every five minutes (to remind me to sit up straight):
chromium-browser --start-maximized &
thunderbird &
code -n path/to/my/workspace &
for i in {1..1000}; do sleep 300 ; xterm -bg yellow -g 240x80 ; done

Now if I close the terminal I launched this in, the script is still running, and it gets killed, and then I don't get any yellow popups.  That's actually a feature for me--I keep the terminal open as long as I want popups, and close it, for example, when I'm screen-sharing.
For whatever reason, though, closing the terminal and killing the script not only stops the popup loop, it now closes Chromium and Thunderbird too.  VSCode (code) stays open.  Why?

A: What happens in the first case:
After the last command in the script is backgrounded, the shell executing the script exits immediately. This shell process was the parent process of the 3 programs started from the script. Now that their parent process has exited, the PID-1 process (init or systemd often nowadays) becomes their parent process.
The link between the terminal and the programs started from the script is gone, because the terminal program is not their (grand)parent process anymore.
What happens in the second case:
After the last backgrounded process, the script stays alive to run the loop. When the terminal exits, it sends SIGHUP to its child processes; the shell being its child, propagates this signal to its child processes (your programs).
The default action when a process receives a HUP signal is to exit. Apparently  VSCode ignores SIGHUP, or fork()s away from its parent process, so it is not affected.


text:
Q: Creating a custom list based off of a task list I have created a content type MyTask that is built ontop of task. The content type ID starts with 0x0108.
I want to create a custom list definition for my task in code. So I have created a List difention based on  my content type in Visual Studio.
I am then using this custom MyTask list in a workflow. However when I deploy my code I am getting the error:

Error occurred in deployment step 'Activate Features': The
  BaseTemplate property of the list is not 'Tasks'.

Looking at my Elements.xml for the list it looks like I should change the base type.

However when searching for the options of base type I can only seem to find:
Custom List 0
Document Library 1
Not used 2
Obsolete. Use 0 for discussion boards.3
Surveys 4
Issues List 5

How can I use my custom list with a workflow?

A: Just add the following attribute in 'ListTemplate' Type=107
for example
  <ListTemplate
      Name="NameOfYourListDefinition"
      Type="107"
      BaseType="0" />

This will resolve your problem.


text:
Q: How to deploy the best tuned model using sagemaker pipelines? I have trained an XGBoost model, finetuned it, evaluated it and registered it using aws sagemaker pipeline. Now I want to deploy the model. However, the location of the model artefact is saved as Join object because of which deployment is not working by best_model.deploy(...). Any suggestions on how to deploy the best trained model.
tuning_step = TuningStep(name="HPTuning",
                        tuner=tuner_log,
                        inputs={
                            "train":...,
                            "validation":...
                        },
                        cache_config=cache_config)

best_model = Model(image_uri=image_uri,
                  model_data=tuning_step.get_top_model_s3_uri(top_k=0,s3_bucket=model_bucket_key),
                  sagemaker_session=sm_session,
                  role=role,
                  predictor_cls=XGBoostPredictor)

register_step = RegisterModel(name="RegisterBestChurnModel",
                             estimator=xgb_estimator,
                             model_data=tuning_step.get_top_model_s3_uri(top_k=0, s3_bucket=model_bucket_key),
                             content_types=["text/csv"],
                             response_types=["test/csv"],
                             inference_instances=["ml.t2.medium", "ml.m5.large"],
                             transform_instances=["ml.m5.large"],
                             approval_status="Approved",
                             model_metrics=model_metrics)

The problem with best_model.deploy(...) is that tuning_step.get_top_model_s3_uri(top_k=0,s3_bucket=model_bucket_key) is a Join object. And deploy needs the s3 bucket location as a string. So that doesn't work.
I was also trying to deploy the registered model using
model_package_arn = register_step.properties.ModelPackageArn,
model = ModelPackage(role=role,
                     model_package_arn=create_top_step.properties.ModelArn,
                     sagemaker_session=session)
model.deploy(initial_instance_count=1, instance_type='ml.m5.xlarge')

which is giving me the error
...

/opt/conda/lib/python3.7/site-packages/sagemaker/model.py in _create_sagemaker_model(self, *args, **kwargs)
   1532             container_def["Environment"] = self.env
   1533
-> 1534         self._ensure_base_name_if_needed(model_package_name.split("/")[-1])
   1535         self._set_model_name_if_needed()
   1536

AttributeError: 'tuple' object has no attribute 'split'

Which I also suspect arise for the same reason.
I followed this tutorial pretty much
https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-pipelines/tabular/tuning-step/sagemaker-pipelines-tuning-step.ipynb

A: There are two ways to do this -
1/ Once you have registered the best model from the Tuning Job in the Model Registry, run your model deployment code through the Lambda Step. Here is an example of how to do that. Pass the output of the register step as the input of the Lambda step and call your model deployment code in the Lambda function.
2/ After your sagemaker pipeline executes and you have registered the model, use the registered model ARN from the Model Registry and call the deployment code. You can not use register_step.properties.ModelPackageArn outside the context of the Pipeline execution.


text:
Q: domain user not able to login with putty ssh A Domain user is not able to log in with putty(ssh). if I see logs I found this error. sshd[2059]: fatal: Timeout before authentication for.
domain joined with the realm.
Distributor ID: Ubuntu
Description:    Ubuntu 22.04.1 LTS
Release:        22.04
Codename:       jammy
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.1 LTS
Release:        20.04
Codename:       focal


text:
Q: Filemaker: behavior of portal rows I am creating a contacts database using FileMaker Pro 19.  Part of the relationship diagram is shown below:

For each Person record, I have zero or more Phone records, each corresponding to exactly one IDDCode record.
In the layout for editing Person records, I have a portal (with all default options) pointing to the Phone table.  In each portal row I have edit boxes for the Phone::Label and Phone::PhoneNumber fields, and a drop-down control with "Display data from" = IDDCode::DisplayCode and the "Values from" list set up as:

Hopefully it is clear enough what I am aiming for.  What actually happens is not even close to that.  Among the many unexpected behaviors:

*

*Changing one drop-down sets the value in all rows

*The values shown in the drop-down do not necessarily correspond to the values in the Phone table

*When I open the drop-down list, the highlighted default is off by one (e.g. if IDDCodeID is 39, the value for IDDCodeID 40 is highlighted)

*Some of the edit boxes are missing, e.g. the second row in the example image should have a phone number filled in

The portal does correctly display the existing (imported) data, though.  Here is an example of what I see when I try to use the layout:

QUESTION:
Obviously the way I have set this up is wrong (I am familiar with databases but brand new to Filemaker).  Rather than address the problems with my setup point by point, I am hoping to find out what is the right way to do this in Filemaker?


text:
Q: How to QueryOver a list of string in NHibernate I have a User model with below string list -
    private ISet<String> _mobileNumbers;

    public virtual ISet<String> MobileNumbers
    {
        get { return _mobileNumbers ?? (_mobileNumbers = new HashedSet<String>()); }
        set { _mobileNumbers = value; }
    }

I need to write a NHibernate QueryOver on this table to get a list of Users having a specific mobile number. Something like -
String mobileNumber = null;
Repository.QueryOver<User>()
            .JoinAlias(u => u.MobileNumbers, () => mobileNumber)
            .WhereRestrictionOn(() => mobileNumber)
                .IsLike(searchedMobileNumber, MatchMode.Exact);

I have thought of creating a Model for MobileNumber, or writing an SQL query which would do the same thing. But is there any other alternative??

A: Not supported in NHibernate QueryOver: see for example QueryOver - add restriction on primitive collection .
It is supported in "pure" HQL queries, as written for example in https://stackoverflow.com/a/23152387/613130 .


text:
Q: Connection error with node js while connecting to postgresql database I'm trying to connect to postgresql database using nodejs. I'm able to connect to only postgre instance in localhost or public ip. But i'm unable to connect to postgre instance in other machine of either the same or different network.What could be the reason.I even tried changing the pg_hba.conf file to listen to all ips even though the same error occurs

Error: connect ETIMEDOUT ip:port
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14).

What should i do to overcome this error? What could be the reason for this?