text:
Q: Cannot update my own windows service because it is being used by another process I created an application to update a Windows service application (that I've also created). This "updater" application works like a charm, but only if the Windows service is already stopped.
The order of operations for the updater application is the following:

*

*Obtain the ServiceController object

*Call myService.Stop() (If it's not already in the ServiceControllerStatus.Stopped state)

*Call myService.WaitForStatus()

*Call myService.Close()

*Update all of the .dll files

*Call myService.Start()

*Call myService.Close()
If the service is already stopped, then this does work. However, if the service was previously running, the updater application will stop the service and move on to step #5. At this point, I will get an error message saying that I cannot override the .dll files because the files are being used by another process.
At first I thought that it was my own updater application that was keeping a reference to the service through the ServiceController object and that's when I added step #4, this did not change anything.
If I run the updater application twice, the first time it stops it and fails at the updating the .dll files. Then the second time it notices that it's already stopped and tries to update the .dll files, then it all works. The service .dll get updated and the service is started.
private static bool ServiceCommand(string serviceName, bool startService, TimeSpan timeout)
{
    if (!GetServiceObject(serviceName, out ServiceController service)) return false;

    try
    {
        // First, check to make sure it's not already started or stopped
        if (service.Status == (startService ? ServiceControllerStatus.Running : ServiceControllerStatus.Stopped))
        {
            return true;
        }

        ServiceControllerStatus myTargetStatus;
        if (startService)
        {
            service.Start();
            myTargetStatus = ServiceControllerStatus.Running;
        }
        else
        {
            service.Stop();
            myTargetStatus = ServiceControllerStatus.Stopped;
        }

        // Wait for the target status
        service.WaitForStatus(myTargetStatus, timeout);

    }
    catch (Exception e)
    {
        Logger.Log("Unable to " + (startService ? "start" : "stop") + " service '" + service.ServiceName + "': " + e.Message);
        return false;
    }
    finally
    {
        if (service != null) service.Close();
    }

    return true;
}

I believe this is where the problem lies. In step #5 all I'm doing is a File.Copy() with the override parameter set as true. This is where I'm getting the error message The process cannot access the file '' because it is being used by another process.
Any help or input is greatly appreciated! Thanks!

A: An executable can report to the Service Control Manager that a service has stopped, but the executable can continue running for a while, for example to clean stuff up or let background threads finish doing their job. It shouldn't do that, it should request for more shutdown time in that case, but that's probably what's happening.
So either fix your service so that its executable stops immediately after reporting the service stopped status, or wait for your executable to stop before copying the files.
See also Service not fully stopped after ServiceController.Stop(), what is the maximum time windows service wait to process stop request and how to request for additional time.


text:
Q: Is there a Map implementation with the same contracts as the ECMAScript 6 Map draft? I wonder If there is an implementation of Map available with the same contract as the ECMAScript 6 draft, such that could be used as a fallback for Browsers not supporting it? I know there are some implementations, e.g. from this SO answer or from here, but they have different contracts so it would need to be manually adjusted.

A: You're looking for es6-shim, which includes a map, set, and other ES6 features.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как обновить Ubuntu 15.10 если умерли репозитории для моей версии Столкнулся с проблемой невозможности установки\обновления пакетов.
При попытке обновления получаю ошибки 404.

A: У меня сейчас такая же задача только с 9.04 до 16.04 серверной версии.
Протестировали 2 пути решения. Первый - это последовательное обновление до нужной версии:
~# apt-get install update-manager-core
~# do-realise-upgrade

Если выдает ошибку об отсуствии репозитория под версию, замените содержимое /etc/apt/ sources.list на (проверте название старой версии):
##  upgraded sources.list
# Required
deb http://old-releases.ubuntu.com/ubuntu/ karmic main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ karmic-updates main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ karmic-security main restricted universe multiverse

После 50 тестов, упешно прошли только 3. Тесты проводились на серверах Supermicro локально, удаленно по ssh и IPMI. Критерием было - сохранить удаленное подлюченияе без вмешательства оператора на другом конце.
Второй вариант - это создание автоматической установки при помощи preseed файла. Делаются бэкапы всех ключевых файлов настройки, создается диск отсылается на объект, востанавливается удаленное соединение с сохраненными настройками. Способ медленный и затратный требуется присуствие оператора; из 4 тестов успешных 4.
Если локальная машина, сохраните копии файлов настройки, базы данных и важные фалы и просто поставте с ноля систему.
Ссылки

*

*https://help.ubuntu.com/lts/installation-guide/armhf/apbs02.html

*https://help.ubuntu.com/community/TrustyUpgrades

A: Версии ubuntu с нечетными номерами 15, 17 и т.д. имеют небольшую поддержку по времени. Для 15 версии это время уже прошло. Вам стоит обновиться до какой-либо версии, которая имеет поддержку длительное время, такие версии называются lts(long term support). Версии Ubuntu lts поддерживаются в течении пяти лет. Т.е. обновления, например, для 16.04 lts вы будете получать вплоть до 2021 года.


text:
Q: How to handle non objects in VueJS loop in laravel 5.4? How can I display an array with objects in laravel 5.4. without getting errors if an object is null.
Data: array list
foreach ($posts as $post) {
echo $post->user->name; // display successfuly name of user
echo $post->likes->id; // show error - Trying to get property of non-object  }

A: Not every $post has a like, so you are basically trying to access a property of null which is, obviously, not an object. Your way around this is simple and I think you are overlooking it because you are expecting Laravel to just handle that error for you.
@foreach( $posts as $post )

{{ $post->name }}

{{ $post->likes ? $post->likes->id : 'No Likes' }}

@endforeach

Also, keep in mind here you have called it likes, which leads me believe it a one to many relationship (a post can have MANY likes). In that case, you are going to need to loop over $posts->likes to get the ID for each one:
@foreach($posts as $post )

{{ $post->name }}

    @if( $post->likes)
      @foreach( $post->likes as $like )
        {{ $like->id }} @if (!$loop->last), @endif
      @endforeach
    @else
      'No Likes';
    @endif

@endforeach


text:
Q: Extracting units of measurement from excel string I have some values in an excel string which contain various combination of characters alongwith unit of measurement. I want to extract only the units of measurement from the string. And if there is none, then it should return "0" or blanks. Following sample values:

*

*4.875 in.

*104°F

*0.2mL

*100 x 0.5, 1.5 and 2mL

*50 x 5 x 49 mm

Could you please suggest a customized formula or VBA macro to help do it.

A: I'm not sure how comfortable you are with using KuTools, but I think this should help.
Try these Steps.....

*

*Select the cell to split, and then click Kutools > Text > Split Cells, see screenshot :

*In the Split Cells dialog box, select Split to Columns under the Type section, and then check Text and number from the Split by section, see screenshot:

*And then click Ok button, select a cell to put the result in the popped out dialog box, see screenshot:

*Then click OK button, and the text strings have been split into separated text and number columns as following screenshot shown:

Let me know if it works out..

A: This simple method will solve the issue:

*

*Formula in cell J9:

=RIGHT(I9,(LEN(I9)-(LEN(I9)-2)))
N.B.

*

*Suggested method considers, sapmle data posted by OP.

Edited:
Since @Akina & OP raised one crucial issue that, unit of  measurement should be variable length therefore I've brought some sample data comprises variable length units as well standard patter of data entry (Space before units and not).
Sample 1: Space before units.

*

*Formula in K10:
=MAX(ISNUMBER(VALUE(MID(I10,{0,1,2,3,4,5,6,7,8,9},1)))*{0,1,2,3,4,5,6,7,8,9})+1

*Formula in M10:
=TRIM(RIGHT(I10,LEN(I10)-K10+1))

Sample 2: No space before units.

N.B.

*

*Method & Formula used with Sample 1 data ,solves this also.

*For neatness you may hide Helper Data.

*Adjust cell references in the formula as needed.

A: This can be done with an Excel formula.
=TRIM(MID(A1,LOOKUP(2,1/(MID(A1,seq,1)),seq)+1,99))

where seq is a named formula that refers to:
=ROW($A$1:INDEX($A:$A,255,1))

The formula finds the last Number in the string, and returns the TRIM'd string after that last number


text:
Q: iostream clear() istream &func(istream &in)
{
    string data;

    while (in >> data, !in.eof()) {
        if (in.bad())
            throw runtime_error("IO stream corrupted");
        if (in.fail()) {
            cerr << "bad data, try again" << endl;
            in.clear();
            in.ignore(200);
            continue;
        }

        cout << data << endl;;
    }

    //in.clear(istream::eofbit | istream::failbit);
    in.clear();

    return in;
}

why in.clear(istream::eofbit | istream::failbit); can not reset the cin?
but in.clear can make it.
PS: I use this function in main(), and use cin as its parameter.

A: clear is defined like this:

void clear(iostate state = goodbit);

So, effectively, in.clear(); is doing this: in.clear(istream::goodbit); which resets the stream. Calling in.clear(istream::eofbit | istream::failbit); would set both the eofbit and failbit, I doubt that is what you want.
std::cin.clear(std::istream::eofbit | std::istream::failbit);
std::ios_base::iostate state = std::cin.rdstate();
if( state == (std::istream::eofbit | std::istream::failbit))
{
    std::cout << "eofbit and failbit set" << std::endl;
}


text:
Q: Making option to choose correct resolution I am making a video game and have problem with screen resolutions.
Earlier, a few month ago, I asked very similar question.
Need images with lower resolution "stretched" to screen size
Back then, it seemed the answer I got (using ViewBox) was perfect, but now I am getting problems.
I want every and every image and control in my game to have a few different possible variations fit for resolutions.
For example, if user sets resolution 800x600, all images and buttons are reduced to correct sizes. But I do want my game to be fullscreen only, not windowed.
So, if the resolution is lower then end-user monitor has, all images must be stretched and look "fuzzy". And if higher, part of it must be outside of screen.
For now, my code just sets resolution to end-user monitor, whatever it is. That's absolutely not what I want.
What I get:

A very crude example of what I need:

I'll show xaml as its now. Of course it isn't full, but I'll show the beginning and a few elements, so you'll know how it's built.
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Name="wdwMain" x:Class="RealityIncognita.MainWindow"
    Height="900" Width="1600" ResizeMode="NoResize" WindowState="Maximized" Cursor="Cross" WindowStyle="None" Loaded="wdwMain_Loaded">

<Viewbox x:Name="viewMain" Stretch="Fill">
    <Grid x:Name="areaContainer" HorizontalAlignment="Left" Height="900" VerticalAlignment="Top" Width="1600">

      <Grid x:Name="areaMain">
            <Grid.Background>
                <ImageBrush ImageSource="Resources/Images/Interface/main_interface.jpg"/>
            </Grid.Background>
            <Label x:Name="lblTextOutput" Content="Label" HorizontalAlignment="Center" Height="52" Margin="55,726,31,0" VerticalAlignment="Top" Width="1514" FontFamily="Arial" FontSize="22" FontWeight="Bold" HorizontalContentAlignment="Center"/>
            <Button x:Name="btnExit" HorizontalAlignment="Left" Height="106" Margin="1464,771,0,0" VerticalAlignment="Top" Width="126" Click="btnExit_Click" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{x:Null}">
                <Button.Template>
                    <ControlTemplate>
                        <Image Source="/Resources/Images/Interface/Blank.png" Stretch="Fill" Margin="12,0,6,0"/>
                    </ControlTemplate>
               </Button.Template>
            </Button>

            <Grid x:Name="areaShowers" HorizontalAlignment="Left" Height="700" Margin="1653,790,-1561,-590" VerticalAlignment="Top" Width="1508"  IsVisibleChanged="areaShowers_IsVisibleChanged">
                <Grid.Background>
                    <ImageBrush ImageSource="Resources/Images/Rooms/Showers/shower_room.jpg" />
                </Grid.Background>

                <Button x:Name="objShowersSoap" HorizontalAlignment="Left" Height="29" Margin="613,423,0,0" VerticalAlignment="Top" Width="17" MouseLeave="MouseLeaveAnyObject" RenderTransformOrigin="11.706,1.897" Click="objShowersSoap_Click" MouseEnter="objShowersSoap_MouseEnter">
                    <Button.Template>
                        <ControlTemplate>
                            <Image Source="Resources/Images/Rooms/Showers/soap.png" Stretch="Fill" Margin="0,0,0,0"/>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Image x:Name="imgShowersOpenMachine" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Source="Resources/Images/Rooms/Showers/drying_machine_open.png" RenderTransformOrigin="0.808,0.471" Stretch="Fill"/>
                </Button>
            </Grid>

            <Grid x:Name="areaLockerRoom" Height="700" VerticalAlignment="Top" Width="1508" IsVisibleChanged="areaLockerRoom_IsVisibleChanged" Margin="1653,17,-1561,0" MouseDown="areaLockerRoom_MouseDown" MouseEnter="areaLockerRoom_MouseEnter" MouseMove="areaLockerRoom_MouseMove">
                <Grid.Background>
                    <ImageBrush ImageSource="Resources/Images/Rooms/LockerRoom/locker_room_ready.png"/>
                </Grid.Background>

                <Button x:Name="objLockerRoomCrowbar" Content="" HorizontalAlignment="Left" Height="243" Margin="604,328,0,0" VerticalAlignment="Top" Width="51" MouseEnter="objCrowbar_MouseEnter" Panel.ZIndex="1" Click="objCrowbar_Click" MouseLeave="MouseLeaveAnyObject">
                    <Button.Template>
                        <ControlTemplate>
                            <Image Source="Resources/Images/Rooms/LockerRoom/crowbar_only.png" Stretch="Fill" Margin="0,0,0,0"/>
                        </ControlTemplate>
                    </Button.Template>
                </Button>

                <Button x:Name="objLockerRoomOdyssey" HorizontalAlignment="Left" Height="53" Margin="797,638,0,0" VerticalAlignment="Top" Width="61" Click="objBookOdyssey_Click" MouseLeave="MouseLeaveAnyObject" MouseEnter="objBookOdyssey_MouseEnter">
                    <Button.Template>
                        <ControlTemplate>
                            <Image Source="Resources/Images/Rooms/LockerRoom/img_book_odyssey.png" Stretch="Fill" Margin="0,0,0,0"/>
                        </ControlTemplate>
                    </Button.Template>
                </Button>
                <Button x:Name="objLockerRoomEdda" HorizontalAlignment="Left" Height="53" Margin="1335,549,0,0" VerticalAlignment="Top" Width="61" MouseLeave="MouseLeaveAnyObject" Click="objBookEdda_Click" MouseEnter="objBookEdda_MouseEnter">
                    <Button.Template>
                        <ControlTemplate>
                            <Image Source="Resources/Images/Rooms/LockerRoom/img_book_edda.png" Stretch="Fill" Margin="0,0,0,0"/>
                        </ControlTemplate>
                    </Button.Template>
                </Button>

To summarize the structure is like that:
Main Window - Viewbox - areaContainer (main grid) - game areas (grids) - images and buttons for each grid
To summarize:
What I get: game screens are set for end-user monitor resolution.
What I need: game sets all images to specific resolution, makes it "fuzzy" if resolution is LOWER then end-user's, and "cuts" it if it is HIGHER.
Thank you in advance,
Evgenie
ADDED:
If I understand correctly how it works - the container grid that includes all other items should be resized, images should become smaller (by default they are 1600x900), if needed. Then, this container grid must fit user's screen resolution, staying with small images quality.
And to simplify it even more: Can I make large images smaller, then change them to be big again (and lose quality) directly in Visual Studio?

A: Actually simply adjusting the viewbox did the trick.
<Viewbox x:Name="viewMain" VerticalAlignment="Center" HorizontalAlignment="Center">

And in code, I had to change MaxWidth and MaxHeight, instead of regular ones.
viewMain.MaxWidth = 1024;
viewMain.MaxHeight = 768;


text:
Q: .htaccess redirection issue I suck at htaccess and trying to achieve the following set of redirections. Any help would be greatly appreciated. I can't find anything on askapache and I don't understand general htaccess rules formating.
domain1.com/x -> sub.domain2.com (x being any page and file under this domain, but not the bare domain itself)
domain1.com -> domain2.com (when they type the bare domaine, redirect to the new one)

A: .htaccess can be used to modify behavior of any directory. Unless you set rule for /x to one directory, you can't use .htaccess. In this case it should be easier to set up redirection in Apache configuration file. Try something like this in Apache configuration file:
RewriteEngine   on
RewriteRule     ^/$     http://domain2.com/     [R,L]
RewriteRule     ^/.+    http://sub.domain2.com/ [R,L]


text:
Q: Fiware Cepheus update failure to context broker with error "Unsupported Media Type" since using  fiware cephues  i follow  the Document i  send  the configration file which is
{
        "host":"http://localhost:8080",
"in":[
    {
      "id":"Lab.*",
      "type":"Lab",
      "isPattern": true,
      "attributes":[
        { "name":"motion", "type":"double","metadata": [
            { "name":"unit", "type":"string" }
          ] }
    , { "name":"priority", "type":"double","metadata": [
            { "name":"unit", "type":"string" }
          ] },

{ "name":"controller", "type":"string"}],

      "providers":[
        "http://localhost:8081"
      ]
    }
  ],

"out":[
    {
      "id":"ControllerX",
      "type":"Controller",
      "attributes":[

    {  "name":"switch", "type":"command"
          ,"metadata": [
            { "name":"unit", "type":"string" }
          ]
       }
,
          {  "name":"number", "type":"double"
          ,"metadata": [
            { "name":"unit", "type":"string" }
          ]  }

]

,

      "brokers":[
        {
          "url":"http://147.27.60.58:1026",
          "serviceName": "try1",
          "servicePath": "/try1",
          "authToken": "token"
        }
      ]
    }
  ],
"statements":[

    " INSERT INTO Controller  SELECT controller as id  , 'ON' as switch, (CASE  WHEN (C is null AND motion = 1) THEN 1 WHEN (C is null AND motion = 3) THEN 0 WHEN (C is not null AND motion = 1) THEN C.number+1 WHEN (motion = 0 AND C.number >= 1) THEN C.number-1 ELSE C.number END) as number FROM  Lab as  L unidirectional LEFT OUTER JOIN Controller.std:groupwin(id).std:lastevent() as C ON controller=C.id  GROUP BY controller HAVING (priority = 0 AND motion = 1) or (priority = 1) or (priority = 0 AND motion = 3 AND C.number > 0)   "
,

" INSERT INTO Controller  SELECT controller as id  ,C.switch as switch,  C.number-1  as number  FROM  Lab as  L unidirectional LEFT OUTER JOIN Controller.std:groupwin(id).std:lastevent() as C ON controller=C.id  GROUP BY controller  HAVING motion = 0 AND C.number > 1 AND (priority=0) "

 ,

 " INSERT INTO Controller  SELECT controller as id ,  'OFF'  as switch ,(CASE WHEN (motion = 0 AND C.number >= 1) THEN C.number-1 WHEN (motion=1 AND C is null) THEN 1 WHEN (C is null AND motion = 3) THEN 0 WHEN (motion = 1 AND C is not null) THEN C.number+1 ELSE C.number END) as number FROM  Lab as L unidirectional LEFT OUTER JOIN Controller.std:groupwin(id).std:lastevent() as C ON controller=C.id GROUP BY controller HAVING (priority = 0 AND C.number = 1 AND motion = 0 ) or (priority = 2)  or (priority = 0 AND motion = 3 AND C.number = 0)
"

    ]
}

and  its  successfuly  sent with  status code 200
but  when sending update
(curl 194.177.207.78:8081/v1/updateContext/ -s -S --header 'Content-Type: application/json' \
 --header 'Accept: application/json' -d @- | python -mjson.tool ) <<EOF

    { "contextElements": [
            {
                "type": "Lab",
                "isPattern": "false",
                "id": "FCI-Lab",
                "attributes": [
                       {
                        "name": "motion",
                        "type": "double",
                        "value": 1
                    },

                                        {
                        "name": "priority",
                        "type": "double",
                        "value": 0
                    },

                       {
                        "name": "controller",
                        "type": "string",
                        "value": "Controller12"
                    }
                ]
            }
        ],
        "updateAction": "UPDATE"
    }
EOF

I cant find  entity  in  context brocker
when checking  Cepheus-cep logs  i  got
2017-03-15 18:04:45.871  INFO 1059 --- [http-nio-8080-exec-8] c.o.cepheus.cep.EsperEventProcessor      : EventIn: Event{type='Lab', values={cont$
2017-03-15 18:04:45.872  INFO 1059 --- [http-nio-8080-exec-8] c.orange.cepheus.cep.EventSinkListener   : EventOut: Controller / number_unit:null$
2017-03-15 18:04:45.888  WARN 1059 --- [I/O dispatcher 2] o.s.web.client.AsyncRestTemplate         : Async POST request for "http://147.27.60.58$
2017-03-15 18:04:45.888  WARN 1059 --- [I/O dispatcher 2] c.orange.cepheus.cep.EventSinkListener   : UpdateContext failed for http://147.27.60.5$
2017-03-15 18:08:53.941  INFO 1059 --- [http-nio-8080-exec-10] c.o.cepheus.cep.EsperEventProcessor      : EventIn: Event{type='Lab', values={con$
2017-03-15 18:08:53.943  INFO 1059 --- [http-nio-8080-exec-10] c.orange.cepheus.cep.EventSinkListener   : EventOut: Controller / number_unit:nul$
2017-03-15 18:08:53.962  WARN 1059 --- [I/O dispatcher 2] o.s.web.client.AsyncRestTemplate         : Async POST request for "http://147.27.60.58$
2017-03-15 18:08:53.962  WARN 1059 --- [I/O dispatcher 2] c.orange.cepheus.cep.EventSinkListener   : UpdateContext failed for http://147.27.60.5$

017-03-15 18:09:05.417  WARN 1059 --- [I/O dispatcher 2] o.s.web.client.AsyncRestTemplate         : Async POST request for "http://147.27.60.58$
$7.60.58:1026: org.springframework.web.client.HttpClientErrorException: 415 **Unsupported Media Type**
2017-03-15 18:09:39.377  INFO 1059 --- [taskScheduler-1] c.o.cepheus.cep.SubscriptionManager      : Launch of the periodic subscription task at $
2017-03-15 18:14:39.378  INFO 1059 --- [taskScheduler-1] c.o.cepheus.cep.SubscriptionManager      : Launch of the periodic subscription task at $

what does it mean by Unsupported Media Type in the logs and how to solve this error ?
 we  really need  help as  fast as possible.


text:
Q: 302 response in flutter I developed an application with native android and native iOS, but now I want to recreate it using flutter.
some of the requests that I done successfully in native android and iOS are returning 302 status code in flutter.
the problem is that I can't get 302 response on postman so I may understand what is the problem, it keep happening only on flutter.
  Map<String, String> headers = {'Content-Type': 'application/json', "Authorization": "Bearer ${App.token}"};

  Response response = await post(URL, body: jsonEncode({"FullName": name}), headers: headers);
  if (checkIfSuccessful(response)) {
    return true;
  } else {
    return false;
  }

A: You can use flutter DevTools to inspect the network; get it in the android studio by pressing this icon
enter network tab and begin recording, you should be able to analyze network traffic and understand the problem
in your code you can check for response status code like
Response response = await post(URL, body: jsonEncode({"FullName": name}), headers: headers);
switch (response.statusCode){
  case (200){
    print('Ok');
    break;
  }
  case (302){
    print('Handling redirect');
    break;
  }
}


text:
Q: How to plot a stacked bar with plotly, from a dataframe I have a df as
name | week |      %
mike   Week 1     .45
mike   Week 2      0
mike   Week 3     .40
mike   Week 4     .15
cindy  Week 1     .25
cindy  Week 2     .25
cindy  Week 3     .25
cindy  Week 4     .25

sampled df where my actual df has many more names
I am trying to plot all of the values of each name per week,
my plotly code is below:
    import plotly.graph_objects as go
    names= df['name'].unique()

    fig = go.Figure(data=[
        go.Bar(name='Week 1', x=names, y=[.15, .29, .19, .07]),
        go.Bar(name='Week 2', x=names, y=[.24, .15, .15, .15]),
        go.Bar(name='Week 3', x=names, y=[.20, .19, .17, .11]),
        go.Bar(name='Week 4', x=names, y=[.41, .37, .49, .67]),

    ])
    # Change the bar mode
    fig.update_layout(barmode='stack', title = 'title',xaxis_title='Month',
                      yaxis=dict(
            tickformat="%",
        ))

fig.show()

But I do not want to manually type out in y each of the values for week 1 then week 2 then week 3 and so on. How can I create a reference where y for each week in the plotting code will refer to all the values in week 1 so I dont have to type out? Thanks

A: *

*The easiest way, is with plotly.express, which takes a tidy (long) dataframe, by column name.

*plotly: Bar chart with Long Format Data
import plotly.express as px
import pandas as pd

# sample dataframe
data = {'name': ['mike', 'mike', 'mike', 'mike', 'cindy', 'cindy', 'cindy', 'cindy'],
        'week': ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 1', 'Week 2', 'Week 3', 'Week 4'],
        '%': [0.45, 0.0, 0.4, 0.15, 0.25, 0.25, 0.25, 0.25]}
df = pd.DataFrame(data)

# display(df)
    name    week     %
0   mike  Week 1  0.45
1   mike  Week 2  0.00
2   mike  Week 3  0.40
3   mike  Week 4  0.15
4  cindy  Week 1  0.25
5  cindy  Week 2  0.25
6  cindy  Week 3  0.25
7  cindy  Week 4  0.25

# plot the long (tidy) dataframe
fig = px.bar(df, x="name", y="%", color="week", title="Title", barmode='stack')
fig.update_layout(xaxis_title='Name', yaxis=dict(tickformat="%",))
fig.show()

*

*plotly.graph_objects requires a plotly.graph_obj, to construct each level of the stacked bar plot

*Using a list-comprehension, a df.groupby object can be unpacked into the necessary form, for go.Figure

*

*As also mentioned in a comment by Juan Estevez
import plotly.graph_objects as go

# using df from above, use groupby and a list comprehension to create data
data = [go.Bar(name=group, x=dfg['name'], y=dfg['%']) for group, dfg in df.groupby(by='week')]

# plot the figure
x = go.Figure(data)
x.update_layout(barmode='stack', title='Title', xaxis_title='Name', yaxis=dict(tickformat="%",))
x.show()

*

*Both implementations produce the following plot


text:
Q: Mixpanel Data Sampling/Event Sampling I found this code for Google Analytics which lets you analyze just a subset of data for your analytics.
_gaq.push(['_setSampleRate', '80']);

I want to do the same thing with Mixpanel but from what I understand SetSampleRate is a function that is specific to Google Analytics.
How might I do something like this in Mixpanel?
I have browsed their KB & Help articles but haven't found anything that talks about this.

A: All you have to do is create a Random number from 0 to 100 and check if it's lower than the sample target you have. If it's lower you track it, otherwise you don't.
The way _setSampleRate works in Google Analytics is that it samples by user not by hit. So when you generate the Random number you also have to store it in a cookie so that you can check for further interactions and either track it or not.
In the Example below I created a helper function that checks if the user is in the Sample and handles the cookie logic for me.
function inSample(target) {
  var domain_name = 'mysite.com'; // CUSTOMIZE WITH YOUR DOMAIN
  var sampleCookie = 'mixpanel_sample='; // COOKIE NAME

  var current = document.cookie;

  if (current.indexOf(sampleCookie) > -1) {
    // Cookie already exists use it
    var current = document.cookie.substring(
      document.cookie.indexOf(sampleCookie) + sampleCookie.length
    );
    if (current.indexOf(';') > -1)
      current = current.substring(0,current.indexOf(';'));

    current = parseInt(current);
  } else {
    // Cookie not found calculate a random number
    current = Math.floor(Math.random()*100)

  }
    // reset the cookie to expire in 2 years
    var two_years = new Date();
    two_years.setTime(two_years.getTime() + 2*365*24*60*60*1000);
    two_years = two_years.toGMTString();

    document.cookie = sampleCookie + current +
      '; domain=' + domain_name + '; path=/' +
      ' ; expires=' + two_years + ';'

    return target >= current;
}

Now all you have to do is use this function in order to fire or not the mixPanel tracking Code.
if (inSample(80)) {
  // MIXPANEL TRACKING CODE GOES HERE
}

What you have in the end is a report in Mixpanel that only includes 80% of your users.


text:
Q: javascript collision detection, d3js Working on a little thing in javascript where im adding elements to an SVG with the d3.js library. The function below runs when a button gets clicked. It simply adds a new circle-element to the SVG. What i need help with is to implement a collision detection so the elements wont get added over each other.
    createCircle = function(p) {
    var person = svg.append("circle")
        .attr("cx", Math.random() * svgWidth)
        .attr("cy", Math.random() * svgHeight)
        .attr("r", 20)
        .attr("class","person")
        .attr("id","p_"+index)
        .style("fill", p.color);
    index++
}


text:
Q: How to bind Model from get to post method MVC 4 I am currently stuck at some point of my implementation where I use a ViewModel class to display data, but I need to post values from other object which are equal to given values in the ViewModel. Here are both model classes
ViewModel.cs
public class ViewModel
{
    public IList<Answer> Answers { get; set; }
    public Question Questions { get; set; }

}

UserScore.cs
public partial class UserScore
{
    public int ScoreID { get; set; }
    public int U_Id { get; set; }
    public int A_Id { get; set; }
    public bool CorrectAnswer { get; set; }
    public int Q_Id { get; set; }

    public virtual Answer Answer { get; set; }
    public virtual Member Member { get; set; }
    public virtual Question Question { get; set; }
}

So far so good. I am using an object of Question and List of Answers to display the data I need in my Controller
Controller.cs
public ActionResult TakeTest(int id=0)
    {
        ViewModel vm = new ViewModel();
        Test t = db.Tests.Find(id);
        if (t == null)
        {
            return HttpNotFound();
        }

        vm.Questions = (from q in db.Questions
                        join tt in db.Tests on q.BelongToTest equals tt.TestId
                        where q.BelongToTest == id
                        select q).FirstOrDefault();

        vm.Answers = new List<Answer>(from a in db.Answers
                      join q in db.Questions on a.BelongToQuestion equals q.QuestionId
                      join tt in db.Tests on q.BelongToTest equals tt.TestId
                      where q.BelongToTest == id &&
                      a.BelongToQuestion == vm.Questions.QuestionId
                      select a).ToList();

        foreach (var i in vm.Answers)
        {
            i.CorrectOrNot = false;
        }

            return View(vm);
    }

View.cshtml
    @model  MvcTestApplication.Models.ViewModel
@using MvcTestApplication.Models

@{
    ViewBag.Title = "TakeTest";
}

TakeTest

@using (Html.BeginForm()) {

        Question Name

            @Html.DisplayFor(model => model.Questions.Question_Text)

        Correct?
        Answer text
        Open Answer

   @for(int i = 0; i < Model.Answers.Count; i++)
   {

         @Html.CheckBoxFor(m => m.Answers[i].CorrectOrNot)
         @Html.DisplayFor(m => m.Answers[i].AnswerText)
         @Html.EditorFor(m => m.Answers[i].OpenAnswerText)

   }

   if(ViewBag.Message != null)
{

}

<input type="submit" value="Next Question" />

}

Now in my post method I need to get the value of vm.Question.QuestionId and AnswerId of the Answer list, set them to be equal to UserScore.Q_Id and UserScore.A_Id. How can I do that ? I tried many ways but with no success.
Controller.cs
[HttpPost]
    [Authorize]
    public ActionResult TakeTest(ViewModel vm)
    {
        if (ModelState.IsValid)
        {
            UserScore us = new UserScore();

            us.U_Id = (from m in db.Members
                       where m.UserID == WebSecurity.CurrentUserId
                       select m.MemberId).FirstOrDefault();

            us.A_Id = 49;
          //us.A_Id = vm.Questions.QuestionID returns NULL

            us.Q_Id = 150;

            db.UserScores.Add(us);
            db.SaveChanges();
        }
        return View(vm);
    }

In general I need to know how to bind this vm.something to us.something because Question appears to be null all the time.

A: vm.Questions.QuestionID returns NULL because u haven't used that on the view anywhere. A easy hack would be to use a hidden field to capture the value or you should be initializing your viewmodel again and follow the logic in the post method.

A: These values are null, because they are not present in your view. You will need to keep them in your View in the form of a hidden control. The ViewModel that you receive in the post can only construct the ViewModel using values present in the View. Since there is no ID maintained in the View, the constructed ViewModel has a null ID.
You can use
@Html.HiddenFor(model => model.Questions.ID)

and for your answer ID
@Html.HiddenFor(m => m.Answers[i].ID)

A: You should use an hiddenfor helpers in your view and try something like that.
@Html.hiddenfor(m=>vm.Questions.QuestionId)

Give it a try : Html.HiddenFor value property not getting set


text:
Q: Post apocalyptic movie set in apartment building I have not had luck in horror.com, reddit, quora, or yahoo, but will still try for this one and another movie
There is only light outside, a blinding light, anyone that goes into the light never comes back, there are survivors bunkered down in an apartment building(one of those large buildings in suburban areas, that are several buildings interconnected by a sort of bridge between them
There are a couple of guys that struggle for control of the group, the de facto leader ATM is a guy that, as I remember thinking, was going crazy, whenever he had an issue he needed to think about, he went to another floor, to some sort of maintenance room were he chatted with a chubby guy, nerdy looking, with glasses, and he "helped" him see things clearer
The group sent "scouts" to other parts of the buildings to get supplies, the run that we see on screen goes wrong and one of the monsters inside the light takes one of them away, after a fight and some deaths, there are only(As far as I remember) a father, his daughter, in her twenties, and the MC, they have a discussion and the father and daughter decide they will go into the light because, as they see it now, it might be a way to paradise, talking as if they were dead, instead of the rest of the world, and the light being the holy light to heaven, or something like that
I really want to see it again as I was working at the time and could not see everything and never got it's name, nor have I been able to find it again
Edit 1: I saw this movie around 7-10 years ago, I saw it in a channel like Cinemax, I don't think it was much older
Edit 2: You actually never see the monsters, you only hear the noises of them walking/running around


text:
Q: Sequence of functions, uniform convergence, and dirac Define the sequence of functions $$\delta_n(x) = \begin{cases} n \quad & \frac{-1}{2n} < x  < \frac{1}{2n}  \\0 &  \text{else} \end{cases}$$ and define the polynomial $g(x)=c_1 + c_2x + \dots c_kx^k$. Then
$$\lim_{n \to \infty} \int_{-1}^{1}g(x)\delta_n(x)=\lim_{n \to \infty} (c_1+c_3\frac{2}{3\cdot4}+\dots c_k\frac{2}{k\cdot n^k}=c_1=g(0).$$
So this is just exactly what would happen if I was allowed to take the limit inside the integral so that
$$\int_{-1}^{1}g(x)\delta(x)=g(0),$$
but I am not allowed to take the limit inside because the sequence of functions doesn't converge uniformly, right? So is this just a coincidence, or am I missing something?

A: The rigorous way to justify "taking limit inside the integral" to a non-function $\delta (x)$ is as follows:
$$ \int_{-1}^1 g(x) \delta_n (x) = n\int_{-1/2n}^{1/2n} g(x) dx = g(0) + \int_{-1/2n}^{1/2n} (g(x)-g(0)), $$
while
$$|g(x)-g(0)| = |c_2 x + \cdots c_k x^k| \le (|c_2| + \cdots |c_k|)|x| \le (|c_2| + \cdots |c_k|).$$
Thus
$$\left| \int_{-1/2n}^{1/2n} (g(x)-g(0))dx\right| \le \frac{(|c_2| + \cdots |c_k|)}{n} \to 0$$
as $n\to \infty$.
In general you have
$$ \int_{-1}^1 g(x) \delta_n(x) dx\to g(0)$$
for all $g$ continuous at $0$, since one can bound $g(x)-g(0)$.


text:
Q: Will using window.stop(); be bad for search engines? Will it hurt my website ? The only reason I ask is because I'm not sure if google wont be able to crawl the page with that function in place..
Also, what this function does is like clicking the (x) button on the browser, that is why I'am a little bit confused..

A: window.stop() stops the loading of external assets, but not the document itself. This should not effect google being able to crawl your site, but it probably wont index the images.


text:
Q: Make a folder "Sharable" on Mac My Mac got two different password protected users. Is there any way I can make the "music" folder a shared folder without copying/duplicating anything?
NOTE: When I right-click and "get info" on music folder, I can click make "shared folder" but then the Mac start yappin about "To publish this folder go to...". Is it dangerous to publish this folder or is it only me and the other user that can edit what's in the folder after I "publish" it.

A: I just followed Apple's advice given on this page where they say:
If you're using Mac OS X, follow these steps:

Quit iTunes. Go to your iTunes Media folder.
  By default, it's in ~/Music/iTunes.
  (This folder may be named iTunes Music if you created
  your iTunes library in iTunes 9 or earlier.)   Note: "~" represents
  your Home folder. Other users on your computer can't access these
  locations. Drag the iTunes Media folder to a public location. For
  example, you could move it to the Public folder in your Home folder
  (~/Public) or to a location outside your Home folder that other users
  can access (/Users/Shared). Important: Don't move the iTunes folder,
  the iTunes library file, or the iTunes library.xml file. Open iTunes.
  Choose iTunes > Preferences. Click Advanced. Click the Change button.
  In the window that opens, go to your iTunes Media folder. Click Choose
  or Open.

and I lost around 5GB because every song got duplicated! Thanks apple!

A: You can make an alias by right clicking on the music folder and selecting Make Alias. Rename the alias to whatever you want and then the alias to the shared folder.
A similar result can be obtained via the /Applications/Utilities/Terminal.app by making a symbolic link (symlink):
ln -s "/path/to/your/music/library" "/Users/Shared/Music"


text:
Q: Why is Rails gsub adding  tags unsafe_input = ActionController::Base.helpers.escape_javascript("'hi'") # comes from user input
html = "<script>console.log('((url))');</script>"
html.gsub("((url))", unsafe_input)

output: "<script>console.log('');</script>hi');</script>');</script>"
expected: <script>console.log('\'hi\'');</script>
I'm trying to build dynamic HTML to inject on the page. This html is a mix of my own (safe) html, and any unsafe code (in the example above, unsafe_input) is ran through escape_javascript and inserted ONLY between single quotes in a javascript variable.
I don't use escape_javascript in the view as building the html is quite complicated and I don't want to do it all inside the view... I do it in a model using the helper, and in the html I simply have:
<%= @combined_html.html_safe %>


text:
Q: can't connect any view controller to any class Hye there , i was trying to connect my view controller to a class and i just can't .
after i was selecting the view controller (from the black line under the screen) and open up
the identity inspector looking fot the right class at the drop down list - my class was not
there , so i copied the name of my class and i paste it into it and pressing "Enter" key i get
an error sound but i can't figure it out why?

*

*I was trying to open new view controller  and not work

*Trying to connect it to new class - and no .

*Reopen Xcode after closing the Process .

*Restart my MAC also .

cam anyone know what is the problem ?

A: I find the answer !
when i changed inherit it was sold.
instead this -      MYClass  : UITableViewController
to this -             MYClass :  UIViewController


text:
Q: WebRTC: onicecandidate function not been called, hence remote video is not showing I am trying to create web RTC peer connection on react native. I am using the react-native-webrtc module. When using two emulators and passing the same room id the video connection is not been created. While debugging I found the onIceCandidate funciton is not been called. I am using socket.io to create the room. Please help me with this.
Git: https://github.com/developerajendra/react-native-webrtc-demo
import React, {useState, useEffect} from 'react';
import {View, SafeAreaView, Button, StyleSheet, Text} from 'react-native';
import {RTCPeerConnection, RTCView, mediaDevices} from 'react-native-webrtc';
import io from "socket.io-client";

export default function WEBRtc({roomNumber}) {
  const [localStream, setLocalStream] = useState();
  const [remoteStream, setRemoteStream] = useState();

  let isCaller, localST, peerConnection;
  const socket = io("http://192.168.0.102:3000", {transports: ['websocket']});

  const constraints = {
    audio: true,
    video:false
  };

/**
 * Getting ready for local stream
 */
  const startLocalStream = () => {
      socket.emit('joinTheRoom', roomNumber);
  };

  socket.on('roomCreated', room=>{
    console.log('room created');

    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        localST = stream;
        isCaller = true;
      })
  });

  socket.on('roomJoined', room=>{
    console.log('room joined');
    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        socket.emit('ready', roomNumber)
      });
  });

  const configuration = {iceServers: [
    {'urls':'stun:stun.services.mozilla.com'},
    {'urls':'stun:stun.l.google.com:19302'}
  ]};

  // const localPC = new RTCPeerConnection(configuration);
  // const remotePC = new RTCPeerConnection(configuration);

  // const peerConnection = new RTCPeerConnection(configuration);

    socket.on('ready', room=>{
      if(isCaller){
        console.log('ready');
        peerConnection = new RTCPeerConnection(configuration);
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;
        peerConnection.createOffer()
        .then(offer=>{
          return peerConnection.setLocalDescription(offer)
          .then(()=>{
            console.log('emit offer');
              socket.emit('offer',{
                type:'offer',
                sdp:offer,
                room: roomNumber
              });
            })
          })
      }
    });

    socket.on("offer",e=>{

      if(!isCaller){
        peerConnection = new RTCPeerConnection(configuration);
        console.log('offer');
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;

        console.log('about to create answer', e);

        //accept offer from here(ready)
        peerConnection.setRemoteDescription(e)
        .then(()=>{
          return peerConnection.createAnswer()
          .then(answer=>{
            return peerConnection.setLocalDescription(answer)
            .then(()=>{
              console.log('emit answer');
                socket.emit('answer',{
                  type:'answer',
                  sdp: answer,
                  room: roomNumber
              });
            })
          })
        });
      }

    });

    function onAddStream(e){
      console.log('remote stream', e);
      if (e.stream && remoteStream !== e.stream) {
        console.log('remote stream', e.stream);

        setRemoteStream(e.stream);
      }
  };

    function onIceCandidate(event){
      console.log('ice candidate');

      if(event.candidate){
          console.log('sending ice candidate', event.candidate);

          socket.emit('candidate',{
              type: 'candidate',
              label: event.candidate.sdpMLineIndex,
              id: event.candidate.sdpMid,
              candidate: event.candidate.candidate,
              room: roomNumber
          });
      }
  }

    socket.on('candidate', e=>{
      console.log('candidate', isCaller);
      peerConnection.addIceCandidate(e);
      peerConnection.addStream(localStream);
    });

    socket.on('answer', e=>{
      console.log('answer');
      peerConnection.setRemoteDescription(e);
    });

  return (
    <SafeAreaView style={styles.container}>
    <View style={styles.streamContainer}>
      <View style={styles.streamWrapper}>
          <View style={styles.localStream}>
            {localStream && <RTCView style={styles.rtc} streamURL={localStream.toURL()} />}
            {!localStream && <Button title="Tap to start" onPress={startLocalStream} />}
          </View>
          <View style={styles.rtcview}>
            {remoteStream && <RTCView style={styles.rtc} streamURL={remoteStream.toURL()} />}
          </View>
        </View>
        {/* {!!remoteStream ? <Button style={styles.toggleButtons} title="Click to stop call" onPress={closeStreams} disabled={!remoteStream} /> : localStream && <Button title="Click to start call" onPress={startCall}  />} */}
    </View>
</SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#313131',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: '100%',
    width:'100%'
  },
  streamContainer:{
    backgroundColor: 'grey',
    // justifyContent: 'space-around',
    alignItems: 'center',
    height: '50%',
    width: '100%',
    flexDirection:'column'
  },
  streamWrapper:{
    backgroundColor: 'grey',
    justifyContent: 'space-around',
    alignItems: 'center',
    height: '100%',
    width: '100%',
    flexDirection:'row'
  },
  roomTitle:{
    fontSize:20,
    paddingTop:20
  },
  rtcview: {
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,

  },
  rtc: {
    width: '100%',
    height: '100%',
  },
  localStream:{
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,
    display:'flex',
    alignItems:'center',
    flexDirection:'row',
    justifyContent:'space-around',

  }
});

A: Your code has a lot of fundamental issues and I am sure that it isn't just ice candidate issue. For instance, you are creating a new socket every time the Components rerenders(since you're using a ). I'd recommend you using a class Component instead and handling events properly. Also, you're calling addStream every time you get a new ice candidate. It should be added only once(i.e preferably before you create an offer or answer). I think you should check WebRTC basics. Please try the below link.
https://webrtc.github.io/samples/src/content/peerconnection/pc1/

A: It may be a good idea to use simple-peer as it simplifies the webrtc script. It's an npm packages so you can directly implement it in react. Here an example project for multi-user calling PROJECT DEMO

A: In WebRTC you have to configure SSL or you can just use it in a local environment. Otherwise MediaStream object can not be captured.
Also, you are not connecting to same-origin in the socket client. Make sure that the socket connection has not faced a CORS problem and your signaling procedure is working properly.


text:
Q: Sequence in Sequence Challenge Suppose that there are two arithmetic sequences $a_n$ and $b_n$. Given that ${a_b}_{20}$ + ${b_a}_{14} = 2014$. What is the value of ${a_b}_{14}$ + ${b_a}_{20}$

A: What an interesting question! And a nice one to commemorate the year!
Here's a rather neat solution (even if I do say so myself), without having to substitute everything from scratch.
Let $p,q$ be the common difference for $a_n, b_n$ respectively.
Hence
$$\large {\begin{align}a_{b_{14}}+b_{a_{20}}&=[\color{red}{a_{b_{20}}}-(b_{20}-b_{14})p]+[\color{red}{b_{a_{14}}}+(a_{20}-a_{14})q]\\
&=\color{red}{a_{b_{20}}+b_{a_{14}}}-(b_{20}-b_{14})p+(a_{20}-a_{14})q\\
&=\color{red}{2014}-(6q)p+(6p)q\\
&=2014\qquad \blacksquare\end{align}} $$

A: Let $a_1=a$, common difference of the sequence is $d_a$, we have $a_n=(n-1)d_a+a$
Let $b_1=b$, common difference of the sequence is $d_b$, we have $b_n=(n-1)d_b+b$
$$a_{b_{20}}+b_{a_{14}}=2014$$
$$a+(b_{20}-1)d_a+b+(a_{14}-1)d_b=2014$$
$$a+(b+19d_b-1)d_a+b+(a+13d_a-1)d_b=2014$$
$$a+b+bd_a+ad_b+32d_ad_b-d_a-d_b=2014$$
Therefore
$$a_{b_{14}}+b_{a_{20}}=\\a+(b_{14}-1)d_a+b+(a_{20}-1)d_b=\\a+(b+13d_b-1)d_a+b+(a+19d_a-1)d_b=\\a+b+bd_a+ad_b+32d_ad_b-d_a-d_b=\\2014$$


text:
Q: How do I interpret the output from lvs and the content in /dev/mapper? I just asked this question and got an answer but it led to new questions. I am trying to follow this guide to create an encrypted volume on an embedded device with a limited version of Linux (e.g., it doesn't have a package manager that can download readymade scripts for this purpose and similar) so I must do it mostly manually and I don't understand how to use the output from lvs and the content of /dev/mapper/ for this purpose.
Output
$ sudo lvs
  LV   VG   Attr       LSize Pool Origin Data%  Meta%  Move Log Cpy%Sync Convert
  lv   vg   -wi-ao---- 8.17t

$ sudo ls -la /dev/mapper/
total 0
drwxr-xr-x    2 root     root            80 Oct  3 14:24 .
drwxr-xr-x   16 root     root          4080 Oct  3 14:24 ..
crw-------    1 root     root       10, 236 Oct  3 14:24 control
lrwxrwxrwx    1 root     root             7 Oct  3 14:25 vg-lv -> ../dm-0

So, how do I use this information in the linked guide? What kind of device is /dev/dm-0?

A: In your example, you have one logical volume called lv, it is 8.17 TiB big and it is the only logical volume in your system. The vg-lv is just a user friendly name, dm-0 is the system name and /dev/mapper/vg-lv is just a symlink to /dev/dm-0 -- when formatting the device (e.g. to ext4 or to LUKS in your case), you can use both, it doesn't matter.
The guide you linked is pretty simple, so to create a LUKS format on it, you just need to replace vg_server-lv_luks from the example with vg-lv and run
cryptsetup luksFormat /dev/mapper/vg-lv

everything else should be the same. (Btw. formatting a device will destroy all data on the device.)
You can just pretend /dev/mapper/vg-lv (or /dev/dm-0) is a normal disk partition with a weird name.


text:
Q: Is the error rate always the Bayesian one? I know from Wikipedia that the Bayes error rate is: $${\displaystyle p=1-\textstyle \sum _{C_{i}\neq C_{\text{max,x}}}\int \limits _{x\in H_{i}}P(C_{i}|x)p(x)\,dx}$$
where $x$ is an instance, $C_i$ is a class into which an instance is classified, $H_i$ is the area/region that a classifier function $h$ classifies as $C_i$.
For instance for a multiclass classifier results predicted["pred_idx_euc"] and the actual labels predicted["target"] I did the following error rate measure :
>>>def accuracy(target, predicted):
       acc = (target==predicted).sum()/len(target)
       return acc
>>>error_rate = 1 - accuracy(predicted["target"], predicted["pred_idx_euc"])

It doesn't look exactly the same way ...


text:
Q: Error: The shape of dict['input'] provided in model.execute(dict) must be [1,224,224,3], but was [1,244,244,3] I'm getting a strange error when using tensorflow.js:

Error: The shape of dict['input'] provided in model.execute(dict) must
  be [1,224,224,3], but was [1,244,244,3]

So the dimensions are the same...but somehow it is incorrect. Any help would be greatly appreciated.
My code is as follows:
import React, { Component } from "react";
import "./App.css";
import * as tf from "@tensorflow/tfjs";
import { loadFrozenModel } from "@tensorflow/tfjs-converter";
class App extends Component {
  // Set state
  state = { selectedFile: null, input: null };
  // File selected
  fileChangedHandler = event => {
    this.setState({ selectedFile: event.target.files[0] });
  };
  // File uploaded
  uploadHandler = () => {
    // Read file
    let reader = new FileReader();
    reader.addEventListener("loadend", () => {
      // Set width and height of image
      let img = new Image(244, 244);
      img.src = reader.result;
      // Convert to tensor
      let imgTensor = tf.fromPixels(img);
      // Init input with correct shape
      let input = tf.zeros([1, 244, 244, 3]);
      // Add img to input
      input[0] = imgTensor;
      this.setState({ input });
    });
    // Get img URL
    reader.readAsDataURL(this.state.selectedFile);
  };

  componentDidMount() {
    // Load model
    loadFrozenModel(
      "http://.../tf_models/tensorflowjs_model.pb",
      "http://.../tf_models/weights_manifest.json"
    ).then(model => this.setState({ model }));
  }

  componentDidUpdate() {
    // Image and model are ready
    if (this.state.model && this.state.input) {
      // Use model for prediction
      this.state.model.execute({
        input: this.state.input
      }).print();
    }
  }
  render() {
    return (
      <div className="App">
        <input type="file" onChange={this.fileChangedHandler.bind(this)} />
        <button onClick={this.uploadHandler.bind(this)}>Upload!</button>
      </div>
    );
  }
}

export default App;

A: The values in the error are different:

Error: The shape of dict['input'] provided in model.execute(dict) must be [1,224,224,3], but was [1,244,244,3]


text:
Q: UIScrollView con UIPageControl no queda centrado correctamente SWIFT Actualmente estoy necesitando tener un UIPageControl haciendo uso del UIScrollView
para poder tener un efecto de carrosuel
Mi problema es que las UIView no quedan centradas cada una un ejemplo mas practico

Se me queda parte de la segunda vista como parte de la primera
Mis clases son :
class InitialViewController: CommonViewController, UIScrollViewDelegate{

@IBOutlet weak var pageControl: UIPageControl!

@IBOutlet weak var scrollView: UIScrollView!{
    didSet{
        scrollView.delegate = self
    }
}

var presenter = InitialPresenter()
var slides:[Slide] = [];

override func viewDidLoad() {
    super.viewDidLoad()

    self.slides = createSlides()
    self.setupSlideScrollView(slides: slides)
    self.pageControl.numberOfPages = slides.count
    self.pageControl.currentPage = 0
    self.view.bringSubview(toFront: pageControl)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.presenter.wfm = WorkflowManager.init(navigationController: self.navigationController)
}

func createSlides() -> [Slide] {

    let slide1:Slide = Bundle.main.loadNibNamed("ViewSlide", owner: self, options: nil)?.first as! Slide
    slide1.imgCenterSlide.image = UIImage(named: "icono_transferencia_carrusel")
    slide1.strLblTitle.text = NSLocalizedString("strLblTitleSlideOne_INTIAL",comment:"")
    slide1.strLblSubTitle.text = NSLocalizedString("strLblSubTitleSlideOne_INTIAL",comment:"")

    let slide2:Slide = Bundle.main.loadNibNamed("ViewSlide", owner: self, options: nil)?.first as! Slide
    slide2.imgCenterSlide.image = UIImage(named: "icono_pago_carrusel")
    slide2.strLblTitle.text = NSLocalizedString("strLblTitleSlideTwo_INTIAL",comment:"")
    slide2.strLblSubTitle.text = NSLocalizedString("strLblSubTitleSlideTwo_INTIAL",comment:"")

    let slide3:Slide = Bundle.main.loadNibNamed("ViewSlide", owner: self, options: nil)?.first as! Slide
    slide3.imgCenterSlide.image = UIImage(named: "icono_consulta_carrusel")
    slide3.strLblTitle.text = NSLocalizedString("strLblTitleSlideTree_INTIAL",comment:"")
    slide3.strLblSubTitle.text = NSLocalizedString("strLblSubTitleSlideTree_INTIAL",comment:"")

    let slide4:Slide = Bundle.main.loadNibNamed("ViewSlide", owner: self, options: nil)?.first as! Slide
    slide4.imgCenterSlide.image = UIImage(named: "icono_simulador_carrusel")
    slide4.strLblTitle.text  = NSLocalizedString("strLblTitleSlideFour_INTIAL",comment:"")
    slide4.strLblSubTitle.text = NSLocalizedString("strLblSubTitleSlideFour_INTIAL",comment:"")

    slide1.strLblTitle.textColor = Utils.Color.BlueLabelText
    slide1.strLblSubTitle.textColor = Utils.Color.BlueLabelText

    slide2.strLblTitle.textColor = Utils.Color.BlueLabelText
    slide2.strLblSubTitle.textColor = Utils.Color.BlueLabelText

    slide3.strLblTitle.textColor = Utils.Color.BlueLabelText
    slide3.strLblSubTitle.textColor = Utils.Color.BlueLabelText

    slide4.strLblTitle.textColor = Utils.Color.BlueLabelText
    slide4.strLblSubTitle.textColor = Utils.Color.BlueLabelText

    return [slide1, slide2, slide3, slide4]
}

func setupSlideScrollView(slides : [Slide]) {
    scrollView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
    scrollView.contentSize = CGSize(width: view.frame.width * CGFloat(slides.count), height: view.frame.height)
    scrollView.isPagingEnabled = true

    for i in 0 ..< slides.count {
        slides[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: view.frame.width, height: view.frame.height)
        scrollView.addSubview(slides[i])
    }
}

/*
 * default function called when view is scolled. In order to enable callback
 * when scrollview is scrolled, the below code needs to be called:
 * slideScrollView.delegate = self or
 */
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let pageIndex = round(scrollView.contentOffset.x/view.frame.width)
    pageControl.currentPage = Int(pageIndex)

    let maximumHorizontalOffset: CGFloat = scrollView.contentSize.width - scrollView.frame.width
    let currentHorizontalOffset: CGFloat = scrollView.contentOffset.x

    // vertical
    let maximumVerticalOffset: CGFloat = scrollView.contentSize.height - scrollView.frame.height
    let currentVerticalOffset: CGFloat = scrollView.contentOffset.y

    let percentageHorizontalOffset: CGFloat = currentHorizontalOffset / maximumHorizontalOffset
    let percentageVerticalOffset: CGFloat = currentVerticalOffset / maximumVerticalOffset

    /*
     * below code changes the background color of view on paging the scrollview
     */
    //        self.scrollView(scrollView, didScrollToPercentageOffset: percentageHorizontalOffset)

    /*
     * below code scales the imageview on paging the scrollview
     */
    let percentOffset: CGPoint = CGPoint(x: percentageHorizontalOffset, y: percentageVerticalOffset)

}

func scrollView(_ scrollView: UIScrollView, didScrollToPercentageOffset percentageHorizontalOffset: CGFloat) {
    if(pageControl.currentPage == 0) {
        //Change background color to toRed: 103/255, fromGreen: 58/255, fromBlue: 183/255, fromAlpha: 1
        //Change pageControl selected color to toRed: 103/255, toGreen: 58/255, toBlue: 183/255, fromAlpha: 0.2
        //Change pageControl unselected color to toRed: 255/255, toGreen: 255/255, toBlue: 255/255, fromAlpha: 1

        pageControl.pageIndicatorTintColor = Utils.Color.BlueLabelText

        slides[pageControl.currentPage].backgroundColor = Utils.Color.LigthViewBackGround

        let pageSelectedColor: UIColor = fade(fromRed: 81/255, fromGreen: 36/255, fromBlue: 152/255, fromAlpha: 1, toRed: 103/255, toGreen: 58/255, toBlue: 183/255, toAlpha: 1, withPercentage: percentageHorizontalOffset * 3)
        pageControl.currentPageIndicatorTintColor = Utils.Color.BlueLabelText
    }
}

func fade(fromRed: CGFloat,
          fromGreen: CGFloat,
          fromBlue: CGFloat,
          fromAlpha: CGFloat,
          toRed: CGFloat,
          toGreen: CGFloat,
          toBlue: CGFloat,
          toAlpha: CGFloat,
          withPercentage percentage: CGFloat) -> UIColor {

    let red: CGFloat = (toRed - fromRed) * percentage + fromRed
    let green: CGFloat = (toGreen - fromGreen) * percentage + fromGreen
    let blue: CGFloat = (toBlue - fromBlue) * percentage + fromBlue
    let alpha: CGFloat = (toAlpha - fromAlpha) * percentage + fromAlpha

    // return the fade colour
    return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}

}
Mi clase Slide es la siguiente
class Slide: UIView {

@IBOutlet weak var strLblTitle: UITextView!

@IBOutlet weak var imgCenterSlide: UIImageView!

@IBOutlet weak var strLblSubTitle: UITextView!
@IBOutlet weak var viewBackGround: UIView!

}
y mis contrainsts son

Desde ya cualquuier ayuda es bienvenida no entiendo porque no puede quedar cada view centrado

A: Te recominedo cambiar tu codigo al sguiente.
override func viewDidLoad() {
    super.viewDidLoad()
    self.setupSlideScrollView(slides: slides)
    self.pageControl.numberOfPages = slides.count
    self.pageControl.currentPage = 0
    self.view.bringSubview(toFront: pageControl)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.slides = createSlides()
    self.presenter.wfm = WorkflowManager.init(navigationController: self.navigationController)
}

El problema es que el slide que estas creando le estas asingnado el ancho de la vista del viewcontroller aun cuando no esta en pantalla por lo que tu vista no tiene el ancho de la pantalla del dispositivo que solo ocurre al aparecer la vista. tambien te recomendaria probar con self.view.layoutIfNeeded() pero no estoy seguro que arregle el centrado. lo otro que podrias hacer seria añadir constrains via codigo.


text:
Q: Positioning a div between two divs I have two div elements as below:

  This is div 1

  This is div 2

With css as:
.div1 {
  border-style: solid;
  float: left;
  width: 50%;
}
.div2 {
  border-style: solid;
  margin-left: 50%;
  padding-left: 10px;
}

I want to add a third div which has nothing but a symbol through css.

with css:
.div3:after {
    font-family: "FontAwesome";
    content: "\f100";
    color: blue;
    font-size: 1.5em;
}

For this to nicely position between the two original div's, I changed div 2's css to:
.div2 {
  border-style: solid;
  margin-left: 51%;
  padding-left: 6px;
}

This looks ok on FullScreen. However, when I minimize the browser window to a smaller size, div2 starts overlapping div3.
How can I nicely position div3 between div1 and div2 with even space at both sides of div2?
Here's the JSFiddle for my try: https://jsfiddle.net/d8nuw2m3/5/
Edit:
The flex solution provided below by Roy works fine. However, assume that the content of left and right div's grows a lot. In which case, scroll bar will appear. What if in this case, I want to keep the position of the middle div fixed as I scroll down ?
Adding position: fixed to div3 css doesn't work.
Here's the fiddle: https://jsfiddle.net/zL8sc2a9/

A: Solution #1
You could use flex for this.
Wrap all div's in a container with display: flex:

    This is div 1

    This is div 2

.flex-container {
  display: flex;
}

Let the div1 and div2 grow equally (remove widths, margins, paddings):
.div1 {
  border-style: solid;
  flex-grow: 1;
}
.div2 {
  border-style: solid;
  flex-grow: 1;
}

Set a fixed width to the div3:
.div3 {
  width: 18px;
}

That's it! Flex will do the trick for you: https://jsfiddle.net/1amuwfj5/
Solution #2
Use calc() to subtract div3 width from div1 and div2. General idea:
.div1 {
  border-style: solid;
  float: left;
  width: calc(50% - 15px); /* we subtract 9x (half of div3) and 6px (border width) */
}
.div2 {
  border-style: solid;
  float: right;
  width: calc(50% - 15px);
}
.div3 {
  width: 18px;
}

Example: https://jsfiddle.net/1amuwfj5/1/

A: You can achieve this adding a div around it and using display: flex;. Floating elements is really the old way to do this.
Edit
I updated the snippet to have the .div3:after fixed with scrolling.

.page {
  background-color: #eee;
  height: 150vh;
}

.wrapper {
  display: flex;
  justify-content: space-between;
}

.div1 {
  border-style: solid;
  width: 50%;
  margin-right: .5em;
}

.div2 {
  border-style: solid;
  width: 50%;
  margin-left: 1.5em;
}

.div3:after {
  position: fixed;
  font-family: "FontAwesome";
  content: "\f100";
  color: blue;
  font-size: 1.5em;
}

      This is div 1

      This is div 2


text:
Q: What Operations in snowflake do not consume compute credits? I know that DDL and Show operations do not consume compute credits? Is there any list some one has compiled to determine what operations in snowflake do not consume compute credits? Appreciate your help

A: There is no hard rule that snowflake doesn't charge for DDL and Show operations. They will charge based on the cost of storage and the cost of compute resources consumed.
Storage:  storage is per terabyte, compressed, per month and charge for compute is based on the processing units, which we refer to as credits, consumed to run our queries.
please refer following link for more details:
https://www.snowflake.com/pricing/

A: There are a list of statements that can be run in Snowflake that do not consume compute (virtual warehouse) credit.  This list can include:
- DDL statements
- Queries that hit result cache
- result_scan query
- Show commands
- Some count, min, max queries.
Snowflake did make an announcement in November that there will be some changes coming starting February 2020 that will include some new Cloud Services billing in some situations for some of these innovative features that were running free of compute credits.  Here's the recently published blog:
https://www.snowflake.com/blog/whats-new-with-the-snowflake-cloud-services-billing-model/


text:
Q: Error: Program type already present: com.facebook.ads.Ad I am trying to implement facebook sdk according to this,
https://developers.facebook.com/docs/audience-network/android
When I trying to compile it im getting this error.

Error: Program type already present: com.facebook.ads.Ad

I'm using android studio 3.2.1
this is my gradle
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '28.0.3'

    defaultConfig {
        applicationId "com.test.test"
        minSdkVersion 16
        targetSdkVersion 27
        multiDexEnabled true

        ndk {
            moduleName "player_shared"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {
    implementation 'com.google.android.gms:play-services:+'
    implementation 'com.android.support:multidex:1.0.3'
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.google.android.gms:play-services-ads:11.6.0'
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
    implementation 'com.facebook.android:facebook-core:[4,5)'
    implementation 'com.facebook.android:facebook-marketing:[4,5)'
    implementation 'com.android.support:recyclerview-v7:25.3.1' // Required Dependency by Audience Network SDK
    implementation 'com.facebook.android:audience-network-sdk:5.+'
    // More deps here //
}


text:
Q: getActivity() returns null in Fragment function I have a fragment (F1) with a public method like this
public void asd() {
    if (getActivity() == null) {
        Log.d("yes","it is null");
    }
}

and yes when I call it (from the Activity), it is null...
FragmentTransaction transaction1 = getSupportFragmentManager().beginTransaction();
F1 f1 = new F1();
transaction1.replace(R.id.upperPart, f1);
transaction1.commit();
f1.asd();

It must be something that I am doing very wrong, but I don't know what that is.

A: The best to get rid of this is to keep activity reference when onAttach is called and use the activity reference wherever needed, for e.g.
@Override
public void onAttach(Context context) {
    super.onAttach(activity);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}

A: This happened when you call getActivity() in another thread that finished after the fragment has been removed. The typical case is calling getActivity() (ex. for a Toast) when an HTTP request finished (in onResponse for example).
To avoid this, you can define a field name mActivity and use it instead of getActivity(). This field can be initialized in onAttach() method of Fragment as following:
@Override
public void onAttach(Context context) {
    super.onAttach(context);

    if (context instanceof Activity){
        mActivity =(Activity) context;
    }
}

In my projects, I usually define a base class for all of my Fragments with this feature:
public abstract class BaseFragment extends Fragment {

    protected FragmentActivity mActivity;

    @Override
public void onAttach(Context context) {
    super.onAttach(context);

    if (context instanceof Activity){
        mActivity =(Activity) context;
    }
}
}

Happy coding,

A: The order in which the callbacks are called after commit():

*

*Whatever method you call manually right after commit()

*onAttach()

*onCreateView()

*onActivityCreated()

I needed to do some work that involved some Views, so onAttach() didn't work for me; it crashed. So I moved part of my code that was setting some params inside a method called right after commit() (1.), then the other part of the code that handled view inside onCreateView() (3.).

A: The other answers that suggest keeping a reference to the activity in onAttach are just suggesting a bandaid to the real problem. When getActivity returns null it means that the Fragment is not attached to the Activity. Most commonly this happens when the Activity has gone away due to rotation or the Activity being finished but the Fragment still has some kind of callback listener registered preventing it from being garbage collected. When the listener gets called if you need to do something with the Activity but the Activity is gone there isn't much you can do. In your code you should just check getActivity() != null and if it's not there then don't do anything. If you keep a reference to the Activity that is gone you are preventing the Activity from being garbage collected. Any UI things you might try to do won't be seen by the user. I can imagine some situations where in the callback listener you want to have a Context for something non-UI related, in those cases it probably makes more sense to get the Application context. Note that the only reason that the onAttach trick isn't a big memory leak is because normally after the callback listener executes it won't be needed anymore and can be garbage collected along with the Fragment, all its View's and the Activity context. If you setRetainInstance(true) there is a bigger chance of a memory leak because the Activity field will also be retained but after rotation that could be the previous Activity not the current one.

A: I am using OkHttp and I just faced this issue.

For the first part @thucnguyen was on the right track.

This happened when you call getActivity() in another thread that finished after the fragment has been removed. The typical case is calling getActivity() (ex. for a Toast) when an HTTP request finished (in onResponse for example).

Some HTTP calls were being executed even after the activity had been closed (because it can take a while for an HTTP request to be completed). I then, through the HttpCallback tried to update some Fragment fields and got a null exception when trying to getActivity().
http.newCall(request).enqueue(new Callback(...
  onResponse(Call call, Response response) {
    ...
    getActivity().runOnUiThread(...) // <-- getActivity() was null when it had been destroyed already

IMO the solution is to prevent callbacks to occur when the fragment is no longer alive anymore (and that's not just with Okhttp).
The fix: Prevention.
If you have a look at the fragment lifecycle (more info here), you'll notice that there's onAttach(Context context) and onDetach() methods. These get called after the Fragment belongs to an activity and just before stop being so respectively.
That means that we can prevent that callback to happen by controlling it in the onDetach method.
@Override
public void onAttach(Context context) {
    super.onAttach(context);

    // Initialize HTTP we're going to use later.
    http = new OkHttpClient.Builder().build();
}

@Override
public void onDetach() {
    super.onDetach();

    // We don't want to receive any more information about the current HTTP calls after this point.
    // With Okhttp we can simply cancel the on-going ones (credits to https://github.com/square/okhttp/issues/2205#issuecomment-169363942).
    for (Call call : http.dispatcher().queuedCalls()) {
        call.cancel();
    }
    for (Call call : http.dispatcher().runningCalls()) {
        call.cancel();
    }
}

A: Where do you call this function? If you call it in the constructor of Fragment, it will return null.
Just call getActivity() when the method onCreateView() is executed.

A: Since Android API level 23, onAttach(Activity activity) has been deprecated. You need to use onAttach(Context context). http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.app.Activity)
Activity is a context so if you can simply check the context is an Activity and cast it if necessary.
@Override
public void onAttach(Context context) {
    super.onAttach(context);

    Activity a;

    if (context instanceof Activity){
        a=(Activity) context;
    }

}

A: commit schedules the transaction, i.e. it doesn't happen straightaway but is scheduled as work on the main thread the next time the main thread is ready.
I'd suggest adding an
onAttach(Activity activity)

method to your Fragment and putting a break point on it and seeing when it is called relative to your call to asd(). You'll see that it is called after the method where you make the call to asd() exits. The onAttach call is where the Fragment is attached to its activity and from this point getActivity() will return non-null (nb there is also an onDetach() call).

A: PJL is right.
I have used his suggestion and this is what i have done:

*

*defined global variables for fragment:
private final Object attachingActivityLock = new Object();
private boolean syncVariable = false;

*implemented

@Override
public void onAttach(Activity activity) {
  super.onAttach(activity);
  synchronized (attachingActivityLock) {
      syncVariable = true;
      attachingActivityLock.notifyAll();
  }
}

3 . I wrapped up my function, where I need to call getActivity(), in thread, because if it would run on main thread, i would block the thread with the step 4. and onAttach() would never be called.
    Thread processImage = new Thread(new Runnable() {

        @Override
        public void run() {
            processImage();
        }
    });
    processImage.start();

4 . in my function where I need to call getActivity(), I use this (before the call getActivity())
    synchronized (attachingActivityLock) {
        while(!syncVariable){
            try {
                attachingActivityLock.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

If you have some UI updates, remember to run them on UI thread. I need to update ImgeView so I did:
image.post(new Runnable() {

    @Override
    public void run() {
        image.setImageBitmap(imageToShow);
    }
});

A: Do as follows. I think it will be helpful to you.
private boolean isVisibleToUser = false;
private boolean isExecutedOnce = false;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_my, container, false);
    if (isVisibleToUser && !isExecutedOnce) {
        executeWithActivity(getActivity());
    }
    return root;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    this.isVisibleToUser = isVisibleToUser;
    if (isVisibleToUser && getActivity()!=null) {
        isExecutedOnce =true;
        executeWithActivity(getActivity());
    }
}

private void executeWithActivity(Activity activity){
    //Do what you have to do when page is loaded with activity

}

A: Those who still have the problem with onAttach(Activity activity), Its just changed to Context -
    @Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context = context;
}

In most cases saving the context will be enough for you - for example if you want to do getResources() you can do it straight from the context. If you still need to make the context into your Activity do so -
 @Override
public void onAttach(Context context) {
    super.onAttach(context);
    mActivity a; //Your activity class - will probably be a global var.
    if (context instanceof mActivity){
        a=(mActivity) context;
    }
}

As suggested by user1868713.

A: Another good solution would be using Android's LiveData with MVVM architecture.
You would define a LiveData object inside your ViewModel and observe it in your fragment, and when LiveData value is changed, it would notify your observer (fragment in this case) only if your fragment is in active state, so it would be guaranteed that you would make your UI works and access the activity only when your fragment is in active state. This is one advantage that comes with LiveData
Of course when this question was first asked, there was no LiveData. I am leaving this answer here because as I see, there is still this problem and it could be helpful to someone.

A: Call getActivity() method inside the onActivityCreated()

A: I have solved my problem this way.I have passed getApplicationContext from the previous class which has already access of  getApplicationContext.I have passed Inputstream object to my new class Nutrients.
try{
                    InputStream is= getApplicationContext().getAssets().open("nutrient_list.json");
                    Nutrients nutrients=Nutrients.getNutrients(topRecognition,is);

                  } catch (IOException e) {
                    e.printStackTrace();
                  }

A: Write a common method that will ensure you will never get null Activity.
public class BaseFragment extends Fragment {
    private Context contextNullSafe;

     @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
         /*View creation related to this fragment is finished here. So in case if contextNullSafe is null
         * then we can populate it here.In some discussion in - https://stackoverflow.com/questions/6215239/getactivity-returns-null-in-fragment-function
         * and https://stackoverflow.com/questions/47987649/why-getcontext-in-fragment-sometimes-returns-null,
         * there are some recommendations to call getContext() or getActivity() after onCreateView() and
         * onViewCreated() is called after the onCreateView() call every time */
        if (contextNullSafe == null) getContextNullSafety();
    }

   @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        contextNullSafe = context;
    }

    /**CALL THIS IF YOU NEED CONTEXT*/
    public Context getContextNullSafety() {
                if (getContext() != null) return getContext();
                if (getActivity() != null) return getActivity();
                if (contextNullSafe != null) return contextNullSafe;
                if (getView() != null && getView().getContext() != null) return getView().getContext();
                if (requireContext() != null) return requireContext();
                if (requireActivity() != null) return requireActivity();
                if (requireView() != null && requireView().getContext() != null)
                    return requireView().getContext();

                return null;

        }

    /**CALL THIS IF YOU NEED ACTIVITY*/
    public FragmentActivity getActivityNullSafety() {
        if (getContextNullSafety() != null && getContextNullSafety() instanceof FragmentActivity) {
            /*It is observed that if context it not null then it will be
             * the related host/container activity always*/
            return (FragmentActivity) getContextNullSafety();
        }
        return null;
    }


text:
Q: Cannot read property 'forEach' of undefined while comparing the database id with user requested id I did insert the data to the MongoDB database and now I want to compare the user requested id with the id stored in the database. When I do that using the forEach loop am getting the error as TypeError: Cannot read property 'forEach' of undefined. I searched in stack overflow but still not able to figure out the problem. Help me to solve this issue!
Here is my code:
app.get('/product/:id', (req, res) => {
    MongoClient.connect(url, { useNewUrlParser: true }, (err, db) => {
        if (err) throw err;
        var dbo = db.db("product");
        var cursor = dbo.collection("details").find({}).toArray((err, result) => {
            if (err) throw err;
            cursor.forEach((_id)=>{
                if (_id == req.params.id) {

                return true;
                db.close();
                }
            })
            console.log(result);
        });

    });
});

And my data stored in database is:
[ { _id: '1', producttitle: 'Levis' } ]

A: you need to iterate the result variable not cursor
this is since the cursor variable is undefined because the task is not completed yet.
Moreover you need to access the _id of the result:
result.forEach((currUser)=>{
            if (currUser._id == req.params.id) {

            return true;
            db.close();
            }
        })

A: If you don't mind using async/await:
app.get('/product/:id', (req, res) => {
    MongoClient.connect(url, { useNewUrlParser: true }, async (err, db) => {
        if (err) throw err;
        var dbo = db.db("product");
        try{
            var results = await dbo.collection("details").find({}).toArray();
            results.forEach((product) => {
                if(product.id === req.params.id){
                    // do something you like here.
                    return true;
                    db.close();
                }
            });
        }catch(e){
            // error
        }
    });
});

BTW, I guess you find all documents from db because you still need to do something else. However, if not, you should put your condition in your queries like dbo.collection("details").find({_id: req.params.id}) .


text:
Q: How to change legend name in Grafana using regex? I am trying to change the names in a panel's legend in Grafana.
Basically my pane's legend names are in the form of:
somestring_someotherstring_somethirdstring.yetanotherstring

I'd like to just keep the name somethirdstring
My current attempt:
I go on the right-hand side of the panel where it says "Overrides" and attempt to replace the word string with nothing, but it does not work.

Can you please assist on how to achieve this goal?


text:
Q: Multiple Producer and Consumer Multithreading Java Not Working as Intended I'm working on the multiple producer and consumer use case of Producer-Consumer problem with Java. The code is on github. The same implementation worked for the single producer consumer use case, but behaved weirdly for the multiple producer consumer case.
I have some questions regarding the output:
At the start, all producers and one consumer has the lock:
Producer t1 has lock
t5 produced 1, integerQueue: [1]
Producer t5 notifiedAll

*

*I thought all threads should compete for the lock and there should be at most one thread that has the lock of all time? Are all producers sharing the lock? How did consumer thread t5 get the lock while producer thread t1 was holding it?

After it runs for a while, another weird phenomenon appears:
Producer t5 has lock
t5 produced 10, integerQueue: [8, 9, 10]
Producer t5 notifiedAll

Producer t5 has lock
t5 produced 11, integerQueue: [8, 9, 10, 11]
Producer t5 notifiedAll

Consumer t8 has lock
t8 consumed 8, integerQueue: [9, 10, 11]
Consumer t8 notified All

Consumer t8 has lock
t8 consumed 9, integerQueue: [10, 11]
Consumer t8 notified All

*It seems all threads except one producer and consumer had died and those 2 are switching lock between each other. Why is this happening? What happened to all the other producers and consumers?

Any help is greatly appreciated.

A: You are using a single instance of your Producer5 runnable and submit it many times to the execution service.
    Producer5 producer = new Producer5(queue, maxCapacity);
    pool.execute(producer);
    pool.execute(producer);
    pool.execute(producer);
    pool.execute(producer);
    pool.execute(producer);

So your threadName field in that single Producer5 instance will get overwritten several times and is not useful (it will no longer print out the name of the thread that is actually running, furthermore it would need to be volatile in order to be updated properly by multiple threads -- for some definition of properly).
  System.out.println(String.format("\nProducer %s has lock",
    threadName // this will be the name of the last thread that entered `run`,
              // they all share the same instance
  ));

Do not re-use the same Runnable instance if it contains mutable state. Make a separate instance for each thread of execution.

How did consumer thread t5 get the lock while producer thread t1 was holding it?

It was still Thread t1 running this code, but the threadName field has in the mean-time been updated by Thread t5. Highly misleading output.

It seems all threads except one producer and consumer had died and those 2 are switching lock between each other.

The threads are all still alive, but there are only two threadName fields in existence, that the threads have been taking turns to update (at the top of the run method), finally settling on some value. All threads just print that value now.


text:
Q: How to prove this countable intersection is empty? Let $(l_p,\|\cdot\|_p)$ be a normed space, for some fixed $p \in [1,\infty)$.
Let $\{e_i\}_{i=1}^{\infty}$ be standard basis and $E_n=\{e_i\}_{i=n}^{\infty},\ n=1,2,3,...\ .$
Then how can I prove $\bigcap \limits_{n=1}^{\infty} E_n=\emptyset$?

A: This has nothing to do with $l^{p}$ space and bases. For any sequence of distinct points $a_1,a_2,...$ (in any set $S$) the set $\cap_n \{a_n,a_{n+1},a_{n+2},...\} =\emptyset$ . This is because LHS is contained in $\{a_1,a_2,a_{n+2},...\}$  , so if there is some pint in LHS it must be one of the points $a_k$. But $a_k$ does not belong to $\{a_{k+1},a_{k+1},a_{n+2},...\}$ so it cannot belong to the intersection.

A: The set $\bigcap \limits_{n=1}^{\infty} E_n$ is the limit superior of the sequence of pairwise disjoint sets $\left(\{e_k\}\right)_{k\geqslant 1}$. A limit superior of pairwise disjoint sets is empty because a element of the limsup belons to infinitely many sets in the sequence.

A: Notice that $\forall n \in \mathbb{N}$, $e_n \in E_k$ for $k \leq n$ and $e_n \notin E_k$ for $k > n$. In particular, $e_n \notin E_{n + 1}$. Therefore, if $\exists x \in \bigcap\limits_{n = 1}^{\infty} E_n$, then in particular $x \in E_1 = \left\lbrace e_i \right\rbrace_{i = 1}^{\infty}$ so that the element is one of the basis element. Let it be $e_{i_0}$ for some $i_0 \in \mathbb{N}$. Since it is in the intersection, $\forall n \in \mathbb{N}$, $e_{i_0} \in E_n$ which is a contradiction to the fact that $e_{i_0} \notin E_{i_0 + 1}$.


text:
Q: Element disapears while calling a function - LZW Compression I made some research but nothing was really concerning my problem...
I'm actually trying to code LZW compression for school, and I need a function to check if an element is in my dictionnary.
However, when I'm calling this function, it tries to access to the 64th element in my dictionnary, but it has desapeared !! I checked it before the function calling, it was here !! And the worse is that I can call this element in the previous callings of the function.
Could you help me please ?
The function :
int is_in_dictionnary(dico * p_pRoot, char * p_string){
    int i = 0, j = 0;
    char a[1024] = { 0 }, b[1024] = { 0 };

    //strcpy(b, p_pRoot->m_dico[64].m_info);

    for (i = 0; i < p_pRoot->m_index; i++){
        printf("dico %s\n", p_pRoot->m_dico[i].m_info);

        strcpy(a, p_string);
        strcpy(b, p_pRoot->m_dico[i].m_info);

        j = strcmp(a, b);

        if (j == 0)
            return i;
    }
    return -1;
}

The console, we are herer abble to see that the function previously called the 64th element "@", whithout any problem
The error on visual studio

Some people Asked me to add the code part where it's not functionning :
void lzw_compress(dico *p_pRoot, char * path)
{
    FILE *pFile = NULL, *pCompFile = NULL;

    int len_c = 0, size_tamp = 0, i = 0, masked_tamp = 0, tamp_to_write = 0, index_tamp = 0, a;
    unsigned char char_tamp = 0, cAndTamp[1024] = { 0 }, tampon[1024] = { 0 }, c = '\0', temp[2] = { 0 };

    char test[128] = { 0 };

    pFile = fopen(path, "r+");
    if (!pFile)
    {
        printf("problem while opening file to compress");
        return;
    }

    size_t len = strlen(path);      //creation of the output file name : paht+ ".lzw"
    unsigned char *compress_name = malloc(len + 4 + 1);
    strcpy(compress_name, path);
    compress_name[len] = '.';
    compress_name[len + 1] = 'l';
    compress_name[len + 2] = 'z';
    compress_name[len + 3] = 'h';
    compress_name[len + 4] = '\0';

    pCompFile = fopen(compress_name, "w");  //creation of the output file

    free(compress_name);

    while (1)
    {
        if (feof(pFile))
            break;

        c = freadByte(pFile);

        for (i = 0; i < 1024; i++)
            cAndTamp[i] = 0;

        temp[0] = c;

        strcat(cAndTamp, tampon);
        strcat(cAndTamp, temp);

        strcpy(test, p_pRoot->m_dico[64].m_info);

        a = 0;

        if (is_in_dictionnary(p_pRoot, cAndTamp) > -1)
        {
            strcpy(tampon, cAndTamp);
            a = 0;
        }

        else
        {
            if (is_in_dictionnary(p_pRoot, tampon) < 256)   //write the character in the file
            {
                char_tamp = tampon[0];
                fwrite(&char_tamp, sizeof(char), 1, pCompFile);
                a = 0;
            }

            else
            {

                a = 0;

                index_tamp = is_in_dictionnary(p_pRoot, tampon);

                a = 0;

                for (i = 0; i < p_pRoot->m_size; i++)
                {
                    mask = 1 << i;
                    masked_tamp = index_tamp & mask;
                    tamp_to_write = masked_tamp >> i;

                    fwriteBit(tamp_to_write, pCompFile);
                    flush(pCompFile);

                }
            }

            strcpy(test, p_pRoot->m_dico[64].m_info);   //HERE IT'S OK

            add_dictionnary(p_pRoot, cAndTamp, size_tamp + 1);  //add the string tamp + read byte in the dictionnay

            strcpy(test, p_pRoot->m_dico[64].m_info);       //HERE IT IS NOT OK

            strcpy(tampon, temp);
        }

        strcpy(test, p_pRoot->m_dico[64].m_info);
        size_tamp = is_in_dictionnary(p_pRoot, tampon);
    }

    if (tampon < 256)   //write the character in the file
    {
        char_tamp = (char)tampon;
        fwrite(&char_tamp, sizeof(char), 1, pCompFile);
    }

    else
    {
        index_tamp = is_in_dictionnary(p_pRoot, tampon);
        for (i = 0; i < p_pRoot->m_size; i++)
        {
            mask = 1 << i;
            masked_tamp = index_tamp & mask;
            tamp_to_write = masked_tamp >> i;

            fwriteBit(tamp_to_write, pCompFile);
            flush(pCompFile);
        }
    }

    fclose(pFile);
    fclose(pCompFile);

}

The fucnction that where I think there is a problem
void add_dictionnary(dico * p_pRoot, char * p_string, int p_stringSize)
{
    p_pRoot->m_index++;

    if (p_pRoot->m_index ==  pow(2, p_pRoot->m_size))
        realloc_dictionnary(p_pRoot);

    p_pRoot->m_dico[p_pRoot->m_index].m_info = (char*)calloc(p_stringSize, sizeof(char));
    strcpy(p_pRoot->m_dico[p_pRoot->m_index].m_info, p_string);

}

Another thank you guys !

A: I showed again the program to my teacher and he found the problem !
The problem is that i never use malloc and rarely use realloc so here was the problem :
void realloc_dictionnary(dico * p_pRoot)
{
    int real = p_pRoot->m_size + 1;
    int size = pow(2, real);

    printf("index %d, previous pow %d, new power %d, size %d\n", p_pRoot->m_index, p_pRoot->m_size, real, size);

    p_pRoot->m_dico = (code*) realloc(p_pRoot->m_dico, size);

    p_pRoot->m_size = real;
}

size in a number of bits, ...
So the correction is : size * sizeof(code)!
void realloc_dictionnary(dico * p_pRoot)
{
    int real = p_pRoot->m_size + 1;
    int size = pow(2, real);

    printf("index %d, previous pow %d, new power %d, size %d\n", p_pRoot->m_index, p_pRoot->m_size, real, size);

    p_pRoot->m_dico = (code*) realloc(p_pRoot->m_dico, size * sizeof(code));

    p_pRoot->m_size = real;
}

I would like to first of all say sorry because of this so little errror and also a big thanks for your great patience !


text:
Q: Bootstrap Rowspan Alignment I want to align my elements on my site like on the picture I attached.
I want to achieve something like you can do with col and row-span with tables in HTML.
I'm using bootstrap 4.
I tried to make it in the same row but it won't fit in the 12 cols that bootstrap allows, also it can't fit because of the carousel.
I'm a beginner and I can't find the solution.
Thanks for the help.
Images:
Current state
Goal
HTML Code:

Üdvözöljük Városunk weboldalán!

                            Előző

                            Következő

Turizmus

Eseménynaptár

Elhelyezkedés

Látnivalók, nevezetességek

Strandfürdő

Szálláshelyek

Gyorslinkek

A Polgármesteri Hivatal ügyfélfogadása

Rendelettár

Képviselő-testület

A Jász-Nagykun-Szolnok Megyei Kormányhivatal Járási Hivatala

Háziorvosok, fogorvosok rendelési ideje

Hirdetmények

Térfigyelő rendszer

WIFI pontok

Beruházások

Pályázatok

Közérdekű információk

Hirdetmények

Térfigyelő rendszer

WIFI pontok

Beruházások

Pályázatok

Közérdekű információk

A: You can try using only One Row :

Üdvözöljük Városunk weboldalán!

A: Here you go...

<!DOCTYPE html>

  <meta charset='UTF-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Document</title>
  <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css' rel='stylesheet' integrity='sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl' crossorigin='anonymous'>

Üdvözöljük Városunk weboldalán!

            Előző

            Következő

Turizmus

Eseménynaptár

Elhelyezkedés

Látnivalók, nevezetességek

Strandfürdő

Szálláshelyek

Hirdetmények

Térfigyelő rendszer

WIFI pontok

Beruházások

Pályázatok

Közérdekű információk

Gyorslinkek

A Polgármesteri Hivatal ügyfélfogadása

Rendelettár

Képviselő-testület

A Jász-Nagykun-Szolnok Megyei Kormányhivatal Járási Hivatala

Háziorvosok, fogorvosok rendelési ideje

Hirdetmények

Térfigyelő rendszer

WIFI pontok

Beruházások

Pályázatok

Közérdekű információk