text:
Q: Where are WPRFLAG and _WINMAIN_ macros defined? You know,
there are codes like
#ifdef WPRFLAG

and
#ifdef _WINMAIN_

in ctrexe.c . I'm using vs2010)
These macros determine what function is called from entry point.
But I can't find these macros even in the macro settings of project setting.
Where teh hell are these macros defined?

A: VS
Project->Configuration properties->Linker->System->SubSystem:

*

*Console (/SUBSYSTEM:CONSOLE)

*Windows (/SUBSYSTEM:WINDOWS)

/SUBSYSTEM:WINDOWS this let it run into _WINMAIN_.

A: WPRFLAG is defined in many wide char version of source files, such as wcrt0.c under source code folder of CRT. _WINMAIN_ is defined in Windows version of CRT source files, such as Wincrt0.c and wWincrt0.c.


text:
Q: Multiview app memory leak warning. I made a multiview app based on this Tutorial.Here is my code in the appdelegate.h
@class Disclaimerviewcontroller;

@interface GAINSAppDelegate : NSObject <UIApplicationDelegate> {
    Disclaimerviewcontroller *firstview;

}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain )Disclaimerviewcontroller *firstview;

-(void)switchview :(UIView *)view1 toview:(UIView *)view2;
@end

and in the ".m" i have the following
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self.window makeKeyAndVisible];
    Disclaimerviewcontroller *aview = [[Disclaimerviewcontroller alloc]initWithNibName:@"Disclaimerviewcontroller"bundle:nil];
    self.firstview = aview;
    [_window addSubview:aview.view];
    [aview release];
    return YES;
}

-(void)switchview :(UIView *)view1 toview:(UIView *)view2{

    [UIView beginAnimations:@"Animation" context:nil];
    [UIView setAnimationDuration:0.50];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.window cache:YES];
    [view1 removeFromSuperview];
    [_window addSubview:view2];
    [UIView commitAnimations];

}

and the dealloc
- (void)dealloc
{   [firstview release];
    [_window release];
    [super dealloc];
}

from there on when ever I want to switch to another view I use the following code
-(IBAction)switchtodisclaimer2:(id)sender{

    GAINSAppDelegate *delegate = (GAINSAppDelegate *)[[UIApplication sharedApplication]delegate];
    Disclaimerviewcontrller2 *disclaimview2 = [[Disclaimerviewcontrller2 alloc]initWithNibName:@"Disclaimerviewcontrller2" bundle:nil];
    [delegate switchview:self.view toview:disclaimview2.view];

}

just like in the tutorial. but when I did an analyze test. xcode warned be of possible memory leak in the above code. so i added (in the above case) [disclaimerview2 release];and when I run the program I get EX_BAD_ACCES error. I thought since it was initwithnibname it was an autorelease ?. I'm confused now. the tutorial doesn't seem to be addressing this at all.

A: The analyzer in some cases can warn even if there isn't one. It would be better if you ran the app through the Instruments application and then see if there actually is  memory leak.

A: As far as I know the method initWithNibName returns and object without autorelease. You should use
 [[[Disclaimerviewcontrller2 alloc]initWithNibName:@"Disclaimerviewcontrller2" bundle:nil] autorelease];.
Alternatively, you can save disclaimerview2 as property and free the memory in the dealloc method (without using autorelease).
Hope this helps.

A: The rule for memory ownership is this :

If your method name starts with 'alloc', 'init', 'copy', 'mutableCopy' or 'new' they you are responsible for releasing it, either with release or with autorelease

So yes, you do have a memory leak so you should release 'disclaimview2' with [disclaimview2 release]
However, the reason that you are crashing is because of another bug somewhere in your code.
If you are going to pass it into your delegate, your delegate should retain it - otherwise, the delegate will try to use it at some point in the future but will have been deallocated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache won't start ubuntu When I'm running service apache2 start
I get the response
 * Starting web server apache2                                                  /usr/sbin/apache2ctl: 87: ulimit: error setting limit (Operation not permitted)
apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
(13)Permission denied: make_sock: could not bind to address [::]:80
(13)Permission denied: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
Action 'start' failed.
The Apache error log may have more information.
                                                                         [fail]

When running `netstat -tulpn| grep :80
I get the response.
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp6       0      0 :::80                   :::*                    LISTEN

How can I solve this?

A: You should run this command with admin permissions. Call sudo service apache2 start.
And if this doesn't help. Go for su and after successfull login run your command. It should work this time.


text:
Q: Cardview corner background not transparent I have a custom implementation of a CardView support widget but I can't seem to get the background for the corners transparent when I include it in my layout-file. However, if I simply place the CardView support widget in my layout-file it suddenly works. How can I get the corners transparent for my custom component?

This is the layout file for my custom implementation of the CardView:
view_card.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/Custom.Widget.CardView">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="@dimen/default_padding">

    <TextView
        android:id="@+id/view_mainText"
        style="@style/Custom.Widget.TextView.Header"
        android:textColor="@color/instruction_balloon_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/view_subText"
        android:textSize="@dimen/text_size_medium"
        android:textColor="@color/instruction_balloon_text"
        android:singleLine="false"
        android:text="Please remove white corners :-("
        android:textIsSelectable="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

styles.xml
<style name="Custom.Widget.CardView" parent="CardView">
    <item name="cardBackgroundColor">@color/card_backgroundColor</item>
    <item name="cardCornerRadius">12dp</item>
</style>

And this is my layout file that includes the two CardViews. The first one with the white corners and the second one that's basically the same layout as view_card.xml but without the white corners (transparent).
example.xml
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <some.private.namespace.CardView
        android:id="@+id/custom_card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/default_margin" />

    <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/view_card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/default_margin"
        style="@style/Custom.Widget.CardView">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="@dimen/default_padding">

            <TextView
                android:id="@+id/view_mainText"
                style="@style/Custom.Widget.TextView.Header"
                android:textColor="@color/instruction_balloon_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/view_subText"
                android:textSize="@dimen/text_size_medium"
                android:textColor="@color/instruction_balloon_text"
                android:singleLine="false"
                android:text="I have no white corners :-)"
                android:textIsSelectable="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </android.support.v7.widget.CardView>
    ... some other views
</LinearLayout>

Update 1
I tried Just89's solution, however it results in a crash on lower Android versions.
 android.graphics.drawable.ColorDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow

After a quick search I found the following post.
android.graphics.drawable.ColorDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow
The answer suggests to set the background color using:setCardBackgroundColor.
However this will bring back the white corners.
Update 2
The accepted answer will solve this problem, however it's not the preferred solution. I made a mistake when creating the custom CardView component that was causing these white corners. Check this answer to see what I did wrong.

A: After a few years I came to the conclusion that I was making a fundamental mistake when creating compound components.
When making a compound component that extends android.support.v7.widget.CardView the layout xml that's inflated shouldn't also contain a CardView. Basically you'll just be adding a CardView to another CardView which will result in the white corners behind my custom CardView.
The accepted answer will solve this problem. However it's not the perfect solution.
There are 2 ways to fix the real problem:

*

*The compound view extends android.support.v7.widget.CardView and the layout xml doesn't contain android.support.v7.widget.CardView but a LinearLayout instead as the root. Styling will have to handled in the class.

*The compound view extends LinearLayout and the layout xml contains android.support.v7.widget.CardView as the root.

I chose the 1st solution to fix this problem. I hope this helps people that made the same mistake.

A: Use the following code, on a place where the context is available, in your custom implementation:
setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent));

EDIT:
Use the following code for android versions lower than Lollipop to avoid the mentioned crash.
  if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
     getBackground().setAlpha(0);
  } else {
     setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent);
  }

A: It looks like you are creating a custom CardView form your layout file because of this
<some.private.namespace.CardView
        android:id="@+id/custom_card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/default_margin" />

Your CardView might be extending something(say LinearLayout) and you may be creating another child view inside that parent View. So just try to set immediate parent of your card layout  to transparent using
setBackground();
May be this helps.

A: add new style into styles.xml file similar this :
<style name="CardViewRadius">
    <item name="cardBackgroundColor">@color/colorGray</item>
    <item name="cardCornerRadius">18dp</item>
</style>

and use :
<android.support.v7.widget.CardView
        style="@style/CardViewRadius"
        android:layout_marginTop="15dip"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:layout_gravity="center_horizontal"/>

and result :

A: I was having similar issue with a darker area/background where the curved corners are as shown in this screenshot. .
I solved by setting the cardElevation to 0dp. This may not work for you if you need the shadow.
app:cardElevation="0dp"

A: You could try nesting your rounded corner view inside another view/layout.
The outer view here could have a transparent background, so that even when the rounded corners of the inner leave space on the corners, that will not be seen since the outer view has a transparent background color.
Something like this :
<RelativeLayout>
android:background = "@color/transparent"
< some.private.namespace.CardView
android:margin="8dp"
.....
/>
</RelativeLayout>


text:
Q: Move spines in matplotlib 3d plot? I'm trying to move the spines in a 3D matplotlib axes object.
This seems like a really simple issue, but I have not found any questions/answers that address this directly. I've included a list of my research on this topic at the bottom of this question.
I can set the position of the spines in matplotlib 2D plots. The following code:
import matplotlib.pyplot as plt, numpy as np

fig, axes = plt.subplots(1, 2)
r, theta = 1, np.linspace(0, 2*np.pi, 100)
x, y = r*np.cos(theta), r*np.sin(theta)
for ax in axes:  # plot the same data on both axes
    ax.plot(x, y)
    ax.set_aspect("equal")
for spine in ax.spines.values():  # adjust spines on last active axis
    spine.set_position(("data", 0))

produces:

However, when I try the same thing with a 3D axis...
z = np.zeros(x.shape)  # exciting stuff
fig = plt.figure()
for i in range(2):  # create two 3D subplots
    ax = plt.subplot(1,2,i+1, projection="3d", aspect="equal")
    plt.plot(x, y, z)
for spine in ax.spines.values():  # adjust spines on last active axis
    spine.set_position(("data", 0))

the above code gives me:

I.e. no effect, even though the code still runs. Also, for the 3D axes, ax.spines looks like:
OrderedDict([('left', <matplotlib.spines.Spine at 0x120857b8>),
             ('right', <matplotlib.spines.Spine at 0xfd648d0>),
             ('bottom', <matplotlib.spines.Spine at 0xe89e4e0>),
             ('top', <matplotlib.spines.Spine at 0xe89eef0>)])

I'm not sure what "left", "right", "bottom", "top" refer to in the context of a 3D axis. I've tried changing other properties like colour of the spines; no luck there either. How can I get hold of the actual x, y, z spines on the axes?
Research:

*

*searching "matplotlib spines 3d" in stackoverflow gives 5 results (including this question) at the time of writing.

*The mplot3d documentation doesn't mention spines at all.

*This question shows how to set the pane colour with ax.w_xaxis.set_pane_color(), but there is no similar ax.w_zaxis.set_spine... method.

*This question shows how to set the spine colour using ax.w_zaxis.line.set_color(). I thought about making a horrible workaround to set ax.w_zaxis.line.set_data manually, but it only has x and y data; no z! Even the x and y axes don't have z data.

A: There seems to be no obvious way to do this at the moment. Setting the spines when the axis projection is 3D is not implemented. However, there is a small hack here.
The ax.spines setting is for 2D rendering. When you set projection=3d in the initialization of the figure, certain 2D properties (like ax.spines, etc.) are ignored. It's why you don't get any response when you set the 2D spines.
The 3D figure axis line (the thick black line for each axis) locations are determined by the parameter ax.xaxis._axinfo['juggled'] (and similarly for y and z axes). This specifies which of the six outer boundaries of a 3D plot bounding box are plotted as thick black lines.
You can shift the position of the axis line for each of x,y,z axis by overwriting the juggled value, which specifies which axis lines are the main ones, as the following example for the x axis,

the default setting, ax.xaxis._axinfo['juggled'] = (1,0,2)

new setting, ax.xaxis._axinfo['juggled'] = (2,0,1)
The parameters for all the six outer boundaries are,


text:
Q: Trigger has no Binding property During i reading up on WPF i have run into a problem trying to create a binding on the Trigger in a template, used to create an image button.
<ControlTemplate x:Key="ToolbarButtonHover" TargetType="Button">
    <Grid Name="backgroundGrid">
        <Image Source="{DynamicResource ResourceKey=Img}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"></Image>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="Button.IsPressed" Value="True">
            <Setter TargetName="backgroundGrid" Property="Background" Value="#007ACC" />
        </Trigger>
        <!--Error: The property 'Binding' was not found in type Trigger-->
        <Trigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource TemplatedParent}}" Value="True">
            <Setter TargetName="backgroundGrid" Property="Background" Value="Red" />
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

Results in the Error The property 'Binding' was not found in type Trigger, more specifically its the line
   <Trigger Binding="{ Path=IsMouseOver, RelativeSource={RelativeSource TemplatedParent}}" Value="True">That generates it.
What is the reason for this error?

A: Probably because there is no Binding property on the Trigger class as you can see here.
You probably are looking for a DataTrigger.
<ControlTemplate x:Key="ToolbarButtonHover" TargetType="Button">
    <Grid Name="backgroundGrid">
        <Image Source="{DynamicResource ResourceKey=Img}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"></Image>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="Button.IsPressed" Value="True">
            <Setter TargetName="backgroundGrid" Property="Background" Value="#007ACC" />
        </Trigger>
        <!--Look below, DataTrigger -->
        <DataTrigger Binding="{Binding Path=IsMouseOver, RelativeSource={RelativeSource TemplatedParent}}" Value="True">
            <Setter TargetName="backgroundGrid" Property="Background" Value="Red" />
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>


text:
Q: How To play 25MB+ audio file directly from google drive in HTML 5? I am fetching 25+ MB Audio file from google drive.
I need to play this file using html5 code.
For this i am using below code.
<!DOCTYPE html>
<html>
<body>

<audio controls>
  <source src="https://drive.google.com/file/d/0B1gAlyxjlHyaZldJTUZsTWwybGM/view">
  Your browser does not support the audio element.
 </audio>

 </body>
</html>

Using this code files which are below 25 MB plays properly. But if it is more then 25 MB then it wont. Please suggest any way to solve this point where i can play files which are more then 25 MB.
Thank you.

A: if this is the file(i downloaded and i got 25.7mb) to play Its working for me.
I used this code
<audio controls="controls">
    <source src="https://docs.google.com/uc?export=download&id=0B1gAlyxjlHyaZldJTUZsTWwybGM">
 </audio>

let me know if you have any problems/doubts.
Thank You.


text:
Q: Bootstrap-Colorpicker: Cannot set property 'colorpicker' of undefined I want to display an color picker in a form. I'm using bootstrap-colorpicker and have build my colorpicker (ok, I have copied it from the advanced forms page from the Admin LTE 2 demo):

     Color picker with addon:

         <input type="text" class="form-control" />

I initialise the plugin:
 $(document).ready(function () {
    //color picker with addon
    $(".colorpicker-critically").colorpicker();
});

And i link the .js before the .css in my  tag. jQuery is of course also included.
When I try the page I get the following errors:

Here is my  Tag:
<title></title>

<link href="/plugins/colorpicker/bootstrap-colorpicker.min.css" rel="stylesheet" type="text/css" />

<link href="/plugins/ionslider/ion.rangeSlider.css" rel="stylesheet" type="text/css" />

<link href="/plugins/ionslider/ion.rangeSlider.skinNice.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="/css/ion.rangeSlider.css"/>
    <link rel="stylesheet" href="/plugins/ionslider/ion.rangeSlider.skinFlat.css"/>
    <link rel="stylesheet" href="/plugins/ionslider//ion.rangeSlider.skinHTML5.css"/>
    <link rel="stylesheet" href="/plugins/ionslider/ion.rangeSlider.skinModern.css"/>
    <link rel="stylesheet" href="/plugins/ionslider/ion.rangeSlider.skinNice.css"/>
    <link rel="stylesheet" href="/plugins/ionslider/ion.rangeSlider.skinSimple.css"/>
    <link rel="stylesheet" href="/plugins/ionslider/normalize.css"/>

<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport" />

<link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css" />

<link href="../dist/css/AdminLTE.min.css" rel="stylesheet" type="text/css" />

<link href="../dist/css/skins/_all-skins.min.css" rel="stylesheet" type="text/css" />

<link href="../plugins/iCheck/flat/blue.css" rel="stylesheet" type="text/css" />

<link href="../plugins/morris/morris.css" rel="stylesheet" type="text/css" />

<link href="../plugins/jvectormap/jquery-jvectormap-1.2.2.css" rel="stylesheet" type="text/css" />

<link href="../plugins/datepicker/datepicker3.css" rel="stylesheet" type="text/css" />

<link href="../plugins/daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css" />

<link href="../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css" rel="stylesheet" type="text/css" />

Thanks for any help.

A: Your color picker library is conflicting that`s why your color picker function is not defined i have a another way to use color picker you can use directly
<input type="color" class="form-control" />

It will add color picker you don`t need to add a color picker library.

A: The bootstrap-colorpicker.js need to be under the jQuery inclusion.
After doing this everything works fine.


text:
Q: WSL in Windows Container I'd like to use Bash for Windows (Windows subsystem for Linux) inside of a Windows Docker Container.
Use Case: I have a Windows application (which I want to dockerize), which also needs to run certain Linux commands.
I've tried to create an image with WSL enabled:
FROM microsoft/windowsservercore

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

# Enable Developer Mode
RUN New-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" -ItemType Directory -Force
RUN New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock" -Name AllowDevelopmentWithoutDevLicense -PropertyType DWORD -Value 1

# Enable WSL
RUN Enable-WindowsOptionalFeature -FeatureName Microsoft-Windows-Subsystem-Linux -Online -All -NoRestart

But it fails with Enable-WindowsOptionalFeature : Feature name Microsoft-Windows-Subsystem-Linux is unknown.
Question: Is this even technically possible? If yes, how would I write the Dockerfile?


text:
Q: Serializing Lists of Classes to XML I have a collection of classes that I want to serialize out to an XML file. It looks something like this:
public class Foo
{
  public List<Bar> BarList { get; set; }
}

Where a bar is just a wrapper for a collection of properties, like this:
public class Bar
{
  public string Property1 { get; set; }
  public string Property2 { get; set; }
}

I want to mark this up so that it outputs to an XML file - this will be used for both persistence, and also to render the settings via an XSLT to a nice human-readable form.
I want to get a nice XML representation like this:
<?xml version="1.0" encoding="utf-8"?>
<Foo>
  <BarList>
    <Bar>
      <Property1>Value</Property1>
      <Property2>Value</Property2>
    </Bar>
    <Bar>
      <Property1>Value</Property1>
      <Property2>Value</Property2>
    </Bar>
  </Barlist>
</Foo>

where are all of the Bars in the Barlist are written out with all of their properties. I'm fairly sure that I'll need some markup on the class definition to make it work, but I can't seem to find the right combination.
I've marked Foo with the attribute
[XmlRoot("Foo")]

and the list<Bar> with the attribute
[XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName="Bar")]

in an attempt to tell the Serializer what I want to happen. This doesn't seem to work however and I just get an empty tag, looking like this:
<?xml version="1.0" encoding="utf-8"?>
<Foo>
  <Barlist />
</Foo>

I'm not sure if the fact I'm using Automatic Properties should have any effect, or if the use of generics requires any special treatment. I've gotten this to work with simpler types like a list of strings, but a list of classes so far eludes me.

A: Everything looks great. As @Carl said you need to add the [Serializable] attibute to your classes, but other than that your XML creation should work find.
Foo
[Serializable]
[XmlRoot("Foo")]
public class Foo
{
    [XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")]
    public List<Bar> BarList { get; set; }
}

Bar
[Serializable]
public class Bar
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

Code to test
Foo f = new Foo();
f.BarList = new List<Bar>();
f.BarList.Add(new Bar() { Property1 = "s", Property2 = "2" });
f.BarList.Add(new Bar() { Property1 = "s", Property2 = "2" });

FileStream fs = new FileStream("c:\\test.xml", FileMode.OpenOrCreate);
System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(Foo));
s.Serialize(fs, f);

Output
<?xml version="1.0" ?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <BarList>
        <Bar>
            <Property1>s</Property1>
            <Property2>2</Property2>
        </Bar>
        <Bar>
            <Property1>s</Property1>
            <Property2>2</Property2>
        </Bar>
    </BarList>
</Foo>

A: Just to check, have you marked Bar as [Serializable]?
Also, you need a parameter-less ctor on Bar, to deserialize
Hmm, I used:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        Foo f = new Foo();

        f.BarList = new List<Bar>();

        f.BarList.Add(new Bar { Property1 = "abc", Property2 = "def" });

        XmlSerializer ser = new XmlSerializer(typeof(Foo));

        using (FileStream fs = new FileStream(@"c:\sertest.xml", FileMode.Create))
        {
            ser.Serialize(fs, f);
        }
    }
}

public class Foo
{
    [XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")]
    public List<Bar> BarList { get; set; }
}

[XmlRoot("Foo")]
public class Bar
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

And that produced:
<?xml version="1.0"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <BarList>
    <Bar>
      <Property1>abc</Property1>
      <Property2>def</Property2>
    </Bar>
  </BarList>
</Foo>

A: var xmlfromLINQ = new XElement("BarList",
            from c in BarList
            select new XElement("Bar",
                new XElement("Property1", c.Property1),
                new XElement("Property2", c.Property2)
             ));

A: It has been over 5 years since this item was posted. I give my experience from July 2013 (.NET Framework 4.5). For what it's worth and to whom it may concern:
When I define a class like so: (VB.Net code)
<Serializable> Public Class MyClass
    Public Property Children as List(of ChildCLass)
    <XmlAttribute> Public Property MyFirstProperty as string
    <XmlAttribute> Public Property MySecondProperty as string
End Class

<Serializable> Public Class ChildClass
    <XmlAttribute> Public Property MyFirstProperty as string
    <XmlAttribute> Public Property MySecondProperty as string
End Class

With this definition the class is (de)serialized without any problems. This is the XML that comes out of here:
<MyClass> MyFirstProperty="" MySecondProperty=""
    <Children>
        <ChildClass> MyFirstProperty="" MySecondProperty=""
        </ChildClass>
   </Children>
</MyClass>

It only took me two days to figure it out that the solution was to leave out the <XmlElement> prefix of the List(of T) elements.


text:
Q: $x^2+ax+b=0 \overset ? \impliedby (A,+,\cdot)$ is a field Let $(A,+,\cdot)$ be a ring with $|A|=9$. Prove that the next statements are equivalent:
a) For all $x\in A-\{0\}$ there exist $a \in \{-1,0,1\}$ and $b \in \{-1,1\}$ s.t.   $x^2+ax+b=0$.
b) $(A,+,\cdot)$ is a field

*

*a) $\implies$ b)
If  $a \in \{-1,0,1\}$ then
\begin{aligned}
ax&=xa \\
x(x+a)&=(x+a)x=b \in\{-1,1\}.
\end{aligned}
So $x$ is invertible and $(A,+, \cdot)$ is a field.
I don't know how to show that b) $\implies$ a). Can somebody help me, please?

A: The proof of (a)$\implies$(b) is not complete as you have not shown that multiplication is commutative. This follows from Wedderburn's theorem that every finite division ring is commutative, but we can avoid using the sledgehammer.
You know that $F=\{0,1,-1\}$ is a subfield of $A$ and is certainly contained in the center. Hence $A$ is a two-dimensional vector space over $F$, so it has a basis $\{1,x\}$ and every element is of the form $a+bx$, for $a,b\in F$. Hence any two elements commute. (Note that for this you don't even need that $A$ is a division ring, so this might go before the proof that every element of $A\setminus\{0\}$ is invertible.)
More generally, if $A$ is a ring of cardinality $p^2$, with $p$ a prime, then $A$ is commutative.
For the converse, you know that $A$ has characteristic $3$, so it is a two-dimensional field extension of $F=\{0,1,-1\}$. For the nonzero elements of $F$ there is no problem in finding the suitable $a$ and $b$. If $x\in A\setminus F$, it has a degree $2$ minimal polynomial over $F$.


text:
Q: Local min and max difference in Numpy python I am trying to write a function that calculates the maximum dip in the numpy arrays A, B, C, D and get the Expected Result. For array C it the values 0,10,-110,23, shows that from 0 it went to 11 and went back down to -110 resulting in a total drawdown of -120. How would I be able to calculate such a thing?
import numpy as np

def MXincrementedDrawdown(cumsum):
    prev = np.arange(0, len(cumsum)-1)
    current =np.arange(1, len(cumsum))
    if cumsum[prev] > cumsum[current]:
        difference = cumsum[prev] - cumsum[current]
        print(difference)
    else:
        return 'No drawdown'
    print("Maximum Drawdown of Incremented is {}".format(difference))

A = np.array([0,2,5,44,-12,3,-5])
B = np.array([0,10,-110,23,45,66,30,2,12])
C = np.array([0,10,11,-23,45,11,66,45,4,12])
D = np.array([0,5,6,7,8])

MXincrementedDrawdown(A)
MXincrementedDrawdown(B)
MXincrementedDrawdown(C)
MXincrementedDrawdown(D)

Expected Output:
-56
-120
-62
No drawdown

A: If I got the question right
import numpy as np
a = np.array([0,2,5,44,-12,3,-5])
_min  = min(a)
index_min = np.where(a == _min)[0][0] #first occurence
_max = max(a[:index_min])
print(_min-_max)


text:
Q: Android: How to convert CMYK color space file to RGB?
Possible Duplicate:
RGB to CMYK and back algorithm

As far as I know Android doesn't support files with CMYK color space. But my application has to show such files. So, how to convert CMYK color space file to RGB?


text:
Q: How can I update a row via a filtered data extension with a value of null in ssjs? I am using ssjs in Marketing Cloud to detect records that were not sent an email through my Journey due to not finding a matching Contact record in Salesforce.
First I am setting all of the values in my EmailSent column to True, the trying to filter the data extension to isolate the records with nothing in the ContactKey_MC__c field (which means they didn't match an existing Contact record) and set the EmailSent column to False so we can fix those and resend the email without the other records getting duplicate emails.
The first part works perfectly, but the second part does nothing. I've tried a number of ways of filtering the rows with null ContactKey_MC__c values (Property:"ContactKey_MC__c",SimpleOperator:"notContains",Value:"0"} is just the latest, since every ContactKey has a 0), but it's ignored regardless. Any help would be much appreciated!
<script runat="server">
Platform.Load("Core","1.1");

var Shipments = DataExtension.Init("Shipping Confirmations");
var result = Shipments.Rows.Update({EmailSent:"True"}, ["EmailSent"],["False"]);

var ShipmentsEmpty = DataExtension.Init("Shipping Confirmations");
var filter = {Property:"ContactKey_MC__c",SimpleOperator:"notContains",Value:"0"};
var data = ShipmentsEmpty.Rows.Retrieve(filter);

 if(data && data.length > 0) {
      for(var i=0; i<data.length; i++) {
        var result = ShipmentsEmpty.Rows.Update({EmailSent:"False"}, ["EmailSent"],["True"]);
      }
 }

A: Use the SimpleOperator isNotNull like this:
var de = DataExtension.Init("AAAAAA-BBBB-CCCC-DDDDD-ABCDEF1234");
var filter = {Property:"Your field",SimpleOperator:"isNotNull"};
var data = de.Rows.Retrieve(filter);
Write("count:" + data.length);

SimpleOperator value of isNull is also possible.
Remember to also use the "External Key" in your DE init.


text:
Q: How do I sum values from different rows with matching columns from a datagridview c# So, my problem is the following: I have a DataGridView with 4 different columns (Name, Group, Value, Date), and I have 6 distinct textboxes for all the 6 groups (let´s suppose a, b, c, d ,e and f)
So my goal is to add the values from the column value, from rows with equal group
For example:
(DataGridView info):
Pear / a / 6 / 10-12-2016
Apple / b / 7 / 10-12-2016
Banana / a / 8 / 10-12-2016

The result should be the sum of the row "Pear" with the row "Banana", resulting on 14 (6+8), because they have the same group (a), and the result should be displayed on the TextBox corresponding to the "Group a".
Hope you can help me :D


text:
Q: Is it possible to fit a logistic regression model to a dataset with categorical predictive variables with very high number of levels each? I want to fit a model to a very large dataset, with a standard binary response variable and with 3 categorical predictor variables with 3000, 15 and 2 levels. Is there any inherent problem in this case, if I want to use logistic regression? Will it be computationally manageable using R?

A: yes you can do this. I would recommend glmnet. This takes a matrix (rather than a dataframe) as input. The creation of sparse model matrices seems a bit memory consuming - have a look at this blog post: creating sparse dummy variables matrix for glmnet


text:
Q: overflow: hidden of absolute positioned elements I've read all the similar examples and still cannot get the right solution.
Basically I have a simple Side Menu which toggles on button click. In the menu there is a list of checkboxes (their position is absolute). The parent container seems to be positioned relatively. Please help me to find the solution so that "overflow: hidden" would word.
I tried to simplify the code below. The working example of the whole app is posted here(it's easier to see the problem): https://arturtakoev.github.io/redux-reader/
And one additional question: I've noticed that the animation significantly slows down when there is a content on the page. This only appears on the deployed version and works fine on local one. Do you know why?
JS (jsx):
const SideMenu = ({ onClick, selectedSources, onSelectAll, onUnselectAll, showMenu }) => {

    const listOfSources = Object.keys(selectedSources).map(key => key)
    function renderSources() {
        return listOfSources.map((source) => (

                 onClick(e, [source])}>{source}

        ))
    }

    function renderSourcesChecks() {
        return listOfSources.map((source) => (

                {selectedSources[source].properties.title}
                    <input type="checkbox" onChange={(e) => onClick(e, [source])} checked={selectedSources[source].isSelected} />

        ))
    }
    return (

                     onSelectAll(e, listOfSources)}>

                        All in one

                     onUnselectAll(e, listOfSources)} id="closeicon" className="close" data-dismiss="alert" aria-label="Close">
                        ×

            {renderSourcesChecks()}

    )
};

CSS:
#sidebar {
    height: 100vh;
    width: 0;
    position: fixed;
    top: 0;
    left: 0;
    transition: 0.5s;
    overflow-x: hidden;
    background-color: #fff;
    /* top layer */
    z-index: 9999;
    border-right: 1px solid rgba(0,0,0,.125);
}
#sidebar.visible {
    width: 250px;
}
#sidebar ul.components {
    padding: 20px 8px 8px 15px;

    cursor: pointer;
}
#sidebar ul li {
    padding: 5px;
    font-size: 15px;
    transition: 0.3s;
}

/* The container */
.containerOne {
    display: block;
    position: relative;

    padding-left: 30px;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* Create a custom checkbox */
.checkmark {
    position: absolute;
    top: 0;
    left: 0;
    height: 20px;
    width: 20px;
    background-color: #fff;
    border: 1px solid;
}

/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

/* Show the checkmark when checked */
.containerOne input:checked ~ .checkmark:after {
    display: block;
}

/* Style the checkmark/indicator */
.containerOne .checkmark:after {
    left: 7px;
    top: 1px;
    width: 5px;
    height: 13px;
    border: solid white;
    border-width: 0 2px 2px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}

A: I didn't get your question exactly but if you want the list will not break when collapsing simply give the "#sidebar ul.components" a fixed width like 250px; so text will not break.
Let me know if you need something else.


text:
Q: PHP File Upload not updaing database or uploading file I have been banging my head against the wall trying to figure out this issue, what I am trying to do is

*

*Check to see if the image textbox is blank or not

*See if the file is a jpg or pjpeg, if not return invalid image

*see if there are any errors

*If an error, display error if not upload the file then update database...

Here is my case:
case"updatesubmit":
    if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {

        if (($_FILES["image"]["type"] == "image/jpeg") || ($_FILES["image"]["type"] == "image/pjpeg")){
            if ($_FILES["image"]["error"] > 0){
                echo $_FILES["image"]["error"];
            }else{
                move_uploaded_file($_FILES["image"]["tmp_name"],
                "../upload/CV_1_" . date("Ymd") . $_FILES["image"]["name"]);
                $class->update($id, $text, $image);
                echo "
Updated!
";
            }
        }else{
            echo "
Invalid Image!
";
        }
    }else{
        $class->updateWithoutImage($id, $text);
        echo "
Updated!
";
    }
        $array = $class->view();
        include("view/CV/view_display.html");
    break;

If anyone can point me in the right direction, that would be awesome!!!

A: you could edit your code in this way:
list($width, $height, $type, $attr) = getimagesize($_FILES['image']['tmp_name']);
if($type!=2){ // SO IS NOT JPG
//ERROR
}


text:
Q: Difference from launching vscode from anaconda navigator vs desktop shortcut Short question, not necessarily related to the installation (like in desktop-vscode-vs-anaconda-vscode ), but more with launching the application.
I installed vscode from the official page, the version without admin requirements because the version I installed from Anaconda couldn't update (don't know if that should happen. I don't have Admin privilegies in work so I blame that). The non-admin version recognizes my anaconda-python environments and seem to run fine except with the terminal, that doesn't recognize the "conda" command. The problem is solved by launching vscode (non-admin version again) from the Anaconda navigator or from anaconda prompt.
What is the difference from launching from the navigator vs launching from my desktop shortcut? The only difference I can recognize from launching the two ways is that the anaconda version allows for more than one shell on terminal, and displays "conda" as the shell.
Is there a way to create a shortcut from the anaconda prompt?

A: The difference will be that Anaconda Navigator seems to be setting up your environment variables so that VS Code is launched it's from an activate conda environment (probably base). The VS Code shortcut doesn't have the equivalent setup.
There's no way to replicate the experience that I'm aware of, but maybe if you look at the Anaconda Prompt shortcut you can see what they are doing to duplicate it. Otherwise launching from the Anaconda Prompt or Navigator is going to be your best option.


text:
Q: Create new column between two elements and between() python I have a data frame data_set and two infos important in a list
cond_list = [{'LQ','DA'},{'HJ','OP'}].
Report all information between the two values LQ and DA OR HJ and OP in new column 'Another Pass' and which condition in the same day and same id.
Example:
Let i, j correspond to the Rank of LQ and DA respective. i<j

*

*ID 1552, date 1/4/2020, we have Info['LQ'] correspond to Rank = 1 and Info['DA'] correspond to Rank = 4 --> So all information 'Another pass' include [LA, BA] because Rank DA < Rank LA, Rank BA < Rank LQ

*ID 1552, date 5/4/2020, we have Info['LQ'] correspond to Rank = 3 and Info['DA'] correspond to Rank = 7 --> So all information 'Another pass' include [VT,AN,VB] because Rank DA < Rank VT, Rank AN, Rank VB < Rank LQ

*ID 1697, date 15/4/2020, we have Info['LQ'] correspond to Rank = 1 and Info['DA'] correspond to Rank = 4 but there is no information in between these two points so 'Another pass' is empty
Input:

ID
Date
Rank
Info
Horaire
Type
Note

1552
1/4/2020
1
LQ
10:00
D
LVM

1552
1/4/2020
1
LQ
10:10
A
LVM

1552
1/4/2020
2
LA
10:12
P

1552
1/4/2020
3
BA
10:15
P

1552
1/4/2020
4
DA
10:25
A
LVD

1552
5/4/2020
1
DT
11:30
D

1552
5/4/2020
2
GR
11:33
P

1552
5/4/2020
3
LQ
11:35
D
LDT

1552
5/4/2020
3
LQ
11:38
A

1552
5/4/2020
4
VT
11:40
P

1552
5/4/2020
5
AN
11:43
P

1552
5/4/2020
6
VB
11:46
P

1552
5/4/2020
7
DA
11:55
A
LDF

1552
5/4/2020
7
DA
11:59
D

1552
5/4/2020
8
AT
12:15
A

1697
15/4/2020
1
HJ
10:00
D
LVM

1697
15/4/2020
4
OP
11:00
A
LVM

i filtered a table of values containing only two condition elements:
mask = df.groupby(['ID', 'Date'])['Info'].agg(set).apply(lambda x: any([y.issubset(x) for y in cond_list]))
data_set = df.set_index(['ID', 'Date']).loc[mask].reset_index()
dt_final = data_set.loc[data_set['Info'].isin(cond.values.ravel())]

I gain a new data frame 'dt_final':

ID
Date
Rank
Info
Horaire
Type
Note

1552
1/4/2020
1
LQ
10:00
D
LVM

1552
1/4/2020
1
LQ
10:10
A
LVM

1552
1/4/2020
4
DA
10:25
A
LVD

1552
5/4/2020
3
LQ
11:35
D
LDT

1552
5/4/2020
3
LQ
11:38
A

1552
5/4/2020
7
DA
11:55
A
LDF

1552
5/4/2020
7
DA
11:59
D

1697
15/4/2020
1
HJ
10:00
D
LVM

1697
15/4/2020
4
OP
11:00
A
LVM

I say an array of values 'Rank':
cd = dt_final.groupby(["ID", "Date"])["Rank"].agg(list).tolist()

i filter the values in between:
for i in cd:
    pr['Another Pass'] = data_set.loc[data_set.Rank.between(i[0],i[-1])].groupby(['ID', 'Date ']).agg({'Info':list})

Although it declares all information by the same date and same id, not the required values between two points in the condition cond_list and like a example :(

A: Since the same ID and Date cannot have both sets of values, you can try:
cond_list = [['LQ','DA'],['HJ','OP']]
firsts = [s[0] for s in cond_list]
lasts = [s[-1] for s in cond_list]

another_pass= df.groupby(["ID", "Date"])
                .apply(lambda x: x[x["Rank"].between(x[x["Info"].isin(firsts)]["Rank"].min(),
                                                     x[x["Info"].isin(lasts)]["Rank"].max(),
                                                     inclusive="neither")]["Info"].tolist())
                .rename("Another Pass")

>>> output

ID    Date
1552  1/4/2020         [LA, BA]
      5/4/2020     [VT, AN, VB]
1697  15/4/2020              []

If you want to merge this back to your original DataFrame to create the new column:
output = df.merge(another_pass, left_on = ["ID", "Date"], right_index=True)

>>> output

      ID       Date  Rank Info Horaire Type Note  Another Pass
0   1552   1/4/2020     1   LQ   10:00    D  LVM      [LA, BA]
1   1552   1/4/2020     1   LQ   10:10    A  LVM      [LA, BA]
2   1552   1/4/2020     2   LA   10:12    P  NaN      [LA, BA]
3   1552   1/4/2020     3   BA   10:15    P  NaN      [LA, BA]
4   1552   1/4/2020     4   DA   10:25    A  LVD      [LA, BA]
5   1552   5/4/2020     1   DT   11:30    D  NaN  [VT, AN, VB]
6   1552   5/4/2020     2   GR   11:33    P  NaN  [VT, AN, VB]
7   1552   5/4/2020     3   LQ   11:35    D  LDT  [VT, AN, VB]
8   1552   5/4/2020     3   LQ   11:38    A  NaN  [VT, AN, VB]
9   1552   5/4/2020     4   VT   11:40    P  NaN  [VT, AN, VB]
10  1552   5/4/2020     5   AN   11:43    P  NaN  [VT, AN, VB]
11  1552   5/4/2020     6   VB   11:46    P  NaN  [VT, AN, VB]
12  1552   5/4/2020     7   DA   11:55    A  LDF  [VT, AN, VB]
13  1552   5/4/2020     7   DA   11:59    D  NaN  [VT, AN, VB]
14  1552   5/4/2020     8   AT   12:15    A  NaN  [VT, AN, VB]
15  1697  15/4/2020     1   HJ   10:00    D  LVM            []
16  1697  15/4/2020     4   OP   11:00    A  LVM            []

Edit:
For the required rows from the output, you can do:
>>> output[((output["Info"].isin(["LQ", "HJ"])) &
            (output["Type"]=="D")) |
           ((output["Info"].isin(["DA", "OP"])) &
            (output["Type"]=="A"))]

      ID       Date  Rank Info Horaire Type Note  Another Pass
0   1552   1/4/2020     1   LQ   10:00    D  LVM      [LA, BA]
4   1552   1/4/2020     4   DA   10:25    A  LVD      [LA, BA]
7   1552   5/4/2020     3   LQ   11:35    D  LDT  [VT, AN, VB]
12  1552   5/4/2020     7   DA   11:55    A  LDF  [VT, AN, VB]
15  1697  15/4/2020     1   HJ   10:00    D  LVM            []
16  1697  15/4/2020     4   OP   11:00    A  LVM            []


text:
Q: Create new column in Python and use value from previous row Im totally beginner in Python but I need to use the value from previous row. I read a lot of articles but I didn't catch the point :(
I have an Excel file with data, I sorted the data by 'D_i' column and here I found a problem. I need to add new column 'C_i' which contains in 1st row value from column 'Time', but in 2nd row and other ones I need to add the value from 2nd row from 'Time' column and value from 1st row in 'C_i' column.
Final layout should looks like this:

below is the 'code' (I got stuck at the beginning...)
import pandas as pd
import sympy as sp
import numpy as np

dane = pd.read_excel(r'/Users/artur/Desktop/Studia/V semestr/IO/Sprawozdanie1_dane.xlsx')
daneSortowane = dane.sort_values('Termin (D_i)')

A: What you're trying to do is known as a cumulative sum. There is a built in function for this in pandas already, pd.cumsum()
From what I can gather from your question, adding the line:
daneSortowane['C_i'] = daneSortowane['Time'].cumsum()

Will add your C_i column as required.


text:
Q: Creating Cases in Salesforce from Social Studio how do I know to which Salesforce account Social Studio is linked to? How do I create cases and leads in Salesforce from Social Studio?

A: You need to add social accounts within Salesforce. Under set up do a quick find for social customer service. Authorize the social account you want to be added there. Once done you need to create engagement macros in social studio and direct to the salesforce org you configured in the previous step. Assuming you are not using social automate in this scenario.

A: After Connection to sales/Service cloud , you will get a option to select org while creating engagement macros. For Every Org of sales/Service cloud, there will be different org id .From there either you can select what u want to  create case or lead or both.


text:
Q: Rails 3 + Mongoid: A good way to let users sort records I need a good (which means easy and comprehensible) way to let users sort records in an app that uses Rails 3 and Mongoid.
To clarify what I mean: let's say there is a Recipe that has a number of Ingredients. At the moment, those recipes have no feature to let the user (who can edit the Recipe) sort the ingredients in a way he/she wants.
Until now I mostly did sorting stuff with a numeric sort order field where the user has to increase/decrease the number of a record to sort it up or down - there has to be a better way (gem?) to do this I guess, but I haven't found much.
Any help appreciated!

A: If your Recipe example is close to what you're doing then you should use embedded documents for your Ingredients. If you have something like this:
class Recipe
  include Mongoid::Document
  embeds_many :ingredients
  # Recipe name, ... fields.
end
class Ingredient
  include Mongoid::Document
  embedded_in :recipe
  # Ingredient name, amount, ... fields.
end

then the ingredients would actually be an array of hashes inside the recipe and recipes would look like this inside MongoDB:
{
  ingredients: [
    { ingredient... },
    ...
  ],
  name: '...',
  ...
}

Since the ingredients are an array, they are implicitly ordered and reordering them is a simple matter of moving things around in the array.
If the "ingredients" need to be separate top-level entities on their own then the embedded ingredients would reference the top-level ingredient in the usual way. If the "ingredients" are really just a list of ids then use an Array field to store them and use the order of the array elements to define the ingredient order.
You might notice that all the above are just different ways to use Array fields to handle the ordering.


text:
Q: Duvida sobre orientação a objetos em Python Eu é um colega de sala estávamos fazendo um script eu escrevi meu script
desta forma:
detalhes = programa.duracao if hasattr(programa, 'duracao') else programa.temporada

No meu caso, eu estou chamando dessa forma! O meu amigo desta forma abaixo, fiquei com duvida quanto ao jeito de escrever e não chegamos a conclusão da melhor for de se fazer a mesma coisa!
detalhes = programa.get_duracao() if hasattr(programa, '_duracao') else programa.get_temporada()

A pergunta é, qual a diferença entre usar o "_" e quando não usar? Isso não quebraria o conceito do encapsulamento?

A: @weltonvaz o caractere "_" foi utilizado devido a convenção de código do python proposto pela pep8 (documentação da PEP8: https://www.python.org/dev/peps/pep-0008/ ). De forma mais básica a pep8 propõe como boa pratica de desenvolvimento e legibilidade na escrita de código em python a criação de métodos e variáveis utilizando o formato Snake Case, onde as palavras são separadas pelo carácter _. Por exemplo, criar uma variável chamada "retornar todos valores", ficaria: retornar_todos_valores. O método seria retornar_todos_valores().
Existem outros estilos de escrita como o Camel Case, onde as palavras são escritas todas juntas, mas a primeira letra de cada palavra é escrita em maiúsculo. Esse estilo é muito utilizado no java, onde utilizando o mesmo exemplo citado a cima a escrita ficaria: retornarTodosValores().
No caso do código do seu amigo ele criou o método get para retornar o valor do atributo duracao da classe programa. É comum na programação Orientada a Objetos a criação dos métodos getters (get) e setters (set) dos atributos de uma classe, nesse caso para acessar os valores dos atributos utiliza-se os métodos get que retornam o valor do atributo e para setar valores aos atributos utiliza-se os métodos set que normalmente recebem um parâmetro que são atribuídos ao atributo da classe, por exemplo:
get_duracao(): retorna o valor do atributo duracao da sua classe programa.
set_duracao(1): adiciona o valor 1 ao atributo duracao da classe programa.
No código citado acontece que você está acessando o atributo duracao da classe pessoa diretamente (programa.duracao) e seu amigo utilizou um método para retornar o valor, por isso o código programa.get_duracao(), se você olhar a classe dele é provável que esteja parecido com isso:
class programa:

    duracao = 0

    def get_duracao():
        return duracao

Recomendo a leitura dos conceitos da orientação a objetos para melhor entender esses conceitos que citei. A Caelum possui uma apostila gratuita de Java que explica bem os conceitos de orientação a objetos, porém, na linguagem java https://www.caelum.com.br/apostila-java-orientacao-objetos/. Mas também existe muito conteúdo de orientação a objetos em python.


text:
Q: HOW : relative pronoun or relative adverb?
Relative pronoun : who, whom, whose, which, that
Relative adverb : when, where, why

Is "how" neither a relative pronoun nor an relative adverb? Then, which category does 'how' belong to?

A: "How" is a flat adverb (an adverb that has no -ly ending), and "how" is also an interrogative adverb (an adverb that is used to ask a direct question or an indirect question).{How are you doing?} Interrogative adverbs can also "modify some word or phrase in the sentence" in which they appear and "they often present a question about manner" {How did the accident happen?} (Garner, 2016, p.131). Additionally, "How" is a conjunctive adverb (an adverb that is used to connect a dependent clause to an independent clause), and conjunctive adverbs can introduce noun clauses {I don't understand how you arrived at that conclusion.} (Garner, 2016, p.133). Garner indicates 'how' is a conjunctive adverb that can introduce noun clauses; he does not give an example of 'how' connecting a dependent clause to an independent clause.
"How" is not a relative adverb because relative adverbs join "a dependent (subordinate) clause to an independent (main) clause while modifying the clause of which it is a part," and relative adverbs, as you know, introduce adjectival clauses and they introduce relative clauses. (Garner, 2016, p.132, italics mine). "How" does not introduce adjectival clauses or relative clauses. Adjectival clauses are introduced by a relative pronoun and relative clauses are also introduced by a relative pronoun. See this link for examples of relative adverbs (with examples of relative adverbs used in sentences).
"How" is also not a relative pronoun. "The most common relative pronouns are who, whom, whose, which, and that. Sometimes when and where can be used as relative pronouns as well" (Relative Pronoun, n.d.).
In summary:

*

*'How' is a flat adverb

*'How' is also an interrogative adverb and

*'How' is a conjunctive adverb

*'How' is not a relative pronoun and

*'How' is not a relative adverb

I hope this information was helpful.


text:
Q: Error while saving launch configuration in Eclipse I have some JUnit files that I need to find coverage.
I installed the EclEmma plugin and I chose the Coverage configurations.
Then in the "Class Path" I selected the 'User Entries' and then selected the "Add folder" radio button, then I selected the source of my project and pressed 'Apply' button.
The Eclipse shows an error message like this:

exception occurred while saving launch configuration - Permission Denied
  Reason :- Couldn't write launch configurations.

Anyone came across the error before?
Currently I'm launching the project from my current user account in CentOS-6.
Which file I need to update to avoid Permission Denied Error?


text:
Q: Cannot read properties of undefined when it shouldn't be undefined in discord.js command handler I created a small command handler with a simple "ping" command. However, trying to access message.channel shows up undefined. Why is this?
./index.js
//Discord, fs, prefix, client etc. declarations

client.commands = new Collection()

const files = fs.readdirSync("./commands").filter(file => file.endsWith(".js")

for (const file of files) {
  const command = require(`./commands/${file}`)
  client.commands.set(command.name, command)
}

client.on("messageCreate", message => {
  const [command, ...args] = message.content.slice(prefix.length).split(/ +/g)
  if (client.commands.has(command) {
    client.commands.get(command).execute(message, client, args)
  }
})

client.login(/*token*/)

./commands/ping.js
module.exports = {
  name: "ping",
  description: "Make me say pong",
  async execute(client, message, args) {
    message.channel.send("Pong!")
  }
}

A: While Message.channel may be valid, message is not an instance of Message. It is actually an instance of Client. The order of the arguments always matter, and putting them in the wrong order can throw TypeErrors. There is 1 simple solution here
Make the arguments in the right order! You can either change the execution, or the declaration
client.commands.get(command).execute(client, message, args)

This is really common and happens for more than sending messages to channels


text:
Q: Improve SQL Server query to convert arbitrary table to JSON After a lot of searching and piecing together the very excellent techniques for converting result sets using the FOR XML and .nodes() commands that are around the web, I was able to create this single query (not a stored procedure) which does a reasonably good job of converting any arbitrary SQL query to a JSON array.
The query will encode each data row as a single JSON object with a leading comma.
The data rows are wrapped by brackets and the whole result set is then expected to be exported to a file.
I'd like to see if anyone out there can see ways to improve its performance?
Here's the query with a sample table:
declare @xd table (col1 varchar(max), col2 int, col3 real, colNull int)

insert into @xd
select '', null, null, null
UNION ALL select 'ItemA', 123, 123.123, null
UNION ALL select 'ItemB', 456, 456.456, null
UNION ALL select '7890', 789, 789.789, null

select '[{}'
UNION ALL
select ',{' + STUFF((
    (select ','
        + '"' + r.value('local-name(.)', 'varchar(max)') + '":'
        + case when r.value('./@xsi:nil', 'varchar(max)') = 'true' then 'null'
        when isnumeric(r.value('.', 'varchar(max)')) = 1
            then r.value('.', 'varchar(max)')
        else '"' + r.value('.', 'varchar(max)') + '"'
        end
    from rows.nodes('/row/*') as x(r) for xml path(''))
    ), 1, 1, '') + '}'
from (
    -- Arbitrary query goes here, (fields go where t.* is, table where @xd t is)
    select (select t.* for xml raw,type,elements XSINIL) rows
    from @xd t
) xd
UNION ALL
select ']'

My biggest critique of it, is that it's insanely slow.
It currently takes about 3:30 for ~42,000 rows.
My other big critique is that it currently assumes that everything that looks like a number is a number.  It doesn't try to discover column type in the least (and I'm not even sure if it can).
A final minor critique is that the first data row will have a comma up front and technically it shouldn't.  To compensate for that it requires that empty JSON object in the first row that starts the JSON array.
Other critiques (preferably with solutions) invited, the only real limitation I have is that the solution be decently repeatable on many arbitrary SQL queries without having to explicitly identify the column names.
I'm using SQL Server 2012.
Thanks and to anyone else like me who was looking for a generalized SQL Results -> JSON Array converter, ENJOY!

A: I say if you really want to kick up performance, use metaprogramming.  The example below tries this with 40,000 rows and returns results in less than a second (not counting inserting the initial 40k rows, which in this example only takes about 2 seconds).  It also takes into account your data types to not enclose numbers in quotes.
declare @xd table (col1 varchar(max), col2 int, col3 real, colDate datetime, colNull int);

declare @i int = 0;

while @i < 10000 begin
    set @i += 1;
    insert into @xd
    select '', null, null, null, null
    union all select 'ItemA', 123, 123.123, getDate(), null
    union all select 'ItemB', 456, 456.456, getDate(), null
    union all select '7890', 789, 789.789, getDate(), null;
end;

select *
into #json_base
from (
    -- Insert SQL Statement here
    select * from @xd
) t;

declare @columns table (
    id int identity primary key,
    name sysname,
    datatype sysname,
    is_number bit,
    is_date bit);

insert into @columns(name, datatype, is_number, is_date)
select columns.name, types.name,
       case when number_types.name is not NULL
            then 1 else 0
       end as is_number,
       case when date_types.name is not NULL
            then 1 else 0
       end as is_date
from tempdb.sys.columns
join tempdb.sys.types
    on (columns.system_type_id = types.system_type_id)
left join (values ('int'), ('real'), ('numeric'),
                  ('decimal'), ('bigint'), ('tinyint')) as number_types(name)
    on (types.name = number_types.name)
left join (values ('date'), ('datetime'), ('datetime2'),
                  ('smalldatetime'), ('time'), ('datetimeoffset')) as date_types(name)
    on (types.name = date_types.name)
where object_id = OBJECT_ID('tempdb..#json_base');

declare @field_list varchar(max) = STUFF((
    select '+'',''+' + QUOTENAME(QUOTENAME(name, '"') + ':', '''')
           + '+' + case when is_number = 1
                        then 'COALESCE(LTRIM('
                                + QUOTENAME(name) + '),''null'')'
                        when is_date = 1
                        then 'COALESCE(QUOTENAME(LTRIM(convert(varchar(max), '
                                + QUOTENAME(name) + ', 126)),''"''),''null'')'
                        else 'COALESCE(QUOTENAME('
                                + QUOTENAME(name) + ',''"''),''null'')'
                   end
    from @columns
    for xml path('')),
    1, 5, '');

create table #json_result (
    id int identity primary key,
    line varchar(max));

declare @sql varchar(max) = REPLACE(
    'insert into #json_result '
  + 'select '',{''+{f}+''}'' '
  + 'from #json_base', '{f}', @field_list);

exec(@sql);

update #json_result
set line = STUFF(line, 1, 1, '')
where id = 1;

select '['
UNION ALL
select line
from #json_result
UNION ALL
select ']';

drop table #json_base;
drop table #json_result;

A: From Firoz Ansari:
CREATE PROCEDURE [dbo].[GetJSON] (
@ParameterSQL AS VARCHAR(MAX)
)
AS
BEGIN

DECLARE @SQL NVARCHAR(MAX)
DECLARE @XMLString VARCHAR(MAX)
DECLARE @XML XML
DECLARE @Paramlist NVARCHAR(1000)
SET @Paramlist = N'@XML XML OUTPUT'
SET @SQL = 'WITH PrepareTable (XMLString) '
SET @SQL = @SQL + 'AS ( '
SET @SQL = @SQL + @ParameterSQL+ ' FOR XML RAW, TYPE, ELEMENTS '
SET @SQL = @SQL + ') '
SET @SQL = @SQL + 'SELECT @XML = XMLString FROM PrepareTable '
EXEC sp_executesql @SQL, @Paramlist, @XML=@XML OUTPUT
SET @XMLString = CAST(@XML AS VARCHAR(MAX))

DECLARE @JSON VARCHAR(MAX)
DECLARE @Row VARCHAR(MAX)
DECLARE @RowStart INT
DECLARE @RowEnd INT
DECLARE @FieldStart INT
DECLARE @FieldEnd INT
DECLARE @Key VARCHAR(MAX)
DECLARE @Value VARCHAR(MAX)

DECLARE @StartRoot VARCHAR(100); SET @StartRoot = ''
DECLARE @EndRoot VARCHAR(100); SET @EndRoot = ''
DECLARE @StartField VARCHAR(100); SET @StartField = ''

SET @RowStart = CharIndex(@StartRoot, @XMLString, 0)
SET @JSON = ''
WHILE @RowStart > 0
BEGIN
    SET @RowStart = @RowStart+Len(@StartRoot)
    SET @RowEnd = CharIndex(@EndRoot, @XMLString, @RowStart)
    SET @Row = SubString(@XMLString, @RowStart, @RowEnd-@RowStart)
    SET @JSON = @JSON+'{'

    -- for each row
    SET @FieldStart = CharIndex(@StartField, @Row, 0)
    WHILE @FieldStart > 0
    BEGIN
        -- parse node key
        SET @FieldStart = @FieldStart+Len(@StartField)
        SET @FieldEnd = CharIndex(@EndField, @Row, @FieldStart)
        SET @Key = SubString(@Row, @FieldStart, @FieldEnd-@FieldStart)
        SET @JSON = @JSON+'"'+@Key+'":'

        -- parse node value
        SET @FieldStart = @FieldEnd+1
        SET @FieldEnd = CharIndex('0 SET @JSON = SubString(@JSON, 0, LEN(@JSON))
    SET @JSON = @JSON+'},'
    --/ for each row

    SET @RowStart = CharIndex(@StartRoot, @XMLString, @RowEnd)
END
IF LEN(@JSON) > 0 SET @JSON = SubString(@JSON, 0, LEN(@JSON))
SET @JSON = '[' + @JSON + ']'
SELECT @JSON
END


text:
Q: Tables do not show in QGIS PostGIS I've created user profiles for my teammates to connect to my postGIS database with QGIS.
with my own user account I am able to successfully connect to my postGIS database on AWS RDS using QGIS 2.18.
user creation SQL:
CREATE USER foobar WITH
    LOGIN
    NOSUPERUSER
    NOCREATEDB
    NOCREATEROLE
    INHERIT
    NOREPLICATION
    CONNECTION LIMIT -1
    PASSWORD 'xxxxxx';

And granted permissions:
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA test TO foobar;

Am I missing a step? When I connect in QGIS, I only see an empty public schema.
EDIT: In addition to the accepted answer, one can also change the default privileges so newly created tables are shown automatically in QGIS:
ALTER DEFAULT PRIVILEGES IN SCHEMA test GRANT ALL ON TABLES to foobar;

A: You also need to grant usage on your schema:
GRANT USAGE ON SCHEMA test TO foobar;


text:
Q: Order By clause causing Performance Hit I've a SQL query that uses pipelined table function as below.
select col1,col2,... col75 from table(pipelinedtablefunction)
order by col1

This query returns 100 000 records in 14 mins. If I remove the order by clause and execute the below query, the query runs in 1 second and retrieves same result.
select col1,col2,... col75 from table(pipelinedtablefunction)

I used order by clause inside pipelined function in the cursor query and I faced the same problem. Is there any way to resolve and improve the performance?

A: I found the problem, in one of the columns col50 , I've called a user defined function like below which actually executes for each row, that caused the time.
When I commented out that column from the select query, it runs within a second.
select col1,col2, ../*my_fun(col50)*/, col51.. col75 from table(pipelinedtablefunction)
order by col1

We have tuned the function and now it is fine.


text:
Q: Ignite: ClassNotFoundException for a class of another service I created a spring service (Service A) which uses an Ignite Cache. The Ignite Cache preloads data from a database using the CacheStoreAdapter. The cache configuration is:
final CacheConfiguration<String, StandardItem> cacheConfiguration = new CacheConfiguration<>(Identifiers.IGNITE_ITEM);

cacheConfiguration.setName(Identifiers.IGNITE_ITEM);
cacheConfiguration.setIndexedTypes(String.class, IgniteItem.class);
cacheConfiguration.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
cacheConfiguration.setCacheStoreFactory(FactoryBuilder.factoryOf(StandardItemCacheStore.class.getName()));
cacheConfiguration.setReadThrough(true);
cacheConfiguration.setWriteThrough(true);
cacheConfiguration.setCopyOnRead(false);
cacheConfiguration.setCacheMode(CacheMode.LOCAL);
cacheConfiguration.setOnheapCacheEnabled(true);

return cacheConfiguration;

The service itself is working great. But I have another service (Service B) which uses Ignite on the same network. The Configuration of the other service is the following:
final CacheConfiguration<String, String> cacheConfiguration = new CacheConfiguration<>(Constants.IGNITE_RESULT_CACHE);

cacheConfiguration.setName(Constants.IGNITE_RESULT_CACHE);
cacheConfiguration.setIndexedTypes(String.class, String.class);
cacheConfiguration.setAtomicityMode(CacheAtomicityMode.ATOMIC);
cacheConfiguration.setCopyOnRead(false);
cacheConfiguration.setCacheMode(CacheMode.LOCAL);
cacheConfiguration.setOnheapCacheEnabled(true);
cacheConfiguration.setEvictionPolicy(new LruEvictionPolicy(1_000_000));

final IgniteConfiguration igniteConfiguration = new IgniteConfiguration();
igniteConfiguration.setIgniteInstanceName("ServiceGrid");
igniteConfiguration.setCacheConfiguration(cacheConfiguration);
igniteConfiguration.setIncludeEventTypes();

return igniteConfiguration;

But for this service now I get exceptions:
2017-12-01 10:25:39.512 ERROR 39 --- [34%ServiceGrid%] .c.d.d.p.GridDhtPartitionsExchangeFuture : Failed to reinitialize local partitions (preloading will be stopped): GridDhtPartitionExchangeId [topVer=AffinityTopologyVersion [topVer=6, minorTopVer=1], nodeId=79de964e, evt=DISCOVERY_CUSTOM_EVT]

java.lang.RuntimeException: Failed to create an instance of io.mio.scap.dao.cache.IgniteItemCacheStore
        at javax.cache.configuration.FactoryBuilder$ClassFactory.create(FactoryBuilder.java:134) ~[cache-api-1.0.0.jar!/:na]
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.createCache(GridCacheProcessor.java:1392) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.prepareCacheStart(GridCacheProcessor.java:1867) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.CacheAffinitySharedManager.onCacheChangeRequest(CacheAffinitySharedManager.java:748) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture.onCacheChangeRequest(GridDhtPartitionsExchangeFuture.java:838) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture.init(GridDhtPartitionsExchangeFuture.java:579) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeWorker.body(GridCachePartitionExchangeManager.java:1901) [ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:110) [ignite-core-2.2.0.jar!/:2.2.0]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
Caused by: java.lang.ClassNotFoundException: io.mio.scap.dao.cache.IgniteItemCacheStore
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_151]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_151]
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:93) ~[app.jar:na]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_151]
        at javax.cache.configuration.FactoryBuilder$ClassFactory.create(FactoryBuilder.java:130) ~[cache-api-1.0.0.jar!/:na]
        ... 8 common frames omitted

2017-12-01 10:25:39.513  INFO 39 --- [34%ServiceGrid%] .c.d.d.p.GridDhtPartitionsExchangeFuture : Snapshot initialization completed [topVer=AffinityTopologyVersion [topVer=6, minorTopVer=1], time=0ms]
2017-12-01 10:25:39.516 ERROR 39 --- [34%ServiceGrid%] .i.p.c.GridCachePartitionExchangeManager : Failed to wait for completion of partition map exchange (preloading will not start): GridDhtPartitionsExchangeFuture [dummy=false, forcePreload=false, reassign=false, discoEvt=DiscoveryCustomEvent [customMsg=null, affTopVer=AffinityTopologyVersion [topVer=6, minorTopVer=1], super=DiscoveryEvent [evtNode=TcpDiscoveryNode [id=79de964e-08e9-4a09-b915-4a221d10c642, addrs=[127.0.0.1, 172.19.0.10], sockAddrs=[1f3ec767d8a2/172.19.0.10:47500, /127.0.0.1:47500], discPort=47500, order=6, intOrder=6, lastExchangeTime=1512123936779, loc=false, ver=2.2.0#20170915-sha1:5747ce6b, isClient=false], topVer=6, nodeId8=68a843cf, msg=null, type=DISCOVERY_CUSTOM_EVT, tstamp=1512123939493]], crd=TcpDiscoveryNode [id=6e5c36ce-5042-4f9b-b507-3f9ed4eb1384, addrs=[127.0.0.1, 172.19.0.11], sockAddrs=[5b8f17420165/172.19.0.11:47500, /127.0.0.1:47500], discPort=47500, order=1, intOrder=1, lastExchangeTime=1512123917048, loc=false, ver=2.2.0#20170915-sha1:5747ce6b, isClient=false], exchId=GridDhtPartitionExchangeId [topVer=AffinityTopologyVersion [topVer=6, minorTopVer=1], nodeId=79de964e, evt=DISCOVERY_CUSTOM_EVT], added=true, initFut=GridFutureAdapter [ignoreInterrupts=false, state=DONE, res=false, hash=2088336463], init=false, lastVer=null, partReleaseFut=null, exchActions=null, affChangeMsg=null, skipPreload=false, clientOnlyExchange=false, initTs=1512123939493, centralizedAff=false, changeGlobalStateE=null, forcedRebFut=null, done=true, evtLatch=0, remaining=[a9181efd-950b-4d23-9697-a301c81094aa, 2fd78465-8a0f-4318-bded-716348753cef, 79de964e-08e9-4a09-b915-4a221d10c642, 3fa0ac5d-c464-46a7-9dac-c56873b64dd0, 6e5c36ce-5042-4f9b-b507-3f9ed4eb1384], super=GridFutureAdapter [ignoreInterrupts=false, state=DONE, res=java.lang.RuntimeException: Failed to create an instance of io.mio.scap.dao.cache.IgniteItemCacheStore, hash=1326392751]]

org.apache.ignite.IgniteCheckedException: Failed to create an instance of io.mio.scap.dao.cache.IgniteItemCacheStore
        at org.apache.ignite.internal.util.IgniteUtils.cast(IgniteUtils.java:7229) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.util.future.GridFutureAdapter.resolve(GridFutureAdapter.java:258) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.util.future.GridFutureAdapter.get0(GridFutureAdapter.java:206) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.util.future.GridFutureAdapter.get(GridFutureAdapter.java:158) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeWorker.body(GridCachePartitionExchangeManager.java:1911) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:110) [ignite-core-2.2.0.jar!/:2.2.0]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
Caused by: java.lang.RuntimeException: Failed to create an instance of io.mio.scap.dao.cache.IgniteItemCacheStore
        at javax.cache.configuration.FactoryBuilder$ClassFactory.create(FactoryBuilder.java:134) ~[cache-api-1.0.0.jar!/:na]
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.createCache(GridCacheProcessor.java:1392) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.GridCacheProcessor.prepareCacheStart(GridCacheProcessor.java:1867) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.CacheAffinitySharedManager.onCacheChangeRequest(CacheAffinitySharedManager.java:748) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture.onCacheChangeRequest(GridDhtPartitionsExchangeFuture.java:838) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture.init(GridDhtPartitionsExchangeFuture.java:579) ~[ignite-core-2.2.0.jar!/:2.2.0]
        at org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager$ExchangeWorker.body(GridCachePartitionExchangeManager.java:1901) ~[ignite-core-2.2.0.jar!/:2.2.0]
        ... 2 common frames omitted
Caused by: java.lang.ClassNotFoundException: io.mio.scap.dao.cache.IgniteItemCacheStore
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_151]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_151]
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:93) ~[app.jar:na]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_151]
        at javax.cache.configuration.FactoryBuilder$ClassFactory.create(FactoryBuilder.java:130) ~[cache-api-1.0.0.jar!/:na]
        ... 8 common frames omitted

2017-12-01 10:25:40.890  INFO 39 --- [34%ServiceGrid%] o.apache.ignite.internal.exchange.time   : Started exchange init [topVer=AffinityTopologyVersion [topVer=6, minorTopVer=2], crd=false, evt=18, node=TcpDiscoveryNode [id=68a843cf-2970-4f2a-930b-c9a36b3942ce, addrs=[127.0.0.1, 172.19.0.9], sockAddrs=[/127.0.0.1:47500, 2a1936cdc613/172.19.0.9:47500], discPort=47500, order=4, intOrder=4, lastExchangeTime=1512123940480, loc=true, ver=2.2.0#20170915-sha1:5747ce6b, isClient=false], evtNode=TcpDiscoveryNode [id=68a843cf-2970-4f2a-930b-c9a36b3942ce, addrs=[127.0.0.1, 172.19.0.9], sockAddrs=[/127.0.0.1:47500, 2a1936cdc613/172.19.0.9:47500], discPort=47500, order=4, intOrder=4, lastExchangeTime=1512123940480, loc=true, ver=2.2.0#20170915-sha1:5747ce6b, isClient=false], customEvt=CacheAffinityChangeMessage [id=2b0ab911061-e15fbf79-7ad2-420e-b870-5a61d94b442c, topVer=AffinityTopologyVersion [topVer=6, minorTopVer=0], exchId=null, partsMsg=null, exchangeNeeded=true]]
2017-12-01 10:25:40.896  INFO 39 --- [34%ServiceGrid%] .c.d.d.p.GridDhtPartitionsExchangeFuture : Finished waiting for partition release future [topVer=AffinityTopologyVersion [topVer=6, minorTopVer=2], waitTime=0ms]
2017-12-01 10:25:40.898  INFO 39 --- [34%ServiceGrid%] o.apache.ignite.internal.exchange.time   : Finished exchange init [topVer=AffinityTopologyVersion [topVer=6, minorTopVer=2], crd=false]
2017-12-01 10:25:40.970  INFO 39 --- [39%ServiceGrid%] .c.d.d.p.GridDhtPartitionsExchangeFuture : Snapshot initialization completed [topVer=AffinityTopologyVersion [topVer=6, minorTopVer=2], time=0ms]
2017-12-01 10:25:40.976  INFO 39 --- [34%ServiceGrid%] .i.p.c.GridCachePartitionExchangeManager : Skipping rebalancing (nothing scheduled) [top=AffinityTopologyVersion [topVer=6, minorTopVer=2], evt=DISCOVERY_CUSTOM_EVT, node=6e5c36ce-5042-4f9b-b507-3f9ed4eb1384]

My question now is: Why does Service B need to know/have the IgniteItemCacheStore which is not even used by that service, its only used by Service A.

A: All Ignite nodes need to have all caches' configurations, and cache store is a part of cache configuration, therefore all Ignite nodes need all classes used by cache store.
There are ways of sidestep this, such as factory that returns lazily-initialized proxy of CacheStore, your mileage may vary.


text:
Q: How to solve the error: 'tuple' object has no attribute 'decode' with django-channels When I tried to execute the channels' tutorial in order to establishing the django website with websocket, the error message emerged:
AttributeError: 'tuple' object has no attribute 'decode'
I just executed following code:
$ python3 manage.py shell
>>> import channels.layers
>>> channel_layer = channels.layers.get_channel_layer()
>>> from asgiref.sync import async_to_sync
>>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})

Tutorial link:
https://channels.readthedocs.io/en/stable/tutorial/part_2.html
Environment:
Ubuntu 20.04LTS with Python 3.8.10
django 4.1.3
channels 4.0.0
channels-redis 4.0.0
daphne 4.0.0
asgiref 3.5.2
I think the problem may caused by asgiref, but there is no documentation for reference.

A: I had the same bug, and because I encountered this issue I downgraded to channels_redis v 3.4.0 and the bug went away. Waiting for a nicer solution, I hope it will help.


text:
Q: vbs script what to replace user in a redirectory? Hi i wanted to know how to replace the user in a directory ? this is my code :
Dim oFS,oFl
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFl = oFSO.GetFile("myexe.exe")
oFl.Move "C:\Users\myusername\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

I dont know what to replace "myusername" to work with any computer. Thanks for the help

A: If you're looking for the currently logged on user you could pull it from a windows environment variable using the shell object like this.
Dim objShell : Set objShell = CreateObject( "WScript.Shell" )
Dim strName : strName = objShell.ExpandEnvironmentStrings( "%USERNAME%" )

Or you could pull it from the network object like this.
Dim objNetwork : Set objNetwork = CreateObject("WScript.Network")
Dim strName : strName = objNetwork.Name

Once you have the username it looks like you're just building a string with the file path it to run an application, which you could use concatenation for.
objShell.Exec("C:\Users\" & strName & "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\myexe.exe")
Set objShell = Nothing


text:
Q: Bezier Curve always the same length I'm working on a game in HTML5 canvas.
I want is draw an S-shaped cubic bezier curve between two points, but I'm looking for a way to calculate the coordinates of the control points so that the curve itself is always the same length no matter how close those points are, until it reaches the point where the curve becomes a straight line.

A: This is solvable numerically. I assume you have a cubic bezier with 4 control points.
at each step you have the first (P0) and last (P3) points, and you want to calculate P1 and P2 such that the total length is constant.
Adding this constraint removes one degree of freedom so we have 1 left (started with 4, determined the end points (-2) and the constant length is another -1). So you need to decide about that.
The bezier curve is a polynomial defined between 0 and 1, you need to integrate on the square root of the sum of elements (2d?). for a cubic bezier, this means a sqrt of a 6 degree polynomial, which wolfram doesn't know how to solve. But if you have all your other control points known (or known up to a dependency on some other constraint) you can have a save table of precalculated values for that constraint.

A: Is it really necessary that the curve is a bezier curve? Fitting two circular arcs whose total length is constant is much easier. And you will always get an S-shape.
Fitting of two circular arcs:

Let D be the euclidean distance between the endpoints. Let C be the constant length that we want. I got the following expression for b (drawn in the image):
b = sqrt(D*sin(C/4)/4 - (D^2)/16)

I haven't checked if it is correct so if someone gets something different, leave a comment.
EDIT: You should consider the negative solution too that I obtain when solving the equation and check which one is correct.
b = -sqrt(D*sin(C/4)/4 - (D^2)/16)

A: Here's a working example in SVG that's close to correct:
http://phrogz.net/svg/constant-length-bezier.xhtml

I experimentally determined that when the endpoints are on top of one another the handles should be
desiredLength × cos(30°)
away from the handles; and (of course) when the end points are at their greatest distance the handles should be on top of one another. Plotting all ideal points looks sort of like an ellipse:

The blue line is the actual ideal equation, while the red line above is an ellipse approximating the ideal. Using the equation for the ellipse (as my example above does) allows the line to get about 9% too long in the middle.
Here's the relevant JavaScript code:
// M is the MoveTo command in SVG (the first point on the path)
// C is the CurveTo command in SVG:
//   C.x is the end point of the path
//   C.x1 is the first control point
//   C.x2 is the second control point
function makeFixedLengthSCurve(path,length){
  var dx   = C.x - M.x, dy = C.y - M.y;
  var len  = Math.sqrt(dx*dx+dy*dy);
  var angle = Math.atan2(dy,dx);
  if (len >= length){
    C.x  = M.x + 100 * Math.cos(angle);
    C.y  = M.y + 100 * Math.sin(angle);
    C.x1 = M.x; C.y1 = M.y;
    C.x2 = C.x; C.y2 = C.y;
  }else{
    // Ellipse of major axis length and minor axis length*cos(30°)
    var a = length, b = length*Math.cos(30*Math.PI/180);
    var handleDistance = Math.sqrt( b*b * ( 1 - len*len / (a*a) ) );
    C.x1 = M.x + handleDistance * Math.sin(angle);
    C.y1 = M.y - handleDistance * Math.cos(angle);
    C.x2 = C.x - handleDistance * Math.sin(angle);
    C.y2 = C.y + handleDistance * Math.cos(angle);
  }
}


text:
Q: Animate a position change along the curve for every iteration I've only had few previous experiences on Mathematica before. So basically an entry-level question that harasses a rookie like me.
I made the following attempt using bisection method to calculate the real root for the function $f(x)=-x^3+2x^2-2$ with basic while loop and if:

a = -5;
b = 5;
m = (a + b)/2;
While [ Abs[f[m]] > 0.000001,
 If[f[m]*f[a] < 0, b = m, a = m];
 m = (a + b)/2]
The answer turns out to be $-(14080895/16777216)$ that is correct.
Then, I wanted to create a animation that shows the change of position of a dot along the function curve for each iteration of the bisection method. But I tried several times with different codes that all fails to do so. One confusion is I am not sure how to set up a stepsize here which involves not a constant number but "While" and "If".
Would you please help me animate the iteration with while and if?

A: Perhaps a more Mathematicaish way of doing more or less the same is with NestWhile
A possible code could be
NestWhile[
 With[{m = Mean[#]},
   If[
    Negative[f[First@#] f[m]], {First@#, m}, {m, Last@#}
    ]] &, {-5, 5},
 Abs@f@Mean@# > 0.000001 &
 ]

If you have your code written with NestWhile, what you want is as simple as changing NestWhile to NestWhileList.
steps = NestWhileList[
   With[{m = Mean[#]},
     If[
      Negative[f[First@#] f[m]], {First@#, m}, {m, Last@#}
      ]] &, {-5, 5},
   Abs@f@Mean@# > 0.000001 &
   ];

ListLinePlot[Mean /@ steps, PlotRange -> Full]

A: Adding a Sow to your loop let's you store the intermediate values of m. You can grab them later with Reap and animate them with Animate:
a = -5; b = 5; m = (a + b)/2;
steps =
 Reap[While[Abs[f[m]] > 0.000001,
    Sow[m] If[f[m]*f[a] < 0, b = m, a = m]; m = (a + b)/2]][[2, 1]];

Animate[
 Plot[f[x], {x, -2.5, -0.5},
  Epilog -> {Red, PointSize[0.03],
    Point@{steps[[i]], f@steps[[i]]}}], {i, 1, Length[steps], 1}
 ]

A: First, what follows is an improvement of your bisection routine, which avoids needless overflow and repeated function evaluations. As with Sjoerd, we use the Sow[]/Reap[] pair for collecting intermediate results:
f[x_] := -2 + 2 x^2 - x^3;
acc = 10.^-6;
a = -5; b = 5;
u = f[a]; v = f[b]; m = $Failed;
pts = Reap[While[NonNegative[u] =!= NonNegative[v],
         m = a + (b - a)/2; h = f[m]; Sow[{m, h}];
         If[NonNegative[u] =!= NonNegative[h],
            (* then *) b = m; v = h,
            (* else *) a = m; u = h];
         If[Abs[h] <= acc, Break[]];
         ]][[2, 1]];

I used OP's absolute termination criterion in the code above, but a relative criterion like Abs[b - a] <= (Abs[a] + Abs[b])*tol is usually more preferable in practice.
Having gathered up all required intermediate results in pts, we can elect to either show progress all at once:
Plot[f[x], {x, -5/2, 0},
 Epilog -> {Arrow /@ Partition[pts, 2, 1], {AbsolutePointSize[7], Red,
     Point[First[pts]]}, {AbsolutePointSize[7], Blue,
    Point[Last[pts]]}}, Frame -> True]

or show it gradually:
ListAnimate[
 MapIndexed[
  Plot[f[x], {x, -5/2, 0},
    Epilog -> {Arrow[#1], {AbsolutePointSize[7], Red,
       Point[First[pts]]}, {AbsolutePointSize[7], Blue,
       Point[Last[pts]]}}, Frame -> True,
    PlotLabel -> StringForm["Iteration `1`", First[#2]]] &,
  Partition[pts, 2, 1]]]

In both cases, we use Arrow[] objects to indicate the direction of progress, a red point to denote the midpoint of the initial interval, and a blue point to denote the final result.


text:
Q: Пишу pipeline jenkins который создает image docker из dockerfile и пушит его на dockerhub pipeline состоит из трех шагов.Первые два отлично работают.Возникла проблема с отправкой готового image в свой репозиторий на dockerhub.
вот весь третий шаг
stage('Deploy image') {
            steps {
                script{
                    docker.withRegistry('https://hub.docker.com', registryCredential ) {
                        dockerImage.push("$BUILD_NUMBER")
                         dockerImage.push('latest')

в environment прописано что registryCredential= 'dockerhub'(dockerhub это логин и пароль от моего аккаунта на  https://hub.docker.com)
Выдает следующую ошибку
$ docker login -u tilk9092 --password-stdin https://hub.docker.com
Error response from daemon: login attempt to https://hub.docker.com/v2/ failed with status: 404 Not Found
[Pipeline] // withDockerRegistry
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: docker login failed
Finished: FAILURE

Идеи?

A: Решение следующее,в энвах объявляется переменная
dockerImage = ''

Соответственно последний шаг выглядит так
stage('Deploy image') {
        steps {
            script{
                docker.withRegistry('', registryCredential ) {
                    dockerImage.push("$BUILD_NUMBER")
                     dockerImage.push('latest')

A: Насколько знаю, второй аргумент у docker.withRegistry(...) - это ID credentials.
Добавлен ли в "Credentials -> System -> Global credentials -> Add Credentials" credential с ID dockerhub с вашим логином и паролем к Docker Hub?
Больше информации тут.


text:
Q: Phaserjs scaleManager add white strip on stage I am working with Phaser.js v2.6.2. When I try to use this.game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;, it adds a white strip on top of Stage area. If I remove this.game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; white strip is gone but stage not scaled.
I dont know what is the problem, I need some help here. Screenshot is attached.
My code is
    var game = new Phaser.Game(800, 250, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {
  game.load.image('background', 'images/gamebg1.jpg');

}

function create() {
  game.add.sprite(0, 0, 'background');
  this.game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
  this.scale.pageAlignHorizontally = true;
  this.scale.pageAlignVertically = true;
}

function update() {
}

NOTE: It only happen in emulator view, chrome.

A: I had a similar problem. I think it has to do with the page giving margin and or padding to the html or body tags.
Try adding some styling to the html and body elements, Make the margin and padding 0 like so:
  <style>
     * {
       padding: 0;
       margin: 0;
     }
  </style>


text:
Q: HTML showing the code as text instead of doing the function I'm new to making websites, only got some notions of C++. So I have this code
in HTML:

Click the button to trigger a function ".

<button onclick="myFunction()">Generate question</button>

And this in JavaScript:
var myArray = ['Question 1', 'Test2', 'Practise 3'];
var rand = Math.floor(Math.random() * myArray.length);

function showquote(){
    document.getElementById('quote').innerHTML = myArray[rand];
                    }
showquote();

When the button is clicked, this line appears:
function showquote(){ document.getElementById('quote').innerHTML = myArray[rand]; }

As I said, I'm just trying things in this languaje I barely know about, am I not invoking the function right? Thanks in advance.

A: function myFunction()
{
        document.getElementById("quote").innerHTML = showquote;
}

should be
function myFunction()
{
        showquote();
}

Click here for an executable demo of the solution above.
Reasoning
When you do
document.getElementById("quote").innerHTML = showquote;

You are assigning to the inner HTML the source code of the showquote function. Which is why you get function showquote(){ document.getElementById('quote').innerHTML = myArray[rand]; } (the source code of showquote) shown in the page.
So, what you really want to do is just call the showquote function, because that function alters the HTML alone. Thus the correct expression being showquote(), which invokes the showcode function.
Other improvements
Since now your myFunction is just a call to  showquote:
function myFunction()
{
        showquote();
}

Then  you could actually remove it and use showquote directly in the HTML element.
<button onclick="showquote()">Generate question</button>

Another thing is, inside your JavaScript file, your first invocation of showquote, right after its declaration, in here:
function showquote() {
      document.getElementById('quote').innerHTML = myArray[rand];
}
showquote(); // <----- this is the invocation I'm talking about

Is goint to yield an error. Simply because its code tries to find the element with id = quote (here: document.getElementById('quote')) and at the point this JavaScript code is executing, such element does not exist yet. Thus you getting an error at that point.
The solution is here is maybe just not call showquote at all. Or call it in a


text:
Q: Good books on OCaml What are the good books on OCaml, which considered as a must read for OCaml developers on all levels?
I came across "Real World OCaml" by Yaron Minsky and Co. (https://realworldocaml.org/). It is quite a good introduction into the language, although biased towards Core library and its features. And so far I could find nothing more descriptive.

A: Start at this page. I would suggest to read Jason Hickey's book... and all others in order. There is also a new book OCaml from the very begining, although I haven't read it myself (only few chapters), I would recommend it.


text:
Q: Convert base 10 colors OR hex colors to ANSI colors in JavaScript? The title pretty much says it all. I need to know a way I can convert either base 10 colors OR hex colors to ANSI colors that I can use in the terminal (for example \u001b[31m which is red in ANSI colors).
Either a JavaScript solution or a JS library would be great!

A: Looking at ANSI Escape Codes I am seeing a way to use RGB colors in ANSI, so you can create a function that takes hex colors and converts them to RGB, and I'm assuming by base 10 colors you already mean RGB
So we can check to see if we have a hex color by seeing if the first character is a "#"
if (color.toString()[0] == "#") { /* then you have yourself a hex color, let's make it RGB*/ }
function hexToRGB(color) {
    color = color.toString();
    var r = parseInt(color.substring(1, 3), 16);
    var g = parseInt(color.substring(3, 5), 16);
    var b = parseInt(color.substring(5, 7), 16);
    return `rgb(${r}, ${g}, ${b})`;
}

So after that you will have your RGB (assuming your hex color is in the form of #FFFFFF)
Use this as a guide to take your RGB string and format it into an ANSI Escape Code:

A: There are several JS libraries that support ANSI rgb and hex colors:

*

*ansis

*chalk
Usage examples:
import ansis from 'ansis';

// using standard named 16 colors
ansis.red('some text')

// red text
ansis.rgb(200, 0, 0)('some text')

// bold orange text on grey background
ansis.hex('#FF4500').bgHex('#333').bold('some bold text')

Usage examples with imported colors and template literal syntax:
import { red, green, hex } from 'ansis/colors';

// using standard named 16 colors
red`some text`

// bold orange text on grey background
hex('#FF4500').bgHex('#333').bold`some bold text`

// nested color strings
hex('#FF4500')`orange ${green.bold`my bold green text`} orange`;


text:
Q: SQLAlchemy tutorial on select statement Im trying to follow sqlalchemy tutorial  from the below site,
http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html

Im really stuck while doing the select statements,
As per the tutorial,the selects are done as below but I dont understand the part where he uses "users.c.name == 'John'" in the users.select. what is the "users.c" in the statement?
shouln't users.name will just suffice?
from sqlalchemy import *

# Let's re-use the same database as before
db = create_engine('sqlite:///tutorial.db')

db.echo = True  # We want to see the SQL we're creating

metadata = BoundMetaData(db)

# The users table already exists, so no need to redefine it. Just
# load it from the database using the "autoload" feature.
users = Table('users', metadata, autoload=True)

def run(stmt):
    rs = stmt.execute()
    for row in rs:
        print row

# Most WHERE clauses can be constructed via normal comparisons
s = users.select(users.c.name == 'John')
run(s)
s = users.select(users.c.age < 40)
run(s)

A: To answer the c part of the question:
users is a Table instance which represents a table in the database
users.c is a Table.c, simply an alias to to Table.columns, so this is how one accesses table columns.
As for the tutorial:
The link you provided refers to the sqlalchemy version 0.2. Needless to say, it is very-very old. Please consider official sqlalchemy documentation and specifically for your case the SQL Expression Language tutorial.