问:
How do I set up Django 1.11 with Python 3.6.1 using Apache 2.4 on Ubuntu 16+
I'd like to know how to quickly and simply set up Django on Ubuntu

I have read so much official and user documentation my head is spinning and am not 100% sure where to start.

I'm not an absolute beginner and I have some working knowledge of Django, Python, and Linux Shell Commands (Ubuntu) so the instructions can be quick and to the point.

Note: I answered my own question below...

答:
Setting up Django 1.11 with Python 3.6.1 using Apache 2.4 on Ubuntu 16+

Note: This does not cover everything you 'could do' - it's meant to get your server up and running with Django as quickly as possible. It should work for later versions, just remember to find the right packages and change versioning accordingly

You will likely have to change a lot of the paths included so be watchful.

1. Install Python 3.6 and virtualenv

```<code>sudo apt-get update
sudo apt-get install python3.6 python3.6-dev
sudo apt-get install virtualenv
</code>```

( Ubuntu Packages https://packages.ubuntu.com/ )

2. Install Apache2 webserver

```<code>sudo apt-get install apache2 apache2-dev
</code>```

( all things apache here https://httpd.apache.org/ )

3. Make and enter a folder for your project - then build a Virtual Environment in it

```<code>mkdir ~/example.com
cd ~/example.com
virtualenv --python=/usr/bin/python3.6 py361ve
</code>```

( more about virtual environments here
  https://virtualenv.pypa.io/en/stable/ )

4. Enter your new Virtual Environment to install packages to it

```<code>source py361ve/bin/activate
</code>```

( using virtualenv https://virtualenv.pypa.io/en/stable/userguide/ )

5. Install Django, mod_wsgi, and any other needed packages

```<code>pip install django
pip install mod_wsgi
pip install ...
</code>```

( no need for pip3 in virtual environment - pip uses your Virtual Environment python version here )

( more on pip can be found here
  https://pip.pypa.io/en/stable/  mod_wsgi
  https://modwsgi.readthedocs.io/en/develop/ )

6. Move an existing project or create a new django project within your ~/example.com folder

```<code>django-admin startproject django_project
</code>```

( how to build a Django app
  https://docs.djangoproject.com/en/1.11/intro/tutorial01/ )

7. Edit the wsgi.py file in your Django project folder to add sys paths for your project

```<code>import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
</code>```

Additional: sys.path.append(‘/path/to/your/library’)

( django deployment https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/ )

8. Edit your Django project’s settings.py for your site and set up any additional things you need for your project to work properly.

I put my ‘static’ and ‘media’ folders in a separate location from my
  python code ( within /var/www/example.com/ ) and I think you should
  too to prevent accidentally making your python code public.

(The VirtualHost example below the instructions should make the setup more
  clear)

( Django Settings
  https://docs.djangoproject.com/en/1.11/topics/settings/ )

9. Run following command and copy output for placement in apache config file

```<code>mod_wsgi-express module-config
</code>```

( https://pypi.python.org/pypi/mod_wsgi )

10. Exit your virtual environment

```<code>deactivate
</code>```

(You can re-enter your virtual environment any time using the source
  method in step 4)

11. Navigate to your apache2 configuration folder ( /etc/apache2/ on Ubuntu ) and place the copied text at the bottom of the Apache2 configuration file.

```<code>sudo nano apache2.conf
</code>```

( more about apache2.conf [ or httpd.conf on some systems ]
  https://httpd.apache.org/docs/2.4/configuring.html )

12. Navigate to the /etc/apache2/sites-available/ and create a new conf file for your site. Edit the VirtualHost template (below all instructions) and copy it to this file.

```<code>sudo apt-get install apache2 apache2-dev
</code>```0

( VirtualHost examples
  https://httpd.apache.org/docs/2.4/vhosts/examples.html and mod_wsgi
  daemon mode
  https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/#using-mod-wsgi-daemon-mode
  )

13. After saving the file, enable this site in Apache

```<code>sudo apt-get install apache2 apache2-dev
</code>```1

( https://wiki.apache.org/httpd/DebianLikePlatform )

14. If you want to enable admin access to your site simply copy the files from your python virtual environment to your aliased static/admin folder

```<code>sudo apt-get install apache2 apache2-dev
</code>```2

( serving admin files
  https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/#serving-the-admin-files
  )

15. Any time you update any python or django related script you’ll need to either ‘touch’ the wsgi.py file to reload the daemon process running your site to make it active or restart apache…

```<code>touch ~/example.com/my_project/my_project/wsgi.py
        or
sudo service apache2 restart
</code>```

16. Lastly check that all your folders and files have sufficient group ( usually www-data ) read and write privileges and that the folder your database is in (if using sqlite) has group write privileges.

( https://help.ubuntu.com/community/FilePermissions )

VirtualHost Example Template...

```<code><VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com
        ServerAdmin info@example.com
        DocumentRoot /var/www/example.com

        <Directory /var/www/example.com>
                Options FollowSymLinks
                AllowOverride All
                Order allow,deny
                Allow from all
        </Directory>

        Alias /robots.txt /var/www/example.com/robots.txt
        Alias /favicon.ico /var/www/example.com/favicon.ico
        Alias /static/ /var/www/example.com/static/
        Alias /media/ /var/www/example.com/media/

        <Directory /var/www/example.com/static>
                Require all granted
        </Directory>

        <Directory /var/www/example.com/media>
                Require all granted
        </Directory>

        WSGIDaemonProcess example.com  python-home=/home/user_name/example.com/py361ve
        WSGIProcessGroup example.com
        WSGIScriptAlias / /home/user_name/example.com/django_project/django_project/wsgi.py

        <Directory /home/user_name/example.com/django_project/django_project>
                <Files wsgi.py>
                         Require all granted
                </Files>
        </Directory>
</VirtualHost>
</code>```

Note: Please edit mistakes and make improvements to the instructions as necessary, but don't try to overcomplicate things

Body:
Setting up Django 1.11 with Python 3.6.1 using Apache 2.4 on Ubuntu 16+

Note: This does not cover everything you 'could do' - it's meant to get your server up and running with Django as quickly as possible. It should work for later versions, just remember to find the right packages and change versioning accordingly

You will likely have to change a lot of the paths included so be watchful.

1. Install Python 3.6 and virtualenv

sudo apt-get update
sudo apt-get install python3.6 python3.6-dev
sudo apt-get install virtualenv

( Ubuntu Packages https://packages.ubuntu.com/ )

2. Install Apache2 webserver

sudo apt-get install apache2 apache2-dev

( all things apache here https://httpd.apache.org/ )

3. Make and enter a folder for your project - then build a Virtual Environment in it

mkdir ~/example.com
cd ~/example.com
virtualenv --python=/usr/bin/python3.6 py361ve

( more about virtual environments here
  https://virtualenv.pypa.io/en/stable/ )

4. Enter your new Virtual Environment to install packages to it

source py361ve/bin/activate

( using virtualenv https://virtualenv.pypa.io/en/stable/userguide/ )

5. Install Django, mod_wsgi, and any other needed packages

pip install django
pip install mod_wsgi
pip install ...

( no need for pip3 in virtual environment - pip uses your Virtual Environment python version here )

( more on pip can be found here
  https://pip.pypa.io/en/stable/  mod_wsgi
  https://modwsgi.readthedocs.io/en/develop/ )

6. Move an existing project or create a new django project within your ~/example.com folder

django-admin startproject django_project

( how to build a Django app
  https://docs.djangoproject.com/en/1.11/intro/tutorial01/ )

7. Edit the wsgi.py file in your Django project folder to add sys paths for your project

import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

Additional: sys.path.append(‘/path/to/your/library’)

( django deployment https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/ )

8. Edit your Django project’s settings.py for your site and set up any additional things you need for your project to work properly.

I put my ‘static’ and ‘media’ folders in a separate location from my
  python code ( within /var/www/example.com/ ) and I think you should
  too to prevent accidentally making your python code public.

(The VirtualHost example below the instructions should make the setup more
  clear)

( Django Settings
  https://docs.djangoproject.com/en/1.11/topics/settings/ )

9. Run following command and copy output for placement in apache config file

mod_wsgi-express module-config

( https://pypi.python.org/pypi/mod_wsgi )

10. Exit your virtual environment

deactivate

(You can re-enter your virtual environment any time using the source
  method in step 4)

11. Navigate to your apache2 configuration folder ( /etc/apache2/ on Ubuntu ) and place the copied text at the bottom of the Apache2 configuration file.

sudo nano apache2.conf

( more about apache2.conf [ or httpd.conf on some systems ]
  https://httpd.apache.org/docs/2.4/configuring.html )

12. Navigate to the /etc/apache2/sites-available/ and create a new conf file for your site. Edit the VirtualHost template (below all instructions) and copy it to this file.

sudo nano example.com.conf

( VirtualHost examples
  https://httpd.apache.org/docs/2.4/vhosts/examples.html and mod_wsgi
  daemon mode
  https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/#using-mod-wsgi-daemon-mode
  )

13. After saving the file, enable this site in Apache

sudo a2ensite example.com.conf
sudo service apache2 reload

( https://wiki.apache.org/httpd/DebianLikePlatform )

14. If you want to enable admin access to your site simply copy the files from your python virtual environment to your aliased static/admin folder

example path: /py361ve/lib/python3.6/site-packages/django/contrib/admin/static/admin

( serving admin files
  https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/#serving-the-admin-files
  )

15. Any time you update any python or django related script you’ll need to either ‘touch’ the wsgi.py file to reload the daemon process running your site to make it active or restart apache…

touch ~/example.com/my_project/my_project/wsgi.py
        or
sudo service apache2 restart

16. Lastly check that all your folders and files have sufficient group ( usually www-data ) read and write privileges and that the folder your database is in (if using sqlite) has group write privileges.

( https://help.ubuntu.com/community/FilePermissions )

VirtualHost Example Template...

<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com
        ServerAdmin info@example.com
        DocumentRoot /var/www/example.com

        <Directory /var/www/example.com>
                Options FollowSymLinks
                AllowOverride All
                Order allow,deny
                Allow from all
        </Directory>

        Alias /robots.txt /var/www/example.com/robots.txt
        Alias /favicon.ico /var/www/example.com/favicon.ico
        Alias /static/ /var/www/example.com/static/
        Alias /media/ /var/www/example.com/media/

        <Directory /var/www/example.com/static>
                Require all granted
        </Directory>

        <Directory /var/www/example.com/media>
                Require all granted
        </Directory>

        WSGIDaemonProcess example.com  python-home=/home/user_name/example.com/py361ve
        WSGIProcessGroup example.com
        WSGIScriptAlias / /home/user_name/example.com/django_project/django_project/wsgi.py

        <Directory /home/user_name/example.com/django_project/django_project>
                <Files wsgi.py>
                         Require all granted
                </Files>
        </Directory>
</VirtualHost>

Note: Please edit mistakes and make improvements to the instructions as necessary, but don't try to overcomplicate things


来源: stackexchange

问:
Load desired EJBs only
Technology I'm using: JavaEE7, JSF2.2.

I have one project called "entity" which contains all the entity, repository, DAO (Stateless EJB).

Other projects will import "entity" project and use this project to connect to DB.
The problem is that "entity" project contains over 5000 EJB, and this takes a lot of time for loading.

But in reality, each project only uses hundreds of EJB.

Can I have a way to load only EJBs that I will really use, without loading all 5000 EJBs. For example: define needed EJBs in .xml file

答: Split the "entity" project in reasonable parts.</p>

ContentLicense: CC BY-SA 3.0

Title: Load desired EJBs only


问:
What is the Delphi equivalent of C#'s PropertyGrid?
Is there a Delphi equivalent to C#'s PropertyGrid? I want to implement something similar to the Object Inspector in RAD Studio.

答:
While I havent checked out the pricing I would also investigate TMS software. I know they have a property-editor that is just as advanced as Developer Express - but TMS are usually more reasonable when it comes to price than Developer Express.

You could also take a quick search as www.Koder.com and see if you come across some opensource alternatives there. Personally I went for TMS.

ContentLicense: CC BY-SA 2.5


问:
Getting the items from a mulitple select ListView WPF c#
I need help from getting the selected value of multiple items in a listview.

Here is my XAML Code:

```<code><ListView x:Name="lb_employees" HorizontalAlignment="Left" Height="140" Margin="141,16,0,0" VerticalAlignment="Top" Width="255" Loaded="lb_employees_Loaded" SelectionChanged="lb_employees_SelectionChanged">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" />
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" />
                <GridViewColumn Header="Employee ID" DisplayMemberBinding="{Binding Path=empid}" Width="0" />
            </GridView>
        </ListView.View>
    </ListView>
</code>```

Here is how I populate the ListView:

```<code>dbml.hrdbDataContext listpeople = new dbml.hrdbDataContext();
        var q = from p in listpeople.EmpIDs
                join pi in listpeople.EmpBasicFiles on p.EmpID1 equals pi.EBF_EmpID
                where pi.EBF_Active == 1
                orderby p.LastName
                select new classes.Employeeselected() { FirstName = p.FirstName, LastName = p.LastName, empid = p.EmpID1 };

        foreach (var item in q)
        {
            this.lb_employees.Items.Add(item);
        }
</code>```

How can I get the value of let’s say, empid when selected?

I have already tried this code, but it’s not working at all.

```<code>        private void lb_employees_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        foreach (classes.Employeeselected item in lb_employees.SelectedItems)
        {
            System.Windows.MessageBox.Show(item.empid.ToString());
        }

    }
</code>```

Any help would be greatly appreciated.

答:
So odd. When I compiled it before, it kept giving me a null exception error. But now, it seems work just fine!

After a reboot, it seems to be working just fine. Maybe it was a problem with this Insider Build?

Body:
I need help from getting the selected value of multiple items in a listview.

Here is my XAML Code:

<ListView x:Name="lb_employees" HorizontalAlignment="Left" Height="140" Margin="141,16,0,0" VerticalAlignment="Top" Width="255" Loaded="lb_employees_Loaded" SelectionChanged="lb_employees_SelectionChanged">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" />
                <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" />
                <GridViewColumn Header="Employee ID" DisplayMemberBinding="{Binding Path=empid}" Width="0" />
            </GridView>
        </ListView.View>
    </ListView>

Here is how I populate the ListView:

dbml.hrdbDataContext listpeople = new dbml.hrdbDataContext();
        var q = from p in listpeople.EmpIDs
                join pi in listpeople.EmpBasicFiles on p.EmpID1 equals pi.EBF_EmpID
                where pi.EBF_Active == 1
                orderby p.LastName
                select new classes.Employeeselected() { FirstName = p.FirstName, LastName = p.LastName, empid = p.EmpID1 };

        foreach (var item in q)
        {
            this.lb_employees.Items.Add(item);
        }

How can I get the value of let’s say, empid when selected?

I have already tried this code, but it’s not working at all.

        private void lb_employees_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        foreach (classes.Employeeselected item in lb_employees.SelectedItems)
        {
            System.Windows.MessageBox.Show(item.empid.ToString());
        }

    }

Any help would be greatly appreciated.


问:
FaceRecognition: Does all the images per person must be the same count?
I want to know that, is this important to have the same count of images per person (e.g: 10 image/person) to train faces in Eigen/Fisher/LBPH FaceRecognizer? Or it can be different count (person1: 10 images, person2: 20 images, ...)</p>

答:
For Eigen/Fisherfaces, the safest answer is that dataset volumes for each class have to be balanced. While lacking just some images for a class may be OK, having a class which has an order of magnitude more images than all the other ones will definetely cause a problem. Tolerable disbalance is individual for every task, I guess.

At the end of the day, each of the mentioned algorithms falls into finding the closest neighbor from the training dataset to query image. Eigen/Fisherfaces are trained on the whole given dataset, calculating vectors at which the dataset images vary the most. Over- or underrepresenting a class would result in a disbalanced model which would work inadequately towards it.

Conversely, LBPH is not trained on the whole dataset. It analyzes each image from the dataset independetly, and compares the query image to each of them separately. Dataset comprehensiveness and representativeness is thus more important here than image count.

OpenCV has an intro to inner workings of these algorithms.


问:
keeping search and filter dropdown on same line
Im working on a section on a webpage, using bootstrap but cant keep filter on same line. Ive tried a few ways, currently trying columns, tried divs inline, still not lining up correctly.

div class="col-lg-12">

        <input type="text" style="width: 80%;" id="rev-search" placeholder="Search" autofocus="" />

       <button class="btn btn-default dropdown-toggle" style="float: right;" type="button" id="group_filter" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"><?php echo $text_filter_group;?></button>

       <?php
        foreach ($customer_groups as $group){
         echo '
'.$group['name'].'
';
        }
        ?>

```

答:
Following the Bootstrap documentation, please use lg (for larger desktops).

Also try wrapping your row in a fluid container.

```<code><div class="container-fluid">
  <div class="row">

    </div>
  </div>
</code>```

Body:
Following the Bootstrap documentation, please use lg (for larger desktops).

Also try wrapping your row in a fluid container.

<div class="container-fluid">
  <div class="row">

    </div>
  </div>


问:
Want to cast unique values into first/second/third variables
I have a sample of a dataset that needs to be cast into a wide format, but I have a particular issue that I haven't seen addressed on StackOveflow yet.

The column that I'd like to use to make a long dataset has unique values for every single row, but I want to create a new dataset so that are n variables for n attributes for each idvar.

I need to convert this:

```<code>state   sector  attribute_value
alabama 1   a
alabama 1   b
alabama 1   c
alabama 1   d
alabama 1   e
alabama 1   f
alabama 1   g
alabama 1   h
alaska  1   i
alaska  1   j
alaska  1   k
alaska  1   l
alaska  1   m
alaska  1   n
alaska  1   o
arizona 1   p
arizona 1   q
arizona 1   r
arizona 1   s
arizona 1   t
arizona 1   u
arizona 1   v
</code>```

into:

```<code>state   sector  attribute_value_1   attribute_value_2   attribute_value_3   attribute_value_4   attribute_value_5   attribute_value_6   attribute_value_7   attribute_value_8
alabama 1   a   b   c   d   e   f   g   h
alaska  1   i   j   k   l   m   n   o   n/a
arizona 1   p   q   r   s   t   u   v   n/a
</code>```

So far, I haven't been able to use dcast or reshape to create this particular transformation.

答:
Try this , using dplyr and splitstackshape

```<code>library(dplyr)
library(splitstackshape)
df=df%>%group_by(state,sector)%>%dplyr::summarise(attribute_value=paste(attribute_value,sep=',',collapse = ","))
concat.split(df, 3, drop = TRUE)

     state sector attribute_value_1 attribute_value_2 attribute_value_3 attribute_value_4 attribute_value_5 attribute_value_6 attribute_value_7 attribute_value_8
1: alabama      1                 a                 b                 c                 d                 e                 f                 g                 h
2:  alaska      1                 i                 j                 k                 l                 m                 n                 o                NA
3: arizona      1                 p                 q                 r                 s                 t                 u                 v                NA
</code>```

Body:
I have a sample of a dataset that needs to be cast into a wide format, but I have a particular issue that I haven't seen addressed on StackOveflow yet.

The column that I'd like to use to make a long dataset has unique values for every single row, but I want to create a new dataset so that are n variables for n attributes for each idvar.

I need to convert this:

state   sector  attribute_value
alabama 1   a
alabama 1   b
alabama 1   c
alabama 1   d
alabama 1   e
alabama 1   f
alabama 1   g
alabama 1   h
alaska  1   i
alaska  1   j
alaska  1   k
alaska  1   l
alaska  1   m
alaska  1   n
alaska  1   o
arizona 1   p
arizona 1   q
arizona 1   r
arizona 1   s
arizona 1   t
arizona 1   u
arizona 1   v

into:

state   sector  attribute_value_1   attribute_value_2   attribute_value_3   attribute_value_4   attribute_value_5   attribute_value_6   attribute_value_7   attribute_value_8
alabama 1   a   b   c   d   e   f   g   h
alaska  1   i   j   k   l   m   n   o   n/a
arizona 1   p   q   r   s   t   u   v   n/a

So far, I haven't been able to use dcast or reshape to create this particular transformation.

Body:
Try this , using dplyr and splitstackshape

library(dplyr)
library(splitstackshape)
df=df%>%group_by(state,sector)%>%dplyr::summarise(attribute_value=paste(attribute_value,sep=',',collapse = ","))
concat.split(df, 3, drop = TRUE)

     state sector attribute_value_1 attribute_value_2 attribute_value_3 attribute_value_4 attribute_value_5 attribute_value_6 attribute_value_7 attribute_value_8
1: alabama      1                 a                 b                 c                 d                 e                 f                 g                 h
2:  alaska      1                 i                 j                 k                 l                 m                 n                 o                NA
3: arizona      1                 p                 q                 r                 s                 t                 u                 v                NA


问:
SCOM: It won't invoke an external module
I have a simple .exe on a network share that merely creates a dummy file on a network share. The program works. I've wrapped it in a .bat file, a .ps1 file, and a .vbs file, and they all work. However, when I create a SCOM rule to invoke any of these beasts it does not run. Am I missing a management pack or building the rule wrong such that SCOM doesn't run my module? What's the secret to having SCOM run an external module? Thanks. </p>

答:
First, Does your SCOM Agent's RunAs account have permission to access the file?
Most folks deploy the SCOM agent and leave it running under a local account.

Second, if this is a custom authored rule, is your rule properly configured to run on the target system or is it running on the management server? ( what is your target? )

With the basics covered, I have a hunch that your SCOM rule is executing PowerShell based on your use of 'invoke'. If you run PowerShell remotely without enabling CredSSP then you wont be able to make an authenticated connection to the file share downstream.

This guy explains it better then I can: https://4sysops.com/archives/using-credssp-for-second-hop-powershell-remoting/

If this is not the issue can you paste in the actual action the rule is taking?


问:
Test prices on shop findelements?
I have little problem with my school project.

It's a shop test in Selenium / Java. This is the shopping query: https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=nothing+car&rh=i%3Aaps%2Ck%3Anothing+car

And I tried get all products prices in test.

Is there any other way than this?

```<code>String string = findelement(by.xpath("//[@id='result_0']/div/div/div/div[2]/div[2]/div[1]/div[1]/a/span/span"))
System.out.println(string);
</code>```

After printing that value, I need to check if the value < 20$, and return a failure if so.

答:
here is the locator to get all li elements with minimal price < 20. Shipping not included.

```<code>//ul[@id='s-results-list-atf']//li[contains(@id,'result')][.//span[contains(@class,'sx-price-whole')][number(./text())<20]]
</code>```

if you want to get li elements with MAX price < 20 - use this:

```<code>//ul[@id='s-results-list-atf']//li[contains(@id,'result')][.//span[contains(@class,'sx-price-whole')][last()][number(./text())<20]]
</code>```

explanation:

//ul[@id='s-results-list-atf']//li[contains(@id,'result')] - get all
  li elements inside ul with goods

[.//span[contains(@class,'sx-price-whole')][...]] - get all prices
  of goods, and 1 more attribute to get those that has price lower 20

[number(./text())<20] - sorting elements with price < 20

Title: Test prices on shop findelements?

Body:
I have little problem with my school project.

It's a shop test in Selenium / Java. This is the shopping query: https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=nothing+car&rh=i%3Aaps%2Ck%3Anothing+car

And I tried get all products prices in test.

Is there any other way than this?

String string = findelement(by.xpath("//[@id='result_0']/div/div/div/div[2]/div[2]/div[1]/div[1]/a/span/span"))
System.out.println(string);

After printing that value, I need to check if the value < 20$, and return a failure if so.

Body:
here is the locator to get all li elements with minimal price < 20. Shipping not included.

//ul[@id='s-results-list-atf']//li[contains(@id,'result')][.//span[contains(@class,'sx-price-whole')][number(./text())<20]]

if you want to get li elements with MAX price < 20 - use this:

//ul[@id='s-results-list-atf']//li[contains(@id,'result')][.//span[contains(@class,'sx-price-whole')][last()][number(./text())<20]]

explanation:

//ul[@id='s-results-list-atf']//li[contains(@id,'result')] - get all
  li elements inside ul with goods

[.//span[contains(@class,'sx-price-whole')][...]] - get all prices
  of goods, and 1 more attribute to get those that has price lower 20

[number(./text())<20] - sorting elements with price < 20


问:
OpenFileDialog Spy
I'm trying to capture the path of selected files and folders from the standard OpenFileDialog window created by another application.

I have seen that is possible to perform this task with windows explorer:

```<code>IntPtr handle = GetOpenFileDialogHwnd();

ArrayList selected = new ArrayList();
var shell = new Shell32.Shell();

foreach(SHDocVw.InternetExplorer window in shell.Windows())
{
    if (window.HWND == (int)handle)
    {
        Shell32.FolderItems items = ((Shell32.IShellFolderViewDual2)window.Document).SelectedItems();
        foreach(Shell32.FolderItem item in items)
        {
            selected.Add(item.Path);
        }
    }
}
</code>```

However, the SHDocVw.ShellWindows () method does not return the opened openFileDialog hwnd. As windows explorer is very similar to OpenFileDialog, I imagine there is some way to do a cast having the hwnd of OpenFileDialog for the Shell32.IShellFolderViewDual2 interface like:

```<code>var view = Shell32.ShellFolderViewDual2.FromHwnd(hwnd);
</code>```

Is there any alternative way?

The goal is simple, make a log of files used in standard OpenFileDialog windows. Workable in Windows 7, 8, 10.

I know, it seems a very very very strange thing.

Edit:

Inspect.exe give me hope:

答:
An open file dialog is not a shell window so it won't show up in the ShellWindows list.

You can send the undocumented WM_GETISHELLBROWSER (WM_USER+7) message to the dialog window, but the returned IShellBrowser pointer is only valid inside the same process. Using it in another process would cause access violation.

Once you got IShellBrowser you can get other interfaces like IShellView or IFolderView2. For selection you want to use IFolderView2::GetSelection.

It is possible to inject a proxy DLL into the target process to control the file dialog, but you can't write the DLL in C#.

Title: OpenFileDialog Spy

Body:
I'm trying to capture the path of selected files and folders from the standard OpenFileDialog window created by another application.

I have seen that is possible to perform this task with windows explorer:

IntPtr handle = GetOpenFileDialogHwnd();

ArrayList selected = new ArrayList();
var shell = new Shell32.Shell();

foreach(SHDocVw.InternetExplorer window in shell.Windows())
{
    if (window.HWND == (int)handle)
    {
        Shell32.FolderItems items = ((Shell32.IShellFolderViewDual2)window.Document).SelectedItems();
        foreach(Shell32.FolderItem item in items)
        {
            selected.Add(item.Path);
        }
    }
}

However, the SHDocVw.ShellWindows () method does not return the opened openFileDialog hwnd. As windows explorer is very similar to OpenFileDialog, I imagine there is some way to do a cast having the hwnd of OpenFileDialog for the Shell32.IShellFolderViewDual2 interface like:

var view = Shell32.ShellFolderViewDual2.FromHwnd(hwnd);

Is there any alternative way?

The goal is simple, make a log of files used in standard OpenFileDialog windows. Workable in Windows 7, 8, 10.

I know, it seems a very very very strange thing.

Edit:

Inspect.exe give me hope:


问:
C# using streamwriter and streamreader at the same time to change line
so i searched a lot about how to change specific line in file, so i found the code which deletes line. I managed to edit the code and it changes exact line, but when i want to change other line after, previous word resets, and I dont know why.

This is the code which i found:

```<code>using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
    while ((line = reader.ReadLine()) != null) {
        if (String.Compare(line, line_to_delete) == 0)
            continue;

        writer.WriteLine(line);
    }
}
</code>```

}

This is my edited code:

```<code>public void ChangeLineInFile(string file, string file2, string linetochange, string changedline) {
            string line = null;

            using (StreamReader reader = new StreamReader(file)) {
                using (StreamWriter writer = new StreamWriter(file2)) {
                    while ((line = reader.ReadLine()) != null) {
                        if (String.Equals(line, linetochange)) {
                            writer.WriteLine(string.Format("{0}", changedline));
                        } else {
                            writer.WriteLine(line);
                        }
                    }
                }
            }
            File.Delete(file);
            File.Move(file2, file);
            File.Delete(file2);
        }
</code>```

答:
seems to me that your code does the following

```<code>file1->editA->file2
</code>```

then you run it again. Did you copy file2 back over file1 before you started or did you just do

```<code>file1->editB->file2
</code>```

After the first pass file1 still has the original data in it. So when you finish the function you need to copy the output file over the input file.

Body:
so i searched a lot about how to change specific line in file, so i found the code which deletes line. I managed to edit the code and it changes exact line, but when i want to change other line after, previous word resets, and I dont know why.

This is the code which i found:

using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
    while ((line = reader.ReadLine()) != null) {
        if (String.Compare(line, line_to_delete) == 0)
            continue;

        writer.WriteLine(line);
    }
}

}

This is my edited code:

public void ChangeLineInFile(string file, string file2, string linetochange, string changedline) {
            string line = null;

            using (StreamReader reader = new StreamReader(file)) {
                using (StreamWriter writer = new StreamWriter(file2)) {
                    while ((line = reader.ReadLine()) != null) {
                        if (String.Equals(line, linetochange)) {
                            writer.WriteLine(string.Format("{0}", changedline));
                        } else {
                            writer.WriteLine(line);
                        }
                    }
                }
            }
            File.Delete(file);
            File.Move(file2, file);
            File.Delete(file2);
        }

Body:
seems to me that your code does the following

file1->editA->file2

then you run it again. Did you copy file2 back over file1 before you started or did you just do

file1->editB->file2

After the first pass file1 still has the original data in it. So when you finish the function you need to copy the output file over the input file.


问:
How do I nest a scss rule for one specific selector in a list using &
I have a question that I could not find in the documentation or by searching stack overflow.

This is not the best example but it will give you the gist of what I am trying to accomplish.

Example

```<code>  .btn-group {

   .btn {
    font-size: 1.2em;
    background: dodgerblue;
    color: white;
    padding: 10px 20px;
    border-radius: 6px;

    &.btn-danger {
      background-color: red;
    }
    &.btn-primary {
      background-color: blue;
    }

    &.btn-primary, &.btn-danger {
      box-shadow: 1px solid black;
      &[0] {
        border: 10px solid black;
      }
    }

    }

  }
</code>```

Is there a way to select only one of the elements in a list? Maybe using array notation or something of that manner?

This does not work, but you can see what I am trying to accomplish.

Demo: https://codepen.io/anon/pen/awjeON

The real world example

```<code>  .bounce {

    .ng-leave {
      display: none;
    }

    .ng-enter, .ng-leave {
      position: relative;
      -webkit-animation-duration: 1s;
      animation-duration: 1s;
    }
  }
</code>```

答:
Yes, you can use nth-child.</p>

```<code>&:nth-child(1) {
    border: 2px solid grey;
}
</code>```

Body:
I have a question that I could not find in the documentation or by searching stack overflow.

This is not the best example but it will give you the gist of what I am trying to accomplish.

Example

  .btn-group {

   .btn {
    font-size: 1.2em;
    background: dodgerblue;
    color: white;
    padding: 10px 20px;
    border-radius: 6px;

    &.btn-danger {
      background-color: red;
    }
    &.btn-primary {
      background-color: blue;
    }

    &.btn-primary, &.btn-danger {
      box-shadow: 1px solid black;
      &[0] {
        border: 10px solid black;
      }
    }

    }

  }

Is there a way to select only one of the elements in a list? Maybe using array notation or something of that manner?

This does not work, but you can see what I am trying to accomplish.

Demo: https://codepen.io/anon/pen/awjeON

The real world example

  .bounce {

    .ng-leave {
      display: none;
    }

    .ng-enter, .ng-leave {
      position: relative;
      -webkit-animation-duration: 1s;
      animation-duration: 1s;
    }
  }

Body:
Yes, you can use nth-child.

&:nth-child(1) {
    border: 2px solid grey;
}


问:
Adding a Dropdown Select menu to select csv files in highcharts
Hi I am very new in programming and trying my hand. I am working on a project where i am using highchart. I am using csv file as data source. please take a look at the code

```<code><script type='text/javascript'>
$(document).ready(function() {
    $.get('dhaka.csv', function(csv) {
        // Create the chart
        window.chart = new Highcharts.StockChart({
            chart: {
                renderTo: 'container',
                type:'spline'
            },
            data: {
                csv: csv
            },
        }, function(chart) {

        });
    });
});
</script>

</head>
<body>
<select id="selectOpt">
    <option value="dhaka.csv">Dhaka</option>
    <option value="khulna.csv">Khulna</option>
    <option value="maymansingh.csv">Maymanshingh</option>
</select>
<div id="container" style="height: 600px; min-width: 600px; margin-top:10px;"></div>
</body>
</code>```

I will be having multiple csv file and need to have an option to select from a dropdown menu. Hope i have explained properly. Thanks in advance. Your help is appriciated.

I have used parsecsv.lib to read a csv file and my select menu will get the options from that csv. which i have done already. but i need to pass few other values ass well which i can not. please help me on this.. the updated code is here

```<code>    <?php
        require_once('parsecsv.lib.php');
        $csv = new parseCSV();
        $csv->auto('latlang.csv');
        $num = count($csv->data);
        $numRow = $num-1;
    ?>
    <select id="selectOpt" style="width:200px;">
    <?php
        for ($x = 0; $x <= $numRow; $x++) {
            $ston= $csv->data[$x]['Station'];
            //$arr = explode(' ',trim($ston));
            echo "<option value=".$ston.">".$ston."</option>";
        }
    ?>
    </select>
    <div id="container" style="height: 400px; width: 600px; margin-top:10px;"></div>
    <p id="demo"></p>

</body>
<script type='text/javascript'>
$(document).ready(function() {
     getChart('Amalshid');
});
var getChart = function(strFileName){
    $.get( strFileName + '.csv', function(csv) {
    // I AM STUCK HERE //
    //  data form latlang.csv
    var locations = <?php print json_encode($csv->data); ?>;
    for (i = 0; i < locations.length; i++) {
        var dataz = locations[i];
        document.getElementById('demo').innerHTML = strFileName + '<br>' + dataz.Station + '<br>' + dataz.DL + '<br>' + dataz.HRWL;
    }
        // Create the chart
        window.chart = new Highcharts.StockChart({
            chart: {
                renderTo: 'container',
                type:'spline'
            },
            data: {
                csv: csv,
                startRow: 34,
                startColumn:3
            },
        }, function(chart) {

        });
    });
};

$("#selectOpt").on("change",function(e){
    getChart($(this).val());
});
</code>```

The csv file looks like this

```<code>Station,RiverName,Longtitude,Latitude,DL,HRWL,CL
Amalshid,Kushiyara,92.4716,24.8845,15.85,18.28,100
Bahadurabad,B'putra,89.6743,25.0934,19.5,20.62,1
Hardinge.Bridge,Ganges,89.0279,24.072,14.25,15.19,1
</code>```

All I need, when I select from the drop-down menu it will take River name and DL and pass the value. thanks in advance

答:
You need to create a function that will create the chart and call it when the select changes. This new function (which I've named 'getChart') will accept the csv file name as an argument and inject it into the $.get. Right now you are only creating the chart once when the document loads.

Something like this should do the trick:

```<code>$(document).ready(function() {
     getChart('dhaka.csv');
});

var getChart = function(strFileName){
    $.get(strFileName, function(csv) {
        // Create the chart
        window.chart = new Highcharts.StockChart({
            chart: {
                renderTo: 'container',
                type:'spline'
            },
            data: {
                csv: csv
            },
        }, function(chart) {

        });
    });
};

$("#selectOpt").on("change",function(e){
    getChart($(this).val());
});
</code>```

(NOTE: I'm not that familiar with highcharts so I am assuming that that part of your code works. I'm only demonstrating the simple act of passing the value of the Select to another function. If the chart is not being generated that is a separate question.)

Body:
Hi I am very new in programming and trying my hand. I am working on a project where i am using highchart. I am using csv file as data source. please take a look at the code

<select id="selectOpt">
    <option value="dhaka.csv">Dhaka</option>
    <option value="khulna.csv">Khulna</option>
    <option value="maymansingh.csv">Maymanshingh</option>
</select>

I will be having multiple csv file and need to have an option to select from a dropdown menu. Hope i have explained properly. Thanks in advance. Your help is appriciated.

I have used parsecsv.lib to read a csv file and my select menu will get the options from that csv. which i have done already. but i need to pass few other values ass well which i can not. please help me on this.. the updated code is here

    <?php
        require_once('parsecsv.lib.php');
        $csv = new parseCSV();
        $csv->auto('latlang.csv');
        $num = count($csv->data);
        $numRow = $num-1;
    ?>
    <select id="selectOpt" style="width:200px;">
    <?php
        for ($x = 0; $x <= $numRow; $x++) {
            $ston= $csv->data[$x]['Station'];
            //$arr = explode(' ',trim($ston));
            echo "<option value=".$ston.">".$ston."</option>";
        }
    ?>
    </select>

Body:
You need to create a function that will create the chart and call it when the select changes. This new function (which I've named 'getChart') will accept the csv file name as an argument and inject it into the $.get. Right now you are only creating the chart once when the document loads.

Something like this should do the trick:

$(document).ready(function() {
     getChart('dhaka.csv');
});

var getChart = function(strFileName){
    $.get(strFileName, function(csv) {
        // Create the chart
        window.chart = new Highcharts.StockChart({
            chart: {
                renderTo: 'container',
                type:'spline'
            },
            data: {
                csv: csv
            },
        }, function(chart) {

        });
    });
};

$("#selectOpt").on("change",function(e){
    getChart($(this).val());
});

(NOTE: I'm not that familiar with highcharts so I am assuming that that part of your code works. I'm only demonstrating the simple act of passing the value of the Select to another function. If the chart is not being generated that is a separate question.)


问:
How do I prevent a JavasScript function from launching when the browser loads?
So I created a function (onSuccess) that launches when an AJAX request is successful. The problem is that my function launches when my browser loads and I would only like for the function only to be called when a button with id myButton is clicked. I am locating my button using document.getElementById("myButton"); but when I run console.log(document.getElementById("myButton")); in my browser console I get a Null result.

I've looked around and gotten a few suggestions stating that my element wasn't in the DOM when my script ran. I can understand that but when I moved the location of my script and moved the document.getElementById... my script still doesn't work. I viewed a few suggestions on Stackoverflow but they were mostly JQuery solutions. I'm looking for a pure JavaScript solution. My  code is below

JSFiddle Example

```<code>            var el = document.getElementById("myButton");
            el.onclick = addUser("username", "email", onSuccess);

            function onSuccess(result){
               alert ('successful');
            }

            // Do not modify this function. Add user service wrapper.
            function addUser(username, email, callback) {
                var xhr = new XMLHttpRequest();
                var response;
                var success = (!!Math.round(Math.random()));

                if (!success){
                    response = JSON.stringify({
                        success: success,
                        error: "Oups, something went wrong!"
                    });
                } else {
                    response = JSON.stringify({
                        success: success,
                        user: {
                            username: username,
                            email: email
                        }
                    });
                }

                xhr.open("POST", "/echo/json/");
                xhr.onload = function () {
                        if (xhr.status === 200) {
                            callback(JSON.parse(xhr.responseText));
                    }
                }
                xhr.send("json=" + response);
            };
</code>```

答:
Create anonymous function call which wraps the function

el.onclick = function() { addUser("username", "email", onSuccess); };

For more detailed explanation you can refer here

Body:
So I created a function (onSuccess) that launches when an AJAX request is successful. The problem is that my function launches when my browser loads and I would only like for the function only to be called when a button with id myButton is clicked. I am locating my button using document.getElementById("myButton"); but when I run console.log(document.getElementById("myButton")); in my browser console I get a Null result.

I've looked around and gotten a few suggestions stating that my element wasn't in the DOM when my script ran. I can understand that but when I moved the location of my script and moved the document.getElementById... my script still doesn't work. I viewed a few suggestions on Stackoverflow but they were mostly JQuery solutions. I'm looking for a pure JavaScript solution. My  code is below

JSFiddle Example

            var el = document.getElementById("myButton");
            el.onclick = addUser("username", "email", onSuccess);

            function onSuccess(result){
               alert ('successful');
            }

            // Do not modify this function. Add user service wrapper.
            function addUser(username, email, callback) {
                var xhr = new XMLHttpRequest();
                var response;
                var success = (!!Math.round(Math.random()));

                if (!success){
                    response = JSON.stringify({
                        success: success,
                        error: "Oups, something went wrong!"
                    });
                } else {
                    response = JSON.stringify({
                        success: success,
                        user: {
                            username: username,
                            email: email
                        }
                    });
                }

                xhr.open("POST", "/echo/json/");
                xhr.onload = function () {
                        if (xhr.status === 200) {
                            callback(JSON.parse(xhr.responseText));
                    }
                }
                xhr.send("json=" + response);
            };


答:
With:

```<code>library(data.table)
dcast(setDT(df),
      state + sector ~ rowid(state, prefix = 'attr_val_'),
      value.var = 'attribute_value')
</code>```

you get:

```<code>     state sector attr_val_1 attr_val_2 attr_val_3 attr_val_4 attr_val_5 attr_val_6 attr_val_7 attr_val_8
1: alabama      1          a          b          c          d          e          f          g          h
2:  alaska      1          i          j          k          l          m          n          o         NA
3: arizona      1          p          q          r          s          t          u          v         NA
</code>```

Title: Want to cast unique values into first/second/third variables

Body:
With:

library(data.table)
dcast(setDT(df),
      state + sector ~ rowid(state, prefix = 'attr_val_'),
      value.var = 'attribute_value')

you get:

     state sector attr_val_1 attr_val_2 attr_val_3 attr_val_4 attr_val_5 attr_val_6 attr_val_7 attr_val_8
1: alabama      1          a          b          c          d          e          f          g          h
2:  alaska      1          i          j          k          l          m          n          o         NA
3: arizona      1          p          q          r          s          t          u          v         NA


问:
Connect to MySQL from terminal with special characters in password not working
My MySQL password contains !@#. When i try to connect to mysql from the terminal using this password, I gives me a bash event not found error.
How do i fix this? I don't even understand why this error shows up with the password.

答:
You need to be sure to quote special characters. ! matches the pattern !<event ID> where <event ID> is something in your history.

Here's my history:

```<code>[vagrant@localhost files]$ history
1  tail /var/log/httpd/error_log
2  ./tools/runcmd deploy latest
3  ./tools/runcmd deploy fntsy.2625
4  ./tools/runcmd deploy fntsy-2625
</code>```

So when I type !1 I get:

```<code>[vagrant@localhost files]$ tail /var/log/httpd/error_log
<!-- tail information here -->
</code>```

In your case, the command line can't find an event with the ID @#, because nothing in your history matches that.

Try quoting your password: -p'<your pass>' or just omit your password altogether (call mysql -u <your-name> -p and it will prompt you to type your password in).

Body:
You need to be sure to quote special characters. ! matches the pattern !<event ID> where <event ID> is something in your history.

Here's my history:

[vagrant@localhost files]$ history
1  tail /var/log/httpd/error_log
2  ./tools/runcmd deploy latest
3  ./tools/runcmd deploy fntsy.2625
4  ./tools/runcmd deploy fntsy-2625

So when I type !1 I get:

[vagrant@localhost files]$ tail /var/log/httpd/error_log
<!-- tail information here -->

In your case, the command line can't find an event with the ID @#, because nothing in your history matches that.

Try quoting your password: -p'<your pass>' or just omit your password altogether (call mysql -u <your-name> -p and it will prompt you to type your password in).


问:
In function `uv__signal_global_init': ... undefined reference to `pthread_atfork'
I'm using libUV in my project and I'm getting the following error when I'm linking...

```<code>In function `uv__signal_global_init': ... undefined reference to `pthread_atfork'
</code>```

The strange thing is, my project only fails to link on certain flavors of Linux, but works on MacOS and Windows.

Any idea how to resolve this error?

答:
After scouring the internet, I found the solution in an obscure post from Ben Noordhuis in a Google group post.

#tl;dr

Link with -luv -ldl -lrt -pthread (in that order or it'll break when
  -W,--as-needed is in effect.)

Body:
I'm using libUV in my project and I'm getting the following error when I'm linking...

In function `uv__signal_global_init': ... undefined reference to `pthread_atfork'

The strange thing is, my project only fails to link on certain flavors of Linux, but works on MacOS and Windows.

Any idea how to resolve this error?


问:
devise and current_user
I have a Rails 3 app that I am trying to implement devise and declarative_authorization.
An important part of declarative_authorization is the presence of a function "role_symbols" within the user model.
Because of the way I implement roles, I am implementing an instance method within the User model to keep track of a value (let's call foo) as such:

```<code>  attr_accessor :foo

  def foo=(val)
    @foo = val
  end

  def foo
    @foo
  end
</code>```

Then we will use the value of foo inside the role_symbols method to limit the valid roles, maybe like this:

```<code>def role_symbols
  roles.where("foo = ?", @foo).name.underscore.to_sym
end
</code>```

The issue is when I try to set the value of foo for the current_user in a controller, the value doesn't stick, for example:

```<code>current_user.foo = 99
</code>```

is successful, but when I check the value in another view (or controller), the value of current_user.foo is nil.

Isn't the current_user object just a User object that is persisted in the Session?
If so, is there some lock on setting instance values within the current_user object?

答:
Was lucky enough to find the answer here:

https://web.archive.org/web/20140113211231/http://blog.drivingthevortex.nl/2010/01/24/using-declarative_authorization-with-subdomains/

Title: devise and current_user

Body:
I have a Rails 3 app that I am trying to implement devise and declarative_authorization.
An important part of declarative_authorization is the presence of a function "role_symbols" within the user model.
Because of the way I implement roles, I am implementing an instance method within the User model to keep track of a value (let's call foo) as such:

  attr_accessor :foo

  def foo=(val)
    @foo = val
  end

  def foo
    @foo
  end

Then we will use the value of foo inside the role_symbols method to limit the valid roles, maybe like this:

def role_symbols
  roles.where("foo = ?", @foo).name.underscore.to_sym
end

The issue is when I try to set the value of foo for the current_user in a controller, the value doesn't stick, for example:

current_user.foo = 99

is successful, but when I check the value in another view (or controller), the value of current_user.foo is nil.

Isn't the current_user object just a User object that is persisted in the Session?
If so, is there some lock on setting instance values within the current_user object?


问:
Tkinter Python listbox
I am a new python user. I'm used to programing on matlab.
I've trying to make a simple GUI with Tkinter pack, but I'm having some problems with that. I had already read and searched what i want but I couldn't develop it.

What I'm trying to do is to make a listbox and when I choose one (or more) options the index be returned (and stored) as a variable (array or vector) that could be used to indexing another array.

The best result I got was a listbox where the index were printed, but not stored as a variable (at least it hasn't been shows in the variables list)

I'm using spyder (anaconda).

I tryied a lot of codes and I don't have this anymore.

Sorry for the dumb question. I guess I still thinking in a Matlab way to write

答:
First, import tkinter, then, create the listbox. Then, you can use curselection to get the contents of the listbox.

```<code>import tkinter as tk
root = tk.Tk() #creates the window
myListbox = tk.Listbox(root, select=multiple) #allows you to select multiple things
contentsOfMyListbox = myListbox.curselection(myListbox) #stores selected stuff in tuple
</code>```

See the documentation here.

Title: Tkinter Python listbox

Body:
First, import tkinter, then, create the listbox. Then, you can use curselection to get the contents of the listbox.

import tkinter as tk
root = tk.Tk() #creates the window
myListbox = tk.Listbox(root, select=multiple) #allows you to select multiple things
contentsOfMyListbox = myListbox.curselection(myListbox) #stores selected stuff in tuple

See the documentation here.


问:
Swift 3 parsing API response trouble
I'm trying to parse an API response in Swift an Im having trouble getting to nested objects and arrays in the response

here is my sample json

```<code>{
  "Id": "10",
  "Name": "PV Prediction By Site",
  "Description": "",
  "Permalink": "",
  "Source_format": "JSON",
  "Internal_function_name": "get-meteo-by-site",
  "Additional_parameters": "Prediction",
  "Sites": null,
  "Data": [
    {
      "UTCDateString": "2017-05-01T20:10:33Z",
      "Value": [
        {
          "metadata": {
            "name": "Beck_Hill",
            "latitude": 46.26,
            "longitude": -112.44,
            "height": 1926,
            "timezone_abbrevation": "MDT",
            "utc_timeoffset": -6,
            "modelrun_utc": "2017-05-01 12:00",
            "modelrun_updatetime_utc": "2017-05-01 16:41",
            "kwp": 40.26,
            "slope": 30,
            "facing": 180,
            "tracking": 0
          },
          "units": {
            "time": "YYYY-MM-DD hh:mm",
            "pvpower": "kW",
            "snowcover": "mm",
            "iam": "percent",
            "temperature": "C"
          },
          "data_xmin": {
            "time": [
              "2017-05-01 07:00",
              "2017-05-01 07:15",
              "2017-05-01 07:30",
              "2017-05-01 07:45",
              "2017-05-01 08:00",
              "2017-05-01 08:15",
              "2017-05-01 08:30"
            ],
            "pvpower_instant": [
              40.26,
              40.26,
              40.26,
              40.26,
              40.26
            ]
          }
        }
      ]
    }
  ]
}
</code>```

And here is some of my parsing code, I can get to the first object in the "Data" array fine, but when i try to get the first object in the Value string it fails to convert the AnyObject to anything else

```<code>//get a Dictionary of sites
        sitesDictionary = try JSONSerialization.jsonObject(with: decodedData, options: .allowFragments) as? [[String:AnyObject]]

        CoreDataStack.sharedInstance.persistentContainer.performBackgroundTask({ (context) in
            //loop thorugh all site and create SiteMO objects from them
            for site in (sitesDictionary?.enumerated())! {
                //SiteMO
                let siteMO = SiteMO.siteInfo(siteInfo: site.element, inManagedObjectContext: context)!
                let siteFeedsDictionary = site.element["Feeds"] as! [[String:AnyObject]]

                //loop through every feed object and create FeedMO objects from them
                for feed in siteFeedsDictionary.enumerated() {
                    //FeedMO
                    let feedMO = FeedMO.feedInfo(feedInfo: feed.element, site: siteMO, inManagedObjectContext: context)!

                    //what type of data is in the feed?
                    switch feedMO.additionalParameters! {
                    case "Weather":
                        //its a feed with a Weather object
                        print("There should be a WeatherMO created Here")

                    case "Prediction":
                        //its a feed with a Prediction object
                        let dataArray = feed.element["Data"] as? [[String:AnyObject]]
</code>```

I need some data out of the "metadata" "units" and "data_xmin" objects

答:
For metadata

result[“Data”][0][“Value”][0]

Title: Swift 3 parsing API response trouble

Body:
I'm trying to parse an API response in Swift an Im having trouble getting to nested objects and arrays in the response

here is my sample json

{
  "Id": "10",
  "Name": "PV Prediction By Site",
  "Description": "",
  "Permalink": "",
  "Source_format": "JSON",
  "Internal_function_name": "get-meteo-by-site",
  "Additional_parameters": "Prediction",
  "Sites": null,
  "Data": [
    {
      "UTCDateString": "2017-05-01T20:10:33Z",
      "Value": [
        {
          "metadata": {
            "name": "Beck_Hill",
            "latitude": 46.26,
            "longitude": -112.44,
            "height": 1926,
            "timezone_abbrevation": "MDT",
            "utc_timeoffset": -6,
            "modelrun_utc": "2017-05-01 12:00",
            "modelrun_updatetime_utc": "2017-05-01 16:41",
            "kwp": 40.26,
            "slope": 30,
            "facing": 180,
            "tracking": 0
          },
          "units": {
            "time": "YYYY-MM-DD hh:mm",
            "pvpower": "kW",
            "snowcover": "mm",
            "iam": "percent",
            "temperature": "C"
          },
          "data_xmin": {
            "time": [
              "2017-05-01 07:00",
              "2017-05-01 07:15",
              "2017-05-01 07:30",
              "2017-05-01 07:45",
              "2017-05-01 08:00",
              "2017-05-01 08:15",
              "2017-05-01 08:30"
            ],
            "pvpower_instant": [
              40.26,
              40.26,
              40.26,
              40.26,
              40.26
            ]
          }
        }
      ]
    }
  ]
}

And here is some of my parsing code, I can get to the first object in the "Data" array fine, but when i try to get the first object in the Value string it fails to convert the AnyObject to anything else

//get a Dictionary of sites
        sitesDictionary = try JSONSerialization.jsonObject(with: decodedData, options: .allowFragments) as? [[String:AnyObject]]

        CoreDataStack.sharedInstance.persistentContainer.performBackgroundTask({ (context) in
            //loop thorugh all site and create SiteMO objects from them
            for site in (sitesDictionary?.enumerated())! {
                //SiteMO
                let siteMO = SiteMO.siteInfo(siteInfo: site.element, inManagedObjectContext: context)!
                let siteFeedsDictionary = site.element["Feeds"] as! [[String:AnyObject]]

                //loop through every feed object and create FeedMO objects from them
                for feed in siteFeedsDictionary.enumerated() {
                    //FeedMO
                    let feedMO = FeedMO.feedInfo(feedInfo: feed.element, site: siteMO, inManagedObjectContext: context)!

                    //what type of data is in the feed?
                    switch feedMO.additionalParameters! {
                    case "Weather":
                        //its a feed with a Weather object
                        print("There should be a WeatherMO created Here")

                    case "Prediction":
                        //its a feed with a Prediction object
                        let dataArray = feed.element["Data"] as? [[String:AnyObject]]

I need some data out of the "metadata" "units" and "data_xmin" objects


问:
Keep Group on one page if possible not working
I am building a SSRS report in 2012.

I have a tablix that has one grouping and one detail. There are 5 rows in the tablix, 4 of which are displaying group level information, or the headers for the detail, and then one detail row itself.

In the Row Groups section I have the following layout

```<code>[ (Group1)
  (Static)
  (Static)
  (Static)
    - (Detail)
  (Static)
  (Static)
</code>```

My goal is to, whenever possible keep all the rows for a group on the same page. If I can fit about 16 rows on a page, as long as I have about less than 12 detial rows I should be able to fit them on one page long with the 4 group level rows.

I have gone to the "Row Groups" section and click on each of the 7 items and selected KeepTogether = True. I also selected the first two static rows and the last two static rows and set them to KeepWithGroup = After. I could not set the middle static row to KeepWithGroup = After because I would get the following error when saving: The grouping 'Group1' has an invalid TablixMember. A TablixMember that is dynamic (i.e., has a Group specified) or has dynamic descendants must have the KeepWithGroup property set to "None".

What else can I do to keep each group on the same page when possible?

答:
Static tablix members will chain together KeepWithGroup=After and KeepWithGroup=Before until they reach a dynamic sibling tablix member and then stick there. Setting all your rows to "keep after" means that the first two rows will try to stay with the dynamic detail line, and the last two rows will try to stay with the first two rows of the next group and their dynamic detail line.

In this case you want to set KeepWithGroup=After on the first two static rows and KeepWithGroup=Before on the last two static rows.

Body:
I am building a SSRS report in 2012.

I have a tablix that has one grouping and one detail. There are 5 rows in the tablix, 4 of which are displaying group level information, or the headers for the detail, and then one detail row itself.

In the Row Groups section I have the following layout

[ (Group1)
  (Static)
  (Static)
  (Static)
    - (Detail)
  (Static)
  (Static)

My goal is to, whenever possible keep all the rows for a group on the same page. If I can fit about 16 rows on a page, as long as I have about less than 12 detial rows I should be able to fit them on one page long with the 4 group level rows.

I have gone to the "Row Groups" section and click on each of the 7 items and selected KeepTogether = True. I also selected the first two static rows and the last two static rows and set them to KeepWithGroup = After. I could not set the middle static row to KeepWithGroup = After because I would get the following error when saving: The grouping 'Group1' has an invalid TablixMember. A TablixMember that is dynamic (i.e., has a Group specified) or has dynamic descendants must have the KeepWithGroup property set to "None".

What else can I do to keep each group on the same page when possible?


问:
import a google static map directly in fpdf
I wanted to place a google static map in a pdffile generated by using the fpdf extension.
and used code to make a tempfile first. Using this code. However I run into an error ('can't open image file').</p>

```<code>// define the mapurl
$fullURL = 'http://maps.googleapis.com/maps/api/staticmap?center=Amsterdam&z=14&size=100x100&sensor=false';
// create a tempfile
$tempF = tmpfile();
fwrite($tempF, file_get_contents($fullURL));
//Rewind to the start of file
rewind($tempF);
// place the image in the pdf.
if (!empty($tempF)) {
    $this->Image($tempF,$start_x, $this->GetY(),0,100);
}
fclose($tempF);  // remove the tempfile
</code>```

答:
You can download the image and use it with fpdf

```<code>$url ="https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=".$googleApiKey;
$img = __DIR__.'/img/map.png';
file_put_contents($img, file_get_contents($url));

$pdf->Image($img,null,null,170);
</code>```

Hope that this will be helpful

Body:
I wanted to place a google static map in a pdffile generated by using the fpdf extension.
and used code to make a tempfile first. Using this code. However I run into an error ('can't open image file').

// define the mapurl
$fullURL = 'http://maps.googleapis.com/maps/api/staticmap?center=Amsterdam&z=14&size=100x100&sensor=false';
// create a tempfile
$tempF = tmpfile();
fwrite($tempF, file_get_contents($fullURL));
//Rewind to the start of file
rewind($tempF);
// place the image in the pdf.
if (!empty($tempF)) {
    $this->Image($tempF,$start_x, $this->GetY(),0,100);
}
fclose($tempF);  // remove the tempfile

Body:
You can download the image and use it with fpdf

$url ="https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=".$googleApiKey;
$img = __DIR__.'/img/map.png';
file_put_contents($img, file_get_contents($url));

$pdf->Image($img,null,null,170);

Hope that this will be helpful


问:
Difference between int a[5],int a[], int a[]={2,3} in Java
How could we statically declare array? Can't it be by int a[5];?

```<code>package oops;

public class exception {
    int arr1[] = new int[10];

    public static void main(String args[]){
        int a[] ={1,9};
        int[] a ;
        int a[9];
        a[0]=10;
    }
}
</code>```

答:
int arr1[] = new int[10]; - > an empty array of size 10 (memory allocated for it)

int a[] ={1,9}; -> [1, 9] (creates an array with the values of 1 and 9)

int[] a ;       -> array that has been declared but not initialized

int a[9]; -> doesn't work

See Arrays

Body:
How could we statically declare array? Can't it be by int a[5];?

package oops;

public class exception {
    int arr1[] = new int[10];

    public static void main(String args[]){
        int a[] ={1,9};
        int[] a ;
        int a[9];
        a[0]=10;
    }
}


问:
Cloning with jQuery
I have a form that allows users to refer friends. I want to add a link below the two input fields, "friend email" and "friend name", that will clone "friend-box" one time and add it below. In addition, the name attribute of "friend email" and "friend name" are name="friend_email[0]" and name="friend_name[0]" as suggested here. What's the best way to clone and increment the subscript? Here's the code:

```<code><div class="friend-box">

    <div class="field">
        <span><label for='friend_name'><strong>Friend's Name *</strong></label> </span>
        <input id='friend_name' name='friend_name[0]' type='text' />
    </div>

    <div class="field">
        <span><label for='friend_email'><strong>Friend's Email *</strong></label></span>
        <input id='friend_email' name='friend_email[0]' type='text' />
    </div>

</div>
</code>```

What's the best way to do this? One of the problems I had for example, is that when I cloned "friend-box" once and then twice, it obviously cloned it exponentially. So I'm guessing I need to have an ID number in there as well and increment it. Or, which is another method I saw, is to clone the "friend-box" when the page loads and keep cloning it from memory.

Thanks,
Ryan

答:
You don't need to specify the index [0], as long as you put [] the browser will automatically increment the index.

As for your question, here's how I would do it: http://jsfiddle.net/EJv4g/3/

Basically, I added a div.friend-boxes which wraps all friend boxes. I use jQuery to obtain the first friend box, clone it then reset the input field values (in case they were filled). I then append it to the .friend-boxes element.

You can change the append to prepend if you want it to be prepended.

Hope this helps!

Christian

Title: Cloning with jQuery

Body:
I have a form that allows users to refer friends. I want to add a link below the two input fields, "friend email" and "friend name", that will clone "friend-box" one time and add it below. In addition, the name attribute of "friend email" and "friend name" are name="friend_email[0]" and name="friend_name[0]" as suggested here. What's the best way to clone and increment the subscript? Here's the code:

        Friend's Name *
        <input id='friend_name' name='friend_name[0]' type='text' />

        Friend's Email *
        <input id='friend_email' name='friend_email[0]' type='text' />

What's the best way to do this? One of the problems I had for example, is that when I cloned "friend-box" once and then twice, it obviously cloned it exponentially. So I'm guessing I need to have an ID number in there as well and increment it. Or, which is another method I saw, is to clone the "friend-box" when the page loads and keep cloning it from memory.

Thanks,
Ryan


问:
How to run gulp tasks in terminal
I am a beginner in gulp. I have created a task named task1 in gulp.js and when i tried to execute that task using "gulp task1" in command line,  Its opening the gulp.js file  on brackets editor rather than  executing in command line. Can somebody help me in solving this problem

The code in my gulp file is

```<code>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');

gulp.task('task1', function () {
    return gulp
        .src(['./src/**/x.js', './*.js'])
        .pipe(jscs())
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish', {
            verbose: true
        }));

})
</code>```

答: In addition to making sure you have gulp globally installed, make sure your gulp file is named *gulpfile.js* and that is in the same directory as where you are running gulp. Then simply run gulp task1. If you run gulp without anything else, the default task will run (you can write a task named "default" which will be run in this case.

Title: How to run gulp tasks in terminal

Body:
I am a beginner in gulp. I have created a task named task1 in gulp.js and when i tried to execute that task using "gulp task1" in command line,  Its opening the gulp.js file  on brackets editor rather than  executing in command line. Can somebody help me in solving this problem

The code in my gulp file is

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');

gulp.task('task1', function () {
    return gulp
        .src(['./src/**/x.js', './*.js'])
        .pipe(jscs())
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish', {
            verbose: true
        }));

})


问:
Convert List into dataframe spark scala
I have a list with more than 30 strings. how to convert list into dataframe .
what i tried:

eg

```<code>Val list=List("a","b","v","b").toDS().toDF()

Output :

+-------+
|  value|
+-------+
|a      |
|b      |
|v      |
|b      |
+-------+

Expected Output is

  +---+---+---+---+
| _1| _2| _3| _4|
+---+---+---+---+
|  a|  b|  v|  a|
+---+---+---+---+
</code>```

any help on this .

答:
List("a","b","c","d") represents a record with one field and so the resultset displays one element in each row.

To get the expected output, the row should have four fields/elements in it. So, we wrap around the list as List(("a","b","c","d")) which represents one row, with four fields.
In a similar fashion a list with two rows goes as List(("a1","b1","c1","d1"),("a2","b2","c2","d2"))

```<code>scala> val list = sc.parallelize(List(("a", "b", "c", "d"))).toDF()
list: org.apache.spark.sql.DataFrame = [_1: string, _2: string, _3: string, _4: string]

scala> list.show
+---+---+---+---+
| _1| _2| _3| _4|
+---+---+---+---+
|  a|  b|  c|  d|
+---+---+---+---+

scala> val list = sc.parallelize(List(("a1","b1","c1","d1"),("a2","b2","c2","d2"))).toDF
list: org.apache.spark.sql.DataFrame = [_1: string, _2: string, _3: string, _4: string]

scala> list.show
+---+---+---+---+
| _1| _2| _3| _4|
+---+---+---+---+
| a1| b1| c1| d1|
| a2| b2| c2| d2|
+---+---+---+---+
</code>```

Title: Convert List into dataframe spark scala

Body:
I have a list with more than 30 strings. how to convert list into dataframe .
what i tried:

eg

Val list=List("a","b","v","b").toDS().toDF()

Output :

+-------+
|  value|
+-------+
|a      |
|b      |
|v      |
|b      |
+-------+

Expected Output is

  +---+---+---+---+
| _1| _2| _3| _4|
+---+---+---+---+
|  a|  b|  v|  a|
+---+---+---+---+

any help on this .

Body:
List("a","b","c","d") represents a record with one field and so the resultset displays one element in each row.

To get the expected output, the row should have four fields/elements in it. So, we wrap around the list as List(("a","b","c","d")) which represents one row, with four fields.
In a similar fashion a list with two rows goes as List(("a1","b1","c1","d1"),("a2","b2","c2","d2"))

scala> val list = sc.parallelize(List(("a", "b", "c", "d"))).toDF()
list: org.apache.spark.sql.DataFrame = [_1: string, _2: string, _3: string, _4: string]

scala> list.show
+---+---+---+---+
| _1| _2| _3| _4|
+---+---+---+---+
|  a|  b|  c|  d|
+---+---+---+---+

scala> val list = sc.parallelize(List(("a1","b1","c1","d1"),("a2","b2","c2","d2"))).toDF
list: org.apache.spark.sql.DataFrame = [_1: string, _2: string, _3: string, _4: string]

scala> list.show
+---+---+---+---+
| _1| _2| _3| _4|
+---+---+---+---+
| a1| b1| c1| d1|
| a2| b2| c2| d2|
+---+---+---+---+


问:
CSS: Liquid Bar with Text Won't Expand
I have a horizontal bar that has been given a width of 100%. Within the horizontal bar, I have text that is left-aligned within a 978px container.  Whenever the browser window is shrunk so that it is less than 978px wide, a scrollbar along the bottom of the page appears.  Whenever I scroll to the right, the bar no longer spans the width of the page but instead, is left behind.  I understand why this happens, but I don't know what to do to fix it.  If you have any ideas, let me know.  Thank you!

An example page

答:
well, you have #header set to 100% of it's containing block (which would be the body). When you shrink the body, the header's width shrinks. If the body's width is less than the container's width, the black bar will not extend the whole way.

What exactly would you rather it did?

-not have a scroll bar: take out the container, center the text using #header

-the black bar expands the whole distance: The easiest way to solve that is to give the container a background-color.

OwnerDisplayName: John

Title: CSS: Liquid Bar with Text Won't Expand

OwnerDisplayName: cofie


问:
Print msg to the console from GUI app - C#
Hi
I want to print some messages when I'm running C# GUI app on Visual Studio. It's like debugging. So I tried it, but not worked. console.writeline() didn't work or It may work, but I couldn't see the messages. Anyone knows about this? give me a solution if you know.
Thank you.</p>

答: Call Debug.WriteLine, which will print to Visual Studio's Output window.


问:
Want to cast unique values into first/second/third variables
I have a sample of a dataset that needs to be cast into a wide format, but I have a particular issue that I haven't seen addressed on StackOveflow yet.

The column that I'd like to use to make a long dataset has unique values for every single row, but I want to create a new dataset so that are n variables for n attributes for each idvar.

I need to convert this:

```<code>state   sector  attribute_value
alabama 1   a
alabama 1   b
alabama 1   c
alabama 1   d
alabama 1   e
alabama 1   f
alabama 1   g
alabama 1   h
alaska  1   i
alaska  1   j
alaska  1   k
alaska  1   l
alaska  1   m
alaska  1   n
alaska  1   o
arizona 1   p
arizona 1   q
arizona 1   r
arizona 1   s
arizona 1   t
arizona 1   u
arizona 1   v
</code>```

into:

```<code>state   sector  attribute_value_1   attribute_value_2   attribute_value_3   attribute_value_4   attribute_value_5   attribute_value_6   attribute_value_7   attribute_value_8
alabama 1   a   b   c   d   e   f   g   h
alaska  1   i   j   k   l   m   n   o   n/a
arizona 1   p   q   r   s   t   u   v   n/a
</code>```

So far, I haven't been able to use dcast or reshape to create this particular transformation.

答:
With dplyr and tidyr.  The trick is to set up a dummy variable (here called ind) and use this to convert to wide format.

```<code>df2 <- df %>% group_by(state, sector) %>%
              mutate(ind=paste0("Attribute_", seq_along(attribute_value))) %>%
              ungroup() %>%
              spread(key=ind, value=attribute_value)

df2
# A tibble: 3 x 10
    state sector Attribute_1 Attribute_2 Attribute_3 Attribute_4 Attribute_5 Attribute_6 Attribute_7 Attribute_8
*   <chr>  <int>       <chr>       <chr>       <chr>       <chr>       <chr>       <chr>       <chr>       <chr>
1 alabama      1           a           b           c           d           e           f           g           h
2  alaska      1           i           j           k           l           m           n           o        <NA>
3 arizona      1           p           q           r           s           t           u           v        <NA>
</code>```

Body:
I have a sample of a dataset that needs to be cast into a wide format, but I have a particular issue that I haven't seen addressed on StackOveflow yet.

The column that I'd like to use to make a long dataset has unique values for every single row, but I want to create a new dataset so that are n variables for n attributes for each idvar.

I need to convert this:

state   sector  attribute_value
alabama 1   a
alabama 1   b
alabama 1   c
alabama 1   d
alabama 1   e
alabama 1   f
alabama 1   g
alabama 1   h
alaska  1   i
alaska  1   j
alaska  1   k
alaska  1   l
alaska  1   m
alaska  1   n
alaska  1   o
arizona 1   p
arizona 1   q
arizona 1   r
arizona 1   s
arizona 1   t
arizona 1   u
arizona 1   v

into:

state   sector  attribute_value_1   attribute_value_2   attribute_value_3   attribute_value_4   attribute_value_5   attribute_value_6   attribute_value_7   attribute_value_8
alabama 1   a   b   c   d   e   f   g   h
alaska  1   i   j   k   l   m   n   o   n/a
arizona 1   p   q   r   s   t   u   v   n/a

So far, I haven't been able to use dcast or reshape to create this particular transformation.

Body:
With dplyr and tidyr.  The trick is to set up a dummy variable (here called ind) and use this to convert to wide format.

df2 <- df %>% group_by(state, sector) %>%
              mutate(ind=paste0("Attribute_", seq_along(attribute_value))) %>%
              ungroup() %>%
              spread(key=ind, value=attribute_value)

df2
# A tibble: 3 x 10
    state sector Attribute_1 Attribute_2 Attribute_3 Attribute_4 Attribute_5 Attribute_6 Attribute_7 Attribute_8
*   <chr>  <int>       <chr>       <chr>       <chr>       <chr>       <chr>       <chr>       <chr>       <chr>
1 alabama      1           a           b           c           d           e           f           g           h
2  alaska      1           i           j           k           l           m           n           o        <NA>
3 arizona      1           p           q           r           s           t           u           v        <NA>


问:
Regex not preceded by href="
So I am adding [embed][/embed] around youtube links in a WordPress environment, since if you use different fields for content input in the backend than the normale content editor, it won't do this automatically (even if you apply_filter the_content).

So, I found this regex which works perfect for my application:

```<code>$firstalinea = preg_replace('/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i', '[embed]https://www.youtube.com/watch?v=$2[/embed]', $firstalinea);
</code>```

Except for one thing. If someone places a link to a YouTube-video instead of wanting to embed it, it also replaces and then the link does not work anymore.

```<code><a href="https://youtu.be/xxxxxx">Link</a>
</code>```

So, how to make the regex NOT work, if preceded by href="   ?

Thanks!

Title: Regex not preceded by href="

Body:
So I am adding [embed][/embed] around youtube links in a WordPress environment, since if you use different fields for content input in the backend than the normale content editor, it won't do this automatically (even if you apply_filter the_content).

So, I found this regex which works perfect for my application:

$firstalinea = preg_replace('/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i', '[embed]https://www.youtube.com/watch?v=$2[/embed]', $firstalinea);

Except for one thing. If someone places a link to a YouTube-video instead of wanting to embed it, it also replaces and then the link does not work anymore.

Link

So, how to make the regex NOT work, if preceded by href="   ?

Thanks!

Body:
Solved it:

$re = '/(?<!href=\")(http:\/\/|https:\/\/)(?:www\.)?youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i';
$firstalinea = preg_replace($re, '[embed]https://www.youtube.com/watch?v=$3[/embed]', $firstalinea);


问:
Git submodule and working copy at the same time?
I have my .dotfiles (.zshrc, .bashrc, etc.) in Git.

I would like to have some extra repos (from me as well) in a plugins subdirectory -- I do have a custom repo for my Emacs config, another for my LaTeX config, etc.

Does it make sense to create those as submodules?  I mean: can I use that as a working copy as well, and directly edit my LaTeX config from the submodule?

Or am I mixing some stuff here?  (I would like to avoid having 2 dirs on my machine with the same contents, or almost, for every submodule repo -- and I would like my submodule to be always at the latest version, or almost.)

UPDATE

I do have my main repo (which is an editable working copy at the same time) in /usr/me/.dotfiles.

If I put submodules in /usr/me/.dotfiles/plugins (for example), I have the advantage of having all the other puzzle pieces fetched at one, when cloning, but I understand that I can't edit those files directly in there, right?  Then, that's a problem... because I do have "task files", for example, which are edited when I reschedule things.

And to properly edit those, I would have to go to /usr/me/dev/repo-task-files... Not practical at all...

Now, I can just put the plain repos in /usr/me/.dotfiles/plugins, though not as submodules. It means that, on other machines, I must manually (or via a script) clone the different repos in the same place, but it's not a one-line operation (when cloning dotfiles).

But, then, I can edit the files directly where they are.

My improved question: is the above description right?  Is there a 3rd way?

答:
Update

Does it make sense to create those as submodules? I mean: can I use
  that as a working copy as well, and directly edit my LaTeX config from
  the submodule?

Yes, submodules are meant to be used as independent repositories. Committing changes inside a submodule is exactly the same as making them in another local copy of the repo. The only difference is you'll have uncommitted changes in the super repo.

If I put submodules in /usr/me/.dotfiles/plugins (for example), I have
  the advantage of having all the other puzzle pieces fetched at one,
  when cloning, but I understand that I can't edit those files directly
  in there, right?

You can edit submodules just like you would any other git repository.

Now, I can just put the plain repos in /usr/me/.dotfiles/plugins,
  though not as submodules. It means that, on other machines, I must
  manually (or via a script) clone the different repos in the same
  place, but it's not a one-line operation (when cloning dotfiles).

The problem with this approach is that any change in the "subrepo" would appear in both repositories. The subproject's folder would be treated just like another tracked directory in the superproject.

When a repo sees its submodule change, it will report a single modified file:

```<code>$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
  (commit or discard the untracked or modified content in submodules)

        modified:   plugins/LaTeX (new commits, modified content)
</code>```

Original answer

The thing about submodules is that you're binding a specific version of the repository to the super project. What if you continued to develop the submodule, and made a change that would break the parent?

By using submodules you make sure to always have a working version.

You shouldn't care about having multiple copies of repositories locally anyway.

If you're concerned about wasting bandwidth when fetching, you could add a remote to a repo pointing to the other local copy.

Body:
Update

Does it make sense to create those as submodules? I mean: can I use
  that as a working copy as well, and directly edit my LaTeX config from
  the submodule?

Yes, submodules are meant to be used as independent repositories. Committing changes inside a submodule is exactly the same as making them in another local copy of the repo. The only difference is you'll have uncommitted changes in the super repo.

If I put submodules in /usr/me/.dotfiles/plugins (for example), I have
  the advantage of having all the other puzzle pieces fetched at one,
  when cloning, but I understand that I can't edit those files directly
  in there, right?

You can edit submodules just like you would any other git repository.

Now, I can just put the plain repos in /usr/me/.dotfiles/plugins,
  though not as submodules. It means that, on other machines, I must
  manually (or via a script) clone the different repos in the same
  place, but it's not a one-line operation (when cloning dotfiles).

The problem with this approach is that any change in the "subrepo" would appear in both repositories. The subproject's folder would be treated just like another tracked directory in the superproject.

When a repo sees its submodule change, it will report a single modified file:

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)
  (commit or discard the untracked or modified content in submodules)

        modified:   plugins/LaTeX (new commits, modified content)

Original answer

The thing about submodules is that you're binding a specific version of the repository to the super project. What if you continued to develop the submodule, and made a change that would break the parent?

By using submodules you make sure to always have a working version.

You shouldn't care about having multiple copies of repositories locally anyway.

If you're concerned about wasting bandwidth when fetching, you could add a remote to a repo pointing to the other local copy.


问:
Managing browser cache
I'm building a web application. I'm linking to separate css and js files and I want to manage cache.
If the script js or the style css file have been updated then force reload and replace that file, else get the file from cache.
Is that possible? How to do that?</p>

答:
This depends a lot on the server, as caching in browsers is based on a set of headers sent by the server, including Cache-Control, Expires, Etag, and the way it handles headers from the client, including If-Modified-Since, and If-None-Match. This allows the browser to try to request that the server return a file only if it doesn't already have the latest version; if, based on headers, the server determines that the browser already has the latest version, it can return a response of 304 not modified.

You can also use "cache buster" query parameters as sia suggested: add a query parameter to the file name, which will be ignored by most servers, but which you can use to indicate that there is a new version of the same file. While the query parameter won't let you control what version is downloaded, it will be part of the key in the browser cache, so when the parameter changes, the browser will download the file again.

There is an excellent rundown of how HTTP caching works over on MDN.

Title: Managing browser cache