text:
Q: Combobox data binding with item templates I am trying to create a wpf combobox containing a list of World of warcraft items. I am using a item template for the combo box so that the items icon and item name are shown in the combobox drop down list. It works as is and I can start typing a item name and the list of items in the popup are automatically filtered.
The problem is that when I click an item I want the item name to be shown in the comboboxes text area. Instead what I get is a very brief ItemDisplayModel.ToString() then a empty string.
The ItemDisplayModel.ToString() being the ItemDisplayModel type that I selected from the list. Which makes sense cause the combobox control ItemsSource property contains an array of ItemDisplayModel types.
But in my AuctionHouseFilterItemNameModel.Value property I am detecting weather the value has changed and if so rebuild the list of items to be displayed in the combobox. So because the Text in the combobox was changed to ItemDisplayModel.ToString() when I click an item in the popup list it again rebuilds the list of items only this time there is no match because ItemDisplayModel.ToString() does not match any known item names.
All I am trying to do is when I click an item in the popup list I want the ItemDisplayModel.Name to be mapped to the AuctionHouseFilterItemNameModel.Value property and have the combobox text area to display AuctionHouseFilterItemNameModel.Value as well.
Does that make sense? I've tried numerous different ways and I am at a loss. Looking around the web did'nt give me the answer either. I'm sure it's something simple to fix but the solution eludes me.
Here is my XAML for the control
<UserControl
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:AuctionHouseSearchFilters="clr-namespace:Codefarts.WowTracks.DataMinerWPF.Models.AuctionHouseSearchFilters"
            xmlns:Models="clr-namespace:Codefarts.WowTracks.DataMinerAppCore.Models;assembly=Codefarts.WowTracks.DataMinerAppCore"
            xmlns:DataMinerAppCore="clr-namespace:Codefarts.WowTracks.DataMinerAppCore;assembly=Codefarts.WowTracks.DataMinerAppCore"
            xmlns:dataMinerWpf="clr-namespace:Codefarts.WowTracks.DataMinerWPF"
            x:Name="userControl"
            x:Class="Codefarts.WowTracks.DataMinerWPF.Controls.AuctionHouseSearchFilters.AuctionHouseItemNameControl"
             mc:Ignorable="d"
             d:DesignHeight="51" d:DesignWidth="283">
    <UserControl.Resources>
        <dataMinerWpf:UriToBitmapImageConverter x:Key="UriToImageConverter" />
        <BitmapImage x:Key='defaultImage' UriSource='/Resources\118.png' />
        <DataTemplate x:Key="ItemTemplate" DataType="Models:ItemDisplayModel" >
            <StackPanel Orientation="Horizontal" Margin="0 5 0 5">
                <Image Width="50" Height="50" Stretch="Fill" Source="{Binding IconUrl, Converter={StaticResource UriToImageConverter}, TargetNullValue={StaticResource defaultImage}}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
                <Label Content="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
            </StackPanel>
        </DataTemplate>

    </UserControl.Resources>
    <UserControl.DataContext>
        <AuctionHouseSearchFilters:AuctionHouseFilterItemNameModel/>
    </UserControl.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <ComboBox x:Name="ItemList" MaxDropDownHeight="592" Grid.Row="0" ItemsSource="{Binding ItemDisplayModels}"   ItemTemplate="{StaticResource ItemTemplate}" IsEditable="True" IsTextSearchEnabled="True" IsTextSearchCaseSensitive="False" Text="{Binding Value}"    >

        </ComboBox>
    </Grid>
</UserControl>

Here is my code behind
  public partial class AuctionHouseItemNameControl : UserControl, IAuctionHouseFilterControl
    {
        private Application app;

        public AuctionHouseItemNameControl()
        {
            InitializeComponent();
        }

        public void SetModel(IAuctionHouseSearchFilter model)
        {
            this.DataContext = model;
        }

        public void SetApplication(Application app)
        {
            this.app = app;
        }

 private void ItemList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            //if (model.Handled)
            //{
            //    return;
            //}

            // model.Handled = true;
            if (e.AddedItems != null && e.AddedItems.Count > 0)
            {
                var model = this.DataContext as Models.AuctionHouseSearchFilters.AuctionHouseFilterItemNameModel;

                var item = e.AddedItems[0] as ItemDisplayModel;
                // this.ItemList.SelectedValue = item.Name;
                model.Value = item.Name;

                // this.ItemList.SelectedItem = item.Name;
            }

            //   model.Handled = false;
        }
    }

and here is my data models
 [Export(typeof(IAuctionHouseSearchFilter))]
    public class AuctionHouseFilterItemNameModel : IAuctionHouseSearchFilter, INotifyPropertyChanged
    {
        private string value;

        private bool connected;

        private Application app;

        private ItemDisplayModel[] displayItems;
        private CancellationTokenSource backgroundCancel;

        private bool buildingDisplayItems;

        private readonly object lockObject = new object();

        private ItemDisplayModel displayValue;

        //  private bool Handled { get; set; }
        public ItemDisplayModel DisplayValue
        {
            get
            {
                return this.displayValue;
            }
            set
            {
                if (value == null)
                {
                    return;
                }
                this.Value = value.Name;
                this.displayValue = value;
                this.OnPropertyChanged();
            }
        }

        public string Value
        {
            get
            {
                return this.value;
            }

            set
            {
                //if (this.Handled)
                //{
                //    return;
                //}

                if (value == this.value)
                {
                    return;
                }

                this.value = value;
              //  this.Handled = true;
                this.OnPropertyChanged();
                var cancellationTokenSource = this.backgroundCancel;
                if (cancellationTokenSource != null)
                {
                    cancellationTokenSource.Cancel();
                }

                this.BuildDisplayItems();
             //   this.Handled = false;
            }
        }

        public IEnumerable<AuctionDataModel> Filter(MainFilterModel model, IEnumerable<AuctionDataModel> items)
        {
            if (!this.connected)
            {
                return items;
            }

            // get item id from it's name
            var list = this.app.ItemNames[model.SelectedRegion];
            var id = list.FirstOrDefault(x => x.Name.ToLowerInvariant().Contains(this.value.Trim().ToLowerInvariant()));

            return items.Where(x => id != null && x.ItemId == id.Id);
        }

        public IEnumerable<ItemDisplayModel> ItemDisplayModels
        {
            get
            {
                return this.displayItems;
            }
        }

        public async void BuildDisplayItems()
        {
            if (this.buildingDisplayItems)
            {
                return;
            }

            if (!this.connected)
            {
                this.displayItems = null;
            }

            //  return this.GetDisplayItems();
            this.buildingDisplayItems = true;
            this.backgroundCancel = new CancellationTokenSource();
            this.OnPropertyChanged("ItemDisplayModels");
            await Task.Factory.StartNew(
                    () =>
                    {
                        var originalItems = this.displayItems;
                        this.displayItems = new[] { new ItemDisplayModel() { Name = "Rebuilding list..." } };
                        var correctedSearchValue = this.value.Trim().ToLowerInvariant();
                        //lock (this.lockObject)
                        //{
                        this.displayItems = (string.IsNullOrWhiteSpace(this.value) ?
                                            this.app.DisplayItemModels :
                                            this.app.DisplayItemModels.Where(x => x.Name.ToLowerInvariant().Contains(correctedSearchValue))).Take(100).AsParallel().ToArray();

                        this.buildingDisplayItems = false;
                        this.OnPropertyChanged("ItemDisplayModels");
                    },
                    this.backgroundCancel.Token);
        }

        public string Name
        {
            get
            {
                return "Item Name";
            }
        }

        public Type Control
        {
            get
            {
                return typeof(AuctionHouseItemNameControl);
            }
        }

        public virtual IAuctionHouseSearchFilter Clone()
        {
            return new AuctionHouseFilterItemNameModel()
                       {
                           Value = this.Value
                       };
        }

        public void Connect(Application app)
        {
            if (this.connected)
            {
                return;
            }

            this.app = app;

            this.connected = true;
        }

        public void Disconnect()
        {
            if (!this.connected)
            {
                return;
            }

            this.app = null;
            this.connected = false;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

   public class ItemDisplayModel : INotifyPropertyChanged
    {
        private string iconUrl;

        private string region;

        private string name;

        private int itemId;

        public int ItemId
        {
            get
            {
                return this.itemId;
            }
            set
            {
                if (value == this.itemId)
                {
                    return;
                }
                this.itemId = value;
                this.OnPropertyChanged();
            }
        }

        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                if (value == this.name)
                {
                    return;
                }
                this.name = value;
                this.OnPropertyChanged();
            }
        }

        public string Region
        {
            get
            {
                return this.region;
            }
            set
            {
                if (value == this.region)
                {
                    return;
                }
                this.region = value;
                this.OnPropertyChanged();
            }
        }

        public string IconUrl
        {
            get
            {
                return this.iconUrl;
            }
            set
            {
                if (value == this.iconUrl)
                {
                    return;
                }
                this.iconUrl = value;
                this.OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

A:
The problem is that when I click an item I want the item name to be shown in the comboboxes text area. Instead what I get is a very brief ItemDisplayModel.ToString() then a empty string.

To get the Name property displayed in the editable text area of the ComboBox use TextSearch.TextPath so your ComboBox definition would look like:
<ComboBox x:Name="ItemList"
          Grid.Row="0"
          IsEditable="True"
          IsTextSearchCaseSensitive="False"
          IsTextSearchEnabled="True"
          ItemTemplate="{StaticResource ItemTemplate}"
          ItemsSource="{Binding ItemDisplayModels}"
          MaxDropDownHeight="592"
          TextSearch.TextPath="Name" />

Now when an item is selected from the dropdown instead of seeing ItemDisplayModel.ToString(), you will see the Name property.


text:
Q: How can I reduce duplicate code in Hibernate classes? At this point we have several Hibernate object classes in our project, like the following:
package org.carl.recordkeeper.entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;

public class BstRecordPK implements Serializable
{
// ------------------------------ FIELDS ------------------------------

private String bst;

private Integer instbit;

// --------------------- GETTER / SETTER METHODS ---------------------

@Id
@Column( name = "BST", nullable = false, length = 1 )
public String getBst()
{
    return bst;
}

public void setBst( String bst )
{
    this.bst = bst;
}

@Id
@Column( name = "INSTBIT", nullable = false )
public Integer getInstbit()
{
    return instbit;
}

public void setInstbit( Integer instbit )
{
    this.instbit = instbit;
}

// ------------------------ CANONICAL METHODS ------------------------

@Override
public boolean equals( Object o )
{
    if ( this == o )
    {
        return true;
    }
    if ( o == null || getClass() != o.getClass() )
    {
        return false;
    }

    BstRecordPK that = (BstRecordPK)o;

    if ( bst != null ? !bst.equals( that.bst ) : that.bst != null )
    {
        return false;
    }
    if ( instbit != null ? !instbit.equals( that.instbit ) : that.instbit != null )
    {
        return false;
    }

    return true;
}

@Override
public int hashCode()
{
    int result = instbit != null ? instbit.hashCode() : 0;
    result = 31 * result + ( bst != null ? bst.hashCode() : 0 );
    return result;
}
}

We also have a duplicate code checker, which keeps going off when we create a new Hibernate class because one of the get/set pairs matches what's in another class (database tables with foreign keys). Is there a way to reduce duplicate code and still keep Hibernate happy? I've thought about using a base class, but it's not like there is a single column used in all the database tables.

A: Code duplication warning a meant to show copied sections of code normally produced with copy & paste. Copying code will reduce maintainability and may result in security issues.
If sonarqube shows me duplication warnings, I have a closer look on the section of fode and decide, if this is a false positive in sense that many pojos will share some code like getId() { return id; } even if the retrn type differs or I some programmer just re-implemented or copied a section.
I would strongly recommend to not reduce you entities. This will only lead to objuscation.
However, you can try to use @MappedSuperClass if you really bother about code dublication detection limitations.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to re-route the user to a main page I have .html file inside a directory "/country/main.html". Now, I want to redirect the user to this page whenever a request arrive for any country. I have written a little code snippet
  public class Global : System.Web.HttpApplication
    {
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            if (app.Request.Path.Contains("/country"))
            {
                app.Context.RewritePath("/country/main.html");
            }
        }
    }

I tried this url http://www.mydomain.com/country, that works fine. But if the request arrive something like this http://www.mydomain.com/country/new_york.html, it gives me 404 error.
Please suggest, what I have to do in that case?


text:
Q: Terraform cidrsubnet function First of all, I apologize for now knowing how to subnet better. It's not something I've had to do up until now.
I have been given a network/cidr of 10.10.32.0/19.
I have 6 subnets that need 255 ips each.
The rest of the IPs I would like to spread across 3 remaining subnets.
This is what i came up with using cidrsubnet
        cidrsubnet("10.10.32.0/19", 2, 0) # "10.10.64.0/21" 2048 hosts
        cidrsubnet("10.10.32.0/19", 2, 1) # "10.10.72.0/21" 2048 hosts
        cidrsubnet("10.10.32.0/19", 2, 2) # "10.10.80.0/21" 2048 hosts

        cidrsubnet("10.10.32.0/19", 5, 24) # "10.10.88.0/24" 255 hosts
        cidrsubnet("10.10.32.0/19", 5, 25) # "10.10.89.0/24" 255 hosts
        cidrsubnet("10.10.32.0/19", 5, 26) # "10.10.90.0/24" 255 hosts

        cidrsubnet("10.10.32.0/19", 5, 27) # "10.10.91.0/24" 255 hosts
        cidrsubnet("10.10.32.0/19", 5, 28) # "10.10.92.0/24" 255 hosts
        cidrsubnet("10.10.32.0/19", 5, 29) # "10.10.93.0/24" 255 hosts

This leaves me with about 512 ips that can't be used. Am I doing this right?

A: You have 2^11 (32-19) hosts == 8192
Your range begins at 10.10.32.0 and runs through 10.10.63.255
6*256+3*2048 == 7680 leaving the 512
You'll need to rebalance so you don't waste IPs.
Your first cidrsubnet(10.10.32/19,2,0) is 10.10.32.0--10.10.39.255


text:
Q: How to set today's date in select boxes on page load using datepicker I have 3 select boxes, day/month/year.  If I load the webpage and click on a date using datepicker, the select fields are updated with the correct date.
However on page load I want the select boxes to be loaded with today's date.  I have tried to set today's date in datepicker on page load, but the select fields are not showing today's date, instead they show the 1st day, 1st month, 1st year from the select lists.
 <script>
$(function() {
    $('#datepicker').datepicker({
beforeShow: readSelected, onSelect: updateSelected,
minDate: new Date(), maxDate: new Date(2016, 12 - 1, 31)});

// Prepare to show a date picker linked to three select controls
function readSelected() {
$('#datepicker').val($('#selectMonth').val() + '/' +
    $('#selectDay').val() + '/' + $('#selectYear').val());
return {};
}

// Update three select controls to match a date picker selection
function updateSelected() {
var date1 = $(this).val();
console.log(date1.substring(0, 2));
console.log(date1.substring(3, 5));
console.log(date1.substring(6, 10));
$('#selectMonth').val(date1.substring(0, 2));
$('#selectDay').val(date1.substring(3, 5));
$('#selectYear').val(date1.substring(6, 10));
}

$('select').change(readSelected);
    $('#pickDate').click(function (e) {
    $('#datepicker').datepicker("show");
    e.preventDefault();
});
});
</script>

 <script>
$( document ).ready(function() {
var currentDate = new Date();
$("#datepicker").datepicker("setDate",currentDate);

});
</script>


text:
Q: Find numerical patterns in Pandas I need to find rows in pandas df which correspond to a particular pattern. For example:
df =

 q1  q2  q3  q4  q5
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 2.0
1.0 1.0 2.0 1.0 1.0
3.0 1.0 1.0 7.0 1.0

is there something like:
>> df == [1.0 1.0 2.0 1.0 1.0]
>> False
   False
   True
   False

A: You can use df.values to compare with the list and check if all elements of row equals the list.
(df.values==[1.0, 1.0, 2.0, 1.0, 1.0]).all(axis=1)
Out[334]: array([False, False,  True, False], dtype=bool)

A: It seems you want compare numpy array with all or
any:
print (df ==np.array([1.0, 1.0, 2.0, 1.0, 1.0]))
      q1    q2     q3     q4     q5
0   True  True  False   True   True
1   True  True  False   True  False
2   True  True   True   True   True
3  False  True  False  False   True

mask = (df == np.array([1.0, 1.0, 2.0, 1.0, 1.0])).all(axis=1)
print (mask)
0    False
1    False
2     True
3    False
dtype: bool

Or:
mask = ~(df != np.array([1.0, 1.0, 2.0, 1.0, 1.0])).any(axis=1)
print (mask)
0    False
1    False
2     True
3    False
dtype: bool


text:
Q: How do I install VMWare Workstation (6.5.5) on ubuntu 10.10 When I try to install I get error:

VMware-Workstation-6.5.5-328052.x86_64.bundle
VMware-Workstation-6.5.5-328052.x86_64.bundle: line 108: syntax error near unexpected token `newline'
VMware-Workstation-6.5.5-328052.x86_64.bundle: line 108: `'

A: The Vmware Website has a new download manager plugin for firefox (and possibly other browsers) that is the reason for the 20K size. Opt to download using your browser to download and you should be able to get the full installer that way.

A: Two possibilities:
a) You tried to execute the .bundle as a shell script (i.e. sh VMware-Workstation-6.5.5-328052.x86_64.bundle)
In this case chmod u+x it, then execute it ./
b) You downloaded it with firefox, in this case for some strange reason the file is only 20k in size an does not work. I ran into this problem yesterday. Downloading it with Opera worked fine.


text:
Q: React App dependency conflict with webpack-server
npm WARN config global --global, --local are deprecated. Use
--location=global instead. npm ERR! code ERESOLVE npm ERR!
webpack-server@"^0.1.2" from the root project npm ERR! npm ERR! Fix
the upstream dependency conflict, or retry npm ERR! this command with
--force, or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR! npm ERR! See
C:\Users\Emre Kızıltoprak\AppData\Local\npm-cache\eresolve-report.txt
for a full report.

Package json:
"dependencies": {
    "@babel/core": "^7.18.9",
    "@babel/plugin-transform-runtime": "^7.18.9",
    "@babel/preset-env": "^7.18.9",
    "@babel/preset-react": "^7.18.6",
    "babel-loader": "^8.2.5",
    "css-loader": "^6.7.1",
    "html-webpack-plugin": "^5.5.0",
    "node-sass": "^7.0.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "sass-loader": "^13.0.2",
    "style-loader": "^3.3.1",
    "webpack": "^5.73.0",
    "webpack-dev-server": "^4.9.3",
    "webpack-server": "^0.1.2"

  },
  "devDependencies": {
    "webpack-cli": "^4.10.0"
  }

I created a react app without create-react-app. I did my setup manually. Now iam getting a dependency conflict. It is gone when i remove webpack server or with the usage of --legacy-peer-deps. But i do not want to force things. Is there anyone with real solution ?

A: Unsure which tutorial you are following, but if it is this one: https://www.linkedin.com/pulse/create-react-app-without-create-react-app-cra-elhousieny-phd%25E1%25B4%25AC%25E1%25B4%25AE%25E1%25B4%25B0/?trackingId=tP9OVj7YQxCNKYXrT5zD1A%3D%3D
I ran into the same issue, I removed Webpack-server, as most other tutorials do not include it. Since removing it seems to be work.


text:
Q: Calculate mode of all column values for the same ID using BigQuery SQL Let's say I have a Bigquery table with columns id, species, genre, and level. There are cases that for the same id, species, and genre my table could have different level values in multiple rows.
Finally, I want to have 1 row per id with level value as mode of all the level values present in the original table for that id.
Example
#standardSQL
with `project.dataset.table` as (
  select '123' id, 'dog' species, 'suspense' genre, 3 level  union all
  select '124', 'cat', 'love', 4 union all
  select '123', 'dog', 'suspense', 5 union all
  select '123', 'dog', 'suspense', 5
)
select *
from `project.dataset.table`

Expected Outcome:
Same dataset with one row for each id. For eg. in the above example, for id 123 level will be 5 (which occurred the most number of times)
How could I achieve this?
[Update]
The above data is just an example. I have 20 million rows in my actual dataset with more than 4 columns.

A: Try this:
with `project.dataset.table` as (
  select '123' id, 'dog' species, 'suspense' genre, 3 level  union all
  select '124', 'cat', 'love', 4 union all
  select '123', 'dog', 'suspense', 5 union all
  select '123', 'dog', 'suspense', 5
)
select id, array_agg(level order by cnt desc limit 1)[offset(0)] as mode
from (
  select id, level, count(level) as cnt
  from `project.dataset.table`
  group by id, level
)
group by id


text:
Q: Making value type behave like a reference type using boxing and implicit conversions I would like to box a value type and give it implicit conversions. Unfortunately doing so makes it stop behaving like a reference type i.e.
MyTnt i1 = 3; //MyValue has a field value = 3
MyInt i2 = 5; //value = 5

i1 = i2;      //both i1 and i2 = 5
i2 = 4;       //i1 = 5, i2 = 4; should be i1 = i2 = 4;

Is it possible to write boxing using implicit conversions so it behaves here as expected?

A: I believe you're misunderstanding some points.
One thing is creating references to hold an object or a value type, and another story is giving an argument by reference.
i1 would also hold 4 if you would pass it by reference in some method:
public void X(int i2, ref MyInt i1)
{
   // When you define a ref parameter
   // you're not creating a new reference but you're
   // reusing the given one
   i1 = i2;
}

MyInt i1 = 4;
MyInt i2 = 0;

// This would produce what you expect
X(i2, ref i1);

// Now i2 is 4


text:
Q: codeigniter join query, display data to view im new to codeigniter & php, and i have some question about join() function.
i have this model:
public function get_categorie()
{
        $this->db->select('*');
        $this->db->from('foxCategory');
        $this->db->join('foxAnnunci', 'foxCategory.id = foxAnnunci.id_foxCategory');

        $query = $this->db->get();
}

this controller:
public function index()
{
    $data['category']= $this->annunci_model->get_categorie();
    $data['annunci'] = $this->annunci_model->get_annunci();
    $data['titolo'] = 'Elenco annunci';

    $this->load->view('templates/header', $data);
    $this->load->view('annunci/index', $data);
    $this->load->view('templates/footer');
}

and this view

<?php echo $value['titolo'] ?>

      Data di creazione: <?php echo $value['creato_il'] ?>

    <?php echo $value['descrizione'] ?>

<a href="<?php echo $value['id'] ?>">Guarda annuncio ||
<?php echo $category['category']['titolo'] ?>

i want to display the name of category as link (classic for blog category function), but this code show nothing, what is the problem?


text:
Q: convert number into binary and Count consecutive 1's in binary number in java I have written below code for displaying count for consecutive 1's in binary number e.g if input is 13 1101 then count should be 2 .
But testcase has failed for 1911
import java.util.Scanner;

/**
 *
 */

/**
 * @author jyotiv
 *
 */
public class BinaryConversion {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    int n=0,count=1;
    String binaryNo="";
    int sum=0;
    Scanner scanner=new Scanner(System.in);
    n=scanner.nextInt();
    binaryNo=Integer.toBinaryString(n);
    System.out.println(binaryNo);
char binaryArray[]=binaryNo.toCharArray();
    for(int i=0;i<binaryArray.length-1;i++)
    {
        //System.out.print(binaryArray[i]);
        if(binaryArray[i]==binaryArray[i+1])
        {
        count++;
        }

    }
    System.out.println(count);
}

}

A: import java.io.*;
import java.util.*;

/**
 * @author jyotiv
 *
 */
public class BinaryConversion{

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int n=0,countOne=0,maxCount = 0;
        String binaryNo="";
        int sum=0;
        Scanner scanner=new Scanner(System.in);
        n=scanner.nextInt();
        binaryNo=Integer.toBinaryString(n);
        System.out.println(binaryNo);
        char binaryArray[]=binaryNo.toCharArray();
        for(int i=0;i<binaryArray.length;i++)
        {
            //System.out.print(binaryArray[i]);

            if(binaryArray[i]=='1')
            {
                countOne++;
            //}
            }
            if(countOne>maxCount)
            {
                maxCount=countOne;
            }
            if(binaryArray[i]=='0')
            {
                countOne=0;
            }
        }
        System.out.println(maxCount);
    }

}

It works with the above modification


text:
Q: How to add a button to call interface? I want to create a app. but
How to add a button to call interface? like this

http://i.stack.imgur.com/qqyfP.jpg

A: The answer is: You can't. The Call interface is provided by iOS and we don't have access to it's UI components.


text:
Q: How to access phpmyadmin on DDEV Windows 10 pro localhost with SSL record too long error I am using DDEv and Docker with Windows 10 pro to set up a localhost install of drupal 8.8 using Composer. I have set up and configured the local drupal installation (it is a fresh install) and it appears to be running correctly, but in the admin section of the drupal site I receive a warning to change write permissions of sites/default/settings.php.
I tried to change settings using Filezilla, but it appears that local files in Filezilla do not provide access to write permissions? When I right-click the file in Filezilla, no permissions option appears.
Following troubleshooting tips from ddev, I tried to access phpmyadmin at https://mysitename.ddev.site:8036
Instead of loading phpmyadmin, I got the following error message:

Secure Connection Failed

An error occurred during a connection to dmckimep.ddev.site:8036. SSL received a record that exceeded the maximum permissible length.
Error code: SSL_ERROR_RX_RECORD_TOO_LONG
The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.

Please contact the website owners to inform them of this problem.

I've been searching around for a couple of hours now and do not find a solution to this. I ran ddev describe and all seems fine with the installation. The drupal site in the container seems to run okay. There are no port conflicts present so far as I have found, so I am not sure why I cannot get access to phpmyadmin.
I am a relative newbie in terms of skills, but have successfully maintained drupal 4-7 on localhost with XAMPP and my web host. Now I am wrestling with the move to drupal 8/composer/docker/ddev. Any suggestions would be much appreciated.
Thank you!

A: Update 2022-09-14: DDEV has had https support fpr PHPMyAdmin and MailHog for years now, ddev describe will show you the URL.
(Original answer) ddev's PHPMyAdmin connection doesn't support https, just http. You can find the links for both PHPMyAdmin and MailHog using ddev describe; both are http-only, as in your example, http://mysitename.ddev.site:8036. It would be possible to provide https URLs for PHPMyAdmin and MailHog, but nobody has ever asked for them, and there's no security reason to do so.
Note that the key reason for https on the actual project URL is because real projects run behind https and people need to see problems like mixed content during the development phase. But there's no such need for PHPMyAdmin. However, I'm sure if people ever want it, we'll do it, it's not hard to do.

A: Just as a general add on, after ddev start you can run ddev launch -p in order to open PHPMyAdmin for the current project database in the browser.


text:
Q: HTML: форма без атрибута action Здравствуйте!
На некоторых сайта есть формы без атрибута action. Например:
<form enctype="multipart/form-data" id="myform" method="post">
</form>

Подскажите, пожалуйста, каким образом реализуется отправка данных на сервер? С помощью JavaScript присваивается URL? Или как-то по другому?
Буду признателен, если приведете пример. Спасибо!

A: *

*Если не указано, куда слать, то стандарт требует слать на текущий адрес.

*Всегда можно при помощи js наделать чего угодно.

A: Отправка осуществляется просто через AJAX. Например

$("form").submit(function(event) {
  event.preventDefault();

  //Какая нить валидация
  if (true) {
    var action = $(this).data('action');
    var data = $(this).serializeArray();
    $.post(action, data);
  }
});
<form data-action='/simple.php'>
  <input type="text" name="a" value="1" id="a">
  <input type="submit" name="g" value="Submit" id="g">
</form>

А причина простая, меньше ботов будет спамить


text:
Q: iOS Realm detect changes for RLMObject I have written code like this to listen for changes in Post object.
    notification = Post.allObjects(in: RLMRealm.encryptedRealm()! as! RLMRealm).addNotificationBlock({ (results, changes, error) in
        let pred = NSPredicate(format:  "tag == %@", self.postTag)
        self.posts = CommonResult.objects(with: pred).sortedResults(usingKeyPath: "id", ascending: true)

        if let _ = changes {
            if (changes!.insertions.count > 0 || changes!.deletions.count > 0 || changes!.modifications.count > 0) {
                    self.tblListing.reloadData()
            }
        }
    })

In my Post object, there are 2 property. One is 'rowHeight' and another is 'isLikeByMyself'.
I want to reload tableview only if 'isLikeByMyself' is changed. How shall I do? Is it possible?

A: You have at least two options.
If you don't have many Post objects, you may want to consider registering object notifications on each of them. Object notifications tell you which properties were changed and how, so you can use that information to reload the table view. However, you will need to register a separate notification on each Post object, which may not be practical if you have a large number of them.
Here is an alternate idea. Add an ignored boolean property to Post called something like isLikeWasChanged, and add a Swift didSet block that will set isLikeWasChanged to true any time you modify isLikeByMyself. Then, in your existing collection observation block, reload the table view only if at least one isLikeWasChanged is true, remembering to set them all back to false before you leave the block.


text:
Q: Filling some region with colour, and the rest of the image as black I have drawn some polygon on an image after using imshow and hold on, and filled it with white as follows:
fill(x(k),y(k),[1 1 1])

How can I make the rest of the image black while keeping the polygon white? In other words, how can I make a binary image, where the polygon is white, and the rest of the image is black? Provided that the polygon is a bit complex.
Thanks.

A: Use roipoly:
BW = roipoly( I, x(k), y(k) );

Where I is your input image (you only need it to get the desired output size of the binary maxk BW). y and x are the corners of your polygon.


text:
Q: Java: convert binary string to hex string I need to convert the binary string to a hex string but i have a problem.
I  converted the binary string to a hex string by this method:
public static String binaryToHex(String bin){
   return Long.toHexString(Long.parseLong(bin,2));
}

it's ok! but I lose the zeros to the left of the string.
Ex:
the method return this: 123456789ABCDEF,
but i want returned this:
00000123456789ABCDEF

A: Instead of Long.toHexString I would use Long.parseLong to parse the value and then String.format to output the value with the desired width (21 in your example):

public static String binaryToHex(String bin) {
   return String.format("%21X", Long.parseLong(bin,2)) ;
}

A: Not very elegant, but works
public static String binaryToHex(String bin) {
    String hex = Long.toHexString(Long.parseLong(bin, 2));
    return String.format("%" + (int)(Math.ceil(bin.length() / 4.0)) + "s", hex).replace(' ', '0');
}

I've used String.format() to left pad string with whitespaces then called replace() to replace it with zeros.

A: Just add the zeros manually. Here's one way:
public static String binaryToHex(String bin){
    return ("0000000000000000" + Long.toHexString(Long.parseLong(bin, 2)).replaceAll(".*.{16}", "$1");
}


text:
Q: How to get the height for the system navigation bar? I'm trying to get the height of the system navigation bar so that I can calculate the height of other widgets accordingly.
I was able to get the height of the screen. Is there a way to get the usable height?

usable_height = total_height-(status_bar_height +
  navigation_bat_height)

I'm using this method to get the total screen size:
double getScreenHeight(BuildContext context) {
  return MediaQuery.of(context).size.height;
}

A: If your Widgets need to know the size available to them then you can wrap them in LayoutBuilder which will have the width and height available to you Widget
Watch official sample here:
https://www.youtube.com/watch?v=IYDVcriKjsw
Some examples:

*

*How can I layout widgets based on the size of the parent?

*https://flutterwidgets.io/widget-of-the-week-layoutbuilder.html

But if want to know the AppBar height then AppBar height in Flutter


text:
Q: spring boot app not launching on Azure Linux VM I have a spring boot app that is running well on AWS Linux VM. Now, I am trying to run it on Azure Linux VM.
I am launching the application using this command (just like I am doing on AWS):
java -Dspring.profiles.active=prod  -jar /home/azureuser/myapp/myapp-server.jar
But nothing happens after this. It doesn't exit but there is no output/log message at all. Ideally, I should see output generated on the shell but it prints nothing. There is no error/exception stack trace.
The same jar is working fine on AWS Linux VM.
The only difference in my AWS and Azure VMs is that on AWS, I have Java 16:
openjdk version "16.0.2" 2021-07-20
OpenJDK Runtime Environment Corretto-16.0.2.7.1 (build 16.0.2+7)
OpenJDK 64-Bit Server VM Corretto-16.0.2.7.1 (build 16.0.2+7, mixed mode, sharing)

while on Azure VM, I have Java 17:
openjdk version "17.0.4.1" 2022-08-12 LTS
OpenJDK Runtime Environment Microsoft-40354 (build 17.0.4.1+1-LTS)
OpenJDK 64-Bit Server VM Microsoft-40354 (build 17.0.4.1+1-LTS, mixed mode, sharing)

But I have tested the jar on my local windows machine on Java 17 and it works fine.
Any idea what might be the issue? Is the output going somewhere else that I don't know about?

A: It is working. I launched the application and then got busy with something else. When I checked back on the window after 10-15 minutes, I saw the output.
The issue was that Azure VM is a lot slower/underpowered than AWS VM. Since the app starts up in a few seconds on AWS, I never imagined that it would be that slow on Azure. It is taking more than one minute for the first line of output to show and more than 5 minutes for the app to finish start up.


text:
Q: breadcrumbs for pages loaded in div my website consists only of one page where all other pages are loaded in a div, what i want to do is to create breadcrumbs to keep track of pages loaded inside the div, all the solutions i found in the internet works only for pages loaded in the whole window, so any one have better idea?
my page:

My Profile

Messages

My Conferences

Conferences

Requests

News

Options

function used to load pages in the div:
$("#nav a").click(function(event) {
    event.preventDefault();
    var page = $(this).attr("href");
    $("#collabsoft").slideUp("500",function() {
        $("#collabsoft").load(page,function() {
            $(this).slideDown(500);
        });
    });
    return false;
});

A: Use browser history widgets like jQuery bbq to keep track of the pages. This way you have both back button enabled and you'll be able to keep track of all the pages that the user visited. Be warned that is has a bit of a steep learning curve.

A: Yes, jQuery bbq is awesome I guess. But in my case recently, I used jQuery hashchange event.. it easy, light and simply did the work for me.
I haven't used breadcrumb, but for the pageheaders, I used $("#pageheader").text("header for div1/div2"); while loading the respective div with jQuery.


text:
Q: How I can solve this BJT?
I edited circuit like this:

I tried representing currents like:
$$
\begin{aligned}
&I_{R1}=100_{B1}+I_{B2}\\
&I_{R2}=101 I_{B2}-I_{B1}\\
&I_{i}=101 I_{B2}+100 I_{B1}
\end{aligned}
$$
Also I get:
$$
U_{BC1}=U_{BE1}-U_{CE1}=4,3(V)
$$
Then setting up equations from second Kirchoff law:
$$
I: U_{CB1}-U_{BE2}+I_{E 2} \cdot 1 k+I_{B 1} \cdot R=0
$$
$$
II:-I_{R 1} \cdot 18 k+I_{C 2} \cdot 7 k-U_{C B 2}=0
$$
$$
III:-25-I_{R 2} \cdot 2 k-I_{E 2} \cdot 1 k+U_{C E 2}-I_{C 2} \cdot 7 k=0
$$
$$
IV:-I_{E_{1}} \cdot 2 k+U_{CE1}-U_{BE2}+I_{E2} \cdot 1 k+I_{R 2} \cdot 2 k=0
$$
After solving system of equations I get wrong numbers so where is problem in this my method?
I'm safer with Symbolab so these are wrong results which I get: $$x=I_{B1}, y=I_{B2}, z=U_{CE}, q=R $$
$$x=I_{B1}=-\left(\frac{13.61731 \ldots}{2040000}\right), y=I_{B2}=-0.0000186856, z=U_{CE}=6.271711, q=R=1.503483 \cdot 10^{8}$$
https://www.symbolab.com/solver/system-of-equations-calculator/3.6%2B101%5Ccdot%20y%2B1000%2Bx%5Ccdot%20q%3D0%2C-18000%5Ccdot%5Cleft(100x%2By%5Cright)%2B7000%5Ccdot100%5Ccdot%20y-%5Cleft(-07%2Bz%5Cright)%3D0%2C-25-%5Cleft(101y-x%5Cright)%5Ccdot2000-101y%5Ccdot1000%2Bz-100y%5Ccdot7000%3D0%2C-101x%5Ccdot2000%2B4.3%2B101y%5Ccdot1000%2B%5Cleft(101y-x%5Cright)%5Ccdot2000%3D0

A: There's an easier way to find the DC Q points and R value starting the 5V for Vce1. (or UCE1 )

It is simpler because we were permitted to ignore I(R) thru T2 as it is only 0.5% more   (hFE=100 * 10uA vs Ie2~2mA ).  10uA/2mA*100%=0.5%

A: Here's a different approach. It's the way I thought about the problem:

simulate this circuit – Schematic created using CircuitLab
In the problem text, they suggest that \$I_{B_1}\$ and \$I_{B_2}\$ can be ignored (\$I_{B_1}\ll I_{C_1}\$ and \$I_{B_2}\ll I_{C_2}\$) for the purposes at hand. But that's obviously wrong. If it really were true, then there would be no current in \$R\$ and therefore no voltage drop and therefore no way to specify its value. So they lied, there. The base currents must be taken into account and the other part of the problem statement mentioning \$\beta_1=\beta_2=100\$ must be used. You can see that I took this last part into account in the above schematic.
Worrying about \$R_3\$ is pointless, as it is at \$Q_2\$'s collector. So all KVL analysis will start with the positive rail voltage, work it's way through \$R_1\$, and then from there along three separate paths. Let's assign the collector voltage for \$Q_1\$ the name, \$V_{C_1}=25\:\text{V} - 18\:\text{k}\Omega\cdot\left(100\cdot I_{B_1}+I_{B_2}\right)\$. Then, it follows that the three equations along the three different paths are:
$$\begin{align*}
V_{C_1}-5\:\text{V}-2\:\text{k}\Omega\cdot 101\cdot I_{B_1}&=0\:\text{V}\\\\
V_{C_1}-700\:\text{mV}-1\:\text{k}\Omega\cdot 101\cdot I_{B_2}-2\:\text{k}\Omega\cdot \left(101\cdot I_{B_2}-I_{B_1}\right)&=0\:\text{V}\\\\
V_{C_1}-700\:\text{mV}-1\:\text{k}\Omega\cdot 101\cdot I_{B_2}-R\cdot I_{B_1}-700\:\text{mV}-2\:\text{k}\Omega\cdot 101\cdot I_{B_1}&=0\:\text{V}
\end{align*}$$
This solves out as: \$I_{B_1}\approx 9.8031\:\mu\text{A}\$, \$I_{B_2}\approx 20.79151\:\mu\text{A}\$, and \$R\approx 153.019\:\text{k}\Omega\$. From those, you find that \$V_{E_2}\approx 6.28\:\text{V}\$ and \$V_{C_2}\approx 10.446\:\text{V}\$ and therefore that \$V_{\text{CE}_2}\approx 4.166\:\text{V}\$.

A: Well, we have the following circuit:

simulate this circuit – Schematic created using CircuitLab
I used Mathematica to solve it, using the following code:
Solve[{Ix == I1 + I4, I4 == I7 + I8, I2 == I5 + I3, Ix == I3 + I6,
  I1 == ((Vx - V2)/(R1)), I2 == ((V3 - V4)/(R2)), I3 == ((V4)/(R3)),
  I4 == ((Vx - V1)/(R4)), I5 == ((V4 - V5)/(R5)), I6 == ((V6)/(R6)),
  V1 - V3 == \[Alpha]1, V5 - V6 == \[Alpha]2, I1/I8 == \[Beta]1,
  I7/I5 == \[Beta]2, I2 == I8 + I1, I6 == I5 + I7}, {Ix, I1, I2, I3,
  I4, I5, I6, I7, I8, V1, V2, V3, V4, V5, V6}]

Your values gave and adding the fact that \$\text{V}_1-\text{V}_6=5\$:
Solve[{Ix == I1 + I4, I4 == I7 + I8, I2 == I5 + I3, Ix == I3 + I6,
  I1 == ((25 - V2)/(7000)), I2 == ((V3 - V4)/(1000)), I3 == ((V4)/(2000)),
  I4 == ((25 - V1)/(18000)), I5 == ((V4 - V5)/(R5)), I6 == ((V6)/(2000)),
  V1 - V3 == 7/10, V5 - V6 == 7/10, I1/I8 == 100,
  I7/I5 == 100, I2 == I8 + I1, I6 == I5 + I7, V1 - V6 == 5}, {Ix, I1, I2, I3,
  I4, I5, I6, I7, I8, V1, V2, V3, V4, V5, V6, R5}]

This gives:
{{Ix -> 9399043/3051390000, I1 -> 63443/30513900,
  I2 -> 6407743/3051390000, I3 -> 637783/305139000,
  I4 -> 3054743/3051390000, I5 -> 9971/1017130000,
  I6 -> 1007071/1017130000, I7 -> 9971/10171300,
  I8 -> 63443/3051390000, V1 -> 3549896/508565, V2 -> 3187465/305139,
  V3 -> 6387801/1017130, V4 -> 1275566/305139, V5 -> 2726133/1017130,
  V6 -> 1007071/508565, R5 -> 352097000/2301}}

Which is:
{{Ix -> 0.00308025, I1 -> 0.00207915, I2 -> 0.00209994,
  I3 -> 0.00209014, I4 -> 0.0010011, I5 -> 9.80307*10^-6,
  I6 -> 0.00099011, I7 -> 0.000980307, I8 -> 0.0000207915,
  V1 -> 6.98022, V2 -> 10.4459, V3 -> 6.28022, V4 -> 4.18028,
  V5 -> 2.68022, V6 -> 1.98022, R5 -> 153019.}}


text:
Q: Search API from external site I'm very new to Magento and am trying to figure out/setup a search API for the products in our catalog for an external site.
How do I enable the API in Magento to be able to call GET /api/rest/products?q=hat, which would return all hats in our list of products?
Another example, GET /api/rest/products?q=shoes, which would return all shoes in our list of products.

A: The problem is that magento's api has no search methods.
You can try searching products using filters:
$filters = array(
    'name' => array('like'=>'zol%')
);

$products = $proxy->call($sessionId, 'product.list', array($filters));

There are some extensions but they are not free. For example this one.
But you also can extend magento api by your own. This manual could help you.


text:
Q: Batch file to read multiple text lines in the text file I have a batch file.
set "firstLine="
for /f "tokens=*" %%A in (input.txt) do (
  If not defined firstLine set "firstLine=%%A"
  set Lastline=%%A
)
REM *** FIRST CHECK ***
if "EOF" NEQ "%Lastline%" goto :fail

call :extractDate firstLineDate firstLine
<file set /p line=
echo "%line%"
for /f "tokens=2 delims=|" %%# in ("%line%") do set "_date=%%#"
echo %_date%

call :convertToJulianDay julianFirstLine firstLineDate
REM GET MONTH, DAY, YEAR VALUES
FOR /F "TOKENS=1-3 DELIMS=/" %%A IN ("%1") DO SET MM=%%A& SET DD=%%B& SET YY=%%C
REM ELIMINATE LEFT ZEROS
SET /A DD=10%DD% %% 100, MM=10%MM% %% 100
REM CALCULATE JULIAN DAY NUMBER
IF %MM% LSS 3 SET /A MM+=12, YY-=1
SET /A A=YY/100, B=A/4, C=2-A+B, E=36525*(YY+4716)/100, F=306*(MM+1)/10, JDN=C+DD+E+F-1524

set "today=%date%"
call :convertToJulianDay julianToday today
REM GET MONTH, DAY, YEAR VALUES
FOR /F "TOKENS=1-3 DELIMS=/" %%A IN ("%1") DO SET MM=%%A& SET DD=%%B& SET YY=%%C
REM ELIMINATE LEFT ZEROS
SET /A DD=10%DD% %% 100, MM=10%MM% %% 100
REM CALCULATE JULIAN DAY NUMBER
IF %MM% LSS 3 SET /A MM+=12, YY-=1
SET /A A=YY/100, B=A/4, C=2-A+B, E=36525*(YY+4716)/100, F=306*(MM+1)/10, JDN=C+DD+E+F-1524

set /a diff=julianToday-julianFirstLine
REM *** SECOND CHECK ***
if %diff% NEQ 1 goto :fail
exit /b

:fail
echo File doesn't fit

And bellow is the sample input.txt
AML.DATA|01-JUN-2016
PORT_DATA|560538
NDB_AML_AA|43063
NDB_AML_LD|12878
NDB_AML_REPO|496
NDB_AML_TRAN|84596
NDB_AML_JOINT_AC|219873
NDB_AML_CUS_REL_PRTY|43
NDB_AML_BICCODE|108292
CUSTOMER_MASTER|684124
CATEGORY.MASTER|3288
DEPT.MASTER|2527
COUNTRY.MASTER|251
CUSTOMER.STATUS.MASTER|26
INDUSTRY.MASTER|65
JOB.TITLE.MASTER|22
COMPANY.MASTER|121
TRANSACTION.MASTER|3133
RELATION.MASTER|56
NDB_AML_TBILL_TBOND|2845
EOF

I want to modify my batch file to read the first line of the input.txt and if the date=sysdate-1 and the last line=EOF then proceed with the prog. But the bat file always say:
The system cannot find the batch label specified - extractDate
The system cannot find the file specified.
The system cannot find the batch label specified - convertToJulianDay
The system cannot find the batch label specified - convertToJulianDay

A: Reading the first line is simple.
If not defined firstLine set firstLine=%%A

Now you need to extract the date.
Then convert it to julian date.
Convert the system date to julian date,  too.
Compare the difference.
That's all
set "firstLine="
for /f "tokens=*" %%A in (input.txt) do (
  If not defined firstLine set "firstLine=%%A"
  set Lastline=%%A
)
REM *** FIRST CHECK ***
if "EOF" NEQ "%Lastline%" goto :fail

call :extractDate firstLineDate firstLine
call :convertToJulianDay julianFirstLine firstLineDate
set "today=%date%"
call :convertToJulianDay julianToday today

set /a diff=julianToday-julianFirstLine
REM *** SECOND CHECK ***
if %diff% NEQ 1 goto :fail
exit /b

:fail
echo File doesn't fit


text:
Q: Apache Spark: Write to multiple sheets in excel I need to write the datasets in different sheets of a single excel workbook.
I was able to achieve the same using the com.crealytics.spark.excel library.
df3.write()
   .format("com.crealytics.spark.excel")
   .option("dataAddress", "lines[#All]")
   .option("header", "true")
   .save("hdfs://${namenode}/" + outFile + ".xls");

fdf3.write()
    .format("com.crealytics.spark.excel")
    .option("dataAddress","newlines[#All]")
    .option("header", "true")
    .mode(SaveMode.Append).save("${namenode}/" + outFile + ".xls");

This is working good with smaller data and written in 2 separate sheets in a single worksheet, but it fails for larger data (Around 1GB file). So I switched to the new library org.zuinnote.spark.office.excel
df3.coalesce(1).write()
               .format("org.zuinnote.spark.office.excel")
               .option("write.spark.defaultsheetname", "lines")
               .option("hadoopoffice.write.header.write", true)
               .save("hdfs://${namenode}/" + outFile + ".xls");

fdf3.coalesce(1).write()
               .format("org.zuinnote.spark.office.excel")
               .option("write.spark.defaultsheetname", "newlines")
               .option("hadoopoffice.write.header.write", true)
               .mode(SaveMode.Append)
               .save("hdfs://${namenode}/" + outFile + ".xls");

But this is creating 2 excel files, not 2 sheets in a single workbook. Is there any option available to write it as new sheet in the workbook?


text:
Q: Edit/Create access in Dynamics CRM for non licensed users We have a scenario where we do not have enough licenses to provide to the users for Dynamics CRM Online. But we need these users to be able to edit/create rows in Appointments and Task tables. We have a license with Admin access. Can this license be shared or used in such a way that users can edit these tables through any other interface say using Power Apps or so? Is there any way to enable them to edit the tables?

A: What you can do is, get the per-user-per-app license for users so they can use Canvas app and get authenticated using AD SSO.
You can use the Admin service account to do data interactions into Dynamics CRM using MS Flow/Power Automate. Essentially CDS connector will use the licensed CRM admin account in the backend. Honestly I never tried this.
Another user also used HTTP request to use LogicApps to POST the data without license. Reference
PowerApps portals is another option.


text:
Q: How to calculate proper R value for RC filters in amplifier power supply This is an extension of a question I asked yesterday here regarding power rail sag I was seeing (turns out I was indeed dropping below the regulator dropout voltage).
I'm trying to figure out how I would obtain the appropriate values for the calculations to devise a proper resistor value if I did indeed want to include one or more RC filters in the power supply rails.
If I were trying to implement an amplifier circuit (past the power supply of this schematic, so the everything but the included power supply) and run a variable load of 16 ohm headphones up to 600 ohm headphones to a reasonable volume, how do I calculate this?  The amplifier circuit is just for reference, it wouldn't be this exact one but similar in nature (two stages, gain and buffer)
Amplifier schematic:

PSU schematic I'm testing with from the previous post:

I tried removing the first set of resistors (of the two in series, so now just 10ohms) to make the reservoir larger but still leave one RC filter, but because I'm not quite sure how to calculate the proper resistor value it ended up instantly frying the leftover resistor once powered.
Sorry for my ignorance on the subject.  I have a basic understanding of calculating various parts of a circuit, but this is much more complex than I've tried before.

A: Overview
Let me start with some thoughts about using headphones. Typically (I think, but I'm open to correction), headphones are arranged as \$32\:\Omega\$ devices. (They will range upwards towards \$600\:\Omega\$, today, though I commonly used very sensitive \$2\:\text{k}\Omega\$ headphones "back in the day." (Hard to find, now.) The power output offered on devices like cell phones (where available) is usually in the small number of milliwatts: perhaps as much as \$10\:\text{mW}\$, give or take. So, assuming a simple sine wave (I need to state that assumption because music and other audio isn't a simple sine wave), the expected peak output voltage will be on the order of \$V_\text{PEAK}=\sqrt{2\cdot R\cdot P}\approx 800\:\text{mV}\$. In short, if the output of a single channel can handle a \$\pm1\:\text{V}\$ swing, you've done more than enough.
Now, amplifiers can be fixed-gain (if we are building one of these on a protoboard) or support a volume control (if making something commercial and more useful.) The above computations were maximum output swing values, assuming the volume control is at its maximum output position. Of course, less swing works fine if you want a lower volume. But the above gives you a back-of-the-envelope estimate of your output requirements.
This relates directly back to your power supply rail requirements. An amplifier system will need voltage rails (of course) in order to operate well. But the closer those rails are (within circuit limitations of course) to the maximum needs at the output, the less wasted power their will be and the easier/cheaper the power supply itself often will also be. You don't want to cut corners. But there's no reason for a \$\pm 12\:\text{V}\$ power supply, if your output isn't ever going to need to do better than \$\pm 1\:\text{V}\$ at its output. Opamp outputs (and inputs) have limitations when they get near their rail voltages. And a BJT circuit will have its own requirements for "voltage headroom." If you want to be generous, I'd say that you should add another \$3\:\text{V}\$ to your output requirements. In this case, I don't think you need more than \$\pm 5\:\text{V}\$ and almost certainly could live very well at \$\pm 4\:\text{V}\$.
So my first thought about your power supply is to reduce the voltage to one that provides \$4.5\:\text{V}\$ with \$\pm 500\:\text{mV}\$ allowable ripple on the supply. Of course, if you already have the transformer and parts then that's another issue.
Also, you really only need to have a peak current compliance of perhaps \$\pm 30\:\text{mA}\$ and certainly no more than \$\pm 50\:\text{mA}\$ at the output. To be honest, this earlier figure of \$\pm 30\:\text{mA}\$ is very close to what you can expect from many simple and cheap opamps. So your headphone needs are well within easy grasp of an opamp circuit, with only minor worries to consider later. This calculation helps validate the first-glance appearances of your circuit, which uses opamp outputs directly (without added external devices to boost compliances.) So that makes me happy, without bothering to check the datasheets on your opamps.
Unregulated Power
A transformer is obvious. This both isolates your circuit from the mains supply and also efficiently steps down the voltages to something closer to your needs. A center-tapped transformer makes using a bridge rectifier easy to use in creating a pair of plus and minus voltage rails, too. So all that is to the good and pretty easy to follow.
Given that, you now have some capacitors added to the circuit. If you add these directly after the diode bridge, then when you power things up there will be very high currents running through the diode bridge as it works to "fill" the capacitors to their nominal voltages. Once that's reached, of course, it calms down a lot.
But it might be best in your case if you'd skip the first bank of capacitors and just focus on using a set of resistors followed by capacitors. The resistors will automatically limit that in-rush of current. And, to be honest, you really don't need a direct connection from the capacitors backwards to the transformer. We are only talking about something like \$10\:\text{mW}\$ per channel (left channel/right channel) or a total of \$20\:\text{mW}\$ into the headphones (if very loud.) If you assume the power supply is designed for \$500\:\text{mW}\$ per rail, it's still a very tiny power supply and the resistors won't interfere much. But they will help protect against the in-rush current and also help "filter" away the ripple.
You could, if you want to be aggressive about it, add another set of resistor+capacitor filters to each side. If so, then your circuit would be extended by adding resistors going from the bridge DC outputs to their first capacitors. But the calculations of the final ripple would take me further than I want to go. So I'm just going to help with calculation of a single, loaded RC filter, exposed to the \$120\:\text{Hz}\$ pulses available at the output of the bridge rectifier.
Filter Capacitor Calculations
In steady state conditions, under load, the capacitors will supply current for the amplifier system and your headphones for some of each \$120\:\text{Hz}\$ period -- in short, for only some part of each \$8.3\:\text{ms}\$ period. But as soon as the next cycle rises upwards enough, the diodes move rapidly into forward conduction and then they (and the transformer) supply the current needed to re-charge the capacitors as well as supply the amplifier system and headphone loads. At the very peak of this next cycle, the voltage at the transformer moves downward again and soon enough the transformer ceases to supply the current. And the load shifts back over to the capacitor.
If there were no load at all, then the capacitors would charge up at the beginning and then nothing much else would happen. But with a load, the voltage on the capacitors will decline as current is drawn from them. Similarly, as the bridge rectifier activates, it will re-charge the capacitors through the (suggested) resistors. The resistors will limit that inflow of current to safe values, but that also means they will make it take longer to charge up the capacitors.
For simple purposes, you can assume that both the process of charging the capacitors upward via the resistors and the process of discharging them into the load is linear, with a computation that looks something like:
$$\Delta V = \Delta t\frac{I}{C}$$
Here, \$I\$ is the total current (\$I_R\$ if charging or \$I_\text{LOAD}\$ if discharging) and \$C\$ is the capacitance, of course. In steady state, the meaning of \$\Delta V\$ will be your allowed peak-to-peak ripple -- obviously, the rise from the minimum capacitor voltage to its maximum must equal the fall from the maximum to its minimum. So that one you can just plug in as you like it. Finally, \$\Delta t\$ will be \$t_\text{charge}\$ when charging through \$R\$ or else \$t_\text{discharge}\$ when supplying current to the amplifier and headphones.
Again, note that the rising \$\Delta V\$ must, in steady state, be equal to the falling \$\Delta V\$. So it follows easily that \$\Delta t_\text{charge}\frac{I_R}{C}=\Delta t_\text{discharge}\frac{I_\text{LOAD}}{C}\$. Cancelling \$C\$, it's \$\Delta Q =  I_R\cdot \Delta t_\text{charge}= I_\text{LOAD}\cdot \Delta t_\text{discharge}\$.
It turns out that charge is everything. I'd mentioned the equation of \$\text{d} Q = C\cdot \text{d} V\$ or, in finite terms, \$\Delta Q = C\cdot \Delta V\$. This means that there will be a certain change in charge on the capacitor during the charging period and the same change (but with opposite sign) in charge during the discharging period. Current times time is charge, so \$\Delta Q = I_R\cdot\Delta t_\text{charge}=I_\text{LOAD}\cdot \Delta t_\text{discharge}\$. You also know that \$\Delta t_\text{charge}+\Delta t_\text{discharge}\approx 8.33\:\text{ms}\$.
Intuitively, I think you may begin to feel that there is something here that allows us to work towards both a good value for \$C\$ as well as \$R\$. Let's put down some numbers. Suppose we go with my \$V_\text{CC}=4.5\:\text{V}\$ with \$\pm 500\:\text{mV}\$. Then this means that \$\Delta V=1\:\text{V}\$, as the voltage at the capacitor goes from \$4\:\text{V}\$ to \$5\:\text{V}\$ and back, again. (Similarly for the negative rail.) Suppose we also decide that our amplifier and headphones will present a total average load of \$I_\text{LOAD}=100\:\text{mA}\$ (per rail.) [Note we are setting up budgets right now for the design.] And finally, let's just assume that the capacitors are supplying the load for "most of the time."
I say "most" and not "all" because if you assumed the capacitors supplied all of the load current, all of the time, there'd be no time for charging them back up and the required \$I_R\$ would be infinite. We know that's crazy. So we know the capacitors will only supply load current for "most of the time." We know also that it will be most because if it weren't most of the time, then the bridge rectifier and resistor would be supplying it and that would imply lots of ripple because that's what the rectified AC pulses "look like" (rising from zero to the max value and then back to zero.) Since we know that's not the case (or, at least, we hope it's not), we can conclude that in any design we care about the capacitors will be supplying the load for most of the \$8.33\:\text{ms}\$ period.
Calculus would let you work out the details. But let's say that since we are going from \$4\:\text{V}\$ to a peak of \$5\:\text{V}\$, then it must be the case that the angle at which charging starts must be about \$\operatorname{sin}^{-1}\left(\frac45\right)\$, stopping near \$90^\circ\$, out of a total of \$180^\circ\$ (each \$120\:\text{Hz}\$ period is half of a sinusoidal period.) This suggests about 20% charging time and 80% discharging time, as a broad guess.
Keeping it very simple, then, we find that \$C=80\%\cdot t_\text{period}\cdot \frac{I_\text{LOAD}}{\Delta V}\approx 666\:\mu\text{F}\$. We'd round that to \$C=680\:\mu\text{F}\$.
Resistor Calculations
I find now that the average charging current through \$R\$ must be four times more, because the time available for charging is four times shorter. We want the peak value, though, for \$I_R\$, which will be about twice the average. So in this case the peak current will be \$2\cdot 4\cdot 100\:\text{mA}\$ or \$800\:\text{mA}\$. As the peak voltage (over the minimum voltage of the once-discharging capacitor) is \$1\:\text{V}\$ (our \$\Delta V\$, so to speak), then \$R=\frac{1\:\text{V}}{800\:\text{mA}}=1.25\:\Omega\$. We can choose a nearby standard value of \$R=1.2\:\Omega\$.
Transformer
With that in hand, the last bit of business is the transformer secondary voltage. With current peaks mentioned above, I'd expect at least one volt and probably more across a diode in the bridge, at peak charging current. (Which occurs close to where the capacitor voltage is at its minimum.) We know the voltage drop across the resistor is \$\Delta V=1\:\text{V}\$, at this moment. So I figure that one side of the center tap must be \$V_{\text{C}_\text{MIN}}+\Delta V+V_\text{DIODE}=4.0\:\text{V}+1\:\text{V}+1.2\:\text{V}=6.2\:\text{V}\$, or about \$4.4\:\text{V}_\text{RMS}\$. Doubled to get both sides of the transformer, that's a secondary rated for \$\ge 8.8\:\text{V}_\text{RMS}\$. (There are more details in specifying an appropriate transformer, such as its "regulation %" and current handling, etc.) But that gives an idea. I'd probably select a \$9\:\text{V}_\text{RMS}\$, center-tapped transformer in this case.
Validation
I promise you that I did not, in any way at all, attempt to do anything with Spice prior to writing the above text. It came entirely from a "stream of consciousness" and nothing more. I was, of course, interested in verifying what I wrote to you. So just a few minutes ago I cobbled up a behavioral Spice schematic to test myself and make sure I didn't completely screw up along the way.
Here is the schematic and resulting waveforms for both rails:

I used a \$45\:\Omega\$ resistor for the load, as this is what I'd assume given an average rail voltage of \$4.5\:\text{V}\$ and a desired average current of \$100\:\text{mA}\$. The \$X\$ parameter on the schematic is just the RMS voltage for the transformer.
Close enough.
[More can be done, of course. But then you'd be deep into coursework and I'd need to write a book, or something (which I promise you I'm not qualified to write.) Since these books have been written by qualified, well-informed authors, I'd suggest you start simple like this but then also consider books and/or just sitting down with paper and pencil to work outward from here, questioning my various (somewhat incorrect) assumptions and thinking more closely. Over time, you'll find interesting nooks and crannies where the above doesn't work well and then you'll expand your reach. For example, there is definitely one place where I seriously glossed over a detail that provides you with a quantity twice the value you'd see with an oscilloscope, but which as you can see from simulation works out in the end and keeps this simpler to write about.]

A: Why don't you put in a higher frequency DC:DC stage to convert your input to something close to the +/- rails, then either use LDO or emitter followers to drop to the rail voltage, removing most of the ripple?
The DC:DC ripple can easily be up at 1MHz or beyond so already beyond audio frequency.
This is going to give you much better supply ripple rejection than a couple of first order filters and in much smaller, cheaper parts.  No need for high power resistors or big caps.


text:
Q: Receive a single weight from scale Using a button press I am tasked with creating a Windows form application for the factory i work for.
We will be weighing multiple bags, so every time the button is pressed it must send the weight that is currently on the scale. In other words just capture the current weight and wait for me to press the button again to capture the next bag that will be loaded on the scale. Currently it continuously receives data from the scale once the button is clicked and the result only flashes in my textbox. I want to change so it only receives one weight then stops. Can you please show me how i can accomplish this.
Thank you in advance
Below is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using Microsoft.Office.Interop.Excel;
namespace ScaleV5
{
    public partial class Form1 : Form
    {
        private SerialPort _serialPort;         //<-- declares a SerialPort Variable to be used throughout the form
        private const int BaudRate = 9600;      //<-- BaudRate Constant. 9600 seems to be the scale-units default value
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] portNames = SerialPort.GetPortNames();     //<-- Reads all available comPorts
            foreach (var portName in portNames)
            {
                comboBox1.Items.Add(portName);                  //<-- Adds Ports to combobox
            }
            comboBox1.SelectedIndex = 0;                        //<-- Selects first entry (convenience purposes)
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //<-- This block ensures that no exceptions happen
            if (_serialPort != null && _serialPort.IsOpen)
                _serialPort.Close();
            if (_serialPort != null)
                _serialPort.Dispose();
            //<-- End of Block

            _serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One);       //<-- Creates new SerialPort using the name selected in the combobox
            _serialPort.DataReceived += SerialPortOnDataReceived;       //<-- this event happens everytime when new data is received by the ComPort
            _serialPort.Open();     //<-- make the comport listen
            textBox1.Multiline = true;
            textBox1.Text += $"Listening on " + _serialPort.PortName + $"\r\n";

        }

        private delegate void Closure();
        private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
        {
            if (InvokeRequired)     //<-- Makes sure the function is invoked to work properly in the UI-Thread
                BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));     //<-- Function invokes itself
            else
            {
                int dataLength = _serialPort.BytesToRead;
                byte[] data = new byte[dataLength];
                int nbrDataRead = _serialPort.Read(data, 0, dataLength);
                if (nbrDataRead == 0)
                    return;
                string str = System.Text.Encoding.UTF8.GetString(data);
                textBox1.Text = str.ToString();

                _serialPort.WriteLine("w");

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Clear();

        }

        private void button3_Click(object sender, EventArgs e)
        {
            _serialPort.Close();
            this.Close();

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {

        }
    }
}

A: *

*put the entire port instantiation and closing/opening code into the SelectedIndexChanged event of the combobox. When the user chooses a port you simply open it and leave it open. Opening and closing ports takes time. So you should keep it to a minimum.

*When pressing the button you would only probe the scale via the port for the values. (If you really have 2 modes of operation choose the single measurement)
 private void button1_Click(object sender, EventArgs e)
 {
    // probe device for value
    _serialPort.WriteLine("w");

    Thread.Sleep(100);

    string response = _serialPort.ReadExisting();
    // here parse the resonse to extract you value

    // stop the device
    _serialPort.WriteLine("w");

    textBox1.Multiline = true; // <- this code belongs into the constructor
    textBox1.Text += extractedStringValue;

 }

disclaimer: this code runs synchronously and will block the UI. It depends strongly on your device how long it need to responde to your first request of measurements. To avoid the blocking of the UI you would need to work with async/await.


text:
Q: Multiple selection UITableView without dequeueReusableCellWithIdentifier When selecting multiple cells in my tabeview the cells out of view are being selected too. I understand that this is because i am reusing the cell and its maintaining its selection as i scroll down. I have found a few people with similar issues but cant translate their solutions across to resolve my issue. I have tried not dequeing a cell and just use:
 let cell = NewBillSplitterItemCell()

but get:
 unexpectedly found nil while unwrapping an Optional value

on the line:
cell.currentSplitters.text = splitterList

in the following code:
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        fetchBillItems()

        let cell: NewBillSplitterItemCell = tableView.dequeueReusableCellWithIdentifier("NewBillSplitterItemCell") as! NewBillSplitterItemCell
        let item = allItems[indexPath.row]
        let numberOfSplitters = item.billSplitters?.count

        if numberOfSplitters == 0 {
            cell.currentSplitters.text = "No one is paying for this item yet."
        } else {

            var splitterList = "Split this item with "
            let itemSplitters = item.billSplitters?.allObjects as! [BillSplitter]
            for i in 0...Int((numberOfSplitters)!-1) {
                if numberOfSplitters == 1 {
                    splitterList += "\(itemSplitters[i].name!)"
                } else {
                    splitterList += ", \(itemSplitters[i].name!)"
                }
            }
            cell.currentSplitters.text = splitterList
        }

        cell.name.text = item.name
        cell.price.text = "£\(item.price!)"

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if let cell = tableView.cellForRowAtIndexPath(indexPath) {
            if cell.accessoryType == .Checkmark
            {
                cell.accessoryType = .None
                selectedItems.removeAtIndex(selectedItems.indexOf(allItems[indexPath.row])!)
            } else {
                cell.accessoryType = .Checkmark
                selectedItems.append(allItems[indexPath.row])
            }
        }
    }

I dont quite understand what to do and any help would be great. Thanks

A: In addition to what @Mike said, inside of cellForRowAtIndexPath you need an additional check because cells get reused.
Something along the line
let isSelected = selectedItems[indexPath.row].selected
if isSelected{
    cell.accessoryType = .Checkmark
} else {
    cell.accessoryType = .None
}

Same thing inside of didSelectRowAtIndexPath you should update the data source instead of relying on the UI of your cell for that condition.

A: Assuming your cell is nil, you should use
let cell = tableView.dequeueReusableCellWithIdentifier("..." forIndexPath:indexPath) as! NewBillSplitterItemCell

instead of
let cell= tableView.dequeueReusableCellWithIdentifier("...") as! NewBillSplitterItemCell

This ensures that cell will never be nil.
Also, I would check if the correct identifier is being used in all of your .xib .storyboard files.


text:
Q: Query works in MSSQL, but not in LINQ I have a method that receives a name of either a Group or a User (email) and has to return the Abstract_Entity object of the Group or User.
The MSSQL query seems to work in all cases, but the only time the LINQ query works is when the string is the email of a user.
TranslateUserOrGroup(string name): Abstract_Entity
Do you guys see any difference in the MSSQL query and the LINQ code?
The LINQ query
return (from e in complementCoinsEntities.Abstract_Entity.AsNoTracking()
     join eg in complementCoinsEntities.Entity_Group on e.ID equals eg.entityID
     join g in complementCoinsEntities.Group on eg.groupID equals g.ID
     join u in complementCoinsEntities.User on e.ID equals u.userID
     where userOrGroup == u.email || userOrGroup == g.name
     select e).SingleOrDefault();

The MSSQL query
select DISTINCT ae.ID
from Abstract_Entity ae
join Entity_Group eg on ae.ID = eg.entityID
join [Group] g on eg.groupID = g.ID
join [User] u on ae.ID = u.userID
where g.name = 'test' OR u.email = 'test'

A: I would start by peeling away the SingleOrDefault and ToList() the results in the Immediate Window to see what query results are being returned. It's likely you're stripping away matching rows trying to use SingleOrDefault instead of DISTINCT. They do not function the same. So take away 'DISTINCT' in your SQL query and remove the SingleOrDEfault call, and assign to an object and run ToList and put a breakpoint. You should see what's different.
Specifically: SingleOrDefault may key on multiple results and you are not guaranteed to get any specific result back (including a null result).

A: .SingleOrDefault()

Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

have you tried .FirstOrDefault() ?


text:
Q: Values change unexpectedly after function is called can you lease tell me why S[f'{colors[0]}'] is changing after calling this function, and how to fix it.
S = {"1": list(range(0,5)), "2": list(range(20,25)), "3": list(range(10,15))}
colors = [1, 2 ,3]

def count_bycolor(colors):
    countries_bycolor = S[f'{colors[0]}']
    for i in range(1, len(colors)):
        countries_bycolor.extend(S[f'{colors[i]}'])
    return countries_bycolor

count_bycolor(colors)
len(S[f'{colors[0]}'])
count_bycolor(colors)
len(S[f'{colors[0]}'])

Thank for your help, and happy holidays!

A: You are performing operations on a list in a dict. Both of these are mutable objects and due to python being passed by reference pass-by-object-reference that has this consequence of changing your "original" object (it's the same object).
This means that you need to make copies of those objects if you want to operate on them without changing the original.
Based on your question it could be as simple as one line change:
import copy

def count_bycolor(colors):
    countries_bycolor = copy.copy(S[f'{colors[0]}'])
    for i in range(1, len(colors)):
        countries_bycolor.extend(S[f'{colors[i]}'])
    return countries_bycolor

count_bycolor(colors)

>>> [0, 1, 2, 3, 4, 20, 21, 22, 23, 24, 10, 11, 12, 13, 14]

S

>>> {'1': [0, 1, 2, 3, 4], '2': [20, 21, 22, 23, 24], '3': [10, 11, 12, 13, 14]}


text:
Q: Java BigDecimal without E I have a BigDecimal variable
BigDecimal x = new BigDecimal("5521.0000000001");

Formula:
x = x.add(new BigDecimal("-1")
      .multiply(x.divideToIntegralValue(new BigDecimal("1.0"))));

I want to remove the integer part, to get the value x = ("0.0000000001"), but my new value is 1E-10 and not the 0.0000000001.

A: Try using BigDecimal.toPlainString() to get value as plain string as you require.

A: To get a String representation of the BigDecimal without the exponent part, you can use
BigDecimal.toPlainString(). In your example:
BigDecimal x = new BigDecimal("5521.0000000001");
x = x.add(new BigDecimal("-1").
              multiply(x.divideToIntegralValue(new BigDecimal("1.0"))));
System.out.println(x.toPlainString());

prints
0.0000000001

A: Perhaps using BigDecimal isn't really helping you.
double d = 5521.0000000001;
double f = d - (long) d;
System.out.printf("%.10f%n", f);

prints
0.0000000001

but the value 5521.0000000001 is only an approximate representation.
The actual representation is
double d = 5521.0000000001;
System.out.println(new BigDecimal(d));
BigDecimal db = new BigDecimal(d).subtract(new BigDecimal((long) d));
System.out.println(db);

prints
5521.000000000100044417195022106170654296875
1.00044417195022106170654296875E-10

I suspect whatever you are trying to is not meaningful as you appear to be trying to obtain a value which is not what you think it is.

A: If you want to do this at your BigDecimal object and not convert it into a String with a formatter you can do it on Java 8 with 2 steps:

*

*stripTrailingZeros()

*if scale < 0 setScale to 0 if don't like esponential/scientific
notation

You can try this snippet to better understand the behaviour
BigDecimal bigDecimal = BigDecimal.valueOf(Double.parseDouble("50"));
bigDecimal = bigDecimal.setScale(2);
bigDecimal = bigDecimal.stripTrailingZeros();
if (bigDecimal.scale()<0)
bigDecimal= bigDecimal.setScale(0);
System.out.println(bigDecimal);//50
bigDecimal = BigDecimal.valueOf(Double.parseDouble("50.20"));
bigDecimal = bigDecimal.setScale(2);
bigDecimal = bigDecimal.stripTrailingZeros();
if (bigDecimal.scale()<0)
bigDecimal= bigDecimal.setScale(0);
System.out.println(bigDecimal);//50.2
bigDecimal = BigDecimal.valueOf(Double.parseDouble("50"));
bigDecimal = bigDecimal.setScale(2);
bigDecimal = bigDecimal.stripTrailingZeros();
System.out.println(bigDecimal);//5E+1
bigDecimal = BigDecimal.valueOf(Double.parseDouble("50.20"));
bigDecimal = bigDecimal.setScale(2);
bigDecimal = bigDecimal.stripTrailingZeros();
System.out.println(bigDecimal);//50.2


text:
Q: How do I respond to a buffer/stack overflow From a security perspective, how do I respond if I have discovered a stack overflow?

A: *

*Disable.
Take the service offline. This will help prevent further damage.

*Verify.
Make sure that the issue is reproducible.

*Find.
Inspect the code to see what the cause is.

*Repair.
Effect the changes required to ensure that the issue does not happen again due to the same cause.


text:
Q: Use MPI_Barrier() to improve performance and avoid buffer issues? Can I do something like this to improve performance and avoid buffer problems I am running into for higher iterations. MaxIterations = 6000
While(numberIterations<= MaxIterations)
{
   MPI_Iprobe() -- check for incoming data
    while(flagprobe !=0)
    {
        MPI_Recv() -- receive data
        MPI_Iprobe() -- loop if more data
    }

   updateData() -- update myData

   for(i=0;i<N;i++) MPI_Isend(request[i]) -- send request

   for(i=0;i<N;i++) MPI_Wait(request[i]) --wait till request is complete

   if(numberIterations = MaxIterations) { MPI_Barrier() }

   numberIterations ++

}


text:
Q: how to play notification sound in html5 android app : [phonegap]? straight to the point, I have developed a normal web app with html5, js and css3 with scripting language as PHP. I wrapped it up using build.phonegap with a proper config.xml. That application has a code to count the total due on some customers, and it it showing alert if the money due reaches to certain limit. The only point I am lagging into is how to put this alerts with notification sounds (ringtones/alerts).
I have googled it all over but coudn't find anything. Can somebody guide me in proper direction that how it should be implemented in android html5 apps??

A: Have you used the Media plugin?
http://docs.phonegap.com/en/edge/cordova_media_media.md.html#Media

A: You simply need to write this:
navigator.notification.beep(1);
The only parameter beep() function takes is for the length of your notification sound.
By default it will make the notification sound you hear on common alerts like for an SMS or other updates.


text:
Q: How to Merge all Text files in a Single file with Broken Lines? I'm using the codes below to combine all text files from a folder to a simple files, the problem is that the code does not break lines and ends up blending the words.
copy *.txt Combined.txt

Echo.
Echo Done!
Echo.

pause

When it ends it, he stay like this:
abcblue

123abcyellow

123abc

When I expected it to go like this:
ABC

blue

123

abc

yellow

123

abc

Whats wrong?
NOTE: I found this snippet of code on the internet and it looks like the subject:
FOR %f IN (*.txt) DO type %f >> Combined.txt & echo. >> Combined.txt

In this context:
type file1.txt >> newfile.txt
echo. >> newfile.txt
type file2.txt >> newfile.txt
echo. >> newfile.txt
type file3.txt >> newfile.txt
echo. >> newfile.txt

But I need it to automatically grab all text files and combine.

A: As long as the files are properly formed Windows (CRLF) ANSI text files then you could consider using Type?
Type *.txt>"..\Combined.txt"

This 'should' write to Combined.txt in the parent of the current directory. I have done this to prevent the command from trying to read it's own content, as it is also a .txt file. Feel free to replace "..\Combined.txt" with a specific path if you prefer.
If you would like the file names above each output .txt file then try changing the command to this:
Type *.txt>"..\Combined.txt" 2>&1

Edit
An additional option which also should prepend files with their names:
Find/V "" *.txt>"..\Combined.txt"


text:
Q: In SwiftUI, I have an object in view1 and a button in view2, I want to change the value of object on a button pressed from view 2. How I do this? I am new to SwiftUI, I've designed the UI using swiftUI, and I have designed a reusable button in another view which I have called in view1. Now how can I make changes into view1 when I tap the button ?
This is my View 1:
struct ContentView: View {

@State var RandomNumber = 1

var body: some View {
    ZStack{
        Color(#colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1))
            .edgesIgnoringSafeArea(.all)

        VStack{
            Image("RollLogo")
            .background(
                Color.clear
                .blur(radius: 4.0)
                .offset(x: -2, y: -2)
            )
            .shadow(color: Color(#colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)), radius: 20.0, x: 10.0, y: 10.0)
            .shadow(color: Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)), radius: 20.0, x: -10.0, y: -10.0)

            Spacer()
            HStack {
                DiceImage(n: RandomNumber)
                //DiceImage(n: 1)
            }.padding(.horizontal)
            Spacer()

            Buttons(CustomColor: Color("Accent"))
            .padding(.top)
            Spacer()

        }
    }
  }
}

In view2 I have a rectangular view with gesture enabled. Now when I tap on it, am generating a random number, Now this random number I want to assign in view1 state variable.
.onTapGesture {
                let numberr = Int.random(in: 1...6)
                print("Am tapped",numberr)
        }

A: You should pass RandomNumber by binding
HStack {
    DiceImage(n: $RandomNumber)    // << here !!
}.padding(.horizontal)

and in DiceImage
struct DiceImage: View {
   @Binding n: Int

   ...

   .onTapGesture {
                let numberr = Int.random(in: 1...6)
                print("Am tapped",numberr)
                self.n = numbers               // << here !!
        }
   ...
}


text:
Q: Purpose for the conditions of Link Function I am studying GLM at the moment and have a few questions regarding link functions.

*

*Why are the conditions of the link function to be smooth monotonic function? What properties are preserved by having such conditions?

*Furthermore, a lot of material that I am reading always takes the inverse of the link function $g$, but since the conditions are monotonic, an inverse is not guaranteed. So what happens if the link function does not have an inverse?
Any clarification will be much appreciated!

A:
Why are the conditions of the link function to be smooth monotonic function? What properties are preserved by having such conditions?

For a glm the mean $\mu$  is linked to the linear predictor $\eta=\beta^T x$ by the link function $g(\mu)=\eta$. Assuming the link function has an inverse, $g^{-1}=m$, we find that
$$ m(g(\mu))=g^{-1}(g(\mu))=\mu$$  or
$$ \mu =m(\eta) $$ so we call $m$ the mean function. If $g$ where not strictly monotone, so it had no inverse, then the equation
$$ g(\mu)=\eta$$ would have multiple solutions, and so the linear predictor $\eta$ would not specify a unique mean!
How woud you then relate your glm model to data? How wpuld you estimate the parameters $\beta$ if the same observed mean could be equally explained by different parameter values? It would not work.

Furthermore, a lot of material that I am reading always takes the inverse of the link function , but since the conditions are monotonic, an inverse is not guaranteed. So what happens if the link function does not have an inverse?

What is meant is strictly monotonic, and then an inverse always exists. The above paragraph explains what will happen if an inverse does not exist. Therefore, existence of an inverse is part of the definition of an glm.
As for your new question in comments:

What is the purposes of the differentiable condition?

That condition is maybe not as fundamental as is monotonicity, but as soon as you start to develop the likelihood theory for glm's, first and second derivatives start to appear. Maybe one could do without it, but the theory would be more difficult, and the need does not seem to be there. Also, numerical optimization of non-differentiable functions is more difficult. But if you see some application for a non-diff link function, just try!


text:
Q: Powershell Remove-Item get Loggingfile i have probably searched the whole web, but I'm not able to help myself. Otherwise I'm just incapable.
All I want is to delete folders after 30 days and display the results in a simple .log file.
dir "C:\Users\sam\Desktop\Files_todelete\*" -ErrorAction SilentlyContinue | Where { ((Get-Date) - $_.LastWriteTime).days -gt 30 } | Remove-Item -Recurse

This works for me, but I tried nearly everything to log the results.
Hopefully you can help me to fix this issue.

A: You need to include logging part to your script. You can make foreach loop for every item that needs to be removed and write down activity to log file. Here is an example:
$LogFile = 'C:\log.txt'
dir "C:\Users\sam\Desktop\Files_todelete\*" -ErrorAction SilentlyContinue |
    Where { ((Get-Date) - $_.LastWriteTime).days -gt 30 } |
        ForEach-Object {
            Remove-Item $_.FullName -Recurse
            Out-File -InputObject $('Removed {0}' -f $_.FullName) -FilePath $LogFile -Append
        }

A: So in this case it worked for me, but I want to use the Script for network drives. If I edit the path everything seems to be fine. But the problem here is the permission. Therefore I found a solution with Get-ChildItem -Directory.
My question here is can pipe this in front of the Remove-Item command?
Like:
$LogFile = '\netshare\folder\log.txt'
dir "\netshare\Files_todelete*" -ErrorAction SilentlyContinue |
Where { ((Get-Date) - $_.LastWriteTime).days -gt 30 } |
ForEach-Object {
Get-ChildItem -Directory | Remove-Item $_.FullName -Recurse
        Out-File -InputObject $('Removed {0}' -f $_.FullName) -FilePath $LogFile -Append
    }

Logically the Get-ChildItem needs to be in front of the loop?! But I'm not that firm to edit the beginning of the loop correctly.


text:
Q: Position middle container right after the one before, but docked to bottom I have a web page that consists of a header, slider menu content and footer.
I need the content to start from the menu (menu size and location is based on the elements above that depends on device), and it should always be 25px from the bottom overlapping the footer.
If I try to make it relative, it hangs to the middle and doesn't reach the end, if I make it absolute, I have to specify the value it should be started from which is dynamic.
Is there an efficient way to do this?
UPDATE
I don't mind doing it with jQuery as long as the top of the content is dynamic and depends on the previous element no matter what it is.
UPDATE
Here's an abstract example to what I need.
The footer should always be anchored to the bottom (later I'll apply sticky footer technique, here my issue is the content), the header, slider and menu are anchored to element above, the content should be anchored to the element above and to the footer.

A: your not very clear with what you want exactly. so I've made some assumptions.
(all of those assumptions can be corrected if I assumed wrong).
Assumptions:

*

*Header should scroll with the content. (that behavior can be changed if you want)

*the scroll should be applied on the 'Content Zone' only. (that behavior can be changed if you want)

*the content wrapper should always span to the end of the page, even if the physical content is smaller then that. and should have a scrolling only when the physical content is larger than the available space. (that behavior can be changed if you want)

[as you can see, all of those behaviors can be changed with the correct CSS]
Here is a Working Fiddle

*

*this is a pure CSS solution. (I always avoid scripts if I can)

*cross browser (Tested on: IE10, IE9, IE8, Chrome, FF)

HTML: (I've added a wrapper for the scroll-able content)

header

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque lacinia tempus diam in malesuada. Aliquam id enim nisl. Integer hendrerit adipiscing quam, fermentum pellentesque nisl. Integer consectetur hendrerit sapien nec vestibulum. Vestibulum ac diam in arcu feugiat fermentum nec id nibh. Proin id laoreet dui, quis accumsan nisi. Quisque eget sem ut arcu faucibus convallis. Sed sed nisl commodo, faucibus leo sed, egestas est. Cras at nibh et erat ullamcorper sollicitudin vitae non nibh.

footer

CSS:
*
{
    padding: 0;
    margin: 0;
}

.scollableContent
{
    position: absolute;
    top: 0;
    bottom: 25px; /*.footer height*/
    overflow: auto;
}
.scollableContent:before
{
    content: '';
    height: 100%;
    float: left;
}
.header
{
    /*Addition*/
    background-color: red;
}
.main
{
    /*Addition*/
    background-color: yellow;
}
    .main:after
    {
        content: '';
        display: block;
        clear: both;
    }

.footer
{
    position: fixed;
    width: 100%;
    bottom: 0px;
    height: 25px;

    /*Addition*/
    color: white;
    background-color: blue;
}

Explanation:
The .footer is fixed to the view port bottom, with a fix height. and spans the whole view port width.
the .scollableContent is absolutely positioned to span exactly all the space between the top of the view port, and the top of the footer. with automatic overflow that allow scrolling if the content is bigger than the available space.
inside the .scollableContent we have a simple block element for the header, that will span his content height. after him we have another block element for the content itself.
now we want the content to always stretch to the end of the container, regardless of the header height (so we can't apply it with a fixed height).
we achieve this using floating & clearing techniques.
we create a floating element before the .scollableContent, with no content (so it's invisible and doesn't really take any place at all) but with 100% height.
and at the end of the content div, we create a block with clear instruction.
now: this new block cannot be position in the same line with the floating element. so he has to be moved down, dragging the content div along with him.
Et voilà!
EDIT:
you're probably going to use this solution inside some existing Container in your website. (and not as the whole website layout).
I've updated the fiddle so that the content is enclosed within a container. that way it will be easier for you to port this solution to your working website.
here is the Updated Fiddle

A:


text:
Q: Styled-components - Over 200 classes were generated, but cant get :hover to work I came across the error in styled-components :
Over 200 classes were generated for component......
and did the suggested fix from console, and that did the trick, but when I have a container component "Card" that when hovered should change text color of another component "Number" (which  has that suggested fix applied, then I cant change the color (i assume because style overrides the hover change, because it works fine with opacity)
the mentioned components are in src/ProgressPieCard (first 2 components)
anyone got any got suggestions, thanks in advance :)
( sorry styling/position is a bit off )
CodeSandBox
const Number = styled.p.attrs<ColorProps>((props) => ({
  style: {
    color: props.color,
  },
}))`
  position: absolute;
  span {
    font-size: 1.5rem;
  }
`;

const Card = styled.div.attrs<ColorProps>((props) => ({
  style: {
    background: props.color,
  },
}))`
  position: relative;
  &:hover {
    ${Number} {
      opacity: 0.5;
      // color: red;  <-- this dont work
    }
  }
`;

A: Values from props were pass as inline styles. They have higher priority. I suggest passing values from props differently. The example below will now work as you wanted.
const Number = styled.p<ColorProps>`
    position: absolute;
    color: ${p => p.color};
    span {
        font-size: 1.5rem;
    }
`;

const Card = styled.div<ColorProps>`
    position: relative;
    background: ${p => p.color};
    &:hover ${Number} {
        opacity: 0.5;
        color: red;  <-- this WILL work :)
    }
`;


text:
Q: Disable app interaction with user on internet connection lost android I'm creating an app the must have internet connection,
and if the connection is lost, i need to disable any interaction with the user.
I do that by listening to android.net.conn.CONNECTIVITY_CHANGE.
which works great.
I want to put an alert dialog and gray the whole background from the BroadcastReceiver.

anyway to make that happen?
Thanks.
Shahar.

A: If anyone wants to know,
i used broadcast receiver on my main activity.
/*
    here we handle connection lost event
    show a popup over the screen to notify the user
 */
static final String ACTION = "android.net.conn.CONNECTIVITY_CHANGE";

public class ConnectionReceiver extends BroadcastReceiver {
    private static final String TAG = "ConnectionReceiver";

    private AlertDialog alertDialog;

    public ConnectionReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
            ConnectivityManager cm =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnectedOrConnecting();
            if (isConnected) {
                try {
                    if (alertDialog != null && alertDialog.isShowing())
                        alertDialog.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                if (alertDialog == null || !alertDialog.isShowing()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("No internet connection");
                    builder.setMessage("check your connection.");
                    builder.setCancelable(false);
                    alertDialog = builder.create();
                    alertDialog.show();
                }
            }
        }
    }
}