问:
Concatenation of multiple HEX values in C
I have an array in memory that holds certain hex values that describe assembly instructions. For example:

```<code>708877665544332211 = jump 0x1122334455667788
</code>```

70 indicates a jump in assembly and the following hex numbers are what I need to concatenate. I've already tried doing,

```<code>address |= memory[1];
address |= memory[2]<<8;
address |= memory[3]<<16;
address |= memory[4]<<24;
address |= memory[5]<<32;
address |= memory[6]<<40;
address |= memory[7]<<48;
address |= memory[8]<<56;
</code>```

The string that was outputted was:

0x100: 708877665544332211   |   jump 1432778700

Where am I going wrong in the concatenation?

EDIT: Following Benjamin's suggestion, I changed it to:

With print statement printf("APPEND: %016llx", address) to debug, I found that the uint64_t was being changed as:

```<code>APPEND: 0000000000002211
APPEND: 0000000000332211
APPEND: 0000000044332211
APPEND: 0000000044332255
APPEND: 0000000044336655
APPEND: 0000000044776655
</code>```

If the address is a 64bit integer, why does it appear to be behaving as a 32bit integer?

答:
The problem is the byte order. Maybe you can try the following:

```<code>address = memory[8];
address |= memory[7]<<8;
address |= memory[6]<<16;
address |= memory[5]<<24;
address |= memory[4]<<32;
address |= memory[3]<<40;
address |= memory[2]<<48;
address |= memory[1]<<56;
</code>```

P.S.: It would help if you code post the full code (including the printing).

Body:
I have an array in memory that holds certain hex values that describe assembly instructions. For example:

708877665544332211 = jump 0x1122334455667788

70 indicates a jump in assembly and the following hex numbers are what I need to concatenate. I've already tried doing,

address |= memory[1];
address |= memory[2]<<8;
address |= memory[3]<<16;
address |= memory[4]<<24;
address |= memory[5]<<32;
address |= memory[6]<<40;
address |= memory[7]<<48;
address |= memory[8]<<56;

The string that was outputted was:

0x100: 708877665544332211   |   jump 1432778700

Where am I going wrong in the concatenation?

EDIT: Following Benjamin's suggestion, I changed it to:

With print statement printf("APPEND: %016llx", address) to debug, I found that the uint64_t was being changed as:

APPEND: 0000000000002211
APPEND: 0000000000332211
APPEND: 0000000044332211
APPEND: 0000000044332255
APPEND: 0000000044336655
APPEND: 0000000044776655

If the address is a 64bit integer, why does it appear to be behaving as a 32bit integer?

Body:
The problem is the byte order. Maybe you can try the following:

address = memory[8];
address |= memory[7]<<8;
address |= memory[6]<<16;
address |= memory[5]<<24;
address |= memory[4]<<32;
address |= memory[3]<<40;
address |= memory[2]<<48;
address |= memory[1]<<56;

P.S.: It would help if you code post the full code (including the printing).


来源: stackexchange

问:
Conditional and non-conditional in one Fluent Validation rule
I need to validate zip code,
- it always must have a value (non-conditional)

```<code>// General Rule:
RuleFor( m => m.Zip ).NotEmpty()
    .WithMessage( "Zip code is required." );
</code>```

If it's in the US, value should match regex (conditional)

```<code>// United States Rule:
RuleFor( m => m.Zip )
    .Matches( ZipCodeRegEx )
    .WithMessage( "Invalid Zip Code" )
    .When( m => IsUnitedStates( m.CountryCode ) );
</code>```

My goal is to combine General Rule and United States Rule in one Rule
, I have tried:

```<code>// doesn't check general rule for non-us
RuleFor( m => m.Zip )
    .NotEmpty()
        .WithMessage( "Zip code is required." )
    .Matches( ZipCodeRegEx )
        .When( m => IsUnitedStates( m.CountryCode ) )
        .WithMessage( "Invalid Zip Code" );

// doesn't check general rule for non-us
RuleFor( m => m.Zip )
    .NotEmpty()
        .When( m => true )// always
        .WithMessage( "Zip code is required." )
    .Matches( ZipCodeRegEx )
        .When( m => IsUnitedStates( m.CountryCode ) )
        .WithMessage( "Invalid Zip Code" );
</code>```

How I can write this in one rule?

答: It is not possible to do it in one rule. FluentValidation was not designed to support that case.</p>

ContentLicense: CC BY-SA 3.0

Body:
I need to validate zip code,
- it always must have a value (non-conditional)

// General Rule:
RuleFor( m => m.Zip ).NotEmpty()
    .WithMessage( "Zip code is required." );

If it's in the US, value should match regex (conditional)

// United States Rule:
RuleFor( m => m.Zip )
    .Matches( ZipCodeRegEx )
    .WithMessage( "Invalid Zip Code" )
    .When( m => IsUnitedStates( m.CountryCode ) );

My goal is to combine General Rule and United States Rule in one Rule
, I have tried:

// doesn't check general rule for non-us
RuleFor( m => m.Zip )
    .NotEmpty()
        .WithMessage( "Zip code is required." )
    .Matches( ZipCodeRegEx )
        .When( m => IsUnitedStates( m.CountryCode ) )
        .WithMessage( "Invalid Zip Code" );

// doesn't check general rule for non-us
RuleFor( m => m.Zip )
    .NotEmpty()
        .When( m => true )// always
        .WithMessage( "Zip code is required." )
    .Matches( ZipCodeRegEx )
        .When( m => IsUnitedStates( m.CountryCode ) )
        .WithMessage( "Invalid Zip Code" );

How I can write this in one rule?


问:
Create a class constructor from scratch in ByteBuddy
I am trying to create a Java class from scratch using ByteBuddy. A class is supposed to have a bunch of private final properties and one constructor which initializes them with the arguments passed. I started with:

```<code>DynamicType.Builder<?> builder = new ByteBuddy()
                .subclass(Object.class)
                .implement(Serializable.class)
                .modifiers(Visibility.PUBLIC, TypeManifestation.FINAL)
                .name("Structure");

// for each property to be declared
builder = builder.defineField(bindingName, bindingType, visibility.PRIVATE, FieldManifestation.FINAL);
// end of for

builder = builder.defineConstructor(Visibility.PUBLIC)
                .withParameters(bindings)
                .intercept(/* Some implementation is supposed to go here*/);
</code>```

I have several questions:

Does ByteBuddy provide some suitable Implementation for that out-of-the-box?

Is there somewhere an overview of ByteBuddy Implementation classes, provided out-of-the-box?

If there is no such Implementation out-of-the-box, I'd be appreciated for some hints on how to make my own Implementation instance serving my purpose.

答:
Didn't found any ready implementation, so end up writing my own. It is not finalized, but it works. Here it is:

```<code>final class ConstructorImplementation implements Implementation {

    static private final class BCA implements ByteCodeAppender {

        @Override
        public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
            TypeDescription instrumentedType = implementationContext.getInstrumentedType();
            Iterator<? extends ParameterDescription> iterator = instrumentedMethod.getParameters().iterator();

            List<StackManipulation> insr = new ArrayList<>();
            insr.add(MethodVariableAccess.loadThis());
            insr.add(MethodInvocation.invoke(TypeDescription.OBJECT.getDeclaredMethods().get(0)));
            for (FieldDescription.InDefinedShape field : instrumentedType.getDeclaredFields()) {
                ParameterDescription.InDefinedShape param = iterator.next().asDefined();
                insr.add(MethodVariableAccess.loadThis());
                insr.add(MethodVariableAccess.load(param));
                insr.add(FieldAccess.forField(field).write());
            }
            insr.add(MethodReturn.VOID);

            StackManipulation.Size operandStackSize = new StackManipulation.Compound(
                    insr
            ).apply(methodVisitor, implementationContext);
            return new Size(operandStackSize.getMaximalSize(),
                    instrumentedMethod.getStackSize());
        }
    }

    private final BCA bca;

    public ConstructorImplementation() {
        bca = new BCA();
    }

    @Override
    public ByteCodeAppender appender(Target implementationTarget) {
        return bca;
    }

    @Override
    public InstrumentedType prepare(InstrumentedType instrumentedType) {
        return instrumentedType;
    }
}
</code>```

I'll leave this question opened for a while, for the case somebody knows a better solution for that.

Body:
I am trying to create a Java class from scratch using ByteBuddy. A class is supposed to have a bunch of private final properties and one constructor which initializes them with the arguments passed. I started with:

DynamicType.Builder<?> builder = new ByteBuddy()
                .subclass(Object.class)
                .implement(Serializable.class)
                .modifiers(Visibility.PUBLIC, TypeManifestation.FINAL)
                .name("Structure");

// for each property to be declared
builder = builder.defineField(bindingName, bindingType, visibility.PRIVATE, FieldManifestation.FINAL);
// end of for

builder = builder.defineConstructor(Visibility.PUBLIC)
                .withParameters(bindings)
                .intercept(/* Some implementation is supposed to go here*/);

I have several questions:

Does ByteBuddy provide some suitable Implementation for that out-of-the-box?

Is there somewhere an overview of ByteBuddy Implementation classes, provided out-of-the-box?

If there is no such Implementation out-of-the-box, I'd be appreciated for some hints on how to make my own Implementation instance serving my purpose.

Body:
Didn't found any ready implementation, so end up writing my own. It is not finalized, but it works. Here it is:

final class ConstructorImplementation implements Implementation {

    static private final class BCA implements ByteCodeAppender {

        @Override
        public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
            TypeDescription instrumentedType = implementationContext.getInstrumentedType();
            Iterator<? extends ParameterDescription> iterator = instrumentedMethod.getParameters().iterator();

            List<StackManipulation> insr = new ArrayList<>();
            insr.add(MethodVariableAccess.loadThis());
            insr.add(MethodInvocation.invoke(TypeDescription.OBJECT.getDeclaredMethods().get(0)));
            for (FieldDescription.InDefinedShape field : instrumentedType.getDeclaredFields()) {
                ParameterDescription.InDefinedShape param = iterator.next().asDefined();
                insr.add(MethodVariableAccess.loadThis());
                insr.add(MethodVariableAccess.load(param));
                insr.add(FieldAccess.forField(field).write());
            }
            insr.add(MethodReturn.VOID);

            StackManipulation.Size operandStackSize = new StackManipulation.Compound(
                    insr
            ).apply(methodVisitor, implementationContext);
            return new Size(operandStackSize.getMaximalSize(),
                    instrumentedMethod.getStackSize());
        }
    }

    private final BCA bca;

    public ConstructorImplementation() {
        bca = new BCA();
    }

    @Override
    public ByteCodeAppender appender(Target implementationTarget) {
        return bca;
    }

    @Override
    public InstrumentedType prepare(InstrumentedType instrumentedType) {
        return instrumentedType;
    }
}

I'll leave this question opened for a while, for the case somebody knows a better solution for that.


问:
Batch hostednetwork IF ELSE not working
I would like to write a batch script, but i'm not very good at it.
I want to start my hostednetwork if it isn't running. If it is already running, I want to stop it. Could somebody help me please?
This is what I have:</p>

```<code>@echo off
netsh wlan show hostednetwork
if not (hostednetwork==started) goto start
else goto stop

:start
    netsh wlan start hostednetwork
    goto end

:stop
</code>```

答:
For anyone who would like to use this method, here is the complete working code

```<code>@ECHO OFF
netsh wlan show hostednetwork|find "Status"|find "Started">nul && goto stop || goto start
:start
    netsh wlan start hostednetwork
    goto end

:stop
    netsh wlan stop hostednetwork
    goto end

:end
    PAUSE
</code>```

Thanks to those who put into the creation of this method

Title: Batch hostednetwork IF ELSE not working

Body:
I would like to write a batch script, but i'm not very good at it.
I want to start my hostednetwork if it isn't running. If it is already running, I want to stop it. Could somebody help me please?
This is what I have:

@echo off
netsh wlan show hostednetwork
if not (hostednetwork==started) goto start
else goto stop

:start
    netsh wlan start hostednetwork
    goto end

:stop

Body:
For anyone who would like to use this method, here is the complete working code

@ECHO OFF
netsh wlan show hostednetwork|find "Status"|find "Started">nul && goto stop || goto start
:start
    netsh wlan start hostednetwork
    goto end

:stop
    netsh wlan stop hostednetwork
    goto end

:end
    PAUSE

Thanks to those who put into the creation of this method


问:
How can I access IME preferences loaded from XML in keyboard service on android?
I am trying to create my own custom software keyboard for Android.I inspired myself by this tutorial, so my keyboard service onCreateInputView() looks like:

```<code>...
private KeyboardView keyboardView;
private Keyboard defaultKeyboard;
private Keyboard charKeyboard;
...
@Override
public View onCreateInputView()
{
    defaultKeyboard = new Keyboard(this, R.xml.alphabet_letter_keyboard);
    charKeyboard = new Keyboard(this, R.xml.specialcharacter_keyboard);
    keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard, null);
    keyboardView.setKeyboard(defaultKeyboard);
...
</code>```

I also looked at the way AOSP-Keyboard is implementing the keyboard preferences  (In the Android settings -> input method, if you click on the Keyboard Name you reach the keyboards settings screen), so I settings from XML-file like:

```<code>public static class Settings extends InputMethodSettingsFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setInputMethodSettingsCategoryTitle(R.string.layout_selection_title);
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.ime_preferences);
...
</code>```

The XML settings look like:

```<code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
    android:title="@string/select_layout">
        android:title="Layouts"
        android:key="layouts"
        android:summary="Click to select the keyboard layout"
        android:defaultValue="qwertz"
        android:entries="@array/list"
        android:entryValues="@array/values"
        ></ListPreference>
</PreferenceCategory>
</code>```

so I can choose in the settings from different layouts (qwerty, alphabetic ...). What I would like to achieve is to access the selected value in the keyboardService onCreateInputView() method, so the right layout will be taken for the defaultKeyboard instance.

E.g.

```<code>@Override
public View onCreateInputView()
{
    // Access the list setting value of the selected layout
    String selectedLayout = ...
    switch(selectedLayout) { // Initialize keyboard with abcde or qwert layout
        case "abcde":
            defaultKeyboard = new Keyboard(this, R.xml.alphabet_letter_keyboard);
            break;
        case "qwert":
            defaultKeyboard = new Keyboard(this, R.xml.typewriter_letter_keyboard);
            break;
    }
...
</code>```

答:
I found a solution. You can access the settings with

```<code>SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getString("layouts", "qwert")
</code>```

The second parameter by prefs.getString is the default value. For changing the keyboard layout on setting-change you need to implement onSharedPreferenceChanged method

The general code looks than like this:

```<code>public class KeyboardService extends InputMethodService implements KeyboardView.OnKeyboardActionListener, SharedPreferences.OnSharedPreferenceChangeListener
{
private KeyboardView keyboardView;
private Keyboard defaultKeyboard;
private Keyboard charKeyboard;
private boolean isCaps = true; //Start the keyboard in Caps-layout
private boolean isCharKeyboard = false; //Start the keyboard with letter-layout
SharedPreferences prefs;

@Override
public View onCreateInputView()
{
    // SharedPreferences prefs = getSharedPreferences("ime_preferences", MODE_PRIVATE);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    // register preference change listener
    prefs.registerOnSharedPreferenceChangeListener(this);

    // Set the initial layout according to the initial layout selection
    switch(prefs.getString("layouts", "qwert")) { // Initialize keyboard with abcde or qwert layout
        case "abcde":
            defaultKeyboard = new Keyboard(this, R.xml.alphabet_letter_keyboard);
            break;
        case "qwert":
            defaultKeyboard = new Keyboard(this, R.xml.typewriter_letter_keyboard);
            break;
    }

...

// handle updates to preferences
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    if (key.equals("layouts")) {
        switch(prefs.getString("layouts", "qwert")) { // Initialize keyboard with abcde or qwert layout
        case "abcde":
            defaultKeyboard = new Keyboard(this, R.xml.alphabet_letter_keyboard);
            break;
        case "qwert":
            defaultKeyboard = new Keyboard(this, R.xml.typewriter_letter_keyboard);
            break;
    }
    keyboardView.setKeyboard(defaultKeyboard);
    setInputView(this.onCreateInputView());
    }
}
</code>```

Body:
I am trying to create my own custom software keyboard for Android.I inspired myself by this tutorial, so my keyboard service onCreateInputView() looks like:

...
private KeyboardView keyboardView;
private Keyboard defaultKeyboard;
private Keyboard charKeyboard;
...
@Override
public View onCreateInputView()
{
    defaultKeyboard = new Keyboard(this, R.xml.alphabet_letter_keyboard);
    charKeyboard = new Keyboard(this, R.xml.specialcharacter_keyboard);
    keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard, null);
    keyboardView.setKeyboard(defaultKeyboard);
...

I also looked at the way AOSP-Keyboard is implementing the keyboard preferences  (In the Android settings -> input method, if you click on the Keyboard Name you reach the keyboards settings screen), so I settings from XML-file like:

public static class Settings extends InputMethodSettingsFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setInputMethodSettingsCategoryTitle(R.string.layout_selection_title);
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.ime_preferences);
...

The XML settings look like:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
    android:title="@string/select_layout">
        android:title="Layouts"
        android:key="layouts"
        android:summary="Click to select the keyboard layout"
        android:defaultValue="qwertz"
        android:entries="@array/list"
        android:entryValues="@array/values"
        ></ListPreference>
</PreferenceCategory>

so I can choose in the settings from different layouts (qwerty, alphabetic ...). What I would like to achieve is to access the selected value in the keyboardService onCreateInputView() method, so the right layout will be taken for the defaultKeyboard instance.

E.g.

@Override
public View onCreateInputView()
{
    // Access the list setting value of the selected layout
    String selectedLayout = ...
    switch(selectedLayout) { // Initialize keyboard with abcde or qwert layout
        case "abcde":
            defaultKeyboard = new Keyboard(this, R.xml.alphabet_letter_keyboard);
            break;
        case "qwert":
            defaultKeyboard = new Keyboard(this, R.xml.typewriter_letter_keyboard);
            break;
    }
...

Body:
I found a solution. You can access the settings with

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getString("layouts", "qwert")

The second parameter by prefs.getString is the default value. For changing the keyboard layout on setting-change you need to implement onSharedPreferenceChanged method

The general code looks than like this:

public class KeyboardService extends InputMethodService implements KeyboardView.OnKeyboardActionListener, SharedPreferences.OnSharedPreferenceChangeListener
{
private KeyboardView keyboardView;
private Keyboard defaultKeyboard;
private Keyboard charKeyboard;
private boolean isCaps = true; //Start the keyboard in Caps-layout
private boolean isCharKeyboard = false; //Start the keyboard with letter-layout
SharedPreferences prefs;

@Override
public View onCreateInputView()
{
    // SharedPreferences prefs = getSharedPreferences("ime_preferences", MODE_PRIVATE);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    // register preference change listener
    prefs.registerOnSharedPreferenceChangeListener(this);

    // Set the initial layout according to the initial layout selection
    switch(prefs.getString("layouts", "qwert")) { // Initialize keyboard with abcde or qwert layout
        case "abcde":
            defaultKeyboard = new Keyboard(this, R.xml.alphabet_letter_keyboard);
            break;
        case "qwert":
            defaultKeyboard = new Keyboard(this, R.xml.typewriter_letter_keyboard);
            break;
    }

...

// handle updates to preferences
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    if (key.equals("layouts")) {
        switch(prefs.getString("layouts", "qwert")) { // Initialize keyboard with abcde or qwert layout
        case "abcde":
            defaultKeyboard = new Keyboard(this, R.xml.alphabet_letter_keyboard);
            break;
        case "qwert":
            defaultKeyboard = new Keyboard(this, R.xml.typewriter_letter_keyboard);
            break;
    }
    keyboardView.setKeyboard(defaultKeyboard);
    setInputView(this.onCreateInputView());
    }
}


问:
Retrieve Java Component name in Mulesoft flow
Is there way in Java to get its own Java Component name in the Mulesoft flow?

In other words - how can I get "JavaComponentName" inside its Java code?

答:
I think the method that you are looking for is :

LocationExecutionContextProvider.resolveProcessorRepresentation(String appId, processorPath, element)

According to the java docs:

```<code> /**
     * Generates a representation of a flow element to be logged in a standard way.
     *
     * @param appId
     * @param processorPath
     * @param element
     * @return
     */
    public static String resolveProcessorRepresentation(String appId, String processorPath, Object element)
</code>```

Give it a try and let us know if is working! cheers!

Body:
I think the method that you are looking for is :

LocationExecutionContextProvider.resolveProcessorRepresentation(String appId, processorPath, element)

According to the java docs:

 /**
     * Generates a representation of a flow element to be logged in a standard way.
     *
     * @param appId
     * @param processorPath
     * @param element
     * @return
     */
    public static String resolveProcessorRepresentation(String appId, String processorPath, Object element)

Give it a try and let us know if is working! cheers!


问:
Is there a way to add a description to each option in a dropdown using select2?
I have a Django project in which I have a select dropdown like this:

But I want something like this:

My <select> form looks like so: (after inspecting in developer tools)

```<code><select class="form-control" data-parsley-required="true" id="id_org_role" name="org_role" required="">
    <option value="A">Administrator</option>
    <option value="M" selected="selected">Member</option>
</select>
</code>```

If not select2, is there any other jquery library that can help me accomplish this?

I have tried following the Select2's documentation, and believe that if
this way (for templates), we can span an image beside the option's text, then, there must be a way to span a "text description" too under each option. But I dont know how this can be achieved. All I have tried to do untill now is this:

```<code>var org_role = function(roles){
      if (!roles.id) {
      return roles.text;
    }
    return $(
    '<strong>' + roles.text + '</strong>' + '<br/>'
    '<span>' + "some description" + '</span>'
  );
};

$("#id_org_role").select2({
  templateResult: org_role,
});
</code>```

But this is not working. Also, even if it does, it would display the same description for all the options. But it has to be different obviously.

My Django form inside the template looks like this:

```<code><form method="POST" action="" class="org-member-edit" id='organization_permissions' data-parsley-validate>

{% csrf_token %}

<div class="form-group member-role{% if org_role_form.org_role.errors %} has-error{% endif %}">

    <label class="control-label" for="{{ org_role_form.org_role.id_for_label }}">{% trans "Role" %}</label>

{% render_field org_role_form.org_role class+="form-control" data-parsley-required="true" %}

    <div class="error-block">{{ org_role_form.org_role.errors }}</div>

  </div>

</form>
</code>```

in the 5th line above, i.e the render_field org_role_form.org_role in the template tag, the org_role takes up values from the following form:
(note : render_field because I am using Django-tweaks-wideget)

```<code>class EditOrganizationMemberForm(SuperUserCheck, forms.Form):

org_role = forms.ChoiceField(choices=ADMIN_CHOICES)
</code>```

which takes choice fields from another file choices.py like so:

```<code>ADMIN_CHOICES = (
         ('A', _('Administrator')),
         ('M', _('Member'))
        )
</code>```

How can I achieve this? (different descriptions for different options) Please help. I have been stuck at this since hours.

答:
What about putting the description in an attribute e.g. title?

$(function(){
  $("select").select2({
    templateResult: formatOption
  });

  function formatOption (option) {
    var $option = $(
      '
' + option.text + '

' + option.title + '
'
    );
    return $option;
  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/select2.full.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />

<select style="width:200px">
  <option value="optionA" title="Description for A">option A</option>
  <option value="optionB" title="Description for B">option B</option>
</select></code>```

Body:
I have a Django project in which I have a select dropdown like this:

But I want something like this:

My <select> form looks like so: (after inspecting in developer tools)

<select class="form-control" data-parsley-required="true" id="id_org_role" name="org_role" required="">
    <option value="A">Administrator</option>
    <option value="M" selected="selected">Member</option>
</select>

If not select2, is there any other jquery library that can help me accomplish this?

I have tried following the Select2's documentation, and believe that if
this way (for templates), we can span an image beside the option's text, then, there must be a way to span a "text description" too under each option. But I dont know how this can be achieved. All I have tried to do untill now is this:

var org_role = function(roles){
      if (!roles.id) {
      return roles.text;
    }
    return $(
    '' + roles.text + '' + '
'
    '' + "some description" + ''
  );
};

$("#id_org_role").select2({
  templateResult: org_role,
});

But this is not working. Also, even if it does, it would display the same description for all the options. But it has to be different obviously.

My Django form inside the template looks like this:

<form method="POST" action="" class="org-member-edit" id='organization_permissions' data-parsley-validate>

{% csrf_token %}

    {% trans "Role" %}

{% render_field org_role_form.org_role class+="form-control" data-parsley-required="true" %}

{{ org_role_form.org_role.errors }}

</form>

in the 5th line above, i.e the render_field org_role_form.org_role in the template tag, the org_role takes up values from the following form:
(note : render_field because I am using Django-tweaks-wideget)

class EditOrganizationMemberForm(SuperUserCheck, forms.Form):

org_role = forms.ChoiceField(choices=ADMIN_CHOICES)

which takes choice fields from another file choices.py like so:

ADMIN_CHOICES = (
         ('A', _('Administrator')),
         ('M', _('Member'))
        )

How can I achieve this? (different descriptions for different options) Please help. I have been stuck at this since hours.

Body:
What about putting the description in an attribute e.g. title?

$(function(){
  $("select").select2({
    templateResult: formatOption
  });

  function formatOption (option) {
    var $option = $(
      '<div><strong>' + option.text + '</strong></div><div>' + option.title + '</div>'
    );
    return $option;
  };
});

<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/select2.full.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />

<select style="width:200px">
  <option value="optionA" title="Description for A">option A</option>
  <option value="optionB" title="Description for B">option B</option>
</select>

ContentLicense: CC BY-SA 4.0


问:
AngularJS 1.6.1, TypeScript, UI Bootstrap Modal: Why are my global variables stored in session storage being updated by the modal?
Please help a newb out. I'm using ngStorage to store some global variables:

```<code>//Global Controller
saveGlobalSettings = () => {
        this.$sessionStorage.QuoteTimes = this.quoteTimes;
        this.$sessionStorage.QuoteTypes = this.quoteTypes;
    };
</code>```

I'm using another method in another controller to create objects that use some of the global variables as properties:

```<code>// Create Controller
addChannel = (channel) => {
        channel.QuotingChannelType = channel.QuotingChannelId;
        console.log(this.$sessionStorage.QuoteTimes);
        channel.QuoteTypes = this.$sessionStorage.QuoteTypes;
        channel.QuoteTimes = this.$sessionStorage.QuoteTimes;
        if (!this.myChannels) { this.myChannels = []; }
        this.myChannels.push(channel);
    };
</code>```

I'm then using ng-repeat to display the objects in myChannels in the browser. When clicked, I'm passing the object to an openDialog() method:

```<code> openPreferencesDialog = (channel) => {
        var options: ng.ui.bootstrap.IModalSettings = {
            templateUrl: 'app/form/templates/editChannelPreferences.html',
            controller: 'EditDialogController',
            controllerAs: '$ctrl',
            resolve: {
                channel: () => channel
            }
        };
        this.$uibModal.open(options).result
            .then(updatedChannel => console.log(updatedChannel));
    };
</code>```

The dialog opens as expected, but when I make changes, it is updating the QuoteTimes and QuoteTypes arrays in $sessionStorage (seen from the console.log in addChannel). So each new object created has the QuoteTimes and QuoteTypes of the last object I edited. I am completely stumped. My best guess is it's some kind of scope chain problem? Any idea what I'm doing wrong?

UPDATE: I was able to get it working as expected by using JSON.parse(JSON.stringify(obj)); as follows:

```<code>openPreferencesDialog = (obj, index) => {
        var channel = JSON.parse(JSON.stringify(obj));
        var options: ng.ui.bootstrap.IModalSettings = {
            templateUrl: 'app/form/templates/editChannelPreferences.html',
            controller: 'EditDialogController',
            controllerAs: '$ctrl',
            resolve: {
                channel: () => channel
            }
        };
        this.$uibModal.open(options).result
            .then(updatedChannel =>
            {
                console.log(updatedChannel);
                this.$sessionStorage.myChannels[index].QuoteTimes = updatedChannel.QuoteTimes;
                this.$sessionStorage.myChannels[index].QuoteTypes = updatedChannel.QuoteTypes;
                console.log(this.$sessionStorage.myChannels)
            });
    };
</code>```

Can anyone explain why this works?

答: If quote... members of channel object are not primitive type it's normal behaviour. Because they are reference type that both last edited channel object and $sessionstorage have same references to them in memory.</p>

Body:
Please help a newb out. I'm using ngStorage to store some global variables:

//Global Controller
saveGlobalSettings = () => {
        this.$sessionStorage.QuoteTimes = this.quoteTimes;
        this.$sessionStorage.QuoteTypes = this.quoteTypes;
    };

I'm using another method in another controller to create objects that use some of the global variables as properties:

// Create Controller
addChannel = (channel) => {
        channel.QuotingChannelType = channel.QuotingChannelId;
        console.log(this.$sessionStorage.QuoteTimes);
        channel.QuoteTypes = this.$sessionStorage.QuoteTypes;
        channel.QuoteTimes = this.$sessionStorage.QuoteTimes;
        if (!this.myChannels) { this.myChannels = []; }
        this.myChannels.push(channel);
    };

I'm then using ng-repeat to display the objects in myChannels in the browser. When clicked, I'm passing the object to an openDialog() method:

 openPreferencesDialog = (channel) => {
        var options: ng.ui.bootstrap.IModalSettings = {
            templateUrl: 'app/form/templates/editChannelPreferences.html',
            controller: 'EditDialogController',
            controllerAs: '$ctrl',
            resolve: {
                channel: () => channel
            }
        };
        this.$uibModal.open(options).result
            .then(updatedChannel => console.log(updatedChannel));
    };

The dialog opens as expected, but when I make changes, it is updating the QuoteTimes and QuoteTypes arrays in $sessionStorage (seen from the console.log in addChannel). So each new object created has the QuoteTimes and QuoteTypes of the last object I edited. I am completely stumped. My best guess is it's some kind of scope chain problem? Any idea what I'm doing wrong?

UPDATE: I was able to get it working as expected by using JSON.parse(JSON.stringify(obj)); as follows:

openPreferencesDialog = (obj, index) => {
        var channel = JSON.parse(JSON.stringify(obj));
        var options: ng.ui.bootstrap.IModalSettings = {
            templateUrl: 'app/form/templates/editChannelPreferences.html',
            controller: 'EditDialogController',
            controllerAs: '$ctrl',
            resolve: {
                channel: () => channel
            }
        };
        this.$uibModal.open(options).result
            .then(updatedChannel =>
            {
                console.log(updatedChannel);
                this.$sessionStorage.myChannels[index].QuoteTimes = updatedChannel.QuoteTimes;
                this.$sessionStorage.myChannels[index].QuoteTypes = updatedChannel.QuoteTypes;
                console.log(this.$sessionStorage.myChannels)
            });
    };

Can anyone explain why this works?


问:
Spark 2.0 - Flatten JSON file to a CSV
I'm trying to convert a JSON file into a flattened CSV file. Here's what I tried:

OUTPUT:

I don't know how to correctly manipulate the qualify columns in spark sql and return the correct values.

```<code>from pyspark.sql.functions import *

dummy = spark.read.json('dummy-3.json')
qualify = dummy.select("user_id", "rec_id", "uut", "hash", explode("qualify").alias("qualify"))
qualify.show()

+-------+------+---+------+--------------------+
|user_id|rec_id|uut|  hash|             qualify|
+-------+------+---+------+--------------------+
|      1|     2| 12|abc123|[cab321,test-1,of...|
|      1|     2| 12|abc123|[cab123,test-2,of...|
+-------+------+---+------+--------------------+
</code>```

JSON example:

```<code>{
  "user_id": 1,
  "rec_id": 2,
  "uut": 12,
  "hash": "abc123"
  "qualify":[{
    "offer": "offer-1",
    "name": "test-1",
    "hash": "cab321",
    "qualified": false"
    "rules": [{
      "name": "name of rule 1",
      "approved": true,
      "details": {}
    },
    {
    "name": "name of rule 2",
    "approved": false,
    "details": {}
    }]
  },{
    "offer": "offer-2",
    "name": "test-2",
    "hash": "cab123",
    "qualified": true
    "rules": [{
      "name": "name of rule 1",
      "approved": true,
      "details": {}
    },
    {
    "name": "name of rule 2",
    "approved": false,
    "details": {}
    }]
  }
}
</code>```

JSON SCHEMA:

```<code>root
 |-- hash: string (nullable = true)
 |-- qualify: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- hash: string (nullable = true)
 |    |    |-- name: string (nullable = true)
 |    |    |-- offer: string (nullable = true)
 |    |    |-- qualified: boolean (nullable = true)
 |    |    |-- rules: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- approved: boolean (nullable = true)
 |    |    |    |    |-- name: string (nullable = true)
 |-- rec_id: long (nullable = true)
 |-- user_id: long (nullable = true)
 |-- uut: long (nullable = true)
</code>```

I tried transforming the DataFrame into a RDD and create a map function to return the values, but I think it's not a good approach. Am I wrong?

Has anybody have worked on a similar issue ?

Thanks for any help.

答:
SOLUTION

I used the explode function, but creating a new dataframe for every explode.

```<code>df2 = df.select(col("userId").alias("user_id"),\
                col("recommendationId").alias("rec_id"),\
                col("utsId").alias("uts_id"),\
                col("gitHash").alias("git_hash"), \
                from_unixtime(col("createdAt")).alias("created"), \
                explode("qualifyResults").alias("qualify"))

df3 = df2.select("user_id",\
                 "rec_id",\
                 "uts_id",\
                 "git_hash",\
                 "created",\
                 col("qualify.offerId").alias("qualify_offer"),\
                 col("qualify.qualifyName").alias("qualify_name"),\
                 col("qualify.qualifyHash").alias("qualify_hash"),\
                 col("qualify.qualified").alias("qualify_qualified"),\
                 explode("qualify.rulesResult").alias("rules"))

#removi os details ate
df4 = df3.select("user_id",\
                 "rec_id",\
                 "uts_id",\
                 "git_hash",\
                 "created",\
                 "qualify_offer",\
                 "qualify_name",\
                 "qualify_hash",\
                 "qualify_qualified",\
                 col("rules.name").alias("rule_name"),\
                 col("rules.approved").alias("rule_approved"),\
                 col("rules.details").alias("rule_details"))
</code>```

Using this approach I was able to get the CSV form I wanted.

Title: Spark 2.0 - Flatten JSON file to a CSV

Body:
I'm trying to convert a JSON file into a flattened CSV file. Here's what I tried:

OUTPUT:

I don't know how to correctly manipulate the qualify columns in spark sql and return the correct values.

from pyspark.sql.functions import *

dummy = spark.read.json('dummy-3.json')
qualify = dummy.select("user_id", "rec_id", "uut", "hash", explode("qualify").alias("qualify"))
qualify.show()

+-------+------+---+------+--------------------+
|user_id|rec_id|uut|  hash|             qualify|
+-------+------+---+------+--------------------+
|      1|     2| 12|abc123|[cab321,test-1,of...|
|      1|     2| 12|abc123|[cab123,test-2,of...|
+-------+------+---+------+--------------------+

JSON example:

{
  "user_id": 1,
  "rec_id": 2,
  "uut": 12,
  "hash": "abc123"
  "qualify":[{
    "offer": "offer-1",
    "name": "test-1",
    "hash": "cab321",
    "qualified": false"
    "rules": [{
      "name": "name of rule 1",
      "approved": true,
      "details": {}
    },
    {
    "name": "name of rule 2",
    "approved": false,
    "details": {}
    }]
  },{
    "offer": "offer-2",
    "name": "test-2",
    "hash": "cab123",
    "qualified": true
    "rules": [{
      "name": "name of rule 1",
      "approved": true,
      "details": {}
    },
    {
    "name": "name of rule 2",
    "approved": false,
    "details": {}
    }]
  }
}

JSON SCHEMA:

root
 |-- hash: string (nullable = true)
 |-- qualify: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- hash: string (nullable = true)
 |    |    |-- name: string (nullable = true)
 |    |    |-- offer: string (nullable = true)
 |    |    |-- qualified: boolean (nullable = true)
 |    |    |-- rules: array (nullable = true)
 |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |-- approved: boolean (nullable = true)
 |    |    |    |    |-- name: string (nullable = true)
 |-- rec_id: long (nullable = true)
 |-- user_id: long (nullable = true)
 |-- uut: long (nullable = true)

I tried transforming the DataFrame into a RDD and create a map function to return the values, but I think it's not a good approach. Am I wrong?

Has anybody have worked on a similar issue ?

Thanks for any help.

Body:
SOLUTION

I used the explode function, but creating a new dataframe for every explode.

df2 = df.select(col("userId").alias("user_id"),\
                col("recommendationId").alias("rec_id"),\
                col("utsId").alias("uts_id"),\
                col("gitHash").alias("git_hash"), \
                from_unixtime(col("createdAt")).alias("created"), \
                explode("qualifyResults").alias("qualify"))

df3 = df2.select("user_id",\
                 "rec_id",\
                 "uts_id",\
                 "git_hash",\
                 "created",\
                 col("qualify.offerId").alias("qualify_offer"),\
                 col("qualify.qualifyName").alias("qualify_name"),\
                 col("qualify.qualifyHash").alias("qualify_hash"),\
                 col("qualify.qualified").alias("qualify_qualified"),\
                 explode("qualify.rulesResult").alias("rules"))

#removi os details ate
df4 = df3.select("user_id",\
                 "rec_id",\
                 "uts_id",\
                 "git_hash",\
                 "created",\
                 "qualify_offer",\
                 "qualify_name",\
                 "qualify_hash",\
                 "qualify_qualified",\
                 col("rules.name").alias("rule_name"),\
                 col("rules.approved").alias("rule_approved"),\
                 col("rules.details").alias("rule_details"))

Using this approach I was able to get the CSV form I wanted.


问:
How to make an unordered list responsive that has icons to the right
I have a list that I have added arrows to the right. I need to make it responsive. But as the browser resizes, the arrows wrap to the next line and the text overlaps other text. This in intended to have paragraphs that will be hidden or displayed based on the list that is selected, but I have not added that code yet since I cant seem to get the list to work for responsive. I have also tried placing a div around the list elements and adding a separate div within the list tag for the arrow, but that didn't work. I also tried mading the unordered list a display of table and the list a display of table cell, but I couldn't get that to work either. I'm not sure what I am doing wrong in any case. There is only one break point for reponsive, and that is 960. Thanks to anyone who can help!!

HTML:

```<code><div class="col-left">
    <div class="line-left"></div>
    <ul class="faqs">
        <li class="sel"><a href="#">What is a notification?</a>
            <p class="faq">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat. </p>

        </li>
        <li><a href="#">How do I know if I’m eligible for notifications?</a>
        <p class="faq">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat. </p>
        </li>
        <li><a href="#">Will I see all notifications?</a>
        <p class="faq">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat. </p>
        </li>
    </ul>
</div>

<div class="col-right">
    <div class="line-right"></div>
    <ul class="faqs">
        <li><a href="#">How often are notifications sent?</a>
        <p class="faq">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat. </p>
        </li>
        <li><a href="#">How do I receive notifications?</a>
        <p class="faq">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat. </p>
        </li>
        <li><a href="#">What will I actually see in the notifications?</a>
        <p class="faq">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat. </p>
        </li>
    </ul>
    </div>
</code>```

CSS:

```<code>    ul.faqs {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

li {
    display: block;
    width: 470px;
    height:auto;
    height: 56px;
    line-height:56px;
    border-bottom: 1px solid #d8d8d8;
}
li a {
    display: block;
    font-family: "helvetica-75-bold";
    font-size:16px;
    color:343366;
    text-decoration: none;
}

li a:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat.svg) no-repeat;
    float: right;
    position: relative;
    top: 19px;
}

li a:hover:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat-hov.svg) no-repeat;
    float: right;
    position: relative;
    top: 19px;
}

li.sel {
    height: auto;
}

li.sel p {
    margin-top: -5px;
    line-height: 19px;
    margin-bottom: 20px;
    color: #595959;
    visibility: visible;
}

p.faq {
    visibility: hidden;
}

li.sel a:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat.svg) no-repeat;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    -ms-transform: rotate(-180deg);
    -o-transform: rotate(-180deg);
    transform: rotate(-180deg);
    margin-right:20px;

}

li.sel a:hover:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat-hov.svg) no-repeat;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    -ms-transform: rotate(-180deg);
    -o-transform: rotate(-180deg);
    transform: rotate(-180deg);
    margin-right:20px;
}

@media (max-width:960px){

    .faqs-title {
    padding-left: 30px;
    padding-bottom: 35px;
}

    .content-faqs {
    width: 100%;
    margin:0 auto;
    padding-left:30px;
    padding-right:30px;
    height: 500px;
}

.col-left {
    width: 100%;
    float:none;
    margin-right: 30px;
}

.col-right {
    width: 100%;
    float:none;
}

    .line-left {
    width: 100%;
    height:1px;
    background-color:#d8d8d8;

}

    .line-right {
    display: none;

}

    li {
    display: block;
    width: 100%;
    height;auto;
    border-bottom: 1px solid #d8d8d8;
}

}
</code>```

答:
If you use display: none | block for toggling visibility, the non-selected paragraphs will collapse. Also, I floated the left column, and gave the right column a 50% left margin when the browser window is larger than your media query. </p>

```<code>ul.faqs {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

li {
    display: block;
    width: 470px;
    height:auto;
    height: 56px;
    line-height:56px;
    border-bottom: 1px solid #d8d8d8;
}
li a {
    display: block;
    font-family: "helvetica-75-bold";
    font-size:16px;
    color:343366;
    text-decoration: none;
}

li a:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat.svg) no-repeat;
    float: right;
    position: relative;
    top: 19px;
}

li a:hover:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat.svg) no-repeat;
    float: right;
    position: relative;
    top: 19px;
}

li.sel {
    height: auto;
}

li.sel p {
    margin-top: -5px;
    line-height: 19px;
    margin-bottom: 20px;
    color: #595959;
    display: block;
    /** visibility: visible; **/
}

p.faq {
    display: none;
    /** visibility: hidden; **/
}

li.sel a:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat.svg) no-repeat;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    -ms-transform: rotate(-180deg);
    -o-transform: rotate(-180deg);
    transform: rotate(-180deg);
    margin-right:20px;

}

li.sel a:hover:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url('ddcarat.png') no-repeat;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    -ms-transform: rotate(-180deg);
    -o-transform: rotate(-180deg);
    transform: rotate(-180deg);
    margin-right:20px;
}

.col-left{
    float:left;
}

.col-right{
    margin-left: 50%;
}

@media (max-width:960px){

.faqs-title {
    padding-left: 30px;
    padding-bottom: 35px;
}

.content-faqs {
    width: 100%;
    margin:0 auto;
    padding-left:30px;
    padding-right:30px;
    height: 500px;
}

.col-left {
    width: 100%;
    float:none;
    margin-right: 30px;
}

.col-right {
    width: 100%;
    float:none;
    margin-left: 0;
}

    .line-left {
    width: 100%;
    height:1px;
    background-color:#d8d8d8;

}

    .line-right {
    display: none;

}

    li {
    display: block;
    width: 100%;
    height: auto; /** typo: had semi colon **/
    border-bottom: 1px solid #d8d8d8;
}

}
</code>```

Body:
I have a list that I have added arrows to the right. I need to make it responsive. But as the browser resizes, the arrows wrap to the next line and the text overlaps other text. This in intended to have paragraphs that will be hidden or displayed based on the list that is selected, but I have not added that code yet since I cant seem to get the list to work for responsive. I have also tried placing a div around the list elements and adding a separate div within the list tag for the arrow, but that didn't work. I also tried mading the unordered list a display of table and the list a display of table cell, but I couldn't get that to work either. I'm not sure what I am doing wrong in any case. There is only one break point for reponsive, and that is 960. Thanks to anyone who can help!!

HTML:

What is a notification?

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat.

How do I know if I’m eligible for notifications?

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat.

Will I see all notifications?

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat.

How often are notifications sent?

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat.

How do I receive notifications?

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat.

What will I actually see in the notifications?

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat.

CSS:

    ul.faqs {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

li {
    display: block;
    width: 470px;
    height:auto;
    height: 56px;
    line-height:56px;
    border-bottom: 1px solid #d8d8d8;
}
li a {
    display: block;
    font-family: "helvetica-75-bold";
    font-size:16px;
    color:343366;
    text-decoration: none;
}

li a:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat.svg) no-repeat;
    float: right;
    position: relative;
    top: 19px;
}

li a:hover:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat-hov.svg) no-repeat;
    float: right;
    position: relative;
    top: 19px;
}

li.sel {
    height: auto;
}

li.sel p {
    margin-top: -5px;
    line-height: 19px;
    margin-bottom: 20px;
    color: #595959;
    visibility: visible;
}

p.faq {
    visibility: hidden;
}

li.sel a:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat.svg) no-repeat;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    -ms-transform: rotate(-180deg);
    -o-transform: rotate(-180deg);
    transform: rotate(-180deg);
    margin-right:20px;

}

li.sel a:hover:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat-hov.svg) no-repeat;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    -ms-transform: rotate(-180deg);
    -o-transform: rotate(-180deg);
    transform: rotate(-180deg);
    margin-right:20px;
}

@media (max-width:960px){

    .faqs-title {
    padding-left: 30px;
    padding-bottom: 35px;
}

    .content-faqs {
    width: 100%;
    margin:0 auto;
    padding-left:30px;
    padding-right:30px;
    height: 500px;
}

.col-left {
    width: 100%;
    float:none;
    margin-right: 30px;
}

.col-right {
    width: 100%;
    float:none;
}

    .line-left {
    width: 100%;
    height:1px;
    background-color:#d8d8d8;

}

    .line-right {
    display: none;

}

    li {
    display: block;
    width: 100%;
    height;auto;
    border-bottom: 1px solid #d8d8d8;
}

}

Body:
If you use display: none | block for toggling visibility, the non-selected paragraphs will collapse. Also, I floated the left column, and gave the right column a 50% left margin when the browser window is larger than your media query.

ul.faqs {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

li {
    display: block;
    width: 470px;
    height:auto;
    height: 56px;
    line-height:56px;
    border-bottom: 1px solid #d8d8d8;
}
li a {
    display: block;
    font-family: "helvetica-75-bold";
    font-size:16px;
    color:343366;
    text-decoration: none;
}

li a:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat.svg) no-repeat;
    float: right;
    position: relative;
    top: 19px;
}

li a:hover:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat.svg) no-repeat;
    float: right;
    position: relative;
    top: 19px;
}

li.sel {
    height: auto;
}

li.sel p {
    margin-top: -5px;
    line-height: 19px;
    margin-bottom: 20px;
    color: #595959;
    display: block;
    /** visibility: visible; **/
}

p.faq {
    display: none;
    /** visibility: hidden; **/
}

li.sel a:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url(../images/../images/DropDownCarat.svg) no-repeat;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    -ms-transform: rotate(-180deg);
    -o-transform: rotate(-180deg);
    transform: rotate(-180deg);
    margin-right:20px;

}

li.sel a:hover:after {
    content: "";
    display: inline-block;
    width:41px;
    height:22px;
    background: url('ddcarat.png') no-repeat;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    -ms-transform: rotate(-180deg);
    -o-transform: rotate(-180deg);
    transform: rotate(-180deg);
    margin-right:20px;
}

.col-left{
    float:left;
}

.col-right{
    margin-left: 50%;
}

@media (max-width:960px){

.faqs-title {
    padding-left: 30px;
    padding-bottom: 35px;
}

.content-faqs {
    width: 100%;
    margin:0 auto;
    padding-left:30px;
    padding-right:30px;
    height: 500px;
}

.col-left {
    width: 100%;
    float:none;
    margin-right: 30px;
}

.col-right {
    width: 100%;
    float:none;
    margin-left: 0;
}

    .line-left {
    width: 100%;
    height:1px;
    background-color:#d8d8d8;

}

    .line-right {
    display: none;

}

    li {
    display: block;
    width: 100%;
    height: auto; /** typo: had semi colon **/
    border-bottom: 1px solid #d8d8d8;
}

}


问:
How do I get the total time it takes for a command to run?
I know you can get the compile time of each individual function using something like this:

```<code>xcodebuild -workspace App.xcworkspace -scheme App clean build OTHER_SWIFT_FLAGS="-Xfrontend -debug-time-function-bodies" | grep .[0-9]ms | grep -v ^0.[0-9]ms | sort -nr > culprits.txt
</code>```

or this

```<code>defaults write com.apple.dt.Xcode ShowBuildOperationDuration -bool YES
</code>```

but how can I get the total build time printed out in command line?

答:
I guess the easiest way would be running something like this:</p>

```<code>#!/bin/sh

COMPILE_START=`date`
# your compile commands
COMPILE_END=`date`
printf "%s\n" $(( $(date -d "$COMPILE_END" "+%s") \
                - $(date -d "$COMPILE_START" "+%s") ))
</code>```

Body:
I know you can get the compile time of each individual function using something like this:

xcodebuild -workspace App.xcworkspace -scheme App clean build OTHER_SWIFT_FLAGS="-Xfrontend -debug-time-function-bodies" | grep .[0-9]ms | grep -v ^0.[0-9]ms | sort -nr > culprits.txt

or this

defaults write com.apple.dt.Xcode ShowBuildOperationDuration -bool YES

but how can I get the total build time printed out in command line?

Body:
I guess the easiest way would be running something like this:

#!/bin/sh

COMPILE_START=`date`
# your compile commands
COMPILE_END=`date`
printf "%s\n" $(( $(date -d "$COMPILE_END" "+%s") \
                - $(date -d "$COMPILE_START" "+%s") ))


问:
Application of 2D ArrayList in Java
I want to create a list of usernames, and then each username would correlate to a password. The purpose is when a username is submitted, I would iterate through the username list to look for a match. If matched, I would then ask for the password of that username. I thought of using a 2D ArrayList of String, but do not think it's possible to ask for a username and then check for the password that way. Would the only possible (and not too advanced) way to do this be to create 2 separate ArrayList? If so, how do I make sure that for each name from username list, there is only one correct password in the password list?

Note: I am just recently introduced to Java.

答:
If by chance you do want to use a 2D ArrayList then this is one way you can do it:</p>

```<code>List<List<String>> users = new ArrayList<>();

// Fill the 2D List
users.add(new ArrayList<>()); users.get(0).add("Joe Blow"); users.get(0).add("password1");
users.add(new ArrayList<>()); users.get(1).add("John Doe"); users.get(1).add("password2");
users.add(new ArrayList<>()); users.get(2).add("Freddy Flint"); users.get(2).add("password3");
users.add(new ArrayList<>()); users.get(3).add("Tracey Johnson"); users.get(3).add("password4");
users.add(new ArrayList<>()); users.get(4).add("Mike Tyson"); users.get(4).add("I bit off his ear? :D");

// Provide a name that might be in the list
// User Name is case sensative.
String suppliedUserName = "Mike Tyson";

// Iterate throught the list of User Names & Passwords...
String successMsg = "Can't Find User Named: " + suppliedUserName;
String password;
for (int i = 0; i < users.size(); i++) {
    if (users.get(i).get(0).equals(suppliedUserName)) {
        password = users.get(i).get(1);
        successMsg = "Hey..." + suppliedUserName + "'s Secret Password is: " + password;
        break; //found it so stop the iteration
    }
}

// Display a Success or Fail message.
System.out.println(successMsg);
</code>```

Title: Application of 2D ArrayList in Java

Body:
If by chance you do want to use a 2D ArrayList then this is one way you can do it:

List<List<String>> users = new ArrayList<>();

// Fill the 2D List
users.add(new ArrayList<>()); users.get(0).add("Joe Blow"); users.get(0).add("password1");
users.add(new ArrayList<>()); users.get(1).add("John Doe"); users.get(1).add("password2");
users.add(new ArrayList<>()); users.get(2).add("Freddy Flint"); users.get(2).add("password3");
users.add(new ArrayList<>()); users.get(3).add("Tracey Johnson"); users.get(3).add("password4");
users.add(new ArrayList<>()); users.get(4).add("Mike Tyson"); users.get(4).add("I bit off his ear? :D");

// Provide a name that might be in the list
// User Name is case sensative.
String suppliedUserName = "Mike Tyson";

// Iterate throught the list of User Names & Passwords...
String successMsg = "Can't Find User Named: " + suppliedUserName;
String password;
for (int i = 0; i < users.size(); i++) {
    if (users.get(i).get(0).equals(suppliedUserName)) {
        password = users.get(i).get(1);
        successMsg = "Hey..." + suppliedUserName + "'s Secret Password is: " + password;
        break; //found it so stop the iteration
    }
}

// Display a Success or Fail message.
System.out.println(successMsg);


问:
Does Freemarker honor MethodDescriptors?
(Background: I've been working with Java beans for somewhere around 18 years off and on; I've been working with Freemarker for a week or two.  :-))

I have a hand-tooled BeanInfo that represents the properties of a class that does not follow the "ordinary" (but obviously arbitrary) get/set-style of method naming.

Semantically, for a Java bean property named x, you would call a method named, simply, x() on this class.

So my BeanInfo implementation (which Freemarker is finding and loading) implements this pattern.  Fine.

The class in question actually has a method called target(), which returns a certain object (let's call it Target here), and which is represented by a PropertyDescriptor whose name is target and whose readMethod is that method.  Fine.

In my Freemarker template, if I do this:

```<code>theObject.target
</code>```

...I get an error saying that target, effectively is a method, not a property, suggesting that my PropertyDescriptor, though technically findable, is not being consulted.  If I change this instead to:

```<code>theObject.target()
</code>```

...then everything works.  The target() method, in other words, seems to be being seen by Freemarker as a method—it's like Freemarker is not "getting through" to the PropertyDescriptor which would otherwise tell it that this is actually the "read method" of a Java bean property.

I tried editing my BeanInfo to return an empty list of MethodDescriptors, thinking that perhaps that was the problem: if you return null from a particular method in BeanInfo then the Introspector does low-level introspection for that thing.  And null is the default.  So if you return null from BeanInfo#getMethodDescriptors(), Introspector will presumably find all the public methods in your class and create MethodDescriptors for them.

Anyway, so I returned an empty list of MethodDescriptors, hoping that I could force Freemarker into not "seeing" target as a method, but as a Java beans property ("falling through" to my BeanInfo's PropertyDescriptor as mentioned above).  This didn't work.

In short, how can I make my:

```<code>someObject.target
</code>```

...incantation access my property descriptor, not the target() method?

答: As FreeMarker uses java.beans.Introspector to discover bean properties and actions, it does honor the content of BeanInfo. Problem is, in your case that will return PropertyDescriptor-s and MethodDescriptor-s with clashing names. As the template language doesn't have a separate namespace for properties and methods, one has to shadow the other. By default, methods shadow  properties (which is not very practical nowadays, as fluent API-s often have methods like Foo foo() instead of Foo getFoo()). You can change that by setting the methodAppearanceFineTuner property of the DefaultObjectWrapperBuilder to a MethodAppearanceFineTurner object that simply always calls decision.setMethodShadowsProperty(false).

Body:
(Background: I've been working with Java beans for somewhere around 18 years off and on; I've been working with Freemarker for a week or two.  :-))

I have a hand-tooled BeanInfo that represents the properties of a class that does not follow the "ordinary" (but obviously arbitrary) get/set-style of method naming.

Semantically, for a Java bean property named x, you would call a method named, simply, x() on this class.

So my BeanInfo implementation (which Freemarker is finding and loading) implements this pattern.  Fine.

The class in question actually has a method called target(), which returns a certain object (let's call it Target here), and which is represented by a PropertyDescriptor whose name is target and whose readMethod is that method.  Fine.

In my Freemarker template, if I do this:

theObject.target

...I get an error saying that target, effectively is a method, not a property, suggesting that my PropertyDescriptor, though technically findable, is not being consulted.  If I change this instead to:

theObject.target()

...then everything works.  The target() method, in other words, seems to be being seen by Freemarker as a method—it's like Freemarker is not "getting through" to the PropertyDescriptor which would otherwise tell it that this is actually the "read method" of a Java bean property.

I tried editing my BeanInfo to return an empty list of MethodDescriptors, thinking that perhaps that was the problem: if you return null from a particular method in BeanInfo then the Introspector does low-level introspection for that thing.  And null is the default.  So if you return null from BeanInfo#getMethodDescriptors(), Introspector will presumably find all the public methods in your class and create MethodDescriptors for them.

Anyway, so I returned an empty list of MethodDescriptors, hoping that I could force Freemarker into not "seeing" target as a method, but as a Java beans property ("falling through" to my BeanInfo's PropertyDescriptor as mentioned above).  This didn't work.

In short, how can I make my:

someObject.target

...incantation access my property descriptor, not the target() method?


问:
xuggle-xuggler 5.4 NullPointerException when encoding audio
Today I was working with the Xuggler library and I tried capturing my screen which worked flawless. But I also wanted to add audio from my microphone to the video file I captured. This was not as easy as I had expected, and now I'm stuck with this strange NullPointerException.

This is my code (abbreviated):

```<code>AudioFormat format = new AudioFormat(8000.0F, 16, 1, true, false);
writer.addAudioStream(1, 0, 1, (int) format.getSampleRate());
TargetDataLine line = getTargetDataLineForRecord(format);
final int frameSizeInBytes = format.getFrameSize();
final int bufferLengthInFrames = line.getBufferSize() / 8;
final int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
final byte[] buf = new byte[bufferLengthInBytes];
final long startTime = System.nanoTime();
...
while (recording) {
    int numBytesRead = 0;
    numBytesRead = line.read(buf, 0, bufferLengthInBytes);
    int numSamplesRead = numBytesRead / 2;
    short[] audioSamples = new short[numSamplesRead];
    if (format.isBigEndian()) {
        for (int i = 0; i < numSamplesRead; i++) {
            audioSamples[i] = (short) ((buf[2 * i] << 8) | buf[2 * i + 1]);
        }
    } else {
        for (int i = 0; i < numSamplesRead; i++) {
            audioSamples[i] = (short) ((buf[2 * i + 1] << 8) | buf[2 * i]);
        }
    }
    writer.encodeAudio(1, audioSamples, System.nanoTime() - startTime, TimeUnit.NANOSECONDS); // CaptureScreen.java:118
    }
writer.close();
</code>```

And here is the NullPointerException:

```<code>java.lang.NullPointerException
    at com.xuggle.mediatool.MediaWriter.encodeAudio(MediaWriter.java:923)
    at exe.media.CaptureScreen.captureScreen(CaptureScreen.java:118)
    at exe.media.CaptureScreen.main(CaptureScreen.java:43)
</code>```

The problem I'm having is at this line (118):

```<code>writer.encodeAudio(1, audioSamples, System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
</code>```

For some reason when I try to encode the audio samples, xuggle throws a NullPointerException, I'm not sure if this is a bug or just me doing something stupid but I am unable to solve it anyway.

For better understanding I have posted all the code on pastebin and this includes code for capturing my screen and also this code where I try to record the audio.

These are the jars I have included:

commons-cli-1.2.jar

logback-classic-1.1.2.jar

logback-core-1.1.2.jar

xuggle-xuggler-arch-x86_x64-w64-mingw32.jar*

xuggle-xuggler-noarch-5.4.jar*

(The '*' means I didn't download the jar from it's primary location.

Thanks in advance <s>and remember ANY helpful answer will be rewarded the 50 rep bounty</s>!

答:
I assume that you have line.open(format); and line.start(); somewhere?

You may need to make sure that you have audiosamples: if (audioSamples.length > 0) writer.encodeAudio ...

Also, you may want to add slf4j-api-1.6.4.jar and slf4j-simple-1.6.4.jar to get more details on the errors from Xuggler.

Body:
Today I was working with the Xuggler library and I tried capturing my screen which worked flawless. But I also wanted to add audio from my microphone to the video file I captured. This was not as easy as I had expected, and now I'm stuck with this strange NullPointerException.

This is my code (abbreviated):

AudioFormat format = new AudioFormat(8000.0F, 16, 1, true, false);
writer.addAudioStream(1, 0, 1, (int) format.getSampleRate());
TargetDataLine line = getTargetDataLineForRecord(format);
final int frameSizeInBytes = format.getFrameSize();
final int bufferLengthInFrames = line.getBufferSize() / 8;
final int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
final byte[] buf = new byte[bufferLengthInBytes];
final long startTime = System.nanoTime();
...
while (recording) {
    int numBytesRead = 0;
    numBytesRead = line.read(buf, 0, bufferLengthInBytes);
    int numSamplesRead = numBytesRead / 2;
    short[] audioSamples = new short[numSamplesRead];
    if (format.isBigEndian()) {
        for (int i = 0; i < numSamplesRead; i++) {
            audioSamples[i] = (short) ((buf[2 * i] << 8) | buf[2 * i + 1]);
        }
    } else {
        for (int i = 0; i < numSamplesRead; i++) {
            audioSamples[i] = (short) ((buf[2 * i + 1] << 8) | buf[2 * i]);
        }
    }
    writer.encodeAudio(1, audioSamples, System.nanoTime() - startTime, TimeUnit.NANOSECONDS); // CaptureScreen.java:118
    }
writer.close();

And here is the NullPointerException:

java.lang.NullPointerException
    at com.xuggle.mediatool.MediaWriter.encodeAudio(MediaWriter.java:923)
    at exe.media.CaptureScreen.captureScreen(CaptureScreen.java:118)
    at exe.media.CaptureScreen.main(CaptureScreen.java:43)

The problem I'm having is at this line (118):

writer.encodeAudio(1, audioSamples, System.nanoTime() - startTime, TimeUnit.NANOSECONDS);

For some reason when I try to encode the audio samples, xuggle throws a NullPointerException, I'm not sure if this is a bug or just me doing something stupid but I am unable to solve it anyway.

For better understanding I have posted all the code on pastebin and this includes code for capturing my screen and also this code where I try to record the audio.

These are the jars I have included:

commons-cli-1.2.jar

logback-classic-1.1.2.jar

logback-core-1.1.2.jar

xuggle-xuggler-arch-x86_x64-w64-mingw32.jar*

xuggle-xuggler-noarch-5.4.jar*

(The '*' means I didn't download the jar from it's primary location.

Thanks in advance <s>and remember ANY helpful answer will be rewarded the 50 rep bounty</s>!


问:
Keeping content above the bottom bar on Mobile Safari iOS 8
I'm aware that minimal-ui is no longer supported on iOS8. But, I have some content fixed to the bottom of a webpage.

The page height is set to 100vh to take up the entire viewport. Some of the content at the bottom is displaying below the bottom bar. So, the user must scroll to see that content.

I would like all of the content to be displayed above the bottom bar. What is the best approach to achieve this?

答:
One solution could be to give a little more of padding-bottom to the element with 100vh in order to leave some space to the iphone bottom bar.

Just use this code to target the mobiles with Safari:

```<code>@media screen and (max-width: 767px) {
    _::-webkit-full-page-media, _:future, :root .safari_only {
        padding-bottom: 65px; //resize
    }
}
</code>```

And don't forget to add the .safari_only class to the element you want to target, example:

```<code><div class='safari_only'> This div will have a padding-bottom:65px in a mobile with Safari  </div>
</code>```

One detail: this is gonna affect also the Safari browser in Android devices, but fortunately not many users use Safari on an Android device, anyway if you need it you can use another css rule for overwrite that rule on Android.

Body:
One solution could be to give a little more of padding-bottom to the element with 100vh in order to leave some space to the iphone bottom bar.

Just use this code to target the mobiles with Safari:

@media screen and (max-width: 767px) {
    _::-webkit-full-page-media, _:future, :root .safari_only {
        padding-bottom: 65px; //resize
    }
}

And don't forget to add the .safari_only class to the element you want to target, example:

<div class='safari_only'> This div will have a padding-bottom:65px in a mobile with Safari  </div>

One detail: this is gonna affect also the Safari browser in Android devices, but fortunately not many users use Safari on an Android device, anyway if you need it you can use another css rule for overwrite that rule on Android.


问:
How to get a push notification at a set time? (Swift 3)
I'm making an app that's supposed the user everyday at a set time about the news. It get's the text of the news through a function which calls it from an array. My question is: how do I get my app to call the function and then send me a push notification with the info text every day at, let's say, 4am?

Thanks to everyone for answering! Have a great day!

答:
Here is some code I used before. Not a hundred-percent what you are looking for, but I hope useful for you.

You need to modify it to be sending daily

```<code>import UIKit
import UserNotifications

class ViewController: UIViewController, UNUserNotificationCenterDelegate {
    var isGrantedNotificationAccess:Bool = false
    @IBAction func send10SecNotification(_ sender: UIButton) {
        if isGrantedNotificationAccess {
            //add notification code here

            //Set the content of the notification
            let content = UNMutableNotificationContent()
            content.title = "10 Second Notification Demo"
            content.subtitle = "From MakeAppPie.com"
            content.body = "Notification after 10 seconds - Your pizza is Ready!!"

            //Set the trigger of the notification -- here a timer.
            let trigger = UNTimeIntervalNotificationTrigger(
                timeInterval: 10.0,
                repeats: true)

            //Set the request for the notification from the above
            let request = UNNotificationRequest(
                identifier: "10.second.message",
                content: content,
                trigger: trigger
            )

            //Add the notification to the currnet notification center
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
            self.isGrantedNotificationAccess = granted
        }
    }
}
</code>```

Body:
Here is some code I used before. Not a hundred-percent what you are looking for, but I hope useful for you.

You need to modify it to be sending daily

import UIKit
import UserNotifications

class ViewController: UIViewController, UNUserNotificationCenterDelegate {
    var isGrantedNotificationAccess:Bool = false
    @IBAction func send10SecNotification(_ sender: UIButton) {
        if isGrantedNotificationAccess {
            //add notification code here

            //Set the content of the notification
            let content = UNMutableNotificationContent()
            content.title = "10 Second Notification Demo"
            content.subtitle = "From MakeAppPie.com"
            content.body = "Notification after 10 seconds - Your pizza is Ready!!"

            //Set the trigger of the notification -- here a timer.
            let trigger = UNTimeIntervalNotificationTrigger(
                timeInterval: 10.0,
                repeats: true)

            //Set the request for the notification from the above
            let request = UNNotificationRequest(
                identifier: "10.second.message",
                content: content,
                trigger: trigger
            )

            //Add the notification to the currnet notification center
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
            self.isGrantedNotificationAccess = granted
        }
    }
}


问:
Paper trail controller as meta data does not work. (Ruby 2.3.3, Rails 4.2 and paper_trail 5.2.3)
Following the steps to capture information from the controller as meta data does not work. (Ruby 2.3.3, Rails 4.2 and paper_trail 5.2.3)

model

```<code>has_paper_trail only: [:status]
</code>```

migrate

```<code>class AddHotelToVersions < ActiveRecord::Migration
    def change
        add_reference :versions, :hotel, index: true, foreign_key: true, null: false
        add_column :versions, :ip, :string, null: false
        add_column :versions, :user_agent, :string, null: false
    end
end
</code>```

controller

```<code>def info_for_paper_trail
    { hotel_id: current_user.hotel.id, ip: request.remote_ip, user_agent: request.user_agent }
end
</code>```

答: I solved it upgrading paper trails to 6.0.2</p>

Body:
Following the steps to capture information from the controller as meta data does not work. (Ruby 2.3.3, Rails 4.2 and paper_trail 5.2.3)

model

has_paper_trail only: [:status]

migrate

class AddHotelToVersions < ActiveRecord::Migration
    def change
        add_reference :versions, :hotel, index: true, foreign_key: true, null: false
        add_column :versions, :ip, :string, null: false
        add_column :versions, :user_agent, :string, null: false
    end
end

controller

def info_for_paper_trail
    { hotel_id: current_user.hotel.id, ip: request.remote_ip, user_agent: request.user_agent }
end


问:
HDF file not saving properly with h5py
I'm trying to save a numpy array in a HDF file with h5py as follows:

```<code>with h5py.File("mfcc_aligned.hdf", "w") as aligned_f:
    # do stuff to create two numpy arrays, training_X and training_Y
    print(len(training_X)) # this returns the number of elements I expect in the the numpy arr
    aligned_f.create_dataset("train_X", data=training_X)
    aligned_f.create_dataset("train_Y", data=training_Y)
    # if I add a line here to access the datasets I just created, I see that aligned_f does indeed have two keys train_X and train_Y with the shapes I expect
</code>```

However, when the program ends and I check the file mfcc_aligned.hdf, it's exactly 800 bytes (much smaller than I expect), and there are no keys. I'm at a loss for what's going on here.

Thanks in advance for any insights!

答:
did you try(didn't format in the comments):</p>

```<code>with h5py.File('mfcc_aligned.hdf', 'r') as hf:
    print hf['train_X'][:]
</code>```

Title: HDF file not saving properly with h5py

Body:
I'm trying to save a numpy array in a HDF file with h5py as follows:

with h5py.File("mfcc_aligned.hdf", "w") as aligned_f:
    # do stuff to create two numpy arrays, training_X and training_Y
    print(len(training_X)) # this returns the number of elements I expect in the the numpy arr
    aligned_f.create_dataset("train_X", data=training_X)
    aligned_f.create_dataset("train_Y", data=training_Y)
    # if I add a line here to access the datasets I just created, I see that aligned_f does indeed have two keys train_X and train_Y with the shapes I expect

However, when the program ends and I check the file mfcc_aligned.hdf, it's exactly 800 bytes (much smaller than I expect), and there are no keys. I'm at a loss for what's going on here.

Thanks in advance for any insights!

Body:
did you try(didn't format in the comments):

with h5py.File('mfcc_aligned.hdf', 'r') as hf:
    print hf['train_X'][:]


问:
Malformed JSON using RxJava and retrofit
I want take some data from a JSON, but the gson is giving an error. I want to know how can i solve this?

I'm using dagger2(this part is 100% ok and working) and rxJava(this part is calling always the onError method).

My model:

```<code>@Data
@NoArgsConstructor
public class GradeModel {

//I'm using lombok to generate getters and setters.

    @SerializedName("grade")
    @Expose
    private DecimalFormat grades;

    @SerializedName("grades")
    @Expose
    private GradeModel listGrades;

    private String matter;
    private int fault;

}
</code>```

My JSON:

```<code>grades: [

    {
        "class": "math"
        "grade": 4.5,
        "next_dates":[
            {
                "exam": "03/03/2017",
                "homework": "03/03/2017"
            }

        ]

    }

    {
        "class": "port"
        "grade": 8,
        "next_dates":[
            {
                "exam": "03/05/2017",
                "homework": "03/03/2017"
            }

        ]

    }

]
</code>```

My Response:

```<code>public class GradeResponse {

    @Inject
    Retrofit retrofit;

    @Inject
    MainPresenter mainPresenter;

    public void getGradeRx() {

        MyApplication.getMainComponent().injectIntoGradeResponse(this);// informando ao dagger sobre o uso de um component e a necessidade de injetar dependência

        Subscription getGrade = retrofit
                .create(GradeService.class)
                .getGrade()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(model -> {
                    // transform model
                        return model.getListGrades();
                })
                .subscribe(new Observer<GradeModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "saporra vai me matar ainda");
                    }

                    @Override
                    public void onNext(GradeModel grades) {
                        Log.i(TAG, "caralhoooooo " + grades.getGrades());
                        //mainPresenter.setListGrades(grades);
                    }
                });
    }
}
</code>```

My retrofit:

```<code>@Module
public class RetrofitModule {
    @Provides
    @PerActivity
    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        //gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }
    @Provides
    @PerActivity
    public OkHttpClient provideHttpClient() {
        return new OkHttpClient().newBuilder().build();
    }
    @Provides
    @PerActivity
    public Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                //converts Retrofit response into Observable
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit;
    }
}
</code>```

My Service:

```<code>public interface GradeService {

    @GET("grades_json.json")
    Observable<GradeModel> getGrade();
}
</code>```

The Error:

com.google.gson.stream.MalformedJsonException: Use
  JsonReader.setLenient(true) to accept malformed JSON at line 1 column
  1 path $

答:
1) grades: [ is not part of valid JSON. Remove grades: and leave the [ if you want to parse a JSON array.

Then, your Gson model is wrong. You have "grades" and "grade", not "grade", "next_dates", and "class".

This is also two objects.

```<code>{                    // One Object here
    "class": "math",
    "grade": 4.5,
    "next_dates":[
        {            // Second object here
            "exam": "03/03/2017",
            "homework": "03/03/2017"
        }
    ]
}
</code>```

So, your Java classes would be something like

```<code>public class GradeDate {
    private String exam, homework;
}

public class GradeModel {
    private String class;
    private Double grade;
    private List<GradeDate> nextDates;
}
</code>```

Then, your JSON is still missing some commas to separate the values in the outer array.

Body:
I want take some data from a JSON, but the gson is giving an error. I want to know how can i solve this?

I'm using dagger2(this part is 100% ok and working) and rxJava(this part is calling always the onError method).

My model:

@Data
@NoArgsConstructor
public class GradeModel {

//I'm using lombok to generate getters and setters.

    @SerializedName("grade")
    @Expose
    private DecimalFormat grades;

    @SerializedName("grades")
    @Expose
    private GradeModel listGrades;

    private String matter;
    private int fault;

}

My JSON:

grades: [

    {
        "class": "math"
        "grade": 4.5,
        "next_dates":[
            {
                "exam": "03/03/2017",
                "homework": "03/03/2017"
            }

        ]

    }

    {
        "class": "port"
        "grade": 8,
        "next_dates":[
            {
                "exam": "03/05/2017",
                "homework": "03/03/2017"
            }

        ]

    }

]

My Response:

public class GradeResponse {

    @Inject
    Retrofit retrofit;

    @Inject
    MainPresenter mainPresenter;

    public void getGradeRx() {

        MyApplication.getMainComponent().injectIntoGradeResponse(this);// informando ao dagger sobre o uso de um component e a necessidade de injetar dependência

        Subscription getGrade = retrofit
                .create(GradeService.class)
                .getGrade()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(model -> {
                    // transform model
                        return model.getListGrades();
                })
                .subscribe(new Observer<GradeModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "saporra vai me matar ainda");
                    }

                    @Override
                    public void onNext(GradeModel grades) {
                        Log.i(TAG, "caralhoooooo " + grades.getGrades());
                        //mainPresenter.setListGrades(grades);
                    }
                });
    }
}

My retrofit:

@Module
public class RetrofitModule {
    @Provides
    @PerActivity
    Gson provideGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        //gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return gsonBuilder.create();
    }
    @Provides
    @PerActivity
    public OkHttpClient provideHttpClient() {
        return new OkHttpClient().newBuilder().build();
    }
    @Provides
    @PerActivity
    public Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                //converts Retrofit response into Observable
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit;
    }
}

My Service:

public interface GradeService {

    @GET("grades_json.json")
    Observable<GradeModel> getGrade();
}

The Error:

com.google.gson.stream.MalformedJsonException: Use
  JsonReader.setLenient(true) to accept malformed JSON at line 1 column
  1 path $

Body:
1) grades: [ is not part of valid JSON. Remove grades: and leave the [ if you want to parse a JSON array.

Then, your Gson model is wrong. You have "grades" and "grade", not "grade", "next_dates", and "class".

This is also two objects.

{                    // One Object here
    "class": "math",
    "grade": 4.5,
    "next_dates":[
        {            // Second object here
            "exam": "03/03/2017",
            "homework": "03/03/2017"
        }
    ]
}

So, your Java classes would be something like

public class GradeDate {
    private String exam, homework;
}

public class GradeModel {
    private String class;
    private Double grade;
    private List<GradeDate> nextDates;
}

Then, your JSON is still missing some commas to separate the values in the outer array.


问:
I can't install udev on plain ubuntu 14.04
I've plain Ubuntu 14.04 Server (64-bit) installation.

When use:

```<code>sudo apt-get update
</code>```

Print this error:

```<code>....
Hit http://security.ubuntu.com trusty-security/universe Translation-en
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.
</code>```

After removing tmp.i /var/lib/dpkg/updates# sudo rm tmp.i apt-get update went OK but...

When I tried 'sudo apt-get upgrade':

```<code>Fetched 534 kB in 4s (112 kB/s)
Reading package lists... Done
root@vps****:/# sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] Y
Setting up udev (204-5ubuntu20.9) ...
 * udev requires hotplug support, not started
   ...fail!
invoke-rc.d: initscript udev, action "restart" failed.
dpkg: error processing package udev (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 udev
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

I can't find any solution for that so far on web, tried many ways but nothing worked...

答:
Instead of editing /etc/init.d/udev twice, you could just add this on a newline after ### END INIT INFO:

```<code>dpkg --configure -a || exit 0
</code>```

That way if the dpkg --configure fails it will exit, otherwise it will continue on as normal.

Or, if editing files isn't your thing, this will do the trick:

```<code>[ ! "$(grep -A1 '### END INIT INFO' /etc/init.d/udev | grep 'dpkg --configure -a || exit 0')" ] \
&& sudo sed -i 's/### END INIT INFO/### END INIT INFO\
dpkg --configure -a || exit 0/' /etc/init.d/udev
</code>```

Body:
I've plain Ubuntu 14.04 Server (64-bit) installation.

When use:

sudo apt-get update

Print this error:

....
Hit http://security.ubuntu.com trusty-security/universe Translation-en
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.

After removing tmp.i /var/lib/dpkg/updates# sudo rm tmp.i apt-get update went OK but...

When I tried 'sudo apt-get upgrade':

Fetched 534 kB in 4s (112 kB/s)
Reading package lists... Done
root@vps****:/# sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] Y
Setting up udev (204-5ubuntu20.9) ...
 * udev requires hotplug support, not started
   ...fail!
invoke-rc.d: initscript udev, action "restart" failed.
dpkg: error processing package udev (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 udev
E: Sub-process /usr/bin/dpkg returned an error code (1)

I can't find any solution for that so far on web, tried many ways but nothing worked...

Body:
Instead of editing /etc/init.d/udev twice, you could just add this on a newline after ### END INIT INFO:

dpkg --configure -a || exit 0

That way if the dpkg --configure fails it will exit, otherwise it will continue on as normal.

Or, if editing files isn't your thing, this will do the trick:

[ ! "$(grep -A1 '### END INIT INFO' /etc/init.d/udev | grep 'dpkg --configure -a || exit 0')" ] \
&& sudo sed -i 's/### END INIT INFO/### END INIT INFO\
dpkg --configure -a || exit 0/' /etc/init.d/udev