text:
Q: Loading a partial view when selecting a control Sorry for the technically incorrect title, i am aware that partial view is more of an MVC term. However i unsure what the equivalent is in WPF.
I have a large form that the users need to complete. In order to assist them i wanted to split the view in two vertically and show helpful information in the right portion of the screen depending on what field they have selected on the left, or load quick select boxes in the right of the view which will then complete the items on the left.
I've been playing around for a few hours and have managed to split the view with a GridSplitter but from here i'm not sure where to go from here.
Could someone give me a few pointers on what to look at so I can progress. In the MVC world I would have had loaded it through Ajax and it would be done.
Update
This question got blocked, honestly im not entirely sure why. The question is valid and seems to be a logical comparison between the two frameworks. Im hoping that the ban is lifted as the answer was exactly what i was looking for and will definitely be helpful to others

A: Good question, and @Andy's comment points you in the correct direction. Here is how I would implement it:
View (MainView.xaml):
<Window x:Class="WpfApp4.MainView"
        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"
        xmlns:local="clr-namespace:WpfApp4"
        mc:Ignorable="d"
        Title="MainView" Height="450" Width="800">
    <Window.DataContext>
        <local:MainViewVM />
    </Window.DataContext>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <StackPanel Orientation="Vertical" VerticalAlignment="Center" HorizontalAlignment="Center">
            <TextBlock Text="Box 1" />
            <TextBox MinWidth="200" Name="TextBox1" GotFocus="TextBox1_GotFocus" />
            <TextBlock Text="Box 2" />
            <TextBox MinWidth="200" Name="TextBox2" GotFocus="TextBox2_GotFocus" />
        </StackPanel>
        <ContentControl Grid.Column="1" Content="{Binding SelectedUserControl}" />
    </Grid>
</Window>

Code behind (MainView.xaml.cs):
using System.Windows;

namespace WpfApp4
{
    /// <summary>
    /// Interaction logic for MainView.xaml
    /// </summary>
    public partial class MainView : Window
    {
        public MainView()
        {
            InitializeComponent();
        }

        // I handle these in the code behind since this is pretty UI dependent.
        private void TextBox1_GotFocus(object sender, RoutedEventArgs e)
        {
            ((MainViewVM)DataContext).ChangeView(0);
        }

        private void TextBox2_GotFocus(object sender, RoutedEventArgs e)
        {
            ((MainViewVM)DataContext).ChangeView(1);
        }
    }
}

ViewModel MainViewVM.cs:
using GalaSoft.MvvmLight;
using System.Collections.Generic;
using System.Windows.Controls;

namespace WpfApp4
{
    public class MainViewVM : ObservableObject
    {
        private UserControl _SelectedUserControl;
        public UserControl SelectedUserControl
        {
            get => _SelectedUserControl;
            set => Set(ref _SelectedUserControl, value);
        }

        public List<UserControl> ViewOptions { get; set; }

        public MainViewVM()
        {
            ViewOptions = new List<UserControl>()
            {
                new Box1View(),
                new Box2View()
            };
            ChangeView();
        }

        public void ChangeView(int index = 0)
        {
            if (index < ViewOptions.Count && index >= 0)
            {
                SelectedUserControl = ViewOptions[index];
            }
        }
    }
}

Then my 2 UserControls...
Box1View.xaml
<UserControl x:Class="WpfApp4.Box1View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfApp4"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid Background="Yellow">
        <TextBlock Text="Box 1" />
    </Grid>
</UserControl>

Box2View.xaml
<UserControl x:Class="WpfApp4.Box2View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfApp4"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid Background="Pink">
        <TextBlock Text="Box 2" />
    </Grid>
</UserControl>

Here are what the two views look like:


text:
Q: How to upgrade resource to admin user role I create an admin user role from setup using this code,
$role=$this->_roleFactory->create();
$role->setName('test')
     ->setPid(0)
     ->setRoleType(RoleGroup::ROLE_TYPE)
     ->setUserType(UserContextInterface::USER_TYPE_ADMIN);

$role->save();
$resource=[
  'Magento_Backend::admin'
];

$this->_rulesFactory->create()
     ->setRoleId($role->getId())->setResources($resource)->saveRel();

But I want to add a new resource to this role, using UpgradeData.
Is there any solution?

A: I do it, using this code :
$role = $this->_roleCollection->addFieldToFilter('role_name', 'test')->getFirstItem();
$resource = $this->_aclRetriver->getAllowedResourcesByRole($role->getId());
array_push($resource,
   'Magento_Catalog::products'
);
$this->_rulesFactory->create()->setRoleId($role->getId())->setResources($resource)->saveRel();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Declaring movements to symbols from other classes I have created three classes in my project (beginning of a game) and I am very new to AS3.
First I have created a class called player which shall contain the movement of ball_A.
Then I have created a class called enemy which shall contain the movement of ball_B.
in my main class I have created references to the player and enemy classes and trying to assign ball_A.x and ball_A.y coordinates according to my player class and the same for enemyclass.
this is my main class.
package
{
import flash.display.*;
import flash.events.*;
import flash.ui.Keyboard;

public class Main extends MovieClip
{
    public var playerClass:player;
    public var enemyClass:enemy;

    public function Main()
    {
        playerClass = new player();
        enemyClass = new enemy();
        addChild(playerClass);
        addChild(enemyClass);

        ball_A.x = playerClass.ball_A_x;
        ball_A.y = playerClass.ball_A_y;

        ball_B.x = enemyClass.ball_B_x;
        ball_B.y = enemyClass.ball_B_y;

    }//Public function

}// Class

}// Package

this is my player class:
    package  {
import flash.display.*;
import flash.events.*;
import flash.ui.Keyboard;

public class player extends MovieClip
{

    var leftIsPressed:Boolean = false;
    var rightIsPressed:Boolean = false;
    var upIsPressed:Boolean = false;
    var downIsPressed:Boolean = false;
    var spaceIsPressed:Boolean = false;
    var rightCtrlIsPressed:Boolean = false;
    var speed:Number = 15;
    var vx:Number = 0;
    var vy:Number = 0;
    var ball_A_x:int = 0;
    var ball_A_y:int = 0;

    public function player()
    {
        this.addEventListener(Event.ADDED_TO_STAGE, initialize);
    }

        private function initialize(e:Event):void
        {
            //EventListeners
            this.removeEventListener(Event.ADDED_TO_STAGE, initialize);
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
            stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
            stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);

        }

        //Functions

        function keyDownHandler(e:KeyboardEvent):void
        {
            switch(e.keyCode)
            {
                case Keyboard.LEFT : leftIsPressed = true; break;
                case Keyboard.RIGHT : rightIsPressed = true; break;
                case Keyboard.UP : upIsPressed = true; break;
                case Keyboard.DOWN : downIsPressed = true; break;
                case e.keyCode = 163 : rightCtrlIsPressed = true; break;

            }

        }

        function keyUpHandler(e:KeyboardEvent):void
        {
            switch(e.keyCode)
            {
                case Keyboard.LEFT : leftIsPressed = false; break;
                case Keyboard.RIGHT : rightIsPressed = false; break;
                case Keyboard.UP : upIsPressed = false; break;
                case Keyboard.DOWN : downIsPressed = false; break;
                case e.keyCode = 163 :  rightCtrlIsPressed = false; break;
            }

        }

        function enterFrameHandler(e:Event):void
        {
            vx = -int(leftIsPressed)*speed + int(rightIsPressed)*speed;
            vy = -int(upIsPressed)*speed + int(downIsPressed)*speed;

                ball_A_x += vx;
                ball_A_y += vy;

                if(ball_A_x >= 530)
                {
                    ball_A_x = 0;
                }
                else if(ball_A_x <= 0)
                {
                    ball_A_x = 530;
                }
                if(ball_A_y >= 370)
                {
                    ball_A_y = -28;
                }
                else if(ball_A_y <= -28)
                {
                    ball_A_y = 370;
                }

        }

    //}//Public function

}//Class
}//Package

I want to make the two symbols in my .fla which is connected to my main class have the functions of player class and enemy class. (didn't show enemy since the code is basically the same)
but when I try to use this code I get this error:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at player()
at Main()

I think this is because of my eventListeners returns nothing since they are void. how can I solve this problem without having to write all the movements commands in one class?

A: I think the problem is that you're referring to 'stage' within Player, before Player is added to the stage. In fact Player is NEVER added to the stage so, as it is, Player will never have access to stage.
In Main, add your Player and Enemy to the stage:
addChild(playerClass);
addChild(enemyClass);

and in the constructor functions of your Player and Enemy classes, add:
this.addEventListener(Event.ADDED_TO_STAGE, initialize);

private function initialize(e:Event):void {
this.removeEventListener(Event.ADDED_TO_STAGE, initialize);
... other event listeners here, now that Player is on stage
}


text:
Q: ggplot(data = df1) with added ggMarginal (data = df2) I aim to create a ggplot with Date along the x axis, and jump height along the y axis. Simplistically, for 1 athlete in a large group of athletes, this will allow the reader to see improvements in jump height over time.
Additionally, I would like to add a ggMarginal(type = "density") to this plot. Here, I aim to plot the distribution of all athlete jump heights. As a result, the reader can interpret the performance of the primary athlete in relationship to the group distribution.
For the sack of a reproducible example, the Iris df will work.
'''
library(dplyr)
library(ggplot2)
library(ggExtra)

df1 <- iris %<%
       filter(Species == "setosa")

df2 <- iris

 #I have tried as follows, but a variety of error have occurred:

 ggplot(NULL, aes(x=Sepal.Length, y=Sepal.Width))+
 geom_point(data=df1, size=2)+
 ggMarginal(data = df2, aes(x=Sepal.Length, y=Sepal.Width), type="density", margins = "y", size = 6)

'''
Although this data frame is significantly different than mine, in relation to the Iris data set, I aim to plot x = Sepal.Length, y = Sepal.Width for the Setosa species (df1), and then use ggMarginal to show the distribution of Sepal.Width on the y axis for all the species (df2)
I hope this makes sense!
Thank you for your time and expertise

A: As far as I get it from the docs you can't specify a separate data frame for ggMarginal. Either you specify a plot to which you want to add a marginal plot or you provide the data directly to ggMarginal.
But one option to achieve your desired result would be to create your density plot as a separate plot and glue it to your main plot via patchwork:
library(ggplot2)
library(patchwork)

df1 <- subset(iris, Species == "setosa")
df2 <- iris

p1 <- ggplot(df1, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(size = 2)

p2 <- ggplot(df2, aes(y = Sepal.Width)) +
  geom_density() +
  theme_void()

p1 + p2 +
  plot_layout(widths = c(6, 1))


text:
Q: Unusual time zones in ipligence pro We have been using IPLEGENCE Database pro to get user timezone based on IP address. Here I have a few unusal time zone off sets. Which are listed below

*

*EST+1

*PST-2

*PST-1

*GMT+12.75

I am not sure what exactly above listed off sets.
Could some one please help me in converting the above time zones to UTC.
Thanks for your time.

A: Here is a list of time zones. EST is almost always (excepting for those DST overlaps) GMT-5. And GMT is either on UTC, or an hour off (again, DST).
EST+1 = GMT-4
PST-2 = GMT-10
PST-1 = GMT-9

The best you can probably do, if you want to convert it to UTC, is to use the DateTime object.

A: That is rather a strange way to denote time zones.  My guess is that GMT+12:45 refers to the Chatham Islands.  Not sure about the others, they could be anywhere.
IMHO, there are a few problems with this type of data:

*

*Time zones are not fixed offsets.  When the database refers to EST, they probably mean "US Eastern Time".  But that could refer to -5 hours offset for Eastern Standard Time (EST), or -4 hours for Eastern Daylight Time (EDT).  By calling it "EST" in the data, they are fixing it to -5, when in fact it might be -4.  See "Time Zone != Offset" in the timezone tag wiki.

*Time zone abbreviations can be ambiguous.  For example, how do I know that "EST" really refers to USA's Eastern Standard Time (-5)? It might refer to Australia's Eastern Standard Time (+10).  There is a list here, and you can see there are lots of time zones with the same abbreviation.

*IP Geolocation is a "best guess", and does not have the kind of accuracy needed to determine time zone.  The time zone in these databases may match the listed coordinates, but you have very little guarantee that the user is actually at those coordinates.  It might be giving you the location of a proxy server or network router.  This is especially true on corporate networks, where (in some cases) you have an IP in a corporate office in another city and all Internet traffic filters through that IP.  You're going to get the timezone of that corporate office - not the time zone of the user.  You can read more about IP Geolocation Accuracy here and here.
If you know the coordinates of the user by some other means, such as from GPS data on a cell phone, then you can use one of the several different techniques described here.


text:
Q: Getting MySQL Schemas for All Tables I want to download/backup the schema of an entire MySQL database. Is there a way to easily do this? I haven't had much luck using a wildcard, but that could be an error on my part.

A: How about using mysqldump?
mysqldump -u root -p[password] [db_name] > backupfile.sql

A: I would use the --no-data option to mysqldump to dump the schema and not table data.
 mysqldump --no-data [db_name] -u[user] -p[password] > schemafile.sql

A: Login as root, then
show databases; # lists all databases
use information_schema; # connect to the mysql schema
show tables;
select * from tables;

Everything you need is in the information_schema schema.  If all you want to do is backup the db, use the builtin dump/restore capabilities.

A: If you want to see all the tables from a schema in MySQL then you can use
SHOW TABLES FROM MY_DATABASE;


text:
Q: VBA Excel Mac Dictionary Class on Mac Get Keys() Attribute The Get Keys() attribute is slow with a decent sized data set.  Is there a way to assign keys without looping through each record individually?
I can only find examples of for or do loops to assign keys individually.

Public Property Get Keys() As String()

'Here is the existing code (status bar updated only so the user knows the
'program is still working).

    Dim vlist() As String, i As Long, myKey As Variant, myArr() As Variant, okVP As KeyValuePair, StatBar As String
    StatBar = Application.StatusBar

    If Me.Count > 0 Then
        ReDim vlist(0 To Me.Count - 1)

        For i = LBound(vlist) To UBound(vlist)
            Set okVP = KeyValuePairs(i + 1)
            vlist(i) = okVP.Key
            If i Mod 5000 = 0 Then
                Application.StatusBar = StatBar & ": " & "Gathering Keys: " & Format(i, "#,##0") & " of " & Format(UBound(vlist), "#,##0")
'                Debug.Print i & " of " & UBound(vlist)
                DoEvents
            End If
        Next i
        Keys = vlist
    End If
    Application.StatusBar = StatBar
End Property

Current approach takes >5 min for ~135K records.

A: No, you can't avoid iterating the items. Under Windows you could probably leverage CopyMemory Win32 API to bulk-copy arrays, but I wouldn't trust these functions to work on a Mac.
Consider swapping your KeyValuePair-based Dictionary with Tim Hall's drop-in Dictionary replacement.
Now, hard to tell without seeing the class' [_NewEnum] implementation and default member (you have those?), but as far as I can tell you're iterating an object collection with a For...Next loop - and that is the slowest possible way to iterate any object collection.
Object collections want to be iterated with For Each...Next. Just that, could slash the run time by several orders of magnitude.
Updating the Application UI and running DoEvents (even once every 5K iterations) is further slowing down the loop... and this isn't the kind of thing you want to be doing in a Property Get member anyway.
Looks like KeyValuePairs is a collection of KeyValuePair objects? 135K of them means quite a lot of overhead - in .NET a KeyValuePair is a struct (value type), not an object (reference type); they are optimized differently, and perform differently too. Regardless, if you have a collection of KeyValuePair objects, the fastest way to iterate them is with a For Each loop.
ReDim result(0 To KeyValuePairs.Count - 1)
Dim i As Long
Dim kvp As KeyValuePair
For Each kvp In KeyValuePairs
    result(i) = kvp.Key
    i = i + 1
Next

Moreover, because of how arrays work in VBA and all the headaches associated with typed arrays, I'd think returning one would be safer if wrapped in a Variant pointer, or "returned" through a ByRef parameter (but that wouldn't work for a Property Get member).


text:
Q: C++ class interface to pass-through to another member variable Let's say I have a class Param defined like this:
class Param {
public:
    std::vector<double> lb;
    std::vector<double> mid;
    std::vector<double> ub;
    int level;
};

The purpose of this class is to define lower- and upper-bounds (lb and ub, respectively) and a midpoint estimate for different parameters.  Assume that for a given object, lb, mid, and ub have the same number of elements.
Now, if level<0, I want to use the lb estimates.  If level==0, I want to use the mid estimates.  Otherwise (if level>0), I want to use the ub estimates.
My question is: how can I create a single member function (or something akin to a reference member variable) that will automatically "pass through" to the appropriate member std::vector<double> based on the value of level?
For example, if I have a function
void f(const std::vector<double>& X);
or
void g(std::vector<double>& X);
I want to be able to do something like this:
Param myParam;
// set values of myParam.lb, myParam.mid, and myParam.ub, and myParam.level
f(myParam.__?__);
g(myParam.__?__);

A: You can add cast operators to your class:
class Param {
    //...

    operator std::vector<double>& () {
        if( level < 0 ) return lb;
        if( level > 0 ) return ub;
        return mid;
    }

    operator const std::vector<double>& () const {
        if( level < 0 ) return lb;
        if( level > 0 ) return ub;
        return mid;
    }
};

Now you can call like this:
f(myParam);
g(myParam);

A: Quite simple.
std::vector< double > & getBound() {
    if ( level < 0 ) return lb;
    if ( level == 0 ) return mid;
    return ub;
}

Add a const overload returning a const & reference if necessary.
I would recommend against doing anything trickier than this. If you want to get something from an object, mentioning a function is usually better than defining a function which is automatically called despite not being named.
(Note: I submitted this more than three hours ago, but connection difficulties delayed it, hence the redundancy.)


text:
Q: Loading an animation during Retrofit 2 requests I am making an android application with a lot a activities and Retrofit 2 requests and I want to know what are the best practices for the loading animations during a request ?
Actually, I use my loading animation like this :
public void getLogin() {

      showDialog();

      retrofitService.getLogin(new Callback<SignInResponse>() {
         @Override
         public void onResponse(Call<SignInResponse> call, Response<SignInResponse> response) {

             hideDialog()
              //My stuff
          }

         @Override
         public void onFailure(Call<SignInResponse> call, Throwable t) {

              hideDialog()
              //My stuff again
          }
 });
}

public void showDialog() {

      ProgressDialog mProgressDialog = new ProgressDialog(this); //Which is deprecated
      mProgressDialog.setIndeterminate(true);
      mProgressDialog.setMessage("Loading...");

      if(mProgressDialog != null && !mProgressDialog.isShowing())
          mProgressDialog.show();
}

public void hideDialog() {

      if(mProgressDialog != null && mProgressDialog.isShowing())
          mProgressDialog.dismiss();
}

I know that ProcessDialog is deprecated since API26 so if you have better ideas, I'll take them !
But it seems like I need to copy past every time this code when I do a requests and I wonder there is a better way to do that.
Thanks for your help :)


text:
Q: Can i get attribute value as a result soapCall? I call soap as follows:
 $context = stream_context_create([
    'ssl' => [
    'verify_peer'       => false,
    'verify_peer_name'  => false,
    'allow_self_signed' => true
    ]
 ]);
 $soapClient = new SoapClient('my_url', [
     'connection_timeout' => '60',
     'stream_context'     => $context,
     'trace'              => 1,
     'cache_wsdl'         => WSDL_CACHE_NONE
 ]);
 $response = $soapClient->__soapCall('create', array($soapParameters));

Result should be something like this:
<SOAP>
  <BEGIN>
    <STATUS Value="OK">
    <CATEGORY Value="12">
  </BEGIN>
</SOAP>

But here is result:
{
 "BEGIN":{
   "STATUS":"",
   "CATEGORY":""
  }
}


text:
Q: What are some alternative phrases to say "for more information"? Lets say, I have written a answer on SE and I have added some citations at the end of it. What words should I use to refer to it (except for more information)? I generally use the following:

For more information, refer to:

*

*[citation]

*[citation]

What other words or phrases may I use to express the same meaning?

A: Two shorthand notes that are used in scholarly writing could come in useful here:

*

*cf.

The abbreviation cf. derives from the Latin verb conferre, to bring together (from which confer is the conjugation of the imperative form), while in English it is commonly read as "compare". The abbreviation advises readers to consult other material, usually for the purpose of drawing a contrast.

*Viz.

The abbreviation viz. (or viz without a full stop), short for the Latin videlicet, is used as a synonym for "namely", "that is to say", "to wit", or "as follows". It is typically used to introduce examples or further details to illustrate a point.


text:
Q: new PR includes changes from older PR in Github I have created 2 PR's to a repo; I was making changes to the new PR and did a
git pull upstream/master

and then create a new branch with git checkout -b <new-Pr>
and modified a file and did git add . and then git commit and git push origin <new-Pr> by doing this my files which I modified from older PR(which was not needed) also appeared in the new PR. How can I rectify the same?

A: You could rebase on top of another base branch:
git rebase --onto new-base old-pr-branch new-pr-branch

A: So, after much headaches I found this as a solution
git reflog

which shows my commits and rebased logs
then i choose to go back to the state by the help of comments and
git reset --hard HEAD@{80}

Then i finally do
git push --force


text:
Q: datetime vanishes from the indicator-datetime datetime doesn't appear in the bar by default on Ubuntu 15.04.
After installing indicator-datetime and running the following comment it starts working:
$ dconf reset -f /com/canonical/indicator/datetime/
But if you select "Date and Month" from in Time & Date settings, it vanishes again.


text:
Q: как сделать запрос на веб сервис с помощью apache camel Здраствуйте.  У меня есть файлик request.xml с таким содержимым:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://localhost:8080/webservices">
   <soapenv:Header/>
   <soapenv:Body>
      <web:deviceRequest>
         <!--Optional:-->
         <devices>
                <device id="1" value="123" date="2002-05-30T09:00:00"/>
                <device id="2" value="123" date="2004-05-30T09:00:00"/>
                <device id="3" value="123" date="2006-05-30T09:00:00"/>
                <device id="4" value="123" date="2008-05-30T09:00:00"/>
                <device id="5" value="123" date="2010-05-30T09:00:00"/>
         </devices>
      </web:deviceRequest>
   </soapenv:Body>
</soapenv:Envelope>

Мне нужно отправить запрос на веб сервис.
У меня все работает если я отправляю запрос на обычной яве.
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
        String url = "http://localhost:8080/ws";
        SOAPMessage soapResponse = soapConnection.call( /* содержимое файлика request.xml сконвертированное в SOAPMessage */ request  , url);
        System.out.print("Response SOAP Message:");
        soapResponse.writeTo(System.out);
        soapConnection.close();

Выше приведенный код работает

Но мне нужно отправить содержимое посредством apache camel, я делаю так.
CamelContext camelContext = new DefaultCamelContext();
camelContext.addRoutes(new RouteBuilder() {
    @Override
    public void configure() {
        // uploadfolder - папка где лежит request.xml
        from("file:uploadfolder").to("spring-ws:http://localhost:8080/ws");
    }
});
camelContext.start();

Вот Pom.xml
<dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-core</artifactId>
        <version>2.18.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-spring-ws</artifactId>
        <version>2.18.1</version>
    </dependency>

При отправке через camel ничего не работает и пишется такое сообщение:
[http-nio-8080-exec-3] WARN  o.s.ws.server.EndpointNotFound - No endpoint mapping found for [SaajSoapMessage {http://schemas.xmlsoap.org/soap/envelope/}Envelope]

org.springframework.ws.client.WebServiceTransportException:  [404]

Помогите понять чего он хочет. Ведь если на обычной яве все нормально отправляется, значит проблема не в веб сервисе ?

A: В принципе чтобы отправить файл с уже готовым реквестом можно обойтись одним camel-http.
from("file:uploadfolder").convertBodyTo(String.class).removeHeaders("*").setHeader("CamelHttpMethod", constant("POST")).setHeader("Content-Type", constant("text/xml;charset=UTF-8")).setHeader("SOAPAction", constant("")).to("http://localhost:8080/ws");


text:
Q: Ordered pairs in a power set The exercise 48 of Chapter 3 in Enderton's Axiomatic Set Theory says:
Let $T$ be the set $$\{\varnothing, \{\varnothing\}\}.$$
Find all of the ordered pairs, if any, in
$$\mathcal{P}T=\{\varnothing, \{\varnothing\}, \{\{\varnothing\}\}, T\}.$$
The set $T$ does not seem anything like the Kuratowski's definition.
I think Enderton is trying to say "There is an ordered pair."
I just can't see how there could be an ordered pair since $\mathcal{P}T$ is not a function or relation.
Could you please help me see?

A: The set-theoretic ordered pair $(a,b)$ is $\{\{a\},\{a,b\}\}$. Note that this is $$\{\{a\},\{a,a\}\}=\{\{a\},\{a\}\}=\{\{a\}\}$$ if $a=b$. So you have at least one pair in ${\mathcal P}(T)$, namely $(\emptyset,\emptyset)=\{\{\emptyset\}\}$. Since the empty set is not an ordered pair, and no element of an ordered pair is empty, this is the only ordered pair in ${\mathcal P}(T)$.


text:
Q: Thread vs Backgroundworker I am working on C# Windows Application and I need to communicate with a device.
While I need to send command to device and receive response from it. In this feature I need to continuously send command and receive response from the device. \
For this which will be better to use , background worker or thread?

A: Backgroundworker has its own advantages like it uses thread from Thread Pool and it is for specific purpose, which is to do time consuming job in the background, also it is very easy to use. In Backgroundworker you have RunWorkerCompleted event which will be on the main thread, so you can update your view in that. And expensive stuff you can run under DoWork event. DoWork run on the background thread from the Thread Pool.

I need to continuously send command and receive response from the
  device.

For your requirement, I suggest you to check TaskSheduler.


text:
Q: Есть ли способ управлять загрузкой ответа WebResponse? Здравствуйте!
Необходимо асинхронно получать ответ с сервера и, при этом, знать на каком этапе находится этот самый ответ, то есть сколько в данный момент загружено байт. Что бы, например, в любой момент можно было бы ограничить скорость загрузки или прервать получение ответа или просто следить за прогрессом загрузки ответа и тп. Возможно ли это вообще?
Нашел в интернете пример с wpf, но в консольной версии такое повторить не удается. В принципе, мне без разницы что использовать - webclent или webresponse или другие средства если они есть.
Если кто-то сталкивался когда-то с такой задачей - отзовитесь.


text:
Q: trying to install teamspeak3 So, I followed some threads created here but nothing solved my problem.
I downloaded the 64bit version of teamspeak3, and did this:

*

*Opened terminal

*Went to the folder where my teamspeak was downloaded (desktop, so I did cd Desktop)

*did this command: chmod u+x ./TeamSpeak3-Client-linux_x86-3.0.12.run

*Then this: ./TeamSpeak3-Client-linux_x86-3.0.12.run
OK, pressed Q and yes, installed and the system created a new folder.
The problem starts here: when I try to open ts3client_linux_amd64, nothing happens. I already changed the propriets to allow executing the file as a program but nothing seems to happen.
What should I do?

A: Download Teamspeak. Open a terminal and run the following commands:
sudo cp TeamSpeak3-Client-linux_x86-3.0.12.run /opt
cd /opt
sudo chmod +x TeamSpeak3-Client-linux_x86-3.0.12.run
sudo TeamSpeak3-Client-linux_x86-3.0.12.run

The script creates a folder with the name TeamSpeak3-Client-linux_x86. Start the client with:
TeamSpeak3-Client-linux_x86/ts3client_runscript.sh

Create a desktop file:
nano ~/.local/share/applications/teamspeak.desktop

Add the following content:
[Desktop Entry]
Type=Application
Name=Teamspeak 3 Client
Comment=Teamspeak 3 Client
Icon=teamspeak3
Exec=/opt/TeamSpeak3-Client-linux_x86/ts3client_runscript.sh
Terminal=false
Categories=Games;
StartupWMClass=Teamspeak

The entry Icon=teamspeak3 you need to replace it with an icon of your choice. In my icon theme is an icon for Teamspeak 3.


text:
Q: VueJS VITE & Laravel - Socket io is not a function I discover "VITE" and vue3, I have always used mix and vue2 until now.
I have this error:
io.on is not a function.
bootstrap.js
    import Echo from "laravel-echo";
    import {io} from "socket.io-client";
    window.io = io;
    if (typeof io !== 'undefined') {
        window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: window.location.hostname + ':6001',
    });

app.js
import './bootstrap';
import { createApp } from 'vue'
import Test from './components/Test.vue'
import App from './components/App.vue'

const app = createApp({})

app.component('test-test', Test)

app.mount('#app')

Test.vue
mounted() {
console.log(io);

io.on("connection", (socket) => {
    socket.join("room1");
});

Echo.channel('test')
.listen('NewMessage', (e)=>{
    console.log(e);
})

},


text:
Q: How to Input UIColor to User defaults?
Possible Duplicate:
Saving UIColor to and loading from NSUserDefaults

I think to init user defaults, make NSDictionary, input data, and refisterDefaults.
But this code has error.
//if UserFilter entry is nothing, create.
NSDictionary *defaultFilter = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:@"UserFilter"];
[userDefaults registerDefaults:defaultFilter];

//if UserBadgeColor entry is nothing, create.
UIColor *color = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
NSValue *valColor = [NSValue value:&color withObjCType:@encode(UIColor)];
NSDictionary *defaultBadgeColor = [NSDictionary dictionaryWithObject:valColor forKey:@"UserBadgeColor"];
[userDefaults registerDefaults:defaultBadgeColor];

Running, UserFilter part has no problem. But UserBadgeFilter part has error.
Error line is last.
Thanks.

A: From the manual:

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData.

But you can simply use NSData, so in your case:
UIColor *color = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
NSData* colorData= [NSKeyedArchiver archivedDataWithRootObject: color];
NSDictionary *defaultBadgeColor = [NSDictionary dictionaryWithObject: colorData forKey:@"UserBadgeColor"];
[userDefaults registerDefaults:defaultBadgeColor];

And when you read from the defaults, decode back the data to UIColor using NSKeyedUnarchiver.


text:
Q: in MYSQL, get only those columns that have values that are the same I have a table showing what pieces of a puzzle a user has in Boolean  like...
client   |  col A | col B | col C | col D | col E
john Doe |    1   |   1   |   0   |   0   |   1
Jane Deer|    0   |   1   |   0   |   1   |   0

And I can grab the row from the Db.
// Get puzzle pieces
$requery = "SELECT * FROM puzzletbl WHERE client_id = '$client_id' LIMIT 1";
$reresult = mysqli_query($dbc, $requery);

// Check for missing pieces
if ($reresult){
    while ($row = mysqli_fetch_array($reresult, MYSQLI_ASSOC)) {
        $status = array("NO", "OKAY");

    } // END WHILE
} // END  IF REresult

I need to get only those columns with 0 (they are missing piece) so I can  add that to an email letting them know what is missing.

A: Loop through $row, and test whether the value is 0.
while ($row = mysqli_fetch_array($reresult, MYSQLI_ASSOC)) {
    $zero_cols = array();
    foreach ($row as $col => $val) {
        if ($col == "client") {
            $client = $val;
        } elseif ($val == 0) {
            $zero_cols[] = $col;
        }
    }
    // Send mail to $client with $zero_cols info
}


text:
Q: How to unshelve changes into another branch using TFS? I am working on an application where I want to unshelve changes from one branch to another branch using TFS. I am attaching different images which contain my branches, shelve set name, and shelve set details. I want to unshelve changes at 05-PartnerIntergration branch.
Shelve Set name is Krone Integration
Here are the branches shown below in image.


text:
Q: Entity Framework automatic relation linking is not working in .net Core 3.0  public class tbl_User
    {
        [Key]
        public int userId { get; set; }
        public string Name { get; set; }
        [Display(Name = "Branch")]
        public int masterbranchId { get; set; }
        //[ForeignKey("masterbranchId")]
        public virtual tbl_MasterBranch MasterBranch { get; set; }
}

This is the class and there is another class for tbl_MasterBranch . When we return users link MasterBranch is null. This was worked fine in MVC5.

A: You're currently (and the MVC5 app was formerly) relying on lazy loading. A key difference in EF Core is that lazy loading must be explicitly enabled via:
services.AddDbContext<MyContext>(o =>
    o.UseSqlServer(Configuration.GetConnectionString("Default"))
     .UseLazyLoadingProxies());

However, you should really avoid lazy loading. For the convenience it may add, there's a ton of potential pitfalls that can severely impact your application performance and hammer you database. If you want related entities included, it's best to eagerly load them when querying:
var users = await _context.Users.Include(x => x.MasterBranch).ToListAsync();


text:
Q: How to prevent modal click-through? I have a modal that looks something like this:

Title Text

Body Text

        <button onClick={this.toggleView} className="toggle-view">Switch View</button>

With the click code like the following:
toggleView = e => {
  e.stopPropagation();

  this.setState(prevState => ({ view: !prevState.view}));
}

But for some reason (despite the stop propagation), when I click the button, sometimes the parent's event handlers are still being activated.
That is, there is a table behind the modal with click-able rows, and when I click the Toggle button in the modal, not only is that button clicked, but also the table row behind the behind (which also has its own click event handlers)
The stranger thing is that this only sometimes happens, and only happens on mobile. Try as I might, I can't replicate the behavior on my PC in Chrome or Firefox.
What could be causing this?

A: You're using the onclick handler, which essentially ignores all the propegation through down-up events. Try using onmousedown. Chances are the thing underneath the modal has a down or up event. Learn about "bubbling" : What is event bubbling and capturing?
<button onMouseDown={this.toggleView} ... yada yada

Using the mousedown will allow you to prevent bubbling through the stopPropegation, and maybe also look into stopImmediatePropegation -- which prevents other listeners of the same type (click, down, up) from getting called: https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation


text:
Q: Capistrano: RSolr::Error::Http - 404 Not Found when reindexing Solr I have not found any concrete examples that could possibly help address my problem. I previously had the sunspot gem working with Capistrano before my update to Rails 4 and Ruby 2. Any help sorting this error out would be greatly appreciated.
Gemfile:
gem 'sunspot_rails', :github => 'hsbt/sunspot', :branch => 'enabled-rails4'
gem 'sunspot_solr', :github => 'hsbt/sunspot', :branch => 'enabled-rails4'

.gitignore
solr/pids
solr/default

config/deploy.rb
namespace :deploy do
  task :start do ; end
  task :stop do ; end
  task :restart, :roles => :app, :except => { :no_release => true } do
    run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
  end

  desc "Migrate Database"
  task :migrate_db do
    run "cd #{current_path} && rake db:migrate RAILS_ENV=production"
    run "touch #{current_path}/tmp/restart.txt"
  end

  desc "Create Solr Directory"
  task :setup_solr_data_dir do
    run "mkdir -p #{shared_path}/solr/data"
  end
end

namespace :solr do
  desc "start solr"
  task :start, :roles => :app, :except => { :no_release => true } do
    run "cd #{current_path} && RAILS_ENV=#{rails_env} bundle exec sunspot-solr start --port=8983 --data-directory=#{shared_path}/solr/data --pid-dir=#{shared_path}/pids > /dev/null 2>&1 || true"
  end
  desc "stop solr"
  task :stop, :roles => :app, :except => { :no_release => true } do
    run ("cd #{current_path} && RAILS_ENV=#{rails_env} bundle exec sunspot-solr stop --port=8983 --data-directory=#{shared_path}/solr/data --pid-dir=#{shared_path}/pids > /dev/null 2>&1 || true")
  end
  desc "reindex the whole database"
  task :reindex, :roles => :app do
    stop
    run "rm -rf #{shared_path}/solr/data"
    start
    run "cd #{current_path} && yes | RAILS_ENV=#{rails_env} bundle exec rake sunspot:solr:reindex"
  end
end

after "deploy", "deploy:cleanup", "deploy:migrate_db",'deploy:setup_solr_data_dir', 'solr:start', 'solr:reindex'

Error Message:
  * 2013-06-24 12:19:20 executing `solr:start'
  * executing "cd /home/username/apps/MyApplication/current && RAILS_ENV=production bundle exec sunspot-solr start --port=8983 --data-directory=/home/username/apps/MyApplication/shared/solr/data --pid-dir=/home/username/apps/MyApplication/shared/pids > /dev/null 2>&1 || true"
    servers: ["0.0.0.0"]
    [0.0.0.0] executing command
    command finished in 1349ms
  * executing "cd /home/username/apps/MyApplication/current && yes | RAILS_ENV=production bundle exec rake sunspot:solr:reindex"
    servers: ["0.0.0.0"]
    [0.0.0.0] executing command
 ** [out :: 0.0.0.0] *Note: the reindex task will remove your current indexes and start from scratch.
 ** [out :: 0.0.0.0]
 ** [out :: 0.0.0.0] If you have a large dataset, reindexing can take a very long time, possibly weeks.
 ** [out :: 0.0.0.0]
 ** [out :: 0.0.0.0] This is not encouraged if you have anywhere near or over 1 million rows.
 ** [out :: 0.0.0.0]
 ** [out :: 0.0.0.0] Are you sure you want to drop your indexes and completely reindex? (y/n)
 ** [out :: 0.0.0.0]
 ** [out :: 0.0.0.0] D, [2013-06-24T12:18:59.139035 #2262] DEBUG -- :   SOLR Request (12.2ms)  [ path=#<RSolr::Client:0x00000007003988> parameters={data: <?xml version="1.0" encoding="UTF-8"?><delete><query>type:Project</query></delete>, headers: {"Content-Type"=>"text/xml"}, method: post, params: {:wt=>:ruby}, query: wt=ruby, path: update, uri: http://localhost:8983/solr/default/update?wt=ruby, open_timeout: , read_timeout: , retry_503: , retry_after_limit: } ]
 ** [out :: 0.0.0.0]
 ** [out :: 0.0.0.0] rake aborted!
 ** [out :: 0.0.0.0]
 ** [out :: 0.0.0.0] RSolr::Error::Http - 404 Not Found
 ** [out :: 0.0.0.0]
 ** [out :: 0.0.0.0] Error:     NOT_FOUND
 ** [out :: 0.0.0.0]
 ** [out :: 0.0.0.0]
 ** [out :: 0.0.0.0] Request Data:

A: Looks like your Solr server does not respond to the endpoint you expect. Your URL seems to be:
localhost:8983/solr/default (with the handler being /update under that).
Is there Solr endpoint there? Can you access it manually?
If not, I would recommend changing your start commands to log to a file instead of /dev/null and seeing what exceptions you get.


text:
Q: Print Spooler service terminated unexpectedly Every time I try to install a printer on this one PC, the Spooler crashes and the installation fails.
PC is brand new.
Through troubleshooting, I found out that anytime I try to do anything with the printers, the spooler fails, like trying to delete drivers.
When the spooler crashes, this error is generated:

*

*Faulting application name: spoolsv.exe, version: 6.3.9600.17480, time stamp: 0x54585db9

*Faulting module name: hpb6sy2917_x64gui.dll, version: 13.2.0.0, time stamp: 0x5553b101

*Exception code: 0xc0000005

*Fault offset: 0x00000000000c2f2b

*Faulting process id: 0x10e0

*Faulting application start time: 0x01d11b2357d095b2

*Faulting application path: C:\WINDOWS\System32\spoolsv.exe

*Faulting module path: C:\WINDOWS\system32\spool\DRIVERS\x64\3\hpb6sy2917_x64gui.dll

*Report Id: baaa4645-8716-11e5-be88-8cdcd453c6a8

*Faulting package full name:

*Faulting package-relative application ID:

Obviously, I have tried manually starting the service, and it does start, but as soon as I try anything, it crashes again.
"SFC /Scannow" found errors, but could not fix.
"dism /Online /Cleanup-Image /RestoreHealth" completed successfully.
I'm at my wits end, any help will be appreciated.

A: We had a similar issue today Nov 23 2016- All Win 8 computers spoolers started failing after we distributed an HP M604 with its specific M604 driver.  The M604 driver does not contain hpb6sy2917_x64gui.dll identified in the crash log, another printer on the systems does however - the HP M553.  We resolved by redistributing both he M604 and M553 printers with UPD drivers (v 6.1).  Also had to cleanup fallout in the form of orphaned 'grayed out' print objects - old object names that were no longer in the GPO had to be deleted in Device Manager/printers with SHOW HIDDEN ITEMS switched on.


text:
Q: Reciprocal sums How can I prove the following?
1)$$\sum_{k=0}^{\infty}\frac{1}{F_{2k+1}}=\frac{\sqrt{5}}{4}\theta_{2}^{2}(0,\frac{3-\sqrt{5}}{2}),$$
2)$$\sum_{k=0}^{\infty}\frac{1}{F_{k}^{2}}=\frac{5}{24}(\theta_{2}^{4}(0,\frac{3-\sqrt{5}}{2})-\theta_{4}^{4}(0,\frac{3-\sqrt{5}}{2})+1),$$
Are there good resources in this case?


text:
Q: 502 nginx can't connect to gunicorn server I am so lost as to what is going wrong.
I have nginx & gunicorn running in separate docker containers. Nginx is running on port 80 forwarding to gunicorn on 8000. I get 502 errors from nginx. If I hit port 8000 I get a 200 response from my gunicorn server.
If I take down the nginx docker and start a nginx server on my laptop forwarding traffic to port 8000, everything works fine. Would could be going wrong with the dockerized nginx server setup?
docker-compose.yml
version: '3.3'
services:
  nginx:
    build: ./nginx
    ports:
      - '1337:80'
    depends_on:
      - django-api
  django-api:
    build:
      context: .
      dockerfile: Dockerfile
    command: gunicorn my_app.wsgi:application --log-level verbose --log-file=/var/log/guni --access-logfile=/var/log/gunia --bind 0.0.0.0:8000 --forwarded-allow-ips "*"
    ports:
      - '8000:8000'
    depends_on:
      - mysql
  mysql:
    image: mysql:5
    volumes:
      - type: bind
        source: ./db/docker-entrypoint-initdb.d
        target: /docker-entrypoint-initdb.d
      - type: volume
        source: mysql-data
        target: /var/lib/mysql
    environment:
        MYSQL_ROOT_PASSWORD: toor
    networks:
      - backend
    ports:
      - '3306:3306'
volumes:
  mysql-data:
  static_volume:
networks:
  backend:

gunicorn Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED 1
ENV DJANGO_SETTINGS_MODULE dori.settings.dev
WORKDIR /app
COPY . /app
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt

# Port to expose
EXPOSE 8000

nginx.conf
upstream hello_django {
    server localhost:8000;
}

server {
    listen 80;
    location / {
        proxy_pass http://hello_django;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

A: The issue is in your nginx config file. You are trying to forward request coming to nginx container to the container itself on port 8000, just change your nginx config file to this:
upstream hello_django {
    server django-api:8000;
}

server {
    listen 80;
    location / {
        proxy_pass http://hello_django;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

django-api is the service name for you container in the network that docker-compose creates, and your other service can resolve it in the local network when trying to connect to it.


text:
Q: can't call the custom field on custom visualforce page i m trying to learn about visualforce page based on my understanding, after reading the material from web and workbooks. I created an C.Object called Book__c and calling custom fields to a visualforce page. I have controller where i m using a soql query to get the fields to use in my vf page. Can anybody tell me what i m doing wrong?
Error:
Error: Unknown property 'testController.Describe__c'
-----------------------------------vfpage--------------------------------------
<apex:page controller="testController" sidebar="false" showHeader="true" standardStylesheets="true">
    <apex:pageBlock title="Hello {!$User.FirstName}! " >

    </apex:pageBlock>
    <apex:form>
    <apex:pageBlock title="Testing picklist values with dependent list">
        <apex:inputtext value='{!Describe__c}' />
    </apex:pageBlock>
    </apex:form>
   <apex:detail subject="{!account.ownerId}" relatedList="true" />
</apex:page>

and here is my controller
public class testController {

        public Book__c myBook {get; set;}

    public testController(ApexPages.StandardController controller) {
    myBook = new Book__c();
    myBook = [SELECT books__c,Describe__c,Id,Name,OwnerId,RecordTypeId FROM Book__c];

    }

    public testController(){

    }

    //mylist = new list<Book__c>();

    public pageReference cancel(){

    Id fId = ApexPages.currentPage().getParameters().get('Id');
    pageReference p = new pageReference('/a00/o');
    return p;
    }

    public pageReference save(){
    pageReference p;
    String Rtype = ApexPages.currentPage().getParameters().get('Rtype');
    myBook.RecordTypeId = Rtype;
    insert myBook;
    return p;
    }

A: Describe__c is a field on the Book__c myBook property of the controller.  You must access it in your Visualforce page through the myBook property:
<apex:inputtext value='{!myBook.Describe__c}' />


text:
Q: Python Input Read Formatting How can i read two values typed in one line to two variable by python
like %d %d in c
raw_input reads everything in that line
eg 1 0
i want 1 in x and 0 in y

A: x, y = map(int, raw_input().split())

A: You can read the whole line and use regular expression to parse it. Use groups to get the parts that are interesting for you. Otherwise just use string.split if you don't need such a control.

A: Using larsmans' method is good enough. If you really want the scanf thing, and most importly, don't want to read the whole line. Try this, it may be slow, though.
import re
import sys

class Pin:
    formatDict = {'%d': r'(\d+)', '%f': r'(\d+\.?\d*)'}
    def __init__(self, input=sys.stdin):
        self.input = input

    def scanf(self, format):
        # change the C style format to python regex
        for a, b in self.formatDict.iteritems():
            format = format.replace(a, b)
        patt = re.compile('^\\s*%s$'%format, re.M)
        buf = ''
        matched = 0
        while 1:
            c = self.input.read(1)
            if not c: break
            buf += c
            g = patt.match(buf)
            if g:
                # matched, but there may be more to match, so don't break now
                matched = 1
                matchedGroup = g
            elif matched:
                # the first unmatch after a match, seek back one char and break now
                self.input.seek(-1, 1)
                break
        if matched:
            return tuple(eval(x) for x in matchedGroup.groups())

scanf = Pin(open('in', 'r')).scanf
print scanf('%d %d')
print scanf('%f %f')

Ugly but interesting, right?


text:
Q: Python - creating a struct with '.' from an array of strings I am new to python and wondering if how I can create data struct using '.'
For example, given an array of strings,
mystr=['aaa', 'bbb', 'ccc']
commonstr = 'zzz'

for str in mystr
    # something like creating '.' struct
    self = __create_dot_struct_with_value__(self, str, str+commonstr)

So the result will look like
self.aaa = 'aaazzz'
self.bbb = 'bbbzzz'
self.ccc = 'ccczzz'

How can I do this?
Thanks!

A: Use setattr:
class x(object):
    pass

for item in mystr:
    setattr(x, item, item + commonstr)

Now you can do things like x.aaa, and have it return aaazzz.
setattr lets you add object attributes dynamically. I would be very wary of using it inside an existing class unless you're absolutely sure it won't mess up the rest of your class, but if you just want a dummy class, this is a good way to do it.

A: from collections import namedtuple
my_class = namedtuple("a_class"," ".join(mystr))
print my_class._make([x+"zzz" for x in mystr])

might be something that works for your use case
a namedtuple is probably the closest thing python has to a struct (in the C/C++ sense)


text:
Q: Get post result with cURL and PHP I have a little function which performs a form submission and it should return the result (html).
The form has only one text input:
<input type="text" value="" maxlength="5" name="CODE" size="10">

This is how I try to fill this variable with cURL:
//open connection
$ch = curl_init();

$myValue = "Test123";
$formUrl = "http://www.mywebsite.com/post.php";

//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $formUrl);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "CODE=".$myValue);

//execute post
$result = curl_exec($ch);
$info = curl_getinfo($ch);

//close connection
curl_close($ch);

echo $result;

My problem is that I don't get any results... Is there any problem with this code?
Thank you very much for the help!
EDIT:
I also tried with this kind of setup, with the same result:
$formData = array('CHKCODE' => $tesseractOutput);

    curl_setopt($ch, CURLOPT_URL, $formUrl);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($formData));

A: You could try a bit different approach. A simple example:
    $data = array("CODE" => "Test123");
    //$ch = curl_init("http://www.mywebsite.com/post.php");
    //EDIT
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    //EDIT
    curl_setopt($ch, CURLOPT_URL, "http://www.mywebsite.com/post.php");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

    $response = curl_exec($ch);
    var_dump($response);
    curl_close($ch);


text:
Q: How to have a function execute on a range of values in a Lua table I have a program that takes letters as input, finds their assigned number in a table, and runs some math operations on that number before giving the finished pair of numbers (the encoded letter) as an output. I have functions set up to check which character is inputted, and to run the math, but my code looks like this:
checkchar(chars[1])
checkchar(chars[2])
checkchar(chars[3])
checkchar(chars[4])
checkchar(chars[5])
checkchar(chars[6])
checkchar(chars[7])
checkchar(chars[8])
checkchar(chars[9])
checkchar(chars[10])
checkchar(chars[11])
checkchar(chars[12])
checkchar(chars[13])
checkchar(chars[14])
checkchar(chars[15])
checkchar(chars[16])
checkchar(chars[17])
checkchar(chars[18])
checkchar(chars[19])
checkchar(chars[20])
checkchar(chars[21])
checkchar(chars[22])
checkchar(chars[23])
checkchar(chars[24])
checkchar(chars[25])

Hardly efficient, plus it imposes a 25 character limit because I really don't want to paste this thing 100 times.
Is there a way that I can have the program find the number of characters that have been inputted and use that number to decide how many values to run with the function, and then use that number again to print out just what was inputted so I don't have to print a bunch of black spaces?

A: I am not entirely sure if I understand your problem correctly, but would iterating using a for loop be solution of the problem? Like
for i=1,25 do
  checkchar(chars[i])
end

Even better
for _, char in pairs(chars) do
  checkchar(char)
end

If want to do it event nicer, and store results, you can use map function
local result = map(checkchar, chars)

Where map is the following
function map(func, array)
  local new_array = {}
  for i,v in ipairs(array) do
    new_array[i] = func(v)
  end
  return new_array
end


text:
Q: WLAN topology: does it work like a bus? Does wifi work as a star network with a switch or does it work like a bus ?
To be more precise, if I am in promiscuous mode, do I only see my traffic and broadcasted messages or do I get every packet sent on the network ?
I am talking about WPA protected networks.


text:
Q: Map a Pandas Series of strings using index position in another array I have a Pandas Series like:
0    bar
1    foo
2    bar
3    bar
4    bar
5    foo

I would like to map this Series to another Series based on a numpy array specifying the order, [bar, foo]. Then the result should be:
0    0
1    1
2    0
3    0
4    0
5    1

How can I do that?
Background: I have a sklearn learner which maps categorical target internally to learner.classes_ numpy array with order of original classes. I am trying to implement some additional methods and I would need to map their input (the input Series above) using those classes_, each class to its index, because this is what is then internally used in the learner.

A: You can use Categorical Data to specify a custom ordering via a list. Conversion to codes is possible via pd.Series.cat.codes:
df = pd.DataFrame({'s': ['bar', 'foo', 'bar', 'bar', 'bar', 'foo']})

orderList = ['bar', 'foo']

df['s'] = pd.Categorical(df['s'], categories=orderList, ordered=True)
df['s'] = df['s'].cat.codes

print(df)

   s
0  0
1  1
2  0
3  0
4  0
5  1

A: OK, it seems this does it:
mapping_series = pandas.Series(range(len(classes)), index=classes)
output = input.map(mapping_series)

So the trick is that the strings should be the index of the mapping series. I was just trying output = input.map(pandas.Series(classes)) but this does not work.

A: you can convert categorical to numerical using the replace function
df=pd.Series(['aa','bb','aa'])
ref=np.array(['aa','bb'])
d=dict({str(r):i for (i,r) in enumerate(ref)})
df=df.replace(d)

A: As sklearn trees depend on the way you integer encode the categories, you might want to custom encode the categories
df = pd.DataFrame({'the_column': ['bar', 'foo', 'bar', 'bar', 'bar', 'foo']})
cat_map = {'bar' :0 , 'foo' : 1}
df['category_map'] = df['the_column'].map(cat_map)
df.drop('the_column',axis = 1)
df.head()

A: Internally all scikit estimators use LabelEncoder to encode the string class labels to integers. LabelEncoder by default uses numpy.unique to get all unique classes and numpy.unique will return them in alphabetical order.
You too can use that (or extend that) to fulfil your requirements.
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
le.fit(['bar', 'foo', 'bar', 'bar', 'bar', 'foo'])

le.classes_
#Output: array(['bar', 'foo'], dtype='|S3')

le.transform(['bar', 'foo', 'bar'])
#Output: array([0, 1, 0])

le.inverse_transform([0, 1, 1])
#Output: array(['bar', 'foo', 'foo'], dtype='|S3')


text:
Q: Create a chart with a particular horizontal bar in Android i asked one month ago if it's possible to make Gantt charts with an open source library on Android. Anyone helped me, so now i'm trying to create a similar graph.
I receive the data from a database  and i have to put this data in one graph.
I have to create where:
-In the x-axis i have the time expressed in hours:minutes
-In the y-axis i have the activities and i want that the graph can show when one activity is happened (for example activity1 from 07.58 to 08.02, from 14.04 to 15.01; activity2 from 12.00 to 13.25)
Gantt would be perfect, but there isn't a chart library on android for that.
A solution can be: If an activity happens, i draw a horizontal bar in the exact time when it happens. So if the activity happens for more seconds, i draw an unique horizontal bar.
Then i can use different colors for the activities to diversify them.
It's possible to create this chart with Achartengine or Afreechart?

A: In AChartEngine, you can just add an extra line chart series for the vertical line.


text:
Q: AutoCompleteTextView Backspace Issue Anyone can pinpoint whats the problem in my code.
My AutoCompleteTextView has strange behavior when I press the backspace. At first when I type on the Textbox it will show the correct values. For example I have a list of string namely "Pallanos", "Palana", "Pandor", "Pasdi".
When i type Pal then Pallanos and Palana will show. But when I press the backspace the suggestion dropbox was NOT refresh. I should have a result of four namely the string above.
Heres my Adapter
class EmployeeAdapter extends ArrayAdapter<EmployeeDetails>{

Context context;
int layoutResourceId;
ArrayList<EmployeeDetails> data;
ArrayList<EmployeeDetails> objects;
//EmployeeDetails data[] = null;

public EmployeeAdapter(Context c, int paramlayoutResourceId, ArrayList<EmployeeDetails> collection) { //EmployeeDetails[] collection) {
    super(c, paramlayoutResourceId, collection);
    this.layoutResourceId = paramlayoutResourceId;
    this.context = c;
    this.data = collection;
    this.objects = collection;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;

    if(row == null) {
        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, null);
    }

    EmployeeDetails emp = data.get(position);
    Departments dept = new Departments(context);
    AccountTypes accType = new AccountTypes(context);

    ((TextView) row.findViewById(R.id.tvMainHeader)).setText(emp.getFirstName() + ", " + emp.getLastName());
    ((TextView) row.findViewById(R.id.tvSubHeader)).setText(dept.GetDepartmentName(emp.getDepartmentID()).toString() + " - " + accType.GetAccountTypeName(emp.getAccountTypeID()).toString());
    ((ImageView) row.findViewById(R.id.imgHeader)).setImageResource(R.drawable.id_card);

    return row;
}

@Override
public Filter getFilter() {
    //return nameFilter;

    Filter nameFilter = new Filter() {

        public String convertResultToString(Object resultValue) {
            String str = ((EmployeeDetails)(resultValue)).getLastName();
            return str;
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            ArrayList<EmployeeDetails> suggestions = new ArrayList<EmployeeDetails>();
            FilterResults filterresults = new FilterResults();

            if (constraint != null) {
                suggestions.clear();

                for (EmployeeDetails employee : objects) {
                    if (employee.getLastName().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        suggestions.add(employee);
                    }
                }

                filterresults.values = suggestions;
                filterresults.count = suggestions.size();
            }

            return filterresults;
        }

        @Override
        @SuppressWarnings("unchecked")
        protected void publishResults(CharSequence constraint, FilterResults results) {
            ArrayList<EmployeeDetails> filteredList = (ArrayList<EmployeeDetails>) results.values;

            if (filteredList != null && filteredList.size() > 0) {
                clear();
                for (EmployeeDetails employee : filteredList) {
                    add(employee);
                }
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    };

    return nameFilter;
}
}

Below code show on how I use the adapter in my AutoCompleteTextView
    EmployeeAdapter adapter = new EmployeeAdapter(this, R.layout.list_row, empFunction.GetAllEmployees());

    AutoCompleteTextView empAuto = (AutoCompleteTextView)findViewById(R.id.auto_Employee);
    empAuto.setThreshold(1);
    empAuto.setAdapter(adapter);

A: I found my solution on my problem. But its a little bit slow. If someone can optimize then feel free to post your answer. :)
Instead of equating object (this.objects = collection) variable inside my constructor I place it inside performFiltering. The idea was to refresh the objects variable every time performFiltering method fire.
Some people add TextWatcher in the TextView to refresh their adapter.
Below is my modified perFormFiltering
            protected FilterResults performFiltering(CharSequence constraint) {
            EmployeeDetails empFunction = new EmployeeDetails(context);
            ArrayList<EmployeeDetails> suggestions = new ArrayList<EmployeeDetails>();
            FilterResults filterresults = new FilterResults();

            if (constraint != null) {
                suggestions.clear();
                objects = empFunction.GetAllEmployees();
                for (EmployeeDetails employee : objects) {
                    if (employee.getLastName().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        suggestions.add(employee);
                    }
                }

                filterresults.values = suggestions;
                filterresults.count = suggestions.size();
            }

            return filterresults;
        }

Thanks


text:
Q: Bean definition and name-lookup I'm trying to experen=ment with spring's name lookup:
<bean id="test" class="com.badmitrii.TestBean" />

<bean id="anotherTest" class="com.badmitrii.AnotherTestBean">
    <lookup-method bean="test" name="getString"/>
</bean>

public class TestBean {

    private String testBean = "Test bean";

    //GET, SET

    public String getString(){
        return "String";
    }
}

public class AnotherTestBean {

    private String testBean = "Another test bean";

    //GET, SET

    public String getString(){
        return "Overriden string";
    }
}

But when I'm trying to run the application I got the following exception:
Exception in thread "main" java.lang.ClassCastException: com.pac.TestBean cannot be cast to java.lang.String
    at com.pac.AnotherTestBean$$EnhancerBySpringCGLIB$$d6d0f4c6.getString(<generated>)

on the line:
System.out.println(((AnotherTestBean) context.getBean("anotherTest")).getString());

What's wrong with that?

A: You're saying that the bean "anotherTest" is of type com.badmitrii.AnotherTestBean, and is created by calling the method getString() of the bean test.
But this method doesn't return an instance of com.badmitrii.AnotherTestBean. It returns a String. Hence the exception.


text:
Q: How to find count of objects with the highest count? create table foos (id, val1, ...)

create table bars (id, foo_id, val2. ...)

insert into foos (1, 1, ..)

insert into foos (2, 2, ..)

insert into foos (3, 3, ..)

insert into bars (1, 1, 1, ..)

insert into bars (2, 1, 1, ..)

insert into bars (3, 1, 1, ..)

insert into bars (4, 2, 1, ..)

insert into bars (5, 2, 1, ..)

insert into bars (6, 2, 1, ..)

insert into bars (7, 2, 1, ..)

insert into bars (8, 3, 1, ..)

I would want to count bars like this, how should I do it in a decreasing count order
2, 4 (foo 2 has 4 bars)

1, 3 (foo 1 has 3 bars)

3, 1 (foo 3 has a bar)

A: SELECT `foo_id`, COUNT(1) AS `count`
FROM `bars`
GROUP BY `foo_id`
ORDER BY `count` DESC

Here's the SQLfiddle link.


text:
Q: Sorting an Integer array based on the english names Example:
Input: { 1,22,44,3456,9999}
Output {44,9999,3456,22}

What i did was put integer,String values in HashMap.(map.put(0,"zero") etc..)
Create a new String array using above HashMap
String Array{ one,twotwo,fourfour,threefourfivesix,ninenineninenine}

remember the indexes of input to String Array
Sort the String Array and then replace the String values with Integers using HashMap.
Is there any other better way for doing this??
package l337;

import java.util.Arrays;
import java.util.HashMap;

public class temp{

public static void main(String[] arg){

    HashMap<Integer,String> map = new HashMap<Integer,String>();
    map.put(0,"zero");
    map.put(1,"one");
    map.put(2,"two");
    map.put(3,"three");
    map.put(4,"four");
    map.put(5,"five");
    map.put(6,"six");
    map.put(7,"seven");
    map.put(8,"eight");
    map.put(9,"nine");

    int[] input ={1,2,44,66,7895,88983};
    String[] stringArray = new String[input.length];

    for(int i=0;i<input.length;i++){

        stringArray[i] = map.get(input[i]);
        if(stringArray[i]==null){
            char[] temp= (new Integer(input[i])).toString().toCharArray();
            for(int j=0;j<temp.length;j++){
                stringArray[i]+=map.get((int)temp[j]-48);
            }
        }
    }
    HashMap<String,Integer> maploc = new HashMap<String,Integer>();
    map.put(0,"zero");
    for(int i=0;i<input.length;i++){
        maploc.put(stringArray[i], input[i]);
    }

    Arrays.sort(stringArray);

    int[] output =new int[input.length];
    for(int i=0;i<input.length;i++){
        output[i]= maploc.get(stringArray[i]);
    }
     for(int i:input){

        System.out.print(i+" ");
    }
     System.out.println();
    for(int i:output){

        System.out.print(i+" ");
    }

    }

}

A: The best way to do this is create a single object that has the number and the string representation.
i.e. when you create a new NumberAndName(3) it will set an internal integer to 3 and internal string to "three". How to handle that mapping is up to you but if you just need the numbers 0 to 9 a simple array of Strings would work.
You can then just use Collections.sort() on a collection of NumberAndName objects, specifying a comparator that uses the name to compare them.

A: When you already have a HashMap storing the mapping, you can just use a Comparator that compares the entries of the array by looking up and comparing the respective values in the map
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;

public class SortByName
{
    public static void main(String[] args)
    {
        Integer input[] = { 1,22,44,3456,9999};
        final String array[] = {
            "one", "twotwo", "fourfour", "threefourfivesix",
            "ninenineninenine"};

        final Map<Integer, String> map = createMap(input, array);
        Arrays.sort(input, new Comparator<Integer>()
        {
            @Override
            public int compare(Integer i0, Integer i1)
            {
                return map.get(i0).compareTo(map.get(i1));
            }

        });
        System.out.println(Arrays.toString(input));
    }

    private static <K, V> Map<K, V> createMap(K k[], V v[])
    {
        Map<K, V> map = new LinkedHashMap<K, V>();
        for (int i=0; i<k.length; i++)
        {
            map.put(k[i], v[i]);
        }
        return map;
    }
}

A: You could use enum to represent digits and have lookups (and reverse lookup), helper functions to convert to/from number-string.
This is a quick dirty implementation that does this.
public static void arrayEnglistTest()
{
    int[] array = { 1, 22, 44, 3456, 9999 };

    String[] stringArray = new String[array.length];
    int idx = 0;
    for (int num : array)
    {
        stringArray[idx++] = getNumberInEnglish(num);
    }

    Arrays.sort(stringArray);

    idx = 0;
    for (String stringNumber : stringArray)
    {
        array[idx++] = getNumber(stringNumber);
    }
}

public static int getNumber(String numberInEnglish)
{
    StringBuilder result = new StringBuilder();
    StringBuilder builder = new StringBuilder();
    for (char c : numberInEnglish.toCharArray())
    {
        builder.append(c);
        String soFar = builder.toString();
        if (DIGIT.getNumber(soFar) != null)
        {
            result.append(DIGIT.getNumber(soFar));
            builder.setLength(0);
        }
    }
    return Integer.parseInt(result.toString());
}

public static String getNumberInEnglish(int number)
{
    StringBuilder builder = new StringBuilder();
    while (number > 0)
    {
        builder.insert(0, DIGIT.getNumberInEnglish(number % 10));
        number /= 10;
    }
    return builder.toString();
}

enum DIGIT
{
    ONE(1, "one"), TWO(2, "two"), THREE(3, "three"), FOUR(4, "four"), FIVE(5, "five"), SIX(6, "six"), SEVEN(7,
            "seven"), EIGHT(8, "eight"), NINE(9, "nine"), ZERO(0, "zero");

    private DIGIT(int digit, String digitInEnglish)
    {
        this.digit = digit;
        this.digitInEnglish = digitInEnglish;
    }

    public static String getNumberInEnglish(int number)
    {
        return map.get(number);
    }

    public static Integer getNumber(String numberInEnglish)
    {
        return reverseMap.get(numberInEnglish);
    }

    int digit;
    String digitInEnglish;

    static Map<Integer,String> map = new HashMap<Integer,String>() {
        {
            for (DIGIT dig : EnumSet.allOf(DIGIT.class))
            {
                put(dig.digit, dig.digitInEnglish);
            }
        }
    };
    static Map<String,Integer> reverseMap = new HashMap<String,Integer>() {
        {
            for (DIGIT dig : EnumSet.allOf(DIGIT.class))
            {
                put(dig.digitInEnglish, dig.digit);
            }
        }
    };
}


text:
Q: angularx-social-login Facebook return "Error: init not called with valid version" I have integrated angularx-social-login to my app in order to login with Facebook. (Angular 11.2.5)
That worked fine until this morning. I didn't made any changes but I started receiving this error in the console :
ERROR Error: Uncaught (in promise): Error: init not called with valid version
at resolvePromise (zone-evergreen.js:1209:1)
at zone-evergreen.js:1116:1
at angularx-social-login.js:81:1
at ZoneDelegate.invoke (zone-evergreen.js:368:1)
at Object.onInvoke (core.js:28513:1)
at ZoneDelegate.invoke (zone-evergreen.js:367:1)
at Zone.run (zone-evergreen.js:130:1)
at zone-evergreen.js:1272:1
at ZoneDelegate.invokeTask (zone-evergreen.js:402:1)
at Object.onInvokeTask (core.js:28500:1)

After checking on the web, I found that I had to change the version of the facebook api that is called.
In my Angular component, I've tried to change :
this.SocialAuthService.signIn(FacebookLoginProvider.PROVIDER_ID);

to :
const fbLoginOptions = {
        scope: 'pages_messaging,pages_messaging_subscriptions,email,pages_show_list,manage_pages',
        locale: 'fr_FR',
        return_scopes: true,
        enable_profile_selector: true,
        fields: 'name,email,picture,first_name,last_name,accounts',
        version: 'v13.0',
    };
this.SocialAuthService.signIn(FacebookLoginProvider.PROVIDER_ID, fbLoginOptions);

Without success.
I've tried to include it directly in       the app.module.ts
{
        provide: 'SocialAuthServiceConfig',
        useValue: {
            autoLogin: false,
            scope: 'pages_messaging,pages_messaging_subscriptions,email,pages_show_list,manage_pages',
            providers: [
                {
                    id: FacebookLoginProvider.PROVIDER_ID,
                    provider: new FacebookLoginProvider('XXXXXXXXXXX'),
                }
            ],
            locale: 'fr_FR',
            return_scopes: true,
            enable_profile_selector: true,
            fields: 'name,email,picture,first_name,last_name,accounts',
            version: 'v13.0',

            onError: (err) => {
                console.error(err);
            }
        } as SocialAuthServiceConfig,
    }

Nothing...
After checking the file     vendor-es2015.js
I found these informations (that I think override mine) :
class FacebookLoginProvider extends BaseLoginProvider {
constructor(clientId, initOptions = {
    scope: 'email,public_profile',
    locale: 'en_US',
    fields: 'name,email,picture,first_name,last_name',
    version: 'v4.0',
}) .....

Problem, this file is generated when launching npm build watch, so no way of editing it directly.
I also tried to manually add

Still nothing..
I also tried to directly edit the file facebook-login-provider.d.ts :
import { BaseLoginProvider } from '../entities/base-login-provider';
import { SocialUser } from '../entities/social-user';
export declare class FacebookLoginProvider extends
BaseLoginProvider {
private clientId;
private initOptions: {
    scope: 'pages_messaging,pages_messaging_subscriptions,email,pages_show_list,manage_pages',
    version: 'v14.0',
};
static readonly PROVIDER_ID: string;
constructor(clientId: string, initOptions?: any);
initialize(): Promise<void>;
getLoginStatus(): Promise<SocialUser>;
signIn(signInOptions?: any): Promise<SocialUser>;
signOut(): Promise<void>;

}
That doesn't work too.
Does anyone knows how to fix this issue ?
Thanks.
PS: I am conscient that there is other posts related to this issue but nothing fixed it.

A: You're probably not the only one with this problem. most likely facebook-sdk has changed in some way, which interferes with the normal work of the "angularx-social-login" library, analyzed the source code of the library a bit (FacebookLoginProvider). I noticed that the init method in FacebookLoginProvider is called only after the dynamic addition of the facebook-sdk script, through the loadScript method of the parent class BaseLoginProvider this does not cause any errors, but when you try to call the signIn method, an error of the wrong version is generated (init not called with valid version) most likely the problem is in the wrong loading facebook-sdk. Most likely this will be fixed soon, but if authorization is critical for your site, I suggest you add facebook sdk loading to index.html (like temporary solution)


text:
Q: How to get rid of background color of Android Studio comments in dark theme? I've installed Android Studio 2.1 and switched to the dark theme. How do I get rid of this background color? I can't seem to find it anywhere. I've changed all the background colors of comments but I can't seem to get rid of this:

The Created by Can... comment has a background like it's selected (of course it's not selected) and it's really disturbing my attention.

A: That background is actually warning highlight from code inspection. You can disable it by going to Settings -> Editor -> Inspections, where you can search for Default File Template Usage and uncheck it (screenshot for help).


text:
Q: "react-native run-android" - BUILD is SUCCESSFUL but get error type 3 Error: Activity class MainActivity does not exist I try to run application on android emulator but it failed.
I run react-native run-android, BUILD is SUCCESSFUL but I get error type 3 and I don't see that it installed on emulator.
This part of what I get when I run "react-native run-android" in cmd:
Installed on 1 device.

BUILD SUCCESSFUL

Total time: 2 mins 24.714 secs
Starting the app on ***** (...\Android\sdk/platform-tools/adb -s **** shell am start -n app/.MainActivity)...
Starting: Intent { cmp=app/.MainActivity }
Error type 3
Error: Activity class {app/app.MainActivity} does not exist.

A: Step 1 : Check whether the following files have the same package name say "com.companyName.appName":
1. package (usually line 2) in /android/app/src/main/AndroidManifest.xml
2. applicationId (usually line 90) in defaultConfig section of /android/app/build.gradle
3. Line 1 of /android/app/src/main/java/com/paysack/MainApplication.java
4. Line 1 of /android/app/src/main/java/com/paysack/MainActivity.java

Step 2 :
react-native run-android

A: I spent hours on this and in the end I ended up replacing the package name. The original name contained 2 dots. E.g. com.abc.test Which I renamed to be com.abctest Also keep in mind to update the folder name in Android (android/app/src/main/java/com).
I also tried react-native init myProject --package "com.abctest" but seems like in recent versions of react native this no longer works.
I also tried using npm instead of yarn and I also tried to remove node-modules and caches but non of it worked.
Potentially you might also need to run
watchman watch-del-all
rm -rf node_modules && npm install
afterwards
I had this project working just fine a few weeks ago, but seems like something has changed somewhere and the . is no longer parsed correctly.

A: shut down the emulator and start again then uninstalling the app from emulator solved my problem, if not then you  may need to restart your computer-good luck


text:
Q: Apache service doesn't start after deleting log files I deleted the whole log files directory.
 sudo apachectl start
Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details.
[root@maximumroulette ~]# systemctl status httpd.service
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Tue 2020-07-21 15:58:15 UTC; 2s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 3703 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 3702 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 3702 (code=exited, status=1/FAILURE)

Jul 21 15:58:15 maximumroulette httpd[3702]: [Tue Jul 21 15:58:15.725253 2020] [so:warn] [pid 3702] AH01574: module proxy_http_module is already loaded, skipping
Jul 21 15:58:15 maximumroulette httpd[3702]: [Tue Jul 21 15:58:15.725424 2020] [so:warn] [pid 3702] AH01574: module proxy_wstunnel_module is already loaded, skipping
Jul 21 15:58:15 maximumroulette httpd[3702]: (13)Permission denied: AH00091: httpd: could not open error log file /var/log/httpd/error_log.
Jul 21 15:58:15 maximumroulette httpd[3702]: AH00015: Unable to open logs
Jul 21 15:58:15 maximumroulette systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Jul 21 15:58:15 maximumroulette kill[3703]: kill: cannot find process ""
Jul 21 15:58:15 maximumroulette systemd[1]: httpd.service: control process exited, code=exited status=1
Jul 21 15:58:15 maximumroulette systemd[1]: Failed to start The Apache HTTP Server.
Jul 21 15:58:15 maximumroulette systemd[1]: Unit httpd.service entered failed state.
Jul 21 15:58:15 maximumroulette systemd[1]: httpd.service failed.

Updated:
Now in error_log I found info:
(13)Permission denied: AH00091: httpd: could not open error log file /etc/httpd/logs/ssl_error_log.

When i want to start mongod service i got same logs...
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)

I found answer here :
https://unix.stackexchange.com/questions/377903/can-not-restart-the-httpd-service/377932#377932
I saw your environment is development, not production.
So set the selinux permissive model can be help
Follow the steps:
# getenforce
# setenforce 0   // there will print `Permissive`
# systemctl start  httpd.service
Check it :

systemctl status  httpd.service

but anyway your answers helps me to move from dead line.

A: Your error is could not open error log file /etc/httpd/logs/ssl_error_log
You say you deleted the whole log folder; the problem is that while Apache will happily create the log file at startup, it will not create the folder.
/etc/httpd/logs is meant to be a symlink to /var/log/httpd, so the question is "what did you delete?".
Execute ls -ld /var/log/httpd /etc/httpd/logs.
You probably only see one of the two, and an error saying that the other one does not exist.
To create /etc/httpd/logs execute ln -s /var/log/httpd /etc/httpd/logs
To create /var/log/httpd execute mkdir -p /var/log/httpd && chmod go= /etc/httpd/logs. This will create the folder and set minimum permissions on it.
I've set folder permissions to the minimum, apache will be running as root when opening the logs so it's not a problem. You may need or wish to relax the permissions later on.

A: Recreate it by running as root:
touch /var/log/httpd/error_log

Then restart apache.


text:
Q: RxJava's switchOnNext method does not behave as JavaDoc described rx.Observable.switchOnNext(Observable>) does not behave as the marble diagram in JavaDoc described.
If I tried below
public static void main(String[] args) throws Exception {
  Observable<Long> o1 = Observable.interval(200L, TimeUnit.MILLISECONDS);
  Observable<Long> o2 = Observable.interval(500L, TimeUnit.MILLISECONDS)
        .map(value -> value * 10);

  Observable.switchOnNext(Observable.just(o1, o2)).subscribe(System.out::println);

  Thread.sleep(2000L);
}

The marble diagram shows that the result might be like below.
| time   | 0   | 200  | 400   | 500  | 1000   | 1500 |.....|
|--------|-----|------|-------|------|--------|------|-----|
| o1     |     | 0    | 1     |....  | ...    | ...  | ... |
| o2     |     |      |       | 0    |  10    | 20   | ... |
| result |     | 0    | 1     | 0    |  10    | 20   | ... |

But the result becomes 0, 10, 20...and so on like below
| time   | 0   | 200  | 400   | 500  | 1000   | 1500 |.....|
|--------|-----|------|-------|------|--------|------|-----|
| o1     |     | 0    | 1     |....  | ...    | ...  | ... |
| o2     |     |      |       | 0    |  10    | 20   | ... |
| result |     |      |       | 0    |  10    | 20   | ... |

Also, if I reverse o1 to o2 like Observable.just(o1, o2) to Observable.just(o2, o1),
the result would be that only o1`s values were emitted.
Is this correct behavior?
if it is ether the JavaDoc would be wrong or the program would be wrong, I will create the issue.
Or, do I misundersand the description?
I'm using RxJava 1.1.5

A: I guess the Javadoc is correct in this case. You have to interpret the upper horizontal line as time as well. So what you give to switchOnNext is an Observable containing a first Observable o1, immediately followed by another Observable o2. So in the marble diagram the left diagonal line represents o1, the right diagonal line represents o2. Since the latter comes immediately after the former, the former is discarded, that's why you only see the latter in your output.
To get the expected behavior like it is in the marble diagram you can for example replace the Observable.just(o1, o2) with
Observable.timer(100L, TimeUnit.MILLISECONDS).map(l -> o1)
          .concatWith(Observable.timer(600L, TimeUnit.MILLISECONDS).map(l -> o2));

or anything along those lines.
The real use of this is to unsubscribe from the first Observable when the second rolls around and subscribe to the second instead.


text:
Q: How to find if an input starts with a certain string from a set Consider the following code:
my_items = {'apple','banana','orange'}
x = input("Enter a string : ")

I need to check whether the input starts with any one of the strings in the set and execute some code if it is true. For example, if the input is "apple is tasty", then it should execute some code, else just pass. How do I do that?

A: You can simply use:
my_items = {'apple','banana','orange'}
x = input("Enter a string : ")
output = any(x.startswith(i) for i in my_items)
print(output)

Output:
Enter a string : apple is tasty
True

If you want it to be true regarless of case you can use:
my_items = {'apple','banana','orange'}
x = input("Enter a string : ")
output = any(x.lower().startswith(i.lower()) for i in my_items)
print(output)

A: You can split x with ' ' (space), so that you can obtain the item at index [0] which is the first word in the string. Then check if it exists in my_items:
splitVar = x.split(' ')
if splitVar[0] in my_items:
    #your code here

A: You can use if-else
my_items = {'apple','banana','orange'}
x = input("Enter a string : ")
for i in my_items:
    if x.startswith(i):
        #Write Your Code
        break
    else:
        pass


text:
Q: Como criar uma função para somar em php e salvar no mysql? Boa tarde.
Primeiramente, quero criar uma função no PHP que sempre que executada adicione +1 no MySQL.
No meu MySQL vai ter uma coluna chamada numeros, sempre que a função por executada, ele ira remover o que tem nessa coluna e vai estar adicionando +1
Exemplo:
Tenho na minha coluna o número 67, ai eu executo a função e na coluna vai passar de 67 pra 68
Espero que tenham entendi kkk
abraço!

A: Você pode fazer isso direto no MySQL
Se você tiver uma tabela "numeros" e ela tiver um campo "numero", você pode primeiro adicionar um registro com o valor zero
INSERT INTO numeros (numero) values (0)

Desta forma, você criou um registro na tabela. Para sempre atualizar este registro, você pode fazer rodar o seguinte comando:
UPDATE numeros SET numero = numero + 1

Desta forma, ao rodar o UPDATE, sempre vai incrementar o campo número em mais 1.


text:
Q: Can't connect to wireless network on Ubuntu Server I tried to install Ubuntu 18.04 and ran into a problem when I tried to install network tools and the error message was:
failed to fetch archive.ubuntu/pool/main/w/wireless-tools/wireless-tools_30"pre9013ubuntu1_amd64.deb. Temporary failure resolving 'archive.ubuntu.com'
^ same thing again
unable to fetch some archives, maybe run apt-get update or try --fix missing

I ran apt-get update then:
Reloading package lists... Done
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - Remove Caches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - Remove caches (13: Permission denied)

A: I have tried doing this before and it's a real pain. My suggestion is to either:

*

*Hook your Ubuntu Server installation to the internet using an Ethernet cable then install what you need (Preferred)

*On a separate machine use apt download and download all the necessary *.deb files into a folder on a flash drive (Make sure to remember dependencies!) then plug it into the Ubuntu Server and run sudo apt install /path/to/dir/* and have them all installed like that.
In general I would not suggest running a server hooked up to Wi-Fi. Use Ethernet instead because it's far more stable and the system will hook itself to the internet software-wise at boot up.
I am sure there are other ways to do what you want. But these two would probably be the most straight forward solution.


text:
Q: How to get all relationships between a set of nodes? In general, the problem is: there is a query with (variable length) matches of node:
MATCH (a:`SOME.LABEL.1` {...})
MATCH (b:`SOME.LABEL.2` {...})
MATCH (c:`SOME.LABEL.3` {...})
...
MATCH (z:`SOME.LABEL.n` {...})

I need to get all relationships between this set of nodes. I started thinking about searching of distinct combinations of (a, b, c, ..., z):
WITH a,b,c, ..., z

MATCH (a) -[ab]-> (b)
MATCH (a) -[ac]-> (c)
...
MATCH (z) -[za]-> (a)

RETURN ab, ac, ..., za;

But I think its too complex.
There is an apoc function. apoc.algo.cover does what I need, but, unfortunately, I need to do it with pure cypher.

A: This will work:
WITH ['LAB1', 'LAB2', 'LAB3', 'LAB4'] AS labs
MATCH (n)-[r]->(m)
WHERE
  ANY(l1 IN labs WHERE l1 IN LABELS(n)) AND
  ANY(l2 IN labs WHERE l2 IN LABELS(m))
RETURN r

But if you are using neo4j 5, the newer label expression syntax will likely be more performant:
MATCH (:LAB1|LAB2|LAB3|LAB4)-[r]->(:LAB1|LAB2|LAB3|LAB4)
RETURN r


text:
Q: How to allow the Drive File Picker access to the users Drive when running the app is executing as me I'm using the Google Drive File Picker in an application that is being executed as me. When a user clicks to select a file they are presented with the Drive Folder structure of me (the user the app is executing as).
In my code I'm referencing Session.getActiveUser so I know who the user is and can performs actions and present data appropriate for their account.
How can I have the Drive File Picker display the files from the active user and not my account? I'm thinking if this cannot be done in the application, how would I spawn a separate window that runs a different web app that executes as them and then capture the call back in my application?

A: You can't (indeed) but what you can do is to let the app run as the user accessing the app and let this app call another app running as a service and that runs as you (and do what has to be done on your side).
You can use urlFetch service to call your app, adding necessary parameters to the url to identify the actual user (of the calling app) and other security/logging data (to prevent access from other source).
Depending on the complexity of your workflow , this can be simple or quite complex but feasible anyway.

A: If you need to show the content of the current user's Google Drive you can do it by performing an Oauth and using Google Picker.
You can find more about Oauth here :

https://developers.google.com/apps-script/reference/script/script-app#getOAuthToken()

Also note that user will have to enable the Drive Picker API for his account in order to perform an Oauth.
Then using the access token from the Oauth you can pass it to the Drive Picker to show the contents.

https://developers.google.com/apps-script/guides/dialogs#file-open_dialogs

When you deploy the app you have to select :
Execute the app as: User accessing the web app

Hope it helps!


text:
Q: Dataframe in R based on comparison of others dataframe I have three datasets
A = matrix( rnorm(9), ncol=3)
B = matrix( rnorm(9), ncol=3)
C = matrix( rnorm(9), ncol=3)

For example
> A
           [,1]       [,2]       [,3]
[1,] -0.4428679 0.01448152 -0.8224422
[2,] -1.3690073 0.56250367  1.2021395
[3,]  0.8035294 0.42666372  1.2945448

> B
             [,1]       [,2]       [,3]
[1,] -0.003198928  1.0213131 -0.7793514
[2,] -1.657098221  0.9322505 -1.4665007
[3,]  0.583796919 -0.9133222 -2.8539670

> C
            [,1]       [,2]        [,3]
[1,]  0.06293484 -0.6532648 -0.55455478
[2,] -0.04065755  1.0875654 -0.01349773
[3,]  0.50026019 -0.3151500  0.63410977

I want to create a dataframe containing A when the value of A is the highest, B when the value of B is the highest and C when the value of C is the highest. So in this case it would be something like:
C B C
C C A
A A A

Thank you in advance!!

A: You can try array + apply + which.max
inds <- apply(array(c(A, B, C), c(dim(A), 3)), 1:2, which.max)
inds[] <- c("A", "B", "C")[inds]

such that
> inds
     [,1] [,2] [,3]
[1,] "C"  "A"  "C"
[2,] "B"  "A"  "A"
[3,] "C"  "B"  "B"

Data
> set.seed(1)

> (A <- matrix(rnorm(9), ncol = 3))
           [,1]       [,2]      [,3]
[1,] -0.6264538  1.5952808 0.4874291
[2,]  0.1836433  0.3295078 0.7383247
[3,] -0.8356286 -0.8204684 0.5757814

> (B <- matrix(rnorm(9), ncol = 3))
           [,1]       [,2]        [,3]
[1,] -0.3053884 -0.6212406 -0.04493361
[2,]  1.5117812 -2.2146999 -0.01619026
[3,]  0.3898432  1.1249309  0.94383621

> (C <- matrix(rnorm(9), ncol = 3))
          [,1]        [,2]        [,3]
[1,] 0.8212212  0.78213630  0.61982575
[2,] 0.5939013  0.07456498 -0.05612874
[3,] 0.9189774 -1.98935170 -0.15579551

A: Hi it is not very succinct but the code below will do the job.
    library(tidyverse)

    A = matrix(rnorm(9), ncol=3)
    B = matrix(rnorm(9), ncol=3)
    C = matrix(rnorm(9), ncol=3)

    # convert to a data frame, 1 column per matrix

    df <- data.frame("A" = as.vector(A), "B" = as.vector(B), "C" = as.vector(C)) %>%
    # use if_else to find the highest column in each row
    mutate(max = if_else(A > B & A > C, "A",
                           if_else(B > A & B > C, "B",
                                   if_else(C > A & C > B, "C",
    # If there is no single max value or something goes wrong "Draw or Error" will be returned
                                           "Draw or Error"))))

    # take the max row from the dataframe and turn it back into a matrix
    result_matrix <- matrix(df$max, nrow = nrow(A))

    # return the output
    result_matrix

    ````


text:
Q: Generate random number only one time I have a method who randomize a number between 1 and 5.
This method needs to stop when all 5 numbers are sorted too (isn't doing it now)
My actual code is:
public ArrayList<String> generated = new ArrayList<String>(); on top
And the method itself is:
public int RandomizeQuestion () {
    // Question numbers
    final int min = 1;
    final int max = 5;

    Random r = new Random();
    int qran = r.nextInt((max - min) + 1) + min;

    if (Collections.singletonList(generated).contains(qran)) {
        RandomizeQuestion();
    } else {
        generated.add(String.valueOf(qran));
    }

    return qran;
}

But that happens is all time the random number appears as new and this number is added repeatedly in generator array.

A: Collections.singletonList(generated) returns a List<ArrayList<String>> containing generated as its only element. Obviously that won't contain qran. Also, you're not checking if the list is the expected length before attempting to add a new item. Something like this should work:
if (generated.size() < max - min + 1) {
    if (generated.contains(String.valueOf(qran))) {
        RandomizeQuestion();
    } else {
        generated.add(String.valueOf(qran));
    }
}

But here's a much simpler and more efficient way to shuffle a sequence of values:
// generate a list of values between min and max
generated = IntStream.rangeClosed(min, max)
        .map(String::valueOf)
        .collect(Collectors.toCollection(ArrayList::new));

// shuffle them
Collections.shuffle(generated);