text:
Q: Send json data in Content of httpresponse in .net core API I am trying to insert multiple users in database using a API. Now, suppose there are three users to be inserted and assume that one user didn't get inserted but other two are suceessfully inserted. So, I have a requirement to show response which shows that user first is successfully inserted , user 2nd have an error. That is why I have useed list of httpResponseMessage and in each httpresponsemessageobject, I will add complete user json indicating that this was the user, who have failed or success status
So, as per my implementation
I am using foreach loop to insert multiple users in db and returning reponse like this but my respose from api do not shows "user" object in content:
public async Task<List<HttpResponseMessage>> InserUsers(JArray obj)
{
List<myDTO> users = obj.ToObject<List<myDTO>>();
List<HttpResponseMessage> list = new List<HttpResponseMessage>();
 foreach (var user in users)
{
    var response = Insert(user);
     list.Add(new HttpResponseMessage
                    {

                        Content = new StringContent(JsonConvert.SerializeObject(user), System.Text.Encoding.UTF8, "application/json"),
                        ReasonPhrase = response.ReasonPhrase,
                        StatusCode = response.StatusCode
                    });

}
return returnResposeList;
}

 public HttpResponseMessage Insert(User user)
{
     // do insert and if there is error

       return new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.Error,
                    ReasonPhrase = $"Error"
                };

     else
    {
          return new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                ReasonPhrase = $"Successfully inserted"
            };
    }
}

Thanks & regards

A: As per some of the comments, I don't understand why you need a status code for each insert rather than returning a bool or something like the inserted Id.
I think something like this works with what you have shown already along with return the user objects:
 public async Task<ObjectResult> InserUsers(JArray obj)
    {
        List<myDTO> users = obj.ToObject<List<myDTO>>();
        List<InsertUserResponseDto> list = new List<InsertUserResponseDto>();
        foreach (var user in users)
        {
            var isSuccess = Insert(user);
            list.Add(new InsertUserResponseDto
            {
                User = user,
                StatusCode = isSuccess ? StatusCodes.Status200OK : StatusCodes.Status500InternalServerError,
            });

        }

        var isSuccessfullInsert = list.Any(x => x.StatusCode == StatusCodes.Status207MultiStatus);
        return StatusCode(isSuccessfullInsert ? StatusCodes.Status207MultiStatus : StatusCodes.Status200OK, list);
    }

    public bool Insert(User user)
    {
        try
        {
            // Complete insert
            return true;
        }
        catch (Exception ex)
        {
            // Log Exception
            return false;
        }
    }

    public class InsertUserResponseDto
    {
        public User User { get; set; }
        public int StatusCode { get; set; }
    }

I have used the response code of 207 if any of the inserts fail otherwise I have used a 200. Each object within the list will contain the original user object along with an associated status code that you wanted including handling for success and failure.

A: For HttpResponseMessage, it used to describe the whole response, you should avoid returning HttpResponseMessage with multiple HttpResponseMessage.
For another option, you could try create your own HttpResponseMessage like
public class ApiResponseMessage
{
    //
    // Summary:
    //     Gets or sets the reason phrase which typically is sent by servers together with
    //     the status code.
    //
    // Returns:
    //     The reason phrase sent by the server.
    public string ReasonPhrase { get; set; }
    //
    // Summary:
    //     Gets or sets the status code of the HTTP response.
    //
    // Returns:
    //     The status code of the HTTP response.
    public HttpStatusCode StatusCode { get; set; }
    //
    // Summary:
    //     Gets or sets the content of a HTTP response message.
    //
    // Returns:
    //     The content of the HTTP response message.
    public object Content { get; set; }

}

And then
[HttpPost("InserUsers")]
public async Task<List<ApiResponseMessage>> InserUsers()
{
    List<User> users = new List<User> {
        new User{ Name = "Jack" },
        new User{ Name = "Tom"},
        new User{ Name = "Tony"}
    };
    List<ApiResponseMessage> list = new List<ApiResponseMessage>();
    foreach (var user in users)
    {
        var response = Insert(user);
        list.Add(new ApiResponseMessage
        {

            Content = new { user },
            ReasonPhrase = response.ReasonPhrase,
            StatusCode = response.StatusCode
        });

    }
    return list;
}

public ApiResponseMessage Insert(User user)
{
    // do insert and if there is error
    if (user.Name == "Tom")
    {
        return new ApiResponseMessage()
        {
            StatusCode = HttpStatusCode.BadRequest,
            ReasonPhrase = $"Error"
        };
    }
    else
    {
        return new ApiResponseMessage()
        {
            StatusCode = HttpStatusCode.OK,
            ReasonPhrase = $"Successfully inserted"
        };
    }
}


text:
Q: Editar usando o foreach (Editado) Boa noite. Tenho um formulário onde quero editar umas informações de um determinado setor. Sendo que os epis do select são um foreach do banco, porém quero que os que eu quero editar fiquem selecionados, porém, além de selecionar eles estão sendo duplicados. Segue o código:
<select title="Selecione os EPIs" multiple>

   <?php

      $epi_explode = explode(',', $result->setor_EPI);

      foreach ($epis as $epi)
      {
           foreach ($epi_explode as $epi_array)
           { ?>
              <option <?=$epi_array == $epi->epi_Nome ? 'selected' : '';?> >
                  <?=$epi->epi_Nome?>
              </option>

     <?php } } ?>

</select>

Controler:
    public function index()
{
    $data = array
    (
        'title' => 'Edição de Setores',
        'epis' => $this->setor_model->getEpis(),
    );

    $this->load->view('frame/cabecalho');
    $this->load->view('frame/navegacao');
    $this->load->view('setor/cadastro', $data);
}

Model da Query.
    public function getEpis()
{
    $this->db->select('*');
    $this->db->from('epi');
    return $this->db->get()->result();
}

Segue a imagem de como lista os resultados.

O select lista dos os equipamento de epi, porem quero que somente os que estão no banco de dados fiquem selecionados, pois isso é uma pagina de editar tal setor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automatically create new Google Drive folder from new files I currently have a Zapier process running that automatically creates 3 new files uploaded from a form into a folder in my Google Drive called "New Users". Each file is formatted as firstname_lastname-filename.ext but this is not good in terms of organization.
Instead, I would like to dynamically create a new folder labeled as firstname_lastname containing the 3 new files every time they come in with the same firstname_lastname, rather than having a generic "New Users" folder filled with hundreds or thousands of files.
Unfortunately I'm a pretty novice programmer, so I'm not quite sure how to go about this using Apps Script.
Any advice?
I've thought about something like:
var files = DriveApp.getFiles();
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName());
    if file.getName().includes("firstname_lastname") { // Check if a file name contains the string firstname_lastname
       var folders = DriveApp.getFolders();
       while (folders.hasNext()) {
          var folder = folders.next();
          Logger.log(folder.getName());
          if folder.getName().includes("firstname_lastname") { // Check if a folder exists with a name that contains the string firstname_lastname
              makeCopy(file.getName(), folder.getName()) // if said folder exists, make a copy of the the file and move it to that folder
          } else { // if said folder does not exist...
          var newFolderName = file.getName() // let the newFolderName be the same name as the file (I know this isn't right if I want the folder name to be firstname_lastname without the actual uploaded file name plus extension)
          createFolder(newFolderName); // then create a folder that has the name newFolderName
          makeCopy(file.getName(), folder.getName(newFolderName)) // then make a copy of the file and put it into the folder
        }
      }
    }
  }

A: You may want to first establish your root folder, "New Users". I've created a snippet for the flow:
//New Users Folder
var rootFolder = DriveApp.getFolderById("FOLDER_ID");

function myFunction() {
  var files = rootFolder.getFolders();
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName());

    if(file.getName() == fileuploadName){
    //copy file if folder is existing
      file.addFile(child)
    }
    else{
    //create folder
    var newFolder =  rootFolder.addFolder(child);
      newFolder.addFile(child)
    }
 }
 Logger.log("Done")

}

This flow should be ok when you want to implement a  dynamic creation of folder then migrate the files to a specific folder name.
Hope this helps.


text:
Q: Erased project from Project Explorer and cannot re-import it I erased a project from the Project Explorer, because I didn't think I had everything in the Workspace folder that it needed.  I was getting error messages.  When I got the complete project into the workspace folder and tried to re-import it I get this message: "Some projects cannot be imported because they already exist in the workspace."
The three folders of the project show up in the window, but are greyed out and cannot be selected.
Thanks to Arun and Francis below.... but new problem
OK. Great! Got passed that one deleting from hard disk and creating a new workspace folder. But now when I try to run it as an Android Application I get the message, "No compatible targets were found. Do you wish to add new Android Virtual device? And in the Console: "Failed to find an AVD compatible with target 'Google APIs'." I'm really new to this so thanks for whatever patience you have to answer newbie questions.

A: Try back up your project folder and delete the project completely from project explorer and from the hard disk. Make your backed up project folder into a zip file and try re-import it and recreate a separate project copy in your workspace. If this doesn't work, try switching workspace...... :)

A: So it sounds like the project is still there in the workspace, so try deleting it again. When you delete it, make sure you select the option "Delete files on the disk", this will actually remove the underlying file in addition to just removing the project definition from the workspace.
If you still have trouble (that is, the project is still there), delete the files from the workspace associated with the project by hand (in the operating system). And then Refresh the project and try deleting it from the workspace again (don't select the option to delete files on disk). It should be gone then.
Once the project is gone from the workspace and the underlying files are gone, try your import again.

A: If you use working sets, make sure they are all deselected. Only the projects from the current working set will display in Project Explorer. By having no working sets selected you can see all the conflicting projects in Project Explorer and delete them by hand. Then re-import.


text:
Q: Microsoft Outlook not displaying background-image I am using the joomla mail function. I have attached a background-image for the message body.
The image is displayed in all tools like: Gmail, Yahoo, Rediff etc.
But it does not show in Outlook 2007.
Seaching the internet, I did not get any information to let me know, wether the img tag is supported in Outlook

A: Background images are not supported in Outlook for any elements other than the body tag of an HTML email. The body of the email is not the same thing as it refers to the contents of the email and not the HTML body tag.
You might also look at this hack to enable background images in outlook - http://emailmarketingvoodoo.com/blog/post/outlook-2007-can-now-render-background-images/


text:
Q: Example of a nontrivial fiber bundle with total space compact, spin, and $p_1=0$ I would really appreciate if anyone could provide me with an example of a locally trivial, but globally nontrivial, fiber bundle $Y\hookrightarrow Z \rightarrow X$, where $X$, $Y$, and $Z$ are all compact spin manifolds with even dimension (preferably divisible by $4$) satisfying $p_1(Z)=0$, but $p_1(X)\neq 0$.

A: Sorry to be so late to the party, but I wanted to mention a general construction for these kinds of problems.
Given a compact Lie group $G$ and a closed subgroup $H\subseteq G$, the action of $H$ on $G$ by (say) right multiplication is free so gives rise to a principal $H$ bundle $H\rightarrow G\rightarrow G/H$.
Since $H$ and $G$ are Lie groups, they are parallelizable, so $H$ and $G$ are spin, have $p_1 = 0$, etc.
On the other hand, there are fairly straight forward methods of computing the topology (homotopy groups, cohomology ring, Stieffel-Whitney and Pontryagin classes) in terms of those of $H$ and $G$ and the embedding $H\rightarrow G$ (which are, at least when $H$ and $G$ are simply connected, quite well understood).
More generally, one can pick 2 homomorphisms $H\rightarrow G$ (equivalently, one homomorphism $H\rightarrow G\times G$ and use this to define and action on $G$ via $(h_1,h_2)*g = h_1gh_2^{-1}$.  This generalizes the previous construction (which occurs when the first homorphism is trivial).  These examples, when free, still have topology which is relatively computatable, but give an even larger class of examples to work with.
Then, for example, a simple example of what you're looking for is $U(2)\subseteq SU(3)$.  Here, $U(2)$ denotes the set of $2\times 2$ complex unitary matrices and $SU(3)$ denotes the set of $3\times 3$ complex unitary matrices with determinant $1$.  The inclusion sends $A$ to $\text{diag}(A,\overline{\det(A)})$.
It is fairly well known that in this case $SU(3)/U(2) = \mathbb{C}P^2$, which has nontrivial $p_1$.
So the bundle $U(2)\rightarrow SU(3)\rightarrow \mathbb{C}P^2$ is an example of what you're looking for.  Further, it's nontrival as $SU(3)$ is simply connected but $\pi_1(U(2)\times \mathbb{C}P^2) = \mathbb{Z}$.


text:
Q: Why is the MySQL query giving a syntax error I have the following query which I am running in MySQL:
CREATE TABLE BookingGuide (
    'ID_INT' INTEGER NOT NULL primary key AUTO_INCREMENT,
    'NAME' VARCHAR(60),
    'SPECIALTY' VARCHAR(60)
    ) ENGINE=INNODB;

I am receiving the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ID_INT' INTEGER NOT NULL primary key AUTO_INCREMENT,
     'NAME' VARCHAR(60),
 ' at line 2

How can I resolve the issue?

A: Get rid of the quotes around your column identifiers. Use ticks or nothing at all.
CREATE TABLE BookingGuide (
    ID_INT INTEGER NOT NULL primary key AUTO_INCREMENT,
    NAME VARCHAR(60),
    SPECIALTY VARCHAR(60)
) ENGINE=INNODB;

or
CREATE TABLE BookingGuide (
    `ID_INT` INTEGER NOT NULL primary key AUTO_INCREMENT,
    `NAME` VARCHAR(60),
    `SPECIALTY` VARCHAR(60)
) ENGINE=INNODB;

A: try this
     CREATE TABLE BookingGuide (
     ID_INT INTEGER NOT NULL primary key AUTO_INCREMENT,
     NAME VARCHAR(60),
     SPECIALTY VARCHAR(60)
     ) ENGINE=INNODB;

instead of single quote you need backticks.


text:
Q: How can I sort rows according minimum values and replace them in Pandas? Let's suppose I have a DataFrame :
import pandas as pd

dict1 = {'Name':['John', 'Sean', 'Philip', 'John', 'Sean', 'Philip'],
     'c_1':['a','b','c','d','f','g'],
     'c_2':[1,2,3,4,2,3],
     'c_3':[2,3,4,2,1,1]}

df = pd.DataFrame(dict1)

And output:
     Name c_1  c_2  c_3
0    John   a    1    2
1    Sean   b    2    3
2  Philip   c    3    4
3    John   d    4    2
4    Sean   f    2    1
5  Philip   g    3    1

Required output:
     Name c_1  c_2  c_3
0    John   a    1    2
1    Sean   f    2    1
2  Philip   g    3    1

I need to find a row with minimum values c_1 and c_2 for each name.
c_1 has high priority (it means that (c_1 = 1) & (c_2 = 2) is more important (and required) than (c_1 = 2) & (c_2 = 1)).
I tried to use loops, but it was unsuccessfully, because I have huge DF and my PC would do that for long time.
How can I do it in the most simplest way?
Thank you so much for answering!

A: You can use sort_values:
df.sort_values(['Name','c_2','c_3']).groupby('Name').agg('first')

       c_1  c_2  c_3
Name
John     a    1    2
Philip   g    3    1
Sean     f    2    1

If you want to preserve the order of the names, convert the column to a categorical:
df['Name'] = pd.Categorical(df.Name, categories=df.Name.unique())
df.sort_values(['Name','c_2','c_3']).groupby('Name').agg('first')

       c_1  c_2  c_3
Name
John     a    1    2
Sean     f    2    1
Philip   g    3    1


text:
Q: Vanilla Masonry + JQuery Flip I'm runnig RoR application with a wall of blocks using Vanilla Masonry, and each block in this wall could be flipped with JQuery Flip! plugin. The issue is that the length of contents on each side of the block could be different, so I want the wall positions reloading after each flip action, to avoid overlapping.
My code works one-way, when I flip the block for the first-time, but when I revert flipping, I encounter overlapping.
I initialize Masonry on load and here is my code for flipping-wall.js:
$(document).ready(function(){
    $('.sponsorFlip').bind("click",function(){
            var elem = $(this);
    var wall = new Masonry( document.getElementById('container'), {
                    gutterWidth:5,
                    isFitWidth: true
                  });

    if(elem.data('flipped'))
    {
        elem.revertFlip();
        elem.data('flipped',false);
                    wall.reload();
    }
    else
    {
        elem.flip({
            direction:'lr',
            speed: 350,
            onBefore: function(){
                elem.html(elem.siblings('.sponsorData').html());
            }
        });
        elem.data('flipped',true);
        wall.reload();
    }
});

});

Here is three steps:

Please, can you tell me what am I doing wrong.
Thanks guys.

A: As far as I can tell (tested on my localhost), after flipping is done you have to refer to already initialized Masonry object (instead of creating yet another instance) and reload it.
It could loook like this (put that in place of your onload function).
$(window).load(function() {
    // initialize Masonry - later on you will refer to this wall variable
    var wall = new Masonry( document.getElementById('container'), {gutterWidth:5, isFitWidth: true});

    $('.box').click(function() {
        var elem = $(this);

        // data('flipped') is a flag we set when we flip the element:

        if(elem.data('flipped'))
        {
        // If the element has already been flipped, use the revertFlip method
        // defined by the plug-in to revert to the default state automatically:

        elem.revertFlip();
        // Unsetting the flag:
        elem.data('flipped',false);

        }
        else
        {
        // Using the flip method defined by the plugin:

        elem.flip({
            direction:'lr',
            speed: 350,
            onBefore: function(){
                // Insert the contents of the .sponsorData div (hidden
                // from view with display:none) into the clicked
                // .sponsorFlip div before the flipping animation starts:

                elem.html(elem.siblings('.box').html());
            }
        });

        // Setting the flag:
        elem.data('flipped',true);

        }
            // reload already existing Masonry object
        wall.reload();
    })
})

P.S.
Using jQuery Masonry would save you some hassle as it can be embedded in head.


text:
Q: Prototype Javascript: getting an elements width as an integer for mobile version of my site, I need to change the size of my icons.
This way I give those Icons that are too small the class "icon".
Then I iterate all img.icon's and want to change their size:
$$("img.icon").each(function (e) {
  // what to do now? e.setStyle({width: (e.width * 2).toString() + "px"});
});

How do I get the width and height of an image in pixels as an integer?
Thanks, yours Joern.

A: Try this:
e.setStyle({width: (e.getDimensions().width * 2).toString() + "px"});

Also, like @clockworkgeek said, make sure to place the above code in a function that waits for the DOM to be loaded, and the image as well.


text:
Q: Downgrading/Partitioning Ubuntu I'm a new Ubuntu user running Ubuntu 20.04 and have been liking it so far. I have reached a dilemma now. I would like to learn Game Development via Unity Hub, a game engine requiring Ubuntu 18.04 or 16.04. I don't want to downgrade because I like this version and many other apps are 20.04 only. I want to know if I need to downgrade to 18.04, and if so, how do I partition both Ubuntu 20.04 and 18.04? I tried running Unity Hub but I can't get past the sign-in page. Thank you for your answers in advance!
Edit:
In more detail, I downloaded the Unity Hub from the Unity website for Linux (BETA), extracted the .tar file, and opened the .AppImage file to open the Unity Hub. It opens and shows a sign-in page. I hit sign-in and it opens a blank page on Chrome. For experiment, I hit create account and that signed me in on Chrome and showed my personal details, but the app did not refresh/redirect.
Sign-in Page
Blank Page from Unity Hub Sign-In

A: How to install Unity Game Engine in Ubuntu 20.04
In order to install Unity Hub in Ubuntu 20.04 you need to download the older Unity Hub AppImage file which unlike the newer Unity Hub .tar.gz file can also be installed in Ubuntu 20.04.
Download Unity Hub for Linux from here.  Select the Save File option and press OK. The UnityHub.AppImage file will be downloaded in the Downloads directory.  Every AppImage contains an app and all the files the app needs to run. For this reason the UnityHub.AppImage file can be installed in Ubuntu 20.04 despite the different system requirements (Ubuntu 16.04 or Ubuntu 18.04) of the newer Unity Hub .tar.gz file.

Once the file is downloaded, open the terminal, change directories to the ~/Downloads/ directory, make the AppImage file executable, and run the executable AppImage file.
cd ~/Downloads
chmod a+x UnityHub.AppImage
./UnityHub.AppImage

Read the Unity Terms of Service and agree to them.

The following message will be printed in the terminal after accepting the license.
License accepted
Checking for update
Generated new staging user ID: f97abfd4-1de8-a7e2-53b5-206e7050b831
Update for version 2.4.5 is not available (latest version: 2.4.5, downgrade is disallowed).
Checking for update
Found version 3.0.0-beta.6 (url: UnityHubBeta.AppImage)

Unlike version 2.4.5 UnityHub version 3.0.0 is a beta version.
If you are running Unity Hub for the first time, click Manage License in the bottom right corner and log into the Unity Hub through Google, Facebook, or Single.

Click Preferences and select the Installs option.

Add the Unity version by selecting the Add button.

Add modules to your install and click Done.

The selected Unity version and modules will install.

When the Unity version and modules install, click the Projects tab, and create a new project.

The Unity project will open, and you can start creating games using Unity immediately.
source: revised from How to Install Unity 2020.2.1f1 in Ubuntu 20.04


text:
Q: Removed features on openlayers 3 is re-rendered on zoom in/out In map I have Vector with Features inside, upon selecting some other options those features should be changed, therefore, I grab the map, select vector that I need, grab source from that map, and then I can remove feature. There are multiple ways that can be done:
this.map.getLayers().a[i].getSource().removeFeature(this.map.getLayers().a[i].getSource().B[2]);

or
this.map.getLayers().a[i].getSource().clear()

Where i is iteration through all layers.
In both cases, selected feature/features are removed from map. BUT if I try to zoom in/zoom out, that features that I have removed are re-rendered again. Is that some sort of cache? How can I remove them permanently?

A: Solution is that I have to clear vector source and also cluster source.
https://github.com/openlayers/ol3/issues/5437

A: could you please provide a jsfiddle with your example ?
Maybe try with map.render() after your clear() method but in my case, there is no issue with deleting features.


text:
Q: Layer error when changing platforms I am running an analysis of vegetation and fire over a 20 year period.
From 2020 - 2016, I have been using the Sentinel-2 imagery but from 2015 back to 1998 I need to use Landsat imagery.
The bands being used for the Sentinel imagery are: ['B12', 'B11', 'B8A','B8', 'B4', 'B3', 'B2'], for Landsat: ['SR_B7', 'SR_B6', 'SR_B5', 'SR_B4', 'SR_B3', 'SR_B2'].
All seems to go well until I try to set visualisation parameters and display the data.  The Sentinel code below works fine:
//  SET VISUALISATION PARAMETERS AND DISPLAY ON MAP
var visNDWI = {palette:['grey','green','blue'],min: 0, max: 0.3, bands: ['nd']};
var vis = {palette:['white','black'],min: -12000, max: 2000, bands: ['B12_1']};
var rgb_vis = {min: 0, max: 3000, bands: ['B12', 'B8', 'B3']}; // <---  *** CHANGE BANDS FOR RGB VISUALISATION ***
var rgb_vis2 = {min: -2000, max: 3000, bands: ['B12_1', 'B8A', 'B4']};
var filtMosaic = T1ndwi.mosaic();
var filtMosaicT2 = T2ndwi.mosaic();
Map.addLayer(filtMosaic.clip(roi), visNDWI, 'NDWI',false);
Map.addLayer(filtMosaicT2.clip(roi), visNDWI, 'NDWI T2',false);
Map.addLayer(filtMosaic, rgb_vis, 'RGB',false);
Map.addLayer(filtMosaicT2, rgb_vis, 'RGB T2',false);

However, when I modify it for Landsat imagery:
//  SET VISUALISATION PARAMETERS AND DISPLAY ON MAP
var visNDWI = {palette:['grey','green','blue'],min: 0, max: 0.3, bands: ['nd']};
var vis = {palette:['white','black'],min: -12000, max: 20000, bands: ['SR_B7_1']};
var rgb_vis = {min: 0, max: 20000, bands: ['SR_B7', 'SR_B5', 'SR_B3']}; // <---  *** CHANGE BANDS FOR RGB VISUALISATION ***
var rgb_vis2 = {min: -2000, max: 20000, bands: ['SR_B7_1', 'SR_B5', 'SR_B4']};
var filtMosaic = T1ndwi.mosaic();
var filtMosaicT2 = T2ndwi.mosaic();
Map.addLayer(filtMosaic.clip(darwin), visNDWI, 'NDWI',false);
Map.addLayer(filtMosaicT2.clip(darwin), visNDWI, 'NDWI T2',false);
Map.addLayer(filtMosaic, rgb_vis, 'RGB',false);
Map.addLayer(filtMosaicT2, rgb_vis, 'RGB T2',false);

I get an error message of:
Layer error: ImageCollection.mosaic: Error in map(ID=LC08_106069_20150511):
Image.select: Pattern 'SR_B7_1' did not match any bands.

I don't understand why using 'B12_1' doesn't give an error but using 'SR_B7_1' does.
I am relatively new to coding and Google Earth Engine so I'm hoping this is a simple error with a simple solution.


text:
Q: Can not include vlc library in java application i'm try to create media player for clients using vlcj with out need to install VLC in their PCs, from VLC.
i take this code from official site of VLC it work fine until i add EmbeddedMediaPlayerComponent() it get error
when i use

new NativeDiscovery().discover();

it work fine because i installed VLC in my PC
but when i use

private static final String NATIVE_LIBRARY_SEARCH_PATH = "C:\\Program
  Files\\VideoLAN\\VLC";
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(),NATIVE_LIBRARY_SEARCH_PATH);
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);

this is error log
14:49:08.471 [main]                  INFO                                                   uk.co.caprica.vlcj.Info - vlcj: 3.10.1
14:49:08.482 [main]                  INFO                                                   uk.co.caprica.vlcj.Info - java: 1.8.0_131 Oracle Corporation
14:49:08.482 [main]                  INFO                                                   uk.co.caprica.vlcj.Info - java home: C:\Program Files\Java\jre1.8.0_131
14:49:08.483 [main]                  INFO                                                   uk.co.caprica.vlcj.Info - os: Windows 10 10.0 amd64

 V: 2.2.6 Umbrella
14:49:08.831 [AWT-EventQueue-0]      DEBUG                uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent - args=[--video-title=vlcj video output, --no-snapshot-preview, --quiet-synchro, --sub-filter=logo:marq, --intf=dummy]
14:49:08.841 [AWT-EventQueue-0]      DEBUG                             uk.co.caprica.vlcj.player.MediaPlayerFactory - initX=null
14:49:08.853 [AWT-EventQueue-0]      INFO                                  uk.co.caprica.vlcj.binding.LibVlcFactory - vlc: 2.2.6 Umbrella, changeset 2.2.6-0-g1aae789
14:49:08.854 [AWT-EventQueue-0]      INFO                                  uk.co.caprica.vlcj.binding.LibVlcFactory - libvlc: C:\Program Files\VideoLAN\VLC\libvlc.dll
14:49:08.854 [AWT-EventQueue-0]      DEBUG                             uk.co.caprica.vlcj.player.MediaPlayerFactory - MediaPlayerFactory(libvlc=Proxy interface to Native Library <C:\Program Files\VideoLAN\VLC\libvlc.dll@1723334656>,libvlcArgs=[--video-title=vlcj video output, --no-snapshot-preview, --quiet-synchro, --sub-filter=logo:marq, --intf=dummy])
14:49:08.855 [AWT-EventQueue-0]      DEBUG                             uk.co.caprica.vlcj.player.MediaPlayerFactory - jna.library.path=null
14:49:08.856 [AWT-EventQueue-0]      DEBUG                             uk.co.caprica.vlcj.player.MediaPlayerFactory - VLC_PLUGIN_PATH=null
[00000000007ecfc0] core libvlc error: No plugins found! Check your VLC installation.
14:49:08.887 [AWT-EventQueue-0]      DEBUG                             uk.co.caprica.vlcj.player.MediaPlayerFactory - instance=null
14:49:08.888 [AWT-EventQueue-0]      ERROR                             uk.co.caprica.vlcj.player.MediaPlayerFactory - Failed to initialise libvlc
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Failed to initialise libvlc.

This is most often caused either by an invalid vlc option being passed when creating a MediaPlayerFactory or by libvlc being unable to locate the required plugins.

If libvlc is unable to locate the required plugins the instructions below may help:

In the text below <libvlc-path> represents the name of the directory containing "libvlc.dll" and "libvlccore.dll" and <plugins-path> represents the name of the directory containing the vlc plugins...

For libvlc to function correctly the vlc plugins must be available, there are a number of different ways to achieve this:
 1. Make sure the plugins are installed in the "<libvlc-path>/plugins" directory, this should be the case with a normal vlc installation.
 2. Set the VLC_PLUGIN_PATH operating system environment variable to point to "<plugins-path>".

More information may be available in the log.

at uk.co.caprica.vlcj.player.MediaPlayerFactory.<init>(MediaPlayerFactory.java:300)
    at uk.co.caprica.vlcj.player.MediaPlayerFactory.<init>(MediaPlayerFactory.java:259)
    at uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent.onGetMediaPlayerFactory(EmbeddedMediaPlayerComponent.java:349)
    at uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent.<init>(EmbeddedMediaPlayerComponent.java:217)
    at tutorial.Tutorial.<init>(Tutorial.java:68)
    at tutorial.Tutorial$1.run(Tutorial.java:49)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

can you help me to bundle up VLC to my project

A: The best solution for me was to write my own discovery strategy and bundle the VLC libraries with the application. This way, an installation of VLC is not required. Everything comes with the app.
Here's an example of a discovery strategy:
https://github.com/johndeverall/BehaviourCoder/blob/master/src/main/java/de/bochumuniruhr/psy/bio/behaviourcoder/BundledVLCLibsDiscoveryStrategy.java
You can probably use the linked class above unedited.
Here's a usage example:
final boolean found = new NativeDiscovery(new BundledVLCLibsDiscoveryStrategy()).discover();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Main(found);
            }
        });

In addition to this, you'll need to include the relevant VLC libraries on the classpath in the same way that they're included in the resources folder of the linked project.
https://github.com/johndeverall/BehaviourCoder/tree/embedded_video_libraries/src/main/resources/lib
Currently I've only got this working on windows, but if you can get it working for mac and / or linux I'd appreciate a PR!

A: I observed this issue with VLCJ - 3.10.1, JNA 4.1 combination.
I solved it by adding JNA 4.2 in my pom.xml file.
<dependency>
    <groupId>uk.co.caprica</groupId>
    <artifactId>vlcj</artifactId>
    <version>3.10.1</version>
</dependency>
<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna</artifactId>
    <version>4.2.0</version>
</dependency>

Then added VLC 2.2.6 library using below code.
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), System.getProperty("user.dir")+"/lib");
System.setProperty("VLC_PLUGIN_PATH",  System.getProperty("user.dir")+"/lib/plugins");

You can find code example here

A: Since I don't have comment privileges...
Is it possible you have more then 1 VLC installation installed?
The reason for asking is that a 64bit jdk/jre is not able to use a 32bit VLC installation and vice versa. Just guessing if it could be that VLCJ finds a incorrect version of vlc and then throws an error..just guessing here though.


text:
Q: Semantics of `errno` I tried searching the standards but couldn't find anything specific regarding errno.
What I mean is some implementations define errno as a global variable while some define it as a macro
#define errno (*_err_no())

The standard doesn't include it in the list of reserved keywords for identifiers.
This means that I should be able to use errno as a local variable. While it should be fine for the first implementation (that defines it as a global), the second one wouldn't be fine.
Is use of errno implementation defined or am I missing something?

A: From the latest C11 draft (N1570), 7.5 Errors <errno.h> (emphasis mine):

The header <errno.h> defines several macros, all relating to the reporting of error conditions.
The macros are
EDOM
EILSEQ
ERANGE

which expand to integer constant expressions with type int, distinct positive values, and which are suitable for use in #if preprocessing directives; and
errno

which expands to a modifiable lvalue that has type int and thread local storage duration, the value of which is set to a positive error number by several library functions.
  If a macro definition is suppressed in order to access an actual object, or a program defines an identifier with the name errno, the behavior is undefined.

This pretty clearly defines errno as a macro, and reserves its name in all scopes.

A: From the standard :

The  header <errno.h> defines  several  macros,  all  relating  to  the  reporting  of  error conditions.
The macros are
EDOM
EILSEQ
ERANGE

which expand to integer constant expressions with type int, distinct positive values, and which are suitable for use in #if preprocessing directives; and
errno

which  expands  to  a  modifiable  lvalue that  has  type int and  thread  local  storage duration, the value of which is set to a positive error number by several library functions.

(emphasis is mine)
So if the implementation defines error as *_err_no(), then _err_no() should return the location of that int, and *_err_no() accesses that location to be edited.

A: It is well defined by the C-Standard

7.5 Errors

*

*The header  defines several macros, all relating to the reporting of error
  conditions.

*2 The macros are
  EDOM
  EILSEQ
  ERANGE
  which expand to integer constant expressions with type int, distinct positive values, and
  which are suitable for use in #if preprocessing directives; and
  errno
  which expands to a modifiable lvalue201) that has type int and thread local storage
  duration, the value of which is set to a positive error number by several library functions.
  If a macro definition is suppressed in order to access an actual object, or a program
  defines an identifier with the name errno, the behavior is undefined.

*The value of errno in the initial thread is zero at program startup
  (the initial value of errno in other threads is an indeterminate
  value), but is never set to zero by any library function.202) The
  value of errno may be set to nonzero by a library function call
  whether or not there is an error, provided the use of errno is not
  documented in the description of the function in this International
  Standard.

*Additional macro definitions, beginning with E and a digit or E and
  an uppercase letter,203) may also be specified by the
  implementation.

Emphasis mine


text:
Q: Pass session information to PHP via curl What I'm trying to do is make the session from the client program available to the server program.
Both programs are running on the same Apache site, so the configuration for the session files, permissions, etc are all the same.
Test server program:
<?php
session_name('main');
session_start();
echo '<pre>'.print_r($_COOKIE, true).'</pre>';
?>

Test client program:
<?php
session_name('main');
session_start();
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_COOKIE, 'main='.session_id());
curl_setopt($ch, CURLOPT_POSTFIELDS, 'A=1&B=2');
$result=curl_exec($ch);
curl_close($ch);
echo $result;
?>

Behavior:

*

*As written, the curl call to the server times out.

*If I remove session_start() from the server, the server returns the cookie value as expected.

*When I remove curl_setopt($ch, CURLOPT_COOKIE, 'main='.session_id()) from the client every call to the server creates a new session file as expected.

*I added curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile) making sure that $cookiefile exists and is writable, no change in behavior.

So is this just not possible to do? I don't need to write any cookies or get cookie information back, I just need the server program to be able to access same session information as the client.

A: After a lot more searching I discovered the cause.  The client script has the session file locked, so the server session cannot read it, hence the time out.  More here: PHP Sessions - Locking and Sharing questions
So doing a session_write_close() in the client solves the issue, and leaves the $_SESSION variable intact, however if using session cookies and output has already happened (client) the session cannot be restarted on the client, so this solution will probably not work for me.
What I will probably need to do is serialize the session manually, put the information in a database table, and pass the key to the server which can read the table, then upon return I can pull the data from the table and update the session in the client.


text:
Q: Getting HtmlElement from document I want to get Element height from document, I am trying get it with const header = document.getElementsByClassName(myClass). But there some problems in conversion of Element to HTMLElement. Are there some ways for building HTMLElement from string or getting attributes like offsetHeight from HTMLCollection?
const myheader = document.getElementsByClassName(myClass);
console.info(myHeader[0].offsetHeight);

A: Yes you can use something like this to get offset height
document.getElementsByClassName('popup')[0].offsetHeight


text:
Q: Blur A Circle In Java I am writing a game in Java but have run in to an issue. I need to blur certain entitities within the game in order to create the right look. However, a lot of these objects are circular and so I am having issues blurring them properly.
Here is an example of the kind of thing I'm aiming for:

Currently, I'm using a box blur but just can't think of a way to achieve this sort of effect.
If somebody could give me a nudge in the direction I need to be looking that would be great.
Thanks.
Will


text:
Q: How to compile VLC 3.0.3 tarball on Arch Linux? I'm trying to report a VLC crash, but compilation fails:
$ ./configure CFLAGS="-g" CXXFLAGS="-g" --enable-debug && make
[…]
  CC       codec/libx264_plugin_la-x264.lo
In file included from ../include/vlc_fixups.h:31,
                 from ../config.h:907,
                 from codec/x264.c:29:
/usr/include/features.h:381:4: warning: #warning _FORTIFY_SOURCE requires compiling with optimization (-O) [-Wcpp]
 #  warning _FORTIFY_SOURCE requires compiling with optimization (-O)
    ^~~~~~~
codec/x264.c: In function 'Open':
codec/x264.c:849:26: error: 'x264_bit_depth' undeclared (first use in this function); did you mean 'x264_picture_t'?
         const int mask = x264_bit_depth > 8 ? X264_CSP_HIGH_DEPTH : 0;
                          ^~~~~~~~~~~~~~
                          x264_picture_t
codec/x264.c:849:26: note: each undeclared identifier is reported only once for each function it appears in

There doesn't seem to be an x264 library package:
$ pacman --sync --search x264
extra/x264 2:155.r0a84d986-2 [installed]
    Open Source H264/AVC video encoder

How do I get past this step? I've already installed all the build dependencies of the vlc-git AUR package.

A: Based on @jasonwryan's comments I was able to modify the official VLC 3.0.3 PKGBUILD to build a debug version of VLC. The PKGBUILD diff:
$ diff PKGBUILD{.orig,}
125c125
<   export CFLAGS+=" -I/usr/include/samba-4.0"
---
>   export CFLAGS+=" -I/usr/include/samba-4.0 -g"
127c127
<   export CXXFLAGS+=" -std=c++11"
---
>   export CXXFLAGS+=" -std=c++11 -g"
222c222,223
<               --with-kde-solid=/usr/share/solid/actions/
---
>               --with-kde-solid=/usr/share/solid/actions/ \
>               --enable-debug

Unfortunately this was not enough to provide enough information to the developers.


text:
Q: Remove node from percona xtradb cluster I have a 5 node cluster.  When I run backups it locks the entire cluster. I use DDL statements in a stored procedure that is used heavily.  What I am trying to achieve is taking one node out of the cluster.  Running the backup then adding the node back to the cluster.
How do I remove a node from a cluster?
 set wsrep_cluster_address = gcomm://192.168.2.59,192.168.2.60,192.168.2.61,192.168.2.62

Leaving the the node I want to backup out of the update.
On the node I want to backup do I set wsrep_cluster_address:
 set wsrep_cluster_address = gcomm://

Do I change the cluster name on the node as well?

A: I wouldn't remove the node, it's sufficient to desync it from the cluster:
SET GLOBAL wsrep_desync=ON;

Then do the backup. Then:
SET GLOBAL wsrep_desync=OFF;

When a node is desynced, it will remain part of the cluster. The node will receive transactions, but not process them. Flow control is disabled, which allows the node to fall behind the cluster. Once we turn off desync again, it will process the queued up transactions.
During desync, the status variable wsrep_cluster_size doesn't change, and the node itself will have wsrep_connected=ON, wsrep_ready=ON as before. However, it will also have wsrep_local_state_comment='Donor/Desynced'.
For your DDL statements, I think your options are:

*

*pt-online-schema-change

*wsrep_OSU_method = RSU

*wsrep_OSU_method = NBO


text:
Q: Can someone define or explain the ABSTRACT role category in WAI-ARIA? The W3C categorizes WAI-ARIA roles into four groups:

*

*Abstract Roles

*Widget Roles

*Document Structure Roles

*Landmark Roles

Can someone explain the Abstract Roles category?

A: It does say in the spec:

Abstract roles are the foundation upon which all other WAI-ARIA roles
  are built. Content authors MUST NOT use abstract roles because they
  are not implemented in the API

Essentially, they are a behind-the-scenes thing, and the useful roles (widget, document, landmark) inherit properties from the abstract roles.
If you look at the taxonomy diagram, the abstract roles are at the top of the tree, and other roles inherit from those.


text: Q: Is there any method to clear web browser console, every time browser get a response.(without page reloading) Instead of clear the web console output using the inbuilt button or calling clear() method of the browser and without reloading the page, is there a way to clear web browser console output (chrome/firefox) when the browser gets a response from backend? So in this case, at a particular time console output is relevant only most recent response. Thank you!


text:
Q: MySQL driver for EF6 returns wrong identity after insert I am using EF6 and MySQL.Data v6.9.5 to connect to a MySQL database. When I insert a record, call db.SaveChanges() and reference the record's ID column, I get what looks like a valid ID, but for some reason the ID will change in the database.
Sample Code
var res = db.SampleRegs.Add(sample);
        try
        {
            db.SaveChanges();
            //now, to fire a trigger, we need to UPDATE the table and set Saved = 10; (trigger fires on UPDATE when Saved = 10).
            db.Entry(res).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
            //Now set Saved = 20 to fire another trigger
            System.Threading.Thread.Sleep(100);//because reasons
            res.Saved = sbyte.Parse("20");
            db.Entry(res).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
        }

When I put a breakpoint on res the ID field would e.g. have a value of 128990. But when I later inspect the MySQL table directly, it will have a different ID value, which seems to always be 100 to 200 less, e.g. 12880.
I have no idea what's going on here because I can't replicate this behaviour in our development and testing environment db's, but when I move to production, this happens. I know the production DB handles a large volume of data in the specific table, if that matters at all.


text:
Q: conemu Log console output option not working I have just installed the 64bit version of ConEmu-Maximus5 (ConEmuSetup.160609.exe) on Windows 10 64bit.  I went to Settings/Features and ticked: 'Log console output (*)', which has the default value of:  %ConEmuDir%\Logs\
I went to Settings/Startup/Environment and confirmed that the option to Add %ConEmuDir% ot %PATH% was ticked, and the textbox had the correct default value of:  set PATH=%ConEmuBaseDir%\Scripts;%PATH%
I then saved the settings and shut down the ConEmu console.  I then started a new ConEmu console and ran a program that printed a heap of lines out to the console.
I then went to C:\Program Files\ConEmu, but there was no Log directory there.
I then created one and ran the console program again, but no log file was created.
What am I doing wrong here... how come the output is not being logged as the documentation says it should be?
Thanks for your time.

A: Well I did two things to get this to work.
In Windows 10 I check the:
Control Panel/System/Advanced System Settings/Environment Variables/

and could not see the ConEmu in the path, or the %ConEmuDir% variable, so I added these.
Then when I restarted the console it showed the log file URL but said Access Denied in the console on startup.  I then restarted it in Admin mode and the log file was created.
Hopefully this saves someone else some time ;)


text:
Q: Is it possible to create SwiftIO Namespace programmatically? I am creating scrollview as follows and I want to go requested button in array
using Namespace variable.
I saw it used to to go to bottom or top of scrollview but Namespace variables created manually. Because I want to go any button might requested I want to create Namespace
for every item in scrollview not only for top or bottom one.
Is it possible to create Namespace ID using index somehow valueIndex in that case.
I hope it would be something like that selectIndex as Namespace.
     ScrollViewReader { proxy in
                            ScrollView(.horizontal, showsIndicators: true){
                                LazyHStack() {
                                    ForEach(0..<listValues[valueIndex].count, id: \.self) { selectIndex in

                                        Button(action: {

                                            dump(selectIndex)

                                        }){
                                            Text(listValues[valueIndex][selectIndex])
                                                .foregroundColor(Color.white)
                                                .background(Color.red)
                                                .frame(width: w2 * 0.5 * 0.5, height: 40)
                                        } .id(**selectIndex as Namespace**)

                                    }.background(Color.gray)

                                }
                            }.frame(width: w2 * 0.5 * 0.5, height: 40)
                        }

A: You don't need a NameSpace in a ScrollViewReader, you just need to use any Hashable to identify the place you want to scroll to. You didn't give a  Minimal Reproducible Example (MRE), and I couldn't find a straightforward scroll to answer, so I made a basic one to show you how it is done. Please see the comments.
// You should always use an Identifiable in a ForEach. For
// a `scrollTo()`, you only need a `Hashable` `.id()`, so
// this struct has been conformed to Hashable.
struct ScrollItem: Identifiable, Hashable {
    let id = UUID()
    var name: String
}

struct ScrollToView: View {
    let scrollItems: [ScrollItem] = Array(0..<100).map( { ScrollItem(name: "Row " + $0.description) })
    @State var selectedItem: ScrollItem?

    var body: some View{
        ScrollViewReader{ scrollReader in
            VStack {
                // This button scrolls the selected row to the top, or as high as it can go
                Button {
                    withAnimation {
                        scrollReader.scrollTo(selectedItem, anchor: .top)
                    }
                } label: {
                    Text(selectedItem != nil ? "Scroll \(selectedItem!.name) To Top" : "Select Row")
                }

                List {
                    // ScrollItem is Identifiable, so you do not need to designate id:
                    ForEach(scrollItems) { item in
                        Text(item.name)
                            .padding()
                            .frame(maxWidth: .infinity, minHeight: 50, alignment: .leading)
                        // If the row is selected, this gives a colored background
                            .background(
                                RoundedRectangle(cornerRadius: 15)
                                    .fill(selectedItem == item ? Color.yellow.opacity(0.4) : Color.clear)
                            )
                            .contentShape(RoundedRectangle(cornerRadius: 15))
                        // This allows you to select and deselect the row
                            .onTapGesture {
                                if selectedItem == item {
                                    selectedItem = nil
                                } else {
                                    selectedItem = item
                                }
                            }
                        // ScrollItem conforms to Hashable, so it can be used as the .id()
                            .id(item)
                    }
                }

                // This button scrolls the selected row to the bottom, or as low as it can go
                Button {
                    withAnimation {
                        scrollReader.scrollTo(selectedItem, anchor: .bottom)
                    }
                } label: {
                    Text(selectedItem != nil ? "Scroll \(selectedItem!.name) To Bottom" : "Select Row")
                }
            }
        }
    }
}


text:
Q: Is there any library to fetch current time of any location from other servers? I want to get the local time of logged in user based on the location. I want a library which connects to any Universal Time server (Google etc.) and returns the current time of the location passed as parameter.
One alternative I have is to stored time difference in a SQL Server table and calculate the actual time from the UTC Time of the logged user. But this approach won't give accurate results and I also doubt on how it will work.

A: TimezoneDb provides a free API: http://timezonedb.com/api
GenoNames also has a RESTful API available to get the current time for a given location: http://www.geonames.org/export/ws-overview.html.
You can use Greenwich, UK if you'd like GMT.

A: Why do you need to store time differences in the database? You've already got their timezones, just add their GMT difference to DateTime.UtcNow.

A: how about getting the function DateTime.Now in you login page? are you using this as a TimeStamp of some sort?


text:
Q: Invalid Thread Access when create a Vaadin Composite I followed the steps in http://vaadin.com/eclipse :

You can create a CustomComponent based compositions and edit them with
  the visual designer tool included with the plug-in.
Select File -> New -> Other... Select Vaadin Composite from the dialog
  Click on the Design tab below the code editor to switch to the visual
  designer

But the eclipse throws the:

Invalid Thread Access

error.
I searched this issue into vaadin, but the one related was https://vaadin.com/forum/-/message_boards/view_message/665040 and it wasn't useful for me.
Someone knows how to correct this problem?
Jas

A: Check to see if the class file you are trying to create already exists. If so, you can right click on it in the Project Explorer and say "Open With -> Vaadin Editor" to access the visual designer tab. Or try "File -> New - > Other -> Vaadin Composite" but use a different package or class name.
(The first time I used the Vaadin composite wizard I got an error that Mozilla XULRunner was not installed. After installing it, I tried to create the composite again and got the same "Invalid thread access" error that you received. Of course, it turned out that the component already existed and I was trying to create a duplicate, hence the (unhelpful) error.)


text:
Q: Change variables between scenes unity I have a scene where I write down my player stats. In the next scene (basically in the next 2 scenes but it doesn't matter) I want to buy some weapons and change the variables.
The thing is I'm saving the object with "DontDestroyOnLoad" and when I go to the next scene I want to find out how can I change the variables.
First Scene:

The code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class statsTextsToDisplayAndChanges : MonoBehaviour
{
    public static statsTextsToDisplayAndChanges _INstance;
    buyWeapons bw;
    public Text m_LevelText;
    public Text m_AttackText;
    public Text m_DefendText;
    public Text m_MoneyText;
    public int level = 0;
    public int money = 500;
    public int health = 400;
    public int attack = 10;
    public int def = 5;
    string answer;
    string url = "http://alex3685.dx.am/display.php";

    public int sword1 = 200;

    public void Start()
    {

        _INstance = this;
        DontDestroyOnLoad(this.gameObject);

        display();

    }

    public void display()
    {

        m_LevelText.text = level.ToString();
        m_AttackText.text = attack.ToString();
        m_DefendText.text = def.ToString();
        m_MoneyText.text = money.ToString();
    }

    public void onPurchase()
    {
        if (money >= sword1)
        {
            Debug.Log("YOU BOUGHT IT");
            money -= sword1;
            //Destroy(GameObject.Find("playerStats"));
            display();
        }
    }

}

Second scene:

When I press the button the debug.log from the purchase function works but in the text nothing changes (from 500 coins-200 coins of the sword=300 coins).

Any ideas?
Thanks in advance.

A: Hmmm....initial thoughs:
This is one of the times where you want a true manager object with a scrip attached that only knows how to store the relevant stat.
Then, in whatever scripts that handles the purchasing they have a private GameObject with a reference to the manager object.private GameObject _Manager;

But the object exists in another scene in my editor so I cant drag and drop the reference!

No problem,
Lets say that the object with the component that stores the stats are called "PlayerManager". In the script that handles the purchasing in the start() method add: _Manager = gameobject.Find("PlayerManager");
Now you can change all the variables to your hearts content, assuming of course that you have set the variables in the manager to be public, or if you are more advanced and concerned about robust code, you have the proper get;set; methods in place.
Hope this helped!

A: Use PlayerPrefs to save and retrieve data.
Source : https://docs.unity3d.com/ScriptReference/PlayerPrefs.html


text:
Q: Git: multiple branches deployment workflow I'm trying to understand how to best improve my workflow when working with multiple branches each of which will deploy to a specific environment.
Let's start by saying I'm using BitBucket to host my git repository and I have three branches on it: origin/master, origin/staging and origin/production.
Whenever I complete a new task I commit the task to my local branch master and then I push it to origin/master. After that if I want to deploy that commit to staging I simply open the branches and run a "sync" (using the BitBucket feature) so that the branch origin/staging matches with origin/master.
However, when I look at the repository on SourceTree it feels like I made a mess and that this is probably not the correct way of doing it.
This is how the repository looks like on SourceTree:

And this is how it looks on BitBucket:

First of all: Why does it say that origin/production and origin/staging are respectively 4 and 6 commits ahead of origin/master?
Secondly, if what I'm doing is wrong/can be improved, what would you suggest me to do?

A: production and staging are ahead of your master branch because there are merge commits that are not present in master. You can easily see this in your SourceTree screenshot: origin/production is four (merge) commits ahead of master, the four commits with the Merged master into production message. It's similar with your staging branch.
You get into this situation because you repeatedly merge your master branch into the other branches, but never merge the other branches back into master. This is not wrong. As long as the "Ahead" count does not bother you, you're all set. If you prefer to have no commits ahead of master, you can just merge production and staging back into master. This will not change anything of your data, the merge commits will just become part of your masters' history as well.


text:
Q: JWT: How to get a List of Values from a specific Key in the Claims. C# Asp.Net Core I am using this piece of code to read a single value from the claims in the JWT.
return httpContext.User.Claims.Single(x => x.Type == "id").Value;

to get the value of this claim:
"id": "b6dddcaa-dba6-49cf-ae2d-7e3a5d060553"

However, I want to read a key that has multiple values.
But with the same code:
return httpContext.User.Claims.Single(x => x.Type == "groups").Value;

for this claim:
  "groups": [
    "123",
    "234"
  ],

I logically get the following error message:
System.InvalidOperationException: "Sequence contains more than one matching element"

I can't find the corresponding method. Can someone help me?

A: It is because of Single(), use Where() instead of Single()
return httpContext.User.Claims
          .Where(x => x.Type == "groups")  //Filter based on condition
          .Select(y => y.Value);  // get only Value

Single(): It returns a single, specific element of a sequence. It throws an error if there are multiple elements found which satisfies the condition

A: Reference ClaimsPrincipal.FindAll(Predicate<Claim>)

Retrieves all of the claims that are matched by the specified predicate.

IEnumerable<Claim> claims = httpContext.User.FindAll(x => x.Type == "groups");
IEnumerable<string> values = claims.Select(c => c.Value);
return values;


text:
Q: If $p,q \in B(\mathcal{H})$ are projections and $q\mathcal{H} \subset p\mathcal{H}$, show that $p\mathcal{H} = q\mathcal{H} \oplus (p-q)\mathcal{H}$. I was given the question: If $p,q \in B(\mathcal{H})$ are projections such that $q\mathcal{H}\subset p\mathcal{H}$, show that $p-q$ is a projection with $p\mathcal{H}= q\mathcal{H}\oplus (p-q)\mathcal{H}$.
Is my proof below rigorous enough?
If $q\mathcal{H}\subset p\mathcal{H}$, then $p$ acts as identity on $q\mathcal{H}$, and
$$
(p-q)^2 = p^2 - 2pq + q^2 = p - 2q + q = p -q
$$
and
$$
    (p-q)^* = p^* - q^* = p -q
$$
since they are projections. Thus $(p-q)$ is a projection. If $v \in \mathcal{H}$ then we can write $v = qv + (1-q)v$ and then applying $p$ across the equation we get
$$
    pv = pqv + p(1-q)v = qv + (p-pq)v = qv + (p-q)v
$$
to show the decomposition we want.


text:
Q: Android Studio internal error and unable to obtain result of 'adb version'? My Android Studio (v 1.5) has always worked perfectly until just recently when my laptop shut down without a warning.
After rebooting, when I relaunched AS, an internal IDE error occurred message popped up but whenever I tried to click on it nothing happens, and suddenly there are tons of errors in my code even when it used to work perfectly fine before (lots of red underlines, mostly 'Cannot resolve' errors).
I have tried:

*

*restarting AS several times

*closing and reopening the project

*cleaning and rebuilding the project

*manipulating the idea.properties file by adding a new line at the end as
commonly suggested in the other solutions I've found (although for some reason I couldn't overwrite the file)

*reinstalling Android Studio and on the first launch it gave me the 'unable to obtain result of adb version'

*I ran adb version in the cmd and it responded instantly with the ff:

Android Debug Bridge version 1.0.32
Revision 09a0d98bebce-android
I'm suspecting the spontaneous shut down must have broken something, but I'm not sure what. Are there any more possible solutions to this?

A: I was able to fix it by:

*

*File > Invalidate Caches/Restart

*Click Invalidate and Restart
After AS rebooted the errors are gone and the device I have plugged in for USB debugging is also detected. Not sure how this fixed it, but there you go.


text:
Q: What images and resource qualifiers do I need to use to ensure that I have a full-screen splashscreen? I'm writing an application that needs to display a full-screen splashscreen image on start. Actually, not exactly full-screen, because status bar is still visible.
This application will be run on a wide range of phones (e.g. from Wildfire to Sensation), but not on tablets. Though, if it can be made to look good on tablets without much effort, I will do that of course.
The problem is - how can I make sure that this splashscreen looks good and fills the entire screen on all devices? It has stretchable parts on all sides, so I can make it a 9-patch if necessary, but I'm still at loss on what pixel sizes I should use.
I resolve that I need to provide images for (small|large)-(ldpi|mdpi|hdpi). What pixel sizes of those images should be? How to calculate them?

A: I have done it in multiple applications that i made an image of 480x800px and then took an image view or linearlayout and gave it fill_parent attributes in widht and height. It worked perfectly on all types of screen
[EDIT] One thing more just add that image in hdpi folder only.

A: For Splash Screen in your xml
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="fitXY"
            android:src="@drawable/splash"/>
    </LinearLayout>

and in your AndroidManifest.xml
    <activity android:name=".Splash" android:theme="@android:style/Theme.NoTitleBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

The Theme.NoTitleBar will also remove the title bar from the splash screen
And for the image for splash screen use images of sizes:
As i had read somewhere and then used
For Portrait: 600 x 1024 px
For Landscape: 1024 x 600 px
I use these sizes in my app and have tested them on android versions 1.6 to 2.3 in each version the resolution of the images appears excellent

A: In the end, I found out that if I provide an hdpi image, it will auto-scale down for lesser dpi. So, to avoid complications, I created a 800x800 image with croppable sides and used it.


text:
Q: undefined method `_input' for ActiveAdmin after changing database I've just changed my model a bit... by doing
rails g migration remove_XXX_from_YYY XXX:string
and then
rails g migration add_AAA_to_YYY AAA:content
Now I'm trying to go to the active admin page and render the "edit: action.. but I get the error msg:
Showing ..../activeadmin-0.3.2/app/views/active_admin/resource/edit.html.arb where line #1 raised:
undefined method `_input' for #<ActiveAdmin::FormBuilder:0xf859210>

Extracted source (around line #1):

1: render renderer_for(:edit)

Application trace:
app/admin/posts.rb:9:in `block (3 levels) in <top (required)>'
app/admin/posts.rb:4:in `block (2 levels) in <top (required)>'

I get the same error with "new" action. Except: 1: render renderer_for(:new)
All other actions with ActiveAdmin work. (show, index, delete).
OBS! I can create and edit posts with the 'normal' _form.html.erb... but not through ActiveAdmin..
Im using ActiveAdmin 0.3.2 and formtastic 1.2.4.
Any suggestions of what can be wrong?
Thanks

A: The error you are getting is not Active Admin related, but comes from Formtastic (the gem Active Admin uses for building nice forms). This could be because you are using a custom data-type on one of model attributes.
I would try to override the form inside the ActiveAdmin.register block (either directly or via a partial). I would do so by specifying each attribute manually and then comment out each field one at a time. Each time I would reload the page to see if the error had disappeared. The second the error disappear I know which field is causing the problem. Then I would add :as => :string (or whatever other input type was appropriate) to force Formtastic to use that particular input type.
Before example:
ActiveAdmin.register User do
  form do |f|
    f.inputs do
      f.input :name
      f.input :email
      f.input :birthday
      f.input :foobar
    end
    f.buttons
  end
end

After example:
ActiveAdmin.register User do
  form do |f|
    f.inputs do
      f.input :name
      f.input :email
      f.input :birthday
      f.input :foobar, :as => :string
    end
    f.buttons
  end
end


text:
Q: Git merge strategy 'theirs' is not resolving modify/delete conflict When performing a git merge with the following options:
git merge -X theirs master
There are occasionally conflicted files like so:

CONFLICT (modify/delete): File_A.java deleted in master and modified
  in HEAD. Version HEAD of File_A.java left in tree.

However, I would like for the -X theirs option to be recognized in these cases, and use the theirs version of the change, which is for the file to be deleted.
Is there a reason this type of conflict is not automatically resolved, especially since I'm providing a specific merge strategy that suggests it should remove the file?
Further, how (if possible) can I update my merge command to use the theirs version of this type of conflict?

A: Looks like theirs option of recursive strategy (this is what you actually use, see the [1]) does not affect tree merging, it is used only for file content merging when both files modified only. I don't really know if there is any merge command option which can do what you want. You could try to make a script which scans conflicted files (with git status --porcelain) and then either removes the file (git rm --force <file>) or get the remote version of it (git checkout --theirs <file>)
[1] https://www.kernel.org/pub/software/scm/git/docs/git-merge.html#_merge_strategies

A: A bit late but might be useful, you can resolve this type of conflict with:
git merge -X theirs master
git diff --name-only --diff-filter=U | xargs git rm

Basically it means "delete all unmerged files" during the conflict resolution.

A:
Further, how (if possible) can I update my merge command to use the theirs version of this type of conflict?

You will need to use Merge Drivers.
You will need to create your own driver and confutation in the .gitattribute file.

Here is a list of related Q which might be helpfully to you.
Each one attach this issue forma different angle

*

*tell git to use ours merge strategy on specific files

*.gitattributes & individual merge strategy for a file

*https://medium.com/@porteneuve/how-to-make-git-preserve-specific-files-while-merging-18c92343826b#.sc08nj3ww


text:
Q: Having one file non-https on https site and how to write the code in the htaccess file Our software uses a file on our website to check if it is valid and is hardcoded into the software, I want our site to go to https but want the directory for this file left as http.

A: You can add .htaccess to your website root directory with following configuration:
# This will enable the Rewrite capabilities
RewriteEngine On

# This checks to make sure the connection is not already HTTPS
RewriteCond %{HTTPS} !=on

# This checks file name is not file.txt
RewriteCond %{REQUEST_FILENAME} !file.txt

# This redirects to all requests to https
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

Please check this reference for more info.


text:
Q: Dynamic .gitignore configs to follow the same pattern over and over git here.
My project structure will look something like this:
app/
    README.md
    .gitignore
    src/
        <all source code goes here>
    docs/
        <docs go here>
    misc/
        examples/
            <examples go here>
        fizzbuzz/
            properties/
            configs/

The misc/fizzbuzz/properties/ directory is very special and I am hoping to be able to set up some special .gitignore configurations for it. In this directory I will have many child directories, like so:
app/
    README.md
    .gitignore
    src/
        <all source code goes here>
    docs/
        <docs go here>
    misc/
        examples/
            <examples go here>
        fizzbuzz/
            properties/
                abc/
                def/
                ghi/
                ...etc.
            configs/

Each of these child directories (of properties/) will follow the same pattern:
abc/
    abc.properties
    abc.txt
    many many other files...
def/
    def.properties
    def.txt
    many many other files...
ghi/
    ghi.properties
    ghi.txt
    many many other files...

So in each child directory there will be:

*

*A properties file whose name is the exact same as the name of the child directory it is a member of (ghi.properties under properties/ghi/, etc.); and

*A txt file whose name is also the exact same as the name of the child directory it is a member of (ghi.txt under properties/ghi/, etc.); and

*Many, many other files. Some will be ghi.* (a "ghi" file, just not of type properties or txt). Some will be *.properties or *.txt (other properties files or txt files, just not ghi.properties or ghi.txt, etc.). Some will be named all over the place (foobar.mp4, flam.csv, etc.). But the thing these files have in common is that they are not of the form "<parent-dir-name>.properties" or "<parent-dir-name>.txt".

I am trying to configure .gitignore to ignore everything in these child directories except for the properties and txt file that matches the name of the directory they live inside of.
Can anyone help nudge me in the right direction?

A: Composing a simple .gitignore file by hand seems simple:
abc
!abc/abc.properties
!abc/abc.txt
def
!def/def.properties
!def/def.txt
# ...etc.

A short Bash shell script to generate such .gitignore file could look like this, but a more readable version with basename would maybe be clearer:
cd app/...../properties
for i in */; do printf "%s\n" "${i%/}" '!'"$i${i%/}."{properties,txt}; done > .gitignore

Such a script could be added to git-commit hooks or to the automation that generates the folders.


text:
Q: php datetime class and for loop problem I was wondering if somebody could help with this problem I have.
I have an array which contains the weekdays in which people want to be contacted. I have then created a for loop which adds 1 day to the current date until the day of the week matches a day in which a person wants to be contacted.
The problem I am having is that the loop always goes one day too far. I am just wondering if this is the best way to accomplish what I am trying to do or is there a better way?
Here is my code:
$ScheduleWindow = array('Monday', 'Tuesday');

$date = new DateTime('today');

$dow = getdate($date->getTimestamp());

for($date, $dow;!in_array($dow['weekday'], $ScheduleWindow);$date->add(new DateInterval('P1D'))){
$dow = getdate($date->getTimestamp());
}

echo "Next date to contact is" . $date->format('Y-m-d H:i:s') . "\n";

The code currently echoes "Next date in schedule window is2011-01-25 00:00:00" however I need it to be the date 2011-01-24.
Thanks for looking.

A: Your for loop expressed in words does this:
If the weekday in $dow is not within schedule window,
assign the current date to $dow,
increase the date,
repeat.

You're checking against the un-increased date on the next loop.
Your loop is also much too complicated. This should do just fine:
while (!in_array($dow['weekday'], $ScheduleWindow)) {
    $date->add(new DateInterval('P1D'));
    $dow = getdate($date->getTimestamp());
}

Your DateTime object, getdate, DateInterval operation is much more complex than it needs to be:
$scheduleWindow = array('Monday', 'Tuesday');

$date = new DateTime('today');
while (!in_array($date->format('l'), $scheduleWindow)) {
    $date->add(new DateInterval('P1D'));
}

echo "Next date to contact is " . $date->format('Y-m-d H:i:s');

A: For applying date in a loop you have to increase date according to your condition. So there is a way:
$date = date ("Y-m-d", strtotime ("+1 day", strtotime($date)));

For further code visit http://urfusion.blogspot.com.


text:
Q: Canceling an area of a Pdf page with Ocular I'd like to cancel a specific area of a page; how can I do this with okular?
In Windows I used Acrobat and it allows me to do this by putting a white text box on the desired area.


text:
Q: Animate divs and order them by number with jQuery here is the scenario that I should create:
there is OL list of numbers, (1,2,3,4,5,6). User can select/click those numbers. When one clicks it, the number should go to another OL list (animated, the number flys overe the screen). The numbers should be always in ordered order in the new list. So if user clicks first 5 it copies and flies to new list, and if user then clicks number 1, it should fly and go before 5. And so... so the new list numbers should something like 1,3,5 no matter in which order user clicked the numbers.
Ok, so that is what I want to achieve. Basically I can do the first part (user clicks the numbers -> it flies to new list), but then how to get the numbers in order always?
JS so far:
$('ol#original li').click(function() {
        $(this).clone().appendTo('ol#newNumbers');

        $('ol#original:last').animate({
            left: "150px",
            position: "relative",
            top: "150px",
        }, 600);
    });

OK, there is still problem that I append the cloned number to same ol list :/
Hopefully you understood and can help me bit. Thank you!

A: quick and simple solution is to create a bunch of empty
 in the other
 and then use $.replaceWith().  Another solution is to give each
 a data attribute that maintain's the sort order.
(first option should be fine for most situations)
edit: http://jsfiddle.net/wA4ex/
/*create empty li's in newlist*/
for (var i=0; i < $('#oglist li').length; i++) {
    $('

').hide().appendTo($('#newlist'));
}

$('#oglist li').click(function(e) {
    var li = $(this),
        index = li.index(),
        clone = li.clone();
    $('#newlist li').eq(index).replaceWith(clone);
});

The main concept is to use place holders to maintain the order.


text:
Q: Get networkx subgraph containing all nodes in between I have a networkx DiGraph and I want to extract a subgraph from it by passing in a list of nodes. The subgraph however can contain all nodes that might be in between the nodes that I have passed. I checked nx.subgraph() but it does not work like I intend to. As for a small example:
import networkx as nx

G = nx.DiGraph()
edges = [(7, 4), (3, 8), (3, 2), (3, 0), (3, 1), (7, 5), (7, 6), (7, 8)]
G.add_edges_from(edges)
H = get_subgraph(G, [0,6,7,8])

How can I write the function get_subgraph() so that H has the edges [(3, 8), (3, 0), (7, 6), (7, 8)]?
The subgraph I need is such that it contains all the nodes that are in the ougoing and incoming paths between the nodes that I pass in the get_subgraph()function.

A: A way to do this could be to find the longest path length between the specified set of nodes, and then find the corresponding induced subgraph containing all nodes in the path. However, being a directed graph, there will be no direct path between say nodes 3 and 7. So we need to find the paths in an undirected copy of the graph. Let's set up the problem:
G = nx.DiGraph()
edges = [(7, 4), (3, 8), (3, 2), (3, 0), (3, 1), (7, 5), (7, 6), (7, 8)]
G.add_edges_from(edges)

plt.figure(figsize=(10,6))
pos = nx.spring_layout(G, scale=20, k=3/np.sqrt(G.order()))
nx.draw(G, pos, node_color='lightblue',
        with_labels=True,
        node_size=1500,
        arrowsize=20)

Now we ca obtain and undirected copy of the graph with nx.to_undirected and find all nx.shortest_path_length for the specified nodes:
from itertools import combinations

H = nx.to_undirected(G)

nodelist = [0,6,7,8]
paths = {}
for nodes in combinations(nodelist, r=2):
    paths[nodes] = nx.shortest_path_length(H, *nodes)

print(paths)
# {(0, 6): 4, (0, 7): 3, (0, 8): 2, (6, 7): 1, (6, 8): 2, (7, 8): 1}

We can find the longest path in the undirected graph with:
max_path = max(paths.items(), key=lambda x: x[1])[0]
longest_induced_path = nx.shortest_path(H, *max_path)

And the corresponding induced subgraph can be obtained with Graph.subgraph:
sG = nx.subgraph(G, longest_induced_path)

pos = nx.spring_layout(sG, scale=20, k=3/np.sqrt(G.order()))
nx.draw(sG, pos, node_color='lightblue',
        with_labels=True,
        node_size=1500,
        arrowsize=20)

A: i understand this from question:
you need all nodes in a path but provide some nodes of that path and algorithm should give all nodes of that path and then you can pass that nodes to a graph and make a new graph.
it should be what you want:
1. you must iterate over all pairs of nodes with this method:
from itertools import combinations
b= combinations('ABCD', 2)
print(list(b))  --> [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]

*you must get all pathes with this:
https://networkx.github.io/documentation/stable/reference/algorithms/simple_paths.html

*you must select path with maximum nodes and that is your solution.


text:
Q: Ubuntu installation failed and left apt broken I've been trying to get Ubuntu GNOME 17.04 and finally got it to boot, however it failed near the end of the installation leaving my apt repositories not set up correctly. Hopefully this is the only part that failed, however I am just taking this one step at a time. This is what it says when I try to update:
CorruptComputer@Ubuntu-GNOME:~$ sudo apt update
[sudo] password for CorruptComputer:
Ign:1 cdrom://Ubuntu-GNOME 17.04 _Zesty Zapus_ - Release amd64 (20170412) zesty InRelease
Err:2 cdrom://Ubuntu-GNOME 17.04 _Zesty Zapus_ - Release amd64 (20170412) zesty Release
  Please use apt-cdrom to make this CD-ROM recognized by APT. apt-get update cannot be used to add new CD-ROMs
Hit:3 http://us.archive.ubuntu.com/ubuntu zesty InRelease
Get:4 http://us.archive.ubuntu.com/ubuntu zesty-updates InRelease [89.2 kB]
Get:5 http://security.ubuntu.com/ubuntu zesty-security InRelease [89.2 kB]
Hit:6 http://us.archive.ubuntu.com/ubuntu zesty-backports InRelease
Reading package lists... Done
E: The repository 'cdrom://Ubuntu-GNOME 17.04 _Zesty Zapus_ - Release amd64 (20170412) zesty Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

A: I was able to fix this by following the same steps in the answer here: How do I restore the default repositories?


text:
Q: How to convert array to another array in Swift I want to convert beforeDataSet to afterDataSet in Swift. Could you tell me how to convert it?
struct BeforeData {
    var value: Int
    var date: Date
}

struct AfterData {
    var sumValue: Int
    var dateString: String
}

let beforeDataSet = [
    BeforeData(value: 100, date: date1), // 2022-01-01 12:00
    BeforeData(value: 150, date: date2), // 2022-01-01 14:11
    BeforeData(value: 120, date: date3), // 2022-01-02 07:00
    BeforeData(value: 120, date: date4), // 2022-01-02 12:00
    BeforeData(value: 200, date: date5), // 2022-01-03 08:00
]

let afterDataSet = [
    AfterData(sumValue: 250, dateString: "2022/1/1"),
    AfterData(sumValue: 240, dateString: "2022/1/2"),
    AfterData(sumValue: 200, dateString: "2022/1/3"),
]

A: What you need is to reduce your original array (considering their elements are sorted by date) and check if the last date is in the same day as the current element date. If true sum the element value with the last element value otherwise append a new element to the result with the current element value and the formatted date string:
let afterDataSet: [AfterData] = beforeDataSet.reduce(into: []) {
    let dateString = Formatter.date.string(from: $1.date)
    if let index = $0.indices.last,
       $0[index].dateString == dateString {
        $0[index].sumValue += $1.value
    } else {
        $0.append(.init(sumValue: $1.value, dateString: dateString))
    }
}

You will need to add these Date Formatter to your project:
extension Formatter {
    static let date: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = .init(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-M-d"
        return formatter
    }()
}

A: If you are grouping these for grouping these in the UI, I would suggest a few things:

*

*AfterData should use Date, not String.

*When you present this in the UI, use a user-friendly date formatter rather than the cryptic yyyy/MM/dd format. E.g., a dateStyle of .medium.

*I would use reduce to calculate the totals by day, sort to sort them, and map to create your custom objects.

*FWIW, using this pattern, you are no longer dependent upon the input data having already been sorted.

So, perhaps:
struct BeforeData {
    var value: Int
    var date: Date
}

struct AfterData {
    var sum: Int
    var date: Date    // note, not `String`
}

let iso = ISO8601DateFormatter()
let date1 = iso.date(from: "2022-01-01T12:00:00Z")!
let date2 = iso.date(from: "2022-01-01T14:11:00Z")!
let date3 = iso.date(from: "2022-01-02T07:00:00Z")!
let date4 = iso.date(from: "2022-01-02T12:00:00Z")!
let date5 = iso.date(from: "2022-01-03T08:00:00Z")!

let before = [
    BeforeData(value: 100, date: date1),
    BeforeData(value: 150, date: date2),
    BeforeData(value: 120, date: date3),
    BeforeData(value: 120, date: date4),
    BeforeData(value: 200, date: date5)
]

let calendar = Calendar.current

let grouped = before
    .reduce(into: [Date: Int]()) { dictionary, object in
        let day = calendar.startOfDay(for: object.date)
        dictionary[day, default: 0] += object.value
    }
    .sorted { $0.0 < $1.0 }
    .map { AfterData(sum: $0.value, date: $0.key) }

And then:
let formatter = DateFormatter()
formatter.dateStyle = .medium

for value in grouped {
    print(formatter.string(from: value.date), value.sum)
}

And a US user will see:
Jan 1, 2022 370
Jan 2, 2022 120
Jan 3, 2022 200

But a UK user will see:
1 Jan 2022 370
2 Jan 2022 120
3 Jan 2022 200

Then we are showing dates in the format with which the end-user is comfortable.


text:
Q: Cannot remove wix bootstrapper application from control panel I have created wix bootsrapper application, which install 2 msi and runs 1 exe files.
Any time I run it, it appears in control panels (duplicated).
But when I want to remove from control panel, it is just running and not uninstalling.
My code for bootsraperr is something like this:
<?xml version="1.0" encoding="UTF-8"?>
    <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:bal="http://schemas.microsoft.com/wix/BalExtension">
        <?define LibsDir="..\Shared\Lib\" ?>
            <Bundle Name="Product Setup" Version="1.0.0.0" Manufacturer="MyCompany" UpgradeCode="{32FC4B59-99BE-4617-867C-4620E2E5772F}">

                <BootstrapperApplicationRef Id="ManagedBootstrapperApplicationHost">
                    <Payload SourceFile="BootstrapperCore.config" />
                    <Payload SourceFile="$(var.LibsDir)WixWPF.dll" />
                    <Payload SourceFile="$(var.LibsDir)WixWPF.pdb" />
                    <Payload SourceFile="msi\p1.msi" />
                    <Payload SourceFile="msi\p2.msi" />
                    <Payload SourceFile=".../.exe" />

                </BootstrapperApplicationRef>

                <Chain>
                    <PackageGroupRef Id="NetFx40Web" />
                    <MsiPackage Id="Product1" SourceFile="msi\p2.msi" InstallCondition="InstallP=1" />
                    <MsiPackage Id="Product2" SourceFile="msi\P1.msi" />
                    <ExePackage Id="Product3" SourceFile="p2.exe" />
                </Chain>

            </Bundle>
    </Wix>

I want to uninstall it from control panel.
How can I handle this?

A: Bootstrapper can be identified by GUID, UpgradeCode and Version. You can't set GUID of the bootstrapper, it will get random new one after EVERY rebuild. So, if you rebuild your bootstrapper, you will get two bootstrappers with same UpgradeCode and Version, but different GUIDs, and they will both be installed, as two different products.
To uninstall old bootstrapper from control panel you need to have it's setup.exe properly cached and with properly configured Uninstall option. If you have problems, do this:

*

*Find out GUID of bootstrapper you want to uninstall. Best way is to find log file of it's installation in %temp% directory and find this line:

Session begin, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall{PUT-GUID-HERE}

If you dont have log file, go to par.2

*Find and delete mentions of your bootstrapper in following Registry keys. Best way is to do that by GUID, but you also can use DisplayName of the bootstapper. Note: if you use DisplayName, you can mix up both installer bootstrappers.

Computer\HKEY_CLASSES_ROOT\Installer\Dependencies
SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall
Software\Microsoft\Windows\CurrentVersion\Uninstall

(Hive of the last two depends on InstallScope of your MSIs. If all of them are per-machine, bundle will be in HKLM.)
If bootstrapper was cached, you also need to clean cache.
To avoid duplication in the future, you have several options:

*

*Don't rebuild your bootstrapper until previous version is installed. Or make backup for every build.

*Upgrade the Version of bootstrapper before every rebuild, it will then be installed as a update.


text:
Q: Ideals of $R/N$ I have a proof in a book I'm reading that says (we are dealing with ring $R$ and ideal $N$) that the ideals of $R/N$ are of the form $M/N$ where $M$ is an ideal of $R$ that contains $N$. Can someone explain this to me please.

A: An ideal of $R/N$ is the kernel of a ring homomorphism $R/N\to A$. Combined with the canonical map $R\to R/N$ we obtain an ideal $M$ as kernel of a homomorphism $R\to A$. Verify that $M/N$ is the original ideal in $R/N$.

A: If $a,b\in M$ then $a+N$ and $b+N$ are elements of $M/N$.
Note that $(a+N)+(b+N)=a+b+N\in M/N$ since $a+b\in M$.
Secondly note that $(r+N)(a+N)=ra+N\in M/N$ for any $r\in R$ since $ra\in M$.
Also $(a+N)(r+N)=ar+N\in M/N$.
This together shows that $M/N$ is a (two-sided) ideal or ring $R/N$.
Conversely let $K$ be some ideal of ring $R/N$. It is to be shown that an ideal $M$ of ring $R$ exists such that $K=M/N$. You can take $M:=\{a\in R\mid a+N\in K\}$ for that.

A: Put $S=R/N$ and let $K$ be an ideal of $S$. Then one has the canonical morphism $S\overset{\pi_2}\to S/K$, which can be composed with the canonical morphism $R\overset{\pi_1}\to R/N$:
$$
  R\overset{\pi_1}\to R/N=S\overset{\pi_2}\to S/K.
$$
Calling $f:R\to S/K$ the composite morphism it is clear that $M=\ker(f)$ is an ideal of$~R$. Now $r\in M\iff \pi_1(r)\in\ker(\pi_2)=K$, and since $\pi_1$ is surjective one has $K=\pi_1(M)$. But $\pi_1$ is taking classes modulo$~N$, so a natural notation for $\pi_1(M)$ is $M/N$, so $K=M/N$. And it is clear that $\ker(f)\supseteq\ker(\pi_1)$, in other words that $M\supseteq N$.


text:
Q: How to get combobox not to accept user input in Excel-Vba and allow vba.value changes? I have a combobox on my userform that should be changed by the vba codes, but I dont want any user to be able to type values, only the vb should have this power, the user should only be able to select values.
Any ideas?

A: As suggested by Chris, add the items and then set a default value for the box, however, don't set locked, by selecting the combobox in this box select the yellow option.

A: Just change the "Locked" property to True. It will prevent the user from changing the value: however VBA will still be able to. For example, the following code locks the ComboBox; then adds two values and selects one:
Private Sub UserForm_Initialize()
    With ComboBox1
       .Locked = True ' Prevents the user changing anything
       .AddItem "Hello"
       .AddItem "World"
       .Value = "Hello" ' Sets the value with VBA
    End with
End Sub


text:
Q: How can we add BOOLEAN datatype in mysql query browser? I am trying to add a BOOLEAN column using EDIT TABLE in mysql workbench, but it automatically changes to TINYINT on applying changes.
How can I get the column to be BOOLEAN?

A: MySQL doesn't support true booleans as per standard SQL. It uses integer values 1 and 0 respectively for true and false. It does support the keywords true and false, but these are mapped to the integer values.
mysql> SELECT true, false;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

They really are mapped to integers:
mysql> SELECT true + 10;
+-----------+
| true + 10 |
+-----------+
|        11 |
+-----------+

This does mean that certain expressions are simpler in MySQL, such as counting the rows where a certain value is true is as easy as SUM() of a boolean expression, which will be 1 where the condition is true and 0 otherwise.
SELECT SUM(name = 'bill') FROM table;

Standard SQL doesn't support this use of booleans as integers, and would require the more verbose:
SELECT COUNT(CASE name WHEN 'bill' THEN 1 END) FROM table;

As other answers have already noted, you can use a data type alias BOOL but it is immediately replaced by TINYINT(1) (MySQL does something similar with other data types, like REAL and SERIAL).

A: In Mysql you can't have bool, because in Mysql bool is Tinyint, just that it's converted when you create the table.So you can "create" the bool and you can use it as a boolean, but it's a tinyint.
jcho360> create table bool_test (bool_field bool);
Query OK, 0 rows affected (0.04 sec)

jcho360> show create table bool_test \G
*************************** 1. row ***************************
       Table: bool_test
Create Table: CREATE TABLE `bool_test` (
  `bool_field` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

the bool_field I created as bool and mysql put it as tinyint(1).
if you want to set it as true or false, in the programming world 1 is true and 0 is false.
You can even make conditionals with 1 and 0, like
if (bool_field){

code here //and if bool_field is 1, it will be the same as bool_field=true

}

A: BOOL and BOOLEAN are synonyms of TINYINT in MySQL. See MySQL docs: Numeric Type Overview
You probably want to use the BIT datatype.


text:
Q: what is the difference between normal js timers and this jquery timers plugin? If I use setInterval or setTimeout for an animation, the speed of the animation is different in all the browsers, but if I use the jquery timer plugin its the speed is almost exactly the same in every browser.
How exactly does it do that? ive looked through the code of the plugin but i cant figure it out.
Here is the link for the plugin jquery.timers

A: Not likely.
This is at the heart of the plugin
if (!element.$timers[label][fn.$timerID])
  element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
.
.
.
window.clearInterval(timers[label][fn.$timerID]);


text:
Q: Strange struts2 behavior There is something strange happening.
Param interceptor is the one in charge to take parameters strings values from the request and put them in the java property of my action.
Some defaults type converters exist (primary types, Date, Map, Array)
And I tried to put a string parameter in a BigDecimal.  Strangely... it works but how ? I am pretty sure that the BigDecimal converters does not exist and has to be implemented by the framework user

A: If i am correct it is using the default BigDecimal parsing.have a look at DefaultTypeConverter


text:
Q: PDF link annotation color space (border) I try to understand the color entry for a Link annotation.
Section 8.4.1 of the PDF 1.7 specification is about annotation dictionaries (common to all annotation types) where the table 8.15 describes an entry C as

An array of numbers in the range 0.0 to 1.0, representing a color used for the following purposes:
• The background of the annotation's icon when closed
• The title bar of the annotation's pop-up window
• The border of a link annotation
The number of array elements determines the color space in which the color is defined:
0 No color; transparent
1 DeviceGray
3 DeviceRGB
4 DeviceCMYK

So I assume that the link annotation in this form
<<
  /A <<
    /S /URI
    /Type /Action
    /URI (www.example.com)
  >>
  /C [
    0.22
    0
    0.55
    0
  ]
  /Rect [
    28.346
    801.543
    50.586
    813.543
  ]
  /Subtype /Link
  /Type /Annot
>>

should be a color in the color space DeviceCMYK (four numbers in the array) and should be some greenish color. But it appears that the color is treated as RGB

(screenshot from Foxit PDF reader, similar to Acrobat)
R: 56/255, G: 0/255, B: 140/255
So there is a misunderstanding on my side here, but where is it?

A: Your understanding is correct, it seems this is a bug in many viewers.
XODO displays the border correctly.