text:
Q: add multiple children to one XML element with PHP I think this task is not to hard, but it looks like i can't figure it out...
This is the data I have:
        $_SESSION["username"]
        $_SESSION["id"]

I want to store these in an XML-file called accounts.xml on registration. This question is not about the entire process, I'm only wondering how to store this correct. After the process I want to have these new structure in my XML-file:
       <account>
           <username>  value of $_SESSION["username"]  </username>
           <user_id>  value of $_SESSION["id"]  </user_id>
       </account>

This is the code I am using so far:
        $xml = simplexml_load_file('accounts.xml');

        $new = new SimpleXMLElement("<account></account>");
        $new->addChild('username', '$_SESSION["username"]');
        $new->addChild('user_id', '$_SESSION["id"]');

        file_put_contents('accounts.xml', $xml->asXML());

I tried some variations, but usually I end up with something like this:
       <username>  $_SESSION["username"]
          <user_id>  $_SESSION["id"]  </user_id>
       </username>

As you can see I have multiple problems:
1.: the < account > element is not even created.
2.: the user_id is inside the username - i don't want that
and 3.: the variables themselves are stored to the file, not their values...
Can you please help me to make things right, here?
note: it is important, that when running another registration, this code works again, without deleting or overwriting anything, simply adding another structure as posted above
Thanks in advance!

A:         $xml = simplexml_load_file('accounts.xml');

        $account = $xml->addChild('account');
        $account->addChild('username', $_SESSION["username"]);
        $account->addChild('user_id', $_SESSION["id"]);

        file_put_contents('accounts.xml', $xml->asXML());

SOLVED

A: I strongly suggest using DOM or XMLWriter to create XML. The Apis are much cleaner and more powerful. In DOM it has 2 parts:

*

*Create the node using a DOMDocument method like createElement(), createTextNode().

*Add the node to its parent (Document or Element) using appendChild(), insertChild(), ...

Additionally you can use the properties and methods of the node to change it.
$document = new DOMDocument();
$account = $document
  ->appendChild($document->createElement('account'));
$account
  ->appendChild($document->createElement('username'))
  ->appendChild($document->createTextNode('John Doe'));
$account
  ->appendChild($document->createElement('user_id'))
  ->appendChild($document->createTextNode(42));
$document->formatOutput = TRUE;
echo $document->saveXml();

XMLWriter:
$writer = new XMLWriter();
$writer->openMemory();
$writer->setIndent(true);
$writer->startDocument('1.0', 'utf-8');
  $writer->startElement('account');
    $writer->writeElement('username', 'John Doe');
    $writer->writeElement('user-id', 42);
  $writer->endElement();
$writer->endDocument();
echo $writer->outputMemory();

You have to keep in mind that anything in an XML document is a node. An element, attributes, cdata sections, etc. SimpleXML is limited and only allows you to access parts of that.


text:
Q: Upgrading R using brew on OS X I have had this problem once before, and I can't figure out the best way to fix it.
I am upgrading r from v3.1.2_1 to v3.1.3 to  using brew upgrade r. But when I do that I lose all the libraries that I installed under v3.1.2_1. I have to install all the libraries from scratch.
The problem seems to be that brew creates two independent directory structures for two different versions of R under /usr/local/Cellar/r. Is there a way to install R by telling it to use the existing libraries that have been installed?
I could just copy over the files from one version to another, but I am afraid of breaking something.

A: You can tell R where to store libraries:
R_LIBS=~/Rlibs

New version of R will look for libraries in this folder. But you will still have to update libraries:
update.packages()

Details are outlined in this post. As a side matter, have a look at the point 2.8 in R FAQ, this one is for Windows but the point is fairly generic. You may be willing to keep old installations the way they are or install new libraries.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I am trying to solve a non-linear equation. In the matlab program, I'm stuck up. One of the problems could be that, I want a matrix of order 33 but the output is 44, with first row and first column consisting of zeros. Can someone help !
n=5; m=5; T=1;
for i=2:n-1
for q=2:m-1
uexact(i,q,T)=exp(i+q-3*T);
end

end
uexact =
     0         0         0         0
     0    2.7183    7.3891   20.0855
     0    7.3891   20.0855   54.5982
     0   20.0855   54.5982  148.4132

A: Use
$uexact(i-1,q-1,T)=exp(i+q-3*T);$
instead.
Even though your original code does only assign values to columns 2-5 and rows 2-5, Matlab automatically assumes that there must be a column 1 and row 1 to which it assigns 0 as a default value.


text:
Q: How can I clear a SDL_Surface to be replaced with another one? Been trying to find this online for a while now.
I have a SDL_Surface with some content (in one it's text, in another is a part of a sprite). Inside the game loop I get the data onto the screen fine. But then it loops again and it doesn't replace the old data but just writes over it. So in the case of the text, it becomes a mess.
I've tried SDL_FreeSurface and it didn't work, anyone know another way?
fpsStream.str("");
fpsStream << fps.get_ticks();
fpsString = fpsStream.str();

game.fpsSurface = TTF_RenderText_Solid(game.fpsFont, fpsString.c_str(), textColor);
game.BlitSurface(0, 0, game.fpsSurface, game.screen);

A: What I do usually is drawing to a secondary surface (that is, an in-memory surface that's not the screen) and then SDL_BlitSurface when it's ready to be copied to the screen. You can then clear the whole secondary buffer (with SDL_FillRect) in the next iteration and redraw everything or just a part of if you don't want to lose the whole surface and only changed a rectangle.
This way, you also get doublebuffering and avoid flickering. Also don't forget SDL_UpdateRects after blitting.

A: If you are drawing something with transparency (eg. stuff from SDL_ttf) then the transparent areas between the text won't be altered, meaning previous writes will remain. This isn't usually a problem because the usual behaviour is for the program to clear the frame buffer and redraw the entire scene once per frame. In the old days it was common to only redraw the 'dirty' parts of the screen but that is not so common now.

A: Try something like:
SDL_FillRect(screen, NULL, 0x000000);
at the beginning of your loop.

A: while( !quit )
            {
                while( SDL_PollEvent( &e ) != 0)
                {
                    if( e.type == SDL_QUIT )
                    {
                        quit = true;
                    }
                    else if( e.type == SDL_KEYDOWN)
                    {
                        **SDL_FillRect(screenSurface, NULL, 0x000000);**
                        switch(e.key.keysym.sym)
                        {
                            case SDLK_w:
                                CurrentSurface = ImageSurfaces[ KEY_PRESS_SURFACE_UP ];
                                break;

                            case SDLK_d:
                                CurrentSurface = ImageSurfaces[ KEY_PRESS_SURFACE_RIGHT ];
                                break;

                            case SDLK_s:
                                CurrentSurface = ImageSurfaces[ KEY_PRESS_SURFACE_DOWN ];
                                break;

                            case SDLK_a:
                                CurrentSurface = ImageSurfaces[ KEY_PRESS_SURFACE_LEFT ];
                                break;

                            default:
                                CurrentSurface = ImageSurfaces[ KEY_PRESS_SURFACE_DEFAULT ];
                                break;
                        }
                    }
                }

                SDL_BlitSurface(CurrentSurface, NULL, screenSurface, NULL);

                SDL_UpdateWindowSurface( window );
            }


text:
Q: Flutter - Animate a widget to move from GridView to BottomBar upon tapping I am looking to animate an image widget to move from a grid view to the bottom bar as shown below but much simpler. Could anyone provide me any guidance as to how to achieve this? I am leaning towards a transform animation, but I have hit a wall trying to calculate the source and destination screen points. Any help is highly appreciated.

A: Try this package, add_cart_parabola:
import 'dart:ui';
import 'package:add_cart_parabola/add_cart_parabola.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  GlobalKey floatKey = GlobalKey();
  GlobalKey rootKey = GlobalKey();
  Offset floatOffset ;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      RenderBox renderBox = floatKey.currentContext.findRenderObject();
      floatOffset = renderBox.localToGlobal(Offset.zero);
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Container(
        key: rootKey,
        width: double.infinity,
        height: double.infinity,
        color: Colors.grey,
        child: ListView(
          children: List.generate(40, (index){
            return generateItem(index);
          }).toList(),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.yellow,
        key: floatKey,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
  Widget generateItem(int index){
    Text text = Text("item $index",style: TextStyle(fontSize:
    25),);

    Offset temp;
    return GestureDetector(
      onPanDown: (details){
        temp = new Offset(details.globalPosition.dx, details.globalPosition
            .dy);
      },
      onTap: (){
        Function callback ;
        setState(() {
          OverlayEntry entry = OverlayEntry(
              builder: (ctx){
                return ParabolaAnimateWidget(rootKey,temp,floatOffset,
                    Icon(Icons.cancel,color: Colors.greenAccent,),callback,);
              }
          );

          callback = (status){
            if(status == AnimationStatus.completed){
              entry?.remove();
            }
          };

          Overlay.of(rootKey.currentContext).insert(entry);
        });
      },
      child: Container(
        color: Colors.orange,
        child: text,
      ),
    );
  }
}


text:
Q: MDX date filter not working properly I am facing this weird behavior for below MDX...where when service date is less than 20170630 I get data for all available service dates till 20171030 but when I reduce the date range I get nothing even though those records were shown earlier with the larger range. Could anyone please help what could be the cause of such behavior.
WITH
MEMBER [Measures].[date_dateid__servicedate] as [Service Date].[Date ID].currentMember.name

MEMBER [Measures].[vendor_vendorname] as [Vendor].[Vendor Name].currentMember.name

MEMBER [Measures].[corporation_corpcode] as [Corporation].[Corp Code].currentMember.name

MEMBER [Measures].[billingcategory_billcategory] as [BillingCategory].[Bill Category].currentMember.name

MEMBER [Measures].[afe_afenumber] as [Afe].[Afe Number].currentMember.name

MEMBER [Measures].[afeproperty_wellname] as [Afe Property].[Well Name].currentMember.name

MEMBER [Measures].[dailygrossexpenses_grossactual] as [Measures].[Gross Actual]

MEMBER [Measures].[dailygrossexpenses_grossexpenseandotherincome_expenseamount] as [Measures].[Gross Expense and Other Income - Expense Amount]

 SELECT
 { [Measures].[date_dateid__servicedate],
   [Measures].[vendor_vendorname],
   [Measures].[corporation_corpcode],
   [Measures].[billingcategory_billcategory],
   [Measures].[afe_afenumber],
   [Measures].[afeproperty_wellname],
   [Measures].[dailygrossexpenses_grossactual],
   [Measures].[dailygrossexpenses_grossexpenseandotherincome_expenseamount]
  } ON columns ,
SUBSET(ORDER(NONEMPTY({ [Vendor].[Vendor Name].Children
       *[Service Date].[Date ID].Children
       *[Corporation].[Corp Code].Children
       *[BillingCategory].[Bill Category].Children
       *[Afe].[Afe Number].Children
       *[Afe Property].[Well Name].Children },
{[Measures].[Gross Actual],
 [Measures].[Gross Expense and Other Income - Expense Amount]}),
 [Measures].[vendor_vendorname],
BASC), 0 ,50 )ON rows
FROM (SELECT { [Vendor].[Vendor Name].&[160] } on columns
  FROM ( SELECT [Service Date].[Date ID].&[20170831]:[Service Date].[Date ID].&[20170930] on columns
    FROM [XXXX] ))


text:
Q: /api/data/v8.2 to /api/data/v9.0 after dynamics CRM online upgrade? I'm relatively new to using the Web API (HTTP REST API) to access Dynamics CRM using javascript so I apologise in advance if this is a stupid question.
We've recently upgraded from v8.2 online to v9.0. Does this mean that I have to parse the js code library that we have and change code such as the one below from v8.2 to v9.0?
req.open("GET", encodeURI(clientUrl + "/api/data/v8.2/accounts?$select=name&$filter=contains(name,'" + strSearch + "')"));

I did perform some preliminary searches but wasn't able to locate anything that answers my question.

A: Not required. As far as I know, D365 9.x releases will support v8.0 Web API unless there is a change in plan for future releases. There are minor changes between the two. For example, if attribute name is same as entity name, v9.x API will not append '1' to the attribute name as v8.x API used to be. In fact, you are required to retest your JavaScript client in case you ever move to v9.0. CRM will otherwise try its best to ensure that backward compatibility is not broken with v8.x APIs.

A: Better to do one time refactoring to use Xrm.Page.context.getVersion, this way the version will be dynamic in supported way.

A: Probably.
Go to Developer Resources within CRM. (Settings > Customisations > Developer Resources).
You can then see the API endpoints for your organisation.


text:
Q: How to change font In Flutter Date Picker? How to change the title and other text's font family, size etc????

A: Use the Theme widget to customize the fonts, size and color and many other properties of showDatePicker. Just add the property builder to showDatePicker and wrap the child with the Theme widget.
Take a look at the live demo on DartPad

Before
After

Here's the source:
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void _showDatePicker() {
    // showMaterialDatePicker(context: context);
    showDatePicker(
      context: context,
      initialDate: DateTime(2022),
      firstDate: DateTime(2022),
      lastDate: DateTime(2023),
      // initialDatePickerMode: DatePickerMode.year,
      initialEntryMode: DatePickerEntryMode.calendar,
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(
            dialogBackgroundColor: Colors.yellow, // days/years gridview
            textTheme: TextTheme(
              headline5: GoogleFonts.greatVibes(), // Selected Date landscape
              headline6: GoogleFonts.greatVibes(), // Selected Date portrait
              overline: GoogleFonts.greatVibes(), // Title - SELECT DATE
              bodyText1: GoogleFonts.greatVibes(), // year gridbview picker
              subtitle1: GoogleFonts.greatVibes(color: Colors.black), // input
              subtitle2: GoogleFonts.greatVibes(), // month/year picker
              caption: GoogleFonts.greatVibes(), // days
            ),
            colorScheme: Theme.of(context).colorScheme.copyWith(
                  // Title, selected date and day selection background (dark and light mode)
                  surface: Colors.amber,
                  primary: Colors.amber,
                  // Title, selected date and month/year picker color (dark and light mode)
                  onSurface: Colors.black,
                  onPrimary: Colors.black,
                ),
            // Buttons
            textButtonTheme: TextButtonThemeData(
              style: TextButton.styleFrom(
                foregroundColor: Colors.yellow,
                backgroundColor: Colors.pink,
                textStyle: GoogleFonts.greatVibes(),
              ),
            ),
            // Input
            inputDecorationTheme: InputDecorationTheme(
              labelStyle: GoogleFonts.greatVibes(), // Input label
            ),
          ),
          child: child!,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: _showDatePicker,
        tooltip: 'Increment',
        child: const Icon(Icons.calendar_month),
      ),
    );
  }
}

A: You can specify fonts in ThemeData() in main.dart.
ThemeData(fontFamily: //Define your font)

NOTE:- It will affects in whole app.


text:
Q: Master View Details with MVVM Pattern I have a MVVM - WPF Browser Application application using Entity Framework 6.
I have tried to select a supplierDataGrid row and display the Products related in another datagrid. But it doesn't work. The application freezes when I select a row. Thanks for your help!
ViewModelBase
public class CommandBase<T> : INotifyPropertyChanged
{
    #region "INotifyPropertyChanged members"
    public event PropertyChangedEventHandler PropertyChanged;
    //This routine is called each time a property value has been set.
    //This will //cause an event to notify WPF via data-binding that a change has occurred.
    protected void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
    private ObservableCollection<T> collection;
    public ObservableCollection<T> Collection
    {
        get
        {
            if (collection == null)
            {
                Get();
            }
            return collection;
        }
        set { collection = value;
            OnPropertyChanged("Collection"); }
    }

    private T _selected;
    public T Selected
    {
        get {
            if(_selected != null)
            GetSub();
            return _selected;
            }
        set { _selected = value;
            OnPropertyChanged("Selected"); }
    }

    private ICommand getCommand;
    private ICommand saveCommand;
    private ICommand removeCommand;
    private ICommand getSubCommand;

    protected virtual void Save()
    {
        //return true;
    }
    protected virtual bool CanSave()
    {
        return true;
    }

    public ICommand DeleteCommand
    {
        get
        {
           // return removeCommand ?? (removeCommand = new RelayCommand(Delete,CanDelete));
            return removeCommand ?? (removeCommand = new RelayCommand(p => this.Delete(), p => this.CanDelete()));

        }
    }

    protected virtual void Delete()
    { }

    protected virtual bool CanDelete()
    {
        if (Selected != null)
            return true;
        else
            return false;
    }

    public ICommand GetSubCommand
    {
        get
        {
            return getSubCommand ?? (getSubCommand = new RelayCommand(p => this.GetSub(), p => this.CanGetSub()));
        }
    }

    protected virtual async Task GetSub()
    {
        await Task.Delay(0);
    }

    protected virtual bool CanGetSub()
    {
        return true;
    }
}

ViewModel
public class SupplierViewModel : CommandBase<foodSupplier>
{
    public Context ctx = new Context();
    protected override void Get()
    {
        ctx.foodSuppliers.ToList().ForEach(supplier => ctx.foodSuppliers.Local.Add(supplier));
        Collection = ctx.foodSuppliers.Local;
    }
    protected override bool CanGet()
    {
        return true;
    }
    protected override void Save()
    {
        foreach (foodSupplier item in Collection)
        {
            if (ctx.Entry(item).State == System.Data.Entity.EntityState.Added)
            {
                ctx.foodSuppliers.Add(item);
            }
        }
        ctx.SaveChanges();
    }
    protected override void Delete()
    {
        var id = Selected;
        var supp = (from s in ctx.foodSuppliers
                where s.idfoodSupplier == id.idfoodSupplier
                select s).SingleOrDefault();
        ctx.foodSuppliers.Remove(supp);
        ctx.SaveChanges();
        Collection.Remove(supp);
    }
    protected virtual bool CanDelete()
    {
        return true;
    }

     protected override async Task GetSub()
    {

        var supplier = Selected;
        var pro = await (from p in ctx.products
                         where p.supplier == supplier.idfoodSupplier
                         select p).ToListAsync();

        Products = pro;

    }

    private IList<product> _products;

    public IList<product> Products
    {
        get
        {

            return _products;

        }
        set
        {
            _products = value;
            OnPropertyChanged("Products");
        }
    }
}

View
<DataGrid x:Name="dataGrid"
          Margin="5"
          ItemsSource="{Binding Collection}"
          AutoGenerateColumns="False"
          SelectedItem="{Binding Selected, Mode=TwoWay}"
          SelectionMode="Extended"
          SelectionUnit="FullRow">
    <DataGrid.Columns>
        <DataGridTextColumn x:Name="dataGridTextColumn"
                            Header="Supplier"
                            Binding="{Binding idfoodSupplier, UpdateSourceTrigger=PropertyChanged}"
                            Visibility="Hidden" />
        <DataGridTextColumn Header="Supplier"
                            Binding="{Binding supplier, UpdateSourceTrigger=PropertyChanged}" />
    </DataGrid.Columns>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <i:InvokeCommandAction Command="{Binding GetCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</DataGrid>
<Button Height="Auto"
        Width="Auto"
        Content="Delete"
        Command="{Binding DeleteCommand}" />

A: EDIT: the program freezes, because you have infinite recursion. Selected getter call GetSub, it calls getter of Selected it call GetSub, etc...
I recommend you to call GetSub in Selected setter, but some additional refactoring may be needed.
TIP: when somethig freezes, pause the program in visual studio and take a look at callstack window. You would immediatelly know whats going on in this case. Maybe you will need to switch to Main thread in Threads window (Ctrl+Alt+H) after you press pause button.


text:
Q: Call Fortran subroutine in a OpenMP parallel region? I am trying to call a subroutine inside the main OpenMP parallel region like:
type(type1) :: A(:)
!$omp parallel private(variable_a, variable_b, ...)
!$do
do i = 1, n, 1
  call A(i) % sub(variable_a, variable_b, ...)
end do
$enddo
!$end parallel

In another file, I define the Fortran type type1, which contains a procedure named sub. The sub is like:
subroutine( this, val_a, val_b, ...)
  class(type1), intent(inout) :: this
  type(anytype), intent(in) :: val_a
  type(anytype), intent(in) :: val_b
  ...

  ! type_2 is another type defined in another file
  type(type2), pointer :: p => null

  do i = 1, n, 1
    allocate(p)
    p => null()
  end do

return
end subroutine

However, I found that the p seems is a shared variable. Why it happens?

A: Following the OpenMP standard p should be shared as it has an initialization and is not part of a threadprivate directive. Quoting from section 5.1.2 in the OpenMP 5.2 standard document:

Local variables declared in called routines in the region and that
have the SAVE attribute, or that are data initialized, are shared
unless they appear as arguments in a threadprivate directive.


text:
Q: Stackdriver Error reporting for Ruby, running on GKE Which steps are required to collect errors from a Rails app running on GKE?
I have added the stackdriver gem to my Rails app and I have created a custom role with the errorreporting.errorEvents.create permission.
That role is given to the Compute Engine default service account
I interpret the docs that one does not have to do the following setup when running on GKE:
# Add this to config/environments/*.rb
Rails.application.configure do |config|
  # Stackdriver Error Reporting specific parameters
  config.google_cloud.error_reporting.project_id = "YOUR-PROJECT-ID"
  config.google_cloud.error_reporting.keyfile    = "/path/to/service-account.json"
end

I manually created an exception
That gave me valuable information:
irb(main):001:0> Google::Cloud::ErrorReporting.report Exception.new(msg: "from console")
=> nil
irb(main):002:0> {:msg=>"from console"} (Exception)
Google::Cloud::PermissionDeniedError: 7:Stackdriver Error Reporting API has not been used in project NNNNN before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/clouderrorreporting.googleapis.com/overview?project=NNNN then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

After enabling the API, then I get this error:
irb(main):004:0> {:msg=>"from console"} (Exception)
Google::Cloud::PermissionDeniedError: 7:User not authorized.

So, which permission do I have to give to which user to make this work? :-|

A: This seems permission issue, so after installing and configuring google-cloud-ruby.
Then, you need to Enable the Stackdriver Error Reporting API.
Then you need to add the role "roles/errorreporting.writer" to the default  compute service account.
gcloud container clusters create example-cluster-name --scopes https://www.googleapis.com/auth/cloud-platform
When you create the cluster you need to add  --scope flag for platform see above an example:


text:
Q: Find the word 'x++' in Fulltextsearch SQLServer I'm trying to indexing the word 'x++' in my fully indexed field, but I don't know how. I think the problem is that the '+' char is not included in indexing list chars.
Executing the query:
SELECT * FROM sys.dm_fts_index_keywords(DB_ID('my_db'), OBJECT_ID('my_table'))

I noticed that the work 'c++' is indexed, so I think there should be a way to ask my sqlserver to index specific word ('c++' is very similar to 'x++' ).
Thanks everybody in advance.

A: It seems that you are looking for something like this.
https://msdn.microsoft.com/en-us/library/ms179859.aspx
SELECT *
FROM table_name
WHERE column_name LIKE '%x++%'


text:
Q: What "type" of impedance is a schematic referring to when talking about differential signals? I'm trying to learn a bit about routing high-speed differential signals. One thing that is confusing me is that often schematics talk about routing certain signal pairs with a specific impedance (usually 90 or 100Ohms). Though while reading into the topic there seems to be quite few different ways to calculate impedance depending on how the signal is propagating through the traces. I'm presented with odd, even, common and differential impedance and when I want to calculate a specific impedance for a microstrip with this tool, it gives me the impedance for all four types mentioned before.
How do I know what the schematic is referring to? Differential impedance sounds obvious but it seems to be a very complicated topic so I don't want to jump to false conclusions.

A: I go into some detail in this answer here: How do I lay out PCB traces for a given "differential impedance", but briefly speaking -- the intention is to create a transmission line of some desired impedance Z. There are a variety of structures that can act as transmission lines, based on whether your signal is single-ended or differential, or whether you are on an external layer vs. internal layer of your PCB.
For example, a microstrip is great for a single-ended signal on the outside of your PCB, say a 50 ohm clock line. Edge-coupled microstrip is great for a say a 90 ohm differential USB trace on the outside of your PCB. On an internal layer, those would become an embedded stripline, and embedded edge-coupled stripline respectively.
The bus you're using should make the single-ended vs. differential question quite obvious, and after that, it would be based on what layer your signal will end up on. Working with your desired PCB fabricator, they can send you the geometries (Width, spacing, etc.) that will result in your desired impedances, usually +/- 10% or so. Then you can set up rules in your PCB layout software to ensure that your traces end up with the correct geometries.


text:
Q: ASP.NET Binding linq query results to HTML.DropDownList() using MVC I am trying to build a drop down list with a single database call.
My table consists of an Id column and a CompanyName column.  I need to display the CompanyName to the user and when one is selected set the Id for the page to Id.
I have put a simple model together to store the information:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace Portal.Models
{
    public class CompanyListId
    {
        public int Id { get; set; }
        public string CompanyName { get; set; }
    }

    public class CompanyListIdDBContext : DbContext
    {
        public DbSet<CompanyListId> Contacts { get; set; }
    }
}

But I am having an issue with the controller and razor call in the view.
My controller:
public void CompanyListIdSearch()
        {
            using (var dc = new CompanyListIdDBContext())
            {
                var content = from p in db.Companies
                                select new { p.CoId, p.CompanyName };
            }
        }

Razor call in View:
<div id="partners" class="linen">

                        @{Html.DropDownList("CompanyListIdSearch", new SelectList(Model.CompanyName));}
                    </div>

Grabbing the model at the top of a view @model Portal.Models.CompanyListId
So at a high level what I am trying to do is have a view that calls the controller with a razor tag, the controller updates the model with data and then that data is displayed in the drop down.  Am I approaching this the wrong way?
I am getting this error:
The model item passed into the dictionary is of type 'Portal.Models.DashboardContents', but this dictionary requires a model item of type 'Portal.Models.CompanyListId'.

A: Not quite. You can't call a method in DropDownList like that.
Firstly, put that collection of items in your ViewBag:
using (var dc = new CompanyListIdDBContext())
{
    var content = from p in db.Companies
       select new { p.CoId, p.CompanyName };

    ViewBag.CompaniesList = content
        .Select(c => new SelectListItem
        {
            Text = c.CompanyName,
            Value = c.CoId.ToString()
        }).ToList();
}

Make sure you call that function in your action result before returning the view.
Lastly, just use your model property and switch to DropDownListFor:
@Html.DropDownListFor(m => m.Id, ViewBag.CompaniesList);

A better approach however, is to not use the ViewBag and to use a view model instead. Something like this:
public class CompanyViewModel
{
    public int Id { get; set; }
    public string CompanyName { get; set; }
    public List<SelectListItem> CompaniesList { get; set; }
}

Then your action method would be something like:
public ActionResult YourAction()
{
    var model = new CompanyViewModel();

    using (var dc = new CompanyListIdDBContext())
    {
        var content = from p in db.Companies
            select new { p.CoId, p.CompanyName };

        model.CompaniesList = content
            .Select(c => new SelectListItem
            {
                Text = c.CompanyName,
                Value = c.CoId.ToString()
            }).ToList();
    }

    return View(model);
}

Then your view would use the new model:
@model CompanyViewModel

Then your dropdown would be:
@Html.DropDownListFor(m => m.Id, Model.CompaniesList)


text:
Q: Can't resolve peer dependencies in node project dev@1d821be6e48f:~/project$ npm i
npm WARN @ngtools/webpack@7.2.1 requires a peer of @angular/compiler-cli@>=5.0.0 <8.0.0 || ^7.0.0-beta.0 but none is installed. You must install peer dependencies yourself.
npm WARN css-loader@2.1.0 requires a peer of webpack@^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@2.29.0 requires a peer of typescript@>=2.1.0 || >=2.1.0-dev || >=2.2.0-dev || >=2.3.0-dev || >=2.4.0-dev || >=2.5.0-dev || >=2.6.0-dev || >=2.7.0-dev || >=2.8.0-dev || >=2.9.0-dev || >= 3.0.0-dev || >= 3.1.0-dev but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.6 (node_modules/@angular-devkit/build-angular/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.6: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.6 (node_modules/@angular/cli/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.6: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.6 (node_modules/@angular/compiler-cli/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.6: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

added 1 package from 1 contributor, moved 1 package and audited 37762 packages in 7.365s
found 0 vulnerabilities

I see that package.json HAS typescript and @angular/compiler-cli. I dont't get NPM logs... What am i missing?
Here is piece of package.json
  "devDependencies": {
    "@angular/compiler-cli": "^7.2.0",
    "typescript": "~3.2.2"
  }

How to translate this? typescript@>=2.1.0 I can't find any good docs concerning version ranges...
Why WARN messages are appearing?

A: try the below command on cmd
npm install -g angular-cli@7.2.0


text:
Q: pandas datetime format drop timezone I have two timeseries that I got from a feather file.
One series turned into dtype datetime64[ns] the other turned into datetime64[ns, UTC]
as the formats are different I can't run pd.merge how can I fix this?
pd.to_datetime(column, utc=False) doesn't seem to do it?

A: I'm still looking for other answers...
However, this works:
Consider the time series ts
ts = pd.date_range('2016-03-31', periods=6, freq='4H', tz='Asia/Hong_Kong')
ts

DatetimeIndex(['2016-03-31 00:00:00+08:00', '2016-03-31 04:00:00+08:00',
               '2016-03-31 08:00:00+08:00', '2016-03-31 12:00:00+08:00',
               '2016-03-31 16:00:00+08:00', '2016-03-31 20:00:00+08:00'],
              dtype='datetime64[ns, Asia/Hong_Kong]', freq='4H')

Then strip off timezone information by building from values
pd.to_datetime(ts.values)

DatetimeIndex(['2016-03-30 16:00:00', '2016-03-30 20:00:00',
               '2016-03-31 00:00:00', '2016-03-31 04:00:00',
               '2016-03-31 08:00:00', '2016-03-31 12:00:00'],
              dtype='datetime64[ns]', freq=None)


text:
Q: How do I open the SearchView programmatically? There is this widget for the ActionBar which called 'SearchView'.
When it's not in use, it looks like this:

And when it's in use, it looks like this:

I want (programmatically of course) to open the searchview (make it "in use").
I tried several functions such as:
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    searchView.setOnQueryTextListener(this);

    searchView.performClick();
    searchView.requestFocus();

But none of those worked...
The SearchView in the XML:
<item android:id="@+id/menu_search"
      android:title="Search"
      android:icon="@drawable/ic_action_search"
      android:showAsAction="ifRoom|collapseActionView"
      android:actionViewClass="android.widget.SearchView" />

A: Try to call expandActionView() on MenuItem, not onActionViewExpanded() on ActionView.
It works for me.
MenuItem searchMenuItem = menu.findItem(R.id.menu_search);
searchView = (SearchView) searchMenuItem.getActionView();
searchMenuItem.expandActionView();

A: I know this is late but
Try calling expandActionView() to open it and collapseActionView() to close it. You can call requestFocus() on the actual Action View via getActionView() to give the search view focus :)

A: For androidx.appcompat.widget.SearchView,
searchView.setIconifiedByDefault(true)   // didn't work

searchMenuItem.expandActionView()  // didn't work

MenuItemCompat.expandActionView(searchMenuItem) // didn't work

searchView.onActionViewExpanded()  // didn't work

The following worked for me,
searchView.findViewById<View>(R.id.search_button).performClick()

A: Expand the SearchView with
searchView.setIconified(false);

and collapse it with
searchView.setIconified(true);

You need to change the value of android:showAsAction from ifRoom|collapseActionView to always. The SearchView's attribute android:iconifiedByDefault should be true, which is the default value, otherwise the user can not collapse the SearchView after it was expanded programmatically.

A: Expanding the answer of Matthias Robberts:
I wanted a list fragment to keep it's search value and set it after user returns from other fragment.
if (myViewModel.filterTextSaved.isNotEmpty()) { // Kotlin, storing state in ViewModel
    searchItem.expandActionView() // needs to come first, otherwise empty text
    theTextArea.setText(courseViewModel.filterTextOnClick)
}

and for the menu I keep always|collapseActionView, otherwise it stays open when user deletes the text.

A: If you want to use support library only when necessary, do this
    MenuItem searchMenuItem = menu.findItem(R.id.action_search);
    if (Utils.hasIceCreamSandwich())
        searchMenuItem.expandActionView();
    else MenuItemCompat.expandActionView(searchMenuItem);

else simply do this
    MenuItem searchMenuItem = menu.findItem(R.id.action_search);
    MenuItemCompat.expandActionView(searchMenuItem);

A: I was searching for a solution to expand SearchView programmatically
because I need to restore expand state. No one solution was worked for me.
Except using Handler().post(). I know it's not a good practice to use post().
But I'm working on legacy project and this workaround is acceptable for me.
Initialize variables block
val searchMenuItem = menu.findItem(R.id.menu_search_item)
val searchView = searchMenuItem.actionView as SearchView

How to expand SearchView:
Handler().post {
   searchMenuItem.expandActionView()
}

Reason why post() helps:
if your app is not well written it may doing too much work on UI thread.
post() ensures that your block of code will be executed when UI thread will be available for execution. Which means if you are using this workaround you can notice small delay between SearchView expanding

A: To open up a searchView keeping the close_button in the end use this in onCreate:-
searchView.findViewById(R.id.search_button).performClick();


text:
Q: How to send text to elements without id or value attribute using Selenium Java HTML:
<input type="text" placeholder="Enter name" class="form-control m-2">

I am trying to send text to this through Selenium.
This is what I tried:
driver.findElement(By.cssSelector("input.form-control m-2[placeholder='Enter name']")).sendKeys("Test");

A: form-control and m-2 are two different classes.
The selector should be input.form-control.m-2[placeholder='Enter name']

A: Use xpath to interact with the web Element.
The xpath will be -
//input[@placeholder='Enter name'][@type='text']

Use the following code -
WebElement inputName = driver.findElement(By.xpath("//input[@placeholder='Enter name'][@type='text']"));
inputName.sendKeys("Test");

A: To send a character sequence to the desired element with placeholder as Enter name you can use either of the following Locator Strategies:

*

*cssSelector:
driver.findElement(By.cssSelector("input[placeholder='Enter name']")).sendKeys("Test");

*xpath:
driver.findElement(By.xpath("//input[@placeholder='Enter name']")).sendKeys("Test");

Ideally, to send a character sequence within the <input> element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

*

*cssSelector:
new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[placeholder='Enter name']"))).sendKeys("Test");

*xpath:
new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@placeholder='Enter name']"))).sendKeys("Test");


text:
Q: Grid Layout in Sass Всем Доброго дня! Подскажите как применить правило Grid к всем child элементам в Sass
.grid *  { grid-column: md; }

A: Нашел ответ, чтобы применить правило ко всем child  элементам в сетке grid
к примеру такое правило будет работать в css
    .grid {
      display: grid;
      grid-template-columns:
      [xl-start] 1fr [md-start] minmax(0, 624px) [md-end] 1fr [xl-end]; }
    .grid *  { grid-column: md; }

в Sass придется писать так:
    .grid
      display: grid
      grid-template-columns: [xl-start] 1fr 1.5rem [md-start] minmax(0, 624px) [md- end] 1.5rem 1fr [xl-end]
      > *
      grid-column: md


text:
Q: Calling another observable during onComplete I have an api call which is a Completable. If Api call is success I have to clear some temp db values (don't do this if api call fails) For clearing temp values from db I have another Completable method. What I have done initially was something like this.
           apiCall()
                    .observeOn(Schedulers.io())
                    .doOnComplete(() -> clearTempDb())
                    .subscribeWith(new DisposableCompletableObserver() {
                        @Override
                        public void onComplete() {
                            Log.d(TAG, "onComplete: ");
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.e(TAG, "onError: " + e.getMessage());
                        }
                    });

        private Completable clearTempDb() {
            return Completable.fromAction(() -> {
                Log.d(TAG, "clear temp db started");
                Thread.sleep(2000);
                Log.d(TAG, "clear temp db completed");
            }).subscribeOn(Schedulers.io());
        }

        private Completable apiCall() {
            return Completable.fromAction(() -> Thread.sleep(2000)).subscribeOn(Schedulers.io());
        }

Then I realized that in doOnComplete calling just clearTempDb() wont work unless you subscribe to it.
So I changed it to
                     apiCall()
                    .observeOn(Schedulers.io())
                    .doOnComplete(() -> clearTempDb().subscribe())
                    .subscribeWith(new DisposableCompletableObserver() {
                        @Override
                        public void onComplete() {
                            Log.d(TAG, "onComplete: ");
                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.e(TAG, "onError: " + e.getMessage());
                        }
                    });

That works , but what happens is any error occurred in the clearTempDb would not be a part of the main stream and will not be passed to the actual subscribers onError
Then I made clearTempDb as a part of the main observable chain, like
apiCall().andThen(clearTempDb())

Now it is working as expected. But the issue is apiCall and clearTempDb have become sequential. which means after completing these 2 only onComplete will be called. But I don't want to wait till the clearTempDb to finish, to complete my main observable.
Again I went back to the doOnComplete with error ignored
             apiCall()
            .doOnComplete(()->clearTempDb().onErrorComplete().subscribe())
            .subscribeWith(new DisposableCompletableObserver() {
                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete: ");
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, "onError: " + e.getMessage());
                }
            });

Now its working fine but I don't know whether it is the proper solution or not. Because in many tutorials I have seen that doing any heavy task in the doOnNext, doOnComplete or such intermediate events are not recommended as it will be outside of your observable chain and its kind of interrupting an active observable chain. So how can I do it in the proper way?  Is apiCall().andThen(clearTempDb()) the recommended and only possible way?


text:
Q: eclipse mercurial plugin installation error I'm trying to install the eclipse mercurial plugin (with eclipse indigo), but I get an error during installation.
I went to help->install new software, then I wrote 'http://cbes.javaforge.com/update - http://cbes.javaforge.com/update' and then checked mercurialEclipse and clicked next. Then I unchecked Windows binaries for Mercurial (I'm on Linux) and clicked 'next'. Then 'next' again. Afterwards, there is a page resuming the license of the software. There are two licenses: "eclipse foundation software user agreement" and "eclipse public license v1.0". The radio button is set by default to "I do no accept the terms of the license", and if I switch it to "I accept the terms of the license agreements", both of the licenses are automatically set to "I accept the terms of the license agreements".
My problem is that, even after I click on "I accept the terms of the license agreements", the "next" button remains grey, and hence I can't proceed to the installation of my plugin.
Is that a bug ? Is there a work around ?
Thanks.

A: Could you try the update URL from the Google Code repository instead? If your next question is "Why do we have two update URLs?" there's another thread hereabouts that should help answer your question.


text:
Q: To maintain same format for data in a column while using it inside concatenation function I'm using formula in excel to generate sql statements. I have used format cells option to make sure all the data in Zip_Codes column have 5 digits. Unfortunately, retrieving cell data using Concatenation function doesn't provide the exact format. for example:
         A   |   B        |       C       |
|  1  | Zip   | City       | SQL Statement |
|-----|-------|------------|---------------|
|  2  | 00501 | Holtsville |=CONCATENATION("INSERT into @table1(Zip_Code, City) values ('",A2,"','",B2,"')") |
|-----|-------|------------|---------------|
|  3  | 00601 |Adjuntas    |=CONCATENATION("INSERT into @table1(Zip_Code, City) values ('",A3,"','",B3,"')")|

The SQL statement I'm getting is:
INSERT into @table 1 (Zip_Code, City) values ('501', 'Holtsville')
INSERT into @table 1 (Zip_Code, City) values ('601', 'Adjuntas')

The SQL statement should be something like this:
INSERT into @table 1 (Zip_Code, City) values ('00501', 'Holtsville')
INSERT into @table 1 (Zip_Code, City) values ('00601', 'Adjuntas')

I'm finding it difficult to get those leading zeros in the Zip_Code.

A: The number in column A have a custom format of 00000 but the actual value is only the three digit number.
So you need to include the formatting with TEXT()
Change ,A2, to:
,TEXT(A2,"00000"),

So the whole Formula:
=CONCATENATION("INSERT into @table1(Zip_Code, City) values ('",TEXT(A2,"00000"),"','",B2,"')")


text:
Q: Find truncation point for top 10% in density plot  I want to shade the region where top 10% are localized. I just arbitrary put truncation point 65, to just plot this plot. That is what I intend to find...for every data sets.
xf <- rnorm(40000, 50, 10);
plot(density(xf),xlim=c(0,100), main = paste(names(xf), "distribution"))
dens <- density(xf)
x1 <- min(which(dens$x >= 65)) # I want identify this point such that
# the shaded region includes top 10%

x2 <- max(which(dens$x <  max(dens$x)))
with(dens, polygon(x=c(x[c(x1,x1:x2,x2)]), y= c(0, y[x1:x2], 0), col="green"))
abline(v= mean(traitF2),  col = "black", lty = 1, lwd =2)

A: I think you are looking for the quantile() function:
xf <- rnorm(40000, 50, 10)
plot(density(xf),xlim=c(0,100), main = paste(names(xf), "distribution"))
dens <- density(xf)
x1 <- min(which(dens$x >= quantile(xf, .90))) # quantile() ftw!

x2 <- max(which(dens$x <  max(dens$x)))
with(dens, polygon(x=c(x[c(x1,x1:x2,x2)]), y= c(0, y[x1:x2], 0), col="green"))

A: You are looking for the quantiles.
http://en.wikipedia.org/wiki/Quantile


text:
Q: MSBuild : how to suppress the warning summary at the end of the build On a MSBuild Script, all errors and warnings are written twice :
- once they occured
- at the end of the build as a summary
I've heard it was possible to avoid the summary at the end of the build however I didn't find the option in the documentation.
Does everybody know this option ?
Thanks

A: You can use the /consoleloggerparameters:NoSummary or /fileloggerparameters:NoSummary options.
See msbuild /? for more information / detail.


text:
Q: Get number of rows updated by Laravel DB Transaction I carry out DB transaction like this:
DB::beginTransaction();
try
{
    foreach ($updates as $column_name => $new_value) {
        DB::table('my_table')
            ->where('id', '=', $line_id)
            ->update(array($column_name => $new_value));
    }
    DB::commit();
    return Response::make('Updated', 200);
}
catch (Exception $ex)
{
    DB::rollback();
    return Response::make('Error - '. $ex->getMessage(), 500);
}

Is it possible to get the number of rows affected/updated when I carry out the DB::commit(); and return it in my response?
EDIT
The $updates contains key = value array (where the key is the column name).
If an update like this occurs: UPDATE some_table SET some_number = some_number WHERE id = 1 the resulting affected row count will be 0 (i.e. nothing really changed).
However, if an update like this occurs: UPDATE some_table SET some_number = some_number + 1 WHERE id = 1 for example, then this will result in affected row count of 1.
This is what I am trying to determine in my code, once the transaction is committed, has any values been really updated.

A: NEW
You could update only if the value is different from the past one:
$count = DB::table('my_table')
  ->where('id', '=', $line_id)
  ->where($column_name, '!=', $new_value)
  ->count();

In this way you can say if the given row has a different value and if you are going to change it.
OLD
A count before the query:
$number = DB::table('my_table')
  ->where('id', '=', $line_id)
  ->count();

Return in the response:
return Response::make('Updated ' . $number, 200);


text:
Q: UrlFetchApp request fails in Menu Functions but not in Custom Functions (connecting to external REST API) I am using the following function to connect to an external API (Binance) using a Google Apps Script to retrieve a JSON array (of market prices). This simple query url works fine in a browser (no need for API keys):
function getMyArray() {
  var url ="https://api.binance.com/api/v3/ticker/price"; // works perfectly in browser
  var params =  {"method"  : "get",  "muteHttpExceptions":true };
  var response = UrlFetchApp.fetch(url, params);
  var array = JSON.parse(response.getContentText());

  return array;
}

However it's a different story when I try to run the function in Google Apps Script:

*

*Script Editor: easy and practical to run within the script editor, but I get a 403 error "Request blocked"

*Menu function: call the function from a menu item added to spreadsheet UI => same 403 error

*Custom function: edit any cell and type =getMyArray() => request works and I can trace the array using Logger

Why is my simple request getting blocked when called from Menu or Script Editor, and is it possile to change that? Thanks

A: When UrlFetchApp is used by the custom function and the script editor, I think that the difference is whether IPv6 is used, while the address of IPv4 is changed every run. In this case, the results of the script editor and custom menu are the same. I thought that this might be the reason of your issue. But I'm not sure whether my guess is the correct. So, in this answer, I would like to propose the following workaround.

*

*Put the formula =getMyArray() to a cell using the script.

*

*By this, the value is retrieved to the cell.

*Retrieve the values from the cell using the script.

*Clear the put formula.

By this flow, I think that your goal can be achieved.
The sample script is as follows.
Sample script:
In this script, as a test, =getMyArray() is put to the cell "A1" on the active sheet and the value is retrieved from the cell. When you use this, please run the function main() at the script editor and custom menu. By this, the value can be retrieved to array.
function getMyArray() {
  var url = "https://api.binance.com/api/v3/ticker/price";
  var params =  {"method": "get", "muteHttpExceptions": true};
  var response = UrlFetchApp.fetch(url, params);
  return response.getContentText();
}

// Please run this function by the script editor and the custom menu.
function main() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange("A1");
  range.setFormula("=getMyArray()");
  SpreadsheetApp.flush();
  var value = range.getValue();
  range.clearContent();
  var array = JSON.parse(value);
  console.log(array)
}

References:

*

*Custom Functions in Google Sheets

*setFormula()

*flush()
Added:
The response value from https://httpbin.org/get is as follows.
Sample script for testing this:
function sample() {
  var url = "https://httpbin.org/get";
  var res = UrlFetchApp.fetch(url);
  console.log(res.getContentText())
  return res.getContentText();
}

Result:
Pattern 1. Script is run with the script editor.
{
  "args": {},
  "headers": {
    "Accept-Encoding": "gzip,deflate,br",
    "Host": "httpbin.org",
    "User-Agent": "Mozilla/5.0 (compatible; Google-Apps-Script; beanserver; +https://script.google.com; id: ###)",
    "X-Amzn-Trace-Id": "Root=###"
  },
  "origin": "### IPV6 ###, ### IPV4 ###", // or "### IPV4 ###, ### IPV4 ###"
  "url": "https://httpbin.org/get"
}

*

*When you are using IPV6, origin is "### IPV6 ###, ### IPV4 ###". But when you are using IPV4, origin is "### IPV4 ###, ### IPV4 ###".

*In this case, the correct value cannot be retrieved from https://api.binance.com/api/v3/ticker/price.

Pattern 2. Script is run with the custom function.
In this case, =sample() is put to a cell and the value is retrieved.
{
  "args": {},
  "headers": {
    "Accept-Encoding": "gzip,deflate,br",
    "Host": "httpbin.org",
    "User-Agent": "Mozilla/5.0 (compatible; Google-Apps-Script; beanserver; +https://script.google.com; id: ###)",
    "X-Amzn-Trace-Id": "Root=###"
  },
  "origin": "### IPV4 ###",
  "url": "https://httpbin.org/get"
}

*

*In this case, the correct value can be retrieved from https://api.binance.com/api/v3/ticker/price.

Pattern 3. Script is run with the OnEdit event trigger.
When UrlFetchApp is used with the custom function, no authorization is required. But when UrlFetchApp is used with the OnEdit event trigger, the installable trigger is required by authorizing. I thought that this authorization might occur this issue. So I compared this.
When UrlFetchApp is used with the installable OnEdit event trigger, the following result is retrieved.
{
  "args": {},
  "headers": {
    "Accept-Encoding": "gzip,deflate,br",
    "Host": "httpbin.org",
    "User-Agent": "Mozilla/5.0 (compatible; Google-Apps-Script; beanserver; +https://script.google.com; id: ###)",
    "X-Amzn-Trace-Id": "Root=###"
  },
  "origin": "### IPV4 ###",
  "url": "https://httpbin.org/get"
}

*

*This result is the same with above pattern 2.

*In this case, the correct value can be retrieved from https://api.binance.com/api/v3/ticker/price.

Result:

*

*The headers including User-Agent are the same for all patterns.

*From pattern 2 and 3, it is not related to the authorization for Google side.

*When WHOIS with IPV4 is retrieved, the same result is returned.

*

*When origin is "### IPV4 ###, ### IPV4 ###", 2nd IPV4 is the Google's IP address.

From above results, the different of all patterns is whether the value of origin is 1 or 2.


text:
Q: Android location only works on WiFi I'm having a problem trying to get locations in a Geocatching app on Android.
For some devices my app caches all the locations and for others devices only get locations on WiFi network. Despite on this, I checked on https://maps.google.com/locationhistory and Google got all locations.
I want to get data from both, mobile and WiFi. Is there anything I'm doing wrong? How can I make it work in all devices?
I'm using ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permissions btw.
This is an example the device that works ok, it collects mobile data as it follows the correct path:

And this, an example of the device that only works on WiFi. It links three points where I had WiFi connection.

Thanks in advance for your time!
EDIT: More info.
I get correct behaviour with HTC One, Android 4.2.2 and Nexus 5, Android 6.0.
With Sony Xperia Z3, Android 5.1.1 I only get locations when connected to WiFi.


text:
Q: Entering the Change Password Custom Policy as an Authenticated User When redirecting the user into a Custom Policy Change Password policy/flow, as shown in the linked documentation below.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-password-change-policy?pivots=b2c-custom-policy
Is there a way to pass the user across without using cookies?  I.e. our user's access token is stored in browser session storage and therefore isn't automatically presented to the policy/flow.  We need a way of passing the token across to the policy/flow.

A: B2C has built in session management that I would take advantage of, but if you don't want to do that, you can attempt to use the id token hint query string parameter. You pass your token to the policy via that query parameter, and then you add a step to your policy that validates the token and any data that's important to you. Here is a link to the docs: https://learn.microsoft.com/en-us/azure/active-directory-b2c/id-token-hint


text:
Q: Show part of an image How can I show a part of the image using jQuery or another JavaScript technique?
Example:
image:
[                ]
[     --------   ]
[     -      -   ]
[     - part -   ]
[     -      -   ]
[     --------   ]
[                ]

A: You can use a div with fixed size and place the image absolutely positioned inside. You can then use javascript to change the top / left / right / bottom position of the image to move it.

...

EDIT: that's if you want to move the image over time... Otherwise simply use CSS

A: Manipulate the CSS property background, like this:
#imgDiv {
    background-image: url(image.jpg);
    background-position: 10px 50px; /* Visible coordinates in image */
    height: 200px; /* Visible height */
    width: 200px; /* Visible width */
}

Here's how to .animate the visible part: http://jsfiddle.net/wGpk9/2/

A: Ivan's example works if you add style overflow:hidden to the div like so..

...


text:
Q: Trap message/exception in jquery to ELMAH In my MVC3 application, I am returning messages from my stored procs. If it is 'successful', I'm moving forward else displaying a custom error page.
When the message is something else, I want to trap it in ELMAH. The problem that I am facing is that the return message is not really an error so I'm not able to figure out how to handle it. I still want to display the custom error page after catching the error in ELMAH.
Please help.
$.ajax({
        url: "../XYZ",
        type: 'POST',
        dataType: 'text',
        async: false,
        data: JSON.stringify({ abcData: abcData, strDeb: strDeb, strCre: strCre }),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (logout != "Logout") {
                if (data.toLowerCase() != "successful") {
                    **//alert(data.toString());
                    window.location.href = "../Error";**
                } else {
                    window.location.href = "../ABC";
                }
            }
        },
        error: function () {
            var sessionWindowElement = $('#SessionLayoutLogOutWindow');
            sessionWindowElement.data('tWindow').center().open();
        }
    });


text:
Q: Why does a view with 600dp width take up all of my Nexus 5's landscape width? I am specifying a button's width as 600dp in values/dimens.xml, but when I deploy and run it on my Nexus 5 it takes up all the available width in the landscape orientation.
My activity only runs in landscape mode, as I have specified in manifest file. The layouts are in the layouts directory. The images are in the 'drawable-xxhdpi' directory and they appear fine, but everything that I specify in dp is magnified.
The previews in Android Studio and the actual device seem to behave as they have 600dp max width when it should be 1920. Why is this, and how can I fix it?

A: The physical width of the display on a landscape Nexus 5 is 1920 pixels, However, 600dp != 600px. The Nexus 5 has a display density of ~445 ppi. A dp is pixels only at medium density (160 ppi). Thus, everything specified in dp will be scaled by a factor of about 445/160 = 2.78125. So 600dp is actually about 1669 pixels. That should account for most of what you're seeing.
There may also be something about your layout that is stretching the button. If you post your layout xml, we might be able to provide more info.


text:
Q: Pull the list of Countries in Microsoft AD using Powershell I need to pull the list of all the countries present in the Drop Down in Microsoft AD using powershell. Please help.

A: I think this is just the built-in list of countries recognised by Windows.  One way to get them is like this:
[CultureInfo]::GetCultures([System.Globalization.CultureTypes]::SpecificCultures) |
    ForEach-Object {
        (New-Object System.Globalization.RegionInfo $_.Name).EnglishName
    } | Select-Object -Unique | Sort-Object

I have a feeling there may be a simpler way, but this works, and gives a list like this:
Afghanistan
Åland Islands
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
Antigua and Barbuda
Argentina
Armenia
Aruba
Australia
Austria
Azerbaijan
...


text:
Q: golang proper http2 request I want to make an http/2 request in go and got to a few issues there.
How to make proper http/2 requests in go?
Error: Get "https://webhook.site/aae1e0ab-3e48-49c8-8cd0-526e12ee4077": http2: unexpected ALPN protocol ""; want "h2" (Why? Other sites are working)
Code:
t := &http2.Transport{}
    c := &http.Client{
        Transport: t,
    }

        r, err := http.NewRequest("GET", "https://webhook.site/aae1e0ab-3e48-49c8-8cd0-526e12ee4077", nil)
        if err != nil {
            fmt.Println(err)
        }
        r.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.2 Safari/605.1.15")
        r.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")

        resp, err := c.Do(r)
        if err != nil {
            fmt.Println(err)
        }
        defer resp.Body.Close()

        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            fmt.Println(err)
        }
        fmt.Println(string(body))
    ```

A: As was mentioned, that server doesn't support HTTP2:
PS C:\> curl.exe -I --http2-prior-knowledge https://webhook.site
curl: (16) Error in the HTTP2 framing layer

Contrast with one that does:
PS C:\> curl.exe -I --http2-prior-knowledge https://example.com
HTTP/2 200

https://curl.se/docs/manpage.html#--http2-prior-knowledge


text:
Q: Keep owners of files from tar file after un-archiving in Gradle task I have a tar.gz file, which is created with the command:
tar -czvpf file.tar.gz my_directory
So files' permissions and owners should be saved there.
If I call un-tar command line directly in the terminal (under the root), files' permissions and owners are okay:
tar --same-owner -xvf file.tar -C /target/directory

^ this produces correct results in un-archived folders structure.
I also have a Gradle task which is supposed to un-tar this file to a destination folder:
task unTarPredefinedProjectTree(type:Exec) {
    workingDir envDumpDir
    commandLine ('tar --same-owner -xvf file.tar.gz -C /target/directory')
}

The problem is: when I call gradle task from the same terminal:
gradle unTarPredefinedProjectTree

All files' owners get reset to root.
I tried putting command line arguments separately:
commandLine ('tar', '--same-owner', '-xvf', 'file.tar.gz', '-C', '/target/directory')

And tried using tarTree function:
task unTarPredefinedProjectTree << {
    copy {
        from tarTree(file('file.tar.gz'))
        into '/target/directory'
    }
}

Still the same: 'root' owner after using Gradle task, but correct owners after calling the command manually in the terminal. The same terminal's window and I'm under the root user in both cases.
So how to force Gradle to keep tar file's owners?
Thanks in advance.


text:
Q: How Do I Use Multiple po Files in CakePHP? I'm just beginning the process of exploring i18n in CakePHP and I can't seem to find the right combination of files and functions that will allow me to use multiple po files. If I want to use a single po file (default.po) for every bit of translatable text, that works fine, but I see that becoming an unmaintainable hairball very, very quickly. I've read the docs and the few articles I can find, but none really dive into i18n beyond the trivial use of one .po file.
Here's where I am right now:

*

*I've "baked" my po templates (.pot files) and copied those into app/locale/eng/LC_MESSAGES (I'm not going to be using the default text as the key so that I can easily spot missing keys). For now, I have -views-layouts-default.po and -views-pages-index.po.

*In those .po files, I've entered the text I want to use for each key.

*In my homepage (views/pages/index.ctp) and default layout (views/layouts/default.ctp) I've wrapped the text key I want to translate with the __() function.

When I load the homepage, though, all I see are they keys. No text has been translated. If I throw up a default.po file, though, any keys I drop in there are populated just fine. I'm clearly missing some piece of the puzzle, but I can't find it. Any help would be much appreciated.
Thanks.

A: I found the piece I was missing thanks to the CakePHP Google Group. I had been playing with the __d() convenience function, but didn't have a clear picture of how to tie it together to my .po files. The answer is easy once you know it:
The domain translation:
__d ( 'login', 'PLEASE_LOGIN' );
Will look for the "PLEASE_LOGIN" key in the file named login.po.  I didn't know (and hadn't read anywhere) that domain == po file name (without extension). Learning that made all the difference.


text:
Q: Calculate array length (sizeof str / sizeof (char)) won't work The function getStringEnd() doesn't work correctly but I don't know why. The function does not return the correct value of the string end. I already found out that the variable max is not calculated right.
But
int max = sizeof str / sizeof (char);
should work, shouldn't it?
Do you have any ideas?
#include <stdio.h>
#define MAX_FIGURES 30

int getStringEnd(const char * str);

int getStringEnd(const char * str)
{
    int max = sizeof str / sizeof (char);

    int counter = 0;
    while (counter <= max -1)
    {
        if ((str[counter] == '\0') || (str[counter] == '\n')) return counter;
        counter += 1;
    }
    return 0;
}

int main(void)
{
    char figures[MAX_FIGURES];
    for (int i = 0; i <= MAX_FIGURES - 1; i++) figures[i] = '\0';

    fgets(figures, MAX_FIGURES, stdin);

    int stringEnd = getStringEnd(&figures);
}

A: In getStringEnd() function, str is a const char *, nothing else. sizeof operator gives back the size of the datatype, not the amount of memory pointed  by the variable.
You need to use strlen() to get the length of the string. You need to write something like
int max = strlen(str); // sizeof(char) == 1, fixed, can be ommitted

Note: FWIW, Remember, strlen() does not take into account the terminating null.


text:
Q: AngularJS : Detect form changes I'm developing an angular app, where I have to check the form changes, and perform some operation depending upon the changes. I know, this can be achieved using $scope.watch but that would cost me performance.
What I'm trying to achieve
I've a pre-populated form and I will take the form data as a reference using angular.copy() and compare with original data.
I had also tried $parsers to check, but failed. So, is there any way to accomplish this?

A: You can use ng-change.
From the docs - "Evaluate the given expression when the user changes the input. The expression is evaluated immediately, unlike the JavaScript onchange event which only triggers at the end of a change (usually, when the user leaves the form element or presses the return key)."
 Difference between ng-change and $watch

A: Did you try with ng-change ? It call a function when value of ng-model change
<input type="search"  ng-change="changeValue()"  ng-model="test" name="test"/>

If you want to know wich field call the function you can add the name as string parameter
<input type="search"  ng-change="changeValue('field1')"  ng-model="field1" name="field1"/>

In the controller don't forget to put the function changeValue in the scope
 $scope.changeValue = function(fieldname){
    switch (fieldname){
        case 'field1' : .... break;
        case 'field2' : .... break;
        case 'field3' : .... break;
        ...
    }
 }

A: When you compare the copied object against the original form data, and you want to check for changes, you can use angular.equals.
 angular.equals(formObj, formObjCopy)

This will do a deep compare of the object and its nested sub-properties, and return true if the object hasn't changed.


text:
Q: Cost of a moving garbage collector Moving garbage collectors, such as generational collectors, incur extra generated code to store and reload references across GC safe points. Has anyone quantified the performance cost of this overhead compared to a non-moving collector?
I ask because I am interested in designing a collector that can recycle short-lived values efficiently without having to move them.

A: The moving vs. non-moving tradeoff is a complex one.  I'm not aware of any particular studies of the aspect you mention - indeed, I'm not sure I understand it completely: an accurate GC always needs to know where all the pointers are, so perhaps you're talking about conservative non-moving GC?  Conservative GC in my opinion is a bad choice if you have enough control over the compilation path to be able to do accurate GC.
The other aspects affecting performance of moving vs. non-moving GC are:

*

*Allocation speed.  Non-moving GC might have to allocate from a free list, whereas coying GC can use bump-pointer allocation.  Hybrid schemes like Immix attempt to strike a better tradeoff between the two.

*Locality and cache behaviour.  There are lots of studies on this for both moving and non-moving GC; see the GC Bibliography.  Generally speaking compaction is good for the cache, although copying GC is typically breadth-first which is a bad choice (access patterns tend to be depth-first) so there's a bunch of research in this area trying to rearrange objects to match the access pattern.
My own personal opinion is that to support really fast allocation you need an L2-sized nursery with copying collection and bump-pointer allocation.  If you do anything else, allocation becomes more expensive which skews lots of things: optimising to reduce allocations becomes more important, so you end up spending effort there and making things more complex.  I'd rather make allocation really really cheap and then not worry about it.


text:
Q: How to open fancybox containing .html files from jquery UI tabs navigation I have a set of jquery tabs for top navigation (tabs are just text links, not "graphical" tabs).  When you click a link, I want a fancybox to open containing an external html file.  This is not happening.  No fancy box is launching.  Below is my code.  Could you guys/gals let me know what I am doing wrong and how to fix? I'm having trouble figuring it out. Thanks.
Scripts:
<link rel="stylesheet" href="../css/jquery.fancybox.css" type="text/css"  />

HTML:

               Addition

               Subtraction

lessons/addition1.html code for fancybox:
<!DOCTYPE HTML>

<meta charset="utf-8">
<title>Just try it!</title>

If you have 14 apples, Justin has 12 and Mary gives you 7 more apples, but only gives Justin 3 apples, how many apples would you and Justin have altogether?

<form>
<input type="radio" name="apples" />24
<input type="radio" name="apples" />42
<input type="radio" name="apples" />36
<input type="radio" name="apples" />16
<input type="submit" value="Answer" />
</form>

lessons/subtraction1.html code for fancybox:
    <!DOCTYPE HTML>

    <meta charset="utf-8">
    <title>Just try it!</title>

Jamie has 38 lives left in play for his new video game.
        He loses 6 lives on level Nine and 5 lives on level Twelve.
        He hasn't gained anymore lives until level Twenty, where he gets 4 more,
        but loses 1 life in play.  How many lives does Jamie have left in play?

        <form>
            <input type="radio" name="apples"  />26
            <input type="radio" name="apples" />30
            <input type="radio" name="apples" />22
            <input type="radio" name="apples" />16
            <input type="submit" value="Answer" class="blkstyle"/>
        </form>


text:
Q: What is object slicing? In c++ what is object slicing and when does it occur?

A: "Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away.
For example,
class A {
   int foo;
};

class B : public A {
   int bar;
};

So an object of type B has two data members, foo and bar.
Then if you were to write this:
B b;

A a = b;

Then the information in b about member bar is lost in a.

A: So ... Why is losing the derived information bad? ... because the author of the derived class may have changed the representation such that slicing off the extra information changes the value being represented by the object.  This can happen if the derived class if used to cache a representation that is more efficient for certain operations, but expensive to transform back to the base representation.
Also thought someone should also mention what you should do to avoid slicing...
Get a copy of C++ Coding Standards, 101 rules guidlines, and best practices.  Dealing with slicing is #54.
It suggests a somewhat sophisticated pattern to fully deal with the issue:  have a protected copy constructor, a protected pure virtual DoClone, and a public Clone with an assert which will tell you if a (further) derived class failed to implement DoClone correctly.  (The Clone method makes a proper deep copy of the polymorphic object.)
You can also mark the copy constructor on the base explicit which allows for explicit slicing if it is desired.

A: The slicing problem in C++ arises from the value semantics of its objects, which remained mostly due to compatibility with C structs. You need to use explicit reference or pointer syntax to achieve "normal" object behavior found in most other languages that do objects, i.e., objects are always passed around by reference.
The short answers is that you slice the object by assigning a derived object to a base object by value, i.e. the remaining object is only a part of the derived object. In order to preserve value semantics, slicing is a reasonable behavior and has its relatively rare uses, which doesn't exist in most other languages. Some people consider it a feature of C++, while many considered it one of the quirks/misfeatures of C++.

A: Most answers here fail to explain what the actual problem with slicing is. They only explain the benign cases of slicing, not the treacherous ones. Assume, like the other answers, that you're dealing with two classes A and B, where B derives (publicly) from A.
In this situation, C++ lets you pass an instance of B to  A's assignment operator (and also to the copy constructor). This works because an instance of B can be converted to a const A&, which is what assignment operators and copy-constructors expect their arguments to be.
The benign case
B b;
A a = b;

Nothing bad happens there - you asked for an instance of A which is a copy of B, and that's exactly what you get. Sure, a won't contain some of b's members, but how should it? It's an A, after all, not a B, so it hasn't even heard about these members, let alone would be able to store them.
The treacherous case
B b1;
B b2;
A& a_ref = b2;
a_ref = b1;
//b2 now contains a mixture of b1 and b2!

You might think that b2 will be a copy of b1 afterward. But, alas, it's not! If you inspect it, you'll discover that b2 is a Frankensteinian creature, made from some chunks of b1 (the chunks that B inherits from A), and some chunks of b2 (the chunks that only B contains). Ouch!
What happened? Well, C++ by default doesn't treat assignment operators as virtual. Thus, the line a_ref = b1 will call the assignment operator of A, not that of B. This is because, for non-virtual functions, the declared (formally: static) type (which is A&) determines which function is called, as opposed to the actual (formally: dynamic) type (which would be B, since a_ref references an instance of B). Now, A's assignment operator obviously knows only about the members declared in A, so it will copy only those, leaving the members added in B unchanged.
A solution
Assigning only to parts of an object usually makes little sense, yet C++, unfortunately, provides no built-in way to forbid this. You can, however, roll your own. The first step is making the assignment operator virtual. This will guarantee that it's always the actual type's assignment operator which is called, not the declared type's. The second step is to use dynamic_cast to verify that the assigned object has a compatible type. The third step is to do the actual assignment in a (protected!) member assign(), since B's assign() will probably want to use A's assign() to copy A's, members.
class A {
public:
  virtual A& operator= (const A& a) {
    assign(a);
    return *this;
  }

protected:
  void assign(const A& a) {
    // copy members of A from a to this
  }
};

class B : public A {
public:
  virtual B& operator= (const A& a) {
    if (const B* b = dynamic_cast<const B*>(&a))
      assign(*b);
    else
      throw bad_assignment();
    return *this;
  }

protected:
  void assign(const B& b) {
    A::assign(b); // Let A's assign() copy members of A from b to this
    // copy members of B from b to this
  }
};

Note that, for pure convenience, B's operator= covariantly overrides the return type, since it knows that it's returning an instance of B.

A: These are all good answers. I would just like to add an execution example when passing objects by value vs by reference:
#include <iostream>

using namespace std;

// Base class
class A {
public:
    A() {}
    A(const A& a) {
        cout << "'A' copy constructor" << endl;
    }
    virtual void run() const { cout << "I am an 'A'" << endl; }
};

// Derived class
class B: public A {
public:
    B():A() {}
    B(const B& a):A(a) {
        cout << "'B' copy constructor" << endl;
    }
    virtual void run() const { cout << "I am a 'B'" << endl; }
};

void g(const A & a) {
    a.run();
}

void h(const A a) {
    a.run();
}

int main() {
    cout << "Call by reference" << endl;
    g(B());
    cout << endl << "Call by copy" << endl;
    h(B());
}

The output is:
Call by reference
I am a 'B'

Call by copy
'A' copy constructor
I am an 'A'

A: 1. THE DEFINITION OF SLICING PROBLEM
If D is a derived class of the base class B, then you can assign an object of type Derived to a variable (or parameter) of type Base.
EXAMPLE
class Pet
{
 public:
    string name;
};
class Dog : public Pet
{
public:
    string breed;
};

int main()
{
    Dog dog;
    Pet pet;

    dog.name = "Tommy";
    dog.breed = "Kangal Dog";
    pet = dog;
    cout << pet.breed; //ERROR

Although the above assignment is allowed, the value that is assigned to the variable pet loses its breed field. This is called the slicing problem.
2. HOW TO FIX THE SLICING PROBLEM
To defeat the problem, we use pointers to dynamic variables.
EXAMPLE
Pet *ptrP;
Dog *ptrD;
ptrD = new Dog;
ptrD->name = "Tommy";
ptrD->breed = "Kangal Dog";
ptrP = ptrD;
cout << ((Dog *)ptrP)->breed;

In this case, none of the data members or member functions of the dynamic variable
being pointed to by ptrD (descendant class object) will be lost. In addition,  if you need to use functions, the function must be a virtual function.

A: It seems to me, that slicing isn't so much a problem other than when your own classes and program are poorly architected/designed.
If I pass a subclass object in as a parameter to a method, which takes a parameter of type superclass, I should certainly be aware of that and know the internally, the called method will be working with the superclass (aka baseclass) object only.
It seems to me only the unreasonable expectation that providing a subclass where a baseclass is requested, would somehow result in subclass specific results, would cause slicing to be a problem.  Its either poor design in the use of the method or a poor subclass implementation.  I'm guessing its usually the result of sacrificing good OOP design in favor of expediency or performance gains.

A: OK, I'll give it a try after reading many posts explaining object slicing but not how it becomes problematic.
The vicious scenario that can result in memory corruption is the following:

*

*Class provides (accidentally, possibly compiler-generated) assignment on a polymorphic base class.

*Client copies and slices an instance of a derived class.

*Client calls a virtual member function that accesses the sliced-off state.

A: Third match in google for "C++ slicing" gives me this Wikipedia article http://en.wikipedia.org/wiki/Object_slicing and this (heated, but the first few posts define the problem) : http://bytes.com/forum/thread163565.html
So it's when you assign an object of a subclass to the super class. The superclass knows nothing of the additional information in the subclass, and hasn't got room to store it, so the additional information gets "sliced off".
If those links don't give enough info for a "good answer" please edit your question to let us know what more you're looking for.

A: The slicing problem is serious because it can result in memory corruption, and it is very difficult to guarantee a program does not suffer from it. To design it out of the language, classes that support inheritance should be accessible by reference only (not by value). The D programming language has this property.
Consider class A, and class B derived from A. Memory corruption can happen if the A part has a pointer p, and a B instance that points p to B's additional data. Then, when the additional data gets sliced off, p is pointing to garbage.

A: Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object.
Explanation:
Consider the following class declaration:
           class baseclass
          {
                 ...
                 baseclass & operator =(const baseclass&);
                 baseclass(const baseclass&);
          }
          void function( )
          {
                baseclass obj1=m;
                obj1=m;
          }

As baseclass copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing.

A: If You have a base class A and a derived class B, then You can do the following.
void wantAnA(A myA)
{
   // work with myA
}

B derived;
// work with the object "derived"
wantAnA(derived);

Now the method wantAnA needs a copy of derived. However, the object derived cannot be copied completely, as the class B could invent additional member variables which are not in its base class A.
Therefore, to call wantAnA, the compiler will "slice off" all additional members of the derived class. The result might be an object you did not want to create, because

*

*it may be incomplete,

*it behaves like an A-object (all special behaviour of the class B is lost).

A: In C++, a derived class object can be assigned to a base class object, but the other way is not possible.
class Base { int x, y; };

class Derived : public Base { int z, w; };

int main()
{
    Derived d;
    Base b = d; // Object Slicing,  z and w of d are sliced off
}

Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object.

A: I see all the answers mention when object slicing happens when data members are sliced. Here I give an example that the methods are not overridden:
class A{
public:
    virtual void Say(){
        std::cout<<"I am A"<<std::endl;
    }
};

class B: public A{
public:
    void Say() override{
        std::cout<<"I am B"<<std::endl;
    }
};

int main(){
   B b;
   A a1;
   A a2=b;

   b.Say(); // I am B
   a1.Say(); // I am A
   a2.Say(); // I am A   why???
}

B (object b) is derived from A (object a1 and a2). b and a1, as we expect, call their member function. But from polymorphism viewpoint we don't expect a2, which is assigned by b, to not be overridden. Basically, a2 only saves A-class part of b and that is object slicing in C++.
To solve this problem, a reference or pointer should be used
 A& a2=b;
 a2.Say(); // I am B

or
A* a2 = &b;
a2->Say(); // I am B

A: class A
{
    int x;
};

class B
{
    B( ) : x(1), c('a') { }
    int x;
    char c;
};

int main( )
{
    A a;
    B b;
    a = b;     // b.c == 'a' is "sliced" off
    return 0;
}

A: I just ran across the slicing problem and promptly landed here. So let me add my two cents to this.
Let's have an example from "production code" (or something that comes kind of close):

Let's say we have something that dispatches actions. A control center UI for example.
This UI needs to get a list of things that are currently able to be dispatched. So we define a class that contains the dispatch-information. Let's call it Action. So an Action has some member variables. For simplicity we just have 2, being a std::string name and a std::function<void()> f. Then it has an void activate() which just executes the f member.
So the UI gets a std::vector<Action> supplied. Imagine some functions like:
void push_back(Action toAdd);

Now we have established how it looks from the UI's perspective. No problem so far. But some other guy who works on this project suddenly decides that there are specialized actions that need more information in the Action object. For what reason ever. That could also be solved with lambda captures.  This example is not taken 1-1 from the code.
So the guy derives from Action to add his own flavour.
He passes an instance of his home-brewed class to the push_back but then the program goes haywire.
So what happened?
As you might have guessed: the object has been sliced.
The extra information from the instance has been lost, and f is now prone to undefined behaviour.

I hope this example brings light about for those people who can't really imagine things when talking about As and Bs being derived in some manner.

A: when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off (discard)  form the base class object.
class Base {
int x;
 };

class Derived : public Base {
 int z;
 };

 int main()
{
Derived d;
Base b = d; // Object Slicing,  z of d is sliced off
}

A: When a Derived class Object is assigned to Base class Object, all the members of derived class object is copied to base class object except the members which are not present in the base class. These members are Sliced away by the compiler.
This is called Object Slicing.
Here is an Example:
#include<bits/stdc++.h>
using namespace std;
class Base
{
    public:
        int a;
        int b;
        int c;
        Base()
        {
            a=10;
            b=20;
            c=30;
        }
};
class Derived : public Base
{
    public:
        int d;
        int e;
        Derived()
        {
            d=40;
            e=50;
        }
};
int main()
{
    Derived d;
    cout<<d.a<<"\n";
    cout<<d.b<<"\n";
    cout<<d.c<<"\n";
    cout<<d.d<<"\n";
    cout<<d.e<<"\n";

    Base b = d;
    cout<<b.a<<"\n";
    cout<<b.b<<"\n";
    cout<<b.c<<"\n";
    cout<<b.d<<"\n";
    cout<<b.e<<"\n";
    return 0;
}

It will generate:
[Error] 'class Base' has no member named 'd'
[Error] 'class Base' has no member named 'e'


text:
Q: manage maven different cglib/asm versions I have a multi-module project in maven, that uses (amongst others) glassfish-jersey, jersey-moxy, wicket-ioc, lucene and lamdbaj These all come with asm, but all with different versions.
Lately, I run into a lot of trouble when running my tests. Typical error I get is:
java.lang.VerifyError: class net.sf.cglib.core.DebuggingClassWriter overrides final method visit.(IILjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V

I read that this can be caused by different asm versions. Is there a way to 'sandbox' these different asm-versions in their dependencies, so they don't get mixed up?
Edit:
My current solution is to use jarjar, like this:
  <build>
    <plugins>
       <plugin>
        <groupId>org.sonatype.plugins</groupId>
        <artifactId>jarjar-maven-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>jarjar</goal>
            </goals>
            <configuration>
              <includes>
                <include>cglib:cglib-nodep</include>
              </includes>
              <rules>
                <rule>
                  <pattern>net.sf.cglib.asm.**</pattern>
                  <result>com.myproject.lambda4j.asm.@1</result>
                </rule>
                <rule>
                  <pattern>net.sf.cglib.**</pattern>
                  <result>com.myproject.lambda4j.cglib.@1</result>
                </rule>
              </rules>
            </configuration>
          </execution>
        </executions>
      </plugin>

A: Try explicitly adding some cglib v3.* on your class path which uses a recent version of ASM. The problem that you encounter is that cglib modifies the behavior of the ASM class writer by inheritance rather then by delegation. However, ASM enforced this latter best practice by making its ClassWriter's methods final from any version 4.* while it was still possible to override its methods in version 3. The error you encounter is a result of combining cglib 2.* with ASM 4.*.
Fortunately (for you), cglib has been rather static in its last versions, i.e. there were only minor API changes while the newer versions mostly consisted of updates of ASM. If you are lucky, this explicit use of cglib v3.* therefore solves your problem. This holds as long as none of your project dependencies has a direct dependency on ASM what seems reasonable for the dependencies you named like Jersey or Lucene.
If this does not work, you need to recompile some of your dependencies while using a tool like jarjar in order to repack the direct ASM dependencies into different name spaces in order to resolve these version conflicts. An alternative could be to isolate different ASM versions by some conditional child-first ClassLoader magic but this is not so recommendable since the effects are unpredictable and will also result in a performance penalty.


text:
Q: Create COM API, or similar, for Node.js app I have written an application in JavaScript that runs on node.js.
Is it possible to create a COM API, or similar, for a Node.js application?
For example, in C, C++, C#, etc, you can write an application, and then have another application, written in a different programming language, interact with your code via the COM API.
I want to be able to do this for my JavaScript application. So that I could interact with it from another programming language. Is this possible?

A: Calling javascript from an outside process is not part of the javascript specification standard.  As such, it is specific to a given javascript implementation.  node.js uses Google's V8 javascript engine and the embedding interface to that engine from a language like C++ is here: https://developers.google.com/v8/embed.
It does not use COM.  I believe there are some other JS engines that might offer a COM interface on Windows.
Some other things to look at:
javascript.net - integrates V8 to Microsoft's CLI language environment: https://github.com/JavascriptNet/Javascript.Net
Windows scripting engine COM interface: http://msdn.microsoft.com/en-us/library/xawadt95%28v=vs.94%29.aspx
Mixing JS code and native code: http://athile.net/library/blog/?p=760


text:
Q: Get data directly from nested array in AngulaJS I have problem with reading data from nested array. Previously, I asked how to read data from nested array to display them in a table (as a new row) on HTML page; now, I need display data from nested array directly.
The array's structure: array1[var1,var2,array2[var3,var4]]
So... there is my problem:

...

I want to read var3 datas from array2 "directly", to display them side by side in the table. I need something as this:

   {{item.var3}}

It is possible?

A: If you already know the name of the nested array and you are sure it exists,
{{item}}
 can work perfectly.
If what you want is to flatten this array from array1[var1,var2,array2[var3,var4]] to [var1, var2, var3, var4], lodash can do you a favor