问:
Incremental Learning in Scikit with PassiveAggressiveClassifier's partial_fit
I'm trying to train a PassiveAggressiveClassifier using TfidVectorizer with partial_fit technique in the script below:

Code Updated:

```<code>a, ta = [], []
r, tr = [], []
g = []

vect = HashingVectorizer(ngram_range=(1,4))
model = PassiveAggressiveClassifier()
with open('files', 'rb') as f:
    for line in f:
        line = line.strip()
        with open('gau-' + line + '.csv', 'rb') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                res = row['gau']
                g.append(res)

        cls = np.unique(g)
        print(len(cls))

        with open('gau-' + line + '.csv', 'rb') as csvfile:
            reader = csv.DictReader(csvfile)
            i = 0
            j = True
            for row in reader:
                arr = row['text']
                res = row['gau']
                a.append(arr)
                if(len(res) > 0):
                    r.append(int(res))
                i = i + 1

                if i % 400 == 0:
                    training_set = vect.fit_transform(a)
                    print(training_set.shape)
                    training_result = np.array(r)
                    model = model.partial_fit(
                        training_set, training_result, classes=cls)
                    a, r, i = [], [], 0

        print(model)
        testing_set = vect.transform(ta)
        testing_result = np.array(tr)
        predicted = model.predict(testing_set)

        print "Result to be predicted: "+testing_result
        print "Prediction: "+predicted
</code>```

There are multiple CSV files each containing 4k-5k records and I am trying to fit 400 records at a time using the partial_fit function. When I ran this code, I ran into the following error:

```<code>Result to be predicted: 1742
Prediction: 2617
</code>```

How do I resolve this issue?  The records in my CSV files are of variable length.

UPDATE:

Replacing TfidVectorizer with HashingVectorizer, I successfully created my model, but now while executing prediction on my test data the predictions generated were all incorrect.
My training data contains millions of lines of csv files and each line contains at most 4k-5k words of text.

So Is there any problem with my approach i.e. can these algorithms can be used with my data?

答:
For those who HashingVectorizer doesn't meet their needs, see a possible alternative in my answer to this related question here. It's basically a custom implementation of partial_fit for TfidfVectorizer and CountVectorizer.

Two comments relating to the specific discussion here:

OP's issue requires that the dimension of the output vector be identical after every call of partial_fit. In general it is expected that every Scikit-Learn estimator that implements partial_fit be able to work within a pipeline after that partial_fit is called, so for vectorizers this means not changing the output dimension since other estimators in the pipeline may not necessarily be able to handle the change. I think this is why partial_fit has not yet been implemented in Scikit-Learn for these vectorizers (see discussion on an active PR), since partial_fit will presumably update the vocabulary which will definitely change the output dimension.

So the solution proposed by my answer (a partial_fit method for TfidfVectorizer) would only solve the first part of OP's needs which is incremental learning. To solve the second part it may be possible to pad the output sequence with zeros into a predetermined vector. It's not ideal, since it would fail when the vocabulary exceeds that limit.

Body:
I'm trying to train a PassiveAggressiveClassifier using TfidVectorizer with partial_fit technique in the script below:

Code Updated:

a, ta = [], []
r, tr = [], []
g = []

vect = HashingVectorizer(ngram_range=(1,4))
model = PassiveAggressiveClassifier()
with open('files', 'rb') as f:
    for line in f:
        line = line.strip()
        with open('gau-' + line + '.csv', 'rb') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                res = row['gau']
                g.append(res)

        cls = np.unique(g)
        print(len(cls))

        with open('gau-' + line + '.csv', 'rb') as csvfile:
            reader = csv.DictReader(csvfile)
            i = 0
            j = True
            for row in reader:
                arr = row['text']
                res = row['gau']
                a.append(arr)
                if(len(res) > 0):
                    r.append(int(res))
                i = i + 1

                if i % 400 == 0:
                    training_set = vect.fit_transform(a)
                    print(training_set.shape)
                    training_result = np.array(r)
                    model = model.partial_fit(
                        training_set, training_result, classes=cls)
                    a, r, i = [], [], 0

        print(model)
        testing_set = vect.transform(ta)
        testing_result = np.array(tr)
        predicted = model.predict(testing_set)

        print "Result to be predicted: "+testing_result
        print "Prediction: "+predicted

There are multiple CSV files each containing 4k-5k records and I am trying to fit 400 records at a time using the partial_fit function. When I ran this code, I ran into the following error:

Result to be predicted: 1742
Prediction: 2617

How do I resolve this issue?  The records in my CSV files are of variable length.

UPDATE:

Replacing TfidVectorizer with HashingVectorizer, I successfully created my model, but now while executing prediction on my test data the predictions generated were all incorrect.
My training data contains millions of lines of csv files and each line contains at most 4k-5k words of text.

So Is there any problem with my approach i.e. can these algorithms can be used with my data?


来源: stackexchange

问:
MySQL ordering by a nextid column
I'm trying to pull some info out of a Moodle database.

There is one part that has a list of questions that you can order in whatever way you want through the Moodle interface.

However, the way it stores this in the database is making it hard for me to make a custom query that orders these items in the same manner outside of the moodle interface.

So there is a column ID, then a column NEXTPAGEID.

Here are the first 5 rows in the SQL to give you an example of what I need:

ID: 1; NEXTPAGEID: 3

ID: 3; NEXTPAGEID: 118

ID: 9; NEXTPAGEID: 10

ID: 10; NEXTPAGEID: 515

ID: 11; NEXTPAGEID: 12

So the order I really need is ID: 1, 3, 118, (whatever the NEXTPAGEID of 118 is), etc.

So is this possible in SQL or do I have to deal with it in the PHP when I output this query?

答: No, you can't.  You'll have to do it in PHP.</p>

ContentLicense: CC BY-SA 2.5

Title: MySQL ordering by a nextid column


答:
One approach:</p>

```<code>library(splitstackshape)
# separate multi observation lines into multiple columns
df2 <- cSplit(df, splitCols='X__1', sep=';')
# put in a long format for easier processing
df3 <- na.omit(data.frame(melt(as.data.frame(df2),measure=names(df2))))

# extractions
# account id
df3$id <- with(df3,gsub(x=value,pattern="^(.*) [[:punct:]](.*)-(.*)[[:punct:]]$",replacement='\\1'))
# start range
df3$begin <- with(df3,gsub(x=value,pattern="^(.*) [[:punct:]](.*)-(.*)[[:punct:]]$",replacement='\\2'))
# end range
df3$end <- with(df3,gsub(x=value,pattern="^(.*) [[:punct:]](.*)-(.*)[[:punct:]]$",replacement='\\3'))
# accounts with multiple:
df3$mult_id <- as.numeric(with(df3,gsub(x=variable,pattern="^X__1_(.*)$",replacement='\\1')))

# apparently you only want those with one obs:
df.final <- df3[which(df4$mult_id==1),]
</code>```

ContentLicense: CC BY-SA 3.0

Title: how can I take values out of many strings

Body:
I have a data like below

df<-structure(list(X__1 = c("Q6NVC0 [197-213]", "A0A0A8UAS1 [48-64]",
"A0A0F0XK65 [8-17]", "A0A0G2JMX7 [481-491]; P20406-6 [106-116]; Q6UIN5 [7-17]; P20406-3 [70-80]; P20406-8 [164-174]",
"A0A0G2JMX7 [481-497]; P20406-6 [106-122]; Q6UIN5 [7-23]; P20406-3 [70-86]; P20406-8 [164-180]",
"P20406-6 [106-132]; Q6UIN5 [7-33]; P20406-3 [70-96]; P20406-8 [164-190]",
"H6VRG2 [603-616]", "P13645 [41-59]", "P35527 [488-513]", "P35908 [525-544]; H2R1Z0 [512-531]",
"H6VRG2 [550-588]", "A0A024RBS2 [150-162]", "A0A023L3M5 [83-110]",
"P10809 [143-156]", "V9HW22 [470-493]", "P20406-8 [379-392]",
"P19338 [524-537]", "A0A024L4P7 [46-57]", "G7YYH5 [45-55]", "Q86YZ3 [973-991]; [1443-1461]; [1913-1931]; [2383-2401]",
"P35527 [375-390]", "P35527 [375-391]", "D2TTS3 [41-50]")), .Names = "X__1", class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -23L))

I am trying to make an output like this
At first I try to get the value next to one two IDs P20406-8 and A0A024RBS2. If they dont exist in a row, we take the first two values of any other ID. if they exist together, we take the value next to the first one and if one of the ID is there, we take its value.

So at the end I want a two column of values like below

197 213
48  64
8   17
164 174
164 180
164 190
603 616
41  59
488 513
525 544
550 588
150 162
83  110
143 156
470 493
379 392
524 537
46  57
45  55
973 991
375 390
375 391
41  50

Body:
One approach:

library(splitstackshape)
# separate multi observation lines into multiple columns
df2 <- cSplit(df, splitCols='X__1', sep=';')
# put in a long format for easier processing
df3 <- na.omit(data.frame(melt(as.data.frame(df2),measure=names(df2))))

# extractions
# account id
df3$id <- with(df3,gsub(x=value,pattern="^(.*) [[:punct:]](.*)-(.*)[[:punct:]]$",replacement='\\1'))
# start range
df3$begin <- with(df3,gsub(x=value,pattern="^(.*) [[:punct:]](.*)-(.*)[[:punct:]]$",replacement='\\2'))
# end range
df3$end <- with(df3,gsub(x=value,pattern="^(.*) [[:punct:]](.*)-(.*)[[:punct:]]$",replacement='\\3'))
# accounts with multiple:
df3$mult_id <- as.numeric(with(df3,gsub(x=variable,pattern="^X__1_(.*)$",replacement='\\1')))

# apparently you only want those with one obs:
df.final <- df3[which(df4$mult_id==1),]


问:
Dropdown selected value to bind the DropDown next row inside gridview
I have a Dropdown inside a gridview which is dynamic. What I want is after selecting the first value from the dropdown in the first row, using that selected value on the fist row bind the dropdown in the second row.

```<code>                                        <asp:TemplateField HeaderText="Staff">
                                        <ItemTemplate>
                                            <asp:DropDownList ID="ddlInsentiveCategory" runat="server" OnSelectedIndexChanged="ddlInsentiveCategory_SelectedIndexChanged" AutoPostBack="true" DataSourceID="InsentiveDataSource"
                                                DataTextField="Name" DataValueField="SalesStaffID">
                                            </asp:DropDownList>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator70" runat="server" ControlToValidate="ddlInsentiveCategory"
                                                CssClass="rfv" ErrorMessage="*" ForeColor="Red" InitialValue="0" ValidationGroup="group2"></asp:RequiredFieldValidator>
                                            <asp:SqlDataSource ID="InsentiveDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:Connection %>"
                                                SelectCommand="SELECT '--Select--' as [Name],'0' as [SalesStaffID]  union all SELECT [Name],[SalesStaffID] FROM [SalesStaff] WHERE ([StaffCategoryID] = @StaffCategoryID)">
                                                <SelectParameters>
                                                    <asp:ControlParameter ControlID="hdnInsentiveCategoryID" Name="StaffCategoryID" PropertyName="Value"
                                                        Type="Int32" />
                                                </SelectParameters>
                                            </asp:SqlDataSource>
                                            <asp:HiddenField ID="hdnInsentiveCategoryID" runat="server" Value='<%# Bind("StaffCategoryID") %>' />
                                        </ItemTemplate>
                                    </asp:TemplateField>
</code>```

Help me to achieve this. thanks in advance.

答:
I am assuming your gridview is also using a SqlDataSource, else there will be a small change required in approach mentioned.

You need to add Selecting event to SqlDataSource for drop down list
as in markup below.

```<code><asp:SqlDataSource ID="InsentiveDataSource" runat="server"
           OnSelecting="InsentiveDataSource_Selecting" ....
</code>```

In code behind add the following C# code. The Selecting event for SqlDataSource of drop down is being subscribed to since it allows to make changes to SqlDataSource just before it gets the data.

Here, you are getting the selected value of drop down whose index has
just been changed, and then getting the next row drop down control.

Once the next row drop down control is obtained, we simply call its
DataBind method which will fire the Selecting event of its data
source

and in the selecting event we can set the parameter value dynamically to previous row's drop down selected value.

```<code>private int dropdpownValue;

protected void ddlInsentiveCategory_SelectedIndexChanged ( object sender, EventArgs e)
{

 //get selected value of drop down and then find
 //the row index of this drop down control

 DropDownList ddl = sender as DropDownList;
 int.TryParse( (sender as DropDownList).SelectedItem.Value, out ddlValue);
 GridViewRow row = (GridViewRow) ddl.NamingContainer;
 int ddlRowIndex = row.RowIndex;

 //find the next row dropdownlist and if there is a next row,
 //then get this control and databind it

 GridView gridView =   (GridView)ddl.NamingContainer.NamingContainer ;
 if((ddlRowIndex + 1) <= (gridView.Rows.Count -1)) {
     DropDownList nextRowDDL = ((System.Web.UI.WebControls.GridView)ddl.NamingContainer.NamingContainer ).Rows[ ddlRowIndex + 1].FindControl("ddlInsentiveCategory")
     nextRowDDL.DataBind();
   }
}

protected void InsentiveDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
   if(dropdpownValue> 0) {
          e.Command.Parameters[0].Value=  dropdpownValue;
          dropdownValue = 0;
   }
}
</code>```

Body:
I have a Dropdown inside a gridview which is dynamic. What I want is after selecting the first value from the dropdown in the first row, using that selected value on the fist row bind the dropdown in the second row.

                                        <asp:TemplateField HeaderText="Staff">
                                        <ItemTemplate>
                                            <asp:DropDownList ID="ddlInsentiveCategory" runat="server" OnSelectedIndexChanged="ddlInsentiveCategory_SelectedIndexChanged" AutoPostBack="true" DataSourceID="InsentiveDataSource"
                                                DataTextField="Name" DataValueField="SalesStaffID">
                                            </asp:DropDownList>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator70" runat="server" ControlToValidate="ddlInsentiveCategory"
                                                CssClass="rfv" ErrorMessage="*" ForeColor="Red" InitialValue="0" ValidationGroup="group2"></asp:RequiredFieldValidator>
                                            <asp:SqlDataSource ID="InsentiveDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:Connection %>"
                                                SelectCommand="SELECT '--Select--' as [Name],'0' as [SalesStaffID]  union all SELECT [Name],[SalesStaffID] FROM [SalesStaff] WHERE ([StaffCategoryID] = @StaffCategoryID)">
                                                <SelectParameters>
                                                    <asp:ControlParameter ControlID="hdnInsentiveCategoryID" Name="StaffCategoryID" PropertyName="Value"
                                                        Type="Int32" />
                                                </SelectParameters>
                                            </asp:SqlDataSource>
                                            <asp:HiddenField ID="hdnInsentiveCategoryID" runat="server" Value='<%# Bind("StaffCategoryID") %>' />
                                        </ItemTemplate>
                                    </asp:TemplateField>

Help me to achieve this. thanks in advance.

Body:
I am assuming your gridview is also using a SqlDataSource, else there will be a small change required in approach mentioned.

You need to add Selecting event to SqlDataSource for drop down list
as in markup below.

<asp:SqlDataSource ID="InsentiveDataSource" runat="server"
           OnSelecting="InsentiveDataSource_Selecting" ....

In code behind add the following C# code. The Selecting event for SqlDataSource of drop down is being subscribed to since it allows to make changes to SqlDataSource just before it gets the data.

Here, you are getting the selected value of drop down whose index has
just been changed, and then getting the next row drop down control.

Once the next row drop down control is obtained, we simply call its
DataBind method which will fire the Selecting event of its data
source

and in the selecting event we can set the parameter value dynamically to previous row's drop down selected value.

private int dropdpownValue;

protected void ddlInsentiveCategory_SelectedIndexChanged ( object sender, EventArgs e)
{

 //get selected value of drop down and then find
 //the row index of this drop down control

 DropDownList ddl = sender as DropDownList;
 int.TryParse( (sender as DropDownList).SelectedItem.Value, out ddlValue);
 GridViewRow row = (GridViewRow) ddl.NamingContainer;
 int ddlRowIndex = row.RowIndex;

 //find the next row dropdownlist and if there is a next row,
 //then get this control and databind it

 GridView gridView =   (GridView)ddl.NamingContainer.NamingContainer ;
 if((ddlRowIndex + 1) <= (gridView.Rows.Count -1)) {
     DropDownList nextRowDDL = ((System.Web.UI.WebControls.GridView)ddl.NamingContainer.NamingContainer ).Rows[ ddlRowIndex + 1].FindControl("ddlInsentiveCategory")
     nextRowDDL.DataBind();
   }
}

protected void InsentiveDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
   if(dropdpownValue> 0) {
          e.Command.Parameters[0].Value=  dropdpownValue;
          dropdownValue = 0;
   }
}


问:
Change title font of Alert Dialog box
I want to change the font of the title of Alert Dialog box.

Can anybody tell how can I do it?

答:
You can try Spannable as well.</p>

```<code>            SpannableString s = new SpannableString("My App");
            s.setSpan(new TypefaceSpan(this, "font.otf"), 0, s.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            s.setSpan(new RelativeSizeSpan(1.3f), 0,s.length(), 0);
            builder.setTitle(s)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Change title font of Alert Dialog box

Body:
You can try Spannable as well.

            SpannableString s = new SpannableString("My App");
            s.setSpan(new TypefaceSpan(this, "font.otf"), 0, s.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            s.setSpan(new RelativeSizeSpan(1.3f), 0,s.length(), 0);
            builder.setTitle(s)


问:
async module (async.waterfall)
I am using async.waterfall module.
scenario :
in first callback function I am populating the data from the DB and passing the output of that in second callback function where I am send a mail notification and then updating the DB with a mail flag.

Code :

```<code>async.waterfall(
function(callback){
   // data population code
},
function(datafromDB, callback){
    NotificationManager.sendEmailToUser('MAIL', variableDetails, email, callback);
   // code to update the database
}],
  function(err,result){
   //callback
}
</code>```

I want the user details in result which I should be getting in callback function once the code to update the database is called but before that while sending the mail callback function is getting resolved. Is there any way to get the user details in the result?

答:
you can make the second callback return two parameters ex: datafromDB, notification</p>

```<code>async.waterfall(
function(callback){
   // data population code
},
function(datafromDB, callback){
    NotificationManager.sendEmailToUser('MAIL', variableDetails, email, callback);
    // code to update the database
    callback(null, datafromDB, notification);
}],
  function(err,result){
   //callback
}
</code>```

Title: async module (async.waterfall)

Body:
I am using async.waterfall module.
scenario :
in first callback function I am populating the data from the DB and passing the output of that in second callback function where I am send a mail notification and then updating the DB with a mail flag.

Code :

async.waterfall(
function(callback){
   // data population code
},
function(datafromDB, callback){
    NotificationManager.sendEmailToUser('MAIL', variableDetails, email, callback);
   // code to update the database
}],
  function(err,result){
   //callback
}

I want the user details in result which I should be getting in callback function once the code to update the database is called but before that while sending the mail callback function is getting resolved. Is there any way to get the user details in the result?

Body:
you can make the second callback return two parameters ex: datafromDB, notification

async.waterfall(
function(callback){
   // data population code
},
function(datafromDB, callback){
    NotificationManager.sendEmailToUser('MAIL', variableDetails, email, callback);
    // code to update the database
    callback(null, datafromDB, notification);
}],
  function(err,result){
   //callback
}


问:
Have java classes all inherit from another Object. (Between Object and Class)
I'm not sure how to get the first part going  which is inheritance.
I know in java all classes inherit from the Object class. I want to have all classes  in Java also inherit from my own custom base class. Something like this:
ObjectClass>CustomBaseClass>OtherClasses

I'm wondering is this possible to do in java without having to ship a custom JRE? I'm needing to augment alot of java classes to contain some extra fields.

答:
You most definitely cannot insert a superclass into the hierarchy. What would it mean to insert your base between Object and String, this would not be meaningful.

I agree, this is an XY Problem.

There's nothing stopping you from setting up your own class hierarchy to include the common base class everywhere for your own classes, but even that can lead to design headaches since Java doesn't support multiple inheritance.


问:
How to flip UIImage horizontally?
How to flip the UIImage horizontally, I found UIImageOrientationUpMirrored enumeration value in the UIImage class reference, how to make use of this property to flip UIImage.

答:
iOS 10+

```<code>[myImage imageWithHorizontallyFlippedOrientation];
</code>```

Swift 4:

```<code>let flippedImage = myImage.withHorizontallyFlippedOrientation()
</code>```

Title: How to flip UIImage horizontally?

Body:
iOS 10+

[myImage imageWithHorizontallyFlippedOrientation];

Swift 4:

let flippedImage = myImage.withHorizontallyFlippedOrientation()


问:
PIP cannot install Django inside VIrtualenv
```<code>(myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip freeze
djangorestframework==3.7.3
pkg-resources==0.0.0
(myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip install django
Collecting django
  Using cached Django-2.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-qAnv7G/django/setup.py", line 32, in <module>
        version = __import__('django').get_version()
      File "django/__init__.py", line 1, in <module>
        from django.utils.version import get_version
      File "django/utils/version.py", line 61, in <module>
        @functools.lru_cache()
    AttributeError: 'module' object has no attribute 'lru_cache'

------------------------------------
</code>```

I keep getting that error whenever i try to pip install django while inside my virtualenv. How can i fix this.

答:
As an alternative to wim's answer, if you can't upgrade your Python version for whatever reason, you can install Django 1.11 which is still compatible with Python 2.7:</p>

```<code>pip install 'django<2.0'
</code>```

Body:
(myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip freeze
djangorestframework==3.7.3
pkg-resources==0.0.0
(myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip install django
Collecting django
  Using cached Django-2.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-qAnv7G/django/setup.py", line 32, in <module>
        version = __import__('django').get_version()
      File "django/__init__.py", line 1, in <module>
        from django.utils.version import get_version
      File "django/utils/version.py", line 61, in <module>
        @functools.lru_cache()
    AttributeError: 'module' object has no attribute 'lru_cache'

------------------------------------

I keep getting that error whenever i try to pip install django while inside my virtualenv. How can i fix this.

Body:
As an alternative to wim's answer, if you can't upgrade your Python version for whatever reason, you can install Django 1.11 which is still compatible with Python 2.7:

pip install 'django<2.0'


问:
Batch 'IF' command not working
this code just skip "if" commend and go to another
i wont to see somethink like that:
"2 2 end" or "3 3 end", but it shows only "3 1 end" or "2 1 end". Please help im new in this.</p>

```<code>@echo off
set /p number=
if %number%=="1" goto 1
if %number%=="2" goto 2
if %number%=="3" goto 3
:1
echo 1
goto end
:2
echo 2
goto end
:3
echo 3
goto end
:end
echo end
pause
</code>```

答:
The IF command in batch is purely a string comparison, not a numeric one. Moreover, quotation marks are significant. Your code contains lines such as

```<code>if %number%=="1" goto 1
</code>```

which compares the value of the variable number with the string "1". However, your SET statement implicitly wants you to type 1 or 2 or 3, with no quotes.

In order to avoid a syntax error if the user provides a blank or a null string as the response to the SET prompt, you want to quote %number%:

```<code>if "%number%"=="1" goto 1
</code>```

Additionally, you want to put an unconditional goto before the label :1 to protect that subroutine; if you don't, then if the user doesn't enter 1, 2, or 3, option 1 will be executed because of fall-through.

It is also possible - I'm not quite clear on how it works myself - that you may want to use delayed expansion, which would require you to change the IFs to use ! instead of %:

```<code>if "!number!"=="1" goto 1
</code>```

There is a very good reference site for batch at SS64; you may want to pay special attention to Delayed Expansion and the IF command.

Title: Batch 'IF' command not working

Body:
this code just skip "if" commend and go to another
i wont to see somethink like that:
"2 2 end" or "3 3 end", but it shows only "3 1 end" or "2 1 end". Please help im new in this.

@echo off
set /p number=
if %number%=="1" goto 1
if %number%=="2" goto 2
if %number%=="3" goto 3
:1
echo 1
goto end
:2
echo 2
goto end
:3
echo 3
goto end
:end
echo end
pause

Body:
The IF command in batch is purely a string comparison, not a numeric one. Moreover, quotation marks are significant. Your code contains lines such as

if %number%=="1" goto 1

which compares the value of the variable number with the string "1". However, your SET statement implicitly wants you to type 1 or 2 or 3, with no quotes.

In order to avoid a syntax error if the user provides a blank or a null string as the response to the SET prompt, you want to quote %number%:

if "%number%"=="1" goto 1

Additionally, you want to put an unconditional goto before the label :1 to protect that subroutine; if you don't, then if the user doesn't enter 1, 2, or 3, option 1 will be executed because of fall-through.

It is also possible - I'm not quite clear on how it works myself - that you may want to use delayed expansion, which would require you to change the IFs to use ! instead of %:

if "!number!"=="1" goto 1

There is a very good reference site for batch at SS64; you may want to pay special attention to Delayed Expansion and the IF command.


问:
Wait for AWS RDS native sql backup to be finished
When creating an EC2 or RDS instance in batch or powershell, you can run the built-in aws rds wait db-instance-available --db-instance-identifier 'myDbInstance' to wait for it to be available before running further commands against it.

I have a script that restores an RDS snapshot into a new instance ($devInstanceDnsName), and then backup a single database from that instance (in MS SQL) to S3.
In powershell, to run the native backup, you run sqlcmd -X -b -S "tcp:$devInstanceDnsName,1433" -d dbName -U dbUser -P dbPwd -Q "exec msdb.dbo.rds_backup_database @source_db_name='dbName', @s3_arn_to_backup_to='arn:aws:s3:::backupsbucket/$backupFileName', @overwrite_S3_backup_file=1".

That is an asynchronous task, it schedules the backup and returns immediately. But how can the script know when the native backup has completed, and continue execution, synchronously?

答:
I've done a simple powershell function called like this:

```<code>Wait-RdsNativeBackupSuccess -server "$devInstanceDnsName,1433" -database dbName -user dbUser -pwd dbPwd
</code>```

and defined like this:

```<code>function Wait-RdsNativeBackupSuccess($server, $database, $user, $pwd)
{
    $startDate = Get-Date
    $timeOutminutes = 45
    $retryIntervalSeconds = 30

    do {
            $awsResponse = Invoke-Sqlcmd -ServerInstance $server -Database $database -Username $user -Password $pwd -Query "exec msdb.dbo.rds_task_status @db_name='dbName'" -DisableCommands -AbortOnError
            Write-Host $awsResponse.lifecycle $awsResponse."% complete"

            if($awsResponse.lifecycle -eq "SUCCESS") {break}
            start-sleep -seconds $retryIntervalSeconds

    } while ($startDate.AddMinutes($timeOutminutes) -gt (Get-Date))

}
</code>```

It calls the rds_task_status sproc every X seconds, for a maximum of X minutes, until it gets a lifecycle value of "SUCCESS".

You can of course improve this:

add a return code or throw in case of timeouts,

handle the lifecycle value of error, maybe showing the value of task_info which will have the error in it.

pass in more parameters to make it more generic (like port number of timeouts and retries), etc.

Output looks like this:

```<code>Task created successfully.
Task Id: 1
CREATED 0
CREATED 0
CREATED 0
IN_PROGRESS 0
IN_PROGRESS 0
IN_PROGRESS 5
IN_PROGRESS 5
IN_PROGRESS 10
...
</code>```

Body:
I've done a simple powershell function called like this:

Wait-RdsNativeBackupSuccess -server "$devInstanceDnsName,1433" -database dbName -user dbUser -pwd dbPwd

and defined like this:

function Wait-RdsNativeBackupSuccess($server, $database, $user, $pwd)
{
    $startDate = Get-Date
    $timeOutminutes = 45
    $retryIntervalSeconds = 30

    do {
            $awsResponse = Invoke-Sqlcmd -ServerInstance $server -Database $database -Username $user -Password $pwd -Query "exec msdb.dbo.rds_task_status @db_name='dbName'" -DisableCommands -AbortOnError
            Write-Host $awsResponse.lifecycle $awsResponse."% complete"

            if($awsResponse.lifecycle -eq "SUCCESS") {break}
            start-sleep -seconds $retryIntervalSeconds

    } while ($startDate.AddMinutes($timeOutminutes) -gt (Get-Date))

}

It calls the rds_task_status sproc every X seconds, for a maximum of X minutes, until it gets a lifecycle value of "SUCCESS".

You can of course improve this:

add a return code or throw in case of timeouts,

handle the lifecycle value of error, maybe showing the value of task_info which will have the error in it.

pass in more parameters to make it more generic (like port number of timeouts and retries), etc.

Output looks like this:

Task created successfully.
Task Id: 1
CREATED 0
CREATED 0
CREATED 0
IN_PROGRESS 0
IN_PROGRESS 0
IN_PROGRESS 5
IN_PROGRESS 5
IN_PROGRESS 10
...


问:
Reset random number stream
It appears that SAS/IML has the ability to reset it's random number stream (doc link) .

Is there a similar feature for random number routines in the SAS data step?

Based on this post, it seems that subsequent calls to streaminit are ignored within a single datastep.

For example, the below code produces different random numbers for each row:

```<code>data want;
  do i = 1 to 2;
    call streaminit(123);  * <-- WANT THIS TO RESET THE STREAM;
    ran1 = rand('uniform');
    ran2 = rand('uniform');
    ran3 = rand('uniform');
    put _all_;
    output;
  end;
run;
</code>```

Output:

```<code>i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.3878454913 ran2=0.3291709244 ran3=0.3615948586
</code>```

I would like the output to be:

```<code>i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
</code>```

答:
You can use call ranuni to use the same seed for two different random number streams.

Note that this uses a different, inferior PRNG, with a much shorter cycle and poorer statistical properties than the rand() function.

Example:

```<code>data x;
  seed1 = 123;
  seed2 = 123;
  do i =1 to 3;
    call ranuni(seed1, x);
    call ranuni(seed2, y);
    output;
  end;
run;
</code>```

Output:

```<code>i=1 x=0.7503960881 y=0.7503960881
i=2 x=0.3209120251 y=0.3209120251
i=3 x=0.178389649 y=0.178389649
</code>```

Title: Reset random number stream

Body:
It appears that SAS/IML has the ability to reset it's random number stream (doc link) .

Is there a similar feature for random number routines in the SAS data step?

Based on this post, it seems that subsequent calls to streaminit are ignored within a single datastep.

For example, the below code produces different random numbers for each row:

data want;
  do i = 1 to 2;
    call streaminit(123);  * <-- WANT THIS TO RESET THE STREAM;
    ran1 = rand('uniform');
    ran2 = rand('uniform');
    ran3 = rand('uniform');
    put _all_;
    output;
  end;
run;

Output:

i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.3878454913 ran2=0.3291709244 ran3=0.3615948586

I would like the output to be:

i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207

Body:
You can use call ranuni to use the same seed for two different random number streams.

Note that this uses a different, inferior PRNG, with a much shorter cycle and poorer statistical properties than the rand() function.

Example:

data x;
  seed1 = 123;
  seed2 = 123;
  do i =1 to 3;
    call ranuni(seed1, x);
    call ranuni(seed2, y);
    output;
  end;
run;

Output:

i=1 x=0.7503960881 y=0.7503960881
i=2 x=0.3209120251 y=0.3209120251
i=3 x=0.178389649 y=0.178389649


问:
Manipulating object in array changes object outside of array?
I don't understand why this behavior is happening. Lets say I define an object and make an array of 3 of this object. If I modify the objects in the array, it affects all instances of the object? Could someone explain why this is? Also, how do I make an array with independent "Copies" of the object to get the desired behavior? Thanks!

example

```<code>testObject = {"value1":"a","value2":"b"};
objArray = [];
for(i=0; i < 3; i++){
   var newobj = testObject; //make a new testObject
   objArray.push(newobj); //push new object to array
   }
delete objArray[0].value2 // Desired, delete value 2 ONLY from array object 0
objArray[2].value2 //Undefined? Why is value2 missing from object 2
testObject.value2 //Undefined? Why is value2 missing from original object?
</code>```

答:
You are pushing same object's reference again and again in the loop.

```<code>for(i=0; i < 3; i++){
   var newobj = testObject; //no new object,same object's reference again
   objArray.push(newobj); //push new object to array
   }
</code>```

It should be

```<code>for(i=0; i < 3; i++){
   var newobj =  {"value1":"a","value2":"b"}; //make a new testObject
   objArray.push(newobj); //push new object to array
   }
</code>```

Body:
I don't understand why this behavior is happening. Lets say I define an object and make an array of 3 of this object. If I modify the objects in the array, it affects all instances of the object? Could someone explain why this is? Also, how do I make an array with independent "Copies" of the object to get the desired behavior? Thanks!

example

testObject = {"value1":"a","value2":"b"};
objArray = [];
for(i=0; i < 3; i++){
   var newobj = testObject; //make a new testObject
   objArray.push(newobj); //push new object to array
   }
delete objArray[0].value2 // Desired, delete value 2 ONLY from array object 0
objArray[2].value2 //Undefined? Why is value2 missing from object 2
testObject.value2 //Undefined? Why is value2 missing from original object?

Body:
You are pushing same object's reference again and again in the loop.

for(i=0; i < 3; i++){
   var newobj = testObject; //no new object,same object's reference again
   objArray.push(newobj); //push new object to array
   }

It should be

for(i=0; i < 3; i++){
   var newobj =  {"value1":"a","value2":"b"}; //make a new testObject
   objArray.push(newobj); //push new object to array
   }


问:
Specified argument was out of the range of valid values. Parameter name: site
I am getting this Kind of Error like::

Specified argument was out of the range of valid values.Parameter name: site

while Debugging any of my Project.

I have also tried after Reinstalling My Visual Studio 2012. But again the same kind of problem I am getting while Debugging.

My System's Configurations are :

Windows 8 : 32-bit

Visual Studio : 2012

Exception is thrown at the time of Showing Web Page Like,

```<code>[ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: site]
   System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException) +298

[HttpException (0x80004005): Specified argument was out of the range of valid values.
Parameter name: site]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873912
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
</code>```

答: Modify was greyed out for me, but adding the IIS Management Console under programs and features fixed this for me. Also on Windows 10 fall update.</p>

Body:
I am getting this Kind of Error like::

Specified argument was out of the range of valid values.Parameter name: site

while Debugging any of my Project.

I have also tried after Reinstalling My Visual Studio 2012. But again the same kind of problem I am getting while Debugging.

My System's Configurations are :

Windows 8 : 32-bit

Visual Studio : 2012

Exception is thrown at the time of Showing Web Page Like,

[ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: site]
   System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException) +298

[HttpException (0x80004005): Specified argument was out of the range of valid values.
Parameter name: site]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873912
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254


问:
Usage of a service from angular HttpInterceptor
I am trying to use a singleton service from a HttpInterceptor in order to have an automatic busy loading indicator.

The problem however is that the interceptor works without the service, but not using the service.

I am referencing the service as follows in the constructor of the HttpInterceptor:

```<code>constructor(private htbs: HttpBusyService) {}
</code>```

In the app module the service and the HttpInterceptor are provided like this:

```<code>providers: [
    HttpBusyService,
    { provide: LocationStrategy, useClass: HashLocationStrategy},
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    MessageService,
    ConfirmationService,
]
</code>```

The error i am getting is:

```<code>Uncaught Error: Can't resolve all parameters for AuthInterceptor: (?).
    at syntaxError (compiler.js:485)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15664)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15499)
    at CompileMetadataResolver._getInjectableMetadata (compiler.js:15479)
    at CompileMetadataResolver.getProviderMetadata (compiler.js:15839)
    at eval (compiler.js:15750)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15710)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15278)
    at JitCompiler._loadModules (compiler.js:34226)
</code>```

I have no clue where to look. I obviously am doing something wrong, because i saw other interceptors using singletons.
I am using angular 5.1.0-rc.1 but 5.0.0 had the same problem

Any help is much appreciated

Jan

PS1 I have seen Angular HTTP Interceptor that uses a Service? but the answer doesn't help

PS2 I tried rearranging the providers

EDIT: The Interceptor

```<code>import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpResponse, HttpHandler, HttpEvent,     HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { HttpBusyService } from './http-busy.service';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/Observable';
import 'rxjs/add/observable/throw';

export class AuthInterceptor implements HttpInterceptor {

  constructor(private htbs: HttpBusyService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<HttpEventType.Response>> {
  // this.htbs.start();
const authReq = req.clone({
  setHeaders: { 'X-AUTH-TOKEN': sessionStorage.getItem('token') }
});
return next
.handle(authReq)
.do((ev: HttpEvent<any>) => {
  if (ev instanceof HttpResponse) {
    console.log('processing response', ev);
  }
})
.catch(response => {
  // if (response instanceof HttpErrorResponse) {
    console.log('Processing http error', response);
  // }

  return Observable.throw(response);
});
  }
}
</code>```

and the busy service:

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class HttpBusyService {
  public busy = false;
  private count = 0;
  constructor() { }
  public start() {
    this.count++;
    this.busy = true;
  }
  public finish() {
    this.count--;
    if (this.count <= 0) {
      this.count = 0;
      this.busy = false;
    }
  }
}
</code>```

答:
You forgot use the @Injectable() Decorator to indicate AuthInterceptor is an injectable element.

The Angular Dependency Injection works like this. You should define any "injectable" component using @Injectable and register in @Component provider. To increase the understanding you chould read this.

Finally, in my humble opinion, sometimes, errors in Angular and its associated call stack are a bit tricky to understand and they are small eloquent

Body:
I am trying to use a singleton service from a HttpInterceptor in order to have an automatic busy loading indicator.

The problem however is that the interceptor works without the service, but not using the service.

I am referencing the service as follows in the constructor of the HttpInterceptor:

constructor(private htbs: HttpBusyService) {}

In the app module the service and the HttpInterceptor are provided like this:

providers: [
    HttpBusyService,
    { provide: LocationStrategy, useClass: HashLocationStrategy},
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    MessageService,
    ConfirmationService,
]

The error i am getting is:

Uncaught Error: Can't resolve all parameters for AuthInterceptor: (?).
    at syntaxError (compiler.js:485)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15664)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15499)
    at CompileMetadataResolver._getInjectableMetadata (compiler.js:15479)
    at CompileMetadataResolver.getProviderMetadata (compiler.js:15839)
    at eval (compiler.js:15750)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15710)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15278)
    at JitCompiler._loadModules (compiler.js:34226)

I have no clue where to look. I obviously am doing something wrong, because i saw other interceptors using singletons.
I am using angular 5.1.0-rc.1 but 5.0.0 had the same problem

Any help is much appreciated

Jan

PS1 I have seen Angular HTTP Interceptor that uses a Service? but the answer doesn't help

PS2 I tried rearranging the providers

EDIT: The Interceptor

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpResponse, HttpHandler, HttpEvent,     HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { HttpBusyService } from './http-busy.service';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/Observable';
import 'rxjs/add/observable/throw';

export class AuthInterceptor implements HttpInterceptor {

  constructor(private htbs: HttpBusyService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<HttpEventType.Response>> {
  // this.htbs.start();
const authReq = req.clone({
  setHeaders: { 'X-AUTH-TOKEN': sessionStorage.getItem('token') }
});
return next
.handle(authReq)
.do((ev: HttpEvent<any>) => {
  if (ev instanceof HttpResponse) {
    console.log('processing response', ev);
  }
})
.catch(response => {
  // if (response instanceof HttpErrorResponse) {
    console.log('Processing http error', response);
  // }

  return Observable.throw(response);
});
  }
}

and the busy service:

import { Injectable } from '@angular/core';

@Injectable()
export class HttpBusyService {
  public busy = false;
  private count = 0;
  constructor() { }
  public start() {
    this.count++;
    this.busy = true;
  }
  public finish() {
    this.count--;
    if (this.count <= 0) {
      this.count = 0;
      this.busy = false;
    }
  }
}


问:
AngularJS Link function not called
I'm trying to write my first AngularJS directive: one involving the link function.  The directive is being loaded, but when I use it in my page the link function is not called.

Here's the fiddle: http://jsfiddle.net/jCUSh/115/

Here's the HTML:

```<code><div ng-app="biApp">
    <google-maps-symbol></google-maps-symbol>
</div>
</code>```

and the JavaScript:

```<code>var appModule = angular.module('biApp', []);

appModule.directive('googleMapsSymbol', function () {
    console.log("Directive was run");
    return {
        link: function (scope, elem, attrs) {
            console.log("Link was called");
        }
    };
});
</code>```

I'll bet I'm doing some simple thing wrong.

答:
Another reason this could happen for people is that there is a runtime error in one of the other compilation phases for the directive.</p>

```<code>ng.module(MODULE).directive('myDirective', [() => {
    return {
        link() {
            // Never getting here
        },
        template() {
            // Error here would mess things up
        },
        controller() {
            // error here would mess things up
        }
    };
}]);
</code>```

Title: AngularJS Link function not called

Body:
I'm trying to write my first AngularJS directive: one involving the link function.  The directive is being loaded, but when I use it in my page the link function is not called.

Here's the fiddle: http://jsfiddle.net/jCUSh/115/

Here's the HTML:

    <google-maps-symbol></google-maps-symbol>

and the JavaScript:

var appModule = angular.module('biApp', []);

appModule.directive('googleMapsSymbol', function () {
    console.log("Directive was run");
    return {
        link: function (scope, elem, attrs) {
            console.log("Link was called");
        }
    };
});

I'll bet I'm doing some simple thing wrong.

Body:
Another reason this could happen for people is that there is a runtime error in one of the other compilation phases for the directive.

ng.module(MODULE).directive('myDirective', [() => {
    return {
        link() {
            // Never getting here
        },
        template() {
            // Error here would mess things up
        },
        controller() {
            // error here would mess things up
        }
    };
}]);


问:
C++ How to break a while find loop?
In this loop I want to add new line (\n) behind evert dot(.).

How to break the loop when new line has been added after each dot?

```<code>while (alltxt.find(".") != string::npos)
    alltxt.replace(alltxt.find("."), 1, ".\n");
</code>```

答:
Here's a generic function that may do what you want:</p>

```<code>std::string& replace_all(std::string& str, const std::string& needle,
                         const std::string& replacement)
{
  auto idx = str.find(needle, 0);
  while (idx != std::string::npos) {
    str.replace(idx, needle.size(), replacement);
    idx = str.find(needle, idx + replacement.size());
  }
  return str;
}
</code>```

Title: C++ How to break a while find loop?

Body:
In this loop I want to add new line (\n) behind evert dot(.).

How to break the loop when new line has been added after each dot?

while (alltxt.find(".") != string::npos)
    alltxt.replace(alltxt.find("."), 1, ".\n");

Body:
Here's a generic function that may do what you want:

std::string& replace_all(std::string& str, const std::string& needle,
                         const std::string& replacement)
{
  auto idx = str.find(needle, 0);
  while (idx != std::string::npos) {
    str.replace(idx, needle.size(), replacement);
    idx = str.find(needle, idx + replacement.size());
  }
  return str;
}


问:
How do I use a dump file to diagnose a memory leak?
I have a .NET service with a normal private working set of about 80 MB. During a recent load test, the process reached 3.5 GB memory usage causing the whole machine to be low on physical memory (3.9 of 4 GB used), and the memory was not released long after the load test was stopped. Using task manager, I took a dump file of the process and opened it in Visual Studio 2010 SP1, and I am able to start debugging on it.

How do I diagnose the memory issue? I have dotTrace Memory 3.x at my disposal, does it support memory profiling on dump files? If not, will the memory profiling features of Visual Studio 2010 Premium help (I currently have Professional)? Can WinDbg help?

UPDATE: The new Visual Studio 2013 Ultimate can now natively diagnose memory issues using dump files. See this blog post for more details.

答: Since version 2017.2 JetBrains dotMemory supports Windows memory dumps analysis with all its power and fancy GUI.</p>


问:
Adding a video url to an sms or mms using twilio
I can add a youtube link to a new message's body like below and it will send the message, but adding the link to the media_url gives an mime type error. Idk how I feel about this method.

```<code>client = Twilio::REST::Client.new 'Axx', 'xx'
message = client.messages.create
    from: '+1xxxxxxxxxx',
    to: 'xxxxxxxxxx',
    body: "Learning to send SMS you are. \n https://www.youtube.com/watch?v=aBlKPLeLU_s"
</code>```

Is there a better way of adding youtube links to a new message?

EDIT

Adding the url to the media_url key like

```<code>client = Twilio::REST::Client.new 'Axx', 'xx'
message = client.messages.create
    from: '+1xxxxxxxxxx',
    to: 'xxxxxxxxxx',
    body: "Learning to send SMS you are."
    media_url: "https://www.youtube.com/watch?v=aBlKPLeLU_s"
</code>```

Gives the error from twilio

Msg=Attempt+to+retrieve+MediaUrl+returned+an+unsupported+Content-Type.&EmailNotification=false&contentType=text%2Fhtml&LogLevel=ERROR&url=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaBlKPLeLU_s

答:
Twilio's example of media_url

Twilio

```<code>  var mediaUrl = new List<Uri>() {
      new Uri("http://www.example.com/hearts.png")
  };
  var to = new PhoneNumber("+14158141829");
  var message = MessageResource.Create(to,
                  from: new PhoneNumber("+15558675309"),
                  body: "Jenny please?! I love you <3",
                  mediaUrl: mediaUrl);
</code>```

And also the allowed options link

Twilio Create function arguments

Could you try...

```<code>client = Twilio::REST::Client.new 'Axx', 'xx'
  message = client.messages.create
  from: '+1xxxxxxxxxx',
  to: 'xxxxxxxxxx',
  body: "Learning to send SMS you are."
  media_url: [URI("https://www.youtube.com/watch?v=aBlKPLeLU_s")]
</code>```

Body:
I can add a youtube link to a new message's body like below and it will send the message, but adding the link to the media_url gives an mime type error. Idk how I feel about this method.

client = Twilio::REST::Client.new 'Axx', 'xx'
message = client.messages.create
    from: '+1xxxxxxxxxx',
    to: 'xxxxxxxxxx',
    body: "Learning to send SMS you are. \n https://www.youtube.com/watch?v=aBlKPLeLU_s"

Is there a better way of adding youtube links to a new message?

EDIT

Adding the url to the media_url key like

client = Twilio::REST::Client.new 'Axx', 'xx'
message = client.messages.create
    from: '+1xxxxxxxxxx',
    to: 'xxxxxxxxxx',
    body: "Learning to send SMS you are."
    media_url: "https://www.youtube.com/watch?v=aBlKPLeLU_s"

Gives the error from twilio

Msg=Attempt+to+retrieve+MediaUrl+returned+an+unsupported+Content-Type.&EmailNotification=false&contentType=text%2Fhtml&LogLevel=ERROR&url=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaBlKPLeLU_s

Body:
Twilio's example of media_url

Twilio

  var mediaUrl = new List<Uri>() {
      new Uri("http://www.example.com/hearts.png")
  };
  var to = new PhoneNumber("+14158141829");
  var message = MessageResource.Create(to,
                  from: new PhoneNumber("+15558675309"),
                  body: "Jenny please?! I love you <3",
                  mediaUrl: mediaUrl);

And also the allowed options link

Twilio Create function arguments

Could you try...

client = Twilio::REST::Client.new 'Axx', 'xx'
  message = client.messages.create
  from: '+1xxxxxxxxxx',
  to: 'xxxxxxxxxx',
  body: "Learning to send SMS you are."
  media_url: [URI("https://www.youtube.com/watch?v=aBlKPLeLU_s")]


问:
Complex filtering SQL Server query with multiple conditions
I have a SQL Server query in which I am joining several tables together and we are using SQL Server 2012. I have a customer number, customer name, item type, a field for document number (which can be one document number in either of the two tables I will mention; even though there are two fields mentioned later, I do want to combine this into one field using a CASE statement), a document amount, document date, due date, amount remaining to be paid, and a description.

The problem is that for my item type, one table (RM20101), doesn't recognize an item type associated with it because no item types are in that table. The other table (Custom_RecData), recognizes the correct item type for all pertinent document numbers but that tables only has a record of document numbers associated with items--which not all document numbers in the system have.

So here's an example of the trimmed down version:

```<code>CUSTNMBR    |  ItemType    |   DocumentNumberRM |  DocNumCUSTOM | DocAmount
------------+--------------+--------------------+---------------+-----------
12345ABC    |  NULL        |   PYMNT01234567    |  NULL         |  - 28.50
12345ABC    |  TOYS        |   9010456778       |  9010456778   |   300.00
12345ABC    |  NULL        |   9010456778       |  NULL         |   300.00
12345ABC    |  NULL        |   9019888878       |  NULL         |    47.90
12345ABC    |  CRAFTS      |   9502345671       |  9502345671   |   145.25
12345ABC    |  NULL        |   9502345671       |  NULL         |   145.25
</code>```

I named the columns in this example for document number as "RM" to come out of the RM20101 table and "CUSTOM" to come out of the Custom_RecDate table.

So I've tried lots of ways, from CASE statements, to my WHERE clause, to a HAVING clause, to subqueries...  I can't figure it out.  Here's what I'd like to see:

```<code>CUSTNMBR    |  ItemType    |   DocumentNumberRM |  DocNumCUSTOM | DocAmount
------------+--------------+--------------------+---------------+-----------
12345ABC    |  NULL        |   PYMNT01234567    |  NULL         |  - 28.50
12345ABC    |  TOYS        |   9010456778       |  9010456778   |   300.00
12345ABC    |  NULL        |   9019888878       |  NULL         |    47.90
12345ABC    |  CRAFTS      |   9502345671       |  9502345671   |   145.25
</code>```

So why did I call this multiple conditions?  Well, if you look at the table, I am cutting out items based on the following:

If both the ItemType And DocNumCUSTOM fields are NULL then show it.

If the ItemType IS NOT NULL and both document number fields are NOT NULL, then show it.

If the ItemType IS NULL and DocNumCUSTOM IS NULL, but we've already seen the document number in the RM20101 DocumentNumberRM field (which I suspect would be in a HAVING clause for a COUNT or something), then don't show it a second time.

If I don't find a way to do step 3, I will get the duplicates as shown in my initial example.

I basically do not want duplication.  I want to show an item type whether it be NULL (non-existent for that document number in either table) or show it only once if existent in the Custom_RecDate table, which is the only table that has the item type information in it.

Does this make sense?  I know it sounds complicated as heck, but hopefully someone can make sense of it all.  :)

Thanks!

By the way, here's the important part (my query, albeit very trimmed down for the example):

```<code>SELECT DISTINCT
    R1.CUSTNMBR,
    I.ITMCLSCD AS [ItemType],
    R1.DOCNUMBR AS [DocumentNumberRM],
    I.DOCNUMBR AS [DocNumCUSTOM],
    R1.ORTRXAMT AS [DocAmount]
FROM
    RM20101 R1
JOIN
    RM40401 R2 ON R2.RMDTYPAL = R1.RMDTYPAL
JOIN
    RM00401 R3 ON R3.DOCNUMBR = R1.DOCNUMBR
JOIN
    RM00101 R4 ON R4.CUSTNMBR = R1.CUSTNMBR
LEFT OUTER JOIN
    SR_ITCMCD C ON C.CUSTNMBR = R1.CUSTNMBR
LEFT OUTER JOIN
    AR_Description D ON D.SOPNUM = R1.DOCNUMBR
LEFT OUTER JOIN
    Custom_RecData I ON I.ITEMNMBR = C.ITEMNMBR
                     AND I.DOCNUMBR = R1.DOCNUMBR
</code>```

Again, I've tried using CASE statements and putting various conditions in my WHERE clause, I just can't figure it out.

答:
Purely based on the sample data, MAX() should do the trick:

```<code>SELECT
    R1.CUSTNMBR,
    MAX(I.ITMCLSCD) AS [ItemType],
    R1.DOCNUMBR AS [DocumentNumberRM],
    MAX(I.DOCNUMBR) AS [DocNumCUSTOM],
    R1.ORTRXAMT AS [DocAmount]
FROM RM20101 R1
JOIN RM40401 R2 ON R2.RMDTYPAL = R1.RMDTYPAL
JOIN RM00401 R3 ON R3.DOCNUMBR = R1.DOCNUMBR
JOIN RM00101 R4 ON R4.CUSTNMBR = R1.CUSTNMBR
LEFT OUTER JOIN SR_ITCMCD C ON C.CUSTNMBR = R1.CUSTNMBR
LEFT OUTER JOIN AR_Description D ON D.SOPNUM = R1.DOCNUMBR
LEFT OUTER JOIN Custom_RecData I ON I.ITEMNMBR = C.ITEMNMBR
                                AND I.DOCNUMBR = R1.DOCNUMBR
GROUP BY
    R1.CUSTNMBR,
    R1.DOCNUMBR,
    R1.ORTRXAMT
</code>```

Removed the DISTINCT since GROUP BY will accomplish the same and is needed for MAX()

Body:
I have a SQL Server query in which I am joining several tables together and we are using SQL Server 2012. I have a customer number, customer name, item type, a field for document number (which can be one document number in either of the two tables I will mention; even though there are two fields mentioned later, I do want to combine this into one field using a CASE statement), a document amount, document date, due date, amount remaining to be paid, and a description.

The problem is that for my item type, one table (RM20101), doesn't recognize an item type associated with it because no item types are in that table. The other table (Custom_RecData), recognizes the correct item type for all pertinent document numbers but that tables only has a record of document numbers associated with items--which not all document numbers in the system have.

So here's an example of the trimmed down version:

CUSTNMBR    |  ItemType    |   DocumentNumberRM |  DocNumCUSTOM | DocAmount
------------+--------------+--------------------+---------------+-----------
12345ABC    |  NULL        |   PYMNT01234567    |  NULL         |  - 28.50
12345ABC    |  TOYS        |   9010456778       |  9010456778   |   300.00
12345ABC    |  NULL        |   9010456778       |  NULL         |   300.00
12345ABC    |  NULL        |   9019888878       |  NULL         |    47.90
12345ABC    |  CRAFTS      |   9502345671       |  9502345671   |   145.25
12345ABC    |  NULL        |   9502345671       |  NULL         |   145.25

I named the columns in this example for document number as "RM" to come out of the RM20101 table and "CUSTOM" to come out of the Custom_RecDate table.

So I've tried lots of ways, from CASE statements, to my WHERE clause, to a HAVING clause, to subqueries...  I can't figure it out.  Here's what I'd like to see:

CUSTNMBR    |  ItemType    |   DocumentNumberRM |  DocNumCUSTOM | DocAmount
------------+--------------+--------------------+---------------+-----------
12345ABC    |  NULL        |   PYMNT01234567    |  NULL         |  - 28.50
12345ABC    |  TOYS        |   9010456778       |  9010456778   |   300.00
12345ABC    |  NULL        |   9019888878       |  NULL         |    47.90
12345ABC    |  CRAFTS      |   9502345671       |  9502345671   |   145.25

So why did I call this multiple conditions?  Well, if you look at the table, I am cutting out items based on the following:

If both the ItemType And DocNumCUSTOM fields are NULL then show it.

If the ItemType IS NOT NULL and both document number fields are NOT NULL, then show it.

If the ItemType IS NULL and DocNumCUSTOM IS NULL, but we've already seen the document number in the RM20101 DocumentNumberRM field (which I suspect would be in a HAVING clause for a COUNT or something), then don't show it a second time.

If I don't find a way to do step 3, I will get the duplicates as shown in my initial example.

I basically do not want duplication.  I want to show an item type whether it be NULL (non-existent for that document number in either table) or show it only once if existent in the Custom_RecDate table, which is the only table that has the item type information in it.

Does this make sense?  I know it sounds complicated as heck, but hopefully someone can make sense of it all.  :)

Thanks!

By the way, here's the important part (my query, albeit very trimmed down for the example):

SELECT DISTINCT
    R1.CUSTNMBR,
    I.ITMCLSCD AS [ItemType],
    R1.DOCNUMBR AS [DocumentNumberRM],
    I.DOCNUMBR AS [DocNumCUSTOM],
    R1.ORTRXAMT AS [DocAmount]
FROM
    RM20101 R1
JOIN
    RM40401 R2 ON R2.RMDTYPAL = R1.RMDTYPAL
JOIN
    RM00401 R3 ON R3.DOCNUMBR = R1.DOCNUMBR
JOIN
    RM00101 R4 ON R4.CUSTNMBR = R1.CUSTNMBR
LEFT OUTER JOIN
    SR_ITCMCD C ON C.CUSTNMBR = R1.CUSTNMBR
LEFT OUTER JOIN
    AR_Description D ON D.SOPNUM = R1.DOCNUMBR
LEFT OUTER JOIN
    Custom_RecData I ON I.ITEMNMBR = C.ITEMNMBR
                     AND I.DOCNUMBR = R1.DOCNUMBR

Again, I've tried using CASE statements and putting various conditions in my WHERE clause, I just can't figure it out.

Body:
Purely based on the sample data, MAX() should do the trick:

SELECT
    R1.CUSTNMBR,
    MAX(I.ITMCLSCD) AS [ItemType],
    R1.DOCNUMBR AS [DocumentNumberRM],
    MAX(I.DOCNUMBR) AS [DocNumCUSTOM],
    R1.ORTRXAMT AS [DocAmount]
FROM RM20101 R1
JOIN RM40401 R2 ON R2.RMDTYPAL = R1.RMDTYPAL
JOIN RM00401 R3 ON R3.DOCNUMBR = R1.DOCNUMBR
JOIN RM00101 R4 ON R4.CUSTNMBR = R1.CUSTNMBR
LEFT OUTER JOIN SR_ITCMCD C ON C.CUSTNMBR = R1.CUSTNMBR
LEFT OUTER JOIN AR_Description D ON D.SOPNUM = R1.DOCNUMBR
LEFT OUTER JOIN Custom_RecData I ON I.ITEMNMBR = C.ITEMNMBR
                                AND I.DOCNUMBR = R1.DOCNUMBR
GROUP BY
    R1.CUSTNMBR,
    R1.DOCNUMBR,
    R1.ORTRXAMT

Removed the DISTINCT since GROUP BY will accomplish the same and is needed for MAX()


问:
How to deploy Class Library (dll or tbl file) with Installer

I have developed a new (small) class using .Net Framework (VB.NET) on Visual Studio and did a reference on VBA-Excel to execute a task. It worked fine on my machine, so the real problem here is to deploy this class on the client's machine.

When I did the build on Visual Studio, I've selected "Register for COM Interop", so it was created a .dll and .tbs file. I thought I could just use a reference on VBA to these files and everything would work fine, but it's not that simple. I have to register the dll on the system before I can use it, and the Visual Studio did that automatically on the build.

The question is, how can I make a common setup installer to only install those dll and tbl files into anyone's machine? The files must remain on a known folder so I can reference them on the VBA, but the windows register must know they exist!

What do I know so far:

On the build, Visual Studio uses Regasm.exe to register the dll; I
could use a bat file to call regasm.exe but it is not a option
because I would have to make a reference to it and each client could
have different .Net Framework versions, so I wouldn't be able to know
the full path of it.

regsvr32.exe won't work it either, since we need Admin Rights, and

the clients don't have it.

I could use ClickOnce, but it's a Class Library so the Publish option
does not exist.

Here I have some references, but I couldn't find a good solution yet.

https://www.red-gate.com/simple-talk/dotnet/visual-studio/build-and-deploy-a-.net-com-assembly/

https://social.msdn.microsoft.com/Forums/windows/en-US/70f5558c-cf53-4bc0-b3ea-435b6f5b3956/how-to-get-setup-project-to-register-assembly-for-com-interop?forum=winformssetup

https://social.msdn.microsoft.com/Forums/en-US/47d6dc58-37ce-4a34-9524-20dc1c1ffd90/how-to-use-clickonce-deployment-technology-for-class-library-project?forum=winformssetup

UPDATE 1

It seems that the only way of installing in the register is through regasm.exe or regsvr32, and both of 'em need elevated command prompt (with admin rights), something the clients do not have.

I guess the solution is to use registration-free activation of COM components, that it wouldn’t require updating Registry or placing assemblies in GAC. Here's the reference:

Is it possible to register a .NET assembly for COM interop without adding registry entries?

UPDATE 2

I've found this answer and I can feel that I'm real close to a solution:

Registering .Net COM DLLs without Admin rights / regasm

The thing is, the class that I've developed is using another class, which is PdfSharp. When I unregister the dll and try to register again (through regasm.exe), my VBA macro gives an error not when I'm creating the object, but when I'm executing a funtion of the class, saying that the PdfSharp couldn't be found.

The solution of this question doesn't say anything about using 3rd party library, and I thought that my .dll would bring the pdfsharp.dll as well.

Any ideias? I'm real close to solve this.

答:
I gave up trying to install the DLL on machines that haven't Admin Rights, so I've developed a Console app on Visual Studio and run it via Shell command on VBA, and it worked like a charm.

I'll set this as the right answer since it solved my problem, but I couldn't find a way to deploy a dll via installer on other machines.


问:
right way of inserting data into two tables in database simultaneously using java
i'm trying two insert two table simultaneously with foreign keys but it is not inserting and i don't why it's not working.
when i click the button, it only inserts the passenger table but leaves the luggage unfilled. I just want to get the id numbers of the foreign keys.
these are my code :-

The passenger database table:

The luggage database table:

and my code :-

```<code>private void InsertLuggageInfo() {
        try {
            String query_passenger = "INSERT INTO passenger (Firstname,Lastname,Email,"
                    + "PhoneNr,Address,Zipcode,City,Country_name) "
                    + "VALUES (?,?,?,?,?,?,?,?)";

        stmt = conn.prepareStatement(query_passenger);

        stmt.setString(1, txtFirstname.getText());
        stmt.setString(2, txtLastname.getText());
        stmt.setString(3, txtEmail.getText());
        stmt.setString(4, txtPhoneNr.getText());
        stmt.setString(5, txtAddress.getText());
        stmt.setString(6, txtZipCode.getText());
        stmt.setString(7, txtCity.getText());
        stmt.setString(8, txtCountry.getText());

        stmt.execute();
        stmt.close();

    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        String query_luggage = "INSERT INTO passenger (DateFound,TimeFound,"
                + "LuggageType_id,Brand_id,MainColor_id,Status_id,Size_id,"
                + "Weight_id,SecondColor_id,LuggageTag,Image,Location_Airport_id,"
                + "Airport_id,Passenger_id) "
                + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

        stmt = conn.prepareStatement(query_luggage);

        stmt.setString(1, txtDatum.getText());
        stmt.setString(2, txtTimeFound.getText());
        stmt.setInt(3, get_LuggageType_id());
        stmt.setInt(4, get_Brand_id());
        stmt.setInt(5, get_MainColor_id());
        stmt.setInt(6, get_Status_id());
        stmt.setInt(7, get_Size_id());
        stmt.setInt(8, get_Weight_id());
        stmt.setInt(9, get_SecondColor_id());
        stmt.setString(10, txtLuggageTag.getText());
        stmt.setString(11, imgLuggage.toString());
        stmt.setInt(12, get_LocationAirport_id());
        stmt.setInt(13, get_Airport_id());
        stmt.setInt(14, get_Passenger_id());

        stmt.execute();
        stmt.close();

    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
}
</code>```

my methods to get the id's :-

```<code> public int get_LuggageType_id() {
    int id = 0;
    try {

        String query = "Select LuggageType_id from luggagetype where LuggageType ='" + ddlLuggageType.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("LuggageType_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Brand_id() {
    int id = 0;
    try {

        String query = "Select Brand_id from brand where Brand ='" + ddlMerk.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Brand_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_MainColor_id() {
    int id = 0;
    try {

        String query = "Select MainColor_id from maincolor where Color ='" + ddlMainColor.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("MainColor_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Status_id() {
    int id = 0;
    try {

        String query = "Select Status_id from status where Status ='" + ddlStatus.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Status_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Size_id() {
    int id = 0;
    try {

        String query = "Select Size_id from size where Size ='" + ddlMerk.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Size_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Weight_id() {
    int id = 0;
    try {

        String query = "Select Weight_id from weight where Weight ='" + ddlWeight.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Weight");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Flight_id() {
    int id = 0;
    try {

        String query = "Select Flight_id from flight where Flight_number ='" + ddlWeight.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Flight_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_SecondColor_id() {
    int id = 0;
    try {

        String query = "Select SecondColor_id from secondcolor where Color ='" + ddlSecondColor.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("SecondColor_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_LocationAirport_id() {
    int id = 0;
    try {

        String query = "Select Location_Airport_id from location_airport where Location_name ='" + ddlLocationFound.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Location_Airport_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Airport_id() {
    int id = 0;
    try {

        String query = "Select Airport_id from airport where Airport_name ='" + ddlLuchthaven.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Airport_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Passenger_id() {
    int id = 0;
    try {

        String query = "Select Passenger_id from passenger where Firstname ='" + txtFirstname.getText() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Passenger_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}
</code>```

答:
First of all, you should change the way you get the generated ID. You can use stmt.getGeneratedKeys(), as following:

```<code>long passengerId = 0;
int affectedRows = stmt.executeUpdate();

if (affectedRows == 0) {
    throw new SQLException("Insert Passenger error: no rows were affected.");
}

try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
    if (generatedKeys.next()) {
        passengerID = generatedKeys.getLong(1);
    }
    else {
        throw new SQLException("Insert Passenger error: no ID obtained.");
    }
}
</code>```

This will garantee you get the new inserted data ID (your passenger FK).

Also, try to use stmt.executeUpdate() for both Inserts.

Body:
i'm trying two insert two table simultaneously with foreign keys but it is not inserting and i don't why it's not working.
when i click the button, it only inserts the passenger table but leaves the luggage unfilled. I just want to get the id numbers of the foreign keys.
these are my code :-

The passenger database table:

The luggage database table:

and my code :-

private void InsertLuggageInfo() {
        try {
            String query_passenger = "INSERT INTO passenger (Firstname,Lastname,Email,"
                    + "PhoneNr,Address,Zipcode,City,Country_name) "
                    + "VALUES (?,?,?,?,?,?,?,?)";

        stmt = conn.prepareStatement(query_passenger);

        stmt.setString(1, txtFirstname.getText());
        stmt.setString(2, txtLastname.getText());
        stmt.setString(3, txtEmail.getText());
        stmt.setString(4, txtPhoneNr.getText());
        stmt.setString(5, txtAddress.getText());
        stmt.setString(6, txtZipCode.getText());
        stmt.setString(7, txtCity.getText());
        stmt.setString(8, txtCountry.getText());

        stmt.execute();
        stmt.close();

    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        String query_luggage = "INSERT INTO passenger (DateFound,TimeFound,"
                + "LuggageType_id,Brand_id,MainColor_id,Status_id,Size_id,"
                + "Weight_id,SecondColor_id,LuggageTag,Image,Location_Airport_id,"
                + "Airport_id,Passenger_id) "
                + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

        stmt = conn.prepareStatement(query_luggage);

        stmt.setString(1, txtDatum.getText());
        stmt.setString(2, txtTimeFound.getText());
        stmt.setInt(3, get_LuggageType_id());
        stmt.setInt(4, get_Brand_id());
        stmt.setInt(5, get_MainColor_id());
        stmt.setInt(6, get_Status_id());
        stmt.setInt(7, get_Size_id());
        stmt.setInt(8, get_Weight_id());
        stmt.setInt(9, get_SecondColor_id());
        stmt.setString(10, txtLuggageTag.getText());
        stmt.setString(11, imgLuggage.toString());
        stmt.setInt(12, get_LocationAirport_id());
        stmt.setInt(13, get_Airport_id());
        stmt.setInt(14, get_Passenger_id());

        stmt.execute();
        stmt.close();

    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

my methods to get the id's :-

 public int get_LuggageType_id() {
    int id = 0;
    try {

        String query = "Select LuggageType_id from luggagetype where LuggageType ='" + ddlLuggageType.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("LuggageType_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Brand_id() {
    int id = 0;
    try {

        String query = "Select Brand_id from brand where Brand ='" + ddlMerk.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Brand_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_MainColor_id() {
    int id = 0;
    try {

        String query = "Select MainColor_id from maincolor where Color ='" + ddlMainColor.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("MainColor_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Status_id() {
    int id = 0;
    try {

        String query = "Select Status_id from status where Status ='" + ddlStatus.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Status_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Size_id() {
    int id = 0;
    try {

        String query = "Select Size_id from size where Size ='" + ddlMerk.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Size_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Weight_id() {
    int id = 0;
    try {

        String query = "Select Weight_id from weight where Weight ='" + ddlWeight.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Weight");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Flight_id() {
    int id = 0;
    try {

        String query = "Select Flight_id from flight where Flight_number ='" + ddlWeight.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Flight_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_SecondColor_id() {
    int id = 0;
    try {

        String query = "Select SecondColor_id from secondcolor where Color ='" + ddlSecondColor.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("SecondColor_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_LocationAirport_id() {
    int id = 0;
    try {

        String query = "Select Location_Airport_id from location_airport where Location_name ='" + ddlLocationFound.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Location_Airport_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Airport_id() {
    int id = 0;
    try {

        String query = "Select Airport_id from airport where Airport_name ='" + ddlLuchthaven.getSelectionModel().getSelectedItem().toString() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Airport_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

public int get_Passenger_id() {
    int id = 0;
    try {

        String query = "Select Passenger_id from passenger where Firstname ='" + txtFirstname.getText() + "'";
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            id = rs.getInt("Passenger_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Verloren_bagageController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return id;
}

Body:
First of all, you should change the way you get the generated ID. You can use stmt.getGeneratedKeys(), as following:

long passengerId = 0;
int affectedRows = stmt.executeUpdate();

if (affectedRows == 0) {
    throw new SQLException("Insert Passenger error: no rows were affected.");
}

try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
    if (generatedKeys.next()) {
        passengerID = generatedKeys.getLong(1);
    }
    else {
        throw new SQLException("Insert Passenger error: no ID obtained.");
    }
}

This will garantee you get the new inserted data ID (your passenger FK).

Also, try to use stmt.executeUpdate() for both Inserts.


问:
max of numeric columns with dplyr
Say, I have a dataframe df with some text and some numeric columns

```<code>species            | short | A    | B    | C
-------------------+-------+------+------+-----
Homo sapiens       | hsa   | 0.1  | 0.2  | 0.7
Mus musculus       | mmu   | 0.3  | 0.7  | 0.0
Rattus norvegicus  | rno   | 0.0  | 1.0  | 0.0
</code>```

I know that I can add a column computing the max of all columns using dplyr, but this works only if all columns are numeric:

```<code>df %>%
    rowwise() %>%
    mutate(max_score = max(.))
</code>```

How can I achieve the same, ignoring all non-numeric columns?

(Obviously, I could name A, B, C manually, but suppose I have a 'fat' data frame with many columns.)

答:
You can use select_if with is.numeric to select numeric columns, and use do.call(pmax, ...) to calculate the rowwise maximum; pmax returns the parallel maxima of input vectors, since it takes vectors as individual argument, we can use do.call to pass all columns of select_if's return (a data frame) as arguments to pmax:

```<code>df %>% mutate(max_score = do.call(pmax, select_if(., is.numeric)))

#            species short   A   B   C max_score
#1      Homo sapiens   hsa 0.1 0.2 0.7       0.7
#2      Mus musculus   mmu 0.3 0.7 0.0       0.7
#3 Rattus norvegicus   rno 0.0 1.0 0.0       1.0
</code>```

Title: max of numeric columns with dplyr

Body:
Say, I have a dataframe df with some text and some numeric columns

species            | short | A    | B    | C
-------------------+-------+------+------+-----
Homo sapiens       | hsa   | 0.1  | 0.2  | 0.7
Mus musculus       | mmu   | 0.3  | 0.7  | 0.0
Rattus norvegicus  | rno   | 0.0  | 1.0  | 0.0

I know that I can add a column computing the max of all columns using dplyr, but this works only if all columns are numeric:

df %>%
    rowwise() %>%
    mutate(max_score = max(.))

How can I achieve the same, ignoring all non-numeric columns?

(Obviously, I could name A, B, C manually, but suppose I have a 'fat' data frame with many columns.)

Body:
You can use select_if with is.numeric to select numeric columns, and use do.call(pmax, ...) to calculate the rowwise maximum; pmax returns the parallel maxima of input vectors, since it takes vectors as individual argument, we can use do.call to pass all columns of select_if's return (a data frame) as arguments to pmax:

df %>% mutate(max_score = do.call(pmax, select_if(., is.numeric)))

#            species short   A   B   C max_score
#1      Homo sapiens   hsa 0.1 0.2 0.7       0.7
#2      Mus musculus   mmu 0.3 0.7 0.0       0.7
#3 Rattus norvegicus   rno 0.0 1.0 0.0       1.0


问:
VCHI initialization failed screen error when executing sh script from php
I want to trigger the screen power on a raspberry pi from an simple php site.

I'm using apache 2 and php7 on raspbian and the files are stored on /var/www/html/controller and all have chmod 777 set.

this is how my php site looks:

```<code><?php
if ($_GET['on']) {
    shell_exec("/var/www/html/controller/on.sh");
}
?>
<a href="?on=true">turn on</a>
</code>```

and my on.sh file like this:

```<code>#!/bin/bash
vcgencmd display_power 1
</code>```

when I click the link I get the following error:

VCHI initialization failed screen

Any suggestions how to fix this?

答:
I figured out that the .sh files need more permissions. To be more precise the user www-data as described here https://unix.stackexchange.com/a/127529

To do so:

Run the command sudo visudo

add www-data ALL=NOPASSWD: /var/www/html/controller/ on the very end

modify shell_exec("/var/www/html/controller/on.sh"); to shell_exec("sudo /var/www/html/controller/on.sh");

Body:
I want to trigger the screen power on a raspberry pi from an simple php site.

I'm using apache 2 and php7 on raspbian and the files are stored on /var/www/html/controller and all have chmod 777 set.

this is how my php site looks:

<?php
if ($_GET['on']) {
    shell_exec("/var/www/html/controller/on.sh");
}
?>
turn on

and my on.sh file like this:

#!/bin/bash
vcgencmd display_power 1

when I click the link I get the following error:

VCHI initialization failed screen

Any suggestions how to fix this?


问:
INSERT INTO error for MYSQL
Hi this is my first time posting. I have searched all over for an answer but can't seem to find one that fixes mine. I am writing mysql code for a project and can't seem to insert data into a database I am creating. The link to the code is here:

http://sqlfiddle.com/#!9/be69b

Below is what I have come up with so far

```<code>CREATE TABLE IF NOT EXISTS `customers` (`CustomerID` INT AUTO_INCREMENT,
`FirstName` VARCHAR(255) NOT NULL,
`LastName` VARCHAR(255) NOT NULL,
`Address` VARCHAR(255) NOT NULL,
`Apt#` VARCHAR(255) NOT NULL,
`City` VARCHAR(50) NOT NULL,
`State` VARCHAR(3) NOT NULL,
`Zip` VARCHAR(9) NOT NULL,
`HomePhone` VARCHAR(11),
`MobilePhone` VARCHAR(11),
`OtherPhone` VARCHAR(11),
PRIMARY KEY(`CustomerID`)
)
ENGINE=INNODB;

INSERT INTO `customers` VALUES
(`1`, `John`, `Doe`, `123 Green St.`, `Apt A.`, `Richmond`, `VA`, `78646`, `18049481616`, ``, ``);
</code>```

It throws out an error saying that Unknown column 1 in field list. I have tried doing this without AUTO_INCREMENT and it doesn't change anything. Can anyone help with this? Thanks for your help!

答:
You define your table with "CustomerId" (auto_increment), so you shouldn't give a value for it in your insert-statement.

```<code>(1, John, Doe, 123 Green St., Apt A., Richmond, VA, 78646, 18049481616, ,)
</code>```

should be

```<code>(John, Doe, 123 Green St., Apt A., Richmond, VA, 78646, 18049481616, ,)
</code>```

That's what i think!

Title: INSERT INTO error for MYSQL

Body:
Hi this is my first time posting. I have searched all over for an answer but can't seem to find one that fixes mine. I am writing mysql code for a project and can't seem to insert data into a database I am creating. The link to the code is here:

http://sqlfiddle.com/#!9/be69b

Below is what I have come up with so far

CREATE TABLE IF NOT EXISTS `customers` (`CustomerID` INT AUTO_INCREMENT,
`FirstName` VARCHAR(255) NOT NULL,
`LastName` VARCHAR(255) NOT NULL,
`Address` VARCHAR(255) NOT NULL,
`Apt#` VARCHAR(255) NOT NULL,
`City` VARCHAR(50) NOT NULL,
`State` VARCHAR(3) NOT NULL,
`Zip` VARCHAR(9) NOT NULL,
`HomePhone` VARCHAR(11),
`MobilePhone` VARCHAR(11),
`OtherPhone` VARCHAR(11),
PRIMARY KEY(`CustomerID`)
)
ENGINE=INNODB;

INSERT INTO `customers` VALUES
(`1`, `John`, `Doe`, `123 Green St.`, `Apt A.`, `Richmond`, `VA`, `78646`, `18049481616`, ``, ``);

It throws out an error saying that Unknown column 1 in field list. I have tried doing this without AUTO_INCREMENT and it doesn't change anything. Can anyone help with this? Thanks for your help!

Body:
You define your table with "CustomerId" (auto_increment), so you shouldn't give a value for it in your insert-statement.

(1, John, Doe, 123 Green St., Apt A., Richmond, VA, 78646, 18049481616, ,)

should be

(John, Doe, 123 Green St., Apt A., Richmond, VA, 78646, 18049481616, ,)

That's what i think!


问:
How to convert numpy array to batches while feeding tensorflow session for training
The dataset is large how to use feed data using a batch size of 100.
x_u is image data and y_u is labels
    x_u, y_u are of sizes 2000000
    with tf.Session() as sess:
    #writer = tf.summary.FileWriter("output", sess.graph)
    sess.run(tf.global_variables_initializer())
    for i in range(3):
        train_accuracy = accuracy.eval(feed_dict={x: x_u, y_: y_u, keep_prob: 1.0})
        print('step %d, training accuracy: %g',  (i, train_accuracy))
        train_step.run(feed_dict={x: x_u, y_: y_u, keep_prob:0.5})

答:
```<code>BATCH_SIZE = 100
for offset in range(0, len(y_u), BATCH_SIZE):
    batch_x = x_u[offset: offset + BATCH_SIZE]
    batch_y = y_u[offset: offset + BATCH_SIZE]

    # Feed batch_x an batch_y
</code>```