问:
How to Get Rid of Tiling Borders When Mipmapping is Disabled
I created a fragment shader that tiles a texture (it is actually a texture array, as you will see in the code). However, I get very ugly 1 pixel borders around each of the tiles. I know this can be caused by discontinuity of the function, causing weird stuff to happen while mipmapping, but I have mipmapping disabled (although I am using antialiasing). Here is my code:

```<code>vec2 tiledCoords = fract(pass_textureCoords * 256.0) / 4.0; // pass_textureCoords are the texture coordinates

out_Color = texture(testArray, vec3(tiledCoords.x, tiledCoords.y, 0)); // testArray is the sampler2DArray
</code>```

I thought I'd have to give a bit of tolerance for rounding errors, but I can't seem to figure out where to put that. How can I get rid of these ugly borders? Thanks in advance!

Here is a screenshot:

答:
I'm not exactly sure what you are trying to do with the calculations in your code. The first line doesn't seem to contribute to the result at all (is overwritten in the second line). Since you didn't set filter modes or wrap modes, you'll have the default settings enabled which is linear filtering and repeat mode.

It seems that you are using tiledCoords in the range of [0, 0.25] and try to wrap from 0.25 to 0. Linear filtering is not going to work automatically in this case since there is no automatic wrap mode for the 0.25 -> 0 transition. The black lines are cause from the linear interpolation in the range [0, 1/(2 * num_pixels)] because this area interpolates linearly between the 0th texel and "-1st" texel  (which is due to wrapping mode the last texel of your texture). Same thing happens for the range [0.25 - 1/(2 * num_pixels), 0.25] where you interpolate the pixel directly left of texture coordinate 0.25 with the texel right of it.

There is no way to get hardware linear interpolation for your scenario. You can either use nearest neighbor sampling or calculate linear interpolate manually.

Body:
I created a fragment shader that tiles a texture (it is actually a texture array, as you will see in the code). However, I get very ugly 1 pixel borders around each of the tiles. I know this can be caused by discontinuity of the function, causing weird stuff to happen while mipmapping, but I have mipmapping disabled (although I am using antialiasing). Here is my code:

vec2 tiledCoords = fract(pass_textureCoords * 256.0) / 4.0; // pass_textureCoords are the texture coordinates

out_Color = texture(testArray, vec3(tiledCoords.x, tiledCoords.y, 0)); // testArray is the sampler2DArray

I thought I'd have to give a bit of tolerance for rounding errors, but I can't seem to figure out where to put that. How can I get rid of these ugly borders? Thanks in advance!

Here is a screenshot:


来源: stackexchange

问:
Retain Count Of Objects
I have a query in MRC in iOS & I am a little bit confuse. Suppose I have two objects ObjectA  & ObjectB of the same type with below retain count

ObjectA : retain count is 1

ObjectB : reatin count 0

Now I am performing operation

```<code>ObjectB = [ObjectA retain];
</code>```

Can anyone tell me what would be retained count of ObjectA & ObjectB?

As per my knowledge retain count of ObjectA = 2 & ObjectB = 1.

Please correct if I am wrong. If we are going to perform the copy operation, then what should be retained count.

答:
Your question doesn't really make sense.

First, a comment about variable names: You should be using variable names that start with lower case letters.

If you have an object in ObjectA and an object in ObjectB and the object in ObjectB's retain count reaches zero, it gets deallocated immediately, and no longer exists. ObjectB is now a "zombie" (A pointer to a deallocated object.)
If you try to do anything with ObjectB once it's retain count reaches zero, you may crash, or the system may store a different object in that memory and your code may actually point to the completely wrong object.

When you execute the line:

ObjectB = [ObjectA retain];

...then the variable ObjectB now also points to ObjectA, and you've increased the retain count on your ObjectA object to 2. (ObjectB and ObjectA are now the same object, with a retain count of 2.)

ContentLicense: CC BY-SA 3.0

Title: Retain Count Of Objects

Body:
I have a query in MRC in iOS & I am a little bit confuse. Suppose I have two objects ObjectA  & ObjectB of the same type with below retain count

ObjectA : retain count is 1

ObjectB : reatin count 0

Now I am performing operation

ObjectB = [ObjectA retain];

Can anyone tell me what would be retained count of ObjectA & ObjectB?

As per my knowledge retain count of ObjectA = 2 & ObjectB = 1.

Please correct if I am wrong. If we are going to perform the copy operation, then what should be retained count.


问:
Connect local ftp server with Android
I have made an ftp server in a Local drive of my laptop and assigned an IP address to it. I want to fetch excel files on that server using my android app and process the data.
How can I go about this?
Is Commons Apache the way to it?</p>

答:
Step 1:make your mobile hotspot on and connect your laptop with that hotspot.

step 2:make sure that your firewall is off. and apache or wampserver is on.

step 3:write ipconfig command in you cmd admin panel and chbeck your ip for wifi.

```<code> ipconfig
</code>```

step 4: same ip put in mobile browser it will show wampserver page..

i do this type configration for android to wampserver connection may be its helpful to you.

Title: Connect local ftp server with Android

Body:
Step 1:make your mobile hotspot on and connect your laptop with that hotspot.

step 2:make sure that your firewall is off. and apache or wampserver is on.

step 3:write ipconfig command in you cmd admin panel and chbeck your ip for wifi.

 ipconfig

step 4: same ip put in mobile browser it will show wampserver page..

i do this type configration for android to wampserver connection may be its helpful to you.


问:
Making csv from txt files
I have a lot of txt files like this:

```<code>Title 1
Text 1(more then 1 line)
</code>```

And I would like to make one csv file from all of them that it will look like this:

```<code>Title 1,Text 1
Title 2,Text 2
Title 3,Text 3
etc
</code>```

How could I do it? I think that awk is good for it but don't know how to realize it.

答:
May I suggest:

```<code>paste -d, file1 file2 file3
</code>```

To handle large numbers of files, max 40 per output file (untested, but close):

```<code>xargs -n40 files... echo >tempfile
num=1
for line in $(<tempfile)
do
    paste -d, $line >outfile.$num
    let num=num+1
done
</code>```

ContentLicense: CC BY-SA 2.5

Title: Making csv from txt files

Body:
I have a lot of txt files like this:

Title 1
Text 1(more then 1 line)

And I would like to make one csv file from all of them that it will look like this:

Title 1,Text 1
Title 2,Text 2
Title 3,Text 3
etc

How could I do it? I think that awk is good for it but don't know how to realize it.

Body:
May I suggest:

paste -d, file1 file2 file3

To handle large numbers of files, max 40 per output file (untested, but close):

xargs -n40 files... echo >tempfile
num=1
for line in $(<tempfile)
do
    paste -d, $line >outfile.$num
    let num=num+1
done


问:
How to get list of an entity with generic search
I have a generic repository, something like this:

```<code>    public IEnumerable<T> SelectAll()
    {
        return table.ToList();
    }

    public T SelectByID(object id)
    {
        return table.Find(id);
    }

    public void Insert(T obj)
    {
        table.Add(obj);
    }
</code>```

This works fine for the basic CRUD, but now I need to search an entity (table) against an user entered searchterm. Is it at all possible to do it with something like:

```<code>public IEnumerable<T> SelectAll(T obj, string searchText, string   columnName)
{
    // I am not sure what code to write here... It should give me all the records that contain the search term.
    // I was thinking something like this could be made to work...but I need help with it.
    return table.GetType().GetProperty(columnName).GetValue())ToList();
}
</code>```

答:
Use a Lambda Expression as the argument

```<code>public virtual async Task<List<T>> SearchBy(Expression<Func<Table, bool>> searchBy)
{
    return await _ctx.Set<Table>().Where(searchBy).ToListAsync();
}
</code>```

with this, you will call the search with a table expression argument returning a boolen

Body:
I have a generic repository, something like this:

    public IEnumerable<T> SelectAll()
    {
        return table.ToList();
    }

    public T SelectByID(object id)
    {
        return table.Find(id);
    }

    public void Insert(T obj)
    {
        table.Add(obj);
    }

This works fine for the basic CRUD, but now I need to search an entity (table) against an user entered searchterm. Is it at all possible to do it with something like:

public IEnumerable<T> SelectAll(T obj, string searchText, string   columnName)
{
    // I am not sure what code to write here... It should give me all the records that contain the search term.
    // I was thinking something like this could be made to work...but I need help with it.
    return table.GetType().GetProperty(columnName).GetValue())ToList();
}

Body:
Use a Lambda Expression as the argument

public virtual async Task<List<T>> SearchBy(Expression<Func<Table, bool>> searchBy)
{
    return await _ctx.Set<Table>().Where(searchBy).ToListAsync();
}

with this, you will call the search with a table expression argument returning a boolen


问:
Android - library module's interface method is not called in app module
I am using Android Image Slider library for showing images on a slider. However, some images are not loading because backend requires authentication. So I need a listener for not loading images.

This is library: inside abstract BaseSliderView class, there is ImageLoadListener interface. I am setting listener using setOnImageLoadListener method.

```<code>public abstract class BaseSliderView {

    .....

    private ImageLoadListener mLoadListener;

    .....

    protected void bindEventAndShow(final View v, ImageView targetImageView){
        ....

        rq.into(targetImageView,new Callback() {
            @Override
            public void onSuccess() {
                if(v.findViewById(R.id.loading_bar) != null){
                    v.findViewById(R.id.loading_bar).setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onError() {
                if(mLoadListener != null){
                    mLoadListener.onEnd(false,me);
                }

                if(v.findViewById(R.id.loading_bar) != null){
                    v.findViewById(R.id.loading_bar).setVisibility(View.INVISIBLE);
                }
            }
        });
   }

    /**
     * set a listener to get a message , if load error.
     * @param l
     */
    public void setOnImageLoadListener(ImageLoadListener l){
        mLoadListener = l;
    }

    .....

    public interface ImageLoadListener{
        void onStart(BaseSliderView target);
        void onEnd(boolean result,BaseSliderView target);
    }

    .....

}
</code>```

I checked, when image is not loaded, interface onEnd method is called in library module.

But on app module, onEnd method is not called even in library module it is called.

Why is this happening? Should not onEnd method be called in app module? How to solve this problem?

答:
I could solve this problem using greenrobot's EventBus library. First of all, I have added library dependency to library build.gradle file:

```<code>compile 'org.greenrobot:eventbus:3.0.0'
</code>```

Created class for event:

```<code>public class ImageLoadErrorEvent {

    String url;
    ImageView imageView;

    public ImageLoadErrorEvent(String url, ImageView imageView) {
        this.url = url;
        this.imageView = imageView;
    }

    public String getUrl() {
        return url;
    }

    public ImageView getImageView() {
        return imageView;
    }

}
</code>```

Posted on BaseSliderView class:

```<code>    @Override
    public void onError() {
        if(mLoadListener != null){
            mLoadListener.onEnd(false,me);
            EventBus.getDefault().post(new ImageLoadErrorEvent(mUrl, targetImageView));
        }

        if(v.findViewById(R.id.loading_bar) != null){
            v.findViewById(R.id.loading_bar).setVisibility(View.INVISIBLE);
        }
    }
</code>```

In Activity, inside onCreate method, registered EventBus:

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

    EventBus.getDefault().register(this);
</code>```

Then created onMessageEvent:

```<code>@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(ImageLoadErrorEvent event) {
    MyToast.show("Error");
}
</code>```

Yay, now it is working!

Body:
I am using Android Image Slider library for showing images on a slider. However, some images are not loading because backend requires authentication. So I need a listener for not loading images.

This is library: inside abstract BaseSliderView class, there is ImageLoadListener interface. I am setting listener using setOnImageLoadListener method.

public abstract class BaseSliderView {

    .....

    private ImageLoadListener mLoadListener;

    .....

    protected void bindEventAndShow(final View v, ImageView targetImageView){
        ....

        rq.into(targetImageView,new Callback() {
            @Override
            public void onSuccess() {
                if(v.findViewById(R.id.loading_bar) != null){
                    v.findViewById(R.id.loading_bar).setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onError() {
                if(mLoadListener != null){
                    mLoadListener.onEnd(false,me);
                }

                if(v.findViewById(R.id.loading_bar) != null){
                    v.findViewById(R.id.loading_bar).setVisibility(View.INVISIBLE);
                }
            }
        });
   }

    /**
     * set a listener to get a message , if load error.
     * @param l
     */
    public void setOnImageLoadListener(ImageLoadListener l){
        mLoadListener = l;
    }

    .....

    public interface ImageLoadListener{
        void onStart(BaseSliderView target);
        void onEnd(boolean result,BaseSliderView target);
    }

    .....

}

I checked, when image is not loaded, interface onEnd method is called in library module.

But on app module, onEnd method is not called even in library module it is called.

Why is this happening? Should not onEnd method be called in app module? How to solve this problem?

Body:
I could solve this problem using greenrobot's EventBus library. First of all, I have added library dependency to library build.gradle file:

compile 'org.greenrobot:eventbus:3.0.0'

Created class for event:

public class ImageLoadErrorEvent {

    String url;
    ImageView imageView;

    public ImageLoadErrorEvent(String url, ImageView imageView) {
        this.url = url;
        this.imageView = imageView;
    }

    public String getUrl() {
        return url;
    }

    public ImageView getImageView() {
        return imageView;
    }

}

Posted on BaseSliderView class:

    @Override
    public void onError() {
        if(mLoadListener != null){
            mLoadListener.onEnd(false,me);
            EventBus.getDefault().post(new ImageLoadErrorEvent(mUrl, targetImageView));
        }

        if(v.findViewById(R.id.loading_bar) != null){
            v.findViewById(R.id.loading_bar).setVisibility(View.INVISIBLE);
        }
    }

In Activity, inside onCreate method, registered EventBus:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);

    EventBus.getDefault().register(this);

Then created onMessageEvent:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(ImageLoadErrorEvent event) {
    MyToast.show("Error");
}

Yay, now it is working!


问:
Does Presto cache intermediate results internally out of the box?
Presto has multi connectors. While the connectors do implement read and write operations, from all the tutorials I read, it seems they are typically used as data sources to read from only. For example, netflix has "10 petabyte" of data on Amazon S3 and they explicitly state that no disk (and no HDFS) is used on the Presto worker nodes.
The stated use case are "ad hoc interactive" queries.

Also, Amazon Athena is essentially S3+Presto and comes with similar use cases.

I'm puzzled how this can work in practice. Obviously, you don't want to read 10 PB of data on every query. So I assume, you want to keep some previously fetched data in memory, such as a database index. However, with no constraints on the data and the queries, I fail to understand how this can be efficient.

Use case 1: I run the same query frequently, e.g. to show metric on a dashboard. Does Presto avoid rescanning the data points which are already 'known'?

Use case 2: I'm analysing a large data set. Each query is slightly different, however there are common subqueries or we filter to a common subset of the data. Does Presto learn from previous queries and carry over intermediate results?

Or, if this is not the case, would I be well advised to store intermediate results somewhere (e.g. CREATE TABLE AS ...)?

答:
As far as I know there is no intermediate implicit caching layer. When you use HDFS on your cluster, you surely benefit from OS disk caches, so next query run will be faster, but you won't get instant cached results. Similar data block-level caching might apply to S3 too.

Generally, no reasonably-sized system can sift through 10 petabytes of data, since reading all that data would take a lot of time. However, data can be partitioned so that Presto knows more or less which pieces of data need to be scanned. When partitioning aligns with query conditions (e.g. you partition data by data and you query for most recent data), this can work really well.

When your data is not partitioned the same way you query, and you don't want to re-partition it differently, saving temporary results with create table ... as select makes much sense. You can also store such temporary tables using some in-memory storage, e.g. raptor (currently undocumented) or memory connectors for even faster access.

For some starter tips about partitioning, tuning storage and queries you can have a look at https://aws.amazon.com/blogs/big-data/top-10-performance-tuning-tips-for-amazon-athena/.

ContentLicense: CC BY-SA 4.0


问:
Wrong format csv output in python
i have the following code that is working 99% - its taken me various attempts to get it right:

```<code>w = csv.writer(filename, lineterminator="\n")
    sC = []
    for i in sOut:
        #print("save", i[1:])
        sC.append(i[1:], "\n") #slice away first part

    sP = self.ids(sC)
    w.writerow(sP)
    filename.close()
    print("You save ", filename) #To show on CLI

def ids(self, numbering):
    tally = 1
    for i in range(len(numbering)):
        id = str(tally)
        numbering[i].insert(0, id)
        tally = tally+1
    return(numbering)
</code>```

The out put it should return inside a CSV file should look like this i.e. in separate columns:

```<code> 1  -4.885276794    55.72986221
 2  -4.885276794    55.72958374
 3  -4.883611202    55.72958374
</code>```

Instead it returns it all in one row and with square brackets, commas and aprostophes all of which I do not want:

```<code> ['1', -4.88527679443359, 55.7298622131348] ['2', -4.7475008964538, 55.9473609924319]   ['3', -4.79416608810425, 56.02791595459]
</code>```

I know I am making some basic mistake somewhere however I just don't know what? All help will be greatly appreciated.

Thanks Jemma

答:
As per juanpa should be w.writerows(saveProcess) instead of w.writerow(saveProcess)

all works!

Title: Wrong format csv output in python

Body:
i have the following code that is working 99% - its taken me various attempts to get it right:

w = csv.writer(filename, lineterminator="\n")
    sC = []
    for i in sOut:
        #print("save", i[1:])
        sC.append(i[1:], "\n") #slice away first part

    sP = self.ids(sC)
    w.writerow(sP)
    filename.close()
    print("You save ", filename) #To show on CLI

def ids(self, numbering):
    tally = 1
    for i in range(len(numbering)):
        id = str(tally)
        numbering[i].insert(0, id)
        tally = tally+1
    return(numbering)

The out put it should return inside a CSV file should look like this i.e. in separate columns:

 1  -4.885276794    55.72986221
 2  -4.885276794    55.72958374
 3  -4.883611202    55.72958374

Instead it returns it all in one row and with square brackets, commas and aprostophes all of which I do not want:

 ['1', -4.88527679443359, 55.7298622131348] ['2', -4.7475008964538, 55.9473609924319]   ['3', -4.79416608810425, 56.02791595459]

I know I am making some basic mistake somewhere however I just don't know what? All help will be greatly appreciated.

Thanks Jemma


问:
How to convert office file to image
I am searching from last two days but did not find any thing.

My requirement is to create a document viewer in my web application (C#.Net) and I don't want to use any third party tool for this. Can I convert the files in image or PDF or in any common formate which can be easly render on web page. I also can not use Introp object.

Any help will be highly appreciated

答:
You mention in one of your comments that you'd like to write all the code yourself but don't know where to start.  Here's how I would go about it...

First, you'll need to familiarize yourself with the Microsoft Office Format specification.  You can find that here (there's a link to the technical specification).  Office documents are actually a .zip file with an XML file inside along with any binary data representing attachments.  Just renamed a .docx file as .zip and you'll be able to open it up and see the XML and any other supporting documents inside (same is true for xlsx, etc...).

Then you'll need to become intimately familiar with either PDF or HTML, as your job now will be to convert the various Office document structure into PDF or HTML structure, being sure to respect page layout, margins, order, etc...

As others have said, this is a large task which is why third party tools exist today.  Also, each third party toolset has it's limitation as this is really hard to "get right" in all situations and there will be edge cases that work for one document and not another (because maybe they didn't use Microsoft Word to save the .docx, maybe they used OpenOffice and OpenOffice interpreted the standard slightly differently...)

Title: How to convert office file to image


问:
How would I get a ListView from ListActivty INSIDE a class that extends on TabActivity?
Newbie here, bear with me..

I have a class that extends TabActivity. One of my tabs currently contains one long string composed of some records i got from my sqlite table. Now i'm following a tutorial and the next step is to move away from the string and create something a bit more appropriate for the records, a listView. However it says i'll need to change my class to extend ListActivity but i've already extended TabActivity (not part of the tutorial)and i don't really have the knowledge yet to know where to go from here.

I figure if my tabs content was set with intents to separate classes I wouldn't have a problem but it's important to me that both the tabs and their content are constructed in the same class because i will want to be doing a lot between them later. But maybe there is no way i can avoid creating a separate class? If so could i still point both of my tabs towards the same class? for the same reason as above. But then how would i get them still displaying different content?

I sure there's an obvious solution but i don't have enough programming experience to have a clue what it is, I've been googling a while now but i'm not really sure what to look for so if somebody could point me in the right direction i'd really appreciate it.

Hope I'm talking sense, Here's a link to see the class i'm working on:

Codeviewer.org , my Budget.java

答:
You can always insert a ListView to your activity, give appropriate android:id so you may refer it to handle data. Theres no compulsion that a ListView must be in a ListActivity.

See my comments so I can help you more.


问:
Using group by and sort by in nested hash
I have a function:

```<code>tracks.group_by { |t| t[:track].track_category }
</code>```

Which creates a hash:

```<code>{

 #<TrackCategory id: 2, order: 0> =>
  [{:track =>
     #<Track promo_order: 2>,
    :order => 2},
   {:track =>
     #<Track promo_order: 2>,
    :order => 1}],

 #<TrackCategory id: 1, order: 1> =>
  [{:track =>
     #<Track promo_order: 2>,
    :order => 2},
   {:track =>
     #<Track promo_order: 2>,
    :order => 1}]
}
</code>```

I've been trying to sort the TrackCategories by order, and inside that sort the Tracks by promo_order.

This keeps giving me errors, and I'm positive I'm doing something wrong

```<code>tracks.group_by { |t| t[:track].track_category }.sort_by { |t| t[:order] }.sort_by { |t| t[:promo_order] }
</code>```

答:
You are passing a key-value pair which came from group_by and was coerced as an array to sort_by, and then trying to access a key in the array, which of course doesn't exist.

In other words, you're mistaking the input used in sort_by. In the first sort_by, |t| is a hash key-pair generated by group_by and coerced into a array of the form [k,v]. In your case, t is:

```<code>[ #<TrackCategory id: 2, order: 0>,
  [{:track =>
     #<Track promo_order: 2>,
    :order => 2},
   {:track =>
     #<Track promo_order: 2>,
    :order => 1}],
 #...
]
</code>```

So what you want is to decompose the array in its elements so you can get the ones you want, something like:

```<code>tracks.group_by { |t| t[:track].track_category }
  .sort_by { |t, _| t[:order] } # here you're sorting by TrackCategory#[:order]
</code>```

And something similar on the second line, but using [:promo_order] instead.

Body:
I have a function:

tracks.group_by { |t| t[:track].track_category }

Which creates a hash:

{

 #<TrackCategory id: 2, order: 0> =>
  [{:track =>
     #<Track promo_order: 2>,
    :order => 2},
   {:track =>
     #<Track promo_order: 2>,
    :order => 1}],

 #<TrackCategory id: 1, order: 1> =>
  [{:track =>
     #<Track promo_order: 2>,
    :order => 2},
   {:track =>
     #<Track promo_order: 2>,
    :order => 1}]
}

I've been trying to sort the TrackCategories by order, and inside that sort the Tracks by promo_order.

This keeps giving me errors, and I'm positive I'm doing something wrong

tracks.group_by { |t| t[:track].track_category }.sort_by { |t| t[:order] }.sort_by { |t| t[:promo_order] }

Body:
You are passing a key-value pair which came from group_by and was coerced as an array to sort_by, and then trying to access a key in the array, which of course doesn't exist.

In other words, you're mistaking the input used in sort_by. In the first sort_by, |t| is a hash key-pair generated by group_by and coerced into a array of the form [k,v]. In your case, t is:

[ #<TrackCategory id: 2, order: 0>,
  [{:track =>
     #<Track promo_order: 2>,
    :order => 2},
   {:track =>
     #<Track promo_order: 2>,
    :order => 1}],
 #...
]

So what you want is to decompose the array in its elements so you can get the ones you want, something like:

tracks.group_by { |t| t[:track].track_category }
  .sort_by { |t, _| t[:order] } # here you're sorting by TrackCategory#[:order]

And something similar on the second line, but using [:promo_order] instead.


问:
Spark Installation
I am a newbie, trying to install spark on a windows 7 Enterprise system. I have completed all the steps, like Environment variables, installed scala also. I have taken the latest spark-1.6.2-bin-hadoop2.6 version of the spark. After installtion, when  i am running the bin\spark-shell. I feel it ran well, but i am seeing some warning's like this. I have installed java also.

I Apologize for the long exception error here. Any help on this would be greatly helpful.

C:\windows\system32>java -version
java version "1.8.0_92"
Java(TM) SE Runtime Environment (build 1.8.0_92-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.92-b14, mixed mode)

```<code>16/06/28 17:18:53 WARN ObjectStore: Version information not found in metastore. hive.metastore.schema.verification is not enabled so recording the schema version 1.2.0
16/06/28 17:18:53 WARN ObjectStore: Failed to get database default, returning NoSuchObjectException
java.lang.RuntimeException: java.lang.NullPointerException
        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:522)
        at org.apache.spark.sql.hive.client.ClientWrapper.<init>(ClientWrapper.scala:204)
        at org.apache.spark.sql.hive.client.IsolatedClientLoader.createClient(IsolatedClientLoader.scala:238)
        at org.apache.spark.sql.hive.HiveContext.executionHive$lzycompute(HiveContext.scala:218)
        at org.apache.spark.sql.hive.HiveContext.executionHive(HiveContext.scala:208)
        at org.apache.spark.sql.hive.HiveContext.functionRegistry$lzycompute(HiveContext.scala:462)
        at org.apache.spark.sql.hive.HiveContext.functionRegistry(HiveContext.scala:461)
        at org.apache.spark.sql.UDFRegistration.<init>(UDFRegistration.scala:40)
        at org.apache.spark.sql.SQLContext.<init>(SQLContext.scala:330)
        at org.apache.spark.sql.hive.HiveContext.<init>(HiveContext.scala:90)
        at org.apache.spark.sql.hive.HiveContext.<init>(HiveContext.scala:101)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.spark.repl.SparkILoop.createSQLContext(SparkILoop.scala:1028)
        at $iwC$$iwC.<init>(<console>:15)
        at $iwC.<init>(<console>:24)
        at <init>(<console>:26)
        at .<init>(<console>:30)
        at .<clinit>(<console>)
        at .<init>(<console>:7)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:1065)
        at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1346)
        at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:840)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:871)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:819)
        at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:857)
        at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:902)
        at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:814)
        at org.apache.spark.repl.SparkILoopInit$$anonfun$initializeSpark$1.apply(SparkILoopInit.scala:132)
        at org.apache.spark.repl.SparkILoopInit$$anonfun$initializeSpark$1.apply(SparkILoopInit.scala:124)
        at org.apache.spark.repl.SparkIMain.beQuietDuring(SparkIMain.scala:324)
        at org.apache.spark.repl.SparkILoopInit$class.initializeSpark(SparkILoopInit.scala:124)
        at org.apache.spark.repl.SparkILoop.initializeSpark(SparkILoop.scala:64)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1$$anonfun$apply$mcZ$sp$5.apply$mcV$sp(SparkILoop.scala:974)
        at org.apache.spark.repl.SparkILoopInit$class.runThunks(SparkILoopInit.scala:159)
        at org.apache.spark.repl.SparkILoop.runThunks(SparkILoop.scala:64)
        at org.apache.spark.repl.SparkILoopInit$class.postInitialization(SparkILoopInit.scala:108)
        at org.apache.spark.repl.SparkILoop.postInitialization(SparkILoop.scala:64)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply$mcZ$sp(SparkILoop.scala:991)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
        at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
        at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$process(SparkILoop.scala:945)
        at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:1059)
        at org.apache.spark.repl.Main$.main(Main.scala:31)
        at org.apache.spark.repl.Main.main(Main.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:731)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.NullPointerException
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1012)
        at org.apache.hadoop.util.Shell.runCommand(Shell.java:482)
        at org.apache.hadoop.util.Shell.run(Shell.java:455)
        at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:715)
        at org.apache.hadoop.util.Shell.execCommand(Shell.java:808)
        at org.apache.hadoop.util.Shell.execCommand(Shell.java:791)
        at org.apache.hadoop.fs.FileUtil.execCommand(FileUtil.java:1097)
        at org.apache.hadoop.fs.RawLocalFileSystem$DeprecatedRawLocalFileStatus.loadPermissionInfo(RawLocalFileSystem.java:582)
        at org.apache.hadoop.fs.RawLocalFileSystem$DeprecatedRawLocalFileStatus.getPermission(RawLocalFileSystem.java:557)
        at org.apache.hadoop.hive.ql.session.SessionState.createRootHDFSDir(SessionState.java:599)
        at org.apache.hadoop.hive.ql.session.SessionState.createSessionDirs(SessionState.java:554)
        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:508)
        ... 62 more

<console>:16: error: not found: value sqlContext
         import sqlContext.implicits._
                ^
<console>:16: error: not found: value sqlContext
         import sqlContext.sql
</code>```

答:
I've been through a lot of pain with running spark on windows. Finally it works fine and I don't need none of the above - winutils, global variables or C:\tmp\hive. I don't even have admin access on windows.

Spark on windows usually throws exceptions bc it can't find hive and hadoop, but depends on your task, you need to import corresponding libraries. Import sqlContext right away after start

```<code>    val sqlContext = new org.apache.spark.sql.SQLContext(sc)
    import sqlContext.implicits._
    import sqlContext.sql
</code>```

Btw, I use pyspark in Jupiter without winutils, just locally tell to python where spark is.

Title: Spark Installation

Body:
I am a newbie, trying to install spark on a windows 7 Enterprise system. I have completed all the steps, like Environment variables, installed scala also. I have taken the latest spark-1.6.2-bin-hadoop2.6 version of the spark. After installtion, when  i am running the bin\spark-shell. I feel it ran well, but i am seeing some warning's like this. I have installed java also.

I Apologize for the long exception error here. Any help on this would be greatly helpful.

C:\windows\system32>java -version
java version "1.8.0_92"
Java(TM) SE Runtime Environment (build 1.8.0_92-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.92-b14, mixed mode)

16/06/28 17:18:53 WARN ObjectStore: Version information not found in metastore. hive.metastore.schema.verification is not enabled so recording the schema version 1.2.0
16/06/28 17:18:53 WARN ObjectStore: Failed to get database default, returning NoSuchObjectException
java.lang.RuntimeException: java.lang.NullPointerException
        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:522)
        at org.apache.spark.sql.hive.client.ClientWrapper.<init>(ClientWrapper.scala:204)
        at org.apache.spark.sql.hive.client.IsolatedClientLoader.createClient(IsolatedClientLoader.scala:238)
        at org.apache.spark.sql.hive.HiveContext.executionHive$lzycompute(HiveContext.scala:218)
        at org.apache.spark.sql.hive.HiveContext.executionHive(HiveContext.scala:208)
        at org.apache.spark.sql.hive.HiveContext.functionRegistry$lzycompute(HiveContext.scala:462)
        at org.apache.spark.sql.hive.HiveContext.functionRegistry(HiveContext.scala:461)
        at org.apache.spark.sql.UDFRegistration.<init>(UDFRegistration.scala:40)
        at org.apache.spark.sql.SQLContext.<init>(SQLContext.scala:330)
        at org.apache.spark.sql.hive.HiveContext.<init>(HiveContext.scala:90)
        at org.apache.spark.sql.hive.HiveContext.<init>(HiveContext.scala:101)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.spark.repl.SparkILoop.createSQLContext(SparkILoop.scala:1028)
        at $iwC$$iwC.<init>(<console>:15)
        at $iwC.<init>(<console>:24)
        at <init>(<console>:26)
        at .<init>(<console>:30)
        at .<clinit>(<console>)
        at .<init>(<console>:7)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:1065)
        at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1346)
        at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:840)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:871)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:819)
        at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:857)
        at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:902)
        at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:814)
        at org.apache.spark.repl.SparkILoopInit$$anonfun$initializeSpark$1.apply(SparkILoopInit.scala:132)
        at org.apache.spark.repl.SparkILoopInit$$anonfun$initializeSpark$1.apply(SparkILoopInit.scala:124)
        at org.apache.spark.repl.SparkIMain.beQuietDuring(SparkIMain.scala:324)
        at org.apache.spark.repl.SparkILoopInit$class.initializeSpark(SparkILoopInit.scala:124)
        at org.apache.spark.repl.SparkILoop.initializeSpark(SparkILoop.scala:64)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1$$anonfun$apply$mcZ$sp$5.apply$mcV$sp(SparkILoop.scala:974)
        at org.apache.spark.repl.SparkILoopInit$class.runThunks(SparkILoopInit.scala:159)
        at org.apache.spark.repl.SparkILoop.runThunks(SparkILoop.scala:64)
        at org.apache.spark.repl.SparkILoopInit$class.postInitialization(SparkILoopInit.scala:108)
        at org.apache.spark.repl.SparkILoop.postInitialization(SparkILoop.scala:64)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply$mcZ$sp(SparkILoop.scala:991)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
        at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
        at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$process(SparkILoop.scala:945)
        at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:1059)
        at org.apache.spark.repl.Main$.main(Main.scala:31)
        at org.apache.spark.repl.Main.main(Main.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:731)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.NullPointerException
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1012)
        at org.apache.hadoop.util.Shell.runCommand(Shell.java:482)
        at org.apache.hadoop.util.Shell.run(Shell.java:455)
        at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:715)
        at org.apache.hadoop.util.Shell.execCommand(Shell.java:808)
        at org.apache.hadoop.util.Shell.execCommand(Shell.java:791)
        at org.apache.hadoop.fs.FileUtil.execCommand(FileUtil.java:1097)
        at org.apache.hadoop.fs.RawLocalFileSystem$DeprecatedRawLocalFileStatus.loadPermissionInfo(RawLocalFileSystem.java:582)
        at org.apache.hadoop.fs.RawLocalFileSystem$DeprecatedRawLocalFileStatus.getPermission(RawLocalFileSystem.java:557)
        at org.apache.hadoop.hive.ql.session.SessionState.createRootHDFSDir(SessionState.java:599)
        at org.apache.hadoop.hive.ql.session.SessionState.createSessionDirs(SessionState.java:554)
        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:508)
        ... 62 more

<console>:16: error: not found: value sqlContext
         import sqlContext.implicits._
                ^
<console>:16: error: not found: value sqlContext
         import sqlContext.sql

Body:
I've been through a lot of pain with running spark on windows. Finally it works fine and I don't need none of the above - winutils, global variables or C:\tmp\hive. I don't even have admin access on windows.

Spark on windows usually throws exceptions bc it can't find hive and hadoop, but depends on your task, you need to import corresponding libraries. Import sqlContext right away after start

    val sqlContext = new org.apache.spark.sql.SQLContext(sc)
    import sqlContext.implicits._
    import sqlContext.sql

Btw, I use pyspark in Jupiter without winutils, just locally tell to python where spark is.


问:
How to check-in changes to multiple branches in TFVC
I have a branch A and a branch B, A is parent of B.

Nowadays, each time a programmer chek-in to B, has to decide either merging that changeset to A or not (it depends on business requirements)

Is there a way to do this in a command line?

Either check-in to A and B at same time, or check-in to A and merge to B?

Thanks a lot!

答: These are always 2 separate actions. Code must be checked in before it can be merged. But of course you could create a little batch file that issues the consecutive commands required to merge right after the check-in.</p>


问:
How do you inspect and element when right click is disabled and the keyboard shortcuts are too?
I am on http://cloudinternetexplorer.com/ and it won't let me use the keyboard shortcuts or right click. How do I inspect elements on the page?</p>

答:
There are so many different ways to do this...
You have given no detail here as to what you're doing. Are you using IE, Chrome, Safari, Firefox, Opera? Windows, Mac, Linux? Try view-source:http://cloudinternetexplorer.com/? Or here, if you just want the index page, I made a pastebin for you - https://pastebin.com/PRZwUVDw.


问:
What is the fastest way to serialize to ByteBuffer?
I would like to write serializer for Ehcache of Optional class. I know, that optional member is seriazizable, so I write:

```<code>@Override
   public ByteBuffer serialize(Optional object) throws SerializerException {

      if( object.isPresent() ) {
         try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            return ByteBuffer.wrap(baos.toByteArray()); // excess copying
         } catch (IOException e) {
            throw new AssertionError(e);
         }

      }
      else {
         return ByteBuffer.wrap(new byte[] {});
      }
   }

   @Override
   public Optional read(ByteBuffer binary) throws ClassNotFoundException, SerializerException {
      if( binary.array().length > 0 ) {
         try {
            byte[] buf = binary.array();
            ByteArrayInputStream bais = new ByteArrayInputStream(buf);
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object object = ois.readObject();
            return Optional.of(object);
         } catch (IOException e) {
            throw new AssertionError(e);
         }
      }
      else {
         return Optional.empty();
      }
   }
</code>```

I confused by commented line, which includes excess copying of data. Can I avoid it and serialize directly with ByteBuffer?

While does Ehcache seriazliers based of ByteBuffer?

答:
Sadly, you can't do Java serialization on a ByteBuffer. You are doing the same thing as the built-in PlainJavaSerializer of Ehcache.

By the way, you could remove a lot of code by doing this:

```<code>public class OptionalSerializer<T> implements Serializer<Optional<T>> {

  private final PlainJavaSerializer<T> serializer;

  public OptionalSerializer(ClassLoader classLoader) {
      serializer = new PlainJavaSerializer<>(classLoader);
  }

  @Override
  public ByteBuffer serialize(Optional<T> object) throws SerializerException {
    return object.map(serializer::serialize).orElse(ByteBuffer.allocate(0));
  }

  @Override
  public Optional<T> read (ByteBuffer binary) throws ClassNotFoundException, SerializerException {
    if(binary.array().length > 0) {
      return Optional.of(serializer.read(binary));
    }
    return Optional.empty();
  }

  @Override
  public boolean equals(Optional<T> object, ByteBuffer binary) throws ClassNotFoundException, SerializerException {
    return object.equals(read(binary));
  }

}
</code>```

Body:
I would like to write serializer for Ehcache of Optional class. I know, that optional member is seriazizable, so I write:

@Override
   public ByteBuffer serialize(Optional object) throws SerializerException {

      if( object.isPresent() ) {
         try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            return ByteBuffer.wrap(baos.toByteArray()); // excess copying
         } catch (IOException e) {
            throw new AssertionError(e);
         }

      }
      else {
         return ByteBuffer.wrap(new byte[] {});
      }
   }

   @Override
   public Optional read(ByteBuffer binary) throws ClassNotFoundException, SerializerException {
      if( binary.array().length > 0 ) {
         try {
            byte[] buf = binary.array();
            ByteArrayInputStream bais = new ByteArrayInputStream(buf);
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object object = ois.readObject();
            return Optional.of(object);
         } catch (IOException e) {
            throw new AssertionError(e);
         }
      }
      else {
         return Optional.empty();
      }
   }

I confused by commented line, which includes excess copying of data. Can I avoid it and serialize directly with ByteBuffer?

While does Ehcache seriazliers based of ByteBuffer?

Body:
Sadly, you can't do Java serialization on a ByteBuffer. You are doing the same thing as the built-in PlainJavaSerializer of Ehcache.

By the way, you could remove a lot of code by doing this:

public class OptionalSerializer<T> implements Serializer<Optional<T>> {

  private final PlainJavaSerializer<T> serializer;

  public OptionalSerializer(ClassLoader classLoader) {
      serializer = new PlainJavaSerializer<>(classLoader);
  }

  @Override
  public ByteBuffer serialize(Optional<T> object) throws SerializerException {
    return object.map(serializer::serialize).orElse(ByteBuffer.allocate(0));
  }

  @Override
  public Optional<T> read (ByteBuffer binary) throws ClassNotFoundException, SerializerException {
    if(binary.array().length > 0) {
      return Optional.of(serializer.read(binary));
    }
    return Optional.empty();
  }

  @Override
  public boolean equals(Optional<T> object, ByteBuffer binary) throws ClassNotFoundException, SerializerException {
    return object.equals(read(binary));
  }

}


问:
Laravel 5.4 pdf generate: Image not found or type unknown in dompdf after download pdf
I am trying to generate a pdf using laravel dom pdf. When i download my pdf it does not show my image. It shows Image not found or type unknown. But in browser it shows correctly. I have followed other corresponding questions in stack. I have enabled $isRemoteEnabled = true;   How can i resolve this?

This is my pdfview:

```<code><html>
    <head>
    {{--<link rel="stylesheet" href="{{ URL::to('css/style.css') }}">--}}
        <style>
            /*pdf view start*/
            .pdf-content{
                /*pdf body*/
                width: 100%;
                height: 100%;
                background-color: #d3d3d3;
            }
            .pdf-doctor{
                /*for doctor*/
                border-bottom: 1px dashed gray;
            }
            .rx{
                float: left;
                margin-top: 5px;
                width: 100px;
                height:100px;
            }
            .rx img{
                width: 100px;
                height:100px;
            }
            .doctor-info p{
                text-align: center;
            }
            /*{{--for patient start--}}*/
            .pdf-patient{
                margin-top: 7px;
                border-top: 1px dashed gray;
                height: 30px;
                width: 100%;
            }
            .pdf-patient h4{
                float: left;
                display: inline;
                color: #0000cc;
            }
            .pdf-patient-name-date{
                float: left;
                margin-left: 76px;
                margin-top: 7px;
                width: 45%;
            }

            .pdf-test{
                /*for test*/
                margin-top: 50px;
                height: 20em;
                width: 100%;
            }
            .pdf-test h4{
                margin-left: 76px;
                /*display: inline;*/
                color: #0000cc;
            }
            .pdf-test-list{
                border: 1px solid black;
                float: left;
                margin-left: 116px;
                width: 40%;
            }
            .pdf-test-list p{
                margin-left: 15px;
                padding-top: 5px;
            }
            .pdf-test-done{
                border-top: 1px solid black;
                border-right: 1px solid black;
                border-bottom: 1px solid black;
                float: left;
                /*margin-left: 76px;*/
                /*margin-top: 15px;*/
                height: 37px;
                width: 10%;
            }
            .pdf-comments{
                /*for comment*/
                margin-top: 50px;
                height: 30px;
                width: 100%;
            }
            .pdf-comments h3{
                /*for comment*/
                margin-left: 76px;
                /*display: inline;*/
                color: #0000cc;
            }

            /*pdf view end*/
        </style>
    </head>
    <body>
        <div class="pdf-content">
            <div class="pdf-doctor">
                <div class="rx">
                    <img src=" {{ url("/images/rx1.png") }}">
                    {{--{{URL::asset('/image/propic.png')}}--}}
                </div>
                {{--for doctor--}}
                <div class="doctor-info">
                    <p>Doctor's name here</p>
                    <p>Doctor's degree here</p>
                    <p>Doctor's Address here</p>
                    <p>Doctor's Mob here</p>
                </div>

            </div>

            <div class="pdf-patient">
                {{--for patient--}}
                <div class="pdf-patient-name" style="float: left;">
                    <h4 style="display: inline;"><i>Patient name</i>:&nbsp&nbsp</h4>
                    <h4 style="display: inline;">{{ $patients->name }}</h4>
                    {{--style="text-decoration: underline; text-decoration-style: dotted;"--}}
                </div>
                <div class="pdf-patient-date" style="margin-left: 175px;">
                    <h4 style="display: inline;"><i>Date</i>:&nbsp&nbsp</h4>
                    <h4 style="display: inline;">{{ $patients->created_at }}</h4>
                </div>
            </div>
            <div class="pdf-test">
                {{--for test--}}
                <h4>Tests</h4>
                <div style="height: 5px;"></div>
                {{--@foreach($patients as $patient)--}}
                <div class="pdf-test-list">
                    <p>{!! nl2br($patients->test) !!}</p>
                </div>
                {{--<div class="pdf-test-done">--}}
                    {{--<p>tik</p>--}}
                {{--</div>--}}
                {{--@endforeach--}}

            </div>
            <div class="pdf-comments">
                {{--for comment--}}
                <h3 >Comments</h3>
            </div>
        </div>
    </body>
</html>
</code>```

my Controller:

```<code>public function PdfView(Request $request, $patient_id)
{
   $patients = Patient::where('id', $patient_id)->first();
   $pdf = PDF::loadView('pdfview', ['patients'=>$patients]);
   return $pdf->download('pdfview.pdf');
}
</code>```

my image is in public/images/rx1.png and pdfview is in views folder. How can i resolve this?

答:
Try to use absolute paths for images, and probably for others resources, like css and javascripts if they are not loaded.

For this its better to have a layout dedicated to pdf export with absolute paths to load resources.

As an alternative you can try to set:

```<code>isRemoteEnabled: true
</code>```

in config/dompdf.php and use your normal view layout.

Body:
I am trying to generate a pdf using laravel dom pdf. When i download my pdf it does not show my image. It shows Image not found or type unknown. But in browser it shows correctly. I have followed other corresponding questions in stack. I have enabled $isRemoteEnabled = true;   How can i resolve this?

This is my pdfview:

    {{--<link rel="stylesheet" href="{{ URL::to('css/style.css') }}">--}}

                    {{--{{URL::asset('/image/propic.png')}}--}}

                {{--for doctor--}}

Doctor's name here

Doctor's degree here

Doctor's Address here

Doctor's Mob here

                {{--for patient--}}

Patient name:&nbsp&nbsp

{{ $patients->name }}

                    {{--style="text-decoration: underline; text-decoration-style: dotted;"--}}

Date:&nbsp&nbsp

{{ $patients->created_at }}

                {{--for test--}}

Tests

                {{--@foreach($patients as $patient)--}}

{!! nl2br($patients->test) !!}

                {{--
--}}
                    {{--
tik
--}}
                {{--
--}}
                {{--@endforeach--}}

                {{--for comment--}}

Comments

my Controller:

public function PdfView(Request $request, $patient_id)
{
   $patients = Patient::where('id', $patient_id)->first();
   $pdf = PDF::loadView('pdfview', ['patients'=>$patients]);
   return $pdf->download('pdfview.pdf');
}

my image is in public/images/rx1.png and pdfview is in views folder. How can i resolve this?

Body:
Try to use absolute paths for images, and probably for others resources, like css and javascripts if they are not loaded.

For this its better to have a layout dedicated to pdf export with absolute paths to load resources.

As an alternative you can try to set:

isRemoteEnabled: true

in config/dompdf.php and use your normal view layout.


问:
How to rewrite txt file-why my code doesn't work
I want rewrite my txt file(I need delete lines). I use this code:

```<code> string cesta3 = cesta + "database.txt";
 string file = new StreamReader(cesta3).ReadToEnd();

 var linesToKeep = File.ReadLines(cesta3)
    .Where(l => l != "Meno: " + textBox1.Text + " PN " + textBox2.Text);
</code>```

But I don't know how to save my file with that same name.I try this:

```<code> File.WriteAllLines(cesta3, linesToKeep); // <== exception

 var tempFile = Path.GetTempFileName();
 File.Move(tempFile + ".txt", cesta3);
</code>```

But it throws exception:

Additional information: Access to the path "'C:\Users\Lenovo\documents\visual studio 2015\Projects\attendancer\attendancer\bin\Debug\database.txt' is denied."

How can I do ?

答:
This line of code locks the file and prevent it from moving: string file = new StreamReader(cesta3).ReadToEnd();.

Fix:

you can properly close StreamReader after reading file text from it with using

alternatively since there is nothing in the sample using that StreamReader or result of ReadToEnd (file variable) you can simply remove that line.

Side note: File.Move will throw more exceptions after you are done with the first one as source file is unlikely to exist - I'm not sure what you were trying to do with that call.

Body:
I want rewrite my txt file(I need delete lines). I use this code:

 string cesta3 = cesta + "database.txt";
 string file = new StreamReader(cesta3).ReadToEnd();

 var linesToKeep = File.ReadLines(cesta3)
    .Where(l => l != "Meno: " + textBox1.Text + " PN " + textBox2.Text);

But I don't know how to save my file with that same name.I try this:

 File.WriteAllLines(cesta3, linesToKeep); // <== exception

 var tempFile = Path.GetTempFileName();
 File.Move(tempFile + ".txt", cesta3);

But it throws exception:

Additional information: Access to the path "'C:\Users\Lenovo\documents\visual studio 2015\Projects\attendancer\attendancer\bin\Debug\database.txt' is denied."

How can I do ?


问:
Issues with selecting rows from large tables and updating them
I have a total of 7 tables.  1 of them will be used as comparison to the other 6 and it will get columns updated from the other 5.  As far as columns there aren't that many, the main table has a total of 17 columns total.  But rows, that main table has approx 66,000 rows.  Now I have been doing a bit of research and set the tables to MYISAM instead of InnoDB but haven't seen much change in load speeds.  So this is my initial approach:

Select all rows from table 1 then in PHP do a foreach row get certain column values and do a specific select on each of the 6 other tables to return a single value:

```<code>$all = $table1->selectAll();
foreach( $all as $a_template ){
      $id = $a_template['id'];

      $table2 = new Table2();
      $table3 = new Table3();
      $table4 = new Table4();
      $table5 = new Table5();
      $table6 = new Table6();

      $table2->select($a_template['column1']);
      $table3->select($a_template['column2']);
      $table4->select($a_template['column3']);
      $table5->select($a_template['column4']);
      $table6->selectByCode($a_template['npsecondarycode']);

      $table1 = new Table1();
      $table1->update($table2->getColumnVal(), $table3->getColumnVal(), $table4->getColumnVal(), $table5->getColumnVal(), $table6->getColumnVal(), $id);

    }
</code>```

the function that gets called "getColumnVal()" all it does is return the value that was set when doing a select, no biggie there.

Now this process takes around 15 - 20 minutes going through 66,000 records and I haven't been able to speed it up any more and in some cases has cause memory issues to where I've had to upgrade the memory limit to 1GB atleast.

I did try going straight through MySQL and doing a select with inner joins, since I've heard that Databases can do more intense queries with larger data and better speeds but in this case it actually locks up and stops working all together, in some cases PhpMyAdmin gives me a 500 error.

I'm not sure which way to go from here since I've never come across this situation before.  I would greatly appreciate it if anyone could point me to the right direction as to what steps should be taken to increase performance and speed in processing this data.  TY :)

Update: here's the actual query based on the Rick James' answer:

```<code>UPDATE templates AS t
         JOIN equipos as e ON e.codigos  = t.npsegment1
         JOIN ubicaciones u ON u.attribute1  = t.atributo1
         JOIN tiendas ti ON ti.nombre_doc_stock = t.atributo1
         JOIN estados es on es.nporganizationid  = t.nporganizationid
         JOIN almacenes a on a.npsecondarycode  = t.npsecondarycode
         SET t.inclusion = e.inclusion,
             t.ubicacion = u.ubicacion11,
             t.tienda_id = ti.idi2b,
             t.estado = es.estado,
             t.considerar = a.considerar
</code>```

The table Templates has 66K records

答:
Look up multi-table UPDATE.  You might be able to perform the entire operation in a single SQL statement.  It will run a lot faster.  Something like

```<code>UPDATE table1
    JOIN table2 ON ...
    JOIN table3 ON ...
    ....
    SET table1.col1 = ...,
        table1.col2 = ...,
        ....;
</code>```

Don't use MyISAM.

More

The query is copying stuff from several tables into one table (t)?  If you are creating t from scratch, then it would probably be much faster to do INSERT INTO t SELECT ... JOIN ...

If you do need massive updates, and if the columns are independent, then it would probably work faster to do one table at a time.  That is,

```<code>UPDATE t JOIN e ON ... SET t.inclusion = e.inclusion;
UPDATE t JOIN u ON ... SET t.... = u....;
etc.
</code>```

I suspect part of the problem is locking so many rows in so many tables.

Another approach is to "chunk" up the task.  I discuss that here .  It will take longer overall, but each chunk will finish in a civilized amount of time.

Body:
I have a total of 7 tables.  1 of them will be used as comparison to the other 6 and it will get columns updated from the other 5.  As far as columns there aren't that many, the main table has a total of 17 columns total.  But rows, that main table has approx 66,000 rows.  Now I have been doing a bit of research and set the tables to MYISAM instead of InnoDB but haven't seen much change in load speeds.  So this is my initial approach:

Select all rows from table 1 then in PHP do a foreach row get certain column values and do a specific select on each of the 6 other tables to return a single value:

$all = $table1->selectAll();
foreach( $all as $a_template ){
      $id = $a_template['id'];

      $table2 = new Table2();
      $table3 = new Table3();
      $table4 = new Table4();
      $table5 = new Table5();
      $table6 = new Table6();

      $table2->select($a_template['column1']);
      $table3->select($a_template['column2']);
      $table4->select($a_template['column3']);
      $table5->select($a_template['column4']);
      $table6->selectByCode($a_template['npsecondarycode']);

      $table1 = new Table1();
      $table1->update($table2->getColumnVal(), $table3->getColumnVal(), $table4->getColumnVal(), $table5->getColumnVal(), $table6->getColumnVal(), $id);

    }

the function that gets called "getColumnVal()" all it does is return the value that was set when doing a select, no biggie there.

Now this process takes around 15 - 20 minutes going through 66,000 records and I haven't been able to speed it up any more and in some cases has cause memory issues to where I've had to upgrade the memory limit to 1GB atleast.

I did try going straight through MySQL and doing a select with inner joins, since I've heard that Databases can do more intense queries with larger data and better speeds but in this case it actually locks up and stops working all together, in some cases PhpMyAdmin gives me a 500 error.

I'm not sure which way to go from here since I've never come across this situation before.  I would greatly appreciate it if anyone could point me to the right direction as to what steps should be taken to increase performance and speed in processing this data.  TY :)

Update: here's the actual query based on the Rick James' answer:

UPDATE templates AS t
         JOIN equipos as e ON e.codigos  = t.npsegment1
         JOIN ubicaciones u ON u.attribute1  = t.atributo1
         JOIN tiendas ti ON ti.nombre_doc_stock = t.atributo1
         JOIN estados es on es.nporganizationid  = t.nporganizationid
         JOIN almacenes a on a.npsecondarycode  = t.npsecondarycode
         SET t.inclusion = e.inclusion,
             t.ubicacion = u.ubicacion11,
             t.tienda_id = ti.idi2b,
             t.estado = es.estado,
             t.considerar = a.considerar

The table Templates has 66K records

Body:
Look up multi-table UPDATE.  You might be able to perform the entire operation in a single SQL statement.  It will run a lot faster.  Something like

UPDATE table1
    JOIN table2 ON ...
    JOIN table3 ON ...
    ....
    SET table1.col1 = ...,
        table1.col2 = ...,
        ....;

Don't use MyISAM.

More

The query is copying stuff from several tables into one table (t)?  If you are creating t from scratch, then it would probably be much faster to do INSERT INTO t SELECT ... JOIN ...

If you do need massive updates, and if the columns are independent, then it would probably work faster to do one table at a time.  That is,

UPDATE t JOIN e ON ... SET t.inclusion = e.inclusion;
UPDATE t JOIN u ON ... SET t.... = u....;
etc.

I suspect part of the problem is locking so many rows in so many tables.

Another approach is to "chunk" up the task.  I discuss that here .  It will take longer overall, but each chunk will finish in a civilized amount of time.


问:
Text file to the hex
I have a text file containing hex codes

```<code>00000000 4f909390
00000002 5e456783
00000003 3fe52341
</code>```

I need to program the embedded device with the above hex values in my_file.txt .
However, when I read the above file and print them, I see the above hex values in text were totally different and I understand that the txt data were converted to hex format.

```<code>void print_file( )
{
char source[1000000];

FILE *fp = fopen("my_file.txt, "r");
UINT32 size = ftell(fp); /* get the size */
if(fp != NULL)
{
    while((symbol = getc(fp)) != EOF)
    {
        strcat(source, &symbol);
    }
    fclose(fp);
}
   for ( UINT32 i = 0; i < size; i++ )
    printf( "%02x", buffer[i] );
}
</code>```

The above code displays the hex converted text format and displays me

```<code>3030303030303030203466393039333930a303030303030303
2203565343536373833a3030303030303033203366653532333431.
</code>```

This is intact with the text to hex conversion that I checked in online.

The desired printout should be

```<code>00000000 4f909390
00000002 5e456783
00000003 3fe52341
</code>```

What is the right to read the hex values in text by itself and not being converted from ASCII to hex ?Thanks in advance.

答:
It's not entirely clear to me what you want, but I think you are trying to read a text file containing two columns of numbers, both in hexadecimal.  This represents an array of 32-bit words which will be written to the onboard memory of a peripheral device.  I am guessing that the first column is an address and the second column is a value to be written at that address.  I don't know what you want written to addresses that aren't listed in the file.

A logical way to represent this file in memory is with an array of two-element structs:

```<code>struct memory_word
{
    uint32_t addr;
    uint32_t value;
};
</code>```

You can parse that from a line of your file using strtoul:

```<code>int
parse_line(struct memory_word *buf, const char *line,
           const char *fname, size_t lineno)
{
    const char *p;
    char *endp;
    unsigned long n;

    errno = 0;
    p = line;
    n = strtoul(p, &endp, 16);
    if (endp == p || !isspace(*endp) || errno || n > (unsigned long)UINT32_MAX) {
        fprintf(stderr, "%s:%d: invalid address\n", fname, lineno);
        return -1;
    }
    buf->addr = (uint32_t)n;

    p = endp;
    n = strtoul(p, &endp, 16);
    if (endp == p || !isspace(*endp) || errno || n > (unsigned long)UINT32_MAX) {
        fprintf(stderr, "%s:%d: invalid value\n", fname, lineno);
        return -1;
    }
    buf->value = (uint32_t)n;

    p = endp;
    while (isspace(*p)) p++;
    if (*p) {
        fprintf(stderr, "%s:%d: junk after record\n", fname, lineno);
        return -1;
    }
    return 0;
}
</code>```

And you can read the entire file by calling that in a loop:

```<code>struct memory_word *
read_memory_file (const char *fname)
{
    struct memory_word *values = 0;
    void *ovalues;
    size_t nvalues = 0;
    size_t avalues = 0;

    char *linebuf = 0;
    size_t linesz = 0;

    FILE *fp = fopen(fname, "rt");
    if (!fp) {
        perror(fname);
        return 0;
    }

    while (getline(&linebuf, &linesz, fp) > 0) {
        nvalues++;
        if (nvalues > avalues) {
            avalues = (avalues == 0) ? 16 : avalues * 2;
            ovalues = values;
            values = reallocarray(values, avalues, sizeof(uint32_t));
            if (!values) {
                perror("realloc");
                free(ovalues);
                return 0;
            }
        }
        if (parse_line(&values[nvalues-1], linebuf, fname, nvalues)) {
            fclose(fp);
            free(values);
            return 0;
        }
    }

    if (ferror(fp)) {
        perror(fname);
        fclose(fp);
        free(values);
        return 0;
    }
    fclose(fp);
    return values;
}
</code>```

(reallocarray is not part of the C standard, but it should be.  You can get a copy from the link.)

Title: Text file to the hex

Body:
I have a text file containing hex codes

00000000 4f909390
00000002 5e456783
00000003 3fe52341

I need to program the embedded device with the above hex values in my_file.txt .
However, when I read the above file and print them, I see the above hex values in text were totally different and I understand that the txt data were converted to hex format.

void print_file( )
{
char source[1000000];

FILE *fp = fopen("my_file.txt, "r");
UINT32 size = ftell(fp); /* get the size */
if(fp != NULL)
{
    while((symbol = getc(fp)) != EOF)
    {
        strcat(source, &symbol);
    }
    fclose(fp);
}
   for ( UINT32 i = 0; i < size; i++ )
    printf( "%02x", buffer[i] );
}

The above code displays the hex converted text format and displays me

3030303030303030203466393039333930a303030303030303
2203565343536373833a3030303030303033203366653532333431.

This is intact with the text to hex conversion that I checked in online.

The desired printout should be

00000000 4f909390
00000002 5e456783
00000003 3fe52341

What is the right to read the hex values in text by itself and not being converted from ASCII to hex ?Thanks in advance.

Body:
It's not entirely clear to me what you want, but I think you are trying to read a text file containing two columns of numbers, both in hexadecimal.  This represents an array of 32-bit words which will be written to the onboard memory of a peripheral device.  I am guessing that the first column is an address and the second column is a value to be written at that address.  I don't know what you want written to addresses that aren't listed in the file.

A logical way to represent this file in memory is with an array of two-element structs:

struct memory_word
{
    uint32_t addr;
    uint32_t value;
};

You can parse that from a line of your file using strtoul:

int
parse_line(struct memory_word *buf, const char *line,
           const char *fname, size_t lineno)
{
    const char *p;
    char *endp;
    unsigned long n;

    errno = 0;
    p = line;
    n = strtoul(p, &endp, 16);
    if (endp == p || !isspace(*endp) || errno || n > (unsigned long)UINT32_MAX) {
        fprintf(stderr, "%s:%d: invalid address\n", fname, lineno);
        return -1;
    }
    buf->addr = (uint32_t)n;

    p = endp;
    n = strtoul(p, &endp, 16);
    if (endp == p || !isspace(*endp) || errno || n > (unsigned long)UINT32_MAX) {
        fprintf(stderr, "%s:%d: invalid value\n", fname, lineno);
        return -1;
    }
    buf->value = (uint32_t)n;

    p = endp;
    while (isspace(*p)) p++;
    if (*p) {
        fprintf(stderr, "%s:%d: junk after record\n", fname, lineno);
        return -1;
    }
    return 0;
}

And you can read the entire file by calling that in a loop:

struct memory_word *
read_memory_file (const char *fname)
{
    struct memory_word *values = 0;
    void *ovalues;
    size_t nvalues = 0;
    size_t avalues = 0;

    char *linebuf = 0;
    size_t linesz = 0;

    FILE *fp = fopen(fname, "rt");
    if (!fp) {
        perror(fname);
        return 0;
    }

    while (getline(&linebuf, &linesz, fp) > 0) {
        nvalues++;
        if (nvalues > avalues) {
            avalues = (avalues == 0) ? 16 : avalues * 2;
            ovalues = values;
            values = reallocarray(values, avalues, sizeof(uint32_t));
            if (!values) {
                perror("realloc");
                free(ovalues);
                return 0;
            }
        }
        if (parse_line(&values[nvalues-1], linebuf, fname, nvalues)) {
            fclose(fp);
            free(values);
            return 0;
        }
    }

    if (ferror(fp)) {
        perror(fname);
        fclose(fp);
        free(values);
        return 0;
    }
    fclose(fp);
    return values;
}

(reallocarray is not part of the C standard, but it should be.  You can get a copy from the link.)


问:
Modal loading the header and footer instead of the just the attended page
I'm trying to use http://jquerymodal.com/ for a simple sign in modal. But for some reason clicking the link_to the modal. open up another view of the application html. Here is a screenshot:

Highlighted in blue there is the only thing that should be displayed but for some reason the entire application is being rendered... Here is my HTML for the page I want to render:

```<code><div id="modal">
  <h2>Sign In</h2>

  <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
    <div class="field">
      <%= f.email_field :email, class: "form-input", autofocus: true, placeholder: "Email" %>
    </div>

    <div class="field">
      <%= f.password_field :password, class: "form-input", autocomplete: "off", placeholder: "Password" %>
    </div>

    <% if devise_mapping.rememberable? -%>
      <div class="field">
        <%= f.check_box :remember_me %>
        <%= f.label :remember_me %>
      </div>
    <% end -%>

    <div class="actions">
      <%= f.submit "Log in" %>
    </div>
  <% end %>

  <%= render "devise/shared/links" %>
</div>
</code>```

MODAL OPEN

```<code><%= link_to "Sign In", new_user_session_path, class: "button", rel: "modal:open" %>
</code>```

I feel like I'm missing something obvious here. What could it be?

答:
Try taking

```<code><div ID="Modal"></div>
</code>```

Outside the container div. Because it is inheriting Box-size of it's parent element which is Container. And Another thing to note is that you'll be calling only modal ID through JQuery so Container Element's styling should not be inherited in modal element. So I think problem is that only.

Body:
I'm trying to use http://jquerymodal.com/ for a simple sign in modal. But for some reason clicking the link_to the modal. open up another view of the application html. Here is a screenshot:

Highlighted in blue there is the only thing that should be displayed but for some reason the entire application is being rendered... Here is my HTML for the page I want to render:

Sign In

  <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

      <%= f.email_field :email, class: "form-input", autofocus: true, placeholder: "Email" %>

      <%= f.password_field :password, class: "form-input", autocomplete: "off", placeholder: "Password" %>

    <% if devise_mapping.rememberable? -%>

        <%= f.check_box :remember_me %>
        <%= f.label :remember_me %>

    <% end -%>

      <%= f.submit "Log in" %>

  <% end %>

  <%= render "devise/shared/links" %>

MODAL OPEN

<%= link_to "Sign In", new_user_session_path, class: "button", rel: "modal:open" %>

I feel like I'm missing something obvious here. What could it be?

Body:
Try taking

<div ID="Modal"></div>

Outside the container div. Because it is inheriting Box-size of it's parent element which is Container. And Another thing to note is that you'll be calling only modal ID through JQuery so Container Element's styling should not be inherited in modal element. So I think problem is that only.


问:
error in my Times Table app in swift
I get the following error when I run my app:

```<code>import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var slider: UISlider!
    @IBOutlet var table: UITableView!

    internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50
    }

    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
        cell.textLabel?.text = String((Int(slider.value * 20)) * (indexPath.row + 1))
        return cell
    }
}
</code>```

答:
You should not be creating a new cell in each call to cellForRowAt. You should be using dequeueReusableCellWithIdentifier to try to recycle a cell. That's not the cause of your problem, but it's important nevertheless.

It's hard to be sure why you are crashing. Can you post the declaration of slider? My guess is that it's an implicitly unwrapped optional (declared with an !)

Does the declaration look something like this:

```<code>@IBoutlet var slider: UISlider!
</code>```

If so, set a breakpoint at the line that's crashing and check to see if slider is nil. (Although you usually get a different error about attempting to unwrap a nil optional when that's the cause.)

Title: error in my Times Table app in swift

Body:
I get the following error when I run my app:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet var slider: UISlider!
    @IBOutlet var table: UITableView!

    internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50
    }

    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
        cell.textLabel?.text = String((Int(slider.value * 20)) * (indexPath.row + 1))
        return cell
    }
}

Body:
You should not be creating a new cell in each call to cellForRowAt. You should be using dequeueReusableCellWithIdentifier to try to recycle a cell. That's not the cause of your problem, but it's important nevertheless.

It's hard to be sure why you are crashing. Can you post the declaration of slider? My guess is that it's an implicitly unwrapped optional (declared with an !)

Does the declaration look something like this:

@IBoutlet var slider: UISlider!

If so, set a breakpoint at the line that's crashing and check to see if slider is nil. (Although you usually get a different error about attempting to unwrap a nil optional when that's the cause.)


问:
Multiple tables show/hide refactor
Let us say I have multiple tables that display specific information, how would I go about displaying the selected table but hiding the others, in the cleanest way possible.

I have come up with the below which works as intended, but definitely not the cleanest way of doing it I am sure.

I have considered a few other methods such as jQuery append and toggle but haven't been able to come up with a viable solution.

```<code> <table id="table-1">
        <th>Table Heading</th>
        <tr>
            <td>Sample Text</td>
        </tr>

    </table>

    <table id="table-2">
        <th>Table Heading</th>
        <tr>
            <td>Sample Text</td>
        </tr>
    </table>

    <table id="table3">
        <tr>
            <th>Table Heading</td>
        </tr>
        <tr>
            <td>Sample Text</td>
        </tr>
    </table>
</code>```

jQuery

```<code>    $("#text-one").click(function () {
        $("#table-1").show();
        $("#table-2").hide();
        $("#table-3").hide();
    });

    $("#text-two").click(function () {
        $("#table-2").show();
        $("#table-1").hide();
        $("#table-3").hide();
    });

    $("#text-three").click(function () {
        $("#table-3").show();
        $("#table-1").hide();
        $("#table-2").hide();
    });
</code>```

答:
You can persist the target in custom data-* prefixed attribute, which can be accessed using .data().

Add a common class to BUTTON and TABLE elements, then Class Selector (".class") can be used to bind event handler.

HTML

```<code><button type="button" class="btn" data-target="#table-1">Button 1</button>
<button type="button" class="btn" data-target="#table-2">Button 2</button>
<button type="button" class="btn" data-target="#table-3">Button 3</button>

<table class="table" id="table-1"></table>
<table class="table" id="table-2"></table>
<table class="table" id="table-3"></table>
</code>```

Script

```<code>$(".btn").click(function () {
    var targetSelector =$(this).data('target');
    var target = $(targetSelector);
    target.show();
    $(".table").not(target).hide();
});
</code>```

$(".btn").click(function() {
  var targetSelector = $(this).data('target');
  var target = $(targetSelector);
  target.show();
  $(".table").not(target).hide();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.table {
  display: none
}</code>```

<button type="button" class="btn" data-target="#table-1">Button 1</button>
<button type="button" class="btn" data-target="#table-2">Button 2</button>
<button type="button" class="btn" data-target="#table-3">Button 3</button>

    Table Heading 1

    Sample Text

    Table Heading 2

    Sample Text

    Table Heading 3

    Sample Text

```

Title: Multiple tables show/hide refactor

Body:
Let us say I have multiple tables that display specific information, how would I go about displaying the selected table but hiding the others, in the cleanest way possible.

I have come up with the below which works as intended, but definitely not the cleanest way of doing it I am sure.

I have considered a few other methods such as jQuery append and toggle but haven't been able to come up with a viable solution.

        Table Heading

            Sample Text

        Table Heading

            Sample Text

            Table Heading

            Sample Text

jQuery

    $("#text-one").click(function () {
        $("#table-1").show();
        $("#table-2").hide();
        $("#table-3").hide();
    });

    $("#text-two").click(function () {
        $("#table-2").show();
        $("#table-1").hide();
        $("#table-3").hide();
    });

    $("#text-three").click(function () {
        $("#table-3").show();
        $("#table-1").hide();
        $("#table-2").hide();
    });

Body:
You can persist the target in custom data-* prefixed attribute, which can be accessed using .data().

Add a common class to BUTTON and TABLE elements, then Class Selector (".class") can be used to bind event handler.

HTML

<button type="button" class="btn" data-target="#table-1">Button 1</button>
<button type="button" class="btn" data-target="#table-2">Button 2</button>
<button type="button" class="btn" data-target="#table-3">Button 3</button>

<table class="table" id="table-1"></table>
<table class="table" id="table-2"></table>
<table class="table" id="table-3"></table>

Script

$(".btn").click(function () {
    var targetSelector =$(this).data('target');
    var target = $(targetSelector);
    target.show();
    $(".table").not(target).hide();
});

$(".btn").click(function() {
  var targetSelector = $(this).data('target');
  var target = $(targetSelector);
  target.show();
  $(".table").not(target).hide();
});

.table {
  display: none
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn" data-target="#table-1">Button 1</button>
<button type="button" class="btn" data-target="#table-2">Button 2</button>
<button type="button" class="btn" data-target="#table-3">Button 3</button>

<table class="table" id="table-1">
  <tr>
    <th>Table Heading 1</th>
  </tr>
  <tr>
    <td>Sample Text</td>
  </tr>
</table>

<table class="table" id="table-2">
  <tr>
    <th>Table Heading 2</th>
  </tr>
  <tr>
    <td>Sample Text</td>
  </tr>
</table>
<table class="table" id="table-3">
  <tr>
    <th>Table Heading 3</th>
  </tr>
  <tr>
    <td>Sample Text</td>
  </tr>
</table>


答:
```<code>   <div id="ex1" style="display:none;">
    <p>modal text........<a href="#" rel="modal:close">Close</a> or press ESC</p>
   </div>

   <p><a href="#ex1" rel="modal:open">Open Modal</a></p>
</code>```

Title: Modal loading the header and footer instead of the just the attended page


问:
Google maps - keep center when zooming
In Google Maps, I would like to be able to keep the center of the map on a marker on my location when I'm zooming in or out. It's something that Ingress does, it doesn't matter where you double tap (or double click) or where you pinch, the map remains centered on your marker. So it's possible...

The best I came up with for now is :

```<code>google.maps.event.addListener(mymap, 'zoom_changed', function() {
    mymap.setCenter({lat: myLoc.lat, lng: myLoc.lon});
})
</code>```

But it's far from perfect, it just re-center the map after the user already zoomed...

Thanks a lot !

[EDIT] absolutely nothing helps in the API ref... Or elsewhere I'm blind and missed it !

答:
Unfortunately Google Maps Api does not provide this behaviour.

The following example doesn't require jQuery and supports double-click and mouse scrolling, but you can add more events if you want.

View in Codepen

Disable:

Double-clickin

Scrolling

Panning

Add dblclick and zoom_changed events on the map and a mousewheel event on the canvas.

I have commented the code, hopefully this works for your case. Keep in mind that you need to normalize mousewheel speed for all browsers and devices. Hammer.js is a good library for that.

var map, zoom;

function initialize() {

  // The white house!
  var myLatLng = new google.maps.LatLng(38.8977, -77.0365);

  // Default zoom level
  zoom = 17;

  // Keep a reference for evens
  var $map = document.getElementById("map");

  // Disable scrolling + double-click + dragging
  map = new google.maps.Map($map, {
    zoom: zoom,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    scrollwheel: false,
    disableDoubleClickZoom: true,
    //draggable: false
  });

  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map
  });

  // EVENTS

  // Double Click: event zoom by 1
  map.addListener('dblclick', function(e) {
    zoomHandler(e.latLng, 1);
  });

  // Zoom changed: update current zoom level
  map.addListener('zoom_changed', function(e) {
    // Using a timeout because `getZoom()` does not return a promise.
    setTimeout(function() {
      zoom = map.getZoom();
    }, 50);

  });

  // Dom event: On mousewheel
  $map.addEventListener('mousewheel', wheelEvent, true);
}

// Mouse Scrolling event
function wheelEvent(event) {
  if (event.deltaY > 1)
    zoomHandler(event, -1);
  else
    zoomHandler(event, 1);
}

// Zoom in/out
function zoomHandler(event, zoomin) {
  zoom += zoomin;
  map.setZoom(zoom);
}

google.maps.event.addDomListener(window, 'load', initialize);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map {
  width: 100%;
  height: 240px;
}</code>```

```

Title: Google maps - keep center when zooming

Body:
In Google Maps, I would like to be able to keep the center of the map on a marker on my location when I'm zooming in or out. It's something that Ingress does, it doesn't matter where you double tap (or double click) or where you pinch, the map remains centered on your marker. So it's possible...

The best I came up with for now is :

google.maps.event.addListener(mymap, 'zoom_changed', function() {
    mymap.setCenter({lat: myLoc.lat, lng: myLoc.lon});
})

But it's far from perfect, it just re-center the map after the user already zoomed...

Thanks a lot !

[EDIT] absolutely nothing helps in the API ref... Or elsewhere I'm blind and missed it !

Body:
Unfortunately Google Maps Api does not provide this behaviour.

The following example doesn't require jQuery and supports double-click and mouse scrolling, but you can add more events if you want.

View in Codepen

Disable:

Double-clickin

Scrolling

Panning

Add dblclick and zoom_changed events on the map and a mousewheel event on the canvas.

I have commented the code, hopefully this works for your case. Keep in mind that you need to normalize mousewheel speed for all browsers and devices. Hammer.js is a good library for that.

var map, zoom;

function initialize() {

  // The white house!
  var myLatLng = new google.maps.LatLng(38.8977, -77.0365);

  // Default zoom level
  zoom = 17;

  // Keep a reference for evens
  var $map = document.getElementById("map");

  // Disable scrolling + double-click + dragging
  map = new google.maps.Map($map, {
    zoom: zoom,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    scrollwheel: false,
    disableDoubleClickZoom: true,
    //draggable: false
  });

  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map
  });

  // EVENTS

  // Double Click: event zoom by 1
  map.addListener('dblclick', function(e) {
    zoomHandler(e.latLng, 1);
  });

  // Zoom changed: update current zoom level
  map.addListener('zoom_changed', function(e) {
    // Using a timeout because `getZoom()` does not return a promise.
    setTimeout(function() {
      zoom = map.getZoom();
    }, 50);

  });

  // Dom event: On mousewheel
  $map.addEventListener('mousewheel', wheelEvent, true);
}

// Mouse Scrolling event
function wheelEvent(event) {
  if (event.deltaY > 1)
    zoomHandler(event, -1);
  else
    zoomHandler(event, 1);
}

// Zoom in/out
function zoomHandler(event, zoomin) {
  zoom += zoomin;
  map.setZoom(zoom);
}

google.maps.event.addDomListener(window, 'load', initialize);

#map {
  width: 100%;
  height: 240px;
}

<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC9d3jaUX6Qdr0Uzvq6fQXVmZ1PBuHEVAQ"></script>


问:
CPropertyPage dialogue OnOk should not close the dialogue if there is an error
I have a class which inherits from CPropertyPage class. I have a OnOk() method and a OnKillActive() method.
Whenever I press Ok on the dialogue. OnKillActive() gets called but OnOk() is never called.
The problem is depending on a condition I do not want to close the dialogue on pressing Ok. But the dialogue is closing on pressing Ok.

How do I prevent the dialogue from closing when I press Ok?

Code:

```<code>In MyClass.h:
    class MyClass : public CPropertyPage {
    }

In MyClass.cpp:
    void MyClass::OnOK(){
        if (condition true) {
            return; // This should prevent the dialogue from closing but still      the dialogue closes
        }
        return CPropertyPage::OnOk();
    }

    BOOL MyClass::OnKillActive() {
        if (condition true) {
            CDialog::DoModal();
            return FALSE; // This should prevent the dialogue from closing but   still the dialogue closes
        }
        return CPropertyPage::OnKillActive();
    }
</code>```

答:
I am not sure if you can call CDialog::DoModal(); as your property page is  not closed yet.

When this event(OnKillActive()) occurs your property page is inactive. But your property page still exists and the data in the property page also exists for validation.

To bring your page back, just set the focus in one of the dialog item. Use "GetDlgItem" to get an object and set the focus using "SetFocus"

An example is available here.

https://msdn.microsoft.com/en-us/library/2122ct0z.aspx

Body:
I have a class which inherits from CPropertyPage class. I have a OnOk() method and a OnKillActive() method.
Whenever I press Ok on the dialogue. OnKillActive() gets called but OnOk() is never called.
The problem is depending on a condition I do not want to close the dialogue on pressing Ok. But the dialogue is closing on pressing Ok.

How do I prevent the dialogue from closing when I press Ok?

Code:

In MyClass.h:
    class MyClass : public CPropertyPage {
    }

In MyClass.cpp:
    void MyClass::OnOK(){
        if (condition true) {
            return; // This should prevent the dialogue from closing but still      the dialogue closes
        }
        return CPropertyPage::OnOk();
    }

    BOOL MyClass::OnKillActive() {
        if (condition true) {
            CDialog::DoModal();
            return FALSE; // This should prevent the dialogue from closing but   still the dialogue closes
        }
        return CPropertyPage::OnKillActive();
    }


问:
PHP header redirect not working
I know this has been covered before but I cannot find an answer to this,

I have always used this;

```<code>header("Location: http://www.website.com/");
exit();
</code>```

This has always worked in my current project and all of a sudden it is not working in any of my browsers

I would like to figure out the problem and fix it instead of using

```<code>echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>";
</code>```

I also have error reporting enabled and it shows no errors

```<code>// SET ERROR REPORTING
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
ini_set('display_errors', TRUE);
</code>```

Any ideas why it will not work?

答:
Try this (working for me):

echo '';

Instead of

header("Location: http://www.example.com");

Title: PHP header redirect not working

Body:
I know this has been covered before but I cannot find an answer to this,

I have always used this;

header("Location: http://www.website.com/");
exit();

This has always worked in my current project and all of a sudden it is not working in any of my browsers

I would like to figure out the problem and fix it instead of using

echo "";

I also have error reporting enabled and it shows no errors

// SET ERROR REPORTING
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
ini_set('display_errors', TRUE);

Any ideas why it will not work?

Body:
Try this (working for me):

echo '<script>window.location.replace("http://www.example.com")</script>';

Instead of

header("Location: http://www.example.com");


问:
Hide status bar in UWP
I have used below code to hide status bar in UWP. When I run the app in development mode in my computer the status bar is not shown in windows phone. I deployed the app in Windows Store, after downloading the app, I see the status bar appears in my app.

Here is my code:

```<code>var isAvailable = Windows.Foundation.Metadata.ApiInformation.IsTypePresent(typeof(StatusBar).ToString());
   if (isAvailable)
       hideBar();

async void hideBar()
{
   StatusBar bar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
   await bar.HideAsync();
}
</code>```

The question is, why the above code shouldn't work in windows store?
Also, I have the link to my app App link in windows store, but when i search for exact key word in windows store, my application is not shown in windows store, but clicking in link would appear my app in window store.

Thanks!

答:
This code won't work because after .Net Native compilation (which Store does) typeof(StatusBar).ToString() will not return the literal type name as you expect, but will return something like "EETypeRVA:0x00021968". Use literal string instead (you aren't going to rename StatusBar, right? ;) or use IsApiContractPresent or typeof(StatusBar).FullName (as was already advised).
P.S. The same issue can be reproduced without publishing, just run it using Release configuration.

Title: Hide status bar in UWP

Body:
I have used below code to hide status bar in UWP. When I run the app in development mode in my computer the status bar is not shown in windows phone. I deployed the app in Windows Store, after downloading the app, I see the status bar appears in my app.

Here is my code:

var isAvailable = Windows.Foundation.Metadata.ApiInformation.IsTypePresent(typeof(StatusBar).ToString());
   if (isAvailable)
       hideBar();

async void hideBar()
{
   StatusBar bar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
   await bar.HideAsync();
}

The question is, why the above code shouldn't work in windows store?
Also, I have the link to my app App link in windows store, but when i search for exact key word in windows store, my application is not shown in windows store, but clicking in link would appear my app in window store.

Thanks!