问:
Spark scala :FIle already exists exception while Uploading csv file to azure blob
I am reading sas file from azure blob . Converting it to csv and trying to upload csv  to azure blob . However for small files in MBs I am able to do the same successfully with the following spark scala code .

```<code>    import org.apache.spark.SparkContext
    import org.apache.spark.SparkConf
    import org.apache.spark.sql.SQLContext
    import com.github.saurfang.sas.spark._

     val sqlContext = new SQLContext(sc)
   val df=sqlContext.sasFile("wasbs://container@storageaccount/input.sas7bdat")
     df.write.format("csv").save("wasbs://container@storageaccount/output.csv");
</code>```

But for large files in GB it gives me Analysis exception wasbs://container@storageaccount/output.csv file already exists exception. I have tried overwrite also . But no luck . Any help would be appriciated

答:
Actually, you could not overwrite an existing file on HDFS normally, even for small files in MBs.

Please try to use the code below to overwrite, please check your spark version because there are some differences to use the methed for different spark version.

```<code>df.write.format("csv").mode("overwrite").save("wasbs://container@storageaccount/output.csv");
</code>```

I don't know the code above using overwrite mode whether you had tried as you said.

So there is another way to do it that first delete the existing files befer do the overwrite operation.

```<code>val hadoopConf = new org.apache.hadoop.conf.Configuration()
val hdfs = org.apache.hadoop.fs.FileSystem.get(new java.net.URI("<hdfs://<namenodehost>/ or wasb[s]://<containername>@<accountname>.blob.core.windows.net/<path> >"), hadoopConf)
try { hdfs.delete(new org.apache.hadoop.fs.Path(filepath), true) } catch { case _ : Throwable => { } }
</code>```

And there is a spark topic discussed similar issue, please see http://apache-spark-user-list.1001560.n3.nabble.com/How-can-I-make-Spark-1-0-saveAsTextFile-to-overwrite-existing-file-td6696.html.

Body:
I am reading sas file from azure blob . Converting it to csv and trying to upload csv  to azure blob . However for small files in MBs I am able to do the same successfully with the following spark scala code .

    import org.apache.spark.SparkContext
    import org.apache.spark.SparkConf
    import org.apache.spark.sql.SQLContext
    import com.github.saurfang.sas.spark._

     val sqlContext = new SQLContext(sc)
   val df=sqlContext.sasFile("wasbs://container@storageaccount/input.sas7bdat")
     df.write.format("csv").save("wasbs://container@storageaccount/output.csv");

But for large files in GB it gives me Analysis exception wasbs://container@storageaccount/output.csv file already exists exception. I have tried overwrite also . But no luck . Any help would be appriciated

Body:
Actually, you could not overwrite an existing file on HDFS normally, even for small files in MBs.

Please try to use the code below to overwrite, please check your spark version because there are some differences to use the methed for different spark version.

df.write.format("csv").mode("overwrite").save("wasbs://container@storageaccount/output.csv");

I don't know the code above using overwrite mode whether you had tried as you said.

So there is another way to do it that first delete the existing files befer do the overwrite operation.

val hadoopConf = new org.apache.hadoop.conf.Configuration()
val hdfs = org.apache.hadoop.fs.FileSystem.get(new java.net.URI("<hdfs://<namenodehost>/ or wasb[s]://<containername>@<accountname>.blob.core.windows.net/<path> >"), hadoopConf)
try { hdfs.delete(new org.apache.hadoop.fs.Path(filepath), true) } catch { case _ : Throwable => { } }

And there is a spark topic discussed similar issue, please see http://apache-spark-user-list.1001560.n3.nabble.com/How-can-I-make-Spark-1-0-saveAsTextFile-to-overwrite-existing-file-td6696.html.


来源: stackexchange

问:
iOS 8: Launch Screen StoryBoard appears black [single XIB file works fine]
So I tried creating a launch storyboard for my iOS 8 app using this tutorial

However, I only get a black screen when I launch my app. A single launch screen.xib file works perfectly, however, when I try to use a storyboard, it doesn't work.

I tried a storyboard with just a single view controller, but it still gives me a black screen, hence I believe the issue is with storyboard files in my setup. Any ideas?

[XCode version 6.4]

EDIT: So I just want to clarify that it is the launch screen that appears black. The main storyboard itself appears correctly when the app has finished loading

答:
For people using UIImageView in the launch screen

Make sure that you are using the image name without the extension in the attributes inspector.

So for example, if your image file is named launcher.png, only use launcher as image name.

This will show the image as invalid (?) in the editor but will show correctly when run on device.

(Don't ask me why it works this way. Ask Apple.)

ContentLicense: CC BY-SA 3.0


问:
How to change the program-->From "Submit Button" to "onchange javascript seleced" dropdown list?
I am creating a page in JSP where I have a three related dropdown list
and once the user selects a value from first dropdown list called
"prefecture" then he has to click on the 'next' button and then the
related value is sent to second dropdown list called "line" then he
has to click again to 'next' button and then the related value is sent
to third dropdown list called "station" and last click  save button
then related company list will be appear from selected nearest
station. and my coding in below:

```<code><body style="overflow: hidden;padding:5px;border-radius:5px;border:1px solid #777">
    <div>
        <div>
        <span id="wishtxt" style="color:#dd0000;font-size: 150%;display:none"></span>
        <form action="<?php echo REQUEST_PATH?>" id="form_eki">
    <?php if($h->is_action('index'))://------------------------------------------------------------------------------------------------------------------------?>
        <input type="hidden" name="wish">

        <div>
            <div style="margin-top: 3px;">
            <select name="pref" tabindex="6" style="width: auto;">
            <option value="">-- select prefecture name --</option>
            <?php $h->pr_ops_pref($h->get_target_pref())?>
            </select>
            <button name="action" value="line" type="submit" tabindex="7">Next</button>
        </div>

    <?php elseif($h->is_action('line'))://------------------------------------------------------------------------------------------------------------------------?>
            <input type="hidden" name="wish">
            <input type="hidden" name="pref">

            <div>
                 <div style="margin-top: 3px;">
                <select name="pref" tabindex="6" style="width: auto;">
                <option value="">-- select prefecture name --</option>
                <?php $h->pr_ops_pref($h->get_target_pref())?>
                </select>
                <button name="action" value="line" type="submit" tabindex="7">Change</button>
                </div>
            </div>

        <?php if($h->d('list_station')):?>

            <div style="margin-top: 3px;">
                <select name="line" tabindex="8" style="width: auto;max-width: 350px;">
                    <?php $h->pr_ops_db($h->d('list_line'),'line_cd',"line_name") ?>
                </select>
                <span>
                    <button name="action" val2ue="line" type="submit" tabindex="9">Change</button>
                </span>
            </div>

            <?php
                $imax = count($h->d('list_station'));
            ?>
            <div style="margin-top: 5px;">
                <select id="station_cd" name="station_cd" style="width: auto;max-width: 350px;">
                <option value="" selected>-- Select the nearest station--</option>
                <?php for ($i=0;$i<$imax;$i++):?>
                <option value="<?php $h->pr_d("list_station/$i/station_cd");?>"><?php $h->pr_d("list_station/$i/station_name")?></option>
                <?php endfor;?>
                </select>
            </div>
            <div style="margin-top: 5px;">
                <button type="submit" name="action" value="clear" tabindex="4">back</button>
                <button id="btn_eki" type="button" tabindex="4" style="color:red">save</button>
            </div>

        <?php elseif($h->d('list_line')):?>
            <h3 style="margin-top: 5px;">Select a railway line</h3>
            <?php
                $company_name = '';
                $imax = count($h->d('list_line'));
            ?>
            <div style="margin-top: 3px;">
            <select name="line" style="width: auto;max-width: 250px;">
                <optgroup label="">
                    <option value="" selected>-- Select nearest railway line --</option>
            <?php for ($i = 0; $i<$imax; $i++):?>
            <?php if($h->d("list_line/$i/company_name") != $company_name):?>
                <?php $company_name = $h->d("list_line/$i/company_name");?>
                </optgroup>
                <optgroup label="<?php echo $company_name;?>">
            <?php endif;?>
                    <option value="<?php $h->pr_d("list_line/$i/line_cd")?>"><?php $h->pr_d("list_line/$i/line_name")?></option>
            <?php endfor;?>
                </optgroup>
            </select>
            </div>
            <div style="margin-top: 3px;">
                <button type="submit" name="action" value="clear" tabindex="4">back</button>
                <button type="submit" name="action" value="line">Next</button>
            </div>
        <?php endif;?>
    <?php endif;//------------------------------------------------------------------------------------------------------------------------?>
        </form>
        </div>
    </div>
</body>
</code>```

But Now i want to make it only three dropdown list and "onChange
select" and there will be no button for "Next" "Back" or "Save". When
i select "Prefecture" from first dropdown list the automitacaly will
be updated to "Line" second dropdown list and when i select second
dropdown list then automitacaly will be updated to "Station" third
dropdown list and finally auto saved in back-end and   related company
list will be appear from selected nearest station.

Thanks for your information.I have changed in following way but when i
  select "prefecture" from first dropdown list then the second dropdown
  list called "line" will not appear... Can anybody help me to sort it out?

my javascript:

```<code>$(document).ready(function(){
    $('#pref_cd').on('change',function(){
        $('#line_cd').val('');
        $('#station_cd').val('');
        $('#form_eki').submit();
        return true;
    });
    $('#line_cd').on('change',function(){
        $('#station_cd').val('');
        $('#form_eki').submit();
        return true;
    });
    $('#btn_eki').click(function(){
        var $option = $('#station_cd option:selected');
        var station_cd = $option.val();
        window.parent.add_tag(station_cd, "", $('#wishtxt').html(),1);
        window.parent.$('#nearStForm' + $('input[name="wish"]').val()).slideUp();
    });
    $('.close').click(function() {
        window.parent.$('#nearStForm' + $('input[name="wish"]').val()).slideUp();
    });
    $('#btn_clear').click(function(){

    });
    $('#wishtxt').html($('#form_eki [name="wish"]').val());
});
</code>```

and i have deleted all buttons & changes programs are
  in First dropdownlist:

```<code><select name="pref" id="pref" onChange="this.form.submit()" tabindex="6" style="width: auto;">
    <option value="">-- select prefecture name --</option>
    <?php $h->pr_ops_pref($h->get_target_pref())?>
</select>
</code>```

in Second dropdownlist:

```<code><select name="line" id="line" onChange="this.form.submit()" tabindex="8" style="width: auto;max-width: 350px;">
    <?php $h->pr_ops_db($h->d('list_line'),'line_cd',"line_name") ?>
</select>
</code>```

in third dropdownlist:

```<code><select id="station_cd" onChange="this.form.submit()" name="station_cd" style="width: auto;max-width: 350px;">
    <option value="" selected>-- Select the nearest station--</option>
    <?php for ($i=0;$i<$imax;$i++):?>
        <option value="<?php $h->pr_d("list_station/$i/station_cd");?>"><?php $h->pr_d("list_station/$i/station_name")?></option>
    <?php endfor;?>
</select>
</code>```

答: On change of "prefecture" call an javascript function inside which call an ajax functionality.In this ajax call do the same thing as you performed inside form submit().On success of ajax call populate 2nd dropdown & do the same thing with 2nd dropdown also.</p>

Body:
I am creating a page in JSP where I have a three related dropdown list
and once the user selects a value from first dropdown list called
"prefecture" then he has to click on the 'next' button and then the
related value is sent to second dropdown list called "line" then he
has to click again to 'next' button and then the related value is sent
to third dropdown list called "station" and last click  save button
then related company list will be appear from selected nearest
station. and my coding in below:

        <form action="<?php echo REQUEST_PATH?>" id="form_eki">
    <?php if($h->is_action('index'))://------------------------------------------------------------------------------------------------------------------------?>
        <input type="hidden" name="wish">

            <select name="pref" tabindex="6" style="width: auto;">
            <option value="">-- select prefecture name --</option>
            <?php $h->pr_ops_pref($h->get_target_pref())?>
            </select>
            <button name="action" value="line" type="submit" tabindex="7">Next</button>

    <?php elseif($h->is_action('line'))://------------------------------------------------------------------------------------------------------------------------?>
            <input type="hidden" name="wish">
            <input type="hidden" name="pref">

                <select name="pref" tabindex="6" style="width: auto;">
                <option value="">-- select prefecture name --</option>
                <?php $h->pr_ops_pref($h->get_target_pref())?>
                </select>
                <button name="action" value="line" type="submit" tabindex="7">Change</button>

        <?php if($h->d('list_station')):?>

                <select name="line" tabindex="8" style="width: auto;max-width: 350px;">
                    <?php $h->pr_ops_db($h->d('list_line'),'line_cd',"line_name") ?>
                </select>

                    <button name="action" val2ue="line" type="submit" tabindex="9">Change</button>

            <?php
                $imax = count($h->d('list_station'));
            ?>

                <select id="station_cd" name="station_cd" style="width: auto;max-width: 350px;">
                <option value="" selected>-- Select the nearest station--</option>
                <?php for ($i=0;$i<$imax;$i++):?>
                <option value="<?php $h->pr_d("list_station/$i/station_cd");?>"><?php $h->pr_d("list_station/$i/station_name")?></option>
                <?php endfor;?>
                </select>

                <button type="submit" name="action" value="clear" tabindex="4">back</button>
                <button id="btn_eki" type="button" tabindex="4" style="color:red">save</button>

        <?php elseif($h->d('list_line')):?>

Select a railway line

            <?php
                $company_name = '';
                $imax = count($h->d('list_line'));
            ?>

            <select name="line" style="width: auto;max-width: 250px;">
                <optgroup label="">
                    <option value="" selected>-- Select nearest railway line --</option>
            <?php for ($i = 0; $i<$imax; $i++):?>
            <?php if($h->d("list_line/$i/company_name") != $company_name):?>
                <?php $company_name = $h->d("list_line/$i/company_name");?>
                </optgroup>
                <optgroup label="<?php echo $company_name;?>">
            <?php endif;?>
                    <option value="<?php $h->pr_d("list_line/$i/line_cd")?>"><?php $h->pr_d("list_line/$i/line_name")?></option>
            <?php endfor;?>
                </optgroup>
            </select>

                <button type="submit" name="action" value="clear" tabindex="4">back</button>
                <button type="submit" name="action" value="line">Next</button>

        <?php endif;?>
    <?php endif;//------------------------------------------------------------------------------------------------------------------------?>
        </form>

But Now i want to make it only three dropdown list and "onChange
select" and there will be no button for "Next" "Back" or "Save". When
i select "Prefecture" from first dropdown list the automitacaly will
be updated to "Line" second dropdown list and when i select second
dropdown list then automitacaly will be updated to "Station" third
dropdown list and finally auto saved in back-end and   related company
list will be appear from selected nearest station.

Thanks for your information.I have changed in following way but when i
  select "prefecture" from first dropdown list then the second dropdown
  list called "line" will not appear... Can anybody help me to sort it out?

my javascript:

$(document).ready(function(){
    $('#pref_cd').on('change',function(){
        $('#line_cd').val('');
        $('#station_cd').val('');
        $('#form_eki').submit();
        return true;
    });
    $('#line_cd').on('change',function(){
        $('#station_cd').val('');
        $('#form_eki').submit();
        return true;
    });
    $('#btn_eki').click(function(){
        var $option = $('#station_cd option:selected');
        var station_cd = $option.val();
        window.parent.add_tag(station_cd, "", $('#wishtxt').html(),1);
        window.parent.$('#nearStForm' + $('input[name="wish"]').val()).slideUp();
    });
    $('.close').click(function() {
        window.parent.$('#nearStForm' + $('input[name="wish"]').val()).slideUp();
    });
    $('#btn_clear').click(function(){

    });
    $('#wishtxt').html($('#form_eki [name="wish"]').val());
});

and i have deleted all buttons & changes programs are
  in First dropdownlist:

<select name="pref" id="pref" onChange="this.form.submit()" tabindex="6" style="width: auto;">
    <option value="">-- select prefecture name --</option>
    <?php $h->pr_ops_pref($h->get_target_pref())?>
</select>

in Second dropdownlist:

<select name="line" id="line" onChange="this.form.submit()" tabindex="8" style="width: auto;max-width: 350px;">
    <?php $h->pr_ops_db($h->d('list_line'),'line_cd',"line_name") ?>
</select>

in third dropdownlist:

<select id="station_cd" onChange="this.form.submit()" name="station_cd" style="width: auto;max-width: 350px;">
    <option value="" selected>-- Select the nearest station--</option>
    <?php for ($i=0;$i<$imax;$i++):?>
        <option value="<?php $h->pr_d("list_station/$i/station_cd");?>"><?php $h->pr_d("list_station/$i/station_name")?></option>
    <?php endfor;?>
</select>


问:
not 'string' in line .vs. 'string' not in line
Assuming one has a string like so:

my_line = 'this is a line of text\n'

and wants to check for the absence of a word, e.g., the word 'row'.

Is there any difference between using:

a) if not 'row' in my_line:

and

b) if 'row' not in my_line:

Are the two exactly the same in this case? Is there any case in which the two diverge?

答:
They are identical, you can see this from the dis CPython bytecode output:

```<code>>>> import dis
>>> def f1():
...     if not 'row' in my_line: pass
...
>>> def f2():
...     if 'row' not in my_line: pass
...
>>> dis.dis(f1)
  2           0 LOAD_CONST               1 ('row')
              2 LOAD_GLOBAL              0 (my_line)
              4 COMPARE_OP               7 (not in)
              6 POP_JUMP_IF_FALSE        8
        >>    8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
>>> dis.dis(f2)
  2           0 LOAD_CONST               1 ('row')
              2 LOAD_GLOBAL              0 (my_line)
              4 COMPARE_OP               7 (not in)
              6 POP_JUMP_IF_FALSE        8
        >>    8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
</code>```

Body:
They are identical, you can see this from the dis CPython bytecode output:

>>> import dis
>>> def f1():
...     if not 'row' in my_line: pass
...
>>> def f2():
...     if 'row' not in my_line: pass
...
>>> dis.dis(f1)
  2           0 LOAD_CONST               1 ('row')
              2 LOAD_GLOBAL              0 (my_line)
              4 COMPARE_OP               7 (not in)
              6 POP_JUMP_IF_FALSE        8
        >>    8 LOAD_CONST               0 (None)
             10 RETURN_VALUE
>>> dis.dis(f2)
  2           0 LOAD_CONST               1 ('row')
              2 LOAD_GLOBAL              0 (my_line)
              4 COMPARE_OP               7 (not in)
              6 POP_JUMP_IF_FALSE        8
        >>    8 LOAD_CONST               0 (None)
             10 RETURN_VALUE


问:
Will my attribute get assigned its default value if I use an initializer list?
I've got a class like,

```<code>public class Revex
{
    public IEnumerable<char> AllCharacters = Enumerable.Range(0, 256).Select(Convert.ToChar).Where(c => !char.IsControl(c)).ToArray();
    // ...
</code>```

If I initialize it with

```<code>var r = new Revex { AllCharacters = "abcd" };
</code>```

Will that line above get executed or not (Enumerable.Range...)? If I want it to not get called when I construct my class this way, how would I do that?

I've got about 10 optional character classes like that, so I don't want to write a constructor for every possible combination of them.

答:
If you initialise a class variable with it's declaration, the initialisation will happen. So in this case your field will get set twice, once as the class is created and then again when you set the property.

If you want the initialisation to be optional then you need to declare it as:

```<code>public IEnunerable<char> AllCharacters;
</code>```

you will then need to initialise it in your constructor or as you have done by setting the property.

ContentLicense: CC BY-SA 2.5

Body:
I've got a class like,

public class Revex
{
    public IEnumerable<char> AllCharacters = Enumerable.Range(0, 256).Select(Convert.ToChar).Where(c => !char.IsControl(c)).ToArray();
    // ...

If I initialize it with

var r = new Revex { AllCharacters = "abcd" };

Will that line above get executed or not (Enumerable.Range...)? If I want it to not get called when I construct my class this way, how would I do that?

I've got about 10 optional character classes like that, so I don't want to write a constructor for every possible combination of them.

Body:
If you initialise a class variable with it's declaration, the initialisation will happen. So in this case your field will get set twice, once as the class is created and then again when you set the property.

If you want the initialisation to be optional then you need to declare it as:

public IEnunerable<char> AllCharacters;

you will then need to initialise it in your constructor or as you have done by setting the property.


问:
How to find options available when installing an application using Installshield
I am trying to install Perforce Helix using Chef. Install file is an .exe file with 4 options available to install. I want to install 3 of them excluding one. Is there a way to identify which option to provide to it from command line. Currently I am able to install package in silent mode and with default settings using

```<code>installer_type :custom
  options %W[
    /s
    /v/qn
  ].join(' ')
</code>```

Any help is appreciated.

答:
Thanks guys, I got the solution. I first installed the application and then removed P4ADMIN from it: </p>

```<code>`installer_type :custom
options %W[
    /s
    /v"ADDLOCAL=ALL REMOVE=P4ADMIN /qn"
].join(' ')`
</code>```

Body:
I am trying to install Perforce Helix using Chef. Install file is an .exe file with 4 options available to install. I want to install 3 of them excluding one. Is there a way to identify which option to provide to it from command line. Currently I am able to install package in silent mode and with default settings using

installer_type :custom
  options %W[
    /s
    /v/qn
  ].join(' ')

Any help is appreciated.

Body:
Thanks guys, I got the solution. I first installed the application and then removed P4ADMIN from it:

`installer_type :custom
options %W[
    /s
    /v"ADDLOCAL=ALL REMOVE=P4ADMIN /qn"
].join(' ')`


问:
Json with dynamic properties - deserialize into C# object
I have the following JSON when user clicks save

```<code>tasks      : {
        updated : [
            { Id : 123, SomeField1 : 'new value', SomeField2 : 'new value', SomeField3 : 'new value' },
            { Id : 125, SomeField2 : 'new value' },
            { Id : 127, SomeField1 : 'new value', SomeField4 : 'new value' },
            { Id : 129, SomeField2 : 'new value', SomeField3 : 'new value' },
            { ................ }
        ],
        removed : [
            { Id : 345 },
            { Id : 847 }
        ]
    }
</code>```

on the MVC server side (C#), I have a ViewModel and .NET deserializes this back to my viewmodel object.
in this example, This object has Id, SomeField1, SomeField2, SomeField3, SomeField4.

The problem I am having is that the client only sends the fields which were actually updated, so If the user never updated SomeField3 it wont be in the json and .NET for that array object will have a null as SomeeField3 ...

so i cant get record, update all the fields to what the viewmodel is and then call an update as it will set SomeField3 to null , which is not correct - there could be data in that field which the user just didn't touch in this case .. (in another case they may have deleted their text, which then the update would be valid..

I am not sure what is the best way to tackle this problem.
Looking forward to your suggestions.

答:
if you are using Newton Json for Deserializing.
Newton Json DeserializeObject method has an overload which takes json string and JsonSerializerSettings as parameters. JsonSerializerSettings has NullValueHandling and MissingMemberHandling properties.

MissingMemberHandling: Gets or sets how missing members (e.g. JSON contains a property that isn't a member on the object) are handled
during deserialization.

NullValueHandling:  Gets or sets how null values are handled during serialization and deserialization

Body:
I have the following JSON when user clicks save

tasks      : {
        updated : [
            { Id : 123, SomeField1 : 'new value', SomeField2 : 'new value', SomeField3 : 'new value' },
            { Id : 125, SomeField2 : 'new value' },
            { Id : 127, SomeField1 : 'new value', SomeField4 : 'new value' },
            { Id : 129, SomeField2 : 'new value', SomeField3 : 'new value' },
            { ................ }
        ],
        removed : [
            { Id : 345 },
            { Id : 847 }
        ]
    }

on the MVC server side (C#), I have a ViewModel and .NET deserializes this back to my viewmodel object.
in this example, This object has Id, SomeField1, SomeField2, SomeField3, SomeField4.

The problem I am having is that the client only sends the fields which were actually updated, so If the user never updated SomeField3 it wont be in the json and .NET for that array object will have a null as SomeeField3 ...

so i cant get record, update all the fields to what the viewmodel is and then call an update as it will set SomeField3 to null , which is not correct - there could be data in that field which the user just didn't touch in this case .. (in another case they may have deleted their text, which then the update would be valid..

I am not sure what is the best way to tackle this problem.
Looking forward to your suggestions.


问:
Incredibly slow cache:clear of symfony in dev environment
I am facing problem from last few months that in my local environment the command cache:clear is incredibly slow. Many times it takes more than a minute. I tried it with both XAMPP and WAMP but It didn't help. I tried to solve by removing different services and bundles but situation remains same.

At the end I found the problem is directly proportionate to the number of Twig files I have in my Resources/Views Folder. I even created a new symfony project with standard command

composer create-project symfony/framework-standard-edition
  test-performance-project "2.7.*"

and created a simple standard controller and twig file to check my hypothesis. The more twig files I added in Resources/Views Folder, the slower the cache:clear command was (More or less proportional). Is there a way to prevent this because in our project we have high number of twig files in our Resources folder.

I am using

Windows     10
PHP          7.0.15
Symfony      2.7.23
Twig         1.31.0

Any help will be highly appreciated :)

答:
A symfony core developer asked me that he always do rm -fr var/cache/* so I always do this before running my app.

Also in config_dev.yml make template caching false

```<code>twig:
    cache:false
</code>```

Body:
A symfony core developer asked me that he always do rm -fr var/cache/* so I always do this before running my app.

Also in config_dev.yml make template caching false

twig:
    cache:false


问:
A segment of code does not work as intended Python 3
Code:

```<code> while True:
  print('who are you')
  name = input()
  if name != (str('joe')):
   continue
  print('hello joe whats the password?')
  if password == 'saltysea':
   break
print ('access granted')
</code>```

the code gets stuck when i input joe: it keeps asking "who are you"

Edit: heres what i did to get the intended result

```<code> password = '0'
while True:
  print('who are you')
  name=input()
  if name != 'joe':
   continue
  print('hello joe whats the password?')
  password=input()
  if password == 'saltysea':
  break

print ('access granted')
</code>```

答:
The continue statement in Python returns the control to the
  beginning of the while loop. The continue statement rejects all the
  remaining statements in the current iteration of the loop and moves
  the control back to the top of the loop.

(Compare TP)

So in your case, you are iterating from top of while to the continue statement over and over. If you want to stop loop from executing after the name is not joe, use break

Your code should look something like this:

```<code>   while True:
           name = input('who are you')
           if name != (str('joe')):
                   break
           else:
                   password = input('hello joe whats the password?')
                   if password == 'saltysea':
                   print ('access granted')
                   break
</code>```

Body:
Code:

 while True:
  print('who are you')
  name = input()
  if name != (str('joe')):
   continue
  print('hello joe whats the password?')
  if password == 'saltysea':
   break
print ('access granted')

the code gets stuck when i input joe: it keeps asking "who are you"

Edit: heres what i did to get the intended result

 password = '0'
while True:
  print('who are you')
  name=input()
  if name != 'joe':
   continue
  print('hello joe whats the password?')
  password=input()
  if password == 'saltysea':
  break

print ('access granted')

Body:
The continue statement in Python returns the control to the
  beginning of the while loop. The continue statement rejects all the
  remaining statements in the current iteration of the loop and moves
  the control back to the top of the loop.

(Compare TP)

So in your case, you are iterating from top of while to the continue statement over and over. If you want to stop loop from executing after the name is not joe, use break

Your code should look something like this:

   while True:
           name = input('who are you')
           if name != (str('joe')):
                   break
           else:
                   password = input('hello joe whats the password?')
                   if password == 'saltysea':
                   print ('access granted')
                   break


问:
Replacing Class Names by Strings Reactjs
This is currently what I do

```<code>var longTextList = this.props.data.map(function(text, index){
                        return <Thumbnail key={index} style={fontSize} ><div style={fontFamily}><img src={text.sprite} />{text.longText} and get {coinName}(s)</div></Thumbnail>;
                      });
</code>```

Since, return returns a string, why can't we replace the class name with a user defined string.

For instance <Thumbnail> with <{this.props.type> where this.props.type=Thumbnail.

EDIT

I'm calling my class like this

```<code><CardView data={actionList} fontSize={fontSize} fontFamily={fontFamily} coinName={coinName} type="Thumbnail"/>
</code>```

where type tells us to render a Thumbnail.

In CardView.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Thumbnail } from 'react-bootstrap';

const CardView = React.createClass({

    render() {
        var fontFamily = this.props.fontFamily;
        var fontSize = this.props.fontSize;
        var coinName = this.props.coinName;
        var Type = this.props.type;
var longTextList = this.props.data.map(function(text, index){
                        return <Type key={index} style={fontSize} ><div style={fontFamily}><img src={text.sprite} />{text.longText} and get {coinName}(s)</div></Thumbnail>;
                      });

        return (
            <div>{longTextList}</div>
            );
    }
});

export default CardView;
</code>```

Facing Error

```<code>Expected corresponding JSX closing tag for <Type>
</code>```

答:
You can replace class names by string as long as this string begins with an uppercase letter. It is JSX standard to have the component first letter uppercase. It is useful to make the difference between standard HTML tag and custom tags representing components. Read more on the dot notation: tags vs react components

As a result, for example, you can use the dot notation: <MyVar.mytype/>

If you define the component type dynamically using a text variable "Tumbnail", you have to reference, in a dictionary, the component related to the component type. Otherwise, there is no possible way transpilation will guess which component to use.

You must do:

In a file name MyComponent.js:

```<code>import { Thumbnail } from 'react-bootstrap';
const MyComponents={
  Thumbnail
};
export default MyComponents;
</code>```

In your React Component, import MyComponent and:

```<code>var Type = MyComponents[this.props.type];
return <Type/>;
</code>```

Body:
This is currently what I do

var longTextList = this.props.data.map(function(text, index){
                        return <Thumbnail key={index} style={fontSize} >
{text.longText} and get {coinName}(s)
</Thumbnail>;
                      });

Since, return returns a string, why can't we replace the class name with a user defined string.

For instance <Thumbnail> with <{this.props.type> where this.props.type=Thumbnail.

EDIT

I'm calling my class like this

<CardView data={actionList} fontSize={fontSize} fontFamily={fontFamily} coinName={coinName} type="Thumbnail"/>

where type tells us to render a Thumbnail.

In CardView.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Thumbnail } from 'react-bootstrap';

const CardView = React.createClass({

    render() {
        var fontFamily = this.props.fontFamily;
        var fontSize = this.props.fontSize;
        var coinName = this.props.coinName;
        var Type = this.props.type;
var longTextList = this.props.data.map(function(text, index){
                        return <Type key={index} style={fontSize} >
{text.longText} and get {coinName}(s)
</Thumbnail>;
                      });

        return (

{longTextList}

            );
    }
});

export default CardView;

Facing Error

Expected corresponding JSX closing tag for <Type>

Body:
You can replace class names by string as long as this string begins with an uppercase letter. It is JSX standard to have the component first letter uppercase. It is useful to make the difference between standard HTML tag and custom tags representing components. Read more on the dot notation: tags vs react components

As a result, for example, you can use the dot notation: <MyVar.mytype/>

If you define the component type dynamically using a text variable "Tumbnail", you have to reference, in a dictionary, the component related to the component type. Otherwise, there is no possible way transpilation will guess which component to use.

You must do:

In a file name MyComponent.js:

import { Thumbnail } from 'react-bootstrap';
const MyComponents={
  Thumbnail
};
export default MyComponents;

In your React Component, import MyComponent and:

var Type = MyComponents[this.props.type];
return <Type/>;


问:
Drag and drop only triggers from the bottom of the Actor Libgdx
I have a table which contains in every cell another table. For example that table can have inside 8 other tables. I added a drag and drop so I can drag the smaller tables. It works but only partially. The drag and drop only gets detected if I touch on the bottom of the smaller tables, it doesn't trigger if I touch on the middle of them or on the top. I tried to set the width and height of the smaller tables, and then the drag and drop also triggers from a point on the top, but still not from everywhere it should? What could be wrong?

My code:
In code, collectionTable is the bigger table and TestCard are the types of the smaller tables that get added to collectionTable.

```<code>dnd = new DragAndDrop();
dnd.setDragTime(50);
for (final Actor x : collectionTable.getChildren()) {
            TestCard y = (TestCard) x;
            y.setWidth(Gdx.graphics.getWidth() / (7 * scale));
            y.setHeight(Gdx.graphics.getHeight() / (3.3f * scale));
            dnd.addSource(new CardSource(y));
dnd.addTarget(new Target(selectedDeck);
//not adding the code from the target as it works as intended

    class CardSource extends Source {

        final Payload payload = new Payload();

        TestCard card;

        public CardSource(Actor actor) {
            super(actor);
        }

        public CardSource(TestCard card) {
            super(card);
            this.card = card;
            card.setWidth(Gdx.graphics.getWidth() / (7 * scale));
            card.setHeight(Gdx.graphics.getHeight() / (3.3f * scale));
        }

        public Payload dragStart(InputEvent event, float x, float y, int pointer) {
            payload.setObject(card.);
            payload.setDragActor(new TestCard(card));
            //payload.setInvalidDragActor(invalidActor);
            payload.setValidDragActor(new TestCard(card));
            return payload;
        }
    }
</code>```

答:
use: setTouchabe(Touchable.enabled)

on the parent table. By default a 'group' (WidgetGroup or Table) only register touch on actual visible actors like buttons and labels.

Body:
I have a table which contains in every cell another table. For example that table can have inside 8 other tables. I added a drag and drop so I can drag the smaller tables. It works but only partially. The drag and drop only gets detected if I touch on the bottom of the smaller tables, it doesn't trigger if I touch on the middle of them or on the top. I tried to set the width and height of the smaller tables, and then the drag and drop also triggers from a point on the top, but still not from everywhere it should? What could be wrong?

My code:
In code, collectionTable is the bigger table and TestCard are the types of the smaller tables that get added to collectionTable.

dnd = new DragAndDrop();
dnd.setDragTime(50);
for (final Actor x : collectionTable.getChildren()) {
            TestCard y = (TestCard) x;
            y.setWidth(Gdx.graphics.getWidth() / (7 * scale));
            y.setHeight(Gdx.graphics.getHeight() / (3.3f * scale));
            dnd.addSource(new CardSource(y));
dnd.addTarget(new Target(selectedDeck);
//not adding the code from the target as it works as intended

    class CardSource extends Source {

        final Payload payload = new Payload();

        TestCard card;

        public CardSource(Actor actor) {
            super(actor);
        }

        public CardSource(TestCard card) {
            super(card);
            this.card = card;
            card.setWidth(Gdx.graphics.getWidth() / (7 * scale));
            card.setHeight(Gdx.graphics.getHeight() / (3.3f * scale));
        }

        public Payload dragStart(InputEvent event, float x, float y, int pointer) {
            payload.setObject(card.);
            payload.setDragActor(new TestCard(card));
            //payload.setInvalidDragActor(invalidActor);
            payload.setValidDragActor(new TestCard(card));
            return payload;
        }
    }


问:
add columns in dataframes dynamically with column names as elements in List
I have List[N] like below

```<code>val check = List ("a","b","c","d")
</code>```

where N can be any number of elements.

I have a dataframe with only column called "value". Based on the contents of value i need to create N columns with column names as elements in the list and column contents as substring(x,y)

I have tried all possible ways, like withColumn, selectExpr, nothing works.
Please consider substring(X,Y) where X and Y as some numbers based on some metadata

Below are my different codes which I tried, but none worked,

```<code>val df = sqlContext.read.text("xxxxx")
val coder: (String => String) = (arg: String) => {
val param = "NULL"
if (arg.length() > Y )
arg.substring(X,Y)
else
val sqlfunc = udf(coder)
val check = List ("a","b","c","d")
for (name <- check){val testDF2 = df.withColumn(name, sqlfunc(df("value")))}
</code>```

testDF2 has only last column d and other columns such as a,b,c are not added in table

```<code>var z:Array[String] = new Array[String](check.size)
var i=0
for ( x <- check ) {
if ( (i+1) == check.size) {
z(i) = s""""substring(a.value,X,Y) as $x""""
i = i+1}
else{
z(i) = s""""substring(a.value,X,Y) as $x","""
i = i+1}}
val zz = z.mkString(" ")
df.alias("a").selectExpr(s"$zz").show()
</code>```

This throws error

Please help how to add columns in DF dynamically with column names as elements in List

I am expecting an Df like below

```<code>-----------------------------
Value| a | b | c | d | .... N
-----------------------------
|xxx|xxx|xxx|xxx|xxx|xxxxxx-
|xxx|xxx|xxx|xxx|xxx|xxxxxx-
|xxx|xxx|xxx|xxx|xxx|xxxxxx-
-----------------------------
</code>```

答:
you can dynamically add columns from your list using for instance this answer by user6910411 to a similar question (see her/his full answer for more possibilities):

val newDF = check.foldLeft(<yourdf>)((df, name) => df.withColumn(name,<yourUDF>$"value"))

Body:
I have List[N] like below

val check = List ("a","b","c","d")

where N can be any number of elements.

I have a dataframe with only column called "value". Based on the contents of value i need to create N columns with column names as elements in the list and column contents as substring(x,y)

I have tried all possible ways, like withColumn, selectExpr, nothing works.
Please consider substring(X,Y) where X and Y as some numbers based on some metadata

Below are my different codes which I tried, but none worked,

val df = sqlContext.read.text("xxxxx")
val coder: (String => String) = (arg: String) => {
val param = "NULL"
if (arg.length() > Y )
arg.substring(X,Y)
else
val sqlfunc = udf(coder)
val check = List ("a","b","c","d")
for (name <- check){val testDF2 = df.withColumn(name, sqlfunc(df("value")))}

testDF2 has only last column d and other columns such as a,b,c are not added in table

var z:Array[String] = new Array[String](check.size)
var i=0
for ( x <- check ) {
if ( (i+1) == check.size) {
z(i) = s""""substring(a.value,X,Y) as $x""""
i = i+1}
else{
z(i) = s""""substring(a.value,X,Y) as $x","""
i = i+1}}
val zz = z.mkString(" ")
df.alias("a").selectExpr(s"$zz").show()

This throws error

Please help how to add columns in DF dynamically with column names as elements in List

I am expecting an Df like below

-----------------------------
Value| a | b | c | d | .... N
-----------------------------
|xxx|xxx|xxx|xxx|xxx|xxxxxx-
|xxx|xxx|xxx|xxx|xxx|xxxxxx-
|xxx|xxx|xxx|xxx|xxx|xxxxxx-
-----------------------------


问:
Please fix your application to end transactions in progress properly and to close the database when it is no longer needed
Trying to integrate FireBase to my app for Push Notifications. I have followed all the instructions given by FirreBase Console. But my app crash when I run it for the first time. Here is LOG.

04-03 13:16:38.620 1514-1525/? W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/metrics.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
      04-03 13:16:38.622 1514-1525/? W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/help_responses.db.18' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
      04-03 13:16:38.623 1514-1525/? W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.

Here is my app gradle file

```<code>apply plugin: 'com.android.application'

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 20
        versionName "2.0.8"

        ndk {
            moduleName = "cTunesInit"
        }
    }

    buildTypes {

    }

    sourceSets {
        main {
            jniLibs.srcDir 'jniLibs'
        }
    }

    repositories {
        mavenCentral() // jcenter() works as well because it pulls from Maven Central
    }

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    //pallette
    compile 'com.android.support:palette-v7:25.1.1'

    //appcompat
    compile 'com.android.support:appcompat-v7:25.1.1'

    //design
    compile 'com.android.support:design:25.1.1'

    //volley
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'

    //paypal
    compile 'com.paypal.sdk:paypal-android-sdk:2.13.1'

    // CardView
    compile 'com.android.support:cardview-v7:25.1.1'

    // RecyclerView
    compile 'com.android.support:recyclerview-v7:25.1.1'

    //glide
    compile 'com.github.bumptech.glide:glide:3.7.0'

    //FireBase Analytics and Push Notifications
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.google.firebase:firebase-messaging:10.2.0'
}

// FireBase
apply plugin: 'com.google.gms.google-services'
</code>```

I have updated libraries. But still not working. I don't know what went wrong.

答: There is a problem with my Android Device, i don't know what it is exactly. I have tried many times but not recovered from the crash problem. But when i run it on another device it's working.  </p>

Body:
Trying to integrate FireBase to my app for Push Notifications. I have followed all the instructions given by FirreBase Console. But my app crash when I run it for the first time. Here is LOG.

04-03 13:16:38.620 1514-1525/? W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/metrics.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
      04-03 13:16:38.622 1514-1525/? W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/help_responses.db.18' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
      04-03 13:16:38.623 1514-1525/? W/SQLiteConnectionPool: A SQLiteConnection object for database '/data/user/0/com.google.android.gms/databases/auto_complete_suggestions.db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.

Here is my app gradle file

apply plugin: 'com.android.application'

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 20
        versionName "2.0.8"

        ndk {
            moduleName = "cTunesInit"
        }
    }

    buildTypes {

    }

    sourceSets {
        main {
            jniLibs.srcDir 'jniLibs'
        }
    }

    repositories {
        mavenCentral() // jcenter() works as well because it pulls from Maven Central
    }

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    //pallette
    compile 'com.android.support:palette-v7:25.1.1'

    //appcompat
    compile 'com.android.support:appcompat-v7:25.1.1'

    //design
    compile 'com.android.support:design:25.1.1'

    //volley
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'

    //paypal
    compile 'com.paypal.sdk:paypal-android-sdk:2.13.1'

    // CardView
    compile 'com.android.support:cardview-v7:25.1.1'

    // RecyclerView
    compile 'com.android.support:recyclerview-v7:25.1.1'

    //glide
    compile 'com.github.bumptech.glide:glide:3.7.0'

    //FireBase Analytics and Push Notifications
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.google.firebase:firebase-messaging:10.2.0'
}

// FireBase
apply plugin: 'com.google.gms.google-services'

I have updated libraries. But still not working. I don't know what went wrong.


问:
Debugging component in main file with ko.toJSON | Knockout
I registered my views(html) and my viewModel(js) as knockout components. In my main file(index.html), I data-bind the components to show the different views. At this time when I want to quick debug a viewModel in the html with ko.toJSON($data, null,2), I need to add the data-bindin for ko.toJSON in everey html file which I want to debug. I would like to have a more generic way to do this like data-bind the ko.toJSON only in the main file(index-html) and pass the viewModel/$data?? to it.  </p>

```<code>//index.html
<body>

//here I want a generic way to debug my app like:
// <div data-bind="?">

    <div id="page" data-bind="component: {name: viewModel}"></div>
</body>

// components
ko.components.register('home', ko_home.init );
ko.components.register('import', ko_import.init );

//view
<main>
    <h1>home</h1>
     <div data-bind="text: greeting"></div>

// here I put the binding for debug in every view. It should be removed and //placed in the index.html
<pre data-bind="text: ko.toJson($data, null,2)">```
</main>

//viewModel
const fs = require('fs');
const template = fs.readFileSync(__dirname + '/home.html', 'utf8');

function Home() {
    this.greeting = ko.observable('Hello');
}

exports.init = { viewModel: Home, template: template };
</code>```

答:
I'd say the easiest way to go about including the debug element is to wrap your template with it when registering the component.

Since you already have an init object that holds the vm and template, you can re-assign the template property just before registering to add the ```</code> html string.</p>

<p>For example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var appendDebugPre = function(htmlString) {
  var pre = document.createElement("pre");
  pre.setAttribute(
    "data-bind",
    "html: ko.toJS($data, null, 2)"
  );

  // Might be better to create a documentFragment,
  // but for debug purposes, this might be enough
  return htmlString + pre.outerHTML;
};

// Regular register:
var c = messageEditor();

ko.components.register(c.name, c.init);

// Register a debug version:
ko.components.register("debug-" + c.name,
  Object.assign({}, c.init, {
    template: appendDebugPre(c.init.template) // Here, we wrap the template
  }));

ko.applyBindings({});

// Utils:
// From knockout docs, an example component:
function messageEditor() {
  return {
    name: 'message-editor',
    init: {
      viewModel: function(params) {
        this.text = ko.observable(params && params.initialText || '');
      },
      template: 'Message: <input data-bind="value: text" /> ' +
        '(length: <span data-bind="text: text().length"></span>)'
    }
  };
};

// Stub
ko.toJS = function(vm) {
  return JSON.stringify(
    Object.keys(vm).reduce(function(res, k) {
      res[k] = ko.unwrap(vm[k]);
      return res;
    }, {}),
    null,
    2
  );
};</code>```

```

Body:
I registered my views(html) and my viewModel(js) as knockout components. In my main file(index.html), I data-bind the components to show the different views. At this time when I want to quick debug a viewModel in the html with ko.toJSON($data, null,2), I need to add the data-bindin for ko.toJSON in everey html file which I want to debug. I would like to have a more generic way to do this like data-bind the ko.toJSON only in the main file(index-html) and pass the viewModel/$data?? to it.

//index.html

//here I want a generic way to debug my app like:
//

// components
ko.components.register('home', ko_home.init );
ko.components.register('import', ko_import.init );

//view

home

// here I put the binding for debug in every view. It should be removed and //placed in the index.html

//viewModel
const fs = require('fs');
const template = fs.readFileSync(__dirname + '/home.html', 'utf8');

function Home() {
    this.greeting = ko.observable('Hello');
}

exports.init = { viewModel: Home, template: template };

Body:
I'd say the easiest way to go about including the debug element is to wrap your template with it when registering the component.

Since you already have an init object that holds the vm and template, you can re-assign the template property just before registering to add the <pre> html string.

For example:

var appendDebugPre = function(htmlString) {
  var pre = document.createElement("pre");
  pre.setAttribute(
    "data-bind",
    "html: ko.toJS($data, null, 2)"
  );

  // Might be better to create a documentFragment,
  // but for debug purposes, this might be enough
  return htmlString + pre.outerHTML;
};

// Regular register:
var c = messageEditor();

ko.components.register(c.name, c.init);

// Register a debug version:
ko.components.register("debug-" + c.name,
  Object.assign({}, c.init, {
    template: appendDebugPre(c.init.template) // Here, we wrap the template
  }));

ko.applyBindings({});

// Utils:
// From knockout docs, an example component:
function messageEditor() {
  return {
    name: 'message-editor',
    init: {
      viewModel: function(params) {
        this.text = ko.observable(params && params.initialText || '');
      },
      template: 'Message: <input data-bind="value: text" /> ' +
        '(length: <span data-bind="text: text().length"></span>)'
    }
  };
};

// Stub
ko.toJS = function(vm) {
  return JSON.stringify(
    Object.keys(vm).reduce(function(res, k) {
      res[k] = ko.unwrap(vm[k]);
      return res;
    }, {}),
    null,
    2
  );
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div data-bind="component: 'message-editor'"></div>
<div data-bind="component: 'debug-message-editor'"></div>


问:
How to fetch class instance from class variable (from outside the class)?
Let's say I have this:

```<code>from PySide2 import QtWidgets

class MyClass(object):
    def __init__(self, parent=None):
        self.class_variable = QtWidgets.QWidget()

class_instance = MyClass()
variable = class_instance.class_variable
class_instance_returned = mystery_method(variable)  # How to make this return class_instance?
</code>```

How should I define mystery_method so that it would return the class_instance instance?

The real-world case I have is that I'm sending a QWidget which I'm using as a base instance for .ui file loading into a function. Inside this function I need to figure out which class instance it belongs to.

答:
In general you cannot (at least not without a lot of searching through all the objects in the system) but if all you want is to find which instances of a class match a particular value then it's fairly easy.

You can create a set of all instances and iterate over them to find what you need.

```<code>from weakref import WeakSet
class MyClass(object):
    _instances = WeakSet()

    def __init__(self, foo):
        self._instances.add(self)
        self.foo = foo

    @classmethod
    def findFoo(cls, foo):
        return [instance for instance in cls._instances if instance.foo == foo]

>>> instance1 = MyClass('bar')
>>> instance2 = MyClass('baz')
>>> MyClass.findFoo('baz')
[<__main__.MyClass object at 0x7f6723308f50>]
>>> MyClass.findFoo('bar')
[<__main__.MyClass object at 0x7f6723308c50>]
</code>```

Note that deleting the object won't remove it immediately, it may not go until garbage collected:

```<code>>>> del instance1
>>> MyClass.findFoo('bar')
[<__main__.MyClass object at 0x7f6723308c50>]
>>> import gc
>>> gc.collect()
16
>>> MyClass.findFoo('bar')
[]
</code>```

However in general you would be better to keep the reference to the original object hanging around and just use that.

Also, note that you cannot reliably tell which instance holds 'bar' if it is stored in more than one object: they could be the same 'bar' or they could be different ones, and whether they are the same or different is an implementation detail.

Body:
Let's say I have this:

from PySide2 import QtWidgets

class MyClass(object):
    def __init__(self, parent=None):
        self.class_variable = QtWidgets.QWidget()

class_instance = MyClass()
variable = class_instance.class_variable
class_instance_returned = mystery_method(variable)  # How to make this return class_instance?

How should I define mystery_method so that it would return the class_instance instance?

The real-world case I have is that I'm sending a QWidget which I'm using as a base instance for .ui file loading into a function. Inside this function I need to figure out which class instance it belongs to.

Body:
In general you cannot (at least not without a lot of searching through all the objects in the system) but if all you want is to find which instances of a class match a particular value then it's fairly easy.

You can create a set of all instances and iterate over them to find what you need.

from weakref import WeakSet
class MyClass(object):
    _instances = WeakSet()

    def __init__(self, foo):
        self._instances.add(self)
        self.foo = foo

    @classmethod
    def findFoo(cls, foo):
        return [instance for instance in cls._instances if instance.foo == foo]

>>> instance1 = MyClass('bar')
>>> instance2 = MyClass('baz')
>>> MyClass.findFoo('baz')
[<__main__.MyClass object at 0x7f6723308f50>]
>>> MyClass.findFoo('bar')
[<__main__.MyClass object at 0x7f6723308c50>]

Note that deleting the object won't remove it immediately, it may not go until garbage collected:

>>> del instance1
>>> MyClass.findFoo('bar')
[<__main__.MyClass object at 0x7f6723308c50>]
>>> import gc
>>> gc.collect()
16
>>> MyClass.findFoo('bar')
[]

However in general you would be better to keep the reference to the original object hanging around and just use that.

Also, note that you cannot reliably tell which instance holds 'bar' if it is stored in more than one object: they could be the same 'bar' or they could be different ones, and whether they are the same or different is an implementation detail.


问:
Enforce Landscape orientation on Windows 8.1 for Unity project
I have exported an app created in Unity 5.2.1f1 to Visual Studio for further processing. I did apply the following settings to the Package.appxmanifest:

Supported Rotations:

Landscape

Landscape-flipped

After export to a WP8.1 device (Nokia Lumia with Lumia Denim), both with Debug and Release/Master configuration, rotating the phone still results in the app switching from Landscape to Portrait mode.

Next, I changed the following lines in the generated App.xaml.cs:

```<code>this.InitializeComponent();
appCallbacks = new AppCallbacks();
</code>```

into this:

```<code>this.InitializeComponent();
Windows.Graphics.Display.DisplayInformation.AutoRotationPreferences = Windows.Graphics.Display.DisplayOrientations.Landscape | Windows.Graphics.Display.DisplayOrientations.LandscapeFlipped;
appCallbacks = new AppCallbacks();
</code>```

in an attempt to reinforce the settings done in the Package.appxmanifest. Still to no avail, the app still rotates freely. I also checked for further calls to AutoRotationPreferences (thought maybe some other auto-generated code), but didn't find anything.

Are there any further options I could try, any detail I might have overseen, or do I use some deprecated approach to solving this problem? Any help would be greatly appreciated!

答:
I know this is an old post, but I found this link providing a link to a blog post indicating how you can disable portrait mode in code.</p>

```<code>public static void SetScreenOrientationToLandscape()
{
    SetDisplayAutoRotationPreferences( (int) ORIENTATION_PREFERENCE.ORIENTATION_PREFERENCE_LANDSCAPE |
        (int) ORIENTATION_PREFERENCE.ORIENTATION_PREFERENCE_LANDSCAPE_FLIPPED );
}

public enum ORIENTATION_PREFERENCE
{
    ORIENTATION_PREFERENCE_NONE = 0x0,
    ORIENTATION_PREFERENCE_LANDSCAPE = 0x1,
    ORIENTATION_PREFERENCE_PORTRAIT = 0x2,
    ORIENTATION_PREFERENCE_LANDSCAPE_FLIPPED = 0x4,
    ORIENTATION_PREFERENCE_PORTRAIT_FLIPPED = 0x8
}
[System.Runtime.InteropServices.DllImport( "User32.dll" )]
public static extern bool SetDisplayAutoRotationPreferences( int value );
</code>```

Body:
I have exported an app created in Unity 5.2.1f1 to Visual Studio for further processing. I did apply the following settings to the Package.appxmanifest:

Supported Rotations:

Landscape

Landscape-flipped

After export to a WP8.1 device (Nokia Lumia with Lumia Denim), both with Debug and Release/Master configuration, rotating the phone still results in the app switching from Landscape to Portrait mode.

Next, I changed the following lines in the generated App.xaml.cs:

this.InitializeComponent();
appCallbacks = new AppCallbacks();

into this:

this.InitializeComponent();
Windows.Graphics.Display.DisplayInformation.AutoRotationPreferences = Windows.Graphics.Display.DisplayOrientations.Landscape | Windows.Graphics.Display.DisplayOrientations.LandscapeFlipped;
appCallbacks = new AppCallbacks();

in an attempt to reinforce the settings done in the Package.appxmanifest. Still to no avail, the app still rotates freely. I also checked for further calls to AutoRotationPreferences (thought maybe some other auto-generated code), but didn't find anything.

Are there any further options I could try, any detail I might have overseen, or do I use some deprecated approach to solving this problem? Any help would be greatly appreciated!

Body:
I know this is an old post, but I found this link providing a link to a blog post indicating how you can disable portrait mode in code.

public static void SetScreenOrientationToLandscape()
{
    SetDisplayAutoRotationPreferences( (int) ORIENTATION_PREFERENCE.ORIENTATION_PREFERENCE_LANDSCAPE |
        (int) ORIENTATION_PREFERENCE.ORIENTATION_PREFERENCE_LANDSCAPE_FLIPPED );
}

public enum ORIENTATION_PREFERENCE
{
    ORIENTATION_PREFERENCE_NONE = 0x0,
    ORIENTATION_PREFERENCE_LANDSCAPE = 0x1,
    ORIENTATION_PREFERENCE_PORTRAIT = 0x2,
    ORIENTATION_PREFERENCE_LANDSCAPE_FLIPPED = 0x4,
    ORIENTATION_PREFERENCE_PORTRAIT_FLIPPED = 0x8
}
[System.Runtime.InteropServices.DllImport( "User32.dll" )]
public static extern bool SetDisplayAutoRotationPreferences( int value );


问:
Importing jars in kotlin REPL
In a project managed by gradle, how to import an installed package in kotlin REPL ?</p>

```<code>Welcome to Kotlin version 1.0.3 (JRE 1.8.0_05-b13)
Type :help for help, :quit for quit
>>> import com.vladsch.flexmark.*
error: unresolved reference: vladsch
import com.vladsch.flexmark.*
           ^
</code>```

答:
As of Kotlin 1.1.1, there is no support to do this automatically. You need to pass the classpath to the kotlinc command manually:

```<code> kotlinc -cp build/classes/main
</code>```

Title: Importing jars in kotlin REPL

Body:
In a project managed by gradle, how to import an installed package in kotlin REPL ?

Welcome to Kotlin version 1.0.3 (JRE 1.8.0_05-b13)
Type :help for help, :quit for quit
>>> import com.vladsch.flexmark.*
error: unresolved reference: vladsch
import com.vladsch.flexmark.*
           ^

Body:
As of Kotlin 1.1.1, there is no support to do this automatically. You need to pass the classpath to the kotlinc command manually:

 kotlinc -cp build/classes/main


问:
How do I create a collision with SpriteKit with an already created SKSpriteNode?
I want the pacman to restart from its original position when it collides with blinky, that is moving.

How can I make them collide considering I have already declared them?

You move the pacman, but blinky moves alone. I want it to work like the pacman game.

```<code>  public class PacmanScene: SKScene {

let playerSpeed: CGFloat = 40.0
var pacman: SKSpriteNode?
var playerTextures: [SKTexture] = []
var lastTouch: CGPoint? = nil
var blinky: SKSpriteNode?
var clyde: SKSpriteNode?
var inky: SKSpriteNode?
var pinky: SKSpriteNode?
override public init(size: CGSize) {
let pacmanTexture = SKTexture(imageNamed: "pacman01.png")
    pacman = SKSpriteNode(texture: pacmanTexture)
    pacman?.name = "pacman"

    pacman?.position = CGPoint(x:30, y:30)
    pacman?.zPosition = 1.0
    pacman?.physicsBody = SKPhysicsBody(texture: pacmanTexture, size: CGSize(width: (pacman?.size.width)!, height: (pacman?.size.height)!))
    pacman?.physicsBody?.allowsRotation = true
    pacman?.physicsBody?.affectedByGravity = false
    pacman?.physicsBody?.mass = 2
 let blinkyTexture = SKTexture(imageNamed: "blinky.png")
    blinky = SKSpriteNode(texture: blinkyTexture)
    blinky?.name = "blinky"

    blinky?.position = CGPoint(x: 15, y: 60)
    blinky?.zPosition = 1.0
    blinky?.physicsBody = SKPhysicsBody(texture: pacmanTexture, size: CGSize(width: (blinky?.size.width)!, height: (blinky?.size.height)!))
    blinky?.physicsBody?.allowsRotation = false
    blinky?.physicsBody?.affectedByGravity = false
    blinky?.physicsBody?.mass = 1000

    super.init(size: size)
    addChild(pacman!)
    addChild(blinky!)

   override public func didMove(to view: SKView) {

    let bmoveUp = SKAction.moveBy(x: 0, y: 450, duration: 4.0)

    let bmoveRight = SKAction.moveBy(x:20, y:0, duration: 1.0)

    let bmoveDown = SKAction.moveBy(x:0, y: -450, duration: 4.0)

   let bmoveLeft = SKAction.moveBy(x:-20, y:0, duration: 1.0)

    let bsequence = SKAction.sequence([bmoveUp, bmoveRight, bmoveDown, bmoveLeft])

    let bendlessAction = SKAction.repeatForever(bsequence)
    blinky?.run(bendlessAction)
 }
</code>```

答:
If iv got this right you want your "blinky" to follow your "pacman" to do this you would have to work out the position of the pacman then add an SKAction to your blinky to move to that position.

Try something like this

```<code>//Speed blinky moves
let blinkySpeed = 100

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
    updateBlinky()
}

func updateBlinky() {
    //Set the point that blinky moves to
    let point = CGPoint(x: pacman.position.x, y: pacman.position.y)
    //Get the distance its got to travel
    let distance = distanceBetweenPoints(first: pacman.position, second: blinky.position)
    //Get the time is got to take from the speed and distance
    let time = distance / blinkySpeed
    //Create and run the action
    let action = SKAction.move(to: point, duration: TimeInterval(time))
    blinky.run(action)
}

//work out the distance between the sprites
func distanceBetweenPoints(first: CGPoint, second: CGPoint) -> Int {
    return Int(hypot(second.x - first.x, second.y - first.y))
}
</code>```

The end result would be something like this

Edit:

Okay I think from your question you already have "blinky" moving you just want to detect collisions.

First you need to add the SKPhysicsContactDelegate to your class

```<code>public class PacmanScene: SKScene, SKPhysicsContactDelegate {
</code>```

Then you need to add a category bit mask to both the sprites then handle the collisions in didBegin(_ contact: SKPhysicsContact) method.

What I would do

```<code>//Create Physics category struct
struct PhysicsCategory {
    static let pacman : UInt32 = 0x1 << 1
    static var blinky : UInt32 = 0x1 << 2
}
</code>```

Then where you are setting up pacman and blinky set the category bitmask

```<code>//Set the category bit mask for pacman
pacman?.physicsBody?.categoryBitMask = PhysicsCategory.pacman
//Set what categories you want to test contact
pacman?.physicsBody?.contactTestBitMask = PhysicsCategory.blinky
//Set what categories you want to collide with each other
pacman?.physicsBody?.collisionBitMask = PhysicsCategory.blinky

//Set the category bit mask for blinky
blinky?.physicsBody?.categoryBitMask = PhysicsCategory.blinky
//Set what categories you want to test contact
blinky?.physicsBody?.contactTestBitMask = PhysicsCategory.pacman
//Set what categories you want to collide with each other
blinky?.physicsBody?.collisionBitMask = PhysicsCategory.pacman
</code>```

Then you would need to implement the didBegin(_ contact: SKPhysicsContact) method to handle the collisions

```<code>func didBegin(_ contact: SKPhysicsContact) {
    //Work out which contact was pacman
    let other = contact.bodyA.categoryBitMask == PhysicsCategory.pacman ? contact.bodyB : contact.bodyA
    //Test what it hit
    switch other.categoryBitMask {

        case PhysicsCategory.blinky:
            print("pacman hit blinky")
            //Move pacman
            pacman?.position = CGPoint(x:30, y:30)

        default:
        break

    }
}
</code>```

Hope this helps

Body:
I want the pacman to restart from its original position when it collides with blinky, that is moving.

How can I make them collide considering I have already declared them?

You move the pacman, but blinky moves alone. I want it to work like the pacman game.

  public class PacmanScene: SKScene {

let playerSpeed: CGFloat = 40.0
var pacman: SKSpriteNode?
var playerTextures: [SKTexture] = []
var lastTouch: CGPoint? = nil
var blinky: SKSpriteNode?
var clyde: SKSpriteNode?
var inky: SKSpriteNode?
var pinky: SKSpriteNode?
override public init(size: CGSize) {
let pacmanTexture = SKTexture(imageNamed: "pacman01.png")
    pacman = SKSpriteNode(texture: pacmanTexture)
    pacman?.name = "pacman"

    pacman?.position = CGPoint(x:30, y:30)
    pacman?.zPosition = 1.0
    pacman?.physicsBody = SKPhysicsBody(texture: pacmanTexture, size: CGSize(width: (pacman?.size.width)!, height: (pacman?.size.height)!))
    pacman?.physicsBody?.allowsRotation = true
    pacman?.physicsBody?.affectedByGravity = false
    pacman?.physicsBody?.mass = 2
 let blinkyTexture = SKTexture(imageNamed: "blinky.png")
    blinky = SKSpriteNode(texture: blinkyTexture)
    blinky?.name = "blinky"

    blinky?.position = CGPoint(x: 15, y: 60)
    blinky?.zPosition = 1.0
    blinky?.physicsBody = SKPhysicsBody(texture: pacmanTexture, size: CGSize(width: (blinky?.size.width)!, height: (blinky?.size.height)!))
    blinky?.physicsBody?.allowsRotation = false
    blinky?.physicsBody?.affectedByGravity = false
    blinky?.physicsBody?.mass = 1000

    super.init(size: size)
    addChild(pacman!)
    addChild(blinky!)

   override public func didMove(to view: SKView) {

    let bmoveUp = SKAction.moveBy(x: 0, y: 450, duration: 4.0)

    let bmoveRight = SKAction.moveBy(x:20, y:0, duration: 1.0)

    let bmoveDown = SKAction.moveBy(x:0, y: -450, duration: 4.0)

   let bmoveLeft = SKAction.moveBy(x:-20, y:0, duration: 1.0)

    let bsequence = SKAction.sequence([bmoveUp, bmoveRight, bmoveDown, bmoveLeft])

    let bendlessAction = SKAction.repeatForever(bsequence)
    blinky?.run(bendlessAction)
 }

Body:
If iv got this right you want your "blinky" to follow your "pacman" to do this you would have to work out the position of the pacman then add an SKAction to your blinky to move to that position.

Try something like this

//Speed blinky moves
let blinkySpeed = 100

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
    updateBlinky()
}

func updateBlinky() {
    //Set the point that blinky moves to
    let point = CGPoint(x: pacman.position.x, y: pacman.position.y)
    //Get the distance its got to travel
    let distance = distanceBetweenPoints(first: pacman.position, second: blinky.position)
    //Get the time is got to take from the speed and distance
    let time = distance / blinkySpeed
    //Create and run the action
    let action = SKAction.move(to: point, duration: TimeInterval(time))
    blinky.run(action)
}

//work out the distance between the sprites
func distanceBetweenPoints(first: CGPoint, second: CGPoint) -> Int {
    return Int(hypot(second.x - first.x, second.y - first.y))
}

The end result would be something like this

Edit:

Okay I think from your question you already have "blinky" moving you just want to detect collisions.

First you need to add the SKPhysicsContactDelegate to your class

public class PacmanScene: SKScene, SKPhysicsContactDelegate {

Then you need to add a category bit mask to both the sprites then handle the collisions in didBegin(_ contact: SKPhysicsContact) method.

What I would do

//Create Physics category struct
struct PhysicsCategory {
    static let pacman : UInt32 = 0x1 << 1
    static var blinky : UInt32 = 0x1 << 2
}

Then where you are setting up pacman and blinky set the category bitmask

//Set the category bit mask for pacman
pacman?.physicsBody?.categoryBitMask = PhysicsCategory.pacman
//Set what categories you want to test contact
pacman?.physicsBody?.contactTestBitMask = PhysicsCategory.blinky
//Set what categories you want to collide with each other
pacman?.physicsBody?.collisionBitMask = PhysicsCategory.blinky

//Set the category bit mask for blinky
blinky?.physicsBody?.categoryBitMask = PhysicsCategory.blinky
//Set what categories you want to test contact
blinky?.physicsBody?.contactTestBitMask = PhysicsCategory.pacman
//Set what categories you want to collide with each other
blinky?.physicsBody?.collisionBitMask = PhysicsCategory.pacman

Then you would need to implement the didBegin(_ contact: SKPhysicsContact) method to handle the collisions

func didBegin(_ contact: SKPhysicsContact) {
    //Work out which contact was pacman
    let other = contact.bodyA.categoryBitMask == PhysicsCategory.pacman ? contact.bodyB : contact.bodyA
    //Test what it hit
    switch other.categoryBitMask {

        case PhysicsCategory.blinky:
            print("pacman hit blinky")
            //Move pacman
            pacman?.position = CGPoint(x:30, y:30)

        default:
        break

    }
}

Hope this helps


问:
Rails - Error pages controller and redirecting the user?
Building a small app and I'd like to intercept error pages.

Is it possible to define a controller where all of Rails's failed page requests end up so I can add my custom behavior there?

答:
Place this at the bottom of your app config/routes.rb</p>

```<code>match '*path', to: redirect('/'), via: :all
</code>```

Body:
Place this at the bottom of your app config/routes.rb

match '*path', to: redirect('/'), via: :all


问:
3d game with Python, starting from nothing
So we want to program a 3d game for school, we can probably use blender for the 3d models, however we are totally clueless as to how to use them in a game/application.

Are there any recommended guides/documents we should read on general 3d game programming and perhaps python specific stuff.

We are also possibly considering programming it in C++ but for now I think it's easier to use Python as we can fully focus on the 3d mechanics that way.

答:
An alternative to PyGame, which I personally prefer, is pyglet.
http://pyglet.org</p>


问:
jQuery DatePicker date format with current calture
I'm using DatePicker with date range and I want to use the current calture format.
I know how to get the current calture:

```<code>var calture = '<%= System.Globalization.CultureInfo.CurrentCulture.Name %>';
</code>```

But this does not give me the date format that I need to for the date picker DateFormat.
How do I get the current calture date format ?

答:
You can try this,

```<code>var cultureLanguageTag = CultureInfo.CurrentCulture.IetfLanguageTag;
var defaultCulture =  CultureInfo.GetCultureInfoByIetfLanguageTag(cultureLanguageTag);
</code>```

This gives the default dateformat.

Body:
I'm using DatePicker with date range and I want to use the current calture format.
I know how to get the current calture:

var calture = '<%= System.Globalization.CultureInfo.CurrentCulture.Name %>';

But this does not give me the date format that I need to for the date picker DateFormat.
How do I get the current calture date format ?

Body:
You can try this,

var cultureLanguageTag = CultureInfo.CurrentCulture.IetfLanguageTag;
var defaultCulture =  CultureInfo.GetCultureInfoByIetfLanguageTag(cultureLanguageTag);

This gives the default dateformat.


问:
Edit code of page on Wordpress
I want to edit the HTML code of my Wordpress page. Exactly, I want to create a page, not posts, in my Wordpress page, where I want expose my CV and insert my photo which will changes when I pass the mouse above of it.

I tried to search something about this and i found this. In this reference, the writer speaks about the code modification, but isn't my particular case.

When I try to edit the code in the Wordpress page, I can't use some codes. For example: ,
 ...

I want to use something like this:

```<code><div class="authorimage">
   <a href="https://www.codesyntax.com/eu/bloga/author/lfernandez">
       <img class="mainimage" src="https://www.codesyntax.com/lfernandez.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
       <img class="hoverimage" src="https://www.codesyntax.com/lfernandezhover.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
   </a>

</div>
</code>```

But in the published page the following appears:

```<code> <img class="mainimage" src="https://www.codesyntax.com/lfernandez.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
 <img class="hoverimage" src="https://www.codesyntax.com/lfernandezhover.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
</code>```

I need use this code for my purpose. what can i do to fix this problem?

Thanks for all.

答: Log into your WordPress dashboard and create a new page. On that new page you can insert your CV and photo and then publish it.</p>

Title: Edit code of page on Wordpress

Body:
I want to edit the HTML code of my Wordpress page. Exactly, I want to create a page, not posts, in my Wordpress page, where I want expose my CV and insert my photo which will changes when I pass the mouse above of it.

I tried to search something about this and i found this. In this reference, the writer speaks about the code modification, but isn't my particular case.

When I try to edit the code in the Wordpress page, I can't use some codes. For example: ,
 ...

I want to use something like this:

But in the published page the following appears:

I need use this code for my purpose. what can i do to fix this problem?

Thanks for all.


问:
File upload from MVC controller to Web API using RestSharp
One of the features of my web application is the ability of the users to upload markdown files. I'd like to pass the file from a MVC controller to a Web API controller, afterwards the Web API will save the markdown file on a specific project folder. I'd like to know if it's possible. If yes, how to do it.

So for what I had in mind is having the MVC controller take a HttpPostedFileBase parameter and afterwards use RestSharp's request.AddFile() to send the file to the Web API controller.

MVC Controller

```<code>[HttpPost]
public ActionResult Upload(HttpPostedFileBase upload)
{
    var client = new RestClient("http://localhost:4000/api/beneficiaries");
    var request = new RestRequest(Method.POST);
    //todo send file to web API
    var response = client.Execute(request);
    return View();
}
</code>```

答:
This should work, even if I haven't tested it:

```<code>request.AddFile(upload.FileName, upload.InputStream.CopyTo, upload.ContentType);
</code>```

Depending of the api target method, and if you need some parameters sent with it, you might need:

```<code>request.AddFile(upload.FileName, upload.InputStream.CopyTo);
request.AddHeader("Content-Type", "multipart/form-data");

request.AddParameter("filename", upload.FileName, ParameterType.RequestBody);
request.AddParameter("otherParameter", "Something here...", ParameterType.RequestBody);
</code>```

Body:
One of the features of my web application is the ability of the users to upload markdown files. I'd like to pass the file from a MVC controller to a Web API controller, afterwards the Web API will save the markdown file on a specific project folder. I'd like to know if it's possible. If yes, how to do it.

So for what I had in mind is having the MVC controller take a HttpPostedFileBase parameter and afterwards use RestSharp's request.AddFile() to send the file to the Web API controller.

MVC Controller

[HttpPost]
public ActionResult Upload(HttpPostedFileBase upload)
{
    var client = new RestClient("http://localhost:4000/api/beneficiaries");
    var request = new RestRequest(Method.POST);
    //todo send file to web API
    var response = client.Execute(request);
    return View();
}

Body:
This should work, even if I haven't tested it:

request.AddFile(upload.FileName, upload.InputStream.CopyTo, upload.ContentType);

Depending of the api target method, and if you need some parameters sent with it, you might need:

request.AddFile(upload.FileName, upload.InputStream.CopyTo);
request.AddHeader("Content-Type", "multipart/form-data");

request.AddParameter("filename", upload.FileName, ParameterType.RequestBody);
request.AddParameter("otherParameter", "Something here...", ParameterType.RequestBody);


问:
allow user in forms authentication wont work in azure website
I have a website on Azure - example.azurewebsites.net.
I configured the default page to index.html.
Now, the website suppose to deny unauthenticated users to website, except index.html and login.html.

That's my code:

```<code>   <system.webServer>
    <defaultDocument>
      <files>
        <clear/>
        <add value="index.html" />
      </files>
    </defaultDocument>
  </system.webServer>
    <location path="index.html">
      <system.web>
         <authorization>
            <allow users="*"/>
         </authorization>
      </system.web>
   </location>
  <system.web>
    <authentication mode="Forms">
         <forms loginUrl="login.html" defaultUrl="~/" />
    </authentication>
    <authorization>
         <deny users="?" />
    </authorization>
  </system.web>
</code>```

example.azurewebsites.net/index.html - this works.
example.azurewebsites.net - and this does not (redirects to login.html).
But they supposed to be the same.
Without authentication example.azurewebsites.net redirects to index.html no problem.

Where am I wrong?

答:
One thing you may wish to check is if the following exists on your web.config.

```<code><system.webServer>
<modules runAllManagedModulesForAllRequests="true">
  <remove name="FormsAuthenticationModule" />
  <add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />
</modules>
</code>```

You don't usually need to do this as the module is defined in C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config on your local OS. It however, is not the case on Azure Web Service environment.

Body:
I have a website on Azure - example.azurewebsites.net.
I configured the default page to index.html.
Now, the website suppose to deny unauthenticated users to website, except index.html and login.html.

That's my code:

   <system.webServer>
    <defaultDocument>
      <files>
        <clear/>
        <add value="index.html" />
      </files>
    </defaultDocument>
  </system.webServer>
    <location path="index.html">
      <system.web>
         <authorization>
            <allow users="*"/>
         </authorization>
      </system.web>
   </location>
  <system.web>
    <authentication mode="Forms">
         <forms loginUrl="login.html" defaultUrl="~/" />
    </authentication>
    <authorization>
         <deny users="?" />
    </authorization>
  </system.web>

example.azurewebsites.net/index.html - this works.
example.azurewebsites.net - and this does not (redirects to login.html).
But they supposed to be the same.
Without authentication example.azurewebsites.net redirects to index.html no problem.

Where am I wrong?

Body:
One thing you may wish to check is if the following exists on your web.config.

<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
  <remove name="FormsAuthenticationModule" />
  <add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />
</modules>

You don't usually need to do this as the module is defined in C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config on your local OS. It however, is not the case on Azure Web Service environment.