text:
Q: Save/Serialize boost or std regexes Is it possible to serialize/deserialize and save/load regular expressions to/from a file?
We have a very time consuming process that constructs some regexes and I'm wondering if we can save some time by saving and loading them.

A: No, it is probably not possible because it would require you to recompile the regex anyway.
However, if you use boost::xpressive, you can do the compilation of the regex during compile time via expression template construction of the regex. This will make it make the regex compile time go away entirely.
Boost Xpressive
However, the true cause of your excess time usage is almost certainly that you are using regexes improperly, IE, through the use of a backtracking regex engine.
RE2 is a traditional automata regex engine that does not use backtracking, but instead constructs an NFA or DFA directly. If you are not using backreferences or many non-regular expression based "features", using RE2 will show an order of magnitude increase in speed for many corner cases.
If you are using those features, you should be aware that they will strictly dominate the speed of your matching, and they are almost certainly the primary cause of the slow down you seek to eliminate.

A: This would be very difficult to achieve with boost/stl regex classes.  The problem is the internal structure of said classes.

*

*How are the implementations storing class properties? by address, value?

*What additional padding has the compiler introduced, if any?

*Are there any platform alignment issues?

*etc...

To help illustrate the difficulty of the problem.  Try and find the sizeof a C++ class instance.
regex pattern( "^Corvusoft$" );

printf( "%lu\n", sizeof( pattern ) );  //32

regex alternative( "C" );

printf( "%lu\n", sizeof( alternative ) );  //32

Alternative Solution 1
Create a library that contains the required regular expressions and link during build time or dynamically open and load the library via the dlopen api.  You would then use tools such as prelink to ensure they are already in memory; pre-compiled.
Alternative Solution 2
Using the C regex.h.
You could walk the regex_t POD structure and write its contents to a binary or memory mapped file.  At a later date you could map these data values back onto a new regex_t structure completely avoiding the recompilation of the regular expression.
#include <regex.h>

regex_t pattern;
int result = 0;

result = regcomp( &pattern, "^Corvusoft$", 0 );

if ( result )
{
   fprintf( stderr, "Failed to compile regular expression pattern\n" );
}

TODO: walk structure and write to binary/memory mapped file.

Alternative Solution 3
Follow @Alice's advice and use Boost.Xpressive

A: You can serialise a boost::regex:
#include <string>
#include <iostream>
#include <sstream>

#include <boost/regex.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/split_free.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

namespace boost
{
  namespace serialization
  {
    template<class Archive, class charT, class traits>
    inline void save(Archive & ar,
                     const boost::basic_regex<charT, traits> & t,
                     const unsigned int /* file_version */)
    {
      std::basic_string<charT> str = t.str();
      typename boost::basic_regex<charT, traits>::flag_type flags = t.flags();
//      typename boost::basic_regex<charT, traits>::locale_type loc = t.getloc();
      ar & str;
      ar & flags;
//      ar & loc;
    }

    template<class Archive, class charT, class traits>
    inline void load(Archive & ar,
                     boost::basic_regex<charT, traits> & t,
                     const unsigned int /* file_version */)
    {
      std::basic_string<charT> str;
      typename boost::basic_regex<charT, traits>::flag_type flags;
//      typename boost::basic_regex<charT, traits>::locale_type loc;
      ar & str;
      ar & flags;
//      ar & loc;
      t.assign(str, flags);
//      t.imbue(loc);
    }

    template<class Archive, class charT, class traits>
    inline void serialize(Archive & ar,
                          boost::basic_regex<charT, traits> & t,
                          const unsigned int file_version)
    {
      boost::serialization::split_free(ar, t, file_version);
    }
  }
}

int main(int argc, char ** argv)
{
  std::stringstream os;

  {
    boost::regex re("");
    boost::archive::text_oarchive oar(os);
    oar & re;
  }

  os.seekg(std::ios_base::beg);

  boost::regex re;
  boost::cmatch matches;
  boost::archive::text_iarchive iar(os);

  iar & re;

  boost::regex_search("example", matches, re);

  std::cout << matches[1] << std::endl;

}

But that doesn't mean that you'll achieve any performance gains versus reconstructing the regular expression from a string.
Note: I left out the std::locale stuff for simplicity


text:
Q: save adview in cache for faster loading I've got two different activities in my application. One contains a surfaceview with an actual game and the other is the "game over screen" containing an adview and a "new game" button.
Now my problem is, when the gameover screen gets called, the adview takes some time to load. So when the user is fast enough he's able to press the new game button without even having seen the ad, because it was still loading.
Is it possible to load this ad, save it in some cache and immediately bring it back to front when the game over activity gets called the next time?
The adview is built programmatically (not via xml files). This is my code for it:
public class GameOverScreen extends Activity {

    private AdView adView();
    private RelativeLayout rLayout;

    protected void onCreate() {
        adView = new AdView(this);
        adView.setUnitId(xxx);
        adView.setAdSize(AdSize.BANNER);
        AdRequest.Builder adBuilder = new AdRequest.Builder();
        adBuilder.addTestDevice(xxx);
        rLayout.addView(adView);
        adView.loadAd(adbuilder.build());
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: create a text box accepting only 0-9 and get these numbers appear in another text box by adding "1" to each number I  have two text box fields , I created the first one accepting numbers only from 0-9 by regular Expression and get them appears again in a second text box field;  I need when you type any number in the first text box field, these numbers appear in the second text box by adding "1" to each number
for example:
when you input "0" in the first field ==> the second field shows "1"
when you input "1" in the first field ==> the second field shows "2"
.....
when you input "9" in the first field ==> alert appears to tell you that "the series is ended, you cannot type 9"
this is the JS code
   var n1 = document.getElementById('numbers-1').value,
       n2 = document.getElementById('numbers-2').value;

    function numbersOnly(input) {
        var regex2 = /[^0-9]/;
        input.value = input.value.replace(regex2, "");

        var n2 = document.getElementById('numbers-1').value;
        document.getElementById('numbers-2').value = n2;
    }

and this is the HTML Code
  <input type="text" maxlength="10" id="numbers-1" oninput="numbersOnly(this)">

  <input type="text" id="numbers-2">

thanks guys

A: You can do it like this,
let me know if any more explanation needed

function numbersOnly(input) {
    var regex2 = /[^0-9]/;
    var val = parseInt(input.replace(regex2, ""));
    if(!isNaN(val)) {
      if(val.toString().indexOf('9') > -1) {
        document.getElementById('numbers-1').value = "";
        document.getElementById('numbers-2').value = "";
        alert('the series is ended, you cannot type 9');
      }
      else{
        document.getElementById('numbers-2').value = val+1;
      }
    } else {
       document.getElementById('numbers-1').value = "";
       document.getElementById('numbers-2').value = "";
    }

}
<input type="text" maxlength="10" id="numbers-1" oninput="numbersOnly(this.value)">

  <input type="text" id="numbers-2">

A: Try this one
<!DOCTYPE html>

<input ng-model="number" type="number" max="9" min="0" ng-keyup="print()" required>

<input ng-model="answer" type="number">


text:
Q: Filter a list of integers based on integer multiples - C# I am trying to filter a list of int based on multiples of a specific number, but I am not sure how to do this.  I have searched this forum and found nothing related, but apologies in advance if I'm wrong.
Here is my code:
int val = 28;

List<int> divisible = new List<int>();

for (int i = 1; i <= val; i++) {
                divisible.Add(i);
}

foreach(var d in divisible)
{
     if(val % d == 0)
     {
         // do something
     }
     else
     {
      // get rid of all multiples of the number that "val" is not divisible by
     }
}

Basically, this code should create a divisible list from 1 to 28.  If val is divisible by one of the numbers in the list, thats fine, but if it falls into else, I want to be able to filter out all multiples of that number out of the current list we are looping through.
The next number that wouldn't be divisible would be 3 in this example, so in the else get rid of 6, 9, 12, ... etc.

A: Your code is fine, but you're just missing the actual code to remove the item. But there is a caveat: You cannot modify a list when you are looping through it using foreach. There are a couple ways to handle that:

*

*Depending on your requirements, maybe just don't add them in the first place. Move your val % d == 0 condition into the for loop that adds the values, and just don't add the values that are divisible by d.

*Make a new list (List<int> toRemove) where you keep track of all the values you need to remove. After you're done the foreach loop, loop through your toRemove list and use divisible.Remove(value) to remove those.

*Change your foreach to a for loop, which will allow you to use divisible.RemoveAt(i). But you will have to make sure you don't skip a value on the next iteration of the for loop (since removing a value changes the size of the list).

A: I agree with Gabriel.  You cannot alter a underlying enumeration while traversing it with with foreach.  The easiest thing to do would be to convert it to a for loop.
Also in the initial population of your list try using the newer way
var divisible = Enumerable.Range(1, val).ToList();

then do
for(int 0 = 1; i < val; i++)
{
    if(val % d == 0)
    {
       // do something
    }
    else
    {
       divisible.RemoveAt(i);
    }
 }


text:
Q: Fluid layout with an inputbox and button, how to solve it? I have a problem with a responsive design using the responsive formula for %. It workes great but not for a search bar, its just an inputbox and a button thats display: inline. It seems like there is an gap between them without me putting in any margin or padding, and that is why the formula dosen't work.. But thats my guess, can anyone tell me how to solve it? Now when I put the % in it scales, but after a while the button jumps down..
My HTML:
<div id="searchWrapper">

 <input type="search" id="inputSearch2">
 <button id="buttonSearch2">Sök</button>

</div>

My CSS:
#searchWrapper{
background-color: #854242;
width: 100%;
display: inline;
}

#inputSearch2, #buttonSearch2{
    margin-top: 10px;
    margin-bottom: 20px;
}

#inputSearch2{
    width: 52.08333333333333%; /* 500px / 960px */
    margin-left: 2.60416666666667%; /* 25px / 960px */
    margin-right: ;
}

#buttonSearch2{
    width: 41.66666666666667%; /* 400px / 960px */
    margin-right: 2.60416666666667%; /* 25px / 960px */
}

For the hole site i uploaded it here: http://jsfiddle.net/6Lbkg/

A: Im not 100% sure what your wanting. As for your button moving down.. If you apply a
min-width: some%;  or min-width: somepx;  it wont move down on you when your scaling to a smaller resolution.

A: if you want your design to be responsive, you need to change all of your widths, margins, and paddings to EM or % (percent will be fine in this case).  remember each element should have a total of width + padding + margin = 100%, and the 100% is 100% of the width of the parent element.


text:
Q: An additional row is added to datagrid after clicking any button I have a popup datagrid that allows users to add information to a database.  It works perfectly except the user has to hit "Accept" twice. The first time it adds another row, the second time it preforms the correct functions. (User can hit any button on the screen and it will add that extra row) What to do?
XAML
<DataGrid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" FontSize="17"          AutoGenerateColumns="False" EnableRowVirtualization="True"
                              Margin="15" Name="addProductDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected"  Visibility="Collapsed" CanUserAddRows="True">
    <DataGrid.Columns>
          <DataGridTextColumn x:Name="prodNameColumn1" Binding="{Binding One}" Header="Name" Width="250"/>
         <DataGridTextColumn x:Name="prodPriceColumn1" Binding="{Binding Two}" Header="Price" Width="100" />
         <DataGridTextColumn x:Name="prodCategoryNameColumn1" Binding="{Binding Three}" Header="Category" Width="200"/>
    </DataGrid.Columns>
</DataGrid>

CODE
AddInput.Visibility = System.Windows.Visibility.Collapsed;
_currentDataGrid.Visibility = System.Windows.Visibility.Collapsed;
MenuDirectEntities db = new MenuDirectEntities();
BindingList<product> tempproduct = new BindingList<product>();
BindingList<Category> tempCategory = new BindingList<Category>();

            String productName = "";
            Decimal price = 0.00M;
            String categoryName = "";

            for (int i = 0; i < addProductDataGrid.Items.Count; i++)
            {
                TextBlock x = addProductDataGrid.Columns[0].GetCellContent(addProductDataGrid.Items[i]) as TextBlock;
                if (x != null)
                {
                    if (!x.Text.Equals(""))
                    {
                       // Console.WriteLine(x.GetType());
                       // Console.WriteLine("Product " + i + ": " + x.Text);
                        productName = x.Text;
                    }
                    else
                    {
                        break;
                    }
                }

                TextBlock y = addProductDataGrid.Columns[1].GetCellContent(addProductDataGrid.Items[i]) as TextBlock;
                if (y != null)
                {
                    if (!y.Text.Equals(""))
                    {
                       // Console.WriteLine("Price " + i + ": " + y.Text);
                        price = Convert.ToDecimal(y.Text);
                    }
                    else
                    {
                        break;
                    }
                }

                TextBlock z = addProductDataGrid.Columns[2].GetCellContent(addProductDataGrid.Items[i]) as TextBlock;
                if (z != null)
                {
                    if (!z.Text.Equals(""))
                    {
                        //Console.WriteLine("Category " + i + ": " + z.Text);
                        categoryName = z.Text;
                    }
                    else
                    {
                        break;
                    }
                }
                theSender.SendToDB(new product() { prodName = productName, prodPrice = price, prodCategoryName = categoryName });
            }

            foreach (product theT in db.products)
            {
                tempproduct.Add(theT);
            }

            productDataGrid.ItemsSource = tempproduct;
            addProductDataGrid.ItemsSource = new BindingList<TestGridItem>();
        }
    }
    private void cancelAddButton_Click(object sender, RoutedEventArgs e)
    {
        AddInput.Visibility = System.Windows.Visibility.Collapsed;
        _currentDataGrid.Visibility = System.Windows.Visibility.Collapsed;
    }

ADDITION INFORMATION
public class TestGridItem
{
    public string One { get; set; }
    public string Two { get; set; }
    public string Three { get; set; }
    public string Four { get; set; }
}

addProductDataGrid.ItemsSource = new BindingList<TestGridItem>();


text:
Q: Printing fibonacci series using lists in python I am relatively a noobie in programming and trying to learn python. I was trying to implement a Fibonacci series into a list within 10.
fibo= [0,1]

for k in range(11):
 i= fibo[-1]
 j = fibo[-2]
 k= fibo[i]+fibo[j]
 fibo.append(k)
 k=+1
print(fibo)

Not sure what I did wrong? Any help is really appreciated!
Output:

[0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

A: You can use this code to print fibonacci series upto N.
N = int(input()) # Length of fibonacci series

fibo = [0, 1]
a = fibo[0]
b = fibo[1]

for each in range(2, N):
    c = a + b
    a, b = b, c
    fibo.append(c)

print(fibo[:N])

OUTPUT
N = 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

A: I can see few issues here:
fibo = [0,1]

# Your loop should start at index 2, otherwise
# you will try to access fibo[-2] and fibo[-1] with k=0
# and fibo[-1] and fibo[0] with k=1
# Also, if you only want 10 values, you should change 11
# to 10 since fibo already has two values.
# for k in range(11):
for k in range(2, 10):
    # You don't want the content of fibo, but the indexes!
    # i = fibo[-1]
    # j = fibo[-2]
    i = k - 1
    j = k - 2

    # You are already using k, so you need to use an other variable
    # k = fibo[i] + fibo[j]
    v = fibo[i] + fibo[j]
    fibo.append(v)

    # You don't need k+=1 because it will be incremented
    # according to range(2, 10). The loop will start with
    # k = 2 and it will stop when k = 9
    # k += 1

print(fibo)

Your code did not crash because you technically can access fibo[-1] and fibo[-2]. It will respectively return the last value of your array, and the value before the last one.


text:
Q: Kinds of PostgreSQL naming domains Which kinds of database objects in PostgreSQL form their own independent name domain, so that name collisions with objects of other kind are excluded?
Kind of database objects mean tables, schemas, views, triggers, procedures, functions, operators, variables, ...
The question is not to be confused with namespace (through schemas).


text:
Q: Detecting Beacon Using android-beacon-library not working I have a beacon I'm trying to use with Android Beacon Library that I do not know much about.
Here are the details for nRF Connect:

Basically, none of the methods inside onBeaconServiceConnect are being called except for the didDetermineStateForRegion override that seems to run once at app startup.
I have also granted my app Location permissions.
Application code that is running and registered in manifest.
class MyApplicationName : Application(), BeaconConsumer  {
    var beaconManager : BeaconManager? = null

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "App started up")
        beaconManager = BeaconManager.getInstanceForApplication(this)
        beaconManager?.beaconParsers?.add(MyBeaconParser())
        beaconManager?.bind(this)
    }

    override fun onBeaconServiceConnect() {
        beaconManager?.removeAllMonitorNotifiers()
        beaconManager?.addMonitorNotifier(object : MonitorNotifier {
            override fun didEnterRegion(region: Region) {
                Log.i(TAG, "I just saw an beacon for the first time!")
            }

            override fun didExitRegion(region: Region) {
                Log.i(TAG, "I no longer see an beacon")
            }

            override fun didDetermineStateForRegion(state: Int, region: Region) {
                Log.i(TAG, "I have just switched from seeing/not seeing beacons: $state")
            }
        })

        try {
            beaconManager?.startMonitoringBeaconsInRegion(Region("myMonitoringUniqueId", null, null, null))
        } catch (e: RemoteException) {
        }

    }

    companion object {
        private val TAG = ".MyApplicationName"
    }
}

And "MyBeaconParser"
class MyBeaconParser : BeaconParser() {
    init {
        mHardwareAssistManufacturers = intArrayOf(0x0551)
        this.setBeaconLayout("m:0-1=03d8,i:0-1,p:1-1")
        this.mIdentifier = "sylerobeacon"
    }
}

A: Try:  setBeaconLayout("m:2-3=03d8,i:0-1,p:1-1")
Understand that the numeric offsets in the "m" beacon layout are measured from the manufacturer advertisement type byte indicator "ff".  So if your advertisement bytes look like this:
06 1b ff 51 05 03 d8 ...
The bytes 51 05 are at offsets 0 and 1 (these are the two byte hardware manufacturer code) followed by 03 d8 at offsets 2 and 3.
The other terms of your beacon parser expression i and p will set the identifier and measured power to start at byte offsets 0 and byte offset 1, respectively. This will result in your identifier always being set to the manufacturer code of 0x0551 and the measured power to 0x51.  This is probably not what you want.  Setting these terms correctly require figuring out where (if anywhere) your beacon format has a useful identifier in the byte pattern, and where it has a measured power byte (if it has one at all).


text:
Q: How do I install psycopg2 for multiple python interpreters on a CentOS box? I have a CentOS 5.5 box, which comes preloaded with Python 2.4. I wanted 2.6, so used yumto get it from the EPEL repository. I also used yum to install the psycopg2 package, but it installed it for Python 2.4.
I tried copying /usr/lib/python2.4/site-packages/psycopg2/ to /usr/lib/python2.6/site-packages/, and when I ran my script, it worked... but it gave me a warning that said
/usr/lib/python2.6/site-packages/psycopg2/__init__.py:69: RuntimeWarning: Python C API version mismatch for module _psycopg: This Python has API version 1013, module _psycopg has version 1012.

So it looks like there's some kind of versioning issue going on here, and I'm wondering what the best way to fix it is. Should I just ignore the warning and carry on? Is there a way to use yum to install psycopg2 for Python 2.6? Should I just install from source using python26 setup.py install? I know installing from source is generally a no-no in CentOS, so I want this to be a last resort, unless it's the only option. I just don't want to mess up yum.

A:
I tried copying /usr/lib/python2.4/site-packages/psycopg2/ to /usr/lib/python2.6/site-packages/...

That is not supposed to work.
If you want psycopg2 available to multiple python interpreters, you have a few options... I like virtualenv for juggling multiple python installations on a system.   This way you can have as many combinations of sandboxed module versions as you like.
If you just want to install psycopg2 where the Python2.6 libraries are, then we need to clarify python interpreters... let's assume Python2.6 is installed in /usr/bin/python26.  I will assume you've satisfied the dependencies for psycopg2 in your Python2.6 install... at this point, download the psycopg2 tarball, untar, cd into the extracted archive directory, and (as root) run /usr/bin/python26 setup.py install.  This will install psycopg2 for Python2.6.


text:
Q: Why won't my console show my javsacript variables? async function drawBars() {
  // your code goes here
  //1)Access Data
  const dataset = await d3.json("my_weather_data.json")

  const metricAccessor = d => d.humidity
  const yAccessor = d => d.length

  //2) Create Chart Dimensions

  const width = 600

  let dimensions = {
    width: width,
    height: width *.6,
    margin:{
      top: 30,
      right:10,
      bottom: 50,
      left: 50,
    }
  }

  dimensions.boundedWidth = dimensions.width - dimensions.margin.left - dimensions.margin.right
  dimensions.boundedHeight = dimensions.height - dimensions.margin.top - dimensions.margin.bottom

  //3)Draw Canvas
  const wrapper = d3.select("#wrapper")
    .append("svg")
      .attr("width", dimensions.width)
      .attr("height", dimensions.height)

      const bounds = wrapper.append("g")
      .style("transform", `translate(${dimensions.margin.left}px, ${dimensions.margin.top}px)`)

  //4) Draw Scales
  const xScale = d3.scaleLinear()
  .domain(d3.extent(dataset, metricAccessor))
  .range([0, dimensions.boundedWidth])
  .nice()

const binsGenerator = d3.bin()
  .domain(xScale.domain())
  .value(metricAccessor)
  .thresholds(12)

const bins = binsGenerator(dataset)

const yScale = d3.scaleLinear()
  .domain([0, d3.max(bins, yAccessor)])
  .range([dimensions.boundedHeight, 0])
  .nice()
}

drawBars()

Code Above. I'm trying to access the variables in the code

Hi!When I run console.log(dataset) to access my data on the live server, it shows no error. I defined the dataset as a constant, and an unsure why this error persists.


text:
Q: GRUB can't find root files Ubuntu 20.04 Just tried to clean install my computer with the newest Ubuntu but it takes me immediately to grub.  My partition is saved at (hd0,msdos5) it seams.  I did the assignments as follows:
grub> set root=(hd0,5)
grub> linux /boot/vmlinuz-5.4.0-29-generic root=/dev/sda5
grub> initrd /boot/initrd.img-5.4.0.29-generic
grub> boot

But after boot I get the message that it gave up waiting for rootfile system device.  And then an ALERT!  /dev/sda5 does not exist.  Dropint to a shell! and then I'm stuck ash, I think.
Really not sure what to do here since I've never had this kind of issue before


text:
Q: Euler characteristic for pair of checkerboard surfaces of a link A knot/link diagram can be checkerboard colored (as in, the regions between the strands can be two-colored), and a checkerboard surface is what you get by taking all the regions of a particular color and attaching twisted bands at the crossings; the boundary of a checkerboard surface is the link.  Every link diagram has two checkerboard surfaces $\Sigma_1$ and $\Sigma_2$.  (Mind that the diagram is in $S^2$, so one of them contains $\infty$ as it were.)
In a paper by Joshua Howie ("A characterization of alternating knot exeriors"), he says that by "a simple Euler characteristic argument"
$$\chi(\Sigma_1)+\chi(\Sigma_2)+n=2$$
where $n$ is the number of crossings in the diagram.
I am not sure what argument he had in mind.  I came up with one which I will post as an answer, but I am afraid I am missing something about the Euler characteristic, and I would appreciate another argument.

A: I ran into Josh Howie a few months ago and he told me the argument he had in mind.  At this point, I don't exactly remember what he said, but the following shouldn't be too far off:

*

*Consider triangulations of $\Sigma_1$ and $\Sigma_2$ which are compatible at the crossings in that they both have an edge spanning the crossing.

*The union of $\Sigma_1$ and $\Sigma_2$ is homotopy equivalent to a sphere, so $\chi(\Sigma_1\cup\Sigma_2)=2$.

*$\chi(\Sigma_1)+\chi(\Sigma_2)$ double counts those $n$ spanning edges, and since the number of edges is subtracted in the formula for Euler characteristic, $\chi(\Sigma_1)+\chi(\Sigma_2)+n=2$.  (It also double counts the link, but Euler characteristic of a link is $0$.)

A: At least for a space $X$ with a finite triangulation with two subcomplexes $A$ and $B$ having $A\cup B=X$, it follows from the short exact sequences for the Mayer-Vietoris sequences that $\chi(A)+\chi(B)=\chi(X)+\chi(A\cap B)$.  The space $\Sigma_1\cup\Sigma_2$ has a finite triangulation, so $\chi(\Sigma_1)+\chi(\Sigma_2)=\chi(\Sigma_1\cup\Sigma_2)+\chi(\Sigma_1\cap\Sigma_2)$.
The union of the checkerboard surfaces is almost $S^2$ except for some singularities at the crossings.  However, the region around a crossing is homotopy equivalent to a disc, so $\chi(\Sigma_1\cup\Sigma_2)=\chi(S^2)=2$.
The intersection of the checkerboard surfaces is the link itself, except that at the crossings there is an additional edge connecting the two strands.  These edges can be retracted to a point, so $\Sigma_1\cap \Sigma_2$ is homotopy equivalent to the projection of the link.  This is a $4$-regular graph, except perhaps for some disconnected loops --- the loops do not contribute to Euler characteristic, so we may ignore them.   Euler characteristic of a graph is $\left|V\right|-\left|E\right|$, and $\left|E\right|=2\left|V\right|$ by $4$-regularity, so $\chi(\Sigma_1\cap \Sigma_2)=-n$, where $n$ is the number of crossings.
Then, $\chi(\Sigma_1)+\chi(\Sigma_2)=2-n$.


text:
Q: How to prevent accidental modification of an array from the method? Without making the array immutable In the following method, how can I prevent the contents of my array from being modified accidentally or otherwise?
Can it be done without changing the array to another type, such as a list?
    public static int LinearSearch(int[] myArray, int target)
    {
        int idx = -1;
        for (int i = 0; i < myArray.Length; i++)
        {
            if (myArray[i] == target) { idx = i; break; }
        }
        return idx;
    }

A: Use the ImmutableArray<T> class.

Provides methods for creating an array that is immutable; meaning it cannot be changed once it is created.

For instance:
ImmutableArray<int> array = ImmutableArray.Create(1, 2, 3);

You can also try the ReadOnlyCollection<T> class, that doesn't include a .Add method.


text:
Q: Using python how to make appium server wait on an particluar screen til a process is completed? I have initiated an copy process in android app, but the appium server backgrounds the app before the copy process is complete, i want the app to wait on copy screen till copy process is completed is there any way of doing it.
I tried using while loop
    result=self.assertTrue(self.driver.find_element_by_name("Ok"))

    while result==True:

        self.driver.implicitly_wait(999)

and also if loop
    if result==True:

         self.driver.implicitly_wait(999)

         print "Copy sucessfull"

A: use time.sleep() for wait.For exp. if you want to wait for 5 seconds then write time.sleep(5)
To use it you have to use. "import time"


text:
Q: CheckBox Checked Event Throws NullReferenceException_ I have  an odd situation which I don't know how to deal with... In my Project I have The following TreeView which holds checkbox in its TreeViewItem:
<DataGrid x:Name="dataGridVirtualMachinesInfo" ItemsSource="{Binding Path=SelectedItem.VMImagesInfo, ElementName=comboBoxUserName}"
                      Style="{DynamicResource RoundDataGridStyle}" RowDetailsVisibilityChanged="dataGridVirtualMachinesInfo_RowDetailsVisibilityChanged"
                      MouseLeftButtonUp="DataGrid_MouseLeftButtonUp" CanUserAddRows="False" Margin="24" AutoGenerateColumns="False" ClipToBounds="True"
                      AreRowDetailsFrozen="false" CanUserResizeRows="False" RowDetailsTemplate="{DynamicResource VMRowDetailsDataTemplate}"
                      Visibility="Visible" Background="White" VerticalAlignment="Top">
                <DataGrid.Resources>
                    <DataTemplate x:Key="VMRowDetailsDataTemplate">
                        <Border BorderThickness="2">
                            <Border.BorderBrush>
                                <SolidColorBrush Color="{DynamicResource ColorBorder}"/>
                            </Border.BorderBrush>
                            <Grid x:Name="gridRowDetail" Height="450" Width="Auto" Margin="0" Background="White" VerticalAlignment="Stretch" >
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="2*"/>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition Height="10*"/>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition Height="5*"/>
                                </Grid.RowDefinitions>
                                <Grid x:Name="gridCurrentVersion" Margin="0" Grid.RowSpan="1" Grid.Row="0">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition/>
                                        <ColumnDefinition/>
                                    </Grid.ColumnDefinitions>
                                    <Label x:Name="lableCurrentVersion" Content="Current Version : " HorizontalAlignment="Left"
                                           Margin="5,0,0,0" VerticalAlignment="Center" Width="Auto" FontWeight="Bold"/>
                                    <TextBox x:Name="textBoxCurrentVersion" Text="{Binding CurrentVersion}" HorizontalAlignment="Left"
                                             Margin="105,0,0,0" TextWrapping="Wrap"  VerticalAlignment="Center" RenderTransformOrigin="0.432,0.365"
                                             Width="100" Height="Auto" Grid.Column="0" AcceptsReturn="True"/>
                                    <Button x:Name="buttonRestoreDefaults" Content="Restore Defaults" HorizontalAlignment="Right"
                                            Margin="0,2,95,2" VerticalAlignment="Center" Width="90" RenderTransformOrigin="0.213,-0.401" Grid.Column="0"
                                            d:LayoutOverrides="HorizontalAlignment, GridBox" Height="30" Grid.ColumnSpan="2"/>
                                    <Button x:Name="buttonSaveInfo" Content="Save Info" Click="buttonSaveInfo_Click" Width="90"
                                            Background="#FF2DD420"  Margin="0,2" HorizontalAlignment="Right" Height="30"
                                            VerticalAlignment="Center" RenderTransformOrigin="1.125,0.599" Grid.Column="1"/>
                                </Grid>
                                <GridSplitter x:Name="gridSplitterCurrVerAndSaveInfoButton"
                                    ResizeDirection="Rows"
                                    Grid.Column="0"
                                    Grid.ColumnSpan="2"
                                    Grid.Row="1"
                                    Width="Auto"
                                    Height="3"
                                    HorizontalAlignment="Stretch"
                                    VerticalAlignment="Stretch"
                                    Margin="0">
                                    <GridSplitter.Background>
                                        <SolidColorBrush Color="{DynamicResource ColorBorder}"/>
                                    </GridSplitter.Background>
                                </GridSplitter>
                                <Grid x:Name="gridFeaturesAndProps" Margin="0" Grid.Row="2">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="3*"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid x:Name="gridFeatures">
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="2*"/>
                                            <RowDefinition Height="15*"/>
                                        </Grid.RowDefinitions>
                                        <Label x:Name="lableFeaturesSelection" Content="Features Selection" HorizontalAlignment="Left"
                                               VerticalAlignment="Top" FontWeight="Bold" Grid.Row="0" Margin="5,0,0,0"/>
                                        <TreeView x:Name="GroupViewFeaturesList" ItemsSource="{Binding Path=InstallPackage.Features.FeaturesTree}"
                                              ItemContainerStyle="{DynamicResource  TreeViewItemStyle}"
                                              Margin="5,0,0,5" FontFamily="Pescadero" BorderThickness="0" FontSize="13.333"
                                              Width="Auto" Height="Auto" Grid.Row="1" VerticalAlignment="Stretch" d:LayoutOverrides="GridBox">
                                            <TreeView.Resources>
                                                <Style x:Key="TreeViewItemStyle" TargetType="{x:Type TreeViewItem}">
                                                    <!--<Setter Property="Visibility" Value="{Binding Path=IsVisible, Mode=TwoWay, Converter={StaticResource boolToVis}}" />-->
                                                    <Setter Property="IsExpanded" Value="True" />
                                                </Style>
                                                <HierarchicalDataTemplate DataType="{x:Type nsMsiObjects:Feature}" ItemsSource="{Binding SubFeatures}">
                                                    <CheckBox x:Name="checkBoxFeatureSelection" Content="{Binding DisplayName}" Checked="checkBoxFeatureSelection_Checked"/>
                                                </HierarchicalDataTemplate>
                                            </TreeView.Resources>
                                            <TreeView.Background>
                                                <LinearGradientBrush EndPoint="1.204,0.5" StartPoint="0.056,0.5">
                                                    <GradientStop Color="White" Offset="1"/>
                                                    <GradientStop Color="#FFD4D7DB"/>
                                                </LinearGradientBrush>
                                            </TreeView.Background>
                                        </TreeView>
                                    </Grid>
                                    <GridSplitter x:Name="gridSplitterFeaturesAndInstallProps"
                                        ResizeDirection="Rows"
                                        Grid.Column="1"
                                        Grid.RowSpan="2"
                                        Grid.Row="0"
                                        Width="3"
                                        Height="Auto"
                                        HorizontalAlignment="Stretch"
                                        VerticalAlignment="Stretch"
                                        Margin="4,0">
                                        <GridSplitter.Background>
                                            <SolidColorBrush Color="{DynamicResource ColorBorder}"/>
                                        </GridSplitter.Background>
                                    </GridSplitter>
                                    <Grid x:Name="gridInstallPropsAndExpendAdditionals" Margin="0" Grid.Column="2">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>
                                        <Grid x:Name="gridInstallProps" Grid.Column="0" Margin="0" Width="Auto">
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="2*"/>
                                                <RowDefinition Height="15*"/>
                                            </Grid.RowDefinitions>
                                            <Label x:Name="lableInstallationProperties" Content="Installation Properties" HorizontalAlignment="Left"
                                                   Margin="0" d:LayoutOverrides="GridBox" Grid.Row="0" Grid.Column="0" FontWeight="Bold" VerticalAlignment="Top"/>
                                            <ScrollViewer Grid.Row="1">
                                                <StackPanel x:Name="StackPanelInstallProps" Width="Auto" Height="Auto">
                                                    <!--<nsProject:ExpanderInstallProperties x:Name="expanderInstallProps" />-->

                                                </StackPanel>
                                            </ScrollViewer>

                                        </Grid>
                                    </Grid>
                                </Grid>
                                <GridSplitter x:Name="gridSplitterFeaturesAndComments"
                                    ResizeDirection="Rows"
                                    Grid.Column="0"
                                    Grid.ColumnSpan="2"
                                    Grid.Row="3"
                                    Width="Auto"
                                    Height="3"
                                    HorizontalAlignment="Stretch"
                                    VerticalAlignment="Stretch"
                                    Margin="0">
                                    <GridSplitter.Background>
                                        <SolidColorBrush Color="{DynamicResource ColorBorder}"/>
                                    </GridSplitter.Background>
                                </GridSplitter>
                                <Grid x:Name="gridComments" HorizontalAlignment="Stretch" Margin="0" Width="Auto" Grid.Row="4">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="2*"/>
                                        <RowDefinition Height="10*"/>
                                    </Grid.RowDefinitions>
                                    <Label x:Name="lableComments" Content="Comments :" HorizontalAlignment="Left"
                                           VerticalAlignment="Top" Width="Auto" FontWeight="Bold" Grid.Row="0" Grid.RowSpan="1"
                                           Margin="5,0,33.866,-200" d:LayoutOverrides="Width"/>
                                    <TextBox x:Name="textBoxComments" Text="{Binding UserComments}" Margin="5" TextWrapping="Wrap"
                                             VerticalAlignment="Stretch" Height="Auto" VerticalScrollBarVisibility="Auto" Grid.Row="1"
                                             BorderThickness="3" AcceptsReturn="True" MaxWidth="{Binding ActualWidth, ElementName=gridComments}"/>
                                </Grid>
                            </Grid>
                        </Border>
                    </DataTemplate>
                </DataGrid.Resources>
                <DataGrid.RowBackground>
                    <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
                        <GradientStop Color="#FFB7CADE"/>
                        <GradientStop Color="#FF5F6264" Offset="1"/>
                    </LinearGradientBrush>
                </DataGrid.RowBackground>
                <DataGrid.Columns>
                    <DataGridTextColumn x:Name="dgTextColumnServerIP" Binding="{Binding VMServerIP}" Header="Server IP" IsReadOnly="True"/>
                    <DataGridTextColumn x:Name="dgTextColumnVMName" Binding="{Binding Name}" Header="Virtual Machine Name" IsReadOnly="True"/>
                    <DataGridTextColumn x:Name="dgTextColumnInstalledVersion" Binding="{Binding InstalledVersion}" Header="Installed Version"/>
                    <DataGridTemplateColumn x:Name="dgTemplateColumnUpgradeMajorVersion" Header="Upgrade Major Version">
                        <DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <ComboBox x:Name="comboBoxMajorVersion" Height="Auto"
                                        SelectedIndex="0"
                                        ItemsSource="{Binding Path=InstallPackage.Versions,UpdateSourceTrigger=PropertyChanged}"
                                    />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellEditingTemplate>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox x:Name="comboBoxMajorVersion" Height="Auto"
                                          SelectedIndex="0"
                                    ItemsSource="{Binding Path=InstallPackage.Versions}"
                                    />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTemplateColumn x:Name="dgTemplateColumnUpgradeVersion" Header="Upgrade Version">
                        <DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <ComboBox x:Name="comboBoxMinorVersion"
                                  SelectedIndex="0"
                                  ItemsSource="{Binding Path=SelectedItem.MinorBuildVersions, ElementName=comboBoxMajorVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                  DisplayMemberPath="Version"
                                  SelectedValue="Version"
                                  SelectedValuePath="Version"
                                  Margin="15,0,0,0" VerticalAlignment="Center" IsEditable="True" IsReadOnly="True"
                                  ToolTip="Choose user to display his virtual machines" Grid.Column="3" Width="220" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellEditingTemplate>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox x:Name="comboBoxMinorVersion"
                                  SelectedIndex="0"
                                  ItemsSource="{Binding Path=SelectedItem.Users, ElementName=comboBoxTeamName, UpdateSourceTrigger=PropertyChanged}"
                                  DisplayMemberPath="Name"
                                  SelectedValuePath="Name"
                                  Margin="15,0,0,0" VerticalAlignment="Center" IsEditable="True" IsReadOnly="True"
                                  ToolTip="Choose user to display his virtual machines" Grid.Column="3" Width="220" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTemplateColumn x:Name="dgTemplateColumnUpgradeTypr" Header="Upgrade Type">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ComboBox Height="Auto"
                                    ItemsSource="{StaticResource UpgradeTypeList}"
                                    SelectedItem="{Binding UpgradeType}"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTemplateColumn x:Name="dgTemplateColumnExecuteUpgrade" Header="Execute Upgrade">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Style="{StaticResource GlassButton}" Content="Go!" Width="25" Height="25" Background="#FF2DD420"  Margin="2"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>

However when i extend the row of my datagrid suddenly a NullReferenceException is thrown with no source code so i can't see where it was thrown from The eveny function is empty so it still does not get there Also I figured that every event causes the same thing I think that for some reason it triggers the event before the checkbox was created when i set the TreeView ItemsSource
This is the attached code for setting TreeView ItemsSource:
/// <summary>
    /// This function occur when selecting one of the rows from dataGridVirtualMachinesInfo
    /// opening its row details and setting its inner controls
    /// </summary>
    private void dataGridVirtualMachinesInfo_RowDetailsVisibilityChanged(object sender, DataGridRowDetailsEventArgs e)
    {
        string path = "Some Path.msi";
        TreeView featuresTree = dataGridVirtualMachinesInfo.GetRowDetailsInnerControl<TreeView>("GroupViewFeaturesList");
        if (featuresTree.Items.IsEmpty)
        {
            // get the selected row of dataGridVirtualMachinesInfo
            DataGridRow dgRow = dataGridVirtualMachinesInfo.GetSelectedRow(dataGridVirtualMachinesInfo.SelectedItem);
            VMImageInfo selectedRowVmInfo = dgRow.DataContext as VMImageInfo;
            selectedRowVmInfo.InstallPackage = new InstallationPackage();
            selectedRowVmInfo.InstallPackage.SetFeatures(path);          DisplayFeaturesGroupedByFeatures(selectedRowVmInfo.InstallPackage.Features.DisplayedFeaturesList);
        }
    }

How Can I deal with it? I've searched all day long for an answer and could not find a thing related to that
Thanks!
Update:
I've added the all DataGrid and its details as you've asked
Also you were right I dont need to set the TreeView in The Code behind so I removed it from there and changed the binding path in the xaml.
The treeView is a part of the DataGridRowDetails Template
The Exception message is:
"Object reference not set to an instance of an object."
There is no stack trace since the source is not available, probably happened in xaml
Thanks again!


text:
Q: Add DEFAULT to existing column In Microsoft SQL server, how can I add/change the default on an existing table column using T-SQL?

A: ALTER TABLE yourTable ADD  CONSTRAINT constraintName
   DEFAULT ('XYZ') FOR [YourColumn]

To change the default, drop the constraint and re-add it with the new value:
ALTER TABLE yourTable
DROP CONSTRAINT constraintName

ALTER TABLE yourTable ADD  CONSTRAINT constraintName
   DEFAULT ('ABC') FOR [YourColumn]


text:
Q: adding a checkboxpreference in java rather than xml android Hi I am wondering if it is possible(and if so then how)to add a checkboxpreference for every number of firebase children I detect.  For example, if I call a query to firebase in order to get all of my users payment information, can I then make a checkboxpreference for the number of credit cards that the user has on file.
However, since I wont have a exact number of boxes(since it will be different for every user) needed I will have to add these checkboxes in java rather than in the xml code, how is this done? Thank You


text:
Q: Change Map language dynamically in angular2 I am using AgmCoreModule to load google map.
Is it possible to change map language dynamically when language is selected?
I am able to set default language on load of map using code below
@NgModule({
  imports: [
    AgmCoreModule.forRoot({
      libraries: ["places"],
      language: 'de'
    }),
    ...
    ]
})

But what I actually needed is to change language of map on language selected from dropdown.
OR
How do I set language in MapsAPILoader?
this._mapsAPILoader.load().then(() => {
...
});

Thanks.

A: Try This:
imports: [
      BrowserModule,
      AgmCoreModule.forRoot({
          apiKey: 'yourmapapikey',
          language: 'iw',
      })
  ],

iw - For Hebrew,
check here for your language.

A: in order to replace the language you should at first delete the script and google maps,
then generate it again and wait a while till it's reloaded
you can do it like that:
async loadScript() {
var oldScript = document.getElementById("agmGoogleMapsApiScript");
if (oldScript !== null) {
  oldScript.parentNode.removeChild(oldScript);
  delete google.maps;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'https://maps.googleapis.com/maps/api/js?
v=3&key={{YourApiKey}}&region=israel&language=
{{language}}';
script.id = "agmGoogleMapsApiScript";
document.body.appendChild(script);
await new Promise(resolve => setTimeout(resolve, 1000));
}

then you should reload the agm-core map, you can do it by stepping out of the component.
don't forget to declare google, like that:
declare var google: any;

worked for me, hope it helps :)


text:
Q: Convert chararray to float I am new to pig programming. I have one txt file and comma (,) as a delimiter. In amount columns i.e; amt_IN and amy_OUT are of type chararray with data $830.03 and $1392.54 respectively.
I need these two columns in INR. I tried this by removing the $ symbol from the string first and then tried to convert it to float.
Following is txt file - petrol.csv
Z7O 7C2,reliance,$830.03,$1392.54,1067,722,1625
T6Q 0L9,hindustan,$994.57,$11765.97,1039,805,1626
S1J 8B8,Bharat,$881.25,$10345.43,1066,657,1627

I used the following code to remove the $ symbol.
A = LOAD 'project/petrol.txt' USING PigStorage(',') as (distributer_id:chararray,distributer_name:chararray,amt_IN:chararray,amy_OUT:chararray,vol_IN:int,vol_OUT:int,year:int);
DUMP A;

(Z7O 7C2,reliance,$830.03,$1392.54,1067,722,1625)
(T6Q 0L9,hindustan,$994.57,$11765.97,1039,805,1626)
(S1J 8B8,Bharat,$881.25,$10345.43,1066,657,1627)

X = FOREACH A GENERATE distributer_id,distributer_name,SUBSTRING(amt_IN,1),SUBSTRING(amy_OUT,1),vol_IN,vol_OUT,year;
DUMP X;

(Z7O 7C2,reliance,830.03,1392.54,1067,722,1625)
(T6Q 0L9,hindustan,994.57,11765.97,1039,805,1626)
(S1J 8B8,Bharat,881.25,10345.43,1066,657,1627)

I need amt_IN and amy_OUT to be converted to float so that I can convert the amount in USD to INR.
Thank you in advance for the help.

A: In Pig, you can cast data types by using (type) in front of the variable. If using Pig 0.17, you can also use AS var_name:type.
As you might not be using Pig 0.17, I expect the first approach is most likely to work.
X = FOREACH A GENERATE
    distributer_id,
    distributer_name,
    (float) SUBSTRING(amt_IN,1),
    (float) SUBSTRING(amy_OUT,1),
    vol_IN,
    vol_OUT,
    year;


text:
Q: Time-varying covariates in longitudinal analysis Let's say that my dataset is in long format. I have a treatment variable that is time-varying, so the individual will NOT receive the treatment initially, but as time goes on, he/she does. How can I take into account that treatment is time-dependent? I was thinking that including the interaction term time*treatment would handle that, but I am not sure. Any suggestions would be greatly appreciated.

A: Since you're analyzing the data in long format, it's enough to include a term for treatment. Since every observation gets a row, any two observations can have a different value of the treatment variable, even for the same subject. You might still want a time-by-treatment interaction, but this concerns something different from the plain treatment effect: it captures how the effect of treatment itself depends on the time.


text:
Q: json: cannot unmarshal string into Go value of type map[string]interface {} I have been working on converting some crypto pool software over to work with an incompatible coin. I believe I have it all about done. But this error keeps popping up and I just can't seem to figure out what the problem is. Here is my code:
type GetBalanceReply struct {
    Unspent string `json:"unspent"`
}

type SendTransactionReply struct {
    Hash string `json:"hash"`
}

type RPCClient struct {
    sync.RWMutex
    Url         string
    Name        string
    Account     string
    Password    string
    sick        bool
    sickRate    int
    successRate int
    client      *http.Client
}

type GetBlockReply struct {
    Difficulty       string `json:"bits"`
    Hash             string `json:"hash"`
    MerkleTreeHash   string `json:"merkle_tree_hash"`
    Nonce            string `json:"nonce"`
    PrevHash         string `json:"previous_block_hash"`
    TimeStamp        string `json:"time_stamp"`
    Version          string `json:"version"`
    Mixhash          string `json:"mixhash"`
    Number           string `json:"number"`
    TransactionCount string `json:"transaction_count"`
}

type GetBlockReplyPart struct {
    Number     string `json:"number"`
    Difficulty string `json:"bits"`
}

type TxReceipt struct {
    TxHash string `json:"hash"`
}

type Tx struct {
    Gas      string `json:"gas"`
    GasPrice string `json:"gasPrice"`
    Hash     string `json:"hash"`
}

type JSONRpcResp struct {
    Id          *json.RawMessage       `json:"id"`
    Result      *json.RawMessage       `json:"result"`
    Balance     *json.RawMessage       `json:"balance"`
    Transaction *json.RawMessage       `json:"transaction"`
    Error  map[string]interface{} `json:"error"`
}

func (r *RPCClient) GetPendingBlock() (*GetBlockReplyPart, error) {
    rpcResp, err := r.doPost(r.Url, "fetchheaderext", []interface{}{r.Account, r.Password, "pending"})
    if err != nil {
        return nil, err
    }
    if rpcResp.Result != nil {
        var reply *GetBlockReplyPart
        err = json.Unmarshal(*rpcResp.Result, &reply)
        return reply, err
    }
    return nil, nil
}

func (r *RPCClient) GetBlockByHeight(height int64) (*GetBlockReply, error) {
    //params := []interface{}{fmt.Sprintf("0x%x", height), true}
    params := []interface{}{"-t", height}
    return r.getBlockBy("fetch-header", params)
}

Whenever I run that manually in the wallet it displays:
"result": {
    "bits": "7326472509313",
    "hash": "060d0f6157d08bb294ad30f97a2c15c821ff46236281f118d65576b9e4a0ba27",
    "merkle_tree_hash": "36936f36718e134e1eecaef05e66ebc4079811d8ee5a543f36d370335adc0801",
    "nonce": "0",
    "previous_block_hash": "10f4da59558fe41bab50a15864d1394462cd90836aecf52524f4cbce02a74a27",
    "time_stamp": "1520718416",
    "version": "1",
    "mixhash": "0",
    "number": "1011160",
    "transaction_count": "1"
}'

But, the code errors out with "json: cannot unmarshal string into Go value of type map[string]interface {}"
Can anyone help me figure this one out? I've been hours on trying to figure it out on my own.

A: Try changing the type of the Error field to interface{} if you are not sure about the error structure, or change it to string if its always a string.
This should get rid of the error.
The error comes from unmarshaling JSONRpcResp. The input data has something like {error: "this is the error message", ...} and unmarshaling this into a map[string]interface{} will simply not work.


text:
Q: Normalizing a wave function in a mixed well So I got this potential and want to solve for the even wavefunctions

Since it's symmetric around the origin I need only to look at the interval $[0,b]$ and solve for the wavefunction there. The energy is lower than $V_0$ so I will get exponentials in $[a,b]$ and sine and cosine in $[0,a]$.
\begin{cases}
A\cos(kx) + B\sin(kx),  & \text{for }0 < x < a  \\
Ce^{Kx} + De^{-Kx}, & \text{for }a < x < b
\end{cases}
Now I use the requirement that psi needs to be continuous at $a$, derivative contionuous at $a$, zero at the infinite wall and since I only look at half of the potential I need to add the condition that the derivative should be zero at $x=0$ for even functions of $\psi$. If I do this I get
\begin{cases}
A\cos(ka) + B\sin(ka) = Ce^{Ka} + De^{-Ka},  & \text{(Continuity at $x=a$) [1]} \\
-Ak\sin(ka) + Bk\cos(ka) = K(Ce^{Ka} - De^{-Ka}), & \text{(Derivative continuous at $x=a$) [2]} \\
Ce^{Kb} + De^{-Kb} = 0, & \text{(Wavefunction should be zero at the wall) [3]}\\
-Ak\sin(0) + Bk\cos(0) = 0, & \text{(derivative at $x=0$ should be zero)  [4]}
\end{cases}
From [4] one can see that B have to be zero and from [3] I can express $C$ in terms of $D$ but here is where I get stuck. I got two equations that I can use to solve for $A$ now, but I get two different answers depending on if I use [1] or [2]
\begin{cases}
A = \frac{C(e^{Ka} - e^{-Ka+2Kb})}{\cos(ka)},  & \text{If I use [1]} \\
A = \frac{-KC*(e^{Ka} + e^{-Ka+2Kb})}{k\sin(ka)} & \text{If I use [2]}
\end{cases}
Which one am I supposed to use in the normalization? Or are they equal if you just rewrite them in some way?

A: Assuming you've done the algebra correctly, these equations can be solved for a relationship between $k$ and $K$, which should lead to the quantization of energy levels in terms of $a$, $b$, and $V_o$. Then you solve for $C$ in terms of $A$ from either equation (you MUST get the same result with either) and then normalize.


text:
Q: Bootstrap's tooltip on dynamically generated content The page I'm working on is this: http://rafaelviana.com.br/busca_usp/
First, hover on the "test" link on top of the page. No bootstrap tooltip, right? Now press 'a' on the form. A table will appear with relevant results. Hover over the "test" link again. The tooltip appears.
I'm trying to make those tooltips appear on the "Unidade" column's items (these are acronyms for University departments' names). Such tooltips should display the department's full names.
But it appears that no tooltips ever work when I add the data-toggle="tooltip" attribute to dynamically-generated elements. They only work on static elements (such as the odd 'test' link on top of the page).
This persists even when I call bootstrap's tooltip from inside the code that generates the table (which is what's happening, as you noticed the test tooltip won't appear unless you make a search), that is, it persists even though $(function () {$('[data-toggle="tooltip"]').tooltip()}) runs after the elements are added to the DOM.
How can I make it so that tooltips appear on every element that contains the data-toogle attribute, be it dynamic or static?
edit: fixed, per solution in the comments. I think what I was doing wrong was make the call for .tooltip() inside a $function () {} element.


text:
Q: Expected value of functions of order statistics Let $F$ be a CDF over $[\underline{y},\bar{y}]$ and $g(\cdot)$ is some strictly increasing function. I know the following has at least one solution.
\begin{equation}
2F(y)\int_{\underline{y}}^{y}g(x)\frac{dF(x)}{F(y)}=\int_{\underline{y}}^{y}g(x)\frac{dF(x)^2}{F(y)^2}\end{equation}
Can we guarantee that the solution is unique? (assume $g(\underline{y})>0$)

A: The solution is not unique, in general. just take $F$ to be uniform on $[0,1]$. Write the equation as $$h(y)=f(y)-g(y)$$
The second derivative of $h$ must be strictly positive or negative in order to guarantee the uniqueness. One gets however (for $\int xdx^2$, i had $dx^2=dy$, $x=\sqrt{y}$)
$$h(y)=(3/2)y^5-y^{3/2}-(3/2)y^2c^3+c^{3/2}$$
and
$$h^{''}(y;c)=30y^3-(3/4)y^{-1/2}-3c^3$$
Since $c=0$, because $F$ is uniform on $[0,1]$, we have
$$h^{''}(y)=30y^3-(3/4)y^{-1/2}$$
which is neither positive nor negative for all $y$.
https://www.wolframalpha.com/input/?i=Plot+30x%5E3-(3%2F4)x%5E(-1%2F2)++from+0+to+0.5


text:
Q: Show more fields with a button on ASP I'm doing website where the employee can write his resume, i have a section of Past Jobs, and i want to display the fields where the employee can write this info (company, position, etc), but, i want to show just one of those sections, if the employee wants to add more old jobs he will click on the add more and then shows 2 or 3 more fields for those past jobs, currently i have 3 of those sections declared like this:
    <asp:Label ID="Label6" runat="server" Text="Empresa" Style="z-index: 1; left: 10px;
        top: 165px; position: absolute"></asp:Label>
    <asp:TextBox ID="TextBox3" runat="server" Style="z-index: 1; left: 80px; top:  165px;
        position: absolute" Width="200px"></asp:TextBox>
    <asp:Label ID="Label7" runat="server" Text="Fecha" Style="z-index: 1; left: 10px;
        top: 195px; position: absolute"></asp:Label>
    <asp:DropDownList ID="DropDownList1" runat="server" Style="z-index: 1; left: 80px;
        top: 195px; position: absolute">
        <asp:ListItem>Enero</asp:ListItem>
        <asp:ListItem>Febrero</asp:ListItem>
        <asp:ListItem>Marzo</asp:ListItem>
        <asp:ListItem>Abril</asp:ListItem>
        <asp:ListItem>Mayo</asp:ListItem>
        <asp:ListItem>Junio</asp:ListItem>
        <asp:ListItem>Julio</asp:ListItem>
        <asp:ListItem>Agosto</asp:ListItem>
        <asp:ListItem>Septiembre</asp:ListItem>
        <asp:ListItem>Octubre</asp:ListItem>
        <asp:ListItem>Noviembre</asp:ListItem>
        <asp:ListItem>Diciembre</asp:ListItem>
    </asp:DropDownList>
    <asp:DropDownList ID="DropDownList2" runat="server" Style="z-index: 1; left: 172px;
        top: 195px; position: absolute" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
    </asp:DropDownList>
    <asp:Label ID="Label8" runat="server" Text="a" Style="z-index: 1; left: 235px; top: 195px;
        position: absolute"></asp:Label>
    <asp:DropDownList ID="DropDownList3" runat="server" Style="z-index: 1; left: 250px;
        top: 195px; position: absolute">
        <asp:ListItem>Enero</asp:ListItem>
        <asp:ListItem>Febrero</asp:ListItem>
        <asp:ListItem>Marzo</asp:ListItem>
        <asp:ListItem>Abril</asp:ListItem>
        <asp:ListItem>Mayo</asp:ListItem>
        <asp:ListItem>Junio</asp:ListItem>
        <asp:ListItem>Julio</asp:ListItem>
        <asp:ListItem>Agosto</asp:ListItem>
        <asp:ListItem>Septiembre</asp:ListItem>
        <asp:ListItem>Octubre</asp:ListItem>
        <asp:ListItem>Noviembre</asp:ListItem>
        <asp:ListItem>Diciembre</asp:ListItem>
    </asp:DropDownList>
    <asp:DropDownList ID="DropDownList4" runat="server" Style="z-index: 1; left: 342px;
        top: 195px; position: absolute" OnSelectedIndexChanged="DropDownList4_SelectedIndexChanged">
    </asp:DropDownList>
    <asp:Label ID="Label9" runat="server" Text="Puesto:" Style="z-index: 1; left: 10px;
        top: 225px; position: absolute"></asp:Label>
    <asp:TextBox ID="TextBox4" runat="server" Style="z-index: 1; left: 80px; top: 225px;
        position: absolute" Width="200px"></asp:TextBox>
    <asp:Label ID="Label10" runat="server" Text="Funciones:" Style="z-index: 1; left: 10px;
        top: 255px; position: absolute"></asp:Label>
    <asp:TextBox ID="TextBox5" runat="server" Rows="5" TextMode="MultiLine" Style="z-index: 1;
        left: 80px; top: 255px; position: absolute" Width="200"></asp:TextBox>

So, i just want to hidden the other 2 and just show them when i click on the button Add More, i'm a really newbie on ASP, and no idea how to do it, and how this can influence the other labels and textboxes i have since everyone has a a position with left and top, if they will be needed to move or what will hapen to them.
I hope i'm explaining my problem and you can help me :D

A: protected void btnShowMore_Click(object sender, EventArgs e)
{
DropDownList1.Visible=false;
DropDownList2.Visible=false;
DropDownList3.Visible=true;
}

And may use properity 'Enabled' if you want the control to be displayed but user can't do actions on it.

A: This sounds like you need some javascript magic. You could perform something like this when a button is clicked inside your aspx page. Would just need to have the section you want to toggle have a display attribute of "none" by default (style="display: none"). Then when "Add More" is clicked, the display attribute will change to "block", showing the hidden section :

Then call this javascript function like this where ever the button or link is:
Add More

Best of luck!


text:
Q: Yii2, хранение в app Здравуствуйте
Хочу в любой точке приложения иметь доступ к app->currentCompany, где будет компонент с моделью.
Делал по мануалу, но данные не сохраняются в app->currentCompany.
Код:
config\web
        'currentCompany' => [
            'class' => 'app\models\company\CurrentCompany',
        ], ....

CurrentCompany
class CurrentCompany extends Component
{
    private $_model = null;

    public function setModel($id){
        $this->_model = Company::getCompanyById($id);
    }

    public function getModel()
    {
        return $this->_model;
    }

в одном контролере задаю Yii::$app->currentCompany->setModel(1) и во view получаю правильно Yii::$app->currentCompany->getModel, но при этом после переходя на другую страницу данные теряются.
как это исправить? чтобы в одном месте сделать setModel и данные оставались во всем приложении


text:
Q: how to add formatted string (for multiple filenames etc.) in tchar Like in win32 C++ we use to use following code if needed to add multiple files as
file_name0.txt, filename1.txt, ...., filename30.txt etc.
char fname[20];
for i = 0 -> 30 {
sprintf(fname, "filename%d.txt", i);
}

How can we do the same with TChar since I need to read multiple files in this case too
thanks
Kashan

A: _stprintf( fname, TEXT("filename%d.txt"), i);

You will need to define fname as a tchar.


text:
Q: Silverstripe bulk save all dataobjects I've added URLSegments to DataObjects (Products) so I can then display the ProductName as the URL....the code works fine:
public function onBeforeWrite(){
    if($this->Name){
        $this->URLSegment = SiteTree::GenerateURLSegment($this->Name);
        if($object = DataObject::get_one($this->ClassName, "URLSegment='".$this->URLSegment."' AND ID !=".$this->ID)){
            $this->URLSegment = $this->URLSegment.'-'.$this->ID;
        }
    } else {
        $this->URLSegment = SiteTree::GenerateURLSegment($this->ClassName.'-'.$this->ID);
    }
    parent::onBeforeWrite();
}

But, I have over 1000 Products...is there any way of generating a bulk save for all Product Dataobjects in code (ie as a one-off) so I don't have to manually save each through the CMS??

A: Just create a controller with an index function and use more or less the same code.
<?php

class UpdateProducts extends Controller {
    public function index() {

        $products = DataObject::get('Products');

        foreach ($products as $product) {

            if (!$product->URLSegment) {
                $product->write();
            }
        }
    }
}

Then you can call the function once from the browser at http://example.com/UpdateProducts
This isn't super efficient so it really is only a one off. If the script times out, you can just run it again as the if statement in there means only products without a URLSegment will be updated.

A: I started to implement drzax solution, then found this, which implements it as a task. This task was created to add URLSegments to products, so fits my needs perfectly...
http://www.balbuss.com/creating-tasks/


text:
Q: Why isn't dplyr filter() properly filtering out blanks found in two columns? Am I doing something wrong with the logic here? See below:
nrow(contractors_fy20)

[1] 59190
y <- contractors_fy20 %>% filter(recipient_name == "" & recipient_parent_name == "")
nrow(y)

[1] 1
This appears to be accurate.
x <- contractors_fy20 %>% filter(recipient_name != "" & recipient_parent_name != "")
nrow(x)

[1] 58952
Why is it removing a thousand rows when it should only be removing one?

A: The first condition checks when both are blank.  In the second case, it is only checking when both are non-blank.  Instead, it should be either one of them as non-blank, as this will also include the cases where both are non-blank
x <- contractors_fy20 %>%
         filter(recipient_name != "" | recipient_parent_name != "")

Consider the below example
x1 <- c("", 'a', 'b', "", "")
x2 <- c("a", "", "a", "", "b")

Checking when both are blank.  It is only the 4th element
x1 == "" & x2 == ""
#[1] FALSE FALSE FALSE  TRUE FALSE

Check if both are non-blank, and it is only the third element
x1 != "" & x2 != ""
#[1] FALSE FALSE  TRUE FALSE FALSE

The OR (|) will be TRUE when either one of them is non-blank
x1 != "" | x2 != ""
#[1]  TRUE  TRUE  TRUE FALSE  TRUE

the total is 5 in length and now we have 4 TRUE


text:
Q: Merging non-contiguous polygons in OpenLayers 3 / Turf.js I need to merge polygons that are in close vicinity to each other.
Consider the following screenshot:

I want the user to select both polygons and then merge them when clicking on a button, so something like this is returned (the area in between would be filled and all of it would be one large polygon):

My initial idea was to use Turf.js to generate hulls, but this is obviously not giving me what I want.
A convex hull returns way too much:

And a convex hull returns way too little:

Is there a way to achieve my goal in OpenLayers 3, natively, or with the assistance of Turf.js? (I am open to other libraries as well)


text:
Q: Best practice for handling optional parameters in ExpressJS I'm a beginner in Node JS and Express JS. I'm working on creating an API with which I use a request URL http://localhost:3000/?term=jerry&city=dublin having two parameters. I'm able to get these values using req.query. I want the city to be optional. If there is no value for city is present, the query should  work fine. How can I implement this? I want multiple parameters to be handled in this way. eg. I want the parameter 'term' to be mandatory and all other terms to be optionals in the request http://localhost:3000/?term=jerry&city=dublin&age=25&profession=student. My database is postgres and how shall I handle the cases when multiple parameters are optionals and the values are not entered for these parameters. Should I modify my query based on the parameter values? I get 'undefined' for parameters that are not sent with the request URL and my query fails to implement. Can someone help me with the best practices regarding this. I was able to find results for handling queries using req.params.
Adding the method where I handle the request:
router.get('/', function (req, res) {
  var db = require('./db');
  console.log(req.query.term);
  console.log(req.query.country);
  var term = req.query.term;
  var country = req.query.country;
  db.any('SELECT s.official_title, e.gender, e.criteria,  fc.name, fc.email, fc.phone, f.country, c.name, c.downcase_name FROM eligibilities AS e LEFT JOIN studies AS s ON e.nct_id = s.nct_id  LEFT JOIN facility_contacts AS fc ON fc.nct_id = s.nct_id  LEFT JOIN facilities AS f ON f.nct_id = s.nct_id LEFT JOIN conditions AS c ON c.nct_id = s.nct_id GROUP BY s.official_title, e.gender, e.criteria,  fc.name, fc.email, fc.phone, f.country, c.name, c.downcase_name HAVING c.downcase_name LIKE $1 AND f.country LIKE $2 LIMIT 10', ['%' + term + '%', '%' + country + '%']).then(function(data) {
  return res.status(200).send(data);
  }).catch(function(error) {
    return res.status(500).send("There was an error");
  });
});


text:
Q: SQL Server 2012 - Unable to drop User Defined function The following syntax successfully creates a user defined function, but does not drop it. Can anyone identify where my error is?
-- Example 1 - scalar function
USE AdventureWorks2012
GO

CREATE FUNCTION Sales.uf_MostRecentCustomerOrderDate (@CustomerID int)
RETURNS
   DATETIME
AS
BEGIN;
    DECLARE @MostRecentOrderDate datetime;

    SELECT @MostRecentOrderDate = MAX(OrderDate)
    FROM Sales.SalesOrderHeader as soh
    Where CustomerID = @CustomerID
RETURN @MostRecentOrderDate
END;
GO

-- Using user defined scalar function
SELECT Sales.uf_MostRecentCustomerOrderDate(29825); -- returns 2008-04-01 00:00:00.000

-- Delete existing scalar valued function
USE AdventureWorks2012;
GO

-- determines if function exists in database
IF OBJECT_ID (N'Sales.uf_MostRecentCustomerOrderDate', N'IF') IS NOT NULL
    -- deletes function
    DROP FUNCTION Sales.uf_MostRecentCustomerOrderDate;
GO

A: That function gets created with a type of FN (not IF as you've used).
Try this code to drop it:
-- determines if function exists in database
IF OBJECT_ID (N'Sales.uf_MostRecentCustomerOrderDate', N'FN') IS NOT NULL
    -- deletes function
    DROP FUNCTION Sales.uf_MostRecentCustomerOrderDate;
GO

Type IF stands for an inline table-valued function - this is not the case here.
Type FN stands for a scalar function - which this is.
See the TechNet docs on sys.objects which also lists all defined types in SQL Server catalog views


text:
Q: Kentico Installation Manager deploy feature I have a question regarding KIM for Kentico 11 CMS, about it's Deploy feature. Documentation states that:

Deploy to ... - allows you to deploy web site projects to a specific directory or remote server. The deployment copies the content of the CMS folder, which you can then use as the physical path of an application in IIS. The Deploy to functionality is not available for web application projects.

Is this therefore recommended way to Deploy a kentico instance (database + codebase) to a production server?

A: Well the option to use KIM is there, but I for example use manual file transfer and DB restore. There is no best way on how to do that and in the end it is just another code that needs to be moved along with database.
Summary of best practices can be found on Kentico Advantage site.


text:
Q: Need image editor in website to edit image i am looking for jquery image editor any one has idea or link please help me.
i want editor like demo
Thanks

A: What you want is basically a text editor with an image uploading capability.
There are some in this link.
http://www.jqueryrain.com/demo/jquery-wysiwyg-editor/


text:
Q: emacs markdown-mode no  tag for inline code I would like the following markdown code:

```
def hello_world(self):
print "hello world!"
```

To be exported by M-x markdown-export as:

 def hello_world(self):
     print "hello world!"

Instead, M-x markdown-export results in:

 def hello_world(self):
     print "hello world!"

Is there a solution for this in emacs?

A: This is no Emacs problem, presuming you are referring to Jason Blevins' Markdown Mode.
This mode does not export HTML by itself.  It simply passes the buffer contents to the external Markdown processor in the variable markdown-command.
By default, Markdown Mode uses the markdown command, that is, the original Markdown implementation, which does not supported various extensions, such as the code blocks in your example.
You need to install a Markdown processor that supports this kind of markup and set markdown-command accordingly.
You can use markdown2, for example:
(setq markdown-command "markdown2 -x fenced-code-blocks")


text:
Q: Is it possible to have multiple SSH keys? I would like to generate multiple SSH keys for my different servers.
For example:

*

*1 RSA 2048 public/private key for 1.1.1.1

*1 ECC public/private key for 2.2.2.3

*1 ECC public/private key for 3.3.3.3

I understand the ssh keys are stored in the .ssh folder, but how can I copy the right public keys to the correct servers, and how can I generate multiple SSH keys without writing each-other over? I have read something about the -c command, but do not fully understand if it is able to do what I am requesting.

A: Yes, you can have multiple SSH keys.
I would suggest reading the man page for ssh-keygen:
http://man.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/ssh-keygen.1?query=ssh-keygen%26sec=1
Use the -f option to specify your own filename.
ssh-keygen -t rsa -f myfirstrsakey


text:
Q: How to scale font and container's height in Xamarin.Forms I have problem with properly scaling height of containers and font size in Xamarin.Forms.
1) The first problem is that I need to set static height in one of my containers but it looks different on different devices. I don't know exactly but suppose that problem can be caused by screen density. Should I scale height of my container somehow or Xamarin.Forms should handle this for me?
2) The second problem is that I need to set proper cross-platform font. Is there a way to Xamarin.Forms handle it for me or need I use Device.RuntimePlatform property to set this? Also as said here: https://learn.microsoft.com/pl-pl/xamarin/xamarin-forms/user-interface/text/fonts - named font sizes are not acceptable solution. For iPod I need to use micro, but on android the text is barely visible.
On emulator there are many weird things happen, topbar is way out of scale and entire look is zoomed. Is this my fault or maybe Xamarin is not such universal platform I thought?
Here is the code of my page:
<StackLayout>
    <SearchBar
        VerticalOptions="Start"
        TextChanged="SearchBar_OnTextChanged"
        PlaceholderColor="#C0C0C0"></SearchBar>

    <ListView
        BackgroundColor="#f2f2f2"
        VerticalOptions="Center"
        ItemTapped="SelectProcedure"
        CachingStrategy="RecycleElement">

        <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell
                    Text="{Binding Name}"
                    TextColor="Black"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

    <StackLayout
        BackgroundColor="White"
        HeightRequest="80"
        HorizontalOptions="FillAndExpand"
        VerticalOptions="EndAndExpand">

        <Grid
            Padding="10,5,10,5"
            HorizontalOptions="FillAndExpand"
            VerticalOptions="FillAndExpand">

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <Label
                Grid.Column="0"
                Grid.Row="0"
                VerticalTextAlignment="Center"
                VerticalOptions="Center"
                HorizontalTextAlignment="Center"
                HorizontalOptions="Center"
                TextColor="Black"/>

            <telerikInput:RadButton
                Grid.Column="1"
                Grid.Row="0"
                Padding="5,0,5,0"
                ImageSource="plus.png"/>

        </Grid>
    </StackLayout>
</StackLayout>

And here are the screenshots for two devices I have and emulator:
Android 8.1

iPod touch 6

Android 8.1 (emulator)

A: Solution: You can set the HeightRequest grid as the percentage of screen height (for example 10%) .
<StackLayout
        BackgroundColor="White"
        HeightRequest="{Binding stackHeight}"
        HorizontalOptions="FillAndExpand"
        VerticalOptions="EndAndExpand">

in Share Project App.xaml.cs
public static double ScreenWidth;
public static double ScreenHeight;

in Android MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
   TabLayoutResource = Resource.Layout.Tabbar;
   ToolbarResource = Resource.Layout.Toolbar;

   base.OnCreate(savedInstanceState);

   Xamarin.Essentials.Platform.Init(this, savedInstanceState);

   global::Xamarin.Forms.Forms.SetFlags("Shell_Experimental", "Visual_Experimental", "CollectionView_Experimental");
   global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

   App.ScreenWidth = Resources.DisplayMetrics.WidthPixels/Resources.DisplayMetrics.Density;
   App.ScreenHeight =Resources.DisplayMetrics.HeightPixels/Resources.DisplayMetrics.Density;

   LoadApplication(new App());
}

in iOS
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    //...
    App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
    App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;
    //...
}

in Code Behind or ViewModel
public double stackHeight { get; private set; }

//...

if(Device.RuntimePlatform=="iOS")
{
  stackHeight= App.ScreenHeight/5.0;
}
else
{
  stackHeight= App.ScreenHeight/20.0;
}

And for Custom Font in Xamarin.Forms , you can check https://xamarinhelp.com/custom-fonts-xamarin-forms/


text:
Q: maven2 dependencies In a pom.xml, when specifying a dependency version, what is the difference between LATEST and [0,) ?
In my opinion they should be equivalent, but for some dependencies, LATEST does not match any version, whereas [0,) does.

A:
In my opinion they should be equivalent, but for some dependencies, LATEST does not match any version, whereas [0,) does.

In theory, LATEST is the latest released or snapshot version (see Rich Seller's excellent answer on the special RELEASE and LATEST versions) so I would indeed expect the same behavior as with the [0,) range. Out of curiosity, can you provide an example where LATEST doesn't match?
That being said, I don't recommend using the LATEST nor RELEASE special versions as they make your build more fragile and harm the build reproducibility (you don't really want your build to suddenly start to fail because of some uncontrolled update). Admittedly, they're considered as a bad idea and references have been removed from the documentation (except from an untranslated part of the German version of the Definitive Guide)
and they are no longer supported in Maven 3.x.
You are thus strongly invited to not use them at all (bad practice, deprecated, not supported in the next version).
And I somehow consider the same applies to version ranges (in general), I don't recommend them either as I wrote many times in previous answers or comments. See for example:

*

*Managing maven dependancies - New Versions and Non-Repo libraries

*Maven automatic SNAPSHOT update

*Debugging Maven's "The artifact has no valid ranges"

Follow-up after comment

Here's an example (among many):
<dependency>
  <groupId>aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>[0,)</version>
</dependency>

-> matches version 1.5.3 Whereas:
<dependency>
  <groupId>aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>LATEST</version>
</dependency>

-> cannot be resolved

I'm not 100% but I don't think this artifact is providing the right maven-metadata.xml for this feature to work. I think metadata should include <release> and <latest> elements like for maven plugins (see for example this maven-metadata.xml). But I wouldn't spend too much time on this for the aforementioned reasons, just forget this LATEST stuff.

A:
When you depend on a plugin or a
  dependency, you can use the a version
  value of LATEST or RELEASE. LATEST
  refers to the latest released or
  snapshot version of a particular
  artifact, the most recently deployed
  artifact in a particular repository.
  RELEASE refers to the last
  non-snapshot release in the
  repository. In general, it is not a
  best practice to design software which
  depends on a non-specific version of
  an artifact. If you are developing
  software, you might want to use
  RELEASE or LATEST as a convenience so
  that you don't have to update version
  numbers when a new release of a
  third-party library is released. When
  you release software, you should
  always make sure that your project
  depends on specific versions to reduce
  the chances of your build or your
  project being affected by a software
  release not under your control. Use
  LATEST and RELEASE with caution, if at
  all.

See, for further information regarding this topic.
Make sure that the artifact you're looking for is present in your local repository.
However, I have to warn you about the LATEST and RELEASE version markers, as the documentation extract says, it is consider a bad practice to work with those. In fact, I think the LATEST and the RELEASE version markers will no longer be supported in Maven 3.X.
My recommendation is that you drop it usage completely and stick to the specific version notation.
EDIT:
Here is a POST that addressed this exact same information, but more thoughtfully.
Thanks to @Pascal Thivent for the observation :) I always include reference to the other StackOverflow questions that deal with the same subject I'm discussing.


text:
Q: trying to add 2 char arrays in different objects via operator+ overloading I seem to be having tons of difficulty getting this addition operator overload to work for my objects. I've scoured the net and can't quite figure out what it is I'm doing wrong. Basically its supposed to be overloaded to concatenate 2 char arrays. Everything I try causes either a crash or a random jumble of characters.
I'm new to operator overloading, so maybe I'm utilizing it wrong.
Its called with:
String myString1, myString2;
std:: cout << "\nYour strings added are: " << myString1 + myString2;

And in the header file...
 String operator+(String);

Here's the relevant code:
String String::operator+(String rhs){
String result;
int i = length;

for(int x = 0; x < length; x++)
{
        result.ch[x] = ch[x];
        std::cout << result.ch[x];
}

std:: cout << " ";

for (int j = 0; rhs.ch[j] != '\0'; ++i, ++j)
{
         result.ch[i] = rhs.ch[j];
         std::cout <<result.ch[i];
}

return result;
}

I'll provide full source code if needed. Everything else works perfectly though.
.hpp:
#include<iostream>
#include<string>

using std::istream;
using std::ostream;

const int default_size = 256;
class String
{

  public:

         // constructors
         String();
         String(const char ch, const int default_size);
         String(const String& rhs, int cap = default_size); // copy constructor

         // accessor functions
         void getLength(String str);
         void outPut(String str);
         void findChar(String str);
         // destructor
         ~String (); // destructor

         // mutator functions
         void getInput(String str);

         // friend I/O function overloads
         friend std::istream& operator>>(std::istream&, const String& str);
         friend std::ostream& operator<<(std::ostream&, const String& str);

         // operator overloads
         String operator+(String str);

  private:
          int strLength, length;
          int capacity;
          char ch[default_size];
          char *s; };

and .cpp
// String.cpp

#include "String.hpp"
#include<iostream>

// default constructor
String::String()
{
}

// char constructor
String::String(const char ch, const int default_size)
{
capacity = default_size;
s = new char[capacity];
s[0] = ch;
s[1] = '\0';
strLength = 1;
}

//copy constructor
String::String(const String& rhs, const int cap)
{
// Check if string capacity is shorter than length
if (cap <= rhs.strLength)
    capacity = rhs.strLength + 1;
    else
        capacity = cap;

    s = new char[capacity];

// Copy chars to string
for (length = 0; rhs.s[length] != '\0'; ++length)
{
    s[length] = rhs.s[length];
}

s[length] = '\0';
}
// destructor
String::~String()
{
strLength = 0;
delete [] s;
}

// overloaded io operatiors
// Outputs string with << operator
ostream& operator<<(ostream& out, const String& str)
{
out << str.s;
return out;
}

// Inputs string with >> operator
istream& operator>>(istream& in, const String& str)
{
in >> str.s;
return in;
}

// gets users input
void String::getInput(String str)
{

 std:: cout << "Please enter a string.\n";
 std:: cin.getline(ch, default_size);

}

// getLength
void String:: getLength(String str)
{
  size_t strLength = strlen(str.ch);
  length = strLength;
  std:: cout << "The length is " << strLength << ".\n";
}

// output
void String:: outPut(String str)
{
 std:: cout << "\nYou entered.\n";
 for(int x = 0; x < str.length; x++)
 {
         std:: cout << ch[x];
 }
         std:: cout << "\n";
 }

// user enters a character, this provides the location(s)
void String:: findChar(String str)
{
char * charSearch;
char s;
std:: cout << "\nPlease enter a character to search for. \n";
std:: cin >> s;
std:: cout << "\n";
charSearch = strchr(ch, s);

while(charSearch != '\0')
{
                 std:: cout << "Found at: " << charSearch-ch+1 << "\n" ;
                 charSearch = strchr(charSearch+1, s);
}
std::cin.ignore();
}

// OPERATOR OVERLOADS---------------------------------------------------

// Addition operator
// adds the right hand object to the lefthand object
String String::operator+(String rhs)
{
String result;
int i = length;
for(int x = 0; x < length; x++)
{
        result.ch[x] = ch[x];
        std::cout << result.ch[x];
}

std:: cout << " ";

for (int j = 0; rhs.ch[j] != '\0'; ++i, ++j)
{
         result.ch[i] = rhs.ch[j];
         std::cout <<result.ch[i];
}
std::cout << "\nHere is result.ch: ";
for(int z = 0; result.ch[z] != '\0'; z++)
{
        std::cout << result.ch[z];
}

return result;
}

A: You have more problems than the concatenation, and I doubt that everything else "works perfectly".

*

*Your default constructor doesn't initialise anything.
Even String s; std::cout << s; shouldn't work, and neither should String s; std::cin >> s;.

*You don't have an assignment operator.
{String s1; String s2; s2 = s1;} will most likely crash.

*You have both a pointer s and an array ch.
You store data in s, but some code uses ch instead.
You need to make up your mind.
(And don't use the same name for parameters and local variables as you do for members.)

*You have both strLength and length, and use them seemingly at random.
There's more undefined behaviour in your code than anyone can be bothered to list.
Your best road ahead is probably to throw the code away and start over.


text:
Q: SOLR \ More Like This Feature \ how to do loose search of similar text, and have some freedom degree Let's say I have long text and I want to search "Term1 Term2 Term3 Term4"
I'd like to surface similar documents in a relaxed way -

*

*other terms can come between in reasonalbe matter - doc with "Term1 OtherTerm Term2 OtherTerm Term3" is acceptable

*not all 4 terms should appear - again in reasonalbe manner (3 terms are ok)
from my expereiment seems like SOLR retrieve only docs with the Exact(!) text you were searching...
I tried add all the params with lower limits:
Raw Query Params: mlt=true&mlt.fl=Text&mlt.boost=true&mlt.mindf=1&mlt.mintf=0&mlt.interestingTerms=Text
So - is it possible to have similarity work and not only exact search to work?

A: The mlt parameters only govern how the more like this operation works.  MoreLikeThis works in two stages, first it gets a set of results from the query, before any MoreLikeThis functionality comes into play.  Then it takes the results of that query, and looks up documents similar to them.  It does this, generally, by picking what it judges to be the most relevant and useful search terms from the body of the document, and searching on them.  So them mlt parameters have nothing to do with how your initial query is handled.  Usually, you want your initial mlt query to get very few results, often a single document.
Sounds like you don't want to be using a phrase query at all, so lose the quotes.

*

*"Term1 Term2 Term3 Term4" = Phrase query, find all those terms in order

*Term1 Term2 Term3 Term4 = Series of separate term queries.  Find all or any of the terms anywhere in the field.

See the lucene query parser syntax documentation for more information.


text:
Q: Html-webpack-plugin URIError: Failed to decode param '/%3C%=%20htmlWebpackPlugin.files.css%20%%3E' I ran into a problem from the title. Initially, I only had index.html and everything was going great.
index.html
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Test</title>
  <link rel="stylesheet" href="<%= htmlWebpackPlugin.files.css %>">

and webpack.config.js
module.exports = () => {
  const isProd = process.argv.includes("production");
  const mode = isProd ? "production" : "development";

  return {
    mode,
    entry: {
      main: './src/main.tsx',
    },
    output: {
      path: resolve(__dirname, 'dist'),
      filename: '[name].min.js',
      chunkFilename: '[name].bundle.js?hash=[contenthash]',
    },
    module: {

      ...

    },
    plugins: [
      new HtmlWebpackPlugin({
        template: 'public/index.html',
        inject: false,
        files: {
          js: 'main.js',
          css: 'main.css',
        },
        cache: false,
      }),

       ...
    ],
    devServer: {
      historyApiFallback: true,
      host: `0.0.0.0`,
      port: process.env.PORT || 8080,
      static: resolve('public'),
    },
  };
};

After that I created a new entry point new-index.html, similar like index.html, but new id. And new webpack config with changes only in html-webpack-plugin:
new HtmlWebpackPlugin({
  template: 'public/new-index.html',
  filename: 'new-index.html',
  inject: false,
  files: {
    js: 'main.js',
    css: 'main.css',
  },
  cache: false,
}),

At the end package.json scripts:
"start": "webpack serve --mode development",
"start:new-engine": "webpack serve --mode development --config=webpack.new-engine.js",

When I run npm start everything remains as before.
When I run npm run start:new-engine I get this error:
URIError: Failed to decode param '/%3C%=%20htmlWebpackPlugin.files.css%20%%3E'
    at decodeURIComponent (<anonymous>)

And my styles isn't processed
DOM screen here
I updated webpack-dev-server and html-webpack-plugin to the latest. Trying run on 14.20 and 16.13 node.
What I'm doing wrong? Thx for ur time.