问:
How to create "Automatic Brightness" to adjust lcd lighting, depending on sunlight conditions?
I create an android app (Point of sale Terminal), to be installed outdoors that is in petrol station. I have a problem: The application becomes invisible during the day (when the sunlight appears).

Based on the information from here, for android applications remain visible when the sun light appears is to set the brightness to the maximum value.

How to create "Automatic Brightness" to adjust lcd lighting, depending on sunlight conditions?

Outside the room, when conditions are:

Morning / Overcast: Screen at medium brightness.

Daytime / Sunny: Screen at high brightness.

Night: Screen at low brightness.

Thanks.

答:
To change brightness automatically based on predetermined time, I create thread worker which automatically run adjustBrightness function every 1 hour interval.

// AutoBrightness.java

```<code>import android.app.Activity;
import android.content.Context;
import android.provider.Settings;
import android.util.Log;
import android.view.WindowManager;

import static android.provider.Settings.System.SCREEN_BRIGHTNESS;

public class AutoBrightness {
    private final static String TAG = AutoBrightness.class.getName();
    private static boolean _isBrightnessThreadEnable;
    private static BrightnessThread _brightnessThread;
    private static Context _context;
    private static AutoBrightness _instance;

    private AutoBrightness(Context context) {
        _context = context;
    }

    public static AutoBrightness getInstance(Context context) {
        if (_instance == null) {
            _instance = new AutoBrightness(context);
        }
        return _instance;
    }

    public void start() {
        if (!_isBrightnessThreadEnable) {
            _brightnessThread = new BrightnessThread(_context);
            _brightnessThread.start();
            _isBrightnessThreadEnable = true;
        }
    }

    private class BrightnessThread extends Thread {
        Context _context;

        BrightnessThread(Context context) {
            _context = context;
            Settings.System.putInt(_context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            setPriority(Thread.NORM_PRIORITY);
        }

        private long getCurrentTime() {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(SHORT_TIME_FORMAT);
            String currentTime = simpleDateFormat.format(Calendar.getInstance().getTime());
            try {
                return simpleDateFormat.parse(currentTime).getTime();
            } catch (ParseException ex) {
                Log.e(TAG, Log.getStackTraceString(ex));
            }
            return 0;
        }

        private void adjustBrightness(float backlightValue){
            WindowManager.LayoutParams layoutParams = ((Activity) _context).getWindow().getAttributes();
            layoutParams.screenBrightness = backlightValue;
            ((Activity) _context).getWindow().setAttributes(layoutParams);

            int systemBacklightValue = (int) (backlightValue * 255);
            android.provider.Settings.System.putInt(_context.getContentResolver(), SCREEN_BRIGHTNESS, systemBacklightValue);
        }

        @Override
        public void run() {
            long morningTime = -3600000L, dayTime = 10800000L, nightTime = 39600000L;
            float backlightValue = 0.5f;

            boolean isMorningAdjusted = false;
            boolean isDayAdjusted = false;
            boolean isNightAdjusted = false;

            while (_isBrightnessThreadEnable) {

                long currentTime = getCurrentTime();
                if (currentTime >= morningTime && currentTime < dayTime) {

                    // 06:00 - 09:59 (morning)
                    if (!isMorningAdjusted) {
                        backlightValue = 0.50f;
                        adjustBrightness(backlightValue);
                        isMorningAdjusted = true;

                        isDayAdjusted = false;
                        isNightAdjusted = false;
                    }

                } else if (currentTime >= dayTime && currentTime < nightTime) {

                    // 10:00 - 17:59 (day)
                    if (!isDayAdjusted) {
                        backlightValue = 1.00f;
                        adjustBrightness(backlightValue);
                        isDayAdjusted = true;

                        isMorningAdjusted = false;
                        isNightAdjusted = false;
                    }
                } else {

                    // 18:00 - 05:59 (night)
                    if (!isNightAdjusted) {
                        backlightValue = 0.35f;
                        adjustBrightness(backlightValue);
                        isNightAdjusted = true;

                        isMorningAdjusted = false;
                        isDayAdjusted = false;
                    }
                }

                try {
                    // delay for 1 hours
                    Thread.sleep(1000 * 60 * 60);
                } catch (InterruptedException ex) {
                    Log.e(TAG, Log.getStackTraceString(ex));
                }
            }
        }
    }
}
</code>```

How to use?

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    _autoBrightness = AutoBrightness.getInstance(this);
    _autoBrightness.start();
}
</code>```

Body:
To change brightness automatically based on predetermined time, I create thread worker which automatically run adjustBrightness function every 1 hour interval.

// AutoBrightness.java

import android.app.Activity;
import android.content.Context;
import android.provider.Settings;
import android.util.Log;
import android.view.WindowManager;

import static android.provider.Settings.System.SCREEN_BRIGHTNESS;

public class AutoBrightness {
    private final static String TAG = AutoBrightness.class.getName();
    private static boolean _isBrightnessThreadEnable;
    private static BrightnessThread _brightnessThread;
    private static Context _context;
    private static AutoBrightness _instance;

    private AutoBrightness(Context context) {
        _context = context;
    }

    public static AutoBrightness getInstance(Context context) {
        if (_instance == null) {
            _instance = new AutoBrightness(context);
        }
        return _instance;
    }

    public void start() {
        if (!_isBrightnessThreadEnable) {
            _brightnessThread = new BrightnessThread(_context);
            _brightnessThread.start();
            _isBrightnessThreadEnable = true;
        }
    }

    private class BrightnessThread extends Thread {
        Context _context;

        BrightnessThread(Context context) {
            _context = context;
            Settings.System.putInt(_context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            setPriority(Thread.NORM_PRIORITY);
        }

        private long getCurrentTime() {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(SHORT_TIME_FORMAT);
            String currentTime = simpleDateFormat.format(Calendar.getInstance().getTime());
            try {
                return simpleDateFormat.parse(currentTime).getTime();
            } catch (ParseException ex) {
                Log.e(TAG, Log.getStackTraceString(ex));
            }
            return 0;
        }

        private void adjustBrightness(float backlightValue){
            WindowManager.LayoutParams layoutParams = ((Activity) _context).getWindow().getAttributes();
            layoutParams.screenBrightness = backlightValue;
            ((Activity) _context).getWindow().setAttributes(layoutParams);

            int systemBacklightValue = (int) (backlightValue * 255);
            android.provider.Settings.System.putInt(_context.getContentResolver(), SCREEN_BRIGHTNESS, systemBacklightValue);
        }

        @Override
        public void run() {
            long morningTime = -3600000L, dayTime = 10800000L, nightTime = 39600000L;
            float backlightValue = 0.5f;

            boolean isMorningAdjusted = false;
            boolean isDayAdjusted = false;
            boolean isNightAdjusted = false;

            while (_isBrightnessThreadEnable) {

                long currentTime = getCurrentTime();
                if (currentTime >= morningTime && currentTime < dayTime) {

                    // 06:00 - 09:59 (morning)
                    if (!isMorningAdjusted) {
                        backlightValue = 0.50f;
                        adjustBrightness(backlightValue);
                        isMorningAdjusted = true;

                        isDayAdjusted = false;
                        isNightAdjusted = false;
                    }

                } else if (currentTime >= dayTime && currentTime < nightTime) {

                    // 10:00 - 17:59 (day)
                    if (!isDayAdjusted) {
                        backlightValue = 1.00f;
                        adjustBrightness(backlightValue);
                        isDayAdjusted = true;

                        isMorningAdjusted = false;
                        isNightAdjusted = false;
                    }
                } else {

                    // 18:00 - 05:59 (night)
                    if (!isNightAdjusted) {
                        backlightValue = 0.35f;
                        adjustBrightness(backlightValue);
                        isNightAdjusted = true;

                        isMorningAdjusted = false;
                        isDayAdjusted = false;
                    }
                }

                try {
                    // delay for 1 hours
                    Thread.sleep(1000 * 60 * 60);
                } catch (InterruptedException ex) {
                    Log.e(TAG, Log.getStackTraceString(ex));
                }
            }
        }
    }
}

How to use?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    _autoBrightness = AutoBrightness.getInstance(this);
    _autoBrightness.start();
}


来源: stackexchange

问:
Is this a correct way to pass a function into a struct?
I looked but couldn't find a direct reference for this question. I'm new to function pointers (and C), so I don't know all the tricks one can do yet :)

I've effectively got a function:

```<code>void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
    ...
</code>```

...where My_Struct has prototype:

```<code>typedef struct my_struct {
    int (*comp)(int x, int y);
} My_Struct;
</code>```

Modulo some minor details. I just want to know if the following is correct syntax:

```<code>void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
    structure->comp = comp;
}
</code>```

It seems almost too easy, and I'm worried it is.

ContentLicense: CC BY-SA 3.0

Body:
I looked but couldn't find a direct reference for this question. I'm new to function pointers (and C), so I don't know all the tricks one can do yet :)

I've effectively got a function:

void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
    ...

...where My_Struct has prototype:

typedef struct my_struct {
    int (*comp)(int x, int y);
} My_Struct;

Modulo some minor details. I just want to know if the following is correct syntax:

void select_comparator(My_Struct *structure, int (*comp)(int x, int y)) {
    structure->comp = comp;
}

It seems almost too easy, and I'm worried it is.

Body:
Nothing's wrong: this is the basis of callbacks in c. Just make sure the signature of your function pointer matches the type defined in your structure. Where it gets remotely tricky is when you're using this in a large project, and people forget to check if the function pointer is valid or void, along with arguments, etc.

Code Listing

/*******************************************************************************
 * Preprocessor directives.
 ******************************************************************************/
#include <stdio.h>

/*******************************************************************************
 * Data types.
 ******************************************************************************/
typedef struct my_struct {
    int (*comp)(int x, int y);
} My_Struct;

/*******************************************************************************
 * Function prototypes.
 ******************************************************************************/
int c(int a, int b);
void select_comparator(My_Struct *structure, int (*comp)(int x, int y));

/*******************************************************************************
 * Function definitions.
 ******************************************************************************/
/*----------------------------------------------------------------------------*/
int main(void)
{
    My_Struct s;

    select_comparator(&s, &c);
    s.comp(1, 2);

    return 0;
}

/*----------------------------------------------------------------------------*/
void select_comparator(My_Struct *structure, int (*comp)(int x, int y))
{
    structure->comp = comp;
}

/*----------------------------------------------------------------------------*/
int c(int a, int b)
{
    int ret = 0;
    if (a < b) {
        ret = (-1);
    } else if (a > b) {
        ret = 1;
    }

    return ret;
}


问:
Compilation error in Selenium Webdriver : field package.Classfile.driver is not visible
I am getting some sort of compilation error it seems.

I have ‘Common.java’ class inside ‘base’ package. It's a program for starting firefox driver. That, I have kept it in the separate package to make it a one time effort and modularity purpose.

I am calling this class file inside the child class ‘tc_01.java’. This TC_01.jave program is in another package ‘testing’. This TC_01.java file is actually accessing driver from Common.java and start the browser and try some login and logout actions.

My child class TC_01.java is showing me compilation error and Error Message on Mouse Hover is – > “field Common.driver is not visible”.
And, at Console : "java.lang.Error: Unresolved compilation problems:
    The field Common.driver is not visible"

My Analysis: It seems TC_01.java file is not able to access the 'driver' from 'Common.java'.
But, I have already written 'extends' keyword for it to inherit the properties.

Please guide me. Thanks

Here is my code:->

```<code>package base;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class Common {

public FirefoxDriver driver;

@BeforeMethod
public void BM(){
System.setProperty(“webdriver.gecko.driver”,”D://Rajiv//Selenium//geckodriver.exe”);
driver = new FirefoxDriver();
driver.get(“http://automationpractice.com/index.php”);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@AfterMethod
public void CM(){
driver.close();
}
}

# Pakage – testing; Class – Tc_01.java

package testing;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import base.Common;

public class TC_01 extends Common{
public FirefoxDriver driver;`
@Test
public void TM(){
System.out.println(“Selenium Webdriver Script in Firefox browser using Gecko` `Driver | AutomationPractice.com PAGE LAUNCHED”);

WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“search_query_top”)));

try{
    String expectedTitle = “My Store”;
    System.out.println(“ExpectedTile = “+expectedTitle );
    String actualTitle = driver.getTitle();
    System.out.println(“The actual Title of the Page is = “+actualTitle);
   Assert.assertEquals(actualTitle, expectedTitle);*/

   System.out.println(“Control has reached here”);
   driver.findElementByClassName(“login”).click(); // field common.driver is not visible
   driver.findElementById(“email”).sendKeys(“*****@yahoo.com”);
   driver.findElementById(“passwd”).sendKeys(“*****”);
   driver.findElementById(“SubmitLogin”).click();

   driver.findElementByClassName(“logout”).click();
   System.out.println(“Sucessfully Logout from the Application”);
   }catch (Exception e){
      e.printStackTrace();
    }
  }
}
</code>```

答:
I was able to find the root cause for this issue.
It wasted my 3 days before i asked for help here in this forum.
As i had analysed initially, i had mentioned my driver properties in parent class and was accessing it in Child Class. There was some name mismatch. When it was trying to inherit the properties from parent, it was not accessible and giving me compilation error. I renamed the parent class name to the same name that i was giving while extending in Child Class. And, it worked.
Thanks again to all of you. It is such a wonderful forum to discuss your issue between each other and getting its resolution.</p>

Body:
I am getting some sort of compilation error it seems.

I have ‘Common.java’ class inside ‘base’ package. It's a program for starting firefox driver. That, I have kept it in the separate package to make it a one time effort and modularity purpose.

I am calling this class file inside the child class ‘tc_01.java’. This TC_01.jave program is in another package ‘testing’. This TC_01.java file is actually accessing driver from Common.java and start the browser and try some login and logout actions.

My child class TC_01.java is showing me compilation error and Error Message on Mouse Hover is – > “field Common.driver is not visible”.
And, at Console : "java.lang.Error: Unresolved compilation problems:
    The field Common.driver is not visible"

My Analysis: It seems TC_01.java file is not able to access the 'driver' from 'Common.java'.
But, I have already written 'extends' keyword for it to inherit the properties.

Please guide me. Thanks

Here is my code:->

package base;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class Common {

public FirefoxDriver driver;

@BeforeMethod
public void BM(){
System.setProperty(“webdriver.gecko.driver”,”D://Rajiv//Selenium//geckodriver.exe”);
driver = new FirefoxDriver();
driver.get(“http://automationpractice.com/index.php”);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@AfterMethod
public void CM(){
driver.close();
}
}

# Pakage – testing; Class – Tc_01.java

package testing;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import base.Common;

public class TC_01 extends Common{
public FirefoxDriver driver;`
@Test
public void TM(){
System.out.println(“Selenium Webdriver Script in Firefox browser using Gecko` `Driver | AutomationPractice.com PAGE LAUNCHED”);

WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“search_query_top”)));

try{
    String expectedTitle = “My Store”;
    System.out.println(“ExpectedTile = “+expectedTitle );
    String actualTitle = driver.getTitle();
    System.out.println(“The actual Title of the Page is = “+actualTitle);
   Assert.assertEquals(actualTitle, expectedTitle);*/

   System.out.println(“Control has reached here”);
   driver.findElementByClassName(“login”).click(); // field common.driver is not visible
   driver.findElementById(“email”).sendKeys(“*****@yahoo.com”);
   driver.findElementById(“passwd”).sendKeys(“*****”);
   driver.findElementById(“SubmitLogin”).click();

   driver.findElementByClassName(“logout”).click();
   System.out.println(“Sucessfully Logout from the Application”);
   }catch (Exception e){
      e.printStackTrace();
    }
  }
}


问:
Set Keystone List "noedit" based on field value?
I would like to make my Keystone List object editable only if the object is not published. Here's my reduced List definition:

```<code>var Campaign = new keystone.List('Campaign', {
  nodelete: true,
  track: {
    createdAt: true,
  },
});

Campaign.add({
  ...,
  publish: {
    type: Types.Boolean,
    required: false,
    initial: false,
    dependsOn: {
      publishedOn: '',
    },
  },
  publishedOn: {
    type: Types.Datetime,
    label: 'Published On',
    hidden: true,
  },
});
</code>```

Is it possible to set noedit only if publishedOn is not null? I'm trying to prevent the object from being modified after it's "published", and am coming up short on examples.

答:
Interestingly, I was able to make the publish field simply check itself:

```<code>Campaign.add({
  ...,
  publish: {
    type: Types.Boolean,
    required: false,
    initial: false,

    dependsOn: {
      publish: false,
    },

  },
  ...,
});
</code>```

and now it only shows if publish is false, which works exactly as I hoped it would.

Body:
I would like to make my Keystone List object editable only if the object is not published. Here's my reduced List definition:

var Campaign = new keystone.List('Campaign', {
  nodelete: true,
  track: {
    createdAt: true,
  },
});

Campaign.add({
  ...,
  publish: {
    type: Types.Boolean,
    required: false,
    initial: false,
    dependsOn: {
      publishedOn: '',
    },
  },
  publishedOn: {
    type: Types.Datetime,
    label: 'Published On',
    hidden: true,
  },
});

Is it possible to set noedit only if publishedOn is not null? I'm trying to prevent the object from being modified after it's "published", and am coming up short on examples.

Body:
Interestingly, I was able to make the publish field simply check itself:

Campaign.add({
  ...,
  publish: {
    type: Types.Boolean,
    required: false,
    initial: false,

    dependsOn: {
      publish: false,
    },

  },
  ...,
});

and now it only shows if publish is false, which works exactly as I hoped it would.


问:
Replace auto filled text via userform
I've developed a user form for the letters we use at work that auto fill the document after required data has been entered.

At this current point in time - when you hit OK the data will be entered and the data will fill the form. Some users are just trying to keep entering information over the top of the already filled form and stacking previously entered data into the letter.

Question: How do I get the user form to replace entered data rather than add entered data.

So if I enter the name as John Wayne, complete my letter and decide to write another letter on the same open document - how do I reopen my macro, populate the data and then overwrite all the previous information of the previous letter.

```<code>    Option Explicit
Private Sub CheckBox1_Click()
    Dim en As Boolean
    en = Not CheckBox1.Value
    EnableControls Array(TBLPGN, TBLPFN), en

    If CheckBox1.Value = True Then ComboBoxLodge.Value = "Applicant"
    If CheckBox1.Value = False Then ComboBoxLodge.Value = "Lodging parent"

End Sub

'utility sub: enable/disable controls
Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(200, 200, 200))
        End With
    Next con
End Sub
Private Sub cmdCancel_Click()
    Unload Me
End Sub

Private Sub cmdClear_Click()
tbForm.Value = Null
tbFN.Value = Null
tbGN.Value = Null
tbDOB.Value = Null
cbLT.Value = Null
tbPN.Value = Null
tbissue.Value = Null
tbexpiry.Value = Null
tbLTD.Value = Null
tbNarrative.Value = Null
tbPRR.Value = Null
cbRecommendation.Value = Null
CheckBox1.Value = False
ComboBoxLodge.Value = Null
End Sub

Private Sub cmdOk_Click()
    Dim useAforB As Boolean
    useAforB = CheckBox1.Value

    Application.ScreenUpdating = False
    With ActiveDocument
        .Bookmarks("Lodge").Range.Text = ComboBoxLodge.Value
        .Bookmarks("Form").Range.Text = tbForm.Value
        .Bookmarks("Form2").Range.Text = tbForm.Value
        .Bookmarks("AGN").Range.Text = tbGN.Value
        .Bookmarks("AFN").Range.Text = tbFN.Value
        .Bookmarks("LGN").Range.Text = IIf(useAforB, _
                                     tbGN.Value, TBLPGN.Value)
        .Bookmarks("RGN").Range.Text = IIf(useAforB, _
                                     tbGN.Value, TBLPGN.Value)
        .Bookmarks("LFN").Range.Text = IIf(useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        .Bookmarks("RFN").Range.Text = IIf(useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        .Bookmarks("DOB").Range.Text = tbDOB.Value
        .Bookmarks("LT").Range.Text = cbLT.Value
        .Bookmarks("PN").Range.Text = tbPN.Value
        .Bookmarks("PN2").Range.Text = tbPN.Value
        .Bookmarks("PN3").Range.Text = tbPN.Value
        .Bookmarks("PN4").Range.Text = tbPN.Value
        .Bookmarks("Issued").Range.Text = tbissue.Value
        .Bookmarks("Expiry").Range.Text = tbexpiry.Value
        .Bookmarks("LTD").Range.Text = tbLTD.Value
        .Bookmarks("LTD2").Range.Text = tbLTD.Value
        .Bookmarks("Narrative").Range.Text = tbNarrative.Value
        .Bookmarks("PRR").Range.Text = tbPRR.Value
        .Bookmarks("Recommendation").Range.Text = cbRecommendation.Value
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub

Private Sub Tbform_Change()
    tbForm = UCase(tbForm)
End Sub

Private Sub Tbfn_Change()
    tbFN = UCase(tbFN)
End Sub
Private Sub Tblpfn_Change()
    TBLPFN = UCase(TBLPFN)
End Sub

Private Sub Tbpn_Change()
    tbPN = UCase(tbPN)
End Sub

Private Sub UserForm_Initialize()
    With cbLT
        .AddItem "lost"
        .AddItem "stolen"
    End With
    With cbRecommendation
        .AddItem "I believe there is an entitlement to have the l/t flag turned off as the applicant has not contributed to the loss of Passport number: "
        .AddItem "I believe there is no entitlement to have the l/t flag turned off as the applicant has contributed to the loss of Passport number:  "
    End With
    With ComboBoxLodge
        .AddItem "Lodging parent"
        .AddItem "Applicant"
     End With
     With CheckBox1
        CheckBox1.Value = True
    End With
lbl_Exit:
    Exit Sub
End Sub

Public Sub AutoOpen()
    frmminute.Show
End Sub

Sub CallUF()
Dim oFrm As frmminute
  Set oFrm = New frmminute
  oFrm.Show
  Unload oFrm
  Set oFrm = Nothing
lbl_Exit:
  Exit Sub
End Sub

Sub AutoNew()
  CallUF
lbl_Exit:
Exit Sub
End Sub
</code>```

new code currently getting a runtime error:

```<code>Private Sub CommandButtonOk_Click()
Dim useAforB As Boolean
useAforB = CheckBox1.Value

Application.ScreenUpdating = False
With ActiveDocument
    Call UpdateBookmark("Title", ComboBoxTitle.Value)
    Call UpdateBookmark("GN", TextBoxGN.Value)
    Call UpdateBookmark("FN", TextBoxFN.Value)
    Call UpdateBookmark("FN2", TextBoxFN.Value)
    Call UpdateBookmark("Street", TextBoxStreet.Value)
    Call UpdateBookmark("suburb", TextBoxSuburb.Value)
    Call UpdateBookmark("postcode", TextBoxpostcode.Value)
    Call UpdateBookmark("state", ComboBoxState.Value)
    Call UpdateBookmark("street2", .Range.Text = IIf(useAforB, _
                                 TextBoxStreet.Value, TextBoxStreet2.Value))

    Call UpdateBookmark("Suburb2", .Range.Text = IIf(useAforB, _
                                 TextBoxSuburb.Value, TextBoxSuburb2.Value))
    Call UpdateBookmark("State2", .Range.Text = IIf(useAforB, _
                                 ComboBoxState.Value, ComboBoxState2.Value))
    Call UpdateBookmark("PostCode2", .Range.Text = IIf(useAforB, _
                                 TextBoxpostcode.Value, TextBoxPostcode2.Value))
    Call UpdateBookmark("CD", TextBoxCD.Value)
    Call UpdateBookmark("MPN", TextboxMPN.Value)
    Call UpdateBookmark("MPN2", TextboxMPN.Value)
    Call UpdateBookmark("MPN3", TextboxMPN.Value)
    Call UpdateBookmark("MPN4", TextboxMPN.Value)
    Call UpdateBookmark("MPN5", TextboxMPN.Value)
    Call UpdateBookmark("MPDD", TextBoxMPDD.Value)
    Call UpdateBookmark("NPN", TextBoxNPN.Value)
    Call UpdateBookmark("NPDD", TextBoxNPDD.Value)
End With
Application.ScreenUpdating = True
Unload Me
End Sub

Sub UpdateBookmark(BookmarkToUpdate As String, TextAtBookmark As String)
   Dim BookmarkRange As Range
   Set BookmarkRange = ActiveDocument.Bookmarks(BookmarkToUpdate).Range
   BookmarkRange.Text = TextAtBookmark
   ActiveDocument.Bookmarks.Add BookmarkToUpdate, BookmarkRange
</code>```

答:
After reading through your question, I realised what you wanted to do was updating the bookmark at the word document.</p>

```<code>Private Sub cmdOk_Click()
   Dim useAforB As Boolean
   useAforB = CheckBox1.Value

   Application.ScreenUpdating = False

   Call UpdateBookmark("Lodge", ComboBoxLodge.Value)
   Call UpdateBookmark("Form", tbForm.Value)
   'Do for the rest.....

   Application.ScreenUpdating = True
   Unload Me
End Sub

Sub UpdateBookmark(BookmarkToUpdate As String, TextAtBookmark as string)
   Dim BookmarkRange As Range
   Set BookmarkRange = ActiveDocument.Bookmarks(BookmarkToUpdate).Range
   BookmarkRange.Text = TextAtBookmark
   ActiveDocument.Bookmarks.Add BookmarkToUpdate, BookmarkRange
End Sub
</code>```

Title: Replace auto filled text via userform

Body:
I've developed a user form for the letters we use at work that auto fill the document after required data has been entered.

At this current point in time - when you hit OK the data will be entered and the data will fill the form. Some users are just trying to keep entering information over the top of the already filled form and stacking previously entered data into the letter.

Question: How do I get the user form to replace entered data rather than add entered data.

So if I enter the name as John Wayne, complete my letter and decide to write another letter on the same open document - how do I reopen my macro, populate the data and then overwrite all the previous information of the previous letter.

    Option Explicit
Private Sub CheckBox1_Click()
    Dim en As Boolean
    en = Not CheckBox1.Value
    EnableControls Array(TBLPGN, TBLPFN), en

    If CheckBox1.Value = True Then ComboBoxLodge.Value = "Applicant"
    If CheckBox1.Value = False Then ComboBoxLodge.Value = "Lodging parent"

End Sub

'utility sub: enable/disable controls
Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(200, 200, 200))
        End With
    Next con
End Sub
Private Sub cmdCancel_Click()
    Unload Me
End Sub

Private Sub cmdClear_Click()
tbForm.Value = Null
tbFN.Value = Null
tbGN.Value = Null
tbDOB.Value = Null
cbLT.Value = Null
tbPN.Value = Null
tbissue.Value = Null
tbexpiry.Value = Null
tbLTD.Value = Null
tbNarrative.Value = Null
tbPRR.Value = Null
cbRecommendation.Value = Null
CheckBox1.Value = False
ComboBoxLodge.Value = Null
End Sub

Private Sub cmdOk_Click()
    Dim useAforB As Boolean
    useAforB = CheckBox1.Value

    Application.ScreenUpdating = False
    With ActiveDocument
        .Bookmarks("Lodge").Range.Text = ComboBoxLodge.Value
        .Bookmarks("Form").Range.Text = tbForm.Value
        .Bookmarks("Form2").Range.Text = tbForm.Value
        .Bookmarks("AGN").Range.Text = tbGN.Value
        .Bookmarks("AFN").Range.Text = tbFN.Value
        .Bookmarks("LGN").Range.Text = IIf(useAforB, _
                                     tbGN.Value, TBLPGN.Value)
        .Bookmarks("RGN").Range.Text = IIf(useAforB, _
                                     tbGN.Value, TBLPGN.Value)
        .Bookmarks("LFN").Range.Text = IIf(useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        .Bookmarks("RFN").Range.Text = IIf(useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        .Bookmarks("DOB").Range.Text = tbDOB.Value
        .Bookmarks("LT").Range.Text = cbLT.Value
        .Bookmarks("PN").Range.Text = tbPN.Value
        .Bookmarks("PN2").Range.Text = tbPN.Value
        .Bookmarks("PN3").Range.Text = tbPN.Value
        .Bookmarks("PN4").Range.Text = tbPN.Value
        .Bookmarks("Issued").Range.Text = tbissue.Value
        .Bookmarks("Expiry").Range.Text = tbexpiry.Value
        .Bookmarks("LTD").Range.Text = tbLTD.Value
        .Bookmarks("LTD2").Range.Text = tbLTD.Value
        .Bookmarks("Narrative").Range.Text = tbNarrative.Value
        .Bookmarks("PRR").Range.Text = tbPRR.Value
        .Bookmarks("Recommendation").Range.Text = cbRecommendation.Value
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub

Private Sub Tbform_Change()
    tbForm = UCase(tbForm)
End Sub

Private Sub Tbfn_Change()
    tbFN = UCase(tbFN)
End Sub
Private Sub Tblpfn_Change()
    TBLPFN = UCase(TBLPFN)
End Sub

Private Sub Tbpn_Change()
    tbPN = UCase(tbPN)
End Sub

Private Sub UserForm_Initialize()
    With cbLT
        .AddItem "lost"
        .AddItem "stolen"
    End With
    With cbRecommendation
        .AddItem "I believe there is an entitlement to have the l/t flag turned off as the applicant has not contributed to the loss of Passport number: "
        .AddItem "I believe there is no entitlement to have the l/t flag turned off as the applicant has contributed to the loss of Passport number:  "
    End With
    With ComboBoxLodge
        .AddItem "Lodging parent"
        .AddItem "Applicant"
     End With
     With CheckBox1
        CheckBox1.Value = True
    End With
lbl_Exit:
    Exit Sub
End Sub

Public Sub AutoOpen()
    frmminute.Show
End Sub

Sub CallUF()
Dim oFrm As frmminute
  Set oFrm = New frmminute
  oFrm.Show
  Unload oFrm
  Set oFrm = Nothing
lbl_Exit:
  Exit Sub
End Sub

Sub AutoNew()
  CallUF
lbl_Exit:
Exit Sub
End Sub

new code currently getting a runtime error:

Private Sub CommandButtonOk_Click()
Dim useAforB As Boolean
useAforB = CheckBox1.Value

Application.ScreenUpdating = False
With ActiveDocument
    Call UpdateBookmark("Title", ComboBoxTitle.Value)
    Call UpdateBookmark("GN", TextBoxGN.Value)
    Call UpdateBookmark("FN", TextBoxFN.Value)
    Call UpdateBookmark("FN2", TextBoxFN.Value)
    Call UpdateBookmark("Street", TextBoxStreet.Value)
    Call UpdateBookmark("suburb", TextBoxSuburb.Value)
    Call UpdateBookmark("postcode", TextBoxpostcode.Value)
    Call UpdateBookmark("state", ComboBoxState.Value)
    Call UpdateBookmark("street2", .Range.Text = IIf(useAforB, _
                                 TextBoxStreet.Value, TextBoxStreet2.Value))

    Call UpdateBookmark("Suburb2", .Range.Text = IIf(useAforB, _
                                 TextBoxSuburb.Value, TextBoxSuburb2.Value))
    Call UpdateBookmark("State2", .Range.Text = IIf(useAforB, _
                                 ComboBoxState.Value, ComboBoxState2.Value))
    Call UpdateBookmark("PostCode2", .Range.Text = IIf(useAforB, _
                                 TextBoxpostcode.Value, TextBoxPostcode2.Value))
    Call UpdateBookmark("CD", TextBoxCD.Value)
    Call UpdateBookmark("MPN", TextboxMPN.Value)
    Call UpdateBookmark("MPN2", TextboxMPN.Value)
    Call UpdateBookmark("MPN3", TextboxMPN.Value)
    Call UpdateBookmark("MPN4", TextboxMPN.Value)
    Call UpdateBookmark("MPN5", TextboxMPN.Value)
    Call UpdateBookmark("MPDD", TextBoxMPDD.Value)
    Call UpdateBookmark("NPN", TextBoxNPN.Value)
    Call UpdateBookmark("NPDD", TextBoxNPDD.Value)
End With
Application.ScreenUpdating = True
Unload Me
End Sub

Sub UpdateBookmark(BookmarkToUpdate As String, TextAtBookmark As String)
   Dim BookmarkRange As Range
   Set BookmarkRange = ActiveDocument.Bookmarks(BookmarkToUpdate).Range
   BookmarkRange.Text = TextAtBookmark
   ActiveDocument.Bookmarks.Add BookmarkToUpdate, BookmarkRange

Body:
After reading through your question, I realised what you wanted to do was updating the bookmark at the word document.

Private Sub cmdOk_Click()
   Dim useAforB As Boolean
   useAforB = CheckBox1.Value

   Application.ScreenUpdating = False

   Call UpdateBookmark("Lodge", ComboBoxLodge.Value)
   Call UpdateBookmark("Form", tbForm.Value)
   'Do for the rest.....

   Application.ScreenUpdating = True
   Unload Me
End Sub

Sub UpdateBookmark(BookmarkToUpdate As String, TextAtBookmark as string)
   Dim BookmarkRange As Range
   Set BookmarkRange = ActiveDocument.Bookmarks(BookmarkToUpdate).Range
   BookmarkRange.Text = TextAtBookmark
   ActiveDocument.Bookmarks.Add BookmarkToUpdate, BookmarkRange
End Sub


问:
Shortening Really long Client ids
I'mm getting really long client ids one such example is below. Some of them are about 100 characters long which is ridiculous.
Is there anything or any tool i can use that will shorten the pages ids?

id="ctl00_ctl00_MainContent_MemberMain_Abc_asdsad...._DlSAdasdasdasd_ctl00_PnsadasdasdnsHF"

EDIT:
I am nesting a lot which is the cause of the problem.
I am using  .net 3.5. and collisions are not ok as some of the ids are being used by javascript funcitons

答:
Maybe. If you're using .NET 4.0. If not, I don't think there's a way to shorten the name. In ASP.net <=3.5, each ContentPlaceHolder or UserControl will add a its name to the  If you're trying to access these with javascript, you can use a few different methods.

For .NET 4.0 Only: Put ClientIDMode="Predictable" or ClientIDMode="Static" in your MasterPage or UserControl Declaration (and maybe your Page Declarations).

If you're on .NET 3.5 or less, you can't shorten, but you can use one of these:

JQuery has a function which allows you to find by end text:
var ElemIWant=$("[id$=PnsadasdasdnsHF]");

Use an inline ASP call:

var ElemIWant=document.getElementById('<% =TextBox1.ClientID %>);

There's also another Article you can look at:
Need workaround for .Net Master Page Name Mangling

ContentLicense: CC BY-SA 2.5

Title: Shortening Really long Client ids


问:
Disk space required for unix sort
I am currently doing a UNIX sort (via GitBash on a Windows machine) of a 500GB text file. Due to running out of space on the main disk, I have used the -T option to direct the temp files to a disk where I have enough space to accommodate the entire file. The thing is, I've been watching the disk space and apparently the temp files are already in excess of what the original file was. I don't know how much further this is going to go, but I'm wondering if there is a rule by which I can predict how much space I will need for temp files.</p>

答:
I'd batch it manually as described in this unix.SE answer.

Find some very basic queries that will divide your content into chunks that are small enough to be sorted.  For example, if it's a file of words, you could create queries like grep ^a …, grep ^b …, and so on.  Some items may need more granularity than others.

You can script that like:

#!/bin/bash
for char1 in other {0..9} {a..z}; do
  out="/tmp/sort.$char1.xz"
  echo "Extracting lines starting with '$char1'"
  if [ "$char1" = "other" ]; then char1='[^a-z0-9]'; fi
  grep -i "^$char1" *.txt |xz -c0 > "$out"
  unxz -c "$out" |sort -u >> output.txt || exit 1
  rm "$out"
done
echo "It worked"
```

I'm using xz -0 because it's almost as fast as gzip's default gzip -6 yet it's vastly better at conserving space.  I omitted it from the final output in order to preserve the exit value of sort -u, but you could instead use a size check (iirc, sort fails with zero output) and then use sort -u |xz -c0 >> output.txt.xz since the xz (and gzip) container lets you concatenate archives (I've written about that before too).

This works because the output of each grep run is already sorted (0 is before 1, which is before a, etc.), so the final assembly doesn't need to run through sort (note, the "other" section will be slightly different since some non-alphanumeric characters are before the numbers, others are between numbers and letters, and others still are after the letters. You can also remove grep's -i flag and additionally iterate through {A..Z} to be case sensitive).  Each individual iteration obviously still needs to be sorted, but hopefully they're manageable.

If the program exits before completing all iterations and saying "It worked" then you can edit the script with a more discrete batch for the last iteration it tried.  Remove all prior iterations since they're successfully saved in output.txt.

Title: Disk space required for unix sort

Body:
I'd batch it manually as described in this unix.SE answer.

Find some very basic queries that will divide your content into chunks that are small enough to be sorted.  For example, if it's a file of words, you could create queries like grep ^a …, grep ^b …, and so on.  Some items may need more granularity than others.

You can script that like:

#!/bin/bash
for char1 in other {0..9} {a..z}; do
  out="/tmp/sort.$char1.xz"
  echo "Extracting lines starting with '$char1'"
  if [ "$char1" = "other" ]; then char1='[^a-z0-9]'; fi
  grep -i "^$char1" *.txt |xz -c0 > "$out"
  unxz -c "$out" |sort -u >> output.txt || exit 1
  rm "$out"
done
echo "It worked"

I'm using xz -0 because it's almost as fast as gzip's default gzip -6 yet it's vastly better at conserving space.  I omitted it from the final output in order to preserve the exit value of sort -u, but you could instead use a size check (iirc, sort fails with zero output) and then use sort -u |xz -c0 >> output.txt.xz since the xz (and gzip) container lets you concatenate archives (I've written about that before too).

This works because the output of each grep run is already sorted (0 is before 1, which is before a, etc.), so the final assembly doesn't need to run through sort (note, the "other" section will be slightly different since some non-alphanumeric characters are before the numbers, others are between numbers and letters, and others still are after the letters. You can also remove grep's -i flag and additionally iterate through {A..Z} to be case sensitive).  Each individual iteration obviously still needs to be sorted, but hopefully they're manageable.

If the program exits before completing all iterations and saying "It worked" then you can edit the script with a more discrete batch for the last iteration it tried.  Remove all prior iterations since they're successfully saved in output.txt.


问:
SSRS returned data type not valid for the aggregate function
I am making a SSRS, when executing the query

```<code>SELECT Brand.[KeyOffer],
   COALESCE(SUM([Key Offer].Revenue),0) as Revenue
FROM [Brand Key Offer] Brand
LEFT JOIN [Key Offer] ON Brand.Keyoffer = [Key Offer].[Key Offer] AND [Key Offer].[Date] = '7/05/2017'
WHERE Brand.[Brand] = 'SMART'
GROUP BY [Brand].[KeyOffer]
ORDER BY [Revenue] DESC
</code>```

But when I preview the reprot, I get this warning message.

```<code>Warning     [rsAggregateOfInvalidExpressionDataType] The Value expression for the textrun ‘Textbox21.Paragraphs[0].TextRuns[0]’ uses an aggregate function with an expression that returned a data type not valid for the aggregate function.       c:\users\t-aordiz\documents\visual studio 2015\Projects\TelemarketingRS\TelemarketingRS\Telemarketing Revenue.rdl   0
</code>```

Ive been to a lot of topics but cant seem to find a way to solve this problem.

答:
It looks like the error is being caused by the call to SUM(), possibly because you are feeding it a non numeric type.  To test this, you could try casting [Key Offer].Revenue to decimal:

```<code>SELECT
    Brand.[KeyOffer],
    COALESCE(SUM(CAST([Key Offer].Revenue AS DECIMAL(10, 2))),0) AS Revenue
FROM [Brand Key Offer] Brand
...
</code>```

Body:
I am making a SSRS, when executing the query

SELECT Brand.[KeyOffer],
   COALESCE(SUM([Key Offer].Revenue),0) as Revenue
FROM [Brand Key Offer] Brand
LEFT JOIN [Key Offer] ON Brand.Keyoffer = [Key Offer].[Key Offer] AND [Key Offer].[Date] = '7/05/2017'
WHERE Brand.[Brand] = 'SMART'
GROUP BY [Brand].[KeyOffer]
ORDER BY [Revenue] DESC

But when I preview the reprot, I get this warning message.

Warning     [rsAggregateOfInvalidExpressionDataType] The Value expression for the textrun ‘Textbox21.Paragraphs[0].TextRuns[0]’ uses an aggregate function with an expression that returned a data type not valid for the aggregate function.       c:\users\t-aordiz\documents\visual studio 2015\Projects\TelemarketingRS\TelemarketingRS\Telemarketing Revenue.rdl   0

Ive been to a lot of topics but cant seem to find a way to solve this problem.

Body:
It looks like the error is being caused by the call to SUM(), possibly because you are feeding it a non numeric type.  To test this, you could try casting [Key Offer].Revenue to decimal:

SELECT
    Brand.[KeyOffer],
    COALESCE(SUM(CAST([Key Offer].Revenue AS DECIMAL(10, 2))),0) AS Revenue
FROM [Brand Key Offer] Brand
...


问:
Force ggplot scales to start on e.g. 1st of year, 1st of month etc
I'm looking for a way to force the date labels on a ggplot to start at a (seemingly) logical time. I've had the problem a number of times but my current problem is I want the breaks to be on the 01/01/yyyy
My data is a large dataset with POSIXct Date column, data to plot in Flow column and a number of site names in the Site column.

```<code>library(ggplot2)
library(scales)
ggplot(AllFlowData, aes(x=Date, y = Flow, colour = Site))+geom_line()+
scale_x_datetime(date_breaks = "1 year", expand =c(0,0),labels=date_format("%Y"))
</code>```

I can force the breaks to be every year and they appear okay without the labels=date_format("%Y") (starting on 01/01 each year) but if I include labels=date_format("%Y") (as there is 10 years of data so gets a bit messy) the date labels move to ~November, and 1989 is the first label even though my data starts on the 01/01/1990.

I have had this problem numerous times in the past on different time steps, such as wanting to force it to the 1st of the month or daily times to be at midnight instead during the day. Is there a generic way to do this?

I have looked at create specific date range in ggplot2 ( scale_x_date), but I do not want to have to hard code my breaks as I have a fair few plots to do with different date ranges.

Thanks

答:
If the dates come to you in a vector like:

```<code>dates <- seq.Date(as.Date("2001-03-04"), as.Date("2001-11-04"), by="day")
## "2001-03-04" "2001-03-05" "2001-03-06" ... "2001-11-03" "2001-11-04"
</code>```

use pretty.Dates() to make a best guess about the end points.

```<code>range(pretty(dates))
## "2001-01-01" "2002-01-01"
</code>```

Then pass this range to ggplot.

However, I recommend coord_cartesian() instead of scale_x_date().  Typically I want to crop the graphic bounds, instead of flat-out exclude the values entirely (which can mess up things like a loess summary).

Body:
I'm looking for a way to force the date labels on a ggplot to start at a (seemingly) logical time. I've had the problem a number of times but my current problem is I want the breaks to be on the 01/01/yyyy
My data is a large dataset with POSIXct Date column, data to plot in Flow column and a number of site names in the Site column.

library(ggplot2)
library(scales)
ggplot(AllFlowData, aes(x=Date, y = Flow, colour = Site))+geom_line()+
scale_x_datetime(date_breaks = "1 year", expand =c(0,0),labels=date_format("%Y"))

I can force the breaks to be every year and they appear okay without the labels=date_format("%Y") (starting on 01/01 each year) but if I include labels=date_format("%Y") (as there is 10 years of data so gets a bit messy) the date labels move to ~November, and 1989 is the first label even though my data starts on the 01/01/1990.

I have had this problem numerous times in the past on different time steps, such as wanting to force it to the 1st of the month or daily times to be at midnight instead during the day. Is there a generic way to do this?

I have looked at create specific date range in ggplot2 ( scale_x_date), but I do not want to have to hard code my breaks as I have a fair few plots to do with different date ranges.

Thanks

Body:
If the dates come to you in a vector like:

dates <- seq.Date(as.Date("2001-03-04"), as.Date("2001-11-04"), by="day")
## "2001-03-04" "2001-03-05" "2001-03-06" ... "2001-11-03" "2001-11-04"

use pretty.Dates() to make a best guess about the end points.

range(pretty(dates))
## "2001-01-01" "2002-01-01"

Then pass this range to ggplot.

However, I recommend coord_cartesian() instead of scale_x_date().  Typically I want to crop the graphic bounds, instead of flat-out exclude the values entirely (which can mess up things like a loess summary).


问:
Detection of rectangles using Hough Transformation. Encountered this error: 'NoneType' object has no attribute '__getitem__'
my code looks like this, getting NoneType error for lines[0] and not able to find why exactly its None type.:</p>

```<code>import numpy as np
import cv2

image=cv2.imread('img.jpg',0)
edges = cv2.Canny(img,50,150,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,200)
for rho,theta in lines[0]:   # Error was said to be in this line
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

cv2.line(img,(x1,y1),(x2,y2),(0,0,255),1)
cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

答:
It is possible that no lines were detected. Do check the result of cv2.Canny using cv2.imshow to see if any straight edges are there. The threshold parameter of HoughLines can be reduced to allow more lines to be detected.

Edit: I tested the code with the image that you sent. The threshold for HoughLines (200) was way too high, because the edges detected by Canny are usually not continuous. Given that the image is only 200 pixels high, I recommend a value between 50 and 100.

Herewith find the sample code after editing:

```<code>import numpy as np
import cv2

image=cv2.imread('/home/foo/Downloads/image_barcode.jpg',0)
edges = cv2.Canny(image,50,150,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,70) # used to be 200
for rho,theta in lines[0]:   # displays only the first line
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

cv2.line(image,(x1,y1),(x2,y2),(255,0,255),1)
cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Body:
my code looks like this, getting NoneType error for lines[0] and not able to find why exactly its None type.:

import numpy as np
import cv2

image=cv2.imread('img.jpg',0)
edges = cv2.Canny(img,50,150,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,200)
for rho,theta in lines[0]:   # Error was said to be in this line
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

cv2.line(img,(x1,y1),(x2,y2),(0,0,255),1)
cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Body:
It is possible that no lines were detected. Do check the result of cv2.Canny using cv2.imshow to see if any straight edges are there. The threshold parameter of HoughLines can be reduced to allow more lines to be detected.

Edit: I tested the code with the image that you sent. The threshold for HoughLines (200) was way too high, because the edges detected by Canny are usually not continuous. Given that the image is only 200 pixels high, I recommend a value between 50 and 100.

Herewith find the sample code after editing:

import numpy as np
import cv2

image=cv2.imread('/home/foo/Downloads/image_barcode.jpg',0)
edges = cv2.Canny(image,50,150,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,70) # used to be 200
for rho,theta in lines[0]:   # displays only the first line
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

cv2.line(image,(x1,y1),(x2,y2),(255,0,255),1)
cv2.imshow('image',image)
cv2.waitKey(0)
cv2.destroyAllWindows()


问:
forms appear poorly scaled at runtime
I have created a form in visual studio (vb.net winforms) and it looks great in designer however at runtime it appears extremely out of scale (on my computer only) - my computer is using resolution of 3840x2160 with DPI scaling of 250% - this is obviously the problem how do I make my application deal with this better?

I have tried using Autoscalemode, autosize, and autosizemode with the form only appearing more broken than it currently does.

Here is the appearance in designer:

Here is the appearance at runtime on my computer:

答:
Is your application DPI Aware? Read this article for more info: https://msdn.microsoft.com/en-us/library/windows/desktop/dn469266(v=vs.85).aspx

Basically you want to add this to your app.manifest inside the <asmv1:assembly> block:

```<code> <asmv3:application>
    <asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
      <dpiAware>true</dpiAware>
    </asmv3:windowsSettings>
  </asmv3:application>
</code>```

Title: forms appear poorly scaled at runtime

Body:
Is your application DPI Aware? Read this article for more info: https://msdn.microsoft.com/en-us/library/windows/desktop/dn469266(v=vs.85).aspx

Basically you want to add this to your app.manifest inside the <asmv1:assembly> block:

 <asmv3:application>
    <asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
      <dpiAware>true</dpiAware>
    </asmv3:windowsSettings>
  </asmv3:application>


问:
Selecting Parent's Child in jQuery
I think all I need is a selector, but can't find one. I want to select the anchor tag, but can only select the li using .parent()...

jQuery:

```<code>$("nav ul li > ul").parent().append('<span class="arrow">↓</span>');
</code>```

HTML:

```<code><li><a href="#">The Events</a>
  <ul>
    <li><a href="#">Schedule</a></li>
    <li><a href="#">Buy Tickets</a></li>
    <li><a href="#">Features</a></li>
  </ul>
</li>
</code>```

The code above puts the arrow on the right lis, but one level to high. I need to target the li's a tag.

答: Does this happen on clicking the link or onload?</p>

Title: Selecting Parent's Child in jQuery

Body:
I think all I need is a selector, but can't find one. I want to select the anchor tag, but can only select the li using .parent()...

jQuery:

$("nav ul li > ul").parent().append('↓');

HTML:

The Events

Schedule

Buy Tickets

Features

The code above puts the arrow on the right lis, but one level to high. I need to target the li's a tag.


问:
409 conflict error when i try mvn appengine:update
After i perform mvn appengine:devserver,
i set my project key using:
gcloud config set project {my-key}
 and i run mvn appengine:update, i receive this error ::::

com.google.appengine.tools.admin.HttpIoException: Error posting to URL: https://appengine.google.com/api/appversion/create?module=apol-web&app_id=apol-145566&version=1&
409 Conflict
Another transaction by user arokoyuolalekan is already in progress for app: e~apol-145566, version: 1. That user can undo the transaction with "appcfg rollback".

Please what do i do to solve it.

答:
409 error when you deploy your app means that there's already another deployment going on and you can't start another one, hence the conflict.
You can either use appcfg rollback to rollback your deployment, or wait till current deployment expires, it should take no more than an hour.

You can read more about appcfg tool on this page https://cloud.google.com/appengine/docs/standard/java/tools/appcfg-arguments


问:
Semantic-UI-React Footer
I've been learning ReactJS for the past couple of days and have been trying to build a website using semantic-ui-react in ReactJS. I understand there are components that one can use now but I am stuck on what to do in a scenario such as the creation of a footer... typically, in my raw HTML, I would have the semantic.min.css file included and at the bottom:

```<code>    <div class="ui inverted pink vertical footer segment">
        <div class="ui center aligned container">
            <h4 class="ui inverted header">© Copyright 2017 | All rights reserved | Blahhh</h4>
            <a href="https://www.facebook.com/"><i class="facebook square icon big"></i></a>
            <a href="https://twitter.com/"><i class="twitter square icon big"></i></a>
            <a href="https://www.linkedin.com/company/c"><i class="linkedin square icon big"></i></a>
        </div>
    </div>
</code>```

Now I want to translate this into semantic-ui-react. Footer is a class not a component in react by default so there's no component for it... Which I assume means I have to make my own component and basically write the code above. My problem now is that I don't know how to make it render as if I was using regular old semantic.min.css. I read somewhere to download the css file and include it, but one, I don't know where to (MyCustomFooterComponent or index.html), and in doing that, am I not increasing by load times on my website. Would this mean that everywhere there's a footer, just for one small section of custom code, the entire CSS file is going to be loaded?

Also, after building, would there be a double-import scenario from my addition of the Semantic CSS and semantic-ui-react's CSS?

Sorry for the long question but I'm new to this and I like to find out what I can before making a terrible mistake.

答:
If you are using react-semantic-ui then you already include 'the old semantic-ui.min.css' already. See here.

Hence, create a component and put those code in render(), change 'class' to 'className' and then use it.

Title: Semantic-UI-React Footer

Body:
I've been learning ReactJS for the past couple of days and have been trying to build a website using semantic-ui-react in ReactJS. I understand there are components that one can use now but I am stuck on what to do in a scenario such as the creation of a footer... typically, in my raw HTML, I would have the semantic.min.css file included and at the bottom:

© Copyright 2017 | All rights reserved | Blahhh

Now I want to translate this into semantic-ui-react. Footer is a class not a component in react by default so there's no component for it... Which I assume means I have to make my own component and basically write the code above. My problem now is that I don't know how to make it render as if I was using regular old semantic.min.css. I read somewhere to download the css file and include it, but one, I don't know where to (MyCustomFooterComponent or index.html), and in doing that, am I not increasing by load times on my website. Would this mean that everywhere there's a footer, just for one small section of custom code, the entire CSS file is going to be loaded?

Also, after building, would there be a double-import scenario from my addition of the Semantic CSS and semantic-ui-react's CSS?

Sorry for the long question but I'm new to this and I like to find out what I can before making a terrible mistake.


问:
How to test for situation where a specific library is missing in Python
I have some packages that have soft dependencies on other packages with a fall back to a default (simple) implementation.

The problem is that this is very hard to test for using unit tests. I could set up separate virtual environments, but that is hard to manage.

Is there a package or a way to achieve the following: have

```<code>import X
</code>```

work as usual, but

```<code>hide_package('X')
import X
</code>```

will raise an ImportError.

I keep having bugs creep into the fall-back part of my code because it is hard to test this.

答:
One way is to edit sys.path, especially if your packages install into different directories/zipfiles (e.g. if you are using eggs). Before importing, drop the ones you don't want from sys.path.

If that's not feasible (because all components live in a single sys.path entry), you can hack suppression into the packages themselves. E.g. have a global variable (environment, or something patched into the sys module) list the packages whose import you want to fail:

```<code>sys.suppressed_packages=set()
sys.suppressed_packages.add('X')
</code>```

Then, in each package, explicitly raise an ImportError:

```<code># X.py
import sys
if 'X' in sys.suppressed_packages:
    raise ImportError, 'X is suppressed'
</code>```

Of course, instead of using the sys module, you can make your own infrastructure for that, along with a hide_package function.

Body:
I have some packages that have soft dependencies on other packages with a fall back to a default (simple) implementation.

The problem is that this is very hard to test for using unit tests. I could set up separate virtual environments, but that is hard to manage.

Is there a package or a way to achieve the following: have

import X

work as usual, but

hide_package('X')
import X

will raise an ImportError.

I keep having bugs creep into the fall-back part of my code because it is hard to test this.

Body:
One way is to edit sys.path, especially if your packages install into different directories/zipfiles (e.g. if you are using eggs). Before importing, drop the ones you don't want from sys.path.

If that's not feasible (because all components live in a single sys.path entry), you can hack suppression into the packages themselves. E.g. have a global variable (environment, or something patched into the sys module) list the packages whose import you want to fail:

sys.suppressed_packages=set()
sys.suppressed_packages.add('X')

Then, in each package, explicitly raise an ImportError:

# X.py
import sys
if 'X' in sys.suppressed_packages:
    raise ImportError, 'X is suppressed'

Of course, instead of using the sys module, you can make your own infrastructure for that, along with a hide_package function.


问:
consume rabbitmq messages hosted locally
I have set-up a clustered local rabbitmq(cluster of 3 nodes) through docker. On the rabbitmq management UI, I am able to successfully create exchanges/queues, and publish messages.
My problem is, on the same UI I do not see the option to create any consumer, so my messages are published but do not show up in acknowledged or delivered state.
Attached below is the screenshot for one of the queues, where you can see No Consumer.

I am new to rabbitmq so probably I have misunderstood the concept of consumer(or how to configure one)
Would really appreciate anyone suggesting how to configure the consumer to a queue through this UI

答: The fact is you cannot configure a consumer throw the Management UI. Consumer can be described as an application/client that receives and consumes message from certain queue. To consume message, you may need to write your own consumer code. Check here for more information. Hope this is helpful for you :)</p>


问:
session modify from webmethod
is it possible to modify a session from a webmethod, well the complete description is,

I have a button that client side triggered to add data from textboxes into one new row inside a session

The session declared as

```<code>public List<Some_Business_Object_Here> A_Session
{
            get
            {
                return (List<Some_Business_Object_Here>)Session["Session_Name_Here"];
            }
            set
            {
                Session["Session_Name_Here"] = value;
            }
}
</code>```

and The WebMethod

```<code>[WebMethod]
public static string InsertItemDt(List<string> dataIns)
{
            BOResponse objRes = new BOResponse();
            SomeFormHere form = new SomeFormHere();

            Some_Business_Object_Here objDet = new Some_Business_Object_Here();
            objDet.Data1 = dataIns[0];
            objDet.Data2 = Convert.ToInt32(dataIns[1]);
            objDet.Data3 = Convert.ToDecimal(dataIns[2]);

            objRes = form.A_Processing_Method(objDet, ListItemDetail);

            return new JavaScriptSerializer().Serialize(objRes);
}
</code>```

and if the method processing to add a new row after some validation

is it possible to do it with this kind of method?

Edit: BOResponse is object for validation, containing only error code and catch error message

so the method be like

```<code> Private BOResponse A_Processing_Method (Some_Business_Object_Here obj)
{
    try
    {
       (Some Validation Here...)

       if (!validation)
       {
          MsgCode = 10;
          MsgDesc = "Some Custom Error Text Here"
       }
       else
       {
           A_Session.Add(obj);
       }
    }
    catch (Exception err)
    {
       MsgCode = 20;
       MsgDesc = err.Message;
    }
}
</code>```

答: nevermind, seems it's working this way</p>

Title: session modify from webmethod

Body:
is it possible to modify a session from a webmethod, well the complete description is,

I have a button that client side triggered to add data from textboxes into one new row inside a session

The session declared as

public List<Some_Business_Object_Here> A_Session
{
            get
            {
                return (List<Some_Business_Object_Here>)Session["Session_Name_Here"];
            }
            set
            {
                Session["Session_Name_Here"] = value;
            }
}

and The WebMethod

[WebMethod]
public static string InsertItemDt(List<string> dataIns)
{
            BOResponse objRes = new BOResponse();
            SomeFormHere form = new SomeFormHere();

            Some_Business_Object_Here objDet = new Some_Business_Object_Here();
            objDet.Data1 = dataIns[0];
            objDet.Data2 = Convert.ToInt32(dataIns[1]);
            objDet.Data3 = Convert.ToDecimal(dataIns[2]);

            objRes = form.A_Processing_Method(objDet, ListItemDetail);

            return new JavaScriptSerializer().Serialize(objRes);
}

and if the method processing to add a new row after some validation

is it possible to do it with this kind of method?

Edit: BOResponse is object for validation, containing only error code and catch error message

so the method be like

 Private BOResponse A_Processing_Method (Some_Business_Object_Here obj)
{
    try
    {
       (Some Validation Here...)

       if (!validation)
       {
          MsgCode = 10;
          MsgDesc = "Some Custom Error Text Here"
       }
       else
       {
           A_Session.Add(obj);
       }
    }
    catch (Exception err)
    {
       MsgCode = 20;
       MsgDesc = err.Message;
    }
}

Body: nevermind, seems it's working this way


问:
Ensure value of @Input() extends a common interface?
Is it possible to ensure that an object instance passed via @Input() extends from a common interface?

I currently have:

```<code>@Input()
associatedObject: IDocument | IOrganization;
</code>```

but it would be nicer to have something like:

```<code>@Input()
associatedObject: <T extends ICommonInterface>;
</code>```

so I don't have to add new types in the future, provided the instance passes the interface check.

答:
I ended up just using the extended interface as the @Input() type, which is working well for now.

```<code>@Input()
associatedObject: ICommonInterface;
</code>```

Body:
Is it possible to ensure that an object instance passed via @Input() extends from a common interface?

I currently have:

@Input()
associatedObject: IDocument | IOrganization;

but it would be nicer to have something like:

@Input()
associatedObject: <T extends ICommonInterface>;

so I don't have to add new types in the future, provided the instance passes the interface check.

Body:
I ended up just using the extended interface as the @Input() type, which is working well for now.

@Input()
associatedObject: ICommonInterface;


问:
How to prevent need for rebuilding app after changing Language/Region
The issue happens at XCode>'Build and run',

not when running it in 'Instruments > Leaks'.
So it seems an issue with Xcode.

If that is the case, I don't mind doing an extra rebuild.

However, if issue will also happen after app is posted in iTunes app store,

and customer installs the app in her device,

she would have to reinstall the app every time she changes language/region.

(needles to say, that would not be acceptable).

Is this issue:

    a) just in Xcode (not in app store)?

    b) not experienced by other developers, so likely is a bug in the app ? or

    c) likely to surface even when app is installed by downloading from app store?

If 'b' or 'c', any ideas how to fix it?

----------------Steps to reproduce issue-----------------

During development:

  1) Do a Xcode>'Build and run', verify app works as expected (in either simulator or device);

  2) Change Language and Region (in the iPhone's 'Settings>General>International')

  3) Verify:

     -Console shows the non-informative error:

                    Program received signal:  “SIGKILL”.

     -App crashes in the background,

     -Clicking app's icon icon no longer launches the app

          (apps' default screen displays for a second, then crashes)

  4) Do another 'Build and run'

  5) verify now app launches and works well

    (in the new language and region as expected. So app's localization strings etc work ok).

6) Do a 'Run with Performance Tool > Leaks'

  7) Change Language and Region (in the iPhone's 'Settings')

  8) verify no issue.

That is:

     Instruments tracking  interrupts (no crashes in app or in tool), and

     user can relaunch the app in iPhone as usual (steps 3 and 4 are eliminated).

答:
SOLUTION: Issue was in the app.

It was storing a localized value in .plist and using that value for comparison.

When language was changed, the value in .plist remained in the old language, so comparison (with value in new language) failed.

Fixed by using  language-independent values in .plist and comparison.


问:
Return Content with alert in Controller
I'm trying to somewhat replicate what I saw in this question, particularly in this answer, but not quite the same.
My intent is, if the zip has no files (it can happen because the folder could be empty) I want to return an alert just so the user is warned that is not possible to obtain the file at the time.
But I'm missing on the redirection point, I don't want the alert to redirect the user to a blank page refering the Action, I want it to stay in the page, also due to some filters.
Is this possible? I couldn't find anything that would stop the redirection from happening.

Here is my the Action Controller code:

```<code>public ActionResult DownloadZip(List<int> things)
    {
        // Create zip with files

        if (!zip.Any())
        {
            return Content(@"<script language='javascript' type='text/javascript'>
                     alert('Message');
                     </script>
                  ");
        }

        // Return zip
    }
</code>```

Here is the call from the view:

```<code>$("#btnExportToZip").on("click", function (e) {

    var grid = $("#gridThings").data("kendoGrid");
    var items = grid.dataSource.data();
    var lstIds = [];
    $.each(items, function (index, elem) {
        if (elem.Checked) {
            lstIds.push(elem.Id);
        }
    });

    if (lstIds.length > 0) {
        var params = lstIds.join("&listAmostras=")
        var url = '/Search/DownloadZip?listAmostras=' + params;

        window.location.href = url;
    }
});
</code>```

答:
As per my understanding, alert is redirect the user to the blank page because in the javascript you have the line window.location.href = url; which might be redirect to the same action again which shows the alert.

So try to give the different url to the window.location.href

for ex:window.location.href = '../somecontroller/someaction';

thanks

Karthik

Title: Return Content with alert in Controller

Body:
I'm trying to somewhat replicate what I saw in this question, particularly in this answer, but not quite the same.
My intent is, if the zip has no files (it can happen because the folder could be empty) I want to return an alert just so the user is warned that is not possible to obtain the file at the time.
But I'm missing on the redirection point, I don't want the alert to redirect the user to a blank page refering the Action, I want it to stay in the page, also due to some filters.
Is this possible? I couldn't find anything that would stop the redirection from happening.

Here is my the Action Controller code:

public ActionResult DownloadZip(List<int> things)
    {
        // Create zip with files

        if (!zip.Any())
        {
            return Content(@"
                  ");
        }

        // Return zip
    }

Here is the call from the view:

$("#btnExportToZip").on("click", function (e) {

    var grid = $("#gridThings").data("kendoGrid");
    var items = grid.dataSource.data();
    var lstIds = [];
    $.each(items, function (index, elem) {
        if (elem.Checked) {
            lstIds.push(elem.Id);
        }
    });

    if (lstIds.length > 0) {
        var params = lstIds.join("&listAmostras=")
        var url = '/Search/DownloadZip?listAmostras=' + params;

        window.location.href = url;
    }
});


问:
Should I pin my Python dependencies versions?
I am about to release a Python library I've been working on the past few weeks. I've read a lot about Python dependencies but something is not quite clear yet:

Some people pretend you should never pin your dependencies versions as it would prevent the users of your library from upgrading those dependencies.

Some other claim that you should always pin your dependencies versions as it is the only way of guaranteeing that your release works the way it did when you developed it and to prevent that a breaking change in a dependency wreaks havoc in your library.

I somehow went for an hybrid solution, where I assumed my dependencies used semantic versioning  and pinned only the major version number (say somelib >= 2.3.0, < 3) except when the major version number is 0 (semantic versioning dictates that such versions are to be considered volatile and may break the API even if only the patch number is bumped).

As of now, I'm not sure which way is the best. Is there an official guideline (even a PEP perhaps ?) that dictates the best practice regarding Python dependencies and how to specify them ?

答:
The reason the two other answers contradict each other is that they're both right (and worth reading), but they apply to different situations.

If you're releasing a library on PyPI, you should declare whatever dependencies you know about, but not pin to a specific version. For example, if you know you need >= 1.2, but 1.4 is broken, then you can write something like somepkg >= 1.2, != 1.4. If one of the things you know is that somepkg follows SemVer, then you can add a < 2.

If you're building something like a web app that you deploy yourself, then you should pin all of your exact dependencies, and use a service like pyup.io or requires.io to notify you when new versions are released. This way you can stay up to date, while making sure that the versions you deploy are the same as the versions you tested against.

Notice that these two pieces of advice complement each other: it's just a fact that if app A uses library B, then either the author of A or the author of B can pin B's dependencies, but not both. So we have to pick one. The underlying principle here is that this is best done as late as possible, i.e., by the author of A, who can see their whole system; the job of library B is to pass on some useful hints to help A make these decisions. In particular, if all of the libraries that A depends on record exactly what they know about their underlying dependencies, then it's possible for A to make sensible decisions about what to do when they overlap. Like if dependency B depends on requests >= 1.0, != 1.2, and dependency C depends on requests >= 1.1, then we can guess that 1.1 or 1.3 might be good versions to pin. If dependency B depends on requests == 1.1 and dependency C depends on requests == 1.2, then we're just stuck.

ContentLicense: CC BY-SA 4.0


问:
Port field from NULLABLE to REQUIRED in BigQuery
I am trying to move a BigQuery table to a new schema that has some additional new NULLABLE fields and in which a field f has become REQUIRED (they were NULLABLE in the old schema.)

I tried to update the table with the new schema through the command

bq update
 <new_schema>

and I get the error

BigQuery error in update operation: Provided Schema does not match Table

As a second attempt, I created a temporary empty table with the new field and then tried to append there the data coming from a query (SELECT * from the old table), but I get the error:

Invalid schema update. Field f has changed mode from REQUIRED to NULLABLE

Is there a way to do this migration easily? Of course I am fine with ignoring rows of the table where the field f is actually NULL. It would be cool if BigQuery could infer that from the query. I tried to do

SELECT * FROM old_table WHERE f IS NOT NULL

and append the result to the table with the new schema, but that doesn't work.

答:
Use second approach - create new table and append data there.
But use StandardSQL dialect. It will avoid "changed mode" error.
If you are trying to insert NULL, the query would still fail, of course.


问:
Is it possible to listen for function calls in C# (i.e. treat C# function calls as events)?
I would like to log when functions in my app are called. Is there a way I can listen for functions called and run code on such events?

If so, where do I start looking at how to do this?

答:
Just do the work to insert your logging directly where you want it.

```<code>public class MyClass
{
    private ILogger _logger;

    public MyClass(ILogger logger)
    {
        _logger = logger;
    }

    public void DoSomething()
    {
        logger.Information("Something happened");
    }
}
</code>```

This will allow you to customize the logging needs to your class - especially if you use something like Serilog in concert with SEQ.

I doubt the Aspect Oriented Logging approach will really allow you to get a nice useful semantic logging experience.

Body:
Just do the work to insert your logging directly where you want it.

public class MyClass
{
    private ILogger _logger;

    public MyClass(ILogger logger)
    {
        _logger = logger;
    }

    public void DoSomething()
    {
        logger.Information("Something happened");
    }
}

This will allow you to customize the logging needs to your class - especially if you use something like Serilog in concert with SEQ.

I doubt the Aspect Oriented Logging approach will really allow you to get a nice useful semantic logging experience.


问:
How to create dynamic views programmatically with a good OO-design
I am facing a problem with creation of dynamic view in Swift. However, the problem is not directly related to Swift itself, it is rather a Object-Oriented programming problem.

The problem is that I need to be able to add additional view elements to a view dynamically. And I am not sure if I'm doing it correctly. My solutions seems as overkill to me.

To solve the problem I thought Decorator pattern would be a good candidate. Additionally to have more control of the flow, I have introduced Template Method pattern.

I have a number of classes that define default look and feel on certain view controls like Labels, TextFields and Buttons. Here below you can see an approximate idea of how it is.

Here is my code:

```<code>class ViewElement{
// this class inherits from default UIKit elemnts and provides default UI view
}
// default cell is the cell that implements default elements layout and margings, etc
class DefaultCell: UITableViewCell {
    let mainStack: UIViewStack
    func addElement(ViewElement)
}

class BlueCell: DefaultCell {

    let textField1: TextField
    let label : Label
    let button: Button

    init(){
        textField = TextField()
        label = Label()
        button = Button()

        addElement(textField)
        addElement(label)
        addElement(button)
    }
}
</code>```

Here is the tableViewDataSource implementation

```<code>class BlueTable: UITableViewDataSource {
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    switch weather {
        case good:

            labelOne
            labelTwo
            buttonOne

            cell.addElement(labelOne)
            cell.addElement(labelTwo)
            cell.addElement(buttonOne)

        case bad:
            // idem
            cell.addView(badWeatherView)
    }
    return cell
    }

}
</code>```

As you can see, the greater the number of conditions, the bigger my switch statement.

Additional problem arises from the fact that I will need to access the additional elements that I assign in the condition, like callbacks, tap events etc. Also the fact that those elements in conditional are added via addElement method, means that those elements will be added at the bottom of the mainStack.

In order to have control over the way elements are added to the stack I decided to go with the following solution: Template Method pattern

```<code>protocol OrderableElements {
    func top()
    func middle()
    func bottom()
}

extension OrderableElements {
    func render() {
        top()
        middle()
        bottom()
    }
}
</code>```

Now the BlueCell implements the protocol and looks like this

```<code>class BlueCell: DefaultCell, OrderableElements {

    init(){
        textField = TextField()
        label = Label()
        button = Button()
    }

    func top() {
        addElement(textField)
    }

    func middle() {
        addElement(label)
    }

    func bottom(){
        addElement(button)
    }
}
</code>```

The tabledatasource class will then look as follows:

```<code>class BlueTable: UITableViewDataSource {
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    switch weather {
        case good:

            labelOne
            labelTwo
            buttonOne

            cell.addElement(labelOne)
            cell.addElement(labelTwo)
            cell.addElement(buttonOne)

        case bad:
            // idem
            cell.addView(badWeatherView)
    }

    ...
    **cell.render()**
    return cell

    }
}
</code>```

Now because I need to add the new view elements in certain location or better said, at certain moments in during the scope of BlueCell, I introduced Decorators for the cell, like this:

```<code>class CellDecorator: OrderableElements {
    var cell: BlueCell
    init(cell: BlueCell){
        self.cell = cell
    }

    func top() {
        self.cell.top()
    }

    func middle(){
        self.cell.middle()
    }

    func bottom(){
        self.cell.bottom()
    }

    func getCell() {
        return self.cell
    }

}
</code>```

Here is the concrete implementation

```<code>class GoodWeatherDecorator: CellDecorator {

    let goodLabel
    let goodTextField
    let goodButton

    override top() {
        super.top()
        addElement(goodLabel)
    }

    override middle(){
        super.middle()
        addElement(goodTextfield)
    }

    override bottom(){
        super.bottom()
        addElement(goodButton)
    }

}
</code>```

The final implementation of the cellForRowAt method looks like below:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    var decoratedCell = CellDecorator(cell: cell)

    switch weather {

        case good:
            decoratedCell = GoodWeatherDecorator(cell: cell)
        case bad:
            decoratedCell = BadWeatherDecorator(cell: cell)

    }

    decoratedCell.configure() // <------------ here is the configure call
    cell = decoratedCell.getCell() // <------- here I get cell from the decorator

    return cell

    }

}
</code>```

Now I do understand that my implementation of the decorator pattern is not 100% valid, because I don't inherit from the BlueCell class, for example. But that does not bother me that much. The things that bothers me is that I think that this solution to the problem is kind of overkill.

All works the right way, but I can help the feeling of having done too much to solve this trivial problem.

What do you think? How would you solve this kind of problem?

Thanks in advace

答:
You should follow Daniel T.'s answer.

But here's a suggested upgrade that I use on my own projects.

Instead of just using

```<code>protocol ConfigurableCell {
    func configure(with weather: Weather)
}
</code>```

I use this for reusability purposes in many different scenarios.

```<code>protocol Configurable {
    associatedtype Initializables

    func configure(_ model: Initializables) -> Self
}
</code>```

Example use cases:

UIViewController

```<code>class SomeViewController: UIViewController {
    var someIntProperty: Int?
    ...
}

extension SomeViewController: Configurable {
    struct Initializables {
        let someIntProperty: Int?
    }

    func configure(_ model: SomeViewController.Initializables) -> Self {
        self.someIntProperty = model.someIntProperty
        return self
    }
}

// on some other part of the code.
let someViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as! SomeViewController
_ = someViewController.configure(SomeViewController.Initializables(someIntProperty: 100))
</code>```

UITableViewCell

```<code>class SomeTableViewCell: UITableViewCell {
    var someIntProperty: Int?
    var someStringProperty: Int?
    ...
}

extension SomeTableViewCell: Configurable {
    struct Initializables {
        let someIntProperty: Int?
        let someStringProperty: Int?
    }

    func configure(_ model: SomeTableViewCell.Initializables) -> Self {
        self.someIntProperty = model.someIntProperty
        self.someStringProperty = model.someStringProperty
        return self
    }
}

// on cellForRow
let cell = tableView.dequeueReusableCell(withIdentifier: "SomeTableViewCell", for: indexPath) as! SomeTableViewCell
return cell.configure(SomeTableViewCell.Initializables(someIntProperty: 100, someStringProperty: "SomeString"))
</code>```

Notes:

As you can see it's very reusable and easy to use and implement. Downside is the code generated could be long when using configure

Body:
I am facing a problem with creation of dynamic view in Swift. However, the problem is not directly related to Swift itself, it is rather a Object-Oriented programming problem.

The problem is that I need to be able to add additional view elements to a view dynamically. And I am not sure if I'm doing it correctly. My solutions seems as overkill to me.

To solve the problem I thought Decorator pattern would be a good candidate. Additionally to have more control of the flow, I have introduced Template Method pattern.

I have a number of classes that define default look and feel on certain view controls like Labels, TextFields and Buttons. Here below you can see an approximate idea of how it is.

Here is my code:

class ViewElement{
// this class inherits from default UIKit elemnts and provides default UI view
}
// default cell is the cell that implements default elements layout and margings, etc
class DefaultCell: UITableViewCell {
    let mainStack: UIViewStack
    func addElement(ViewElement)
}

class BlueCell: DefaultCell {

    let textField1: TextField
    let label : Label
    let button: Button

    init(){
        textField = TextField()
        label = Label()
        button = Button()

        addElement(textField)
        addElement(label)
        addElement(button)
    }
}

Here is the tableViewDataSource implementation

class BlueTable: UITableViewDataSource {
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    switch weather {
        case good:

            labelOne
            labelTwo
            buttonOne

            cell.addElement(labelOne)
            cell.addElement(labelTwo)
            cell.addElement(buttonOne)

        case bad:
            // idem
            cell.addView(badWeatherView)
    }
    return cell
    }

}

As you can see, the greater the number of conditions, the bigger my switch statement.

Additional problem arises from the fact that I will need to access the additional elements that I assign in the condition, like callbacks, tap events etc. Also the fact that those elements in conditional are added via addElement method, means that those elements will be added at the bottom of the mainStack.

In order to have control over the way elements are added to the stack I decided to go with the following solution: Template Method pattern

protocol OrderableElements {
    func top()
    func middle()
    func bottom()
}

extension OrderableElements {
    func render() {
        top()
        middle()
        bottom()
    }
}

Now the BlueCell implements the protocol and looks like this

class BlueCell: DefaultCell, OrderableElements {

    init(){
        textField = TextField()
        label = Label()
        button = Button()
    }

    func top() {
        addElement(textField)
    }

    func middle() {
        addElement(label)
    }

    func bottom(){
        addElement(button)
    }
}

The tabledatasource class will then look as follows:

class BlueTable: UITableViewDataSource {
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    switch weather {
        case good:

            labelOne
            labelTwo
            buttonOne

            cell.addElement(labelOne)
            cell.addElement(labelTwo)
            cell.addElement(buttonOne)

        case bad:
            // idem
            cell.addView(badWeatherView)
    }

    ...
    **cell.render()**
    return cell

    }
}

Now because I need to add the new view elements in certain location or better said, at certain moments in during the scope of BlueCell, I introduced Decorators for the cell, like this:

class CellDecorator: OrderableElements {
    var cell: BlueCell
    init(cell: BlueCell){
        self.cell = cell
    }

    func top() {
        self.cell.top()
    }

    func middle(){
        self.cell.middle()
    }

    func bottom(){
        self.cell.bottom()
    }

    func getCell() {
        return self.cell
    }

}

Here is the concrete implementation

class GoodWeatherDecorator: CellDecorator {

    let goodLabel
    let goodTextField
    let goodButton

    override top() {
        super.top()
        addElement(goodLabel)
    }

    override middle(){
        super.middle()
        addElement(goodTextfield)
    }

    override bottom(){
        super.bottom()
        addElement(goodButton)
    }

}

The final implementation of the cellForRowAt method looks like below:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    var decoratedCell = CellDecorator(cell: cell)

    switch weather {

        case good:
            decoratedCell = GoodWeatherDecorator(cell: cell)
        case bad:
            decoratedCell = BadWeatherDecorator(cell: cell)

    }

    decoratedCell.configure() // <------------ here is the configure call
    cell = decoratedCell.getCell() // <------- here I get cell from the decorator

    return cell

    }

}

Now I do understand that my implementation of the decorator pattern is not 100% valid, because I don't inherit from the BlueCell class, for example. But that does not bother me that much. The things that bothers me is that I think that this solution to the problem is kind of overkill.

All works the right way, but I can help the feeling of having done too much to solve this trivial problem.

What do you think? How would you solve this kind of problem?

Thanks in advace

Body:
You should follow Daniel T.'s answer.

But here's a suggested upgrade that I use on my own projects.

Instead of just using

protocol ConfigurableCell {
    func configure(with weather: Weather)
}

I use this for reusability purposes in many different scenarios.

protocol Configurable {
    associatedtype Initializables

    func configure(_ model: Initializables) -> Self
}

Example use cases:

UIViewController

class SomeViewController: UIViewController {
    var someIntProperty: Int?
    ...
}

extension SomeViewController: Configurable {
    struct Initializables {
        let someIntProperty: Int?
    }

    func configure(_ model: SomeViewController.Initializables) -> Self {
        self.someIntProperty = model.someIntProperty
        return self
    }
}

// on some other part of the code.
let someViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as! SomeViewController
_ = someViewController.configure(SomeViewController.Initializables(someIntProperty: 100))

UITableViewCell

class SomeTableViewCell: UITableViewCell {
    var someIntProperty: Int?
    var someStringProperty: Int?
    ...
}

extension SomeTableViewCell: Configurable {
    struct Initializables {
        let someIntProperty: Int?
        let someStringProperty: Int?
    }

    func configure(_ model: SomeTableViewCell.Initializables) -> Self {
        self.someIntProperty = model.someIntProperty
        self.someStringProperty = model.someStringProperty
        return self
    }
}

// on cellForRow
let cell = tableView.dequeueReusableCell(withIdentifier: "SomeTableViewCell", for: indexPath) as! SomeTableViewCell
return cell.configure(SomeTableViewCell.Initializables(someIntProperty: 100, someStringProperty: "SomeString"))

Notes:

As you can see it's very reusable and easy to use and implement. Downside is the code generated could be long when using configure


问:
Does throwing an Exception have to cause the program to terminate
Does throwing an Exception have to cause the program to terminate?

I think its no, I just want to make sure

答: Failing to catch an exception will likely cause the program to terminate, but the act of throwing one will not.  At the very least, any application should have some kind of last line of defense for catching all otherwise unhandled exceptions and handling them (even if handling them means, for some at least, throwing them outside of the application and terminating because something external to the application expects this).</p>


问:
How do I use a form to change the SQL query to only display registered dates between a specific range?
The code below is what I have so far, if anyone has any knowledge of how BETWEEN works and could point me in the right direction I would really appreciate it.</p>

```<code><form action="index.php" method="GET">
    Starting from:<br>
    <input type="date" name="startDate" ><br><br>
    Upto:<br>
    <input type="date" name="uptoDate" ><br><br>
    <input type="submit">
</form>

<?php
    // I removed the connection details for obvious reasons
    // It does connect and display the data with no problems
    $startingFrom = $_GET[startDate];
    $upto = $_GET[uptoDate];

    // I tried this but it does not seem to work
    // $query = "SELECT * FROM table BETWEEN $startingFrom AND $upto";
    $query = "SELECT * FROM table";
    $result = mysql_query($query);

    echo "<table><th>Name</th><th>Registered Date</th>";

    while($row = mysql_fetch_array($result)){
        echo "<tr><td>" . $row['name'] . "</td><td>" . $row['registered'] . "</td></tr>";
    }
    echo "</table>";
    mysql_close();
?>
</code>```

答:
Your query should be:</p>

```<code>select * from table where registered >= $startDate and registered <= $endDate;
</code>```

Body:
The code below is what I have so far, if anyone has any knowledge of how BETWEEN works and could point me in the right direction I would really appreciate it.

<form action="index.php" method="GET">
    Starting from:

    <input type="date" name="startDate" >

    Upto:

    <input type="date" name="uptoDate" >

    <input type="submit">
</form>

<?php
    // I removed the connection details for obvious reasons
    // It does connect and display the data with no problems
    $startingFrom = $_GET[startDate];
    $upto = $_GET[uptoDate];

    // I tried this but it does not seem to work
    // $query = "SELECT * FROM table BETWEEN $startingFrom AND $upto";
    $query = "SELECT * FROM table";
    $result = mysql_query($query);

    echo "
Name	Registered Date	";

    while($row = mysql_fetch_array($result)){
        echo "
" . $row['name'] . "	" . $row['registered'] . "
";
    }
    echo "
";
    mysql_close();
?>

Body:
Your query should be:

select * from table where registered >= $startDate and registered <= $endDate;