问:
Ajax call is double-posting a form the second time it is submitted
For some reason my ajax call is double-posting the second time I submit.

I have a view containing this:

```<code> @using (Ajax.BeginForm("Create", "BasketPage", new AjaxOptions
{
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "myDiv",

}))
    {
        <textarea id="comment" name="comment"> </textarea> <br />
        <input type="submit" class="btn btn-blue" value="Comment" />
    }
</code>```

The BasketPage Controller Action which is invoked looks like this:

```<code>public PartialViewResult Create(BasketPage currentPage, string comment)
        {
                Comment newComment = new Comment()
                {
                    Username = User.Identity.Name,
                    Text = HttpUtility.HtmlEncode(comment),
                    PageID = currentPage.PageLink.ID
                };

                commentRepository.Save(newComment);

                var model = new BasketListModel(currentPage)
                                {
                                    CommentsList = commentRepository.GetComments(currentPage.PageLink)
                                };

                return PartialView("_Comment", model);
        }

</code>```

Problem scenario:

I enter a value, submit the form. Everything works as expected.

I once again (thus a second time) enter a value, submit the form. NOW the Save method is called twice -  which is resulting in that the value is saved twice in the DB, creating two rows with same value.

If I replace the Ajax.beginform with a regular @Html.BeginForm the Save method is only called once.

What am I missing?

答:
I have had this issue before, I had a partial view with data looking similiar to this

```<code><div id="OuterDiv">
        @using (Ajax.BeginForm("ProcessStuff", "Stuff", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "divWrapper" }, new { @class = "form-horizontal", @id = "frmProcess" }))
            {
            <div ="divWrapper">
            <--add some controls --!>
            </div>
            }
<div/>
</code>```

My controller had code returning the view again:

```<code>[HttpPost]
public ActionResult ProcessStuff(WhateverNamespace.Models model)
{
  //do some processing
 return PartialView("_stuff", model);
}
</code>```

The problem was in the view itsself, if you look carefully, my UpdateTargetId was inside the ajax form, resulting in the second post returning the partial view and placing the Ajax form inside an already existing Ajax form. This caused all requests from the second one onwards to post multiple times.

The solution here is to change the UpdateTargetId to a control that lives outside the ajax form, in this case "OuterDiv"

Body:
For some reason my ajax call is double-posting the second time I submit.

I have a view containing this:

 @using (Ajax.BeginForm("Create", "BasketPage", new AjaxOptions
{
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "myDiv",

}))
    {
        <textarea id="comment" name="comment"> </textarea>

        <input type="submit" class="btn btn-blue" value="Comment" />
    }

The BasketPage Controller Action which is invoked looks like this:

public PartialViewResult Create(BasketPage currentPage, string comment)
        {
                Comment newComment = new Comment()
                {
                    Username = User.Identity.Name,
                    Text = HttpUtility.HtmlEncode(comment),
                    PageID = currentPage.PageLink.ID
                };

                commentRepository.Save(newComment);

                var model = new BasketListModel(currentPage)
                                {
                                    CommentsList = commentRepository.GetComments(currentPage.PageLink)
                                };

                return PartialView("_Comment", model);
        }

Problem scenario:

I enter a value, submit the form. Everything works as expected.

I once again (thus a second time) enter a value, submit the form. NOW the Save method is called twice -  which is resulting in that the value is saved twice in the DB, creating two rows with same value.

If I replace the Ajax.beginform with a regular @Html.BeginForm the Save method is only called once.

What am I missing?

Body:
I have had this issue before, I had a partial view with data looking similiar to this

<div id="OuterDiv">
        @using (Ajax.BeginForm("ProcessStuff", "Stuff", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "divWrapper" }, new { @class = "form-horizontal", @id = "frmProcess" }))
            {
            <div ="divWrapper">
            <--add some controls --!>
            </div>
            }
<div/>

My controller had code returning the view again:

[HttpPost]
public ActionResult ProcessStuff(WhateverNamespace.Models model)
{
  //do some processing
 return PartialView("_stuff", model);
}

The problem was in the view itsself, if you look carefully, my UpdateTargetId was inside the ajax form, resulting in the second post returning the partial view and placing the Ajax form inside an already existing Ajax form. This caused all requests from the second one onwards to post multiple times.

The solution here is to change the UpdateTargetId to a control that lives outside the ajax form, in this case "OuterDiv"


来源: stackexchange

问:
User Provided CSV in Django Web Project
I'm using Django to host a web application, and I would like to obtain a CSV file from the user, and process this information (using Python). I am currently using this line of code in the HTML to obtain the CSV file:

```<code><input type="file" accept="text/csv" id="mycsv">
</code>```

Where in the Django project should I obtain the information from the CSV file, and how would I go about doing this? (I know the question is broad and doesn't give context for my specific project, but I figure that once I know how to access the data in the CSV I can figure the rest out).

答:
Step 1: upload the file

```<code># forms.py
from django import forms

class UploadFileForm(forms.Form):
    file  = forms.FileField()
</code>```

Step 2: parse data and update database

```<code># views.py
import csv

from .models import YourModel

def myview(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)

        if form.is_valid():
            reader = csv.reader(form.cleaned_data['file'])

            for row in reader:
                try:
                    some_instance = YourModel.objects.get_or_create(row[...])

            ...
</code>```

ContentLicense: CC BY-SA 3.0

Title: User Provided CSV in Django Web Project

Body:
I'm using Django to host a web application, and I would like to obtain a CSV file from the user, and process this information (using Python). I am currently using this line of code in the HTML to obtain the CSV file:

<input type="file" accept="text/csv" id="mycsv">

Where in the Django project should I obtain the information from the CSV file, and how would I go about doing this? (I know the question is broad and doesn't give context for my specific project, but I figure that once I know how to access the data in the CSV I can figure the rest out).

Body:
Step 1: upload the file

# forms.py
from django import forms

class UploadFileForm(forms.Form):
    file  = forms.FileField()

Step 2: parse data and update database

# views.py
import csv

from .models import YourModel

def myview(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)

        if form.is_valid():
            reader = csv.reader(form.cleaned_data['file'])

            for row in reader:
                try:
                    some_instance = YourModel.objects.get_or_create(row[...])

            ...


问:
Retrieving a property of a JSON object by index?
Assuming this JSON object:

```<code>var obj = {
    "set1": [1, 2, 3],
    "set2": [4, 5, 6, 7, 8],
    "set3": [9, 10, 11, 12]
};
</code>```

The "set2" property may be retrieved like so:

```<code>obj["set2"]
</code>```

Is there a way to retrieve the "set2" property by index? It is the second property of the JSON object. This does not work (of course):

```<code>obj[1]
</code>```

So, let's say that I want to retrieve the second property of the JSON object, but I don't know its name - how would I do it then?

Update: Yes, I understand that objects are collections of unordered properties. But I don't think that the browsers mess with the "original" order defined by the JSON literal / string.

答:
Jeroen Vervaeke's answer is modular and the works fine, but it can cause  problems if it is using with jQuery or other libraries that count on "object-as-hashtables" feature of Javascript.

I modified it a little to make usable with these libs.

```<code>function getByIndex(obj, index) {
  return obj[Object.keys(obj)[index]];
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Assuming this JSON object:

var obj = {
    "set1": [1, 2, 3],
    "set2": [4, 5, 6, 7, 8],
    "set3": [9, 10, 11, 12]
};

The "set2" property may be retrieved like so:

obj["set2"]

Is there a way to retrieve the "set2" property by index? It is the second property of the JSON object. This does not work (of course):

obj[1]

So, let's say that I want to retrieve the second property of the JSON object, but I don't know its name - how would I do it then?

Update: Yes, I understand that objects are collections of unordered properties. But I don't think that the browsers mess with the "original" order defined by the JSON literal / string.

Body:
Jeroen Vervaeke's answer is modular and the works fine, but it can cause  problems if it is using with jQuery or other libraries that count on "object-as-hashtables" feature of Javascript.

I modified it a little to make usable with these libs.

function getByIndex(obj, index) {
  return obj[Object.keys(obj)[index]];
}


问:
Resizing wallpaper after reboot
I build my custom launcher for Android 4.4.2 and have some problem with wallpapers. When I set new wallpaper everything is good image fit to screen, but after reloading device, wallpaper gets scaled and I see the only center part, even if screen size and image size identical by default.
I think this is because of multiple screens mode, but I'm not sure. Right now I reset wallpaper every time with Broadcast Receiver on ACTION_BOOT event, but it provides some lags and doesn't look like an elegant solution.
I set and reload wallpaper with this class:

```<code>public class WallpaperUtils {

public static final String PREF_CUSTOM_WALLPAPER = "PREF_CUSTOM_WALLPAPER";
public static final String PREF_WALLPAPER_RES = "PREF_WALLPAPER_RES";

public static void reloadWallpaper(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean isCustomWallpaper = prefs.getBoolean(PREF_CUSTOM_WALLPAPER, false);

    if (isCustomWallpaper) {
        int wallRes = prefs.getInt(PREF_WALLPAPER_RES, 0);
        setWallpaper(context, wallRes);
    }

}

public static void setWallpaper(Context context, int wallRes) {

    WallpaperManager manager = WallpaperManager.getInstance(context.getApplicationContext());

    WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

    DisplayMetrics metrics = new DisplayMetrics();
    window.getDefaultDisplay().getMetrics(metrics);

    int width = metrics.widthPixels;
    int height = metrics.heightPixels;

    Bitmap tempBitmap = BitmapFactory.decodeResource(context.getResources(), wallRes);
    Bitmap bitmap = Bitmap.createScaledBitmap(tempBitmap, width, height, true);

    manager.setWallpaperOffsetSteps(1, 1);
    manager.suggestDesiredDimensions(width, height);

    try {
        manager.setBitmap(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

}

and in AndroidManifest home screen looks like:

```<code>    <activity
        android:name=".ui.main.MainActivity"
        android:launchMode="singleTask"
        android:screenOrientation="landscape"
        android:theme="@android:style/Theme.Wallpaper.NoTitleBar.Fullscreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.HOME" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</code>```

In default launcher wallpaper scales too, so I don't think that problem with style, but I can't find where is the problem.

答:
After researching about android themes and styles I'll understand what's going wrong.

@android:style/Theme

is deprecated and don't recommend to use after API 11.

So I just get the wallpaper in home screen activity in an onStart callback via wallpaper manager and set as background to the main layout.

Title: Resizing wallpaper after reboot

Body:
I build my custom launcher for Android 4.4.2 and have some problem with wallpapers. When I set new wallpaper everything is good image fit to screen, but after reloading device, wallpaper gets scaled and I see the only center part, even if screen size and image size identical by default.
I think this is because of multiple screens mode, but I'm not sure. Right now I reset wallpaper every time with Broadcast Receiver on ACTION_BOOT event, but it provides some lags and doesn't look like an elegant solution.
I set and reload wallpaper with this class:

public class WallpaperUtils {

public static final String PREF_CUSTOM_WALLPAPER = "PREF_CUSTOM_WALLPAPER";
public static final String PREF_WALLPAPER_RES = "PREF_WALLPAPER_RES";

public static void reloadWallpaper(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean isCustomWallpaper = prefs.getBoolean(PREF_CUSTOM_WALLPAPER, false);

    if (isCustomWallpaper) {
        int wallRes = prefs.getInt(PREF_WALLPAPER_RES, 0);
        setWallpaper(context, wallRes);
    }

}

public static void setWallpaper(Context context, int wallRes) {

    WallpaperManager manager = WallpaperManager.getInstance(context.getApplicationContext());

    WindowManager window = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

    DisplayMetrics metrics = new DisplayMetrics();
    window.getDefaultDisplay().getMetrics(metrics);

    int width = metrics.widthPixels;
    int height = metrics.heightPixels;

    Bitmap tempBitmap = BitmapFactory.decodeResource(context.getResources(), wallRes);
    Bitmap bitmap = Bitmap.createScaledBitmap(tempBitmap, width, height, true);

    manager.setWallpaperOffsetSteps(1, 1);
    manager.suggestDesiredDimensions(width, height);

    try {
        manager.setBitmap(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

and in AndroidManifest home screen looks like:

    <activity
        android:name=".ui.main.MainActivity"
        android:launchMode="singleTask"
        android:screenOrientation="landscape"
        android:theme="@android:style/Theme.Wallpaper.NoTitleBar.Fullscreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.HOME" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

In default launcher wallpaper scales too, so I don't think that problem with style, but I can't find where is the problem.


问:
Cannot get item when crawl data using scrapy
I have inspected element from chrome:

I want to get data in the red box (can be more than one) using scrapy. I used this code (I see the tutorial from the scrapy documentation):

```<code>import scrapy

class KamusSetSpider(scrapy.Spider):
    name = "kamusset_spider"
    start_urls = ['http://kbbi.web.id/' + 'abad']

    def parse(self, response):
        for kamusset in response.css("div#d1"):
            text = kamusset.css("div.sub_17 b.tur.highlight::text").extract()
            print(dict(text=text))
</code>```

But, there is no result:

What happen? I have change it to this(use splash) but still not working:

```<code>    def start_requests(self):
        for url in self.start_urls:
            yield SplashRequest(url, self.parse, args={'wait': 0.5})

    def parse(self, response):
        html = response.body

        for kamusset in response.css("div#d1"):
            text = kamusset.css("div.sub_17 b.tur.highlight::text").extract()
            print(dict(text=text))
</code>```

答:
In this case it seems that the page content is generated dynamically --
 eventhough you can see the elements present when inspecting from browser, they are not present in the HTML source (i.e. in what Scrapy sees). That's because Scrapy can't render JavaScript etc. You need to use some kind of browser to render the page and then put the result to Scrapy for processing. I recommend using Splash for it's seamless integration with Scrapy.</p>

Body:
I have inspected element from chrome:

I want to get data in the red box (can be more than one) using scrapy. I used this code (I see the tutorial from the scrapy documentation):

import scrapy

class KamusSetSpider(scrapy.Spider):
    name = "kamusset_spider"
    start_urls = ['http://kbbi.web.id/' + 'abad']

    def parse(self, response):
        for kamusset in response.css("div#d1"):
            text = kamusset.css("div.sub_17 b.tur.highlight::text").extract()
            print(dict(text=text))

But, there is no result:

What happen? I have change it to this(use splash) but still not working:

    def start_requests(self):
        for url in self.start_urls:
            yield SplashRequest(url, self.parse, args={'wait': 0.5})

    def parse(self, response):
        html = response.body

        for kamusset in response.css("div#d1"):
            text = kamusset.css("div.sub_17 b.tur.highlight::text").extract()
            print(dict(text=text))


问:
get title inside link tag in HTML using beautifulsoup
I am extracting data from https://data.gov.au/dataset?organization=reservebankofaustralia&_groups_limit=0&groups=business
and got output I wanted but now problem is: the output that I am getting is Business Support an... and Reserve Bank of Aus...., not complete text, I want to print the whole text not "......." for all. I replaced line 9 and 10 in answer by jezrael, please refer to Fetching content from html and write fetched content in a specific format in CSV with code
org = soup.find_all('a', {'class':'nav-item active'})[0].get('title')
groups = soup.find_all('a', {'class':'nav-item active'})[1].get('title')
. And I am running it separately and getting error: list index out of range. What should I use to extract complete sentences? I also tried :
org = soup.find_all('span',class_="filtered pill"), it gave answer of type string when I ran separately but could not run with whole code.

答:
I guess you are trying to do this. Here in each link there is title attribute. So here I simply checked if there is any title attribute present or not and if it is then I simply printed it.

There are blank lines because there are few links where title="" so you can avoid that using conditional statement and then get all titles from that.

```<code>>>> l = soup.find_all('a')
>>> for i in l:
...     if i.has_attr('title'):
...             print(i['title'])
...
Remove
Remove
Reserve Bank of Australia

Business Support and Regulation

Creative Commons Attribution 3.0 Australia
>>>
</code>```

Body:
I guess you are trying to do this. Here in each link there is title attribute. So here I simply checked if there is any title attribute present or not and if it is then I simply printed it.

There are blank lines because there are few links where title="" so you can avoid that using conditional statement and then get all titles from that.

>>> l = soup.find_all('a')
>>> for i in l:
...     if i.has_attr('title'):
...             print(i['title'])
...
Remove
Remove
Reserve Bank of Australia

Business Support and Regulation

Creative Commons Attribution 3.0 Australia
>>>


问:
python: taking random sample from data but keeping the same distribution
I have a training data that has 20,000 and more instances, split into 3 classes, with a distribution like A=10%, B=20%, C=70%. Is there a way in sklearn or pandas or anything else that can take a sample of 10% from this data but at the same time respecting the distribution of different classes? As I need do grid search on the data but the original dataset is too high dimensional (20,000 x 12,000 feature dimension)

The train_test_split will keep the distribution but it only splits the entire dataset into two sets, which are still too large.

Thanks

答:
The train_test_split function allows a definition of the size of the training data:

```<code>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1)
</code>```

See the docs

Body:
The train_test_split function allows a definition of the size of the training data:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1)

See the docs


问:
Spark history server
I'm currently working on Spark in Scala with the IntelliJ IDE. I have access to the web UI when my program is executed but i don't have access to the history server afterwards.

Any help would be very appreciated, i'm using windows by the way.
I also have created a log folder at C:/tmp/spark-events and edited the spark-defaults.conf this way :

```<code># Example:
# spark.master                     spark://master:7077
# spark.eventLog.enabled           true
# spark.eventLog.dir               hdfs://namenode:8021/directory
# spark.serializer                 org.apache.spark.serializer.KryoSerializer
# spark.driver.memory              5g
# spark.executor.extraJavaOptions  -XX:+PrintGCDetails -Dkey=value -Dnumbers="one two three"
-Dspark.eventLog.enabled           true
-Dspark.history.fs.logDirectory    file:///C:/tmp/spark-events
-Dspark.eventLog.dir               file:///C:/tmp/spark-events
</code>```

but I don't see any logs after execution

UPDATE 1 : After seeing this tutorial https://medium.com/@eyaldahari/how-to-run-spark-history-server-on-windows-52cde350de07 I have now access to the history server. However it is empty and the logs don't exist...

UPDATE 2 : I am very close now, if I launch spark-shell in the console, the log and history work however when i use this programm in my IDE it doesn't write any logs.

Here's my code

```<code>object SimpleScalaSpark {
  def main(args: Array[String]) {
    val logFile = "/Users/me/README.md" // Should be some file on your system
    val conf = new SparkConf().setAppName("Simple Application").setMaster("local[*]")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()

      val numAs = logData.filter(line => line.contains("a")).count()
      val numBs = logData.filter(line => line.contains("b")).count()
      println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))

  }
}
</code>```

答:
I finally solved the issue by adding the following lines in the code :

```<code>conf.set("spark.eventLog.enabled", "true")
conf.set("spark.eventLog.dir", "file:///C:/Users/me/spark/logs")
</code>```

It's all working perfectly now

Title: Spark history server

Body:
I'm currently working on Spark in Scala with the IntelliJ IDE. I have access to the web UI when my program is executed but i don't have access to the history server afterwards.

Any help would be very appreciated, i'm using windows by the way.
I also have created a log folder at C:/tmp/spark-events and edited the spark-defaults.conf this way :

# Example:
# spark.master                     spark://master:7077
# spark.eventLog.enabled           true
# spark.eventLog.dir               hdfs://namenode:8021/directory
# spark.serializer                 org.apache.spark.serializer.KryoSerializer
# spark.driver.memory              5g
# spark.executor.extraJavaOptions  -XX:+PrintGCDetails -Dkey=value -Dnumbers="one two three"
-Dspark.eventLog.enabled           true
-Dspark.history.fs.logDirectory    file:///C:/tmp/spark-events
-Dspark.eventLog.dir               file:///C:/tmp/spark-events

but I don't see any logs after execution

UPDATE 1 : After seeing this tutorial https://medium.com/@eyaldahari/how-to-run-spark-history-server-on-windows-52cde350de07 I have now access to the history server. However it is empty and the logs don't exist...

UPDATE 2 : I am very close now, if I launch spark-shell in the console, the log and history work however when i use this programm in my IDE it doesn't write any logs.

Here's my code

object SimpleScalaSpark {
  def main(args: Array[String]) {
    val logFile = "/Users/me/README.md" // Should be some file on your system
    val conf = new SparkConf().setAppName("Simple Application").setMaster("local[*]")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()

      val numAs = logData.filter(line => line.contains("a")).count()
      val numBs = logData.filter(line => line.contains("b")).count()
      println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))

  }
}

Body:
I finally solved the issue by adding the following lines in the code :

conf.set("spark.eventLog.enabled", "true")
conf.set("spark.eventLog.dir", "file:///C:/Users/me/spark/logs")

It's all working perfectly now


问:
Are line breaks in XML attribute values allowed?
I realise that it's not elegant or desired, but is it allowed (in well-formed XML) for an attribute value in an XML element to span multiple lines?

e.g.

```<code><some-xml-element value="this value goes over....
multiple lines!" />
</code>```

Yeah I realise there's better ways of writing that. I would personally write it like:

```<code><some-xml-element>
<value>this value goes over...
multiple lines!</value>
</some-xml-element>
</code>```

or:

```<code><some-xml-element value="this value goes over....
" />
</code>```

But we have our own XML parser and I'd like to know whether the first example is allowed in well-formed XML.

答:
http://www.w3.org/TR/REC-xml/#NT-AttValue

Seems to say everything except <, &, and your delimiter (' or ") are OK. So newline should be, too.

OwnerDisplayName: Ben Daniel

Body:
I realise that it's not elegant or desired, but is it allowed (in well-formed XML) for an attribute value in an XML element to span multiple lines?

e.g.

<some-xml-element value="this value goes over....
multiple lines!" />

Yeah I realise there's better ways of writing that. I would personally write it like:

<some-xml-element>
<value>this value goes over...
multiple lines!</value>
</some-xml-element>

or:

<some-xml-element value="this value goes over....
" />

But we have our own XML parser and I'd like to know whether the first example is allowed in well-formed XML.

OwnerDisplayName: derobert


问:
Unable save data using sqlserverce
I'm trying to save data using local database (SQLServerCe) with below code

```<code>Private Sub save_setup()
    Dim msg As String
    Try
        If setupupdate = True Then
            sql = "UPDATE connection_setup SET datasource_name = '" & t_hostname.Text & "'" & _
                  ", database_name = '" & t_dbname.Text & "', username = '" & t_uid.Text & "'" & _
                  ", password = '" & t_passwd.Text & "'"
            msg = "Updated"
        Else
            sql = "INSERT INTO connection_setup(datasource_name, database_name, username, password)" & _
                  " VALUES('" & t_hostname.Text & "', '" & t_dbname.Text & "','" & t_uid.Text & "'" & _
                  " , '" & t_passwd.Text & "') "
            msg = "Inserted"
        End If

        If conCe.State = ConnectionState.Closed Then
            conCe.Open()
        End If

        comCe = New SqlCeCommand(sql, conCe)
        comCe.ExecuteNonQuery()

        comCe.Dispose()
        conCe.Close()
        MsgBox(msg, MsgBoxStyle.Information, "Connection Setup")
    Catch
        MsgBox(Err.Description, MsgBoxStyle.Information, "Connection Setup")
    End Try
End Sub
</code>```

When i push button save, which is run code above, no issue on the process but the data is not saved.
I'm using Visual Studio 2010 with .NET Framework 4.
Any idea what the cause and its solution?

FYI:
If I ran insert/update data by SQL query, the data can be saved.

答: Your data is saved in a copy of the database in the bin/debug folder. Simplest fix is to specify a full path in the connection string during development.</p>

Title: Unable save data using sqlserverce

Body:
I'm trying to save data using local database (SQLServerCe) with below code

Private Sub save_setup()
    Dim msg As String
    Try
        If setupupdate = True Then
            sql = "UPDATE connection_setup SET datasource_name = '" & t_hostname.Text & "'" & _
                  ", database_name = '" & t_dbname.Text & "', username = '" & t_uid.Text & "'" & _
                  ", password = '" & t_passwd.Text & "'"
            msg = "Updated"
        Else
            sql = "INSERT INTO connection_setup(datasource_name, database_name, username, password)" & _
                  " VALUES('" & t_hostname.Text & "', '" & t_dbname.Text & "','" & t_uid.Text & "'" & _
                  " , '" & t_passwd.Text & "') "
            msg = "Inserted"
        End If

        If conCe.State = ConnectionState.Closed Then
            conCe.Open()
        End If

        comCe = New SqlCeCommand(sql, conCe)
        comCe.ExecuteNonQuery()

        comCe.Dispose()
        conCe.Close()
        MsgBox(msg, MsgBoxStyle.Information, "Connection Setup")
    Catch
        MsgBox(Err.Description, MsgBoxStyle.Information, "Connection Setup")
    End Try
End Sub

When i push button save, which is run code above, no issue on the process but the data is not saved.
I'm using Visual Studio 2010 with .NET Framework 4.
Any idea what the cause and its solution?

FYI:
If I ran insert/update data by SQL query, the data can be saved.


问:
Javascript functions are not implementing
My webpage should display a slideshow on page load but the script functions doesn't seem to be working. I have tried running simple scripts containing  prompt() and confirm() functions and they are working fine but custom functions doesn't seem to work. Same is the case with my "modal.js" script which should display a modal box on button click. Please help me out

```<code><!doctype html>
<html lang = "en">
<head>
    <title> Ice Cream </title>
    <link rel="stylesheet" href="main_ice.css" />
    <script type = "text/javascript" src = "slideShow.js"> </script>
    <script src = "modal.js"> </script>
    <meta charset = "utf-8" />
</head>
<body>
    <div id = "big_wrapper">
            <header  class= "top_header">
                <hgroup>
                    <h1> ICE Funky </h1>
                    <h3> ice cream production </h3>
                </hgroup>
            </header>

            <nav class= "nav_bar">
                <ul>
                    <label><li name = "home"> Home </li>
                    <li> About Us </li>
                    <li> Products </li>
                    <li> Services </li>
                    <li> Contacts </li>
                    </label>
                </ul>
            </nav>

        <div id = "slideshow">

            <span class = "image_slide"><img src = "4072.jpg" width = "500px" height = "300px"/> </span>
            <span class = "image_slide"><img src = "26551.jpg" width = "500px" height = "300px"/> </span>
            <span class = "image_slide"><img src = "30225.jpg" width = "500px" height = "300px"/> </span>
            <span class = "image_slide"><img src = "74223.jpg" width = "500px" height = "300px"/> </span>
            <span class = "image_slide"><img src = "74285.jpg" width = "500px" height = "300px"/> </span>

        </div>
        <button id = "modalButton"> Modal </button>
                <div id = "myModal">
                    <div id = "modal_title"> Main Title </div><br><br>
                    <div id = "modal_body"> Body </div>
                </div>

    </div>

</body>
</html>
</code>```

!-----------CSS File ----------------!

```<code>*{
    margin:0px;
    padding:0px;
}

header, footer, nav, hgroup, aside, article, section{
    display : block;
}

body{
    width:100%;
    display: -webkit-box;
    -webkit-box-pack: center;
}

#big_wrapper{
    max-width: 100%;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-box-flex: 1;
}

.top_header{
    position: absolute;
    margin: 20px 0px 0px 120px;
    border: 2px solid black;
    width: 180px;
    padding: 25px;

}

.nav_bar{
    margin-left: 350px;
    margin-top: 85px;
    text-align: center;
}
.nav_bar li{
    position: relative;
    list-style: none;
    display: inline-block;
    -webkit-box-flex: 1;
    margin: 20px;
    border: 2px solid white;
    padding: 5px;
    -webkit-transition: border-left 1s,  border-top 3s,  border-right 4s,
                         border-bottom 6s;
}

.nav_bar li:hover{
    border-left: 2px solid black;
    border-top: 2px solid black;
    border-right: 2px solid black;
    border-bottom: 2px solid black;
}

#slideshow{
    position: absolute;
    margin-top: 50px;
    margin-left: 400px;
    width: 500px;
}

.image_slide{
    position: absolute;
    /*display: none;*/

}

.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 150px;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: yellow;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next{
    /*left: 458px;*/
    right: 0px;
}

.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

#modalButton{
    background: rgba(0,256,0,0.5);
    padding: 5px;
    margin-left: 40px;
    margin-top: 40px;
    color: chocolate;
}

#myModal{
    position: fixed;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    background-color: rgba(0,0,0,0.4);
    display: none;
}

#modal_title{
    width: 95%;
    height: 5%;
    position: fixed;
    bottom: 15%;
    left: 30px;
    background: rgba(0,256,0,0.4);
}

#modal_body{
    width: 95%;
    height: 10%;
    position: fixed;
    top: 85%;
    left: 30px;
    background: rgba(256,256,256,0.4);

}
</code>```

!--------------JS File(slideShow.js)----------------!

```<code>    var slideIndex = 0;
    showSlides();

    function showSlides() {
        var i;
        var slides = document.getElementsByClassName("image_slide");
        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        slideIndex++;
        if (slideIndex> slides.length) {slideIndex = 1}
        slides[slideIndex-1].style.display = "block";
        setTimeout(showSlides, 2000); // Change image every 2 seconds
    }
</code>```

!---------------JS File(modal.js)------------------!

```<code>modalButton = getElementById("modalButton");
myModal = getElementById("myModal");
modalButton.onclick = function(){
    prompt("hi");
    myModal.style.display = "block";

}
</code>```

答:
First, as mentioned by ricky, you need to use document.getElementById("modalButton") instead of getElementById("modalButton").

Second, your scripts are evaluated before the markup is parsed. Either move the script tags out of your head to the end of the body tag, or alternatively wrap the contents of both files in event listeners for load:

```<code>window.addEventListener( 'load', function() {
    // your code here
} );
</code>```

For example modal.js should look like this:

```<code>window.addEventListener( 'load', function() {
    var modalButton = document.getElementById("modalButton");
    var myModal = document.getElementById("myModal");
    modalButton.onclick = function(){
        prompt("hi");
        myModal.style.display = "block";
    }
} );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My webpage should display a slideshow on page load but the script functions doesn't seem to be working. I have tried running simple scripts containing  prompt() and confirm() functions and they are working fine but custom functions doesn't seem to work. Same is the case with my "modal.js" script which should display a modal box on button click. Please help me out

<!doctype html>

    <title> Ice Cream </title>
    <link rel="stylesheet" href="main_ice.css" />

    <meta charset = "utf-8" />

                <hgroup>

 ICE Funky

 ice cream production

                </hgroup>

 Home

 About Us

 Products

 Services

 Contacts

        <button id = "modalButton"> Modal </button>

 Main Title

 Body

!-----------CSS File ----------------!

*{
    margin:0px;
    padding:0px;
}

header, footer, nav, hgroup, aside, article, section{
    display : block;
}

body{
    width:100%;
    display: -webkit-box;
    -webkit-box-pack: center;
}

#big_wrapper{
    max-width: 100%;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-box-flex: 1;
}

.top_header{
    position: absolute;
    margin: 20px 0px 0px 120px;
    border: 2px solid black;
    width: 180px;
    padding: 25px;

}

.nav_bar{
    margin-left: 350px;
    margin-top: 85px;
    text-align: center;
}
.nav_bar li{
    position: relative;
    list-style: none;
    display: inline-block;
    -webkit-box-flex: 1;
    margin: 20px;
    border: 2px solid white;
    padding: 5px;
    -webkit-transition: border-left 1s,  border-top 3s,  border-right 4s,
                         border-bottom 6s;
}

.nav_bar li:hover{
    border-left: 2px solid black;
    border-top: 2px solid black;
    border-right: 2px solid black;
    border-bottom: 2px solid black;
}

#slideshow{
    position: absolute;
    margin-top: 50px;
    margin-left: 400px;
    width: 500px;
}

.image_slide{
    position: absolute;
    /*display: none;*/

}

.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 150px;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: yellow;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next{
    /*left: 458px;*/
    right: 0px;
}

.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

#modalButton{
    background: rgba(0,256,0,0.5);
    padding: 5px;
    margin-left: 40px;
    margin-top: 40px;
    color: chocolate;
}

#myModal{
    position: fixed;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    background-color: rgba(0,0,0,0.4);
    display: none;
}

#modal_title{
    width: 95%;
    height: 5%;
    position: fixed;
    bottom: 15%;
    left: 30px;
    background: rgba(0,256,0,0.4);
}

#modal_body{
    width: 95%;
    height: 10%;
    position: fixed;
    top: 85%;
    left: 30px;
    background: rgba(256,256,256,0.4);

}

!--------------JS File(slideShow.js)----------------!

    var slideIndex = 0;
    showSlides();

    function showSlides() {
        var i;
        var slides = document.getElementsByClassName("image_slide");
        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";
        }
        slideIndex++;
        if (slideIndex> slides.length) {slideIndex = 1}
        slides[slideIndex-1].style.display = "block";
        setTimeout(showSlides, 2000); // Change image every 2 seconds
    }

!---------------JS File(modal.js)------------------!

modalButton = getElementById("modalButton");
myModal = getElementById("myModal");
modalButton.onclick = function(){
    prompt("hi");
    myModal.style.display = "block";

}

Body:
First, as mentioned by ricky, you need to use document.getElementById("modalButton") instead of getElementById("modalButton").

Second, your scripts are evaluated before the markup is parsed. Either move the script tags out of your head to the end of the body tag, or alternatively wrap the contents of both files in event listeners for load:

window.addEventListener( 'load', function() {
    // your code here
} );

For example modal.js should look like this:

window.addEventListener( 'load', function() {
    var modalButton = document.getElementById("modalButton");
    var myModal = document.getElementById("myModal");
    modalButton.onclick = function(){
        prompt("hi");
        myModal.style.display = "block";
    }
} );


问:
How to solve AOT and code stripping on Unity3D iOS builds
What should you do when the IL2CPP compiler starts striping your code from your external assemblies (dll) in you iOS builds. Causing your JSON De/serialization code to break.</p>

答:
1) Make sure you are using the Unity3d "tuned" version of JSON.Net. You can find the latest version here: Json.Net.Unity3D. This version does not make use of dynamic code - thus is "safe" for Ahead-of-time compilers.

2) Make sure you add the correct preservation lines into your Unity3D "link.xml" file:

```<code><linker>
  <assembly fullname="AssemblyName.Common">
     <type fullname="AssemblyName.Common.*" preserve="all" />
   </assembly>
</linker>
</code>```

The * will ensure that all namespaces as well as all classes are preserved - and will not be stripped.

That should do it.

Body:
1) Make sure you are using the Unity3d "tuned" version of JSON.Net. You can find the latest version here: Json.Net.Unity3D. This version does not make use of dynamic code - thus is "safe" for Ahead-of-time compilers.

2) Make sure you add the correct preservation lines into your Unity3D "link.xml" file:

<linker>
  <assembly fullname="AssemblyName.Common">
     <type fullname="AssemblyName.Common.*" preserve="all" />
   </assembly>
</linker>

The * will ensure that all namespaces as well as all classes are preserved - and will not be stripped.

That should do it.


问:
Set a CSS Property (color) to a VueJS Variable
I want to set the CSS property of a class using rgb(redComp, greenComp, blueComp) format. I want to get these components from Vuejs component code.

```<code>.progress {
    color: rgb(256,0,0);
    border-radius: 0px;
}
</code>```

I want the CSS to be something like :-

```<code>.progress {
    color: rgb(redComp, greenComp, blueComp);
    border-radius: 0px;
}
</code>```

Where redComp, greenComp and blueComp will be variables in the VueJS Component.
How can I implement this?

答:
The only way to do that is to set the element :style attribute usint a computed property.

In your template part :

```<code><div :style="dynamicStyle"></div>
</code>```

In your vue part :

```<code>/...
computed : {
    dynamicStyle() {
        return {
            // in the case of redComp, greenComp and blueComp are a vue prop or data
            color : `rgb(${this.redComp}, ${this.greenComp}, ${this.blueComp});`,
        };
    },
},
/...
</code>```

Body:
I want to set the CSS property of a class using rgb(redComp, greenComp, blueComp) format. I want to get these components from Vuejs component code.

.progress {
    color: rgb(256,0,0);
    border-radius: 0px;
}

I want the CSS to be something like :-

.progress {
    color: rgb(redComp, greenComp, blueComp);
    border-radius: 0px;
}

Where redComp, greenComp and blueComp will be variables in the VueJS Component.
How can I implement this?

Body:
The only way to do that is to set the element :style attribute usint a computed property.

In your template part :

<div :style="dynamicStyle"></div>

In your vue part :

/...
computed : {
    dynamicStyle() {
        return {
            // in the case of redComp, greenComp and blueComp are a vue prop or data
            color : `rgb(${this.redComp}, ${this.greenComp}, ${this.blueComp});`,
        };
    },
},
/...


问:
Unable to get jhipster gateway home page
I am unable to open My JHipster + Angular 2 (Gateway) Application home page with port 8080 (which is given at server port in application-dev.yml)
There is no errors in console.

index.html completely loading may be routing is not working fine.

The Same application is running fine on port 9000 (which is provided by yarn)

My problem is if I use 9000 port (Given by yarn) unable to communicate with other micro services applications.

答:
In development:

run JHipster registry

on gateway, run both mvnw and yarn start at same time and then open app in browser at port 9000, all calls to services will be proxied to the java applications transparently: gateway + microservices apps

run microservices apps with mvnw

EDIT:

I looked at your link though I hesitated because it was an archive of 135 MB !!!
Few remarks:

Next time, please publish source on github rather than packaging node_modules folders

agreeGatewayV1 uses mysql as dev database which made it difficult for me to run. h2 is much easier to work with especially for a gateway where you are not going to modify the data schema.

Application-2 does not include a .yo-rc.json file so I couldn't inspect its configuration. Same as your gateway, it uses mysql in dev so I could not test it

I found 5 java crash reports in your archive, your environment seems very unstable. Maybe you should upgrade your OS and jvm or maybe you don't have enough RAM

So sorry but I can't help you, it would take too much time.


问:
How can I compare images in a PictureBox and an ImageList?
I am using an ImageList and a PictureBox in my application. I am loading the image in the PictureBox dynamically from an image in the ImageList. I need to check whether the image in the PictureBox and a certain index of an image in the ImageList are equal. Can anyone guide me?

答:
Unfortunately, the Image class doesn't implement the == operator or the Equals method, which means it inherits the default implementation from the Object class that simply checks if the object references are the same. It turns out that this will fail, even if an image is assigned to the PictureBox directly out of your ImageList.

So, you'll need to implement your own logic to check if the images are the same. There are a couple of different approaches. You could either load each of the two images into a byte array and do a byte-by-byte comparison, or you could loop through the two images pixel-by-pixel and compare their colors. Of course, both of these methods are going to be anywhere from relatively to unreasonably slow. You could potentially optimize either by simply comparing the dimensions first (the Image object does provide a Size property that returns its dimensions) and returning False if they are not equal, but this probably won't work in your case, since all of the images in the ImageList will have the same dimensions.

If it were me, I'd save myself the trouble and just keep the index of the image in the ImageList that I assigned to the PictureBox somewhere in a class-level variable...

If you're still resolute despite my warnings, see the answers to this similar question.


问:
How do I use a variable in the WHERE condition of a MySQL query using a php variable?
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.

The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.

For testing I selected a user I knew had a rapsheet and used

```<code>$usersql = "SELECT *
 FROM character_data_store
 WHERE character_data_store.`key` = 'RapSheet'
 AND character_data_store.character_id = '216'";
</code>```

Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.

I've tried using:

```<code>$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove

$usersql = "SELECT *
  FROM character_data_store
  WHERE character_data_store.'key' = 'RapSheet'
  AND character_data_store.character_id = '$correctPlayer'";
</code>```

I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:

```<code>$usersql = "SELECT *
  FROM character_data_store
  WHERE character_data_store.'key' = 'RapSheet'
  AND character_data_store.character_id = {$_SESSION['selpid']}";
</code>```

Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?

It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".

How do I use a variable in the WHERE condition of a MySQL query using a php variable?

答:
There are multiple ways to do this. A naive way to do this would be-

```<code>$usersql = "SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ".$correctPlayer;
</code>```

But to avoid sql injections I would recommend you use bindparam function to bind paramaters in a statement.

```<code>$sql="SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ?";
if($stmt = $dbh->prepare($sql)){

    $stmt->bindParam(1, $correctPlayer, PDO::PARAM_STR);
    $ql = $stmt->execute() or die("ERROR: " . implode(":", $dbh->errorInfo()));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $result['data'] = $row;
</code>```

Body:
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.

The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.

For testing I selected a user I knew had a rapsheet and used

$usersql = "SELECT *
 FROM character_data_store
 WHERE character_data_store.`key` = 'RapSheet'
 AND character_data_store.character_id = '216'";

Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.

I've tried using:

$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove

$usersql = "SELECT *
  FROM character_data_store
  WHERE character_data_store.'key' = 'RapSheet'
  AND character_data_store.character_id = '$correctPlayer'";

I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:

$usersql = "SELECT *
  FROM character_data_store
  WHERE character_data_store.'key' = 'RapSheet'
  AND character_data_store.character_id = {$_SESSION['selpid']}";

Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?

It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".

How do I use a variable in the WHERE condition of a MySQL query using a php variable?

Body:
There are multiple ways to do this. A naive way to do this would be-

$usersql = "SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ".$correctPlayer;

But to avoid sql injections I would recommend you use bindparam function to bind paramaters in a statement.

$sql="SELECT * FROM character_data_store WHERE character_data_store.'key' = 'RapSheet' AND character_data_store.character_id = ?";
if($stmt = $dbh->prepare($sql)){

    $stmt->bindParam(1, $correctPlayer, PDO::PARAM_STR);
    $ql = $stmt->execute() or die("ERROR: " . implode(":", $dbh->errorInfo()));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $result['data'] = $row;


问:
scrollBy doesn't work properly in nested recyclerview
I have a vertically scrolling RecyclerView with horizontally scrolling inner RecyclerViews just like this.

With this implementation, users can scroll each horizontal recyclerview synchronously. However, when a user scroll vertically to the parent recyclerView, a new horizontal recyclerview which has just attached on window doesn't display on same scroll x position. This is normal. Because it has just created.

So, I had tried to scroll to the scrolled position before it was displayed. Just like this:

Note: this is in adapter of the parent recyclerview whose orientation is vertical.

```<code> @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        CellColumnViewHolder viewHolder = (CellColumnViewHolder) holder;
        if (m_nXPosition != 0) {
             // this doesn't work properly
             viewHolder.m_jRecyclerView.scrollBy(m_nXPosition, 0);
        }
    }
</code>```

As you can see, scrollBy doesn't effect for row 10, row 11, row 12 and row 13 After that, I debugged the code to be able find out find out what's happening. When I set scroll position using scrollBy,  childCount() return zero for row 10, row 11, row 12 and row 13 So they don't scroll. But why ? and Why others work ?

How can I fix this ?

Is onViewAttachedToWindow right place to scroll new attached recyclervViews ?

Note: I have also test scrollToPosition(), it doesn't get any problem like this. But I can't use it at my case. Because users can scroll to the any x position which may not the exact position. So I need to set scroll position using x value instead of the position.

Edit: You can check The source code

答:
I found a solution that is use scrollToPositionWithOffset method instead using scrollBy. Even if both of two scroll another position, they have really different work process in back side.

For example: if you try to use scrollBy to scroll any pixel position and your recyclerView had not been set any adapter which means there is no any data to display and so it has no any items yet, then scrollBy doesn't work. RecyclerView uses its layoutManager's scrollBy method. So in my case, I am using LinearLayoutManager to the horizontal recyclerViews.

Lets see what it's doing :

```<code>int scrollBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (getChildCount() == 0 || dy == 0) {
            return 0;
        }
        mLayoutState.mRecycle = true;
        ensureLayoutState();
        final int layoutDirection = dy > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START;
        final int absDy = Math.abs(dy);
        updateLayoutState(layoutDirection, absDy, true, state);
        final int consumed = mLayoutState.mScrollingOffset
                + fill(recycler, mLayoutState, state, false);
        if (consumed < 0) {
            if (DEBUG) {
                Log.d(TAG, "Don't have any more elements to scroll");
            }
            return 0;
        }
        final int scrolled = absDy > consumed ? layoutDirection * consumed : dy;
        mOrientationHelper.offsetChildren(-scrolled);
        if (DEBUG) {
            Log.d(TAG, "scroll req: " + dy + " scrolled: " + scrolled);
        }
        mLayoutState.mLastScrollDelta = scrolled;
        return scrolled;
    }
</code>```

As you can see scrollBy ignores the scroll intentions if there is no any child at that time.

```<code>  if (getChildCount() == 0 || dy == 0) {
     return 0;
  }
</code>```

On the other hand scrollToPosition can work perfectly even if there is no any set data yet.

According to the Pro RecyclerView slide, the below sample works perfectly. However you can not do that with scrollBy.

```<code>void onCreate(SavedInstanceState state) {
    ....
    mRecyclerView.scrollToPosition(selectedPosition);
    mRecyclerView.setAdapter(myAdapter);
}
</code>```

As a result, I have changed little thing to use scrollToPositionWithOffset().

Before this implementation I was calculating the exact scroll x position as a pixel.

After that, when the scroll came idle state, calculating the first complete visible position to the first parameter of the scrollToPositionWithOffset().

For second parameter which is the offset, I am getting the value using view.getLeft() function which helps to get left position of this view relative to its parent.

And it works perfectly!!

Body:
I have a vertically scrolling RecyclerView with horizontally scrolling inner RecyclerViews just like this.

With this implementation, users can scroll each horizontal recyclerview synchronously. However, when a user scroll vertically to the parent recyclerView, a new horizontal recyclerview which has just attached on window doesn't display on same scroll x position. This is normal. Because it has just created.

So, I had tried to scroll to the scrolled position before it was displayed. Just like this:

Note: this is in adapter of the parent recyclerview whose orientation is vertical.

 @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        CellColumnViewHolder viewHolder = (CellColumnViewHolder) holder;
        if (m_nXPosition != 0) {
             // this doesn't work properly
             viewHolder.m_jRecyclerView.scrollBy(m_nXPosition, 0);
        }
    }

As you can see, scrollBy doesn't effect for row 10, row 11, row 12 and row 13 After that, I debugged the code to be able find out find out what's happening. When I set scroll position using scrollBy,  childCount() return zero for row 10, row 11, row 12 and row 13 So they don't scroll. But why ? and Why others work ?

How can I fix this ?

Is onViewAttachedToWindow right place to scroll new attached recyclervViews ?

Note: I have also test scrollToPosition(), it doesn't get any problem like this. But I can't use it at my case. Because users can scroll to the any x position which may not the exact position. So I need to set scroll position using x value instead of the position.

Edit: You can check The source code

Body:
I found a solution that is use scrollToPositionWithOffset method instead using scrollBy. Even if both of two scroll another position, they have really different work process in back side.

For example: if you try to use scrollBy to scroll any pixel position and your recyclerView had not been set any adapter which means there is no any data to display and so it has no any items yet, then scrollBy doesn't work. RecyclerView uses its layoutManager's scrollBy method. So in my case, I am using LinearLayoutManager to the horizontal recyclerViews.

Lets see what it's doing :

int scrollBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        if (getChildCount() == 0 || dy == 0) {
            return 0;
        }
        mLayoutState.mRecycle = true;
        ensureLayoutState();
        final int layoutDirection = dy > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START;
        final int absDy = Math.abs(dy);
        updateLayoutState(layoutDirection, absDy, true, state);
        final int consumed = mLayoutState.mScrollingOffset
                + fill(recycler, mLayoutState, state, false);
        if (consumed < 0) {
            if (DEBUG) {
                Log.d(TAG, "Don't have any more elements to scroll");
            }
            return 0;
        }
        final int scrolled = absDy > consumed ? layoutDirection * consumed : dy;
        mOrientationHelper.offsetChildren(-scrolled);
        if (DEBUG) {
            Log.d(TAG, "scroll req: " + dy + " scrolled: " + scrolled);
        }
        mLayoutState.mLastScrollDelta = scrolled;
        return scrolled;
    }

As you can see scrollBy ignores the scroll intentions if there is no any child at that time.

  if (getChildCount() == 0 || dy == 0) {
     return 0;
  }

On the other hand scrollToPosition can work perfectly even if there is no any set data yet.

According to the Pro RecyclerView slide, the below sample works perfectly. However you can not do that with scrollBy.

void onCreate(SavedInstanceState state) {
    ....
    mRecyclerView.scrollToPosition(selectedPosition);
    mRecyclerView.setAdapter(myAdapter);
}

As a result, I have changed little thing to use scrollToPositionWithOffset().

Before this implementation I was calculating the exact scroll x position as a pixel.

After that, when the scroll came idle state, calculating the first complete visible position to the first parameter of the scrollToPositionWithOffset().

For second parameter which is the offset, I am getting the value using view.getLeft() function which helps to get left position of this view relative to its parent.

And it works perfectly!!


问:
Android studio execute AsyncClass before onMapReady
I have this code where i have to call data from database yung asynctask the coordinates for my googlemap. but the onMapReady is executing before my Asynctask so the location is always null. I call the asynctask on my oncreate here is my code.

AsyncTask on onCreate

```<code>        HashMap<String, String> postData = new HashMap<>();
        postData.put("rqstID", rqstID);
        AsyncClass taskDetails = new AsyncClass(AcceptActivity.this, postData, "Getting details", new AsyncResponse() {
            @Override
            public void processFinish(String s) {
                Log.d("AcceptActivity", s);
                JSONObject parentObject = null;
                try {
                    parentObject = new JSONObject(s);
                    JSONArray parentArray = parentObject.getJSONArray("result");
                    JSONObject finalObject = parentArray.getJSONObject(0);
                    lat1 = finalObject.getString("rqstLat");
                    lng1 = finalObject.getString("rqstLng");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        taskDetails.execute("http://10.0.2.2/wingman/requestDetails.php");
</code>```

onMapReady

```<code> @Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    LatLng location = new LatLng(Double.valueOf(lat1), Double.valueOf(lng1));
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(location, 15);
    mGoogleMap.moveCamera(update);
    MarkerOptions options = new MarkerOptions()
            .position(location)
            .snippet("I'm around here!!!");
    CircleOptions circle = new CircleOptions()
            .center(location)
            .radius(2000)
            .fillColor(0x55add8e6)
            .strokeColor(Color.BLUE)
            .strokeWidth(2);
    mGoogleMap.addCircle(circle);
    mGoogleMap.addMarker(options);
}
</code>```

答:
There is no way to guarantee that your async task could complete before the Google map's onMapReady() were called.  Instead, I propose that you make the REST call for map information from the onMapReady() method itself.  This way, you can be sure that when the callback is fired, there is an actual live Google map handle to which you could assign a marker etc.

Here is a skeleton of what the code might look like:

```<code>@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    new YourAsyncTask(this).execute();
}
</code>```

Then in your async task you can parse the data and assign the marker to your Google Map.

Body:
I have this code where i have to call data from database yung asynctask the coordinates for my googlemap. but the onMapReady is executing before my Asynctask so the location is always null. I call the asynctask on my oncreate here is my code.

AsyncTask on onCreate

        HashMap<String, String> postData = new HashMap<>();
        postData.put("rqstID", rqstID);
        AsyncClass taskDetails = new AsyncClass(AcceptActivity.this, postData, "Getting details", new AsyncResponse() {
            @Override
            public void processFinish(String s) {
                Log.d("AcceptActivity", s);
                JSONObject parentObject = null;
                try {
                    parentObject = new JSONObject(s);
                    JSONArray parentArray = parentObject.getJSONArray("result");
                    JSONObject finalObject = parentArray.getJSONObject(0);
                    lat1 = finalObject.getString("rqstLat");
                    lng1 = finalObject.getString("rqstLng");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        taskDetails.execute("http://10.0.2.2/wingman/requestDetails.php");

onMapReady

 @Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    LatLng location = new LatLng(Double.valueOf(lat1), Double.valueOf(lng1));
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(location, 15);
    mGoogleMap.moveCamera(update);
    MarkerOptions options = new MarkerOptions()
            .position(location)
            .snippet("I'm around here!!!");
    CircleOptions circle = new CircleOptions()
            .center(location)
            .radius(2000)
            .fillColor(0x55add8e6)
            .strokeColor(Color.BLUE)
            .strokeWidth(2);
    mGoogleMap.addCircle(circle);
    mGoogleMap.addMarker(options);
}

Body:
There is no way to guarantee that your async task could complete before the Google map's onMapReady() were called.  Instead, I propose that you make the REST call for map information from the onMapReady() method itself.  This way, you can be sure that when the callback is fired, there is an actual live Google map handle to which you could assign a marker etc.

Here is a skeleton of what the code might look like:

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    new YourAsyncTask(this).execute();
}

Then in your async task you can parse the data and assign the marker to your Google Map.


问:
How do I calculate the duration for multiple continuous occurrence of an event?
This is a subset of my data

```<code>    # | Event | Time
    1    A       22:00:00
    2    B       22:00:10
    3    B       22:00:20
    4    B       22:00:30
    5    C       22:00:40
    6    B       22:00:10
    7    B       22:00:20
    8    B       22:00:30
    9    A       22:00:40
</code>```

I want to calculate the duration of a continuous occurrence of a same event – so, say I want the duration of event B, the output should be

```<code>    # | Event | Time      | Duration
    1    A       22:00:00   NA
    2    B       22:00:10   20 Secs
    3    B       22:00:20   NA
    4    B       22:00:30   NA
    5    C       22:00:40   NA
    6    B       22:00:10   20 Secs
    7    B       22:00:20   NA
    8    B       22:00:30   NA
    9    A       22:00:40   NA
</code>```

I've tried (variations of) solutions from:
Using conditional statements with difftime in R  and
Calulcate running difference of time using difftime on one column of timestamps

But I can't seem to get what I'm trying to achieve. Hope I can get some help! Thanks!

答:
We can use data.table.  Convert the 'data.frame' to 'data.table' (setDT(df1)), create a grouping variable based on the run-length-id of 'Event' i.e. based on same adjacent elements ('grp'), convert the 'Time' to POSIXct , grouped by 'grp', specifying the 'i' with the logical condition (Event == "B"), find the difference of the last and first 'Time1' using difftime, then we assign the values of the 'Duration' that is not the first observation for each 'grp' to NA.

```<code>library(data.table)
setDT(df1)[, grp := rleid(Event)][, Time1 := as.POSIXct(Time, format =
       "%H:%M:%S")][Event == "B",
     Duration := as.numeric(difftime(Time1[.N], Time1[1], unit = "secs")), grp]
df1[df1[, .I[seq_len(.N) != 1], grp]$V1, Duration := NA][, c("Time1", "grp") := NULL][]
#   No Event     Time Duration
#1:  1     A 22:00:00       NA
#2:  2     B 22:00:10       20
#3:  3     B 22:00:20       NA
#4:  4     B 22:00:30       NA
#5:  5     C 22:00:40       NA
#6:  6     B 22:00:10       20
#7:  7     B 22:00:20       NA
#8:  8     B 22:00:30       NA
#9:  9     A 22:00:40       NA
</code>```

data

```<code>df1 <- structure(list(No = 1:9, Event = c("A", "B", "B", "B", "C", "B",
 "B", "B", "A"), Time = c("22:00:00", "22:00:10", "22:00:20",
 "22:00:30", "22:00:40", "22:00:10", "22:00:20", "22:00:30", "22:00:40"
 )), .Names = c("No", "Event", "Time"), class = "data.frame", row.names = c(NA,
-9L))
</code>```

Body:
This is a subset of my data

    # | Event | Time
    1    A       22:00:00
    2    B       22:00:10
    3    B       22:00:20
    4    B       22:00:30
    5    C       22:00:40
    6    B       22:00:10
    7    B       22:00:20
    8    B       22:00:30
    9    A       22:00:40

I want to calculate the duration of a continuous occurrence of a same event – so, say I want the duration of event B, the output should be

    # | Event | Time      | Duration
    1    A       22:00:00   NA
    2    B       22:00:10   20 Secs
    3    B       22:00:20   NA
    4    B       22:00:30   NA
    5    C       22:00:40   NA
    6    B       22:00:10   20 Secs
    7    B       22:00:20   NA
    8    B       22:00:30   NA
    9    A       22:00:40   NA

I've tried (variations of) solutions from:
Using conditional statements with difftime in R  and
Calulcate running difference of time using difftime on one column of timestamps

But I can't seem to get what I'm trying to achieve. Hope I can get some help! Thanks!

Body:
We can use data.table.  Convert the 'data.frame' to 'data.table' (setDT(df1)), create a grouping variable based on the run-length-id of 'Event' i.e. based on same adjacent elements ('grp'), convert the 'Time' to POSIXct , grouped by 'grp', specifying the 'i' with the logical condition (Event == "B"), find the difference of the last and first 'Time1' using difftime, then we assign the values of the 'Duration' that is not the first observation for each 'grp' to NA.

library(data.table)
setDT(df1)[, grp := rleid(Event)][, Time1 := as.POSIXct(Time, format =
       "%H:%M:%S")][Event == "B",
     Duration := as.numeric(difftime(Time1[.N], Time1[1], unit = "secs")), grp]
df1[df1[, .I[seq_len(.N) != 1], grp]$V1, Duration := NA][, c("Time1", "grp") := NULL][]
#   No Event     Time Duration
#1:  1     A 22:00:00       NA
#2:  2     B 22:00:10       20
#3:  3     B 22:00:20       NA
#4:  4     B 22:00:30       NA
#5:  5     C 22:00:40       NA
#6:  6     B 22:00:10       20
#7:  7     B 22:00:20       NA
#8:  8     B 22:00:30       NA
#9:  9     A 22:00:40       NA

data

df1 <- structure(list(No = 1:9, Event = c("A", "B", "B", "B", "C", "B",
 "B", "B", "A"), Time = c("22:00:00", "22:00:10", "22:00:20",
 "22:00:30", "22:00:40", "22:00:10", "22:00:20", "22:00:30", "22:00:40"
 )), .Names = c("No", "Event", "Time"), class = "data.frame", row.names = c(NA,
-9L))


问:
How to load binary files with Logstash
How to load binary files  (pdf, xls, other...) with Logstash and not changing their content.

Currently I try to load with

```<code>input {
file {
    path => "C:/path/files/*"
    type => "gesamt"
    start_position => "beginning"
    sincedb_path => "NUL"
}
}
filter {
   multiline {
      pattern => "/.*./gesamt"
      negate => true
      what => "previous"
  }

base64 {
    field => "blob"
}
}
output {
  elasticsearch {
    hosts => ["http://localhost:9200"]
    index => "index-name"
    pipeline=>"test-pipeline"
 }
}
</code>```

It seems that multiline filter damages the binary content.

答:
You cannot just dump binary files into Elasticsearch, this will not make them searchable, and a filesystem might be better suited to hold them.

If you want to make them searchable, you might want to take a look at the ingest attachment processor

Title: How to load binary files with Logstash

Body:
How to load binary files  (pdf, xls, other...) with Logstash and not changing their content.

Currently I try to load with

input {
file {
    path => "C:/path/files/*"
    type => "gesamt"
    start_position => "beginning"
    sincedb_path => "NUL"
}
}
filter {
   multiline {
      pattern => "/.*./gesamt"
      negate => true
      what => "previous"
  }

base64 {
    field => "blob"
}
}
output {
  elasticsearch {
    hosts => ["http://localhost:9200"]
    index => "index-name"
    pipeline=>"test-pipeline"
 }
}

It seems that multiline filter damages the binary content.


问:
In Codeigniter extends one controller into another controller
I am using codeigniter(3.1.5) and Ihave two controllers in my application/controllers/ folder. with name controller A and Controller B. I want to extends Controller A in Controller B so that I can use methods of Controller A. But it generates class not found error.

Here is my sample code:

A_Controller.php:

```<code>defined('BASEPATH') OR exit('No direct script access allowed');
class A_Controller extends CI_Controller {
  public function index()
  {
  }

  public function display(){
     echo 'base controller function called.';
  }
 }
</code>```

B_Controller.php:

```<code> defined('BASEPATH') OR exit('No direct script access allowed');
 class B_Controller extends A_Controller {

 }
</code>```

I want to execute display() method of controller A in controller B.
If i put controller A in application/core/ folder and in application/config/config.php file make

$config['subclass_prefix'] = 'A_';

then I can able to access methods of controller A.

Please suggest.
Thanks in advance.

答:
Extending a controller in another controller is not really good. Building with MVC and especially with CI, you have other options to achieve this.

Use a class MY_Controller inside application/core that extends the CI_Controller. Later, all (or some) of your controllers should extend the MY_Controller. In MY_Controller you can have many functions and you can call which function you want in your controller.

Use a library. Write your own library in application/libraries and load it in your controller wherever you want. A library is a class with functionality for your project.

Use a helper. Write your own helper in application/helpers and load it in your controller. A helper should have a general purpose for your application.

In that way, your code will be more flexible and reusable for the future. Messing with 2 Controllers seems bad to me. Remember that with the default Routing system of CI you can be confused.

Body:
I am using codeigniter(3.1.5) and Ihave two controllers in my application/controllers/ folder. with name controller A and Controller B. I want to extends Controller A in Controller B so that I can use methods of Controller A. But it generates class not found error.

Here is my sample code:

A_Controller.php:

defined('BASEPATH') OR exit('No direct script access allowed');
class A_Controller extends CI_Controller {
  public function index()
  {
  }

  public function display(){
     echo 'base controller function called.';
  }
 }

B_Controller.php:

 defined('BASEPATH') OR exit('No direct script access allowed');
 class B_Controller extends A_Controller {

 }

I want to execute display() method of controller A in controller B.
If i put controller A in application/core/ folder and in application/config/config.php file make

$config['subclass_prefix'] = 'A_';

then I can able to access methods of controller A.

Please suggest.
Thanks in advance.


问:
running parallel npm scripts on windows
I have an npm parallel script in my package.json that works on a mac but not on windows:

```<code>"myScript": "nodemon ./server.js & cross-env NODE_ENV=development webpack-dev-server"
</code>```

When it is separated into two scripts to run separately, it works fine on both mac and windows:

```<code>"myScript1": "cross-env NODE_ENV=development webpack-dev-server",
"myScript2": "nodemon ./server.js",
</code>```

I would like to keep the parallel script so that I don't have to run both separately.  How do I make this work on windows?

答:
I have a workaround for this, using module concurrently. So you script section would look something like this:</p>

```<code>scripts: {
  "myScript": "concurrently \"npm run myScript1\" \"npm run myScript2\"",
  "myScript1": "cross-env NODE_ENV=development webpack-dev-server",
  "myScript2": "nodemon ./server.js",
}
</code>```

Title: running parallel npm scripts on windows

Body:
I have an npm parallel script in my package.json that works on a mac but not on windows:

"myScript": "nodemon ./server.js & cross-env NODE_ENV=development webpack-dev-server"

When it is separated into two scripts to run separately, it works fine on both mac and windows:

"myScript1": "cross-env NODE_ENV=development webpack-dev-server",
"myScript2": "nodemon ./server.js",

I would like to keep the parallel script so that I don't have to run both separately.  How do I make this work on windows?

Body:
I have a workaround for this, using module concurrently. So you script section would look something like this:

scripts: {
  "myScript": "concurrently \"npm run myScript1\" \"npm run myScript2\"",
  "myScript1": "cross-env NODE_ENV=development webpack-dev-server",
  "myScript2": "nodemon ./server.js",
}


问:
How to handle strings with a block ( awk )
Each block starts with 'COL ID' in an input data.
I need to print 'COL ID' and JOB_subid if there is. As you can see in input data, 'COLID=2' has a job_subid(1 / left of table name) but 'COLID=3' or 'COLID=4' doesn't have.
For COLID=3/4, I want to print 'no_data' as it doesn't have any job_subid.
How can I handle this data?

AWK

```<code>/COL ID/        {JOBID=$4;}

/^[0-9]/ {
    JOB_SUBID=$1;
    printf "%s#%s",JOBID,JOB_SUBID;
    printf "\n";
}

END {

if (JOB_SUBID="") then
  JOB_SUBID="no_data";
  printf "%s#%s",JOBID,JOB_SUBID;
  printf "\n";
end if;

}
</code>```

input data

```<code>COL ID    : 2
PID       : 26788

ID     TABLE
------ ------------------------------
1      "SCOTT"."PRINCE01"

COL ID    : 3
PID       : 26788

COL ID    : 4
PID       : 26788
</code>```

Incorrect result

```<code>2#1
4#no_data
</code>```

Required result

```<code>2#1
3#no_data
4#no_data
</code>```

答:
awk solution:

```<code>awk '/COL ID/{
        if(colid) { sid=(subid)? subid:"no_data"; print colid"#"sid; subid="" } colid=$4
     }
     /^[0-9]+/{ subid=$1 }END{ if(colid) print colid"#"sid }' inputfile
</code>```

The output:

```<code>2#1
3#no_data
4#no_data
</code>```

Body:
Each block starts with 'COL ID' in an input data.
I need to print 'COL ID' and JOB_subid if there is. As you can see in input data, 'COLID=2' has a job_subid(1 / left of table name) but 'COLID=3' or 'COLID=4' doesn't have.
For COLID=3/4, I want to print 'no_data' as it doesn't have any job_subid.
How can I handle this data?

AWK

/COL ID/        {JOBID=$4;}

/^[0-9]/ {
    JOB_SUBID=$1;
    printf "%s#%s",JOBID,JOB_SUBID;
    printf "\n";
}

END {

if (JOB_SUBID="") then
  JOB_SUBID="no_data";
  printf "%s#%s",JOBID,JOB_SUBID;
  printf "\n";
end if;

}

input data

COL ID    : 2
PID       : 26788

ID     TABLE
------ ------------------------------
1      "SCOTT"."PRINCE01"

COL ID    : 3
PID       : 26788

COL ID    : 4
PID       : 26788

Incorrect result

2#1
4#no_data

Required result

2#1
3#no_data
4#no_data

Body:
awk solution:

awk '/COL ID/{
        if(colid) { sid=(subid)? subid:"no_data"; print colid"#"sid; subid="" } colid=$4
     }
     /^[0-9]+/{ subid=$1 }END{ if(colid) print colid"#"sid }' inputfile

The output:

2#1
3#no_data
4#no_data


问:
Possible to index into contents of array subject to transpose function?
In fortran, is it possible to index into elements of an array subject to an intrinsic? I am referring in particular to the transpose function. In the following code, I am generating and initializing an array named A and trying to index into a value inside the transposed array

```<code>program test
    integer, dimension(5,3) :: A
    integer :: i,j

    A = reshape((/1,2,3,4,5,6,7,8,9,10,11,12,13,14,15/), shape(A))

    print *, transpose(A)(1,1)
end program test
</code>```

however I am getting a syntax error as follows:

**D:\TEMP\FortranTest>gfortran -o Test Transposecommand.f90 Transposecommand.f90:11:22:

print *, transpose(A)(1,1)
                        1 Error: Syntax error in PRINT statement at (1)**

It there a way to accomplish this without having to declare a separate variable then assign the transposed array to it? I would like to avoid declaring new variables if possible...

答:
No, Fortran doesn't support that kind of indexing into function results.  You'll have to devise an elegant solution of your own (aka a kludge).  My own would take account of

```<code>transpose(a)(i,j) == a(j,i)
</code>```

Body:
In fortran, is it possible to index into elements of an array subject to an intrinsic? I am referring in particular to the transpose function. In the following code, I am generating and initializing an array named A and trying to index into a value inside the transposed array

program test
    integer, dimension(5,3) :: A
    integer :: i,j

    A = reshape((/1,2,3,4,5,6,7,8,9,10,11,12,13,14,15/), shape(A))

    print *, transpose(A)(1,1)
end program test

however I am getting a syntax error as follows:

**D:\TEMP\FortranTest>gfortran -o Test Transposecommand.f90 Transposecommand.f90:11:22:

print *, transpose(A)(1,1)
                        1 Error: Syntax error in PRINT statement at (1)**

It there a way to accomplish this without having to declare a separate variable then assign the transposed array to it? I would like to avoid declaring new variables if possible...

Body:
No, Fortran doesn't support that kind of indexing into function results.  You'll have to devise an elegant solution of your own (aka a kludge).  My own would take account of

transpose(a)(i,j) == a(j,i)


问:
Adobe Reader process fails when starting second instance
In our C# WinForms application, we generate PDF files and launch Adobe Reader (or whatever the default system .pdf handler is) via the Process class. Since our PDF files can be large (approx 200K), we handle the Exited event to then clean up the temp file afterwards.

The system works as required when a file is opened and then closed again. However, when a second file is opened (before closing Adobe Reader) the second process immediately exits (since Reader is now using it's MDI powers) and in our Exited handler our File.Delete call should fail because it's locked by the now joined Adobe process. However, in Reader we instead get:

There was an error opening this document. This file cannot be found.

The unusual thing is that if I put a debugger breakpoint before the file deletion and allow it to attempt (and fail) the deletion, then the system behaves as expected!

I'm positive that the file exists and fairly positive that all handles/file streams to the file are closed before starting the process.

We are launching with the following code:

```<code>// Open the file for viewing/printing (if the default program supports it)
var pdfProcess = new Process();
pdfProcess.StartInfo.FileName = tempFileName;
if (pdfProcess.StartInfo.Verbs.Contains("open", StringComparer.InvariantCultureIgnoreCase))
{
    var verb = pdfProcess.StartInfo.Verbs.First(v => v.Equals("open", StringComparison.InvariantCultureIgnoreCase));
    pdfProcess.StartInfo.Verb = verb;
}
pdfProcess.StartInfo.Arguments = "/N"; // Specifies a new window will be used! (But not definitely...)
pdfProcess.SynchronizingObject = this;
pdfProcess.EnableRaisingEvents = true;
pdfProcess.Exited += new EventHandler(pdfProcess_Exited);

_pdfProcessDictionary.Add(pdfProcess, tempFileName);

pdfProcess.Start();
</code>```

Note: We are using the _pdfProcessDictionary to store references to the Process objects so that they stay in scope so that Exited event can successfully be raised.

Our cleanup/exited event is:

```<code>void pdfProcess_Exited(object sender, EventArgs e)
{
    Debug.Assert(!InvokeRequired);
    var p = sender as Process;
    try
    {
        if (_pdfProcessDictionary.ContainsKey(p))
        {
            var tempFileName = _pdfProcessDictionary[p];
            if (File.Exists(tempFileName)) // How else can I check if I can delete it!!??
            {
                // NOTE: Will fail if the Adobe Reader application instance has been re-used!
                File.Delete(tempFileName);
                _pdfProcessDictionary.Remove(p);
            }

            CleanOtherFiles(); // This function will clean up files for any other previously exited processes in our dictionary
        }
    }
    catch (IOException ex)
    {
        // Just swallow it up, we will deal with trying to delete it at another point
    }
}
</code>```

Possible solutions:

Detect that the file is still open in another process

Detect that the second process hasn't really been fully exited and that the file is opened in the first process instead

答:
I just dealt with this a couple of days ago.

When there is no instance open already, the document opens in a new instance directly.

When there is an instance already open, I believe that instance spawns a new instance which you don't actually get a handle to. What happens is control returns to your function immediately, which then goes and deletes the file before the new instance has had a chance to read the file -- hence it appears to not be there.

I "solved" this by not deleting the files immediately, but keeping track of the paths in a list, and then nuking all of them when the program exits (wrap each delete in a try/catch with an empty catch block in case the file has disappeared in the meantime).

Body:
In our C# WinForms application, we generate PDF files and launch Adobe Reader (or whatever the default system .pdf handler is) via the Process class. Since our PDF files can be large (approx 200K), we handle the Exited event to then clean up the temp file afterwards.

The system works as required when a file is opened and then closed again. However, when a second file is opened (before closing Adobe Reader) the second process immediately exits (since Reader is now using it's MDI powers) and in our Exited handler our File.Delete call should fail because it's locked by the now joined Adobe process. However, in Reader we instead get:

There was an error opening this document. This file cannot be found.

The unusual thing is that if I put a debugger breakpoint before the file deletion and allow it to attempt (and fail) the deletion, then the system behaves as expected!

I'm positive that the file exists and fairly positive that all handles/file streams to the file are closed before starting the process.

We are launching with the following code:

// Open the file for viewing/printing (if the default program supports it)
var pdfProcess = new Process();
pdfProcess.StartInfo.FileName = tempFileName;
if (pdfProcess.StartInfo.Verbs.Contains("open", StringComparer.InvariantCultureIgnoreCase))
{
    var verb = pdfProcess.StartInfo.Verbs.First(v => v.Equals("open", StringComparison.InvariantCultureIgnoreCase));
    pdfProcess.StartInfo.Verb = verb;
}
pdfProcess.StartInfo.Arguments = "/N"; // Specifies a new window will be used! (But not definitely...)
pdfProcess.SynchronizingObject = this;
pdfProcess.EnableRaisingEvents = true;
pdfProcess.Exited += new EventHandler(pdfProcess_Exited);

_pdfProcessDictionary.Add(pdfProcess, tempFileName);

pdfProcess.Start();

Note: We are using the _pdfProcessDictionary to store references to the Process objects so that they stay in scope so that Exited event can successfully be raised.

Our cleanup/exited event is:

void pdfProcess_Exited(object sender, EventArgs e)
{
    Debug.Assert(!InvokeRequired);
    var p = sender as Process;
    try
    {
        if (_pdfProcessDictionary.ContainsKey(p))
        {
            var tempFileName = _pdfProcessDictionary[p];
            if (File.Exists(tempFileName)) // How else can I check if I can delete it!!??
            {
                // NOTE: Will fail if the Adobe Reader application instance has been re-used!
                File.Delete(tempFileName);
                _pdfProcessDictionary.Remove(p);
            }

            CleanOtherFiles(); // This function will clean up files for any other previously exited processes in our dictionary
        }
    }
    catch (IOException ex)
    {
        // Just swallow it up, we will deal with trying to delete it at another point
    }
}

Possible solutions:

Detect that the file is still open in another process

Detect that the second process hasn't really been fully exited and that the file is opened in the first process instead


问:
UIGesture ignore all transparent areas
Imagine a transparent frame, like an image frame, as a UIImageview and a text view in the middle.

The user see a frame and a text in the middle, but if he try to touch the text, he think he touch the text, but he may touch the frame if it's z position is on top.

I am looking for a way to "see" touches from GestureRecognizer, as the actual pixel that you touch.

So if the frame is on top, in terms of software it covers the text, but the user see the text and try to touch it, but instead the frame will recieve it.

Is there a way to "follow" the actual pixels, and receive the touches as you see them
 and not as their containers ?

答:
You can specified the location in certain view of your gesture recognizer.

Suppose I have a view containing a button(UIView).

View

My Button

```<code>class ViewController: UIViewController {

    @IBOutlet weak var myButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        addGesture()
    }

    private func addGesture() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
        view.addGestureRecognizer(panGesture)
    }

    @objc func handlePan(sender: UIPanGestureRecognizer) {
        let location sender.location(in: view)
        for subview in view {
            if subview.frame.contains(location) {
               // check whether this view is what you wanted? (by tag or something else...)
            }
        }

    }

}
</code>```

Title: UIGesture ignore all transparent areas

Body:
You can specified the location in certain view of your gesture recognizer.

Suppose I have a view containing a button(UIView).

View

My Button

class ViewController: UIViewController {

    @IBOutlet weak var myButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        addGesture()
    }

    private func addGesture() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
        view.addGestureRecognizer(panGesture)
    }

    @objc func handlePan(sender: UIPanGestureRecognizer) {
        let location sender.location(in: view)
        for subview in view {
            if subview.frame.contains(location) {
               // check whether this view is what you wanted? (by tag or something else...)
            }
        }

    }

}


问:
How to load my website dynamically when user requests from mobile or computer
I need to display my website dynamically. I.e when user requests form a computer the large layout should display and if user requests from mobile, my jquery mobile page should be displayed.

I'm not asking about Bootstrap framework.

Body:
Instead of using jquery you can use simple javascript to detect it:

var isMobile = false; //initiate as false

// device detection
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) isMobile = true;


问:
How to list all files of a given directory in Mac terminal except a file or directory
I want to display all the files in the working directory except for a file or directory. We have --exclude option in Ubuntu for dir command.

To be more specific, am trying to move files of my working directory to a subdirectory using this command:

```<code>git ls-tree -z --name-only HEAD | xargs -0 -I {} git mv {} sub_directory/
</code>```

And, while doing that, I don't want to move few files and directories. How can that be achieved in Mac?

答:
I am using macOS 10.12.5 . I did these steps:

(1) Install Homebrew

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

Reference: https://brew.sh/

(2) Install tree command what likes on Linux.

```<code>brew install tree
</code>```

(3) Use command tree and exclude directory pattern (For example: Exclude directory foo and fuu).

```<code>tree -f -I "foo|fuu"
</code>```

Learn more: https://unix.stackexchange.com/a/61078

See official document about command tree, on macOS type:

```<code>tree --help
</code>```

You will see many options, arguments for this command.

Body:
I want to display all the files in the working directory except for a file or directory. We have --exclude option in Ubuntu for dir command.

To be more specific, am trying to move files of my working directory to a subdirectory using this command:

git ls-tree -z --name-only HEAD | xargs -0 -I {} git mv {} sub_directory/

And, while doing that, I don't want to move few files and directories. How can that be achieved in Mac?

Body:
I am using macOS 10.12.5 . I did these steps:

(1) Install Homebrew

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Reference: https://brew.sh/

(2) Install tree command what likes on Linux.

brew install tree

(3) Use command tree and exclude directory pattern (For example: Exclude directory foo and fuu).

tree -f -I "foo|fuu"

Learn more: https://unix.stackexchange.com/a/61078

See official document about command tree, on macOS type:

tree --help

You will see many options, arguments for this command.


问:
V Json Data is not getting read in Hive Table
I am reading one line json data from Twitter in a Hive External Table. The table gets created but while reading the data, I get an error. I want to read the hashtags. I've followed the below steps:

```<code>hive (test)> add jar /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar;
Added /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar to class path
Added resource: /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar
</code>```

Data in file:

```<code>hive (test)> dfs -cat abhijit_hdfs/flume2/tweets/Twitter_test.js;

"entities":{"symbols":[],"urls":[],"hashtags":[{"text":"AchieveMore","indices":[56,68]}]}
</code>```

DDL statement

```<code>hive (test)> create external table tt4
           > (entities struct<hashtags:array<struct<text:string>>>)
           > row format serde 'com.cloudera.hive.serde.JSONSerDe'
           > LOCATION '/user/training/abhijit_hdfs/flume2/tweets/' ;
OK

Time taken: 0.193 seconds.
hive (test)> select * from tt4;
OK
Failed with exception java.io.IOException:org.apache.hadoop.hive.serde2.SerDeException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of VALUE_STRING token
 at [Source: java.io.StringReader@1cc892e; line: 1, column: 1]
Time taken: 0.384 seconds
</code>```

Please Guide.

答:
Dear Friends this issue is solved I Downloaded and saved following jar and restarted my claudera VM(Non commercial use).Thank you for your help which gave me direction to solve it.

hive> add jar /usr/lib/hive/lib/json-serde-1.3.6-jar-with-dependencies.jar;

Added /usr/lib/hive/lib/json-serde-1.3.6-jar-with-dependencies.jar to class path

Added resource: /usr/lib/hive/lib/json-serde-1.3.6-jar-with-dependencies.jar

hive> create external table t24

(entities struct<hashtags:array<struct<text:string>>>)
  row format serde 'org.openx.data.jsonserde.JsonSerDe'
  LOCATION '/user/training/abhijit_hdfs/flume4/tweets/'
  ;
  OK
  Time taken: 1.623 seconds
  hive> select * from t24;
  OK
  {"hashtags":[{"text":"AchieveMore"}]}
  null
  Time taken: 1.13 seconds
  hive>

Body:
I am reading one line json data from Twitter in a Hive External Table. The table gets created but while reading the data, I get an error. I want to read the hashtags. I've followed the below steps:

hive (test)> add jar /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar;
Added /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar to class path
Added resource: /usr/lib/hive/lib/hive-serdes-1.0-SNAPSHOT.jar

Data in file:

hive (test)> dfs -cat abhijit_hdfs/flume2/tweets/Twitter_test.js;

"entities":{"symbols":[],"urls":[],"hashtags":[{"text":"AchieveMore","indices":[56,68]}]}

DDL statement

hive (test)> create external table tt4
           > (entities struct<hashtags:array<struct<text:string>>>)
           > row format serde 'com.cloudera.hive.serde.JSONSerDe'
           > LOCATION '/user/training/abhijit_hdfs/flume2/tweets/' ;
OK

Time taken: 0.193 seconds.
hive (test)> select * from tt4;
OK
Failed with exception java.io.IOException:org.apache.hadoop.hive.serde2.SerDeException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.LinkedHashMap out of VALUE_STRING token
 at [Source: java.io.StringReader@1cc892e; line: 1, column: 1]
Time taken: 0.384 seconds

Please Guide.