问:
__sync_bool_compare_and_swap Compiler Flags and Includes
I am working on a lock free data structure, and am trying to CAS pointers.

When using compare and swap, what flags should I pass into the compiler?
I have gotten a license for http://locklessinc.com/ memory allocator.
I am also using netbeans 7.

Currently The only flags I have are under the linker, -march=native -lllalloc.

However when I run the program I get weird memory issues.
I think I may be missing a flag or two...
Also netbeans says "unable to resolve identifier __sync_bool_compare_and_swap" but it still compiles it.

Anyone have any ideas?

Data Structure:

```<code>struct Ambigous
{
    short type;
    union{
        struct{
            bool inCleanup;
            KEY key;
            VALUE value;
        };
        Ambigous* volatile list[MAIN_SIZE];//CHANGED ordering, still have netbeans error
    };

};
</code>```

My Compare and swap code

```<code>bool res= __sync_bool_compare_and_swap(&(local->list[pos]), current_node, new_node);
</code>```

How I allocate memory:

```<code>Ambigous *temp_spine = (Ambigous *) calloc(1,sizeof (Ambigous));
</code>```

答:
__sync_bool_compare_and_swap is a GCC intrinsic. You don't need any particular compiler flags for it; however, your IDE won't be able to find its definition, because it doesn't have one. And it may not work on other compilers; eg, the Visual Studio compilers call it InterlockedCompareExchange

As for where your problem is, it's hard to say without seeing the rest of your code. Lockless algorithms are very tricky to get right; it's all too easy to miss some small race condition. Stick to locks unless you have a very good reason to do otherwise.

Body:
I am working on a lock free data structure, and am trying to CAS pointers.

When using compare and swap, what flags should I pass into the compiler?
I have gotten a license for http://locklessinc.com/ memory allocator.
I am also using netbeans 7.

Currently The only flags I have are under the linker, -march=native -lllalloc.

However when I run the program I get weird memory issues.
I think I may be missing a flag or two...
Also netbeans says "unable to resolve identifier __sync_bool_compare_and_swap" but it still compiles it.

Anyone have any ideas?

Data Structure:

struct Ambigous
{
    short type;
    union{
        struct{
            bool inCleanup;
            KEY key;
            VALUE value;
        };
        Ambigous* volatile list[MAIN_SIZE];//CHANGED ordering, still have netbeans error
    };

};

My Compare and swap code

bool res= __sync_bool_compare_and_swap(&(local->list[pos]), current_node, new_node);

How I allocate memory:

Ambigous *temp_spine = (Ambigous *) calloc(1,sizeof (Ambigous));


来源: stackexchange

问:
How do I change the background color of the ActionBar of an ActionBarActivity using XML?
Details:

I'm extending ActionBarActivity.

Eclipse and SDK fully patched as of 2011-11-06.

```<code><uses-sdk android:minSdkVersion="4" android:targetSdkVersion="14" />
</code>```

Deployed to Samsung device with Android 2.3.3

Application has android:theme="@android:style/Theme.Light"

Issue: application is light, but ActionBar is blue with grey icons, hardly visible against the blue background color. I also want the ActionBar to be light, so they grey icons are more visible.

I've tried modifying the styles but to no avail.

I'm probably missing something trivial.

How do I change the background color of the ActionBar of an ActionBarActivity using XML ?

答:
If you are using androidx AppCompact. Use below code.</p>

```<code>androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable("Color"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Details:

I'm extending ActionBarActivity.

Eclipse and SDK fully patched as of 2011-11-06.

<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="14" />

Deployed to Samsung device with Android 2.3.3

Application has android:theme="@android:style/Theme.Light"

Issue: application is light, but ActionBar is blue with grey icons, hardly visible against the blue background color. I also want the ActionBar to be light, so they grey icons are more visible.

I've tried modifying the styles but to no avail.

I'm probably missing something trivial.

How do I change the background color of the ActionBar of an ActionBarActivity using XML ?

Body:
If you are using androidx AppCompact. Use below code.

androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable("Color"));

ContentLicense: CC BY-SA 4.0


问:
How to solve Android MultiDex Apllication Instance Null Pointer Exception?
I want to do a core api service integration in my Android project.
My core service class is as follows:

```<code>public class TestApplication extends MultiDexApplication {
    private static final String LOG_TAG_NETWORK = "GNetwork";
    public static JacksonConverterFactory factory;
    private static TestApplication instance;
    private OkHttpClient.Builder okHttpBuilder;
    private TestService testtService;
    private Location lastKnownLocation;

public static TestApplication getInstance() {
    return instance;
}

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

    Pref.init(this);

    okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.connectTimeout(UrlConstants.CONNECT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .readTimeout(UrlConstants.READ_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .writeTimeout(UrlConstants.WRITE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    if (BuildConfig.LOG_ENABLED) {
        HttpLoggingInterceptor httpLoggingInterceptor =
                new HttpLoggingInterceptor(message -> Log.d(LOG_TAG_NETWORK, message));
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpBuilder.addInterceptor(httpLoggingInterceptor);
    }
    factory = getJacksonConverterFactory();
}

@NonNull
private JacksonConverterFactory getJacksonConverterFactory() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return JacksonConverterFactory.create(objectMapper);
}

public void setupRetrofit() {

    String BASE_URL = "http://xxxxx";

    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpBuilder.build())
            .addConverterFactory(factory).build();

    testService = retrofit.create(TestService.class);
}

public TestService getTestService() {
    return testService;
    }
}
</code>```

Then I create an instance from this core class. But here my constant getIntance value returns null.

```<code>TestApplication.getInstance().setupRetrofit();
</code>```

I can't understand that. GetInstance method always return null;

In my app build.gradle file is multiDexEnabled true.

How to solve this situation?

答:
change getInstance()

from this

```<code>public static TestApplication getInstance() {
return instance;
}
</code>```

to this

```<code>public static TestApplication getInstance() {
instance=new TestApplication();
return instance;
}
</code>```

and also remove this line from oncreate

```<code>instance = this;
</code>```

Body:
I want to do a core api service integration in my Android project.
My core service class is as follows:

public class TestApplication extends MultiDexApplication {
    private static final String LOG_TAG_NETWORK = "GNetwork";
    public static JacksonConverterFactory factory;
    private static TestApplication instance;
    private OkHttpClient.Builder okHttpBuilder;
    private TestService testtService;
    private Location lastKnownLocation;

public static TestApplication getInstance() {
    return instance;
}

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

    Pref.init(this);

    okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.connectTimeout(UrlConstants.CONNECT_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .readTimeout(UrlConstants.READ_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS)
            .writeTimeout(UrlConstants.WRITE_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
    if (BuildConfig.LOG_ENABLED) {
        HttpLoggingInterceptor httpLoggingInterceptor =
                new HttpLoggingInterceptor(message -> Log.d(LOG_TAG_NETWORK, message));
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        okHttpBuilder.addInterceptor(httpLoggingInterceptor);
    }
    factory = getJacksonConverterFactory();
}

@NonNull
private JacksonConverterFactory getJacksonConverterFactory() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return JacksonConverterFactory.create(objectMapper);
}

public void setupRetrofit() {

    String BASE_URL = "http://xxxxx";

    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpBuilder.build())
            .addConverterFactory(factory).build();

    testService = retrofit.create(TestService.class);
}

public TestService getTestService() {
    return testService;
    }
}

Then I create an instance from this core class. But here my constant getIntance value returns null.

TestApplication.getInstance().setupRetrofit();

I can't understand that. GetInstance method always return null;

In my app build.gradle file is multiDexEnabled true.

How to solve this situation?

Body:
change getInstance()

from this

public static TestApplication getInstance() {
return instance;
}

to this

public static TestApplication getInstance() {
instance=new TestApplication();
return instance;
}

and also remove this line from oncreate

instance = this;


问:
How to securely create PHP variables with extract
In my previous post i ask how to create variables from an array ( PHP Variables made with foreach ) i got several answers and i was testing extract() but i have seen several against it for security reasons.

Now my question here is how can i use extract in a secure way from a $_POST that has an array that was made using jquery serialized.

With secure i mean that if a user inputs the wrong data, the secure way can take care of that with no problems.

THe PHP Site has a small warning in the extract command the says the following:

Do not use extract() on untrusted
  data, like user input (i.e. $_GET,
  $_FILES, etc.). If you do, for example
  if you want to run old code that
  relies on register_globals
  temporarily, make sure you use one of
  the non-overwriting extract_type
  values such as EXTR_SKIP and be aware
  that you should extract in the same
  order that's defined in
  variables_order within the php.ini.

It warns about the use but does not provide an example at least of how to solve the user of extract in a secure way.

答:
This is secure enough as long as you use a prefix that doesn't exist in other variables:

```<code>extract($_POST, EXTR_PREFIX_ALL, 'unique_prefix');
</code>```

The reason why extract might be dangerous is the same as using register_globals.

Body:
This is secure enough as long as you use a prefix that doesn't exist in other variables:

extract($_POST, EXTR_PREFIX_ALL, 'unique_prefix');

The reason why extract might be dangerous is the same as using register_globals.


问:
How to add rounded corner to a UIBezierPath custom rectangle?
I managed to create the rounded corners, but I'm having trouble with the first rounded corner (lower right )

Question :

Can I add an (addArcWithCenter) method before the ( moveToPoint ) method ?

How can i get rid of the straight line at the beginning of the rectangle (lower right) ?

here is my code for the custom rectangle and a screenshot :

```<code>let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 300, y: 0))
path.addArcWithCenter(CGPoint(x: 300-10, y: 50), radius: 10 , startAngle: 0 , endAngle: CGFloat(M_PI/2)  , clockwise: true) //1st rounded corner
path.addArcWithCenter(CGPoint(x: 200, y: 50), radius:10, startAngle: CGFloat(2 * M_PI / 3), endAngle:CGFloat(M_PI) , clockwise: true)// 2rd rounded corner
path.addArcWithCenter(CGPoint(x: 200, y: 10), radius:10, startAngle: CGFloat(M_PI), endAngle:CGFloat(3 * M_PI / 2), clockwise: true)// 3rd rounded corner
// little triangle at the bottom
path.addLineToPoint(CGPoint(x:240 , y:0))
path.addLineToPoint(CGPoint(x: 245, y: -10))
path.addLineToPoint(CGPoint(x:250, y: 0))
path.addArcWithCenter(CGPoint(x: 290, y: 10), radius: 10, startAngle: CGFloat(3 * M_PI / 2), endAngle: CGFloat(2 * M_PI ), clockwise: true)
path.closePath()
</code>```

答:
Swift 5 with configuration variables:

```<code>override func draw(_ rect: CGRect) {
    let arrowXOffset: CGFloat = 13
    let cornerRadius: CGFloat = 6
    let arrowHeight: CGFloat = 6

    let mainRect = CGRect(origin: rect.origin, size: CGSize(width: rect.width, height: rect.height - arrowHeight))

    let leftTopPoint = mainRect.origin
    let rightTopPoint = CGPoint(x: mainRect.maxX, y: mainRect.minY)
    let rightBottomPoint = CGPoint(x: mainRect.maxX, y: mainRect.maxY)
    let leftBottomPoint = CGPoint(x: mainRect.minX, y: mainRect.maxY)

    let leftArrowPoint = CGPoint(x: leftBottomPoint.x + arrowXOffset, y: leftBottomPoint.y)
    let centerArrowPoint = CGPoint(x: leftArrowPoint.x + arrowHeight, y: leftArrowPoint.y + arrowHeight)
    let rightArrowPoint = CGPoint(x: leftArrowPoint.x + 2 * arrowHeight, y: leftArrowPoint.y)

    let path = UIBezierPath()
    path.addArc(withCenter: CGPoint(x: rightTopPoint.x - cornerRadius, y: rightTopPoint.y + cornerRadius), radius: cornerRadius,
                startAngle: CGFloat(3 * Double.pi / 2), endAngle: CGFloat(2 * Double.pi), clockwise: true)
    path.addArc(withCenter: CGPoint(x: rightBottomPoint.x - cornerRadius, y: rightBottomPoint.y - cornerRadius), radius: cornerRadius,
                startAngle: 0, endAngle: CGFloat(Double.pi / 2), clockwise: true)

    path.addLine(to: rightArrowPoint)
    path.addLine(to: centerArrowPoint)
    path.addLine(to: leftArrowPoint)

    path.addArc(withCenter: CGPoint(x: leftBottomPoint.x + cornerRadius, y: leftBottomPoint.y - cornerRadius), radius: cornerRadius,
                startAngle: CGFloat(Double.pi / 2), endAngle: CGFloat(Double.pi), clockwise: true)
    path.addArc(withCenter: CGPoint(x: leftTopPoint.x + cornerRadius, y: leftTopPoint.y + cornerRadius), radius: cornerRadius,
                startAngle: CGFloat(Double.pi), endAngle: CGFloat(3 * Double.pi / 2), clockwise: true)

    path.addLine(to: rightTopPoint)
    path.close()
}
</code>```

Body:
I managed to create the rounded corners, but I'm having trouble with the first rounded corner (lower right )

Question :

Can I add an (addArcWithCenter) method before the ( moveToPoint ) method ?

How can i get rid of the straight line at the beginning of the rectangle (lower right) ?

here is my code for the custom rectangle and a screenshot :

let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 300, y: 0))
path.addArcWithCenter(CGPoint(x: 300-10, y: 50), radius: 10 , startAngle: 0 , endAngle: CGFloat(M_PI/2)  , clockwise: true) //1st rounded corner
path.addArcWithCenter(CGPoint(x: 200, y: 50), radius:10, startAngle: CGFloat(2 * M_PI / 3), endAngle:CGFloat(M_PI) , clockwise: true)// 2rd rounded corner
path.addArcWithCenter(CGPoint(x: 200, y: 10), radius:10, startAngle: CGFloat(M_PI), endAngle:CGFloat(3 * M_PI / 2), clockwise: true)// 3rd rounded corner
// little triangle at the bottom
path.addLineToPoint(CGPoint(x:240 , y:0))
path.addLineToPoint(CGPoint(x: 245, y: -10))
path.addLineToPoint(CGPoint(x:250, y: 0))
path.addArcWithCenter(CGPoint(x: 290, y: 10), radius: 10, startAngle: CGFloat(3 * M_PI / 2), endAngle: CGFloat(2 * M_PI ), clockwise: true)
path.closePath()

Body:
Swift 5 with configuration variables:

override func draw(_ rect: CGRect) {
    let arrowXOffset: CGFloat = 13
    let cornerRadius: CGFloat = 6
    let arrowHeight: CGFloat = 6

    let mainRect = CGRect(origin: rect.origin, size: CGSize(width: rect.width, height: rect.height - arrowHeight))

    let leftTopPoint = mainRect.origin
    let rightTopPoint = CGPoint(x: mainRect.maxX, y: mainRect.minY)
    let rightBottomPoint = CGPoint(x: mainRect.maxX, y: mainRect.maxY)
    let leftBottomPoint = CGPoint(x: mainRect.minX, y: mainRect.maxY)

    let leftArrowPoint = CGPoint(x: leftBottomPoint.x + arrowXOffset, y: leftBottomPoint.y)
    let centerArrowPoint = CGPoint(x: leftArrowPoint.x + arrowHeight, y: leftArrowPoint.y + arrowHeight)
    let rightArrowPoint = CGPoint(x: leftArrowPoint.x + 2 * arrowHeight, y: leftArrowPoint.y)

    let path = UIBezierPath()
    path.addArc(withCenter: CGPoint(x: rightTopPoint.x - cornerRadius, y: rightTopPoint.y + cornerRadius), radius: cornerRadius,
                startAngle: CGFloat(3 * Double.pi / 2), endAngle: CGFloat(2 * Double.pi), clockwise: true)
    path.addArc(withCenter: CGPoint(x: rightBottomPoint.x - cornerRadius, y: rightBottomPoint.y - cornerRadius), radius: cornerRadius,
                startAngle: 0, endAngle: CGFloat(Double.pi / 2), clockwise: true)

    path.addLine(to: rightArrowPoint)
    path.addLine(to: centerArrowPoint)
    path.addLine(to: leftArrowPoint)

    path.addArc(withCenter: CGPoint(x: leftBottomPoint.x + cornerRadius, y: leftBottomPoint.y - cornerRadius), radius: cornerRadius,
                startAngle: CGFloat(Double.pi / 2), endAngle: CGFloat(Double.pi), clockwise: true)
    path.addArc(withCenter: CGPoint(x: leftTopPoint.x + cornerRadius, y: leftTopPoint.y + cornerRadius), radius: cornerRadius,
                startAngle: CGFloat(Double.pi), endAngle: CGFloat(3 * Double.pi / 2), clockwise: true)

    path.addLine(to: rightTopPoint)
    path.close()
}


问:
(WPF) Binding does not show anything in the UI
I am currently learning WPF and trying to test some binding.Here I want to bind my tab page's header with a property fileName in the MainWindow.xaml.cs, but it doesn't show anything

I don't see any errors in the output window either
DataContext in the Window tag:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Binding in the xaml :

<TabItem Header="{Binding fileName, Mode=TwoWay}" x:Name="Header_Tab" Height="20" Width="175">

My property:

```<code>protected void NotifyPropertyChanged(string PropertyName)
        {
            if (PropertyChanged != null)

                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(PropertyName));

        }
...
public string filePath { get; set; }
        public string folderPath { get; set; }
        public string fileName
        {
            get
            {
                return Path.GetFileName(filePath);
            }
            set
            {
                if (value != Path.GetFileName(filePath))
                {
                    value = Path.GetFileName(filePath);
                    NotifyPropertyChanged(fileName);
                }
            }
        }
</code>```

答:
The filePath property should be implemented like this:

```<code>private string _filePath;
public string filePath
{
    get
    {
        return _filePath;
    }
    set
    {
        if(value != _filePath)
        {
            _filePath = value;
            NotifyPropertyChanged("filePath");

            // Notify the UI that it should update fileName
            // when there is a change on filePath
            NotifyPropertyChanged("fileName");
        }
    }
}
</code>```

And the fileName property should be read-only:

```<code>public string fileName
{
    get
    {
        return Path.GetFileName(_filePath);
    }
}
</code>```

Body:
I am currently learning WPF and trying to test some binding.Here I want to bind my tab page's header with a property fileName in the MainWindow.xaml.cs, but it doesn't show anything

I don't see any errors in the output window either
DataContext in the Window tag:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Binding in the xaml :

<TabItem Header="{Binding fileName, Mode=TwoWay}" x:Name="Header_Tab" Height="20" Width="175">

My property:

protected void NotifyPropertyChanged(string PropertyName)
        {
            if (PropertyChanged != null)

                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(PropertyName));

        }
...
public string filePath { get; set; }
        public string folderPath { get; set; }
        public string fileName
        {
            get
            {
                return Path.GetFileName(filePath);
            }
            set
            {
                if (value != Path.GetFileName(filePath))
                {
                    value = Path.GetFileName(filePath);
                    NotifyPropertyChanged(fileName);
                }
            }
        }

Body:
The filePath property should be implemented like this:

private string _filePath;
public string filePath
{
    get
    {
        return _filePath;
    }
    set
    {
        if(value != _filePath)
        {
            _filePath = value;
            NotifyPropertyChanged("filePath");

            // Notify the UI that it should update fileName
            // when there is a change on filePath
            NotifyPropertyChanged("fileName");
        }
    }
}

And the fileName property should be read-only:

public string fileName
{
    get
    {
        return Path.GetFileName(_filePath);
    }
}


问:
OpenGL ES Texture Coordinates Slightly Off
I'm trying to draw a subregion of a texture in OpenGL by specifying the coordinates I want. What's happening though is that, depending on the size of the image, it seems there's a slight offset in the origin of where it selects the texture coordinates. The offset amount seems to be less than the size of a pixel & the output is is blurred combination of neighboring pixels.

Here's an idea of what I'm describing. In this case I'd want to select the 6x5 green/white region but what OpenGL is rendering includes a slight pink tint to the top & left pixels.

What the output would look like:

I can fix it by adding an offset to the texture coordinates before passing them to glTexCoordPointer but the problem is that I have no way to calculate what the offset is and it seems different for different textures.

Pseudocode:

```<code>float uFactor = regionWidth / textureWidth;   // For the example: 0.6f
float vFactor = regionHeight / textureHeight; // For the example: 0.5f

data[0].t[0] = 0.0f * uFactor;
data[0].t[1] = 0.0f * vFactor;
data[1].t[0] = 1.0f * uFactor;
data[1].t[1] = 0.0f * vFactor;
data[2].t[0] = 0.0f * uFactor;
data[2].t[1] = 1.0f * vFactor;
data[3].t[0] = 1.0f * uFactor;
data[3].t[1] = 1.0f * vFactor;

glPushMatrix();

// translate/scale/bind operations

glTexCoordPointer(2, GL_FLOAT, 0, data[0].t);
</code>```

答:
Propably this has to do with the wrap around. Try this when you create the source image:</p>

```<code>glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP )
</code>```

Body:
I'm trying to draw a subregion of a texture in OpenGL by specifying the coordinates I want. What's happening though is that, depending on the size of the image, it seems there's a slight offset in the origin of where it selects the texture coordinates. The offset amount seems to be less than the size of a pixel & the output is is blurred combination of neighboring pixels.

Here's an idea of what I'm describing. In this case I'd want to select the 6x5 green/white region but what OpenGL is rendering includes a slight pink tint to the top & left pixels.

What the output would look like:

I can fix it by adding an offset to the texture coordinates before passing them to glTexCoordPointer but the problem is that I have no way to calculate what the offset is and it seems different for different textures.

Pseudocode:

float uFactor = regionWidth / textureWidth;   // For the example: 0.6f
float vFactor = regionHeight / textureHeight; // For the example: 0.5f

data[0].t[0] = 0.0f * uFactor;
data[0].t[1] = 0.0f * vFactor;
data[1].t[0] = 1.0f * uFactor;
data[1].t[1] = 0.0f * vFactor;
data[2].t[0] = 0.0f * uFactor;
data[2].t[1] = 1.0f * vFactor;
data[3].t[0] = 1.0f * uFactor;
data[3].t[1] = 1.0f * vFactor;

glPushMatrix();

// translate/scale/bind operations

glTexCoordPointer(2, GL_FLOAT, 0, data[0].t);

Body:
Propably this has to do with the wrap around. Try this when you create the source image:

glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP )


问:
Writing computed data to a txt/csv after each iterations step
Consider the following simple example:

```<code>x1, x2, x3, x4 = 0, 0, 0, 0
index = 0

for i in range(3):
    index += 1
    x1 += 2
    x2 += 2
    x3 += 2
    x4 += 2
</code>```

How can i create a txt or csv file that stores x1,x2,x3,x4 and index after each iteration in separate columns (5 in total). Is it also possible to give each column a title?

The end result should look like

```<code>Index    Data1    Data2    Data3    Data4
1        2        2        2        2
2        4        4        4        4
3        6        6        6        6
</code>```

It is important that the stored data is well separated because it will be later used for another computation. If the variable with the stored values is called " data_ " , i want to apply slice operations, e.g. data_[:,0] = [1,2,3].

Edit:
@abc i tried your method but it does not work

```<code>import pandas as pd
from numpy import array

index = 0

for i in range(3):
    index += 1
    x1 += 2
    x2 += 2
    x3 += 2
    compact = [[index, x1, x2, x3]]
    pd.DataFrame(compact, columns=   ['Index','Data1','Data2','Data3']).to_csv('example.csv',index=False)
</code>```

The example.csv file will only obtain the last computed values, e.g.

In my real program it is not possible to first store all the computed values (10^6 iterations) and only afterwards to save them. The values need to be stored after each iteration!

答:
What you need is pandas:

```<code>Import pandas as pd
Import os

x1, x2, x3, x4 = 0, 0, 0, 0
index = 0
Index,Data1,Data2,Data3,Data4=[],[],[],[],[]
for i in range(3):
    index += 1
    x1 += 2
    x2 += 2
    x3 += 2
    x4 += 2
    df=pd.DataFrame([index,x1,x2,x3,x4],columns=['Index','Data1','Data2','Data3','Data4'])
    df.to_csv('data.csv',index=False,mode='a')
</code>```

data.csv file:

```<code>Index,Data1,Data2,Data3,Data4
1,2,2,2,2
2,4,4,4,4
3,6,6,6,6
</code>```

Body:
Consider the following simple example:

x1, x2, x3, x4 = 0, 0, 0, 0
index = 0

for i in range(3):
    index += 1
    x1 += 2
    x2 += 2
    x3 += 2
    x4 += 2

How can i create a txt or csv file that stores x1,x2,x3,x4 and index after each iteration in separate columns (5 in total). Is it also possible to give each column a title?

The end result should look like

Index    Data1    Data2    Data3    Data4
1        2        2        2        2
2        4        4        4        4
3        6        6        6        6

It is important that the stored data is well separated because it will be later used for another computation. If the variable with the stored values is called " data_ " , i want to apply slice operations, e.g. data_[:,0] = [1,2,3].

Edit:
@abc i tried your method but it does not work

import pandas as pd
from numpy import array

index = 0

for i in range(3):
    index += 1
    x1 += 2
    x2 += 2
    x3 += 2
    compact = [[index, x1, x2, x3]]
    pd.DataFrame(compact, columns=   ['Index','Data1','Data2','Data3']).to_csv('example.csv',index=False)

The example.csv file will only obtain the last computed values, e.g.

In my real program it is not possible to first store all the computed values (10^6 iterations) and only afterwards to save them. The values need to be stored after each iteration!

Body:
What you need is pandas:

Import pandas as pd
Import os

x1, x2, x3, x4 = 0, 0, 0, 0
index = 0
Index,Data1,Data2,Data3,Data4=[],[],[],[],[]
for i in range(3):
    index += 1
    x1 += 2
    x2 += 2
    x3 += 2
    x4 += 2
    df=pd.DataFrame([index,x1,x2,x3,x4],columns=['Index','Data1','Data2','Data3','Data4'])
    df.to_csv('data.csv',index=False,mode='a')

data.csv file:

Index,Data1,Data2,Data3,Data4
1,2,2,2,2
2,4,4,4,4
3,6,6,6,6


问:
jq: Add field to collection deep in nested structure, calculated from other fields at the same level
I'm looking for someone who can give me a hint with jq here - it seems I'm missing out on something.

My JSON source would be similar to this:

```<code>[
    {
        "cluster": "one",
        "slots": [
            {
                "instances": [
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 0,
                                "healthy": 4
                            },
                            {
                                "name": "B",
                                "unhealthy": 2,
                                "healthy": 2
                            }
                        ]
                    },
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 6
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 2
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "cluster": "two",
        "slots": [
            {
                "instances": [
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 1,
                                "healthy": 9
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 10
                            }
                        ]
                    },
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 9
                            },
                            {
                                "name": "D",
                                "unhealthy": 0,
                                "healthy": 14
                            }
                        ]
                    }
                ]
            }
        ]
    }
]
</code>```

What I need would be a new "status" field in each innermost collection as the sum of the "healthy" and "unhealthy" states, like this:

```<code>[
    {
        "cluster": "one",
        "slots": [
            {
                "instances": [
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 0,
                                "healthy": 4,
                                "status": 4
                            },
                            {
                                "name": "B",
                                "unhealthy": 2,
                                "healthy": 2,
                                "status": 4
                            }
                        ]
                    },
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 6,
                                "status": 6
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 2,
                                "status": 2
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "cluster": "two",
        "slots": [
            {
                "instances": [
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 1,
                                "healthy": 9,
                                "status": 10
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 10,
                                "status": 10
                            }
                        ]
                    },
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 9,
                                "status": 9
                            },
                            {
                                "name": "D",
                                "unhealthy": 0,
                                "healthy": 14,
                                "status": 14
                            }
                        ]
                    }
                ]
            }
        ]
    }
]
</code>```

Is there a way to iterate in this manner:

jq '.[].slots[].instances[].services[] += { "status": ($iterator.healthy + $iterator.unhealthy) }'

In all my attempts so far, I either couldn't access the elements at the same level for the calculation... or the rest of my data got dumped.

答:
You're looking for |= operator.

```<code>.[].slots[].instances[].services[] |= (.status = .unhealthy + .healthy)
</code>```

Body:
I'm looking for someone who can give me a hint with jq here - it seems I'm missing out on something.

My JSON source would be similar to this:

[
    {
        "cluster": "one",
        "slots": [
            {
                "instances": [
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 0,
                                "healthy": 4
                            },
                            {
                                "name": "B",
                                "unhealthy": 2,
                                "healthy": 2
                            }
                        ]
                    },
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 6
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 2
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "cluster": "two",
        "slots": [
            {
                "instances": [
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 1,
                                "healthy": 9
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 10
                            }
                        ]
                    },
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 9
                            },
                            {
                                "name": "D",
                                "unhealthy": 0,
                                "healthy": 14
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

What I need would be a new "status" field in each innermost collection as the sum of the "healthy" and "unhealthy" states, like this:

[
    {
        "cluster": "one",
        "slots": [
            {
                "instances": [
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 0,
                                "healthy": 4,
                                "status": 4
                            },
                            {
                                "name": "B",
                                "unhealthy": 2,
                                "healthy": 2,
                                "status": 4
                            }
                        ]
                    },
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 6,
                                "status": 6
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 2,
                                "status": 2
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "cluster": "two",
        "slots": [
            {
                "instances": [
                    {
                        "number": 1,
                        "services": [
                            {
                                "name": "A",
                                "unhealthy": 1,
                                "healthy": 9,
                                "status": 10
                            },
                            {
                                "name": "C",
                                "unhealthy": 0,
                                "healthy": 10,
                                "status": 10
                            }
                        ]
                    },
                    {
                        "number": 0,
                        "services": [
                            {
                                "name": "B",
                                "unhealthy": 0,
                                "healthy": 9,
                                "status": 9
                            },
                            {
                                "name": "D",
                                "unhealthy": 0,
                                "healthy": 14,
                                "status": 14
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

Is there a way to iterate in this manner:

jq '.[].slots[].instances[].services[] += { "status": ($iterator.healthy + $iterator.unhealthy) }'

In all my attempts so far, I either couldn't access the elements at the same level for the calculation... or the rest of my data got dumped.

Body:
You're looking for |= operator.

.[].slots[].instances[].services[] |= (.status = .unhealthy + .healthy)


问:
Update a table with longblobs is too slow
I have a table filled with data (about 20,000 records). I am trying to update it by the data from another table, but I have a timeout (30 seconds).
At first I tried a naive solution:

```<code>UPDATE TableWhithBlobs a
JOIN AnotherTable b on a.AnotherTableId = b.Id
SET a.SomeText= b.Description;
</code>```

This script is working much longer then 30 seconds, so I tried to reduce join:

```<code>UPDATE TableWhithBlobs a
SET a.SomeText = (select b.Description from AnotherTable b where a.AnotherTableId = b.Id);
</code>```

but this one is still very slow. Is there any cases how it could be fast?

Edit:

A bit explanation about what I'm doing. Previously, I had two tables, which in my script are called TableWhithBlobs and AnotherTable. In table TableWhithBlobs, a link to table AnotherTable was stored, but this link was not a real foreign key, it was just a guid from table AnotherTable. And there is a Unique key constraint for this reference in TableWhithBlobs for this guid. I decided to fix this, remove the old field from table TableWhithBlobs and add a normal foreign key to it (using the primary ID from AnotherTable). The script from the question just adds the correct data to this new field. After that, I delete old guid reference and add a new foreign key constraint. Everything works fine in the small amount of data in TableWhithBlobs, but on QA database with 20000 rows its extremely slow.

Update

SHOW CREATE TABLE TableWhithBlobs;

```<code>CREATE TABLE `TableWhithBlobs` (
`Id` bigint(20) NOT NULL AUTO_INCREMENT,
`AnotherTableId` char(36) CHARACTER SET ascii NOT NULL,
`ChunkNumber` bigint(20) NOT NULL,
`Content` longblob NOT NULL,
`SomeText` bigint(20) NOT NULL,
PRIMARY KEY (`Id`),
UNIQUE KEY `AnotherTableId` (`AnotherTableId`,`ChunkNumber`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
</code>```

SHOW CREATE TABLE AnotherTable ;

```<code>CREATE TABLE `AnotherTable` (
`Description` bigint(20) NOT NULL AUTO_INCREMENT,
`Id` char(36) CHARACTER SET ascii NOT NULL,
`Length` bigint(20) NOT NULL,
`ContentDigest` char(68) CHARACTER SET ascii NOT NULL,
`ContentAndMetadataDigest` char(68) CHARACTER SET ascii NOT NULL,
`Status` smallint(6) NOT NULL,
`ChunkStartNumber` bigint(20) NOT NULL DEFAULT '0',
`IsTestData` bit(1) NOT NULL DEFAULT b'0',
PRIMARY KEY (`Description`),
UNIQUE KEY `Id` (`Id`),
UNIQUE KEY `ContentAndMetadataDigest` (`ContentAndMetadataDigest`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
</code>```

PS. Column names may look weird because i want to hide the actual production scheme names.

innodb_buffer_pool_size is 134217728, RAM is 4Gb

Result of

```<code>explain UPDATE TableWhithBlobs a JOIN AnotherTable b on a.AnotherTableId =
b.Id SET a.SomeText= b.Description;
</code>```

Version: mysql  Ver 14.14 Distrib 5.7.21-20, for debian-linux-gnu (x86_64) using  6.3

答:
What about doing smaller updates?

```<code>UPDATE TableWhithBlobs a
JOIN AnotherTable b on a.AnotherTableId = b.Id
SET a.SomeText= b.Description
WHERE a.SomeText <> b.Description;
</code>```

or even:

```<code>UPDATE TableWhithBlobs a
JOIN AnotherTable b on a.AnotherTableId = b.Id
SET a.SomeText= b.Description
WHERE a.SomeText <> b.Description
LIMIT 100;
</code>```

Your timeout problem should be solved , but i do not know how many times you have to run this to finally get the 0 rows affected...

Body:
I have a table filled with data (about 20,000 records). I am trying to update it by the data from another table, but I have a timeout (30 seconds).
At first I tried a naive solution:

UPDATE TableWhithBlobs a
JOIN AnotherTable b on a.AnotherTableId = b.Id
SET a.SomeText= b.Description;

This script is working much longer then 30 seconds, so I tried to reduce join:

UPDATE TableWhithBlobs a
SET a.SomeText = (select b.Description from AnotherTable b where a.AnotherTableId = b.Id);

but this one is still very slow. Is there any cases how it could be fast?

Edit:

A bit explanation about what I'm doing. Previously, I had two tables, which in my script are called TableWhithBlobs and AnotherTable. In table TableWhithBlobs, a link to table AnotherTable was stored, but this link was not a real foreign key, it was just a guid from table AnotherTable. And there is a Unique key constraint for this reference in TableWhithBlobs for this guid. I decided to fix this, remove the old field from table TableWhithBlobs and add a normal foreign key to it (using the primary ID from AnotherTable). The script from the question just adds the correct data to this new field. After that, I delete old guid reference and add a new foreign key constraint. Everything works fine in the small amount of data in TableWhithBlobs, but on QA database with 20000 rows its extremely slow.

Update

SHOW CREATE TABLE TableWhithBlobs;

CREATE TABLE `TableWhithBlobs` (
`Id` bigint(20) NOT NULL AUTO_INCREMENT,
`AnotherTableId` char(36) CHARACTER SET ascii NOT NULL,
`ChunkNumber` bigint(20) NOT NULL,
`Content` longblob NOT NULL,
`SomeText` bigint(20) NOT NULL,
PRIMARY KEY (`Id`),
UNIQUE KEY `AnotherTableId` (`AnotherTableId`,`ChunkNumber`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

SHOW CREATE TABLE AnotherTable ;

CREATE TABLE `AnotherTable` (
`Description` bigint(20) NOT NULL AUTO_INCREMENT,
`Id` char(36) CHARACTER SET ascii NOT NULL,
`Length` bigint(20) NOT NULL,
`ContentDigest` char(68) CHARACTER SET ascii NOT NULL,
`ContentAndMetadataDigest` char(68) CHARACTER SET ascii NOT NULL,
`Status` smallint(6) NOT NULL,
`ChunkStartNumber` bigint(20) NOT NULL DEFAULT '0',
`IsTestData` bit(1) NOT NULL DEFAULT b'0',
PRIMARY KEY (`Description`),
UNIQUE KEY `Id` (`Id`),
UNIQUE KEY `ContentAndMetadataDigest` (`ContentAndMetadataDigest`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

PS. Column names may look weird because i want to hide the actual production scheme names.

innodb_buffer_pool_size is 134217728, RAM is 4Gb

Result of

explain UPDATE TableWhithBlobs a JOIN AnotherTable b on a.AnotherTableId =
b.Id SET a.SomeText= b.Description;

Version: mysql  Ver 14.14 Distrib 5.7.21-20, for debian-linux-gnu (x86_64) using  6.3

Body:
What about doing smaller updates?

UPDATE TableWhithBlobs a
JOIN AnotherTable b on a.AnotherTableId = b.Id
SET a.SomeText= b.Description
WHERE a.SomeText <> b.Description;

or even:

UPDATE TableWhithBlobs a
JOIN AnotherTable b on a.AnotherTableId = b.Id
SET a.SomeText= b.Description
WHERE a.SomeText <> b.Description
LIMIT 100;

Your timeout problem should be solved , but i do not know how many times you have to run this to finally get the 0 rows affected...


问:
Spring 3.0.5 and Hibernate 3.5.3 - wrong package reference?
I am trying to use Spring 3.0.5 with Hibernate 3.5.3-Final and when Spring creates the session, it throws an exception:

java.lang.NoClassDefFoundError: org/hibernate/annotations/common/AssertionFailure

The issue is that the AssertionFailure class is actually in the org.hibernate package (not org.hibernate.annotations.common).  3.0.5 is the latest stable release of Spring and Hibernate 3.5.3-Final was released about a year ago, so it seems odd that it would not be supported.  Is there some workaround for this issue?

答: You also need the hibernate commons annotations jar (https://repository.jboss.org/nexus/content/groups/public/org/hibernate/hibernate-commons-annotations/3.3.0.ga/)</p>


问:
relationship between K8S iptables and the one of a container inside a pod
I have enabled the privileged mode in the container and add a rule to it,

```<code>iptables -N udp2rawDwrW_191630ce_C0
iptables -F udp2rawDwrW_191630ce_C0
iptables -I udp2rawDwrW_191630ce_C0 -j DROP
iptables -I INPUT -p tcp -m tcp --dport 4096 -j udp2rawDwrW_191630ce_C0
</code>```

and kt exec into the container and use iptables --table filter -L, I can see the added rules.

```<code>/ # iptables --table filter -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
udp2rawDwrW_191630ce_C0  tcp  --  anywhere             anywhere             tcp dpt:4096

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain udp2rawDwrW_191630ce_C0 (1 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere
</code>```

While when I logged into the node where the container lives, and run sudo iptalbes --table filter -L, I cannot see the same result.

I was thinking by default the previleged is dropped because the container might leverage it to change something like the iptables in the node, however it looks not like that.

So my question is "what is the relationship between K8S iptables and the one of a container inside a pod" and "why we stop user from modifying the container's iptables without the privileged field"?

答:
if you want to manipulate node's iptables then you definitely need to put the pod on host's network (hostNetwork: true within pod's spec). After that granting to the container NET_ADMIN and NET_RAW capabilities (in containers[i].securityContext.capabilities.add) is sufficient.
example json slice:

```<code>  "spec": {
    "hostNetwork": true,
    "containers": [{
      "name": "netadmin",
      "securityContext": {"capabilities": { "add": ["NET_ADMIN", "NET_RAW"] } }
</code>```

I'm not sure if privileged mode has anything to do with manipulating host's iptables these days.

Body:
I have enabled the privileged mode in the container and add a rule to it,

iptables -N udp2rawDwrW_191630ce_C0
iptables -F udp2rawDwrW_191630ce_C0
iptables -I udp2rawDwrW_191630ce_C0 -j DROP
iptables -I INPUT -p tcp -m tcp --dport 4096 -j udp2rawDwrW_191630ce_C0

and kt exec into the container and use iptables --table filter -L, I can see the added rules.

/ # iptables --table filter -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
udp2rawDwrW_191630ce_C0  tcp  --  anywhere             anywhere             tcp dpt:4096

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain udp2rawDwrW_191630ce_C0 (1 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere

While when I logged into the node where the container lives, and run sudo iptalbes --table filter -L, I cannot see the same result.

I was thinking by default the previleged is dropped because the container might leverage it to change something like the iptables in the node, however it looks not like that.

So my question is "what is the relationship between K8S iptables and the one of a container inside a pod" and "why we stop user from modifying the container's iptables without the privileged field"?

Body:
if you want to manipulate node's iptables then you definitely need to put the pod on host's network (hostNetwork: true within pod's spec). After that granting to the container NET_ADMIN and NET_RAW capabilities (in containers[i].securityContext.capabilities.add) is sufficient.
example json slice:

  "spec": {
    "hostNetwork": true,
    "containers": [{
      "name": "netadmin",
      "securityContext": {"capabilities": { "add": ["NET_ADMIN", "NET_RAW"] } }

I'm not sure if privileged mode has anything to do with manipulating host's iptables these days.


问:
Delete a value of an array if exist on another array
I have a set of data on the table. Which are all owners.

```<code>  <table class="table">
  <tr>
    <td>
      <button id="John" onclick="deleteVal('John');" type="button"> Delete </button>
    </td>
    <td> <input type="text" name="owner[]" value="John"> John </td>
  </tr>
  <tr>
    <td><button id="Mike" onclick="deleteVal('Mike');" type="button"> Delete </button></td>
    <td> <input type="text" name="owner[]" value="Mike"> Mike </td>
  </tr>
  <tr>
    <td><button id="Sam" onclick="deleteVal('Sam');" type="button"> Delete </button></td>
    <td> <input type="text" name="owner[]" value="Sam"> Sam </td>
  </tr>
</table>
</code>```

When the submit button is clicked all owners are stored to this final_owner field. This is what i've tried.

```<code><button type="submit" id="submit">Submit</button>
FINAL OWNERS: <input type="text" id="final_owner">

 $('#submit').on('click', function() {
      var owner_value = [];
  var del_owners = document.getElementById('deleted_owners').value
      $('input[name="owner[]"]').each(function() {
          owner_value.push($(this).val());
      });
      $("#final_owner").val(owner_value);
});
</code>```

Next is Each time I click Delete Button the owners name is stored to the deleted_owners input field. Which I already made.

My question is how can I remove from the array of final_owner field if the owner is already exist on the delete_owners input field.

```<code><input type="text" id="deleted_owners">.
</code>```

答:
last line in $('#submit').on('click')... You can try this.

```<code>    var deleted_owners = $("#deleted_owners").val()
    var current_final_owner = $("#final_owner").val()

    var new_final_owner = current_final_owner.filter(item => !deleted_owners.inculdes(item))

    $("#final_owner").val(new_final_owner )
</code>```

Edited

Body:
I have a set of data on the table. Which are all owners.

      <button id="John" onclick="deleteVal('John');" type="button"> Delete </button>

     <input type="text" name="owner[]" value="John"> John

    <button id="Mike" onclick="deleteVal('Mike');" type="button"> Delete </button>
     <input type="text" name="owner[]" value="Mike"> Mike

    <button id="Sam" onclick="deleteVal('Sam');" type="button"> Delete </button>
     <input type="text" name="owner[]" value="Sam"> Sam

When the submit button is clicked all owners are stored to this final_owner field. This is what i've tried.

<button type="submit" id="submit">Submit</button>
FINAL OWNERS: <input type="text" id="final_owner">

 $('#submit').on('click', function() {
      var owner_value = [];
  var del_owners = document.getElementById('deleted_owners').value
      $('input[name="owner[]"]').each(function() {
          owner_value.push($(this).val());
      });
      $("#final_owner").val(owner_value);
});

Next is Each time I click Delete Button the owners name is stored to the deleted_owners input field. Which I already made.

My question is how can I remove from the array of final_owner field if the owner is already exist on the delete_owners input field.

<input type="text" id="deleted_owners">.

Body:
last line in $('#submit').on('click')... You can try this.

    var deleted_owners = $("#deleted_owners").val()
    var current_final_owner = $("#final_owner").val()

    var new_final_owner = current_final_owner.filter(item => !deleted_owners.inculdes(item))

    $("#final_owner").val(new_final_owner )

Edited


问:
Differential AJAX updates for HTML table?
I have a game that's based on a 25x20 HTML table (the game board). Every 3 seconds the user can "move," which sends an AJAX request to the server, at which time the server rerenders the entire HTML table and sends it to the user.

This was easy to write, but it wastes a lot of bandwidth. Are there any libraries, client (preferably jquery) or server-side, that help send differential instead of full updates for large tables? Usually only 5-10 tiles change on a given reload, so I feel like I could cut bandwidth use by an order of magnitude by sending just those tiles instead of all 500 every 3 seconds.

I'm also open to "you idiot, why are you using HTML tables"-type comments if you can suggest a better alternative. For example are there any CSS/DOM manipulation techniques I should be considering instead of using an HTML table? Should I use a table but give each td coordinates for an id (like "12x08") and then use jquery to replace cells by id?

A clarification: the tiles are text, not images.

答:
Without thinking of deltas:

You can use JSON quite easily to do this sort of thing.  You can roll out your own compressed format, too.

I think compressing the data using gzip would help a lot.  Most browsers nowadays support it, and it will greatly reduce the size of your responses.

OwnerDisplayName: Brandon

LastEditorDisplayName: Brandon

OwnerDisplayName: strager

ContentLicense: CC BY-SA 2.5


问:
Get JSON data with jQuery from a .NET service: confused with ajax setup
I've just spent six hours trying to get this straight in my head and I haven't succeeded.

There's a HelloWorld .NET 3.5 web service on my local machine. Set up as required.

The service returns a List of custom structures.

I'm trying to consume it with jQuery 1.4.4.

When I try to do what the documentation says, I always get back an XML response from the service, which either causes parseerror in jQuery or gets passed as a dumb string to the success function. That is, however I combine dataType and accepts (which, according to the documentation, control how the received data is handled), I get an XML back.

But, when I do something that does not logically follow from the documentation, I successfully get my array of objects. That is, when I ignore dataType and accepts, and set contentType: "application/json; charset=utf-8" instead, it works fine. But contentType, according to the docs, control the data being sent to the server, not received.

In code:

```<code>$.ajax(
  {
  type: "GET",
  url: "http://localhost:52624/Service1.asmx/HelloWorld",
  dataType: "json",
  //accepts can be anything, or it can be missing, doesn't matter, only depends on dataType
  success: function(data, textStatus, jqXHR) {...},
  error: function(jqXHR, textStatus, errorThrown) {...}
  }
)
</code>```

Result: error handler called, textStatus = parseerror.

```<code>$.ajax(
  {
  type: "GET",
  url: "http://localhost:52624/Service1.asmx/HelloWorld",
  dataType: "application/json",
  //accepts can be anything, or it can be missing, doesn't matter, only depends on dataType
  success: function(data, textStatus, jqXHR) {...},
  error: function(jqXHR, textStatus, errorThrown) {...}
  }
)
</code>```

Result: Web service returns XML, it's passed to the success handler as string.

```<code>$.ajax(
  {
  type: "GET",
  url: "http://localhost:52624/Service1.asmx/HelloWorld",
  accepts: "json",  // or "application/json"
  success: function(data, textStatus, jqXHR) {...},
  error: function(jqXHR, textStatus, errorThrown) {...}
  }
)
</code>```

Result: Web service returns XML, it's parsed and passed as IXMLDOMDocument2.

```<code>$.ajax(
  {
  type: "GET",
  url: "http://localhost:52624/Service1.asmx/HelloWorld",
  contentType: "application/json; charset=utf-8",
  success: function(data, textStatus, jqXHR) {...},
  error: function(jqXHR, textStatus, errorThrown) {...}
  }
)
</code>```

Result: Web service returns JSON, which gets partially parsed by jQuery (numbers and strings are parsed into properties of objects, but dates remain in the form of "/Date(1303003305724)/").

Questions:

Do I understand jQuery specs at all? Why is the parameter that is said to control sent data in fact controls received data?

What am I doing blatantly wrong?

What's the last step to get dates parsed by jQuery, too?

答:
Looks like I'm going to answer that myself.

I'm not saying the following is the absolute truth. Rather, it is what I have found to be working.

First of all, I found three articles that explained a lot:

Using jQuery to Consume ASP.NET JSON Web Services

ASMX ScriptService mistake – Invalid JSON primitive

3 mistakes to avoid when using jQuery with ASP.NET AJAX

In short, the problem with .NET web services is that you have to call them in a special way:

Using a POST request (but see below), and

Providing Content-Type of application/json; charset=utf-8

This is by design and for security reasons.

The latter may not be avoided, you must provide that content type. And because content type does dictate how parameters are encoded in the request, you must encode your parameters in JSON.

This is where jQuery jumps in. For no reason jQuery would ignore contentType and encode your parameters in application/x-www-form-urlencoded. At which point the web service will dislike you for saying "here is JSON" and providing form-encoded stuff instead.

In these articles, the author recommends that you play a trick with jQuery by enclosing your JSON data in another pair of quotes so that it's interpreted as a string and doesn't get fiddled with by jQuery:

```<code>$.ajax({
  type: "POST",
  url: "ServiceName.asmx/WebMethodName",
  data: "{'fname':'dave','lname':'ward'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {...}
});
</code>```

This does work indeed.

Also, if you don't have any data, you still must provide an empty JSON object, {}, because if you don't, jQuery will not set Content-Length, and without Content-Length the web service will dislike you again (more security reasons).

However.

Since FW 3.5, it is possible to use GET with JSON-enabled .NET services. At which point you might wonder how JSON-encoded parameters align with GET requests. Here's how.

If your web service doesn't have any parameters, the call is simple:

```<code>$.ajax(
  {
    type: "GET",
    url: "ServiceName.asmx/WebMethodName",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data, textStatus, jqXHR) {...}
  }
);
</code>```

And if there are parameters, then the call is also simple. What you have to do is provide additional quotes around parameters that should have them! This is because you want these quotes to appear as part of the form-encoded request. This way the form-encoded request will look sort of like json-encoded one:

```<code>$.ajax(
  {
    type: "GET",
    url: "ServiceName.asmx/WebMethodName",
    contentType: "application/json; charset=utf-8",
    data: {DatePlaced:'"2011-05-13"'},
    dataType: "json",
    success: function(data, textStatus, jqXHR) {...}
  }
);
</code>```

This request will result in a request that looks similar to:

GET /ServiceName.asmx/WebMethodName?DatePlaced="2011-05-13" HTTP/1.1

  Content-Type: application/json; charset=utf-8

Note the quotes that are required for JSON-like GET requests, but cause an error if you meant to ask for XML.

Body:
I've just spent six hours trying to get this straight in my head and I haven't succeeded.

There's a HelloWorld .NET 3.5 web service on my local machine. Set up as required.

The service returns a List of custom structures.

I'm trying to consume it with jQuery 1.4.4.

When I try to do what the documentation says, I always get back an XML response from the service, which either causes parseerror in jQuery or gets passed as a dumb string to the success function. That is, however I combine dataType and accepts (which, according to the documentation, control how the received data is handled), I get an XML back.

But, when I do something that does not logically follow from the documentation, I successfully get my array of objects. That is, when I ignore dataType and accepts, and set contentType: "application/json; charset=utf-8" instead, it works fine. But contentType, according to the docs, control the data being sent to the server, not received.

In code:

$.ajax(
  {
  type: "GET",
  url: "http://localhost:52624/Service1.asmx/HelloWorld",
  dataType: "json",
  //accepts can be anything, or it can be missing, doesn't matter, only depends on dataType
  success: function(data, textStatus, jqXHR) {...},
  error: function(jqXHR, textStatus, errorThrown) {...}
  }
)

Result: error handler called, textStatus = parseerror.

$.ajax(
  {
  type: "GET",
  url: "http://localhost:52624/Service1.asmx/HelloWorld",
  dataType: "application/json",
  //accepts can be anything, or it can be missing, doesn't matter, only depends on dataType
  success: function(data, textStatus, jqXHR) {...},
  error: function(jqXHR, textStatus, errorThrown) {...}
  }
)

Result: Web service returns XML, it's passed to the success handler as string.

$.ajax(
  {
  type: "GET",
  url: "http://localhost:52624/Service1.asmx/HelloWorld",
  accepts: "json",  // or "application/json"
  success: function(data, textStatus, jqXHR) {...},
  error: function(jqXHR, textStatus, errorThrown) {...}
  }
)

Result: Web service returns XML, it's parsed and passed as IXMLDOMDocument2.

$.ajax(
  {
  type: "GET",
  url: "http://localhost:52624/Service1.asmx/HelloWorld",
  contentType: "application/json; charset=utf-8",
  success: function(data, textStatus, jqXHR) {...},
  error: function(jqXHR, textStatus, errorThrown) {...}
  }
)

Result: Web service returns JSON, which gets partially parsed by jQuery (numbers and strings are parsed into properties of objects, but dates remain in the form of "/Date(1303003305724)/").

Questions:

Do I understand jQuery specs at all? Why is the parameter that is said to control sent data in fact controls received data?

What am I doing blatantly wrong?

What's the last step to get dates parsed by jQuery, too?

Body:
Looks like I'm going to answer that myself.

I'm not saying the following is the absolute truth. Rather, it is what I have found to be working.

First of all, I found three articles that explained a lot:

Using jQuery to Consume ASP.NET JSON Web Services

ASMX ScriptService mistake – Invalid JSON primitive

3 mistakes to avoid when using jQuery with ASP.NET AJAX

In short, the problem with .NET web services is that you have to call them in a special way:

Using a POST request (but see below), and

Providing Content-Type of application/json; charset=utf-8

This is by design and for security reasons.

The latter may not be avoided, you must provide that content type. And because content type does dictate how parameters are encoded in the request, you must encode your parameters in JSON.

This is where jQuery jumps in. For no reason jQuery would ignore contentType and encode your parameters in application/x-www-form-urlencoded. At which point the web service will dislike you for saying "here is JSON" and providing form-encoded stuff instead.

In these articles, the author recommends that you play a trick with jQuery by enclosing your JSON data in another pair of quotes so that it's interpreted as a string and doesn't get fiddled with by jQuery:

$.ajax({
  type: "POST",
  url: "ServiceName.asmx/WebMethodName",
  data: "{'fname':'dave','lname':'ward'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {...}
});

This does work indeed.

Also, if you don't have any data, you still must provide an empty JSON object, {}, because if you don't, jQuery will not set Content-Length, and without Content-Length the web service will dislike you again (more security reasons).

However.

Since FW 3.5, it is possible to use GET with JSON-enabled .NET services. At which point you might wonder how JSON-encoded parameters align with GET requests. Here's how.

If your web service doesn't have any parameters, the call is simple:

$.ajax(
  {
    type: "GET",
    url: "ServiceName.asmx/WebMethodName",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data, textStatus, jqXHR) {...}
  }
);

And if there are parameters, then the call is also simple. What you have to do is provide additional quotes around parameters that should have them! This is because you want these quotes to appear as part of the form-encoded request. This way the form-encoded request will look sort of like json-encoded one:

$.ajax(
  {
    type: "GET",
    url: "ServiceName.asmx/WebMethodName",
    contentType: "application/json; charset=utf-8",
    data: {DatePlaced:'"2011-05-13"'},
    dataType: "json",
    success: function(data, textStatus, jqXHR) {...}
  }
);

This request will result in a request that looks similar to:

GET /ServiceName.asmx/WebMethodName?DatePlaced="2011-05-13" HTTP/1.1

  Content-Type: application/json; charset=utf-8

Note the quotes that are required for JSON-like GET requests, but cause an error if you meant to ask for XML.


问:
Change location of onclick function after form is processed
I am using this button to close an form when it is shown to the user before the form is processed.

```<code><button type="button" class="btn btn-secondary" data-dismiss="modal" id="submit_delete_dismiss_calc" onclick="window.location.reload()">Close</button>
</code>```

After the form is successfully processed the location does not longer exists so I need to change the location to

```<code>dossier_detail_folders.php?id=<?php echo $_GET['id']; ?>
</code>```

Therefor I have added to exisitng JS:

```<code>$("#submit_delete_dismiss_calc"+formid).setAttribute("onClick", "location.href='dossier_detail_folders.php?id=<?php echo $_GET['id']; ?>'");
</code>```

And that gives the console error:
Uncaught TypeError: $(...).setAttribute is not a function

The rest of the JS has no issues, how to get the location changed correctly?
My complete JS:

```<code>// delete_calc
$(document).ready(function () {
    $("body").on("click", ".delete_calc", function() {
        formid=($(this).attr("alt"));
        subform_delete_calc(formid);
    });
});
function subform_delete_calc(formid)
{
       $("#submit_delete_dismiss_calc"+formid).hide();
       $("#submit_delete_calc"+formid).hide();
       $("#submit_delete_spinner_calc"+formid).show();

       var postData = $("#delete_calc"+formid).serializeArray();
       var formURL='processing/calculatie_delete.php';
        $.ajax({
            url: formURL,
            type: "POST",
            data: postData,
            success: function(data, textStatus, jqXHR) {
                $('#modal_delete_calc'+formid+' .modal-body').html(data);

                $("#submit_delete_spinner_calc"+formid).hide();
                $("#submit_delete_dismiss_calc"+formid).show();
                $("#submit_delete_dismiss_calc"+formid).setAttribute("onClick", "location.href='dossier_detail_folders.php?id=<?php echo $_GET['id']; ?>'");
            },
            error: function(jqXHR, status, error) {
                console.log(status + ": " + error);
            }
        });
        e.preventDefault();
}
</code>```

答:
setAttribute is javascript native method and is not part of jquery. You can use attr to add attribute using jquery

```<code>$("#submit_delete_dismiss_calc"+formid)
.attr("onClick", "location.href='dossier_detail_folders.php?id=<?php echo $_GET['id']; ?>'");
</code>```

Body:
I am using this button to close an form when it is shown to the user before the form is processed.

<button type="button" class="btn btn-secondary" data-dismiss="modal" id="submit_delete_dismiss_calc" onclick="window.location.reload()">Close</button>

After the form is successfully processed the location does not longer exists so I need to change the location to

dossier_detail_folders.php?id=<?php echo $_GET['id']; ?>

Therefor I have added to exisitng JS:

$("#submit_delete_dismiss_calc"+formid).setAttribute("onClick", "location.href='dossier_detail_folders.php?id=<?php echo $_GET['id']; ?>'");

And that gives the console error:
Uncaught TypeError: $(...).setAttribute is not a function

The rest of the JS has no issues, how to get the location changed correctly?
My complete JS:

// delete_calc
$(document).ready(function () {
    $("body").on("click", ".delete_calc", function() {
        formid=($(this).attr("alt"));
        subform_delete_calc(formid);
    });
});
function subform_delete_calc(formid)
{
       $("#submit_delete_dismiss_calc"+formid).hide();
       $("#submit_delete_calc"+formid).hide();
       $("#submit_delete_spinner_calc"+formid).show();

       var postData = $("#delete_calc"+formid).serializeArray();
       var formURL='processing/calculatie_delete.php';
        $.ajax({
            url: formURL,
            type: "POST",
            data: postData,
            success: function(data, textStatus, jqXHR) {
                $('#modal_delete_calc'+formid+' .modal-body').html(data);

                $("#submit_delete_spinner_calc"+formid).hide();
                $("#submit_delete_dismiss_calc"+formid).show();
                $("#submit_delete_dismiss_calc"+formid).setAttribute("onClick", "location.href='dossier_detail_folders.php?id=<?php echo $_GET['id']; ?>'");
            },
            error: function(jqXHR, status, error) {
                console.log(status + ": " + error);
            }
        });
        e.preventDefault();
}

Body:
setAttribute is javascript native method and is not part of jquery. You can use attr to add attribute using jquery

$("#submit_delete_dismiss_calc"+formid)
.attr("onClick", "location.href='dossier_detail_folders.php?id=<?php echo $_GET['id']; ?>'");


问:
How to click OK in alert box using protractor
I am using AngularJS and I want to delete a link, in such cases, an alert box appears to confirm the delete.

I am trying to do e2e test using protractor, how do I confirm in an alert box?

I tried:

```<code>browser.switchTo().alert().accept()
</code>```

but it doesn't seem to work.

Is there a provision in protractor for handling alert boxes?

答:
This will work fine: </p>

```<code>await browser.switchTo().alert().accept();
</code>```

Body:
I am using AngularJS and I want to delete a link, in such cases, an alert box appears to confirm the delete.

I am trying to do e2e test using protractor, how do I confirm in an alert box?

I tried:

browser.switchTo().alert().accept()

but it doesn't seem to work.

Is there a provision in protractor for handling alert boxes?

Body:
This will work fine:

await browser.switchTo().alert().accept();


问:
How to plot Month name in correct order, using strftime?
Here's a quick peek of my dataframe:

```<code>   local_date  amount
0  2017-08-16   10.00
1  2017-10-26   21.70
2  2017-11-04    5.00
3  2017-11-12   37.20
4  2017-11-13   10.00
5  2017-11-18   31.00
6  2017-11-27   14.00
7  2017-11-29   10.00
8  2017-11-30   37.20
9  2017-12-16    8.00
10 2017-12-17   43.20
11 2017-12-17   49.60
12 2017-12-19  102.50
13 2017-12-19   28.80
14 2017-12-22   72.55
15 2017-12-23   24.80
16 2017-12-24   62.00
17 2017-12-26   12.40
18 2017-12-26   15.50
19 2017-12-26   40.00
20 2017-12-28   57.60
21 2017-12-31   37.20
22 2018-01-01   18.60
23 2018-01-02   12.40
24 2018-01-04   32.40
25 2018-01-05   17.00
26 2018-01-06   28.80
27 2018-01-11   20.80
28 2018-01-12   10.00
29 2018-01-12   26.00
</code>```

I am trying to plot monthly sum of transactions, which is fine, except for ugly x-ticks:

I would like to change it to Name of the month and year (e.g. Jan 2019). So I sort the dates, change them using strftime and plot it again, but the order of the date are completely messed up.

The code I used to sort the dates and conver them is:

```<code>transactions = transactions.sort_values(by='local_date')

transactions['month_year'] = transactions['local_date'].dt.strftime('%B %Y')

#And then groupby that column:

transactions.groupby('month_year').amount.sum().plot(kind='bar')
</code>```

When doing this, the Month_year are paired together. January 2019 comes after January 2018 etc. etc.

I thought sorting by date would fix this, but it doesn't. What's the best way to approach this?

答:
You can convert column to mont periods by Series.dt.to_period and then change PeriodIndex to custom format in rename:

```<code>transactions = transactions.sort_values(by='local_date')
(transactions.groupby(transactions['local_date'].dt.to_period('m'))
             .amount.sum()
             .rename(lambda x: x.strftime('%B %Y'))
             .plot(kind='bar'))
</code>```

Alternative solution:

```<code>transactions = transactions.sort_values(by='local_date')
s = transactions.groupby(transactions['local_date'].dt.to_period('m')).amount.sum()
s.index = s.index.strftime('%B %Y')
s.plot(kind='bar')
</code>```

Body:
Here's a quick peek of my dataframe:

   local_date  amount
0  2017-08-16   10.00
1  2017-10-26   21.70
2  2017-11-04    5.00
3  2017-11-12   37.20
4  2017-11-13   10.00
5  2017-11-18   31.00
6  2017-11-27   14.00
7  2017-11-29   10.00
8  2017-11-30   37.20
9  2017-12-16    8.00
10 2017-12-17   43.20
11 2017-12-17   49.60
12 2017-12-19  102.50
13 2017-12-19   28.80
14 2017-12-22   72.55
15 2017-12-23   24.80
16 2017-12-24   62.00
17 2017-12-26   12.40
18 2017-12-26   15.50
19 2017-12-26   40.00
20 2017-12-28   57.60
21 2017-12-31   37.20
22 2018-01-01   18.60
23 2018-01-02   12.40
24 2018-01-04   32.40
25 2018-01-05   17.00
26 2018-01-06   28.80
27 2018-01-11   20.80
28 2018-01-12   10.00
29 2018-01-12   26.00

I am trying to plot monthly sum of transactions, which is fine, except for ugly x-ticks:

I would like to change it to Name of the month and year (e.g. Jan 2019). So I sort the dates, change them using strftime and plot it again, but the order of the date are completely messed up.

The code I used to sort the dates and conver them is:

transactions = transactions.sort_values(by='local_date')

transactions['month_year'] = transactions['local_date'].dt.strftime('%B %Y')

#And then groupby that column:

transactions.groupby('month_year').amount.sum().plot(kind='bar')

When doing this, the Month_year are paired together. January 2019 comes after January 2018 etc. etc.

I thought sorting by date would fix this, but it doesn't. What's the best way to approach this?

Body:
You can convert column to mont periods by Series.dt.to_period and then change PeriodIndex to custom format in rename:

transactions = transactions.sort_values(by='local_date')
(transactions.groupby(transactions['local_date'].dt.to_period('m'))
             .amount.sum()
             .rename(lambda x: x.strftime('%B %Y'))
             .plot(kind='bar'))

Alternative solution:

transactions = transactions.sort_values(by='local_date')
s = transactions.groupby(transactions['local_date'].dt.to_period('m')).amount.sum()
s.index = s.index.strftime('%B %Y')
s.plot(kind='bar')


问:
Using PHPUnit to test a Laravel package inside a host application with Github actions?

Summary

I have a package that needs to be wrapped by a real laravel app to be tested properly. Unfortunately I cant use the orchestra testbench. However I have setup a Github action for this. But, when running the final step vendor/phpunit/phpunit/phpunit path/to/package im experiencing the following issues:

PHPUnit can't resolve certain classes

It thinks PHPUnit setUp() is public in my parent class though it is protected.

I suspect some issue with caching or delay after push (but I have tested wiping all cache,
autoload and config)

Example error

```<code>Run vendor/phpunit/phpunit/phpunit packages/Ajthinking/PHPFileManipulator/tests
PHP Fatal error:  Uncaught Error: Class 'PHPFileManipulator\Tests\FileTestCase' not found in /home/runner/work/php-file-manipulator/php-file-manipulator/host/packages/Ajthinking/PHPFileManipulator/tests/Unit/APIDelegationTest.php:10
Stack trace:
#0 /home/runner/work/php-file-manipulator/php-file-manipulator/host/vendor/phpunit/phpunit/src/Util/FileLoader.php(59): include_once()
#1 /home/runner/work/php-file-manipulator/php-file-manipulator/host/vendor/phpunit/phpunit/src/Util/FileLoader.php(47):
</code>```

Reviewing my master branch, the requested file FileTestCase is there.

The full action script:

```<code>name: Laravel-wrapped-package-test

on: [push]

jobs:
  laravel-tests:
    runs-on: ubuntu-latest
    steps:
    - name: Install host app
      run: composer create-project --prefer-dist laravel/laravel host

    - name: Install package (this repo)
      uses: actions/checkout@v2
      with:
        path: host/packages/Ajthinking/PHPFileManipulator

    - name: Add this package to composer.json repositories
      uses: ajthinking/merge-json-files@v1.0.20
      with:
        repo_relative_path: 'host/packages/Ajthinking/PHPFileManipulator'

    - name: Require this package
      working-directory: ./host
      run: composer require ajthinking/php-file-manipulator @dev

    - name: Publish things
      working-directory: ./host
      run: php artisan vendor:publish --provider="PHPFileManipulator\ServiceProvider"

    - name: Run tests
      working-directory: ./host
      run: vendor/phpunit/phpunit/phpunit packages/Ajthinking/PHPFileManipulator/tests
</code>```

TestCase

Below is my base test case. But the setUp method is never called. (Previously it was called TestCase as the default laravel provides - it was renamed while debugging)

```<code><?php

namespace PHPFileManipulator\Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class FileTestCase extends BaseTestCase
{
    protected function setUp() : void
    {
        parent::setUp();
        dd("it will never reach this dd call on github actions!");
    }
}
</code>```

Usage:

```<code><?php

namespace PHPFileManipulator\Tests\Unit;

use PHPFileManipulator\Tests\FileTestCase;

class StupidTest extends FileTestCase
{
    /** @test */
    public function it_can_run_tests()
    {
        $this->assertTrue(true);
    }
}
</code>```

versions

Im using PHP 7.4.2 and PHPUnit 8.5.2 (same as github actions ubuntu-latest) Mimicing the action script on my own machine works fine.
I have reviewed CASE on github/local found no differences.

Any ideas, what I am missing?

答:
I failed updating the host app composer.json repositories section. That meant requiring the package with @dev flag (taking latest commit) had no effect
 - instead an outdated package version was pulled from packagagist.

Fixed github workflow:

```<code>name: tests

on: [push, pull_request]

jobs:
  laravel-tests:
    runs-on: ubuntu-latest
    steps:
    - name: Install host app
      run: composer create-project --prefer-dist laravel/laravel host

    - name: Checkout the package
      uses: actions/checkout@v2
      with:
        path: host/packages/Ajthinking/PHPFileManipulator

    - name: Add composer.json repository
      working-directory: ./host
      run: composer config repositories.php-file-manipulator path "/home/runner/work/php-file-manipulator/php-file-manipulator/host/packages/Ajthinking/PHPFileManipulator"

    - name: Require the package
      working-directory: ./host
      run: composer require ajthinking/php-file-manipulator @dev

    - name: Publish things
      working-directory: ./host
      run: php artisan vendor:publish --provider="PHPFileManipulator\ServiceProvider"

    - name: Run tests
      working-directory: ./host
      run: vendor/phpunit/phpunit/phpunit packages/Ajthinking/PHPFileManipulator/tests
</code>```

Body:
Summary

I have a package that needs to be wrapped by a real laravel app to be tested properly. Unfortunately I cant use the orchestra testbench. However I have setup a Github action for this. But, when running the final step vendor/phpunit/phpunit/phpunit path/to/package im experiencing the following issues:

PHPUnit can't resolve certain classes

It thinks PHPUnit setUp() is public in my parent class though it is protected.

I suspect some issue with caching or delay after push (but I have tested wiping all cache,
autoload and config)

Example error

Run vendor/phpunit/phpunit/phpunit packages/Ajthinking/PHPFileManipulator/tests
PHP Fatal error:  Uncaught Error: Class 'PHPFileManipulator\Tests\FileTestCase' not found in /home/runner/work/php-file-manipulator/php-file-manipulator/host/packages/Ajthinking/PHPFileManipulator/tests/Unit/APIDelegationTest.php:10
Stack trace:
#0 /home/runner/work/php-file-manipulator/php-file-manipulator/host/vendor/phpunit/phpunit/src/Util/FileLoader.php(59): include_once()
#1 /home/runner/work/php-file-manipulator/php-file-manipulator/host/vendor/phpunit/phpunit/src/Util/FileLoader.php(47):

Reviewing my master branch, the requested file FileTestCase is there.

The full action script:

name: Laravel-wrapped-package-test

on: [push]

jobs:
  laravel-tests:
    runs-on: ubuntu-latest
    steps:
    - name: Install host app
      run: composer create-project --prefer-dist laravel/laravel host

    - name: Install package (this repo)
      uses: actions/checkout@v2
      with:
        path: host/packages/Ajthinking/PHPFileManipulator

    - name: Add this package to composer.json repositories
      uses: ajthinking/merge-json-files@v1.0.20
      with:
        repo_relative_path: 'host/packages/Ajthinking/PHPFileManipulator'

    - name: Require this package
      working-directory: ./host
      run: composer require ajthinking/php-file-manipulator @dev

    - name: Publish things
      working-directory: ./host
      run: php artisan vendor:publish --provider="PHPFileManipulator\ServiceProvider"

    - name: Run tests
      working-directory: ./host
      run: vendor/phpunit/phpunit/phpunit packages/Ajthinking/PHPFileManipulator/tests

TestCase

Below is my base test case. But the setUp method is never called. (Previously it was called TestCase as the default laravel provides - it was renamed while debugging)

<?php

namespace PHPFileManipulator\Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class FileTestCase extends BaseTestCase
{
    protected function setUp() : void
    {
        parent::setUp();
        dd("it will never reach this dd call on github actions!");
    }
}

Usage:

<?php

namespace PHPFileManipulator\Tests\Unit;

use PHPFileManipulator\Tests\FileTestCase;

class StupidTest extends FileTestCase
{
    /** @test */
    public function it_can_run_tests()
    {
        $this->assertTrue(true);
    }
}

versions

Im using PHP 7.4.2 and PHPUnit 8.5.2 (same as github actions ubuntu-latest) Mimicing the action script on my own machine works fine.
I have reviewed CASE on github/local found no differences.

Any ideas, what I am missing?

Body:
I failed updating the host app composer.json repositories section. That meant requiring the package with @dev flag (taking latest commit) had no effect
 - instead an outdated package version was pulled from packagagist.

Fixed github workflow:

name: tests

on: [push, pull_request]

jobs:
  laravel-tests:
    runs-on: ubuntu-latest
    steps:
    - name: Install host app
      run: composer create-project --prefer-dist laravel/laravel host

    - name: Checkout the package
      uses: actions/checkout@v2
      with:
        path: host/packages/Ajthinking/PHPFileManipulator

    - name: Add composer.json repository
      working-directory: ./host
      run: composer config repositories.php-file-manipulator path "/home/runner/work/php-file-manipulator/php-file-manipulator/host/packages/Ajthinking/PHPFileManipulator"

    - name: Require the package
      working-directory: ./host
      run: composer require ajthinking/php-file-manipulator @dev

    - name: Publish things
      working-directory: ./host
      run: php artisan vendor:publish --provider="PHPFileManipulator\ServiceProvider"

    - name: Run tests
      working-directory: ./host
      run: vendor/phpunit/phpunit/phpunit packages/Ajthinking/PHPFileManipulator/tests


问:
MVC Custom Validation String Array Client Side
There are examples out there of custom MVC validators that take an array parameter, but only server side - none of them show an example of implementing the client side with array parameter.

The problem is instead of outputting the array's contents in the html data- attribute, it outputs "System.String[]":

data-val-total-propertynames="System.String[]"

Here is my attribute class:

```<code>public class TotalAttribute : ValidationAttribute, IClientValidatable
    {
        private String[] PropertyNames { get; set; }

        public TotalAttribute(String[] propertyNames)
        {
            PropertyNames = propertyNames;
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            float total = 0;

            foreach (var propertyName in PropertyNames)
                total += (float)context.ObjectInstance.GetType().GetProperty(propertyName).GetValue(context.ObjectInstance, null);

            if (total != (float)value)
                return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });

            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "total",
            };
            rule.ValidationParameters["propertynames"] = PropertyNames;

            yield return rule;
        }
    }
</code>```

Here it is implemented in the model:

```<code>[Total(new string[] { "SomeOtherField1", "SomeOtherField2" }, ErrorMessage = "'Line12Balance' must equal total of 'SomeOtherField1' and 'SomeOtherField2'")]
public decimal? Line12Balance { get; set; }
</code>```

Here is the html data-val attribute output:

```<code>data-val-total-propertynames="System.String[]"
</code>```

What am I doing wrong?

答:
You get "System.String[]" string because the value of ValidationParameters["propertynames"] is written by calling ToString on it, so string[] variable returns "System.String[]" in this case. If you need to output specific value you need to format it by yourself in your validation attribute. For example, change

```<code>rule.ValidationParameters["propertynames"] = PropertyNames;
</code>```

to

```<code>rule.ValidationParameters["propertynames"] =  string.Join(",", PropertyNames);
</code>```

and you will get

```<code>data-val-total-propertynames="SomeOtherField1,SomeOtherField2"
</code>```

Body:
There are examples out there of custom MVC validators that take an array parameter, but only server side - none of them show an example of implementing the client side with array parameter.

The problem is instead of outputting the array's contents in the html data- attribute, it outputs "System.String[]":

data-val-total-propertynames="System.String[]"

Here is my attribute class:

public class TotalAttribute : ValidationAttribute, IClientValidatable
    {
        private String[] PropertyNames { get; set; }

        public TotalAttribute(String[] propertyNames)
        {
            PropertyNames = propertyNames;
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            float total = 0;

            foreach (var propertyName in PropertyNames)
                total += (float)context.ObjectInstance.GetType().GetProperty(propertyName).GetValue(context.ObjectInstance, null);

            if (total != (float)value)
                return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });

            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "total",
            };
            rule.ValidationParameters["propertynames"] = PropertyNames;

            yield return rule;
        }
    }

Here it is implemented in the model:

[Total(new string[] { "SomeOtherField1", "SomeOtherField2" }, ErrorMessage = "'Line12Balance' must equal total of 'SomeOtherField1' and 'SomeOtherField2'")]
public decimal? Line12Balance { get; set; }

Here is the html data-val attribute output:

data-val-total-propertynames="System.String[]"

What am I doing wrong?

Body:
You get "System.String[]" string because the value of ValidationParameters["propertynames"] is written by calling ToString on it, so string[] variable returns "System.String[]" in this case. If you need to output specific value you need to format it by yourself in your validation attribute. For example, change

rule.ValidationParameters["propertynames"] = PropertyNames;

to

rule.ValidationParameters["propertynames"] =  string.Join(",", PropertyNames);

and you will get

data-val-total-propertynames="SomeOtherField1,SomeOtherField2"


问:
Redirect Java 8 GC logs to stderr
Is there any way to print GC logs to stderr instead of stdout in SunJDK Java 8.
I am using -verbose:gc to enable GC logs and it is redirecting to stdout by default.
This can printed to a file using -Xloggc: argument.

But unable to print GC logs to stderr. Printing to stdout clutters my log file with GC allocation failure logs

答:
For Java 8 use

```<code>java -Xloggc:stderr
</code>```

For Java 9+ try using

```<code>java -Xlog:gc:stderr ...
</code>```

Or for a higher log level

```<code>java -Xlog:gc=debug:stderr ...
</code>```

Or for logging each garbage collection:

```<code>java -Xlog:gc*:stederr
</code>```

Title: Redirect Java 8 GC logs to stderr

Body:
For Java 8 use

java -Xloggc:stderr

For Java 9+ try using

java -Xlog:gc:stderr ...

Or for a higher log level

java -Xlog:gc=debug:stderr ...

Or for logging each garbage collection:

java -Xlog:gc*:stederr


问:
Finding median of list in Python
How do you find the median of a list in Python? The list can be of any size and the numbers are not guaranteed to be in any particular order.

If the list contains an even number of elements, the function should return the average of the middle two.

Here are some examples (sorted for display purposes):

```<code>median([1]) == 1
median([1, 1]) == 1
median([1, 1, 2, 4]) == 1.5
median([0, 2, 5, 6, 8, 9, 9]) == 6
median([0, 0, 0, 0, 4, 4, 6, 8]) == 2
</code>```

答:
Function median:

```<code>def median(d):
    d=np.sort(d)
    n2=int(len(d)/2)
    r=n2%2
    if (r==0):
        med=d[n2]
    else:
        med=(d[n2] + d[n2+1]) / 2
    return med
</code>```

Title: Finding median of list in Python

Body:
How do you find the median of a list in Python? The list can be of any size and the numbers are not guaranteed to be in any particular order.

If the list contains an even number of elements, the function should return the average of the middle two.

Here are some examples (sorted for display purposes):

median([1]) == 1
median([1, 1]) == 1
median([1, 1, 2, 4]) == 1.5
median([0, 2, 5, 6, 8, 9, 9]) == 6
median([0, 0, 0, 0, 4, 4, 6, 8]) == 2

Body:
Function median:

def median(d):
    d=np.sort(d)
    n2=int(len(d)/2)
    r=n2%2
    if (r==0):
        med=d[n2]
    else:
        med=(d[n2] + d[n2+1]) / 2
    return med


问:
Genymotion network error when tried to register the installation
I just installed Genymotion, when I started and tried to register via Genymotion app this error appeared:

Network Error

Seems like Genymotion can't figure out a way to connect to Internet!

答: Uninstall and Reinstall Genymotion just works for me.</p>


问:
F# - Convert a char to int
While coding in F# for a project, I have come to a point where I want to convert a char to an int. I.e.

```<code>let c = '3'
c |> int //this will however give the ascii value of 3 I believe
</code>```

My question is, what is the best way to convert a single char to an int without converting the char to a string or another types, in a case where the char only holds a digit?

答:
Convert to string first:</p>

```<code>c |> sprintf "%c" |> int
</code>```

Title: F# - Convert a char to int

Body:
While coding in F# for a project, I have come to a point where I want to convert a char to an int. I.e.

let c = '3'
c |> int //this will however give the ascii value of 3 I believe

My question is, what is the best way to convert a single char to an int without converting the char to a string or another types, in a case where the char only holds a digit?

Body:
Convert to string first:

c |> sprintf "%c" |> int


问:
how to convert date in month python?
i m currently working in Generating dynamic invoice on monthly basis but i m stuck in getting month name in python from user input date

Example: Given Date is :15/03/2020 is date and month is March

Any help would be appreciated

答:
Assuming that you are receiving the date in the form of a string like "15/03/2020":

int(date.split('/')[1]) returns the value between the first and second / of date as an integer.  This can then be used as the index for a list of month names to return the name of the month:

```<code>months = ["January","February","March",...]
print(months[int(date.split('/')[1])-1])
</code>```

Title: how to convert date in month python?

Body:
Assuming that you are receiving the date in the form of a string like "15/03/2020":

int(date.split('/')[1]) returns the value between the first and second / of date as an integer.  This can then be used as the index for a list of month names to return the name of the month:

months = ["January","February","March",...]
print(months[int(date.split('/')[1])-1])