问:
Huge memory usage in notifications
I am developing an application with a service which show the progress of a timer in the notification area (with a progress bar and a text). I have extracted below a simpler example with the same problem.

The code of the Service:

```<code>public class TNService extends Service {
    private NotificationManager nm;
    private Notification notification;
    private RemoteViews remoteView;

    @Override
    public void onCreate () {
        nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        notification = new Notification(android.R.drawable.stat_sys_download,
                "My notification",
                System.currentTimeMillis());
        remoteView = new RemoteViews(this.getPackageName(),
                R.layout.notification);
        remoteView.setImageViewResource(R.id.icon, android.R.drawable.stat_sys_download);
        remoteView.setTextViewText(R.id.text, "");
        remoteView.setProgressBar(R.id.progress, 100, 0, false);
        notification.flags = Notification.FLAG_NO_CLEAR;
        notification.contentView = remoteView;
        notification.contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                TNActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        Timer timer = new Timer ();
        timer.schedule(new TNTask(this), 0, 200);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    public void updateNotification(int progress) {
        remoteView.setProgressBar(R.id.progress, 1000, progress, false);
        remoteView.setTextViewText(R.id.text, "Progress: " + progress);
        nm.notify(0, notification);
    }
}
</code>```

The code of the TimerTask:

```<code>public class TNTask extends TimerTask {
    private TNService service;
    private int progress;

    public TNTask(TNService s) {
        this.service = s;
        this.progress = 0;
    }

    @Override
    public void run() {
            progress = (progress + 1) % 1000;
        this.service.updateNotification (progress);
    }
}
</code>```

The problem is the huge memory usage. Here is the logcat output:

```<code>D/dalvikvm(11985): GC_EXPLICIT freed 1258 objects / 84016 bytes in 1157ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 52216 objects / 1900968 bytes in 130ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 49465 objects / 1805248 bytes in 125ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 53106 objects / 1909992 bytes in 134ms
D/dalvikvm(12008): GC_EXPLICIT freed 1604 objects / 100944 bytes in 90ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 53011 objects / 1937160 bytes in 135ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 49806 objects / 1817992 bytes in 143ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 49016 objects / 1769536 bytes in 135ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 53509 objects / 1941064 bytes in 145ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 49895 objects / 1842312 bytes in 146ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 48728 objects / 1774496 bytes in 150ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 47557 objects / 1701976 bytes in 146ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 53540 objects / 1903808 bytes in 156ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 48997 objects / 1784048 bytes in 158ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 48326 objects / 1776864 bytes in 158ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 47566 objects / 1742488 bytes in 169ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 47606 objects / 1703416 bytes in 170ms
D/dalvikvm(  162): GC_EXPLICIT freed 11238 objects / 641368 bytes in 1064ms
</code>```

I think it is too much memory and after a while the phone hangs with this output:

```<code>D/dalvikvm(   85): GC_FOR_MALLOC freed 0 objects / 0 bytes in 241ms
I/dalvikvm-heap(   85): Clamp target GC heap from 24.008MB to 24.000MB
I/dalvikvm-heap(   85): Grow heap (frag case) to 24.000MB for 52-byte allocation
I/dalvikvm-heap(   85): Clamp target GC heap from 26.008MB to 24.000MB
D/dalvikvm(   85): GC_FOR_MALLOC freed 0 objects / 0 bytes in 241ms
I/dalvikvm-heap(   85): Clamp target GC heap from 24.008MB to 24.000MB
I/dalvikvm-heap(   85): Grow heap (frag case) to 24.000MB for 24-byte allocation
I/dalvikvm-heap(   85): Clamp target GC heap from 26.008MB to 24.000MB
D/dalvikvm(   85): GC_FOR_MALLOC freed 0 objects / 0 bytes in 247ms
I/dalvikvm-heap(   85): Clamp target GC heap from 24.009MB to 24.000MB
I/dalvikvm-heap(   85): Grow heap (frag case) to 24.000MB for 28-byte allocation
I/dalvikvm-heap(   85): Clamp target GC heap from 26.009MB to 24.000MB
D/dalvikvm(   85): GC_FOR_MALLOC freed 0 objects / 0 bytes in 247ms
I/dalvikvm-heap(   85): Clamp target GC heap from 24.009MB to 24.000MB
</code>```

Anyone knows how can I do it without using so many memory?

Thanks!

答:
The problem with this workaround is that if it's an ongoing notification, it will "hop" on the status bar and notification pane as other ongoing notifications are updated.

I've tried several things, including declaring the RemoteView and Notification members as volatile (because RemoteView is cross-thread), which seemed to work, but only slowed down the problem.

What I settled on was using a choke member, and "cacheing" the RemoteView and Notification up to X times, then recreating them.

When their members are set to null, the small leak seems to be freed.

Title: Huge memory usage in notifications

Body:
I am developing an application with a service which show the progress of a timer in the notification area (with a progress bar and a text). I have extracted below a simpler example with the same problem.

The code of the Service:

public class TNService extends Service {
    private NotificationManager nm;
    private Notification notification;
    private RemoteViews remoteView;

    @Override
    public void onCreate () {
        nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        notification = new Notification(android.R.drawable.stat_sys_download,
                "My notification",
                System.currentTimeMillis());
        remoteView = new RemoteViews(this.getPackageName(),
                R.layout.notification);
        remoteView.setImageViewResource(R.id.icon, android.R.drawable.stat_sys_download);
        remoteView.setTextViewText(R.id.text, "");
        remoteView.setProgressBar(R.id.progress, 100, 0, false);
        notification.flags = Notification.FLAG_NO_CLEAR;
        notification.contentView = remoteView;
        notification.contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                TNActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        Timer timer = new Timer ();
        timer.schedule(new TNTask(this), 0, 200);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    public void updateNotification(int progress) {
        remoteView.setProgressBar(R.id.progress, 1000, progress, false);
        remoteView.setTextViewText(R.id.text, "Progress: " + progress);
        nm.notify(0, notification);
    }
}

The code of the TimerTask:

public class TNTask extends TimerTask {
    private TNService service;
    private int progress;

    public TNTask(TNService s) {
        this.service = s;
        this.progress = 0;
    }

    @Override
    public void run() {
            progress = (progress + 1) % 1000;
        this.service.updateNotification (progress);
    }
}

The problem is the huge memory usage. Here is the logcat output:

D/dalvikvm(11985): GC_EXPLICIT freed 1258 objects / 84016 bytes in 1157ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 52216 objects / 1900968 bytes in 130ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 49465 objects / 1805248 bytes in 125ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 53106 objects / 1909992 bytes in 134ms
D/dalvikvm(12008): GC_EXPLICIT freed 1604 objects / 100944 bytes in 90ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 53011 objects / 1937160 bytes in 135ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 49806 objects / 1817992 bytes in 143ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 49016 objects / 1769536 bytes in 135ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 53509 objects / 1941064 bytes in 145ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 49895 objects / 1842312 bytes in 146ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 48728 objects / 1774496 bytes in 150ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 47557 objects / 1701976 bytes in 146ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 53540 objects / 1903808 bytes in 156ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 48997 objects / 1784048 bytes in 158ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 48326 objects / 1776864 bytes in 158ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 47566 objects / 1742488 bytes in 169ms
D/dalvikvm(   85): GC_FOR_MALLOC freed 47606 objects / 1703416 bytes in 170ms
D/dalvikvm(  162): GC_EXPLICIT freed 11238 objects / 641368 bytes in 1064ms

I think it is too much memory and after a while the phone hangs with this output:

D/dalvikvm(   85): GC_FOR_MALLOC freed 0 objects / 0 bytes in 241ms
I/dalvikvm-heap(   85): Clamp target GC heap from 24.008MB to 24.000MB
I/dalvikvm-heap(   85): Grow heap (frag case) to 24.000MB for 52-byte allocation
I/dalvikvm-heap(   85): Clamp target GC heap from 26.008MB to 24.000MB
D/dalvikvm(   85): GC_FOR_MALLOC freed 0 objects / 0 bytes in 241ms
I/dalvikvm-heap(   85): Clamp target GC heap from 24.008MB to 24.000MB
I/dalvikvm-heap(   85): Grow heap (frag case) to 24.000MB for 24-byte allocation
I/dalvikvm-heap(   85): Clamp target GC heap from 26.008MB to 24.000MB
D/dalvikvm(   85): GC_FOR_MALLOC freed 0 objects / 0 bytes in 247ms
I/dalvikvm-heap(   85): Clamp target GC heap from 24.009MB to 24.000MB
I/dalvikvm-heap(   85): Grow heap (frag case) to 24.000MB for 28-byte allocation
I/dalvikvm-heap(   85): Clamp target GC heap from 26.009MB to 24.000MB
D/dalvikvm(   85): GC_FOR_MALLOC freed 0 objects / 0 bytes in 247ms
I/dalvikvm-heap(   85): Clamp target GC heap from 24.009MB to 24.000MB

Anyone knows how can I do it without using so many memory?

Thanks!


来源: stackexchange

问:
How do I append to a csv file all into one cell, without using lists.(Python3.5)
My code looks like this.

```<code>    import csv
    name = input("entername")
    with open('details.csv','a') as csvDataFile:
        csvWriter = csv.writer(csvDataFile)
        csvWriter.writerow(name)
</code>```

When i run it, and say my name was name, the csv file would look like this:

```<code>n a m e
</code>```

with each of the letters being in seperate cells, how do i get them into one, without using a list.

答:
Try,

```<code>csvWriter.writerow([name])
</code>```

writerow() is expecting an iterable of strings, https://docs.python.org/2/library/csv.html#csv.csvwriter.writerow

if you give "hello", it will write h, e, l, l, o

if you give ["hello", "world"],  it will write as hello, world

ContentLicense: CC BY-SA 3.0

Body:
My code looks like this.

    import csv
    name = input("entername")
    with open('details.csv','a') as csvDataFile:
        csvWriter = csv.writer(csvDataFile)
        csvWriter.writerow(name)

When i run it, and say my name was name, the csv file would look like this:

n a m e

with each of the letters being in seperate cells, how do i get them into one, without using a list.

Body:
Try,

csvWriter.writerow([name])

writerow() is expecting an iterable of strings, https://docs.python.org/2/library/csv.html#csv.csvwriter.writerow

if you give "hello", it will write h, e, l, l, o

if you give ["hello", "world"],  it will write as hello, world


问:
Symfony + Doctrine: Strange parameters injection in the action method
I'm using Symfony and Doctrine in my project. And I noticed one strange (for me) thing.

I have simple action in my controller:

```<code>    /**
     * @param Request      $request
     * @param Product|null $product
     *
     * @Config\Route("/{category}/create", name="my_project_create_product")
     * @Config\Route("/{category}/edit/{product}", name="my_project_edit_product")
     * @Config\Template()
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function createEditAction(Request $request, ProductCategory $category, Product $product = null)
</code>```

The product parameter is optional and using only for edit action as you can see in my annotation.

The problem is that when I use url /{category}/create it somehow injects the product object (it's the first product in my collection with the given category). However, the product parameter expected to be null.

The question is how the product parameter injects by itself if I don't pass it to url?

P.S The product has the reference to category. And this only happens if I use the category parameter in the method.

Symfony version 3.3.4

Thank you for your help!

答:
After some investigations and debugging I actually found the solution to that problem.

I really didn't know that ParamConverter "will attempt to do a findOneBy() fetch by using all of the wildcards in your route that are actually properties on your entity (non-properties are ignored)". (source link). So if it doesn't find by id (primary key) it will tries to search by criteria. There are some ways to fix that (and all options could be found here). However, I chose to exclude the category from product mapping:

```<code> /**
 * @param Request      $request
 * @param Product|null $product
 *
 * @Config\Route("/{category}/create", name="my_project_create_product")
 * @Config\Route("/{category}/edit/{product}", name="my_project_edit_product")
 * @Config\ParamConverter("product", options={"exclude": {"category"}})
 * @Config\Template()
 *
 * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
 */
public function createEditAction(Request $request, ProductCategory $category, Product $product = null)
</code>```

Actually, this line "@Config\ParamConverter("product", options={"exclude": {"category"}})" solves the entire issue.

Hope, this will help someone and will save some time.

Body:
I'm using Symfony and Doctrine in my project. And I noticed one strange (for me) thing.

I have simple action in my controller:

    /**
     * @param Request      $request
     * @param Product|null $product
     *
     * @Config\Route("/{category}/create", name="my_project_create_product")
     * @Config\Route("/{category}/edit/{product}", name="my_project_edit_product")
     * @Config\Template()
     *
     * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function createEditAction(Request $request, ProductCategory $category, Product $product = null)

The product parameter is optional and using only for edit action as you can see in my annotation.

The problem is that when I use url /{category}/create it somehow injects the product object (it's the first product in my collection with the given category). However, the product parameter expected to be null.

The question is how the product parameter injects by itself if I don't pass it to url?

P.S The product has the reference to category. And this only happens if I use the category parameter in the method.

Symfony version 3.3.4

Thank you for your help!

Body:
After some investigations and debugging I actually found the solution to that problem.

I really didn't know that ParamConverter "will attempt to do a findOneBy() fetch by using all of the wildcards in your route that are actually properties on your entity (non-properties are ignored)". (source link). So if it doesn't find by id (primary key) it will tries to search by criteria. There are some ways to fix that (and all options could be found here). However, I chose to exclude the category from product mapping:

 /**
 * @param Request      $request
 * @param Product|null $product
 *
 * @Config\Route("/{category}/create", name="my_project_create_product")
 * @Config\Route("/{category}/edit/{product}", name="my_project_edit_product")
 * @Config\ParamConverter("product", options={"exclude": {"category"}})
 * @Config\Template()
 *
 * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
 */
public function createEditAction(Request $request, ProductCategory $category, Product $product = null)

Actually, this line "@Config\ParamConverter("product", options={"exclude": {"category"}})" solves the entire issue.

Hope, this will help someone and will save some time.


问:
Play multiple instances of an html5's Audio object
I'm making a small game in Javascript and it requires some audio for better user experience.
The main issue I have is that I have to play 1 song/sound multiple times, and sometimes at the same time.
However, if I cloneNode the Audio object, the audio is downloaded one more time from the server, and so is only played latter, as it has to be downloaded first. So the sound can be downloaded over 100 times during normal game !

As I coulnd't find an answer on Internet, I'm asking you :)

Please note, that I want to do that with my own code, and not with a library.

答:
I have not tested this, but it might be worth trying to use data URIs for the src of the audio clips that need to be played simultaneously. This would prevent the server hit when you clone the element - although the fact that it is downloaded each time really sounds like a browser bug. I would think it should be pulled from browser cache.

Looks like someone has tried this already: Is it possible to use data URIs in video and audio tags?

ContentLicense: CC BY-SA 2.5


问:
Preprocessor batch for all structure members
Is it possible to write a preprocessor macro that automatically iterates for all members of a structure?

I have such a structure (automatically generated from a Simulink model):

```<code>typedef struct {
  real_T driveStatusword;
  real_T posSensor[2];
  real_T softAbortDemand;
} ExtU_motionCtrlRTOS_T;
</code>```

And a similar one:

```<code>struct CoreInputOffsets
{
    uint32_t driveStatusword;
    uint32_t posSensor;
    uint32_t softAbortDemand;
};
</code>```

And I would like to do such an operation:

```<code>void getCoreInputOffsets(CoreInputOffsets* pCoreInputOffsets)
{
    pCoreInputOffsets->driveStatusword = offsetof(ExtU_motionCtrlRTOS_T, driveStatusword);
    pCoreInputOffsets->posSensor = offsetof(ExtU_motionCtrlRTOS_T, posSensor);
    pCoreInputOffsets->softAbortDemand = offsetof(ExtU_motionCtrlRTOS_T, softAbortDemand);
}
</code>```

But without having to edit this function each time the structure changes, by iterating for all members of CoreInputOffsets.

答:
There are no "automatic" means, no.

And unfortunately your structures are automatically generated. If they were under your full control, I'd recommend the REFLECTABLE macro like it is described here.

Please read that answer, maybe you can restructure your code and/or work flow to make it work?

Body:
Is it possible to write a preprocessor macro that automatically iterates for all members of a structure?

I have such a structure (automatically generated from a Simulink model):

typedef struct {
  real_T driveStatusword;
  real_T posSensor[2];
  real_T softAbortDemand;
} ExtU_motionCtrlRTOS_T;

And a similar one:

struct CoreInputOffsets
{
    uint32_t driveStatusword;
    uint32_t posSensor;
    uint32_t softAbortDemand;
};

And I would like to do such an operation:

void getCoreInputOffsets(CoreInputOffsets* pCoreInputOffsets)
{
    pCoreInputOffsets->driveStatusword = offsetof(ExtU_motionCtrlRTOS_T, driveStatusword);
    pCoreInputOffsets->posSensor = offsetof(ExtU_motionCtrlRTOS_T, posSensor);
    pCoreInputOffsets->softAbortDemand = offsetof(ExtU_motionCtrlRTOS_T, softAbortDemand);
}

But without having to edit this function each time the structure changes, by iterating for all members of CoreInputOffsets.


问:
Proc.new binding change and loops logic abstraction
I've two loops in two different methods which look very similar. I wanted to abstract most of their logic in a Proc.new

This works

```<code>def matches_base?
  proc_exec = Proc.new do |subclass, breakpoint|
    # next and return are meant to act inside the loop and quit it if needed
    response = process_match(subclass)
    next if response == :continue
    return true if response == false

    return response
  end

  subclasses(BASE_NAMESPACE).each do |subclass|
    proc_exec.call(subclass)
  end
  false
end
</code>```

The obvious issue here is the proc_exec is defined inside the method itself, but I want to use it in another method

```<code>def matches_breakpoints?
  breakpoints.fetch.each do |breakpoint|
    # I want to include the proc_exec here too
  end
  false
end
</code>```

So I just tried to extract it at the class level like so

This does not work

```<code>def proc_exec
  Proc.new do |subclass, breakpoint|
    response = process_match(subclass)
    next if response == :continue
    return true if response == false

    return response
  end
end

def matches_base?
  subclasses(BASE_NAMESPACE).each do |subclass|
    proc_exec.call(subclass)
  end
  false
end
</code>```

Then I could have called it like proc_exec.call from within both instance methods. Currently it throws

```<code> LocalJumpError:
   unexpected return
</code>```

I tried many tricks such as instance_eval or instance_exec without success. I'm out of solution right now.

Easily executable, simplified example of what I want below.

```<code>class MyLoops
  def proc_exec
    Proc.new do |num|
      next if num == 1
      # we want this `return` to act in the method context
      # as it would do if I defined it inside a method directly
      return if num == 4
      puts "Current number : #{num}"
    end
  end

  def method_a
    [0,1,2].each do |num|
      proc_exec.call(num)
    end
    false
  end

  def method_b
    [3,4,5].each do |num|
      proc_exec.call(num)
    end
  end
  # this `false` below should never be reached ; that's the trick
  false
end

loops = MyLoops.new
loops.method_a
loops.method_b
</code>```

答:
You can't have your cake and eat it too. If you want return from the proc to abort the method, it must be in the method's lexical scope* (which is another way to say "it must be defined within the same method").

An alternative is to have proc/lambda return a "stop" value, which caller will use to abort its execution.

(Your experiments with instance_eval/instance_exec were misdirected, sadly. Those methods only change current self. This problem has nothing to do with current self, but rather current lexical scope, in which return is executed.)

* The error you're getting, it is caused by return trying to return from a method that is no longer running (proc_exec).

Body:
I've two loops in two different methods which look very similar. I wanted to abstract most of their logic in a Proc.new

This works

def matches_base?
  proc_exec = Proc.new do |subclass, breakpoint|
    # next and return are meant to act inside the loop and quit it if needed
    response = process_match(subclass)
    next if response == :continue
    return true if response == false

    return response
  end

  subclasses(BASE_NAMESPACE).each do |subclass|
    proc_exec.call(subclass)
  end
  false
end

The obvious issue here is the proc_exec is defined inside the method itself, but I want to use it in another method

def matches_breakpoints?
  breakpoints.fetch.each do |breakpoint|
    # I want to include the proc_exec here too
  end
  false
end

So I just tried to extract it at the class level like so

This does not work

def proc_exec
  Proc.new do |subclass, breakpoint|
    response = process_match(subclass)
    next if response == :continue
    return true if response == false

    return response
  end
end

def matches_base?
  subclasses(BASE_NAMESPACE).each do |subclass|
    proc_exec.call(subclass)
  end
  false
end

Then I could have called it like proc_exec.call from within both instance methods. Currently it throws

 LocalJumpError:
   unexpected return

I tried many tricks such as instance_eval or instance_exec without success. I'm out of solution right now.

Easily executable, simplified example of what I want below.

class MyLoops
  def proc_exec
    Proc.new do |num|
      next if num == 1
      # we want this `return` to act in the method context
      # as it would do if I defined it inside a method directly
      return if num == 4
      puts "Current number : #{num}"
    end
  end

  def method_a
    [0,1,2].each do |num|
      proc_exec.call(num)
    end
    false
  end

  def method_b
    [3,4,5].each do |num|
      proc_exec.call(num)
    end
  end
  # this `false` below should never be reached ; that's the trick
  false
end

loops = MyLoops.new
loops.method_a
loops.method_b


问:
Where is deployed content for JBoss AS 7
I am new to JBoss AS 7. I have tried to deploy my war file on JBoss AS 7, which seems working fine. My question is where I can see the deployed content.

I would expect it to be like Tomcat, it should have a explored war folder some where to hold the deployed content. Is there such thing for JBoss AS 7.

答:
you can find your deployed jars here:
$JBOSS_HOME/standalone/tmp/vfs/deployment/</p>


问:
Populate select options from database to dynamic select option using jQuery
From the database I have selected the names of the members as the select options. With jQuery, I have a dynamic Add button that adds new select field with the append function. But what could be the standard way to pass my select options generated by php in the append?

I have researched for a while but could not get it working. So any suggestions would be really helpful.

This is the page structure. It looks messy but please have a look at it. I have passed the $members as <?php echo $members; ?> in a static select that already is there from the beginning, but for the dynamic ones, I have created a variable var members and tried to pass it in the append but it is not working.

```<code><?php
   require_once 'db_connect.php';

   $members = '';
   $query = "SELECT memberID, memberName FROM members";
   $result = mysqli_query($connect, $query);
   while($row = mysqli_fetch_array($result))
   {
    $members .= '<option value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
   }
   ?>
<script>
   var members = "<?php echo $members; ?>";

   $(document).ready(function() {
          var fixHelperModified = function(e, div) {
                var $originals = div.children();
                var $helper = div.clone();
                $helper.children().each(function(index) {
                   $(this).width($originals.eq(index).width())
                });
                return $helper;
             },
             updateIndex = function() {
                $('div.index').each(function(i) {
                   $(this).html(i + 1);
                });
             };
          $("#add").sortable({
             helper: fixHelperModified,
             stop: updateIndex
          }).disableSelection();
          $("#addNew").click(function() {
             $('#add').append("<div class='row rem' id='move'><div class='col-md-1 index'>1. </div><div class='col-md-9'><select name='members[]'><option value=''>Select member</option>"+members+"</select></div><div class='col-md-1'><button class='delete btn btn-warning btn-xs'>Delete</button></div></div>");
             updateIndex();
          });
          $("body").on('click', '#add .delete', function() {
             $(this).closest(".rem").remove();
             updateIndex();
          });
       });
</script>
<form method="post">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <select name='members[]'>
                           <option value=''>Select member</option>
                           <?php echo $members; ?>
                        </select>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>
</code>```

Here is a snippet of the form without the php if you need to see the jQuery in action.

    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("

1.

<select name='members[]'><option value=''>Select member</option></select>

<button class='delete btn btn-warning btn-xs'>Delete</button>

");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<form method="post">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <select name='members[]'>
                        <option value=''>Select member</option>
                        <option value='First'>First</option>
                        <option value='Second'>Second</option>
                        </select>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form></code>```

答:
I dont understand your many code but if what you want to do is add an option when clicked this is what i think should work</p>

```<code><select name='members' id="members_select">
<option value=''>Select member</option>
</select>
<button id="add">Add Option</button>
<script>
var current_member = 0; // global variable that tells what part index of the members array we currently are..
add_button = document.getElementById("add");
add_button.addEventListener('click') = function(){
   // i imagine the members array above is already set
  $('#members_select').append(members[current_member]);
  current_member++;
}
</script>
</code>```

Body:
From the database I have selected the names of the members as the select options. With jQuery, I have a dynamic Add button that adds new select field with the append function. But what could be the standard way to pass my select options generated by php in the append?

I have researched for a while but could not get it working. So any suggestions would be really helpful.

This is the page structure. It looks messy but please have a look at it. I have passed the $members as <?php echo $members; ?> in a static select that already is there from the beginning, but for the dynamic ones, I have created a variable var members and tried to pass it in the append but it is not working.

<?php
   require_once 'db_connect.php';

   $members = '';
   $query = "SELECT memberID, memberName FROM members";
   $result = mysqli_query($connect, $query);
   while($row = mysqli_fetch_array($result))
   {
    $members .= '<option value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
   }
   ?>

<form method="post">
   <fieldset>

            Members

1.

                        <select name='members[]'>
                           <option value=''>Select member</option>
                           <?php echo $members; ?>
                        </select>

                        <button class='delete btn btn-warning btn-xs'>Delete</button>

                     <button id='addNew' type="button" href="#">Add another</button>

   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>

Here is a snippet of the form without the php if you need to see the jQuery in action.

    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("

1.

<select name='members[]'><option value=''>Select member</option></select>

<button class='delete btn btn-warning btn-xs'>Delete</button>

");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });

<form method="post">
   <fieldset>

            Members

1.

                        <select name='members[]'>
                        <option value=''>Select member</option>
                        <option value='First'>First</option>
                        <option value='Second'>Second</option>
                        </select>

                        <button class='delete btn btn-warning btn-xs'>Delete</button>

                     <button id='addNew' type="button" href="#">Add another</button>

   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>

Body:
I dont understand your many code but if what you want to do is add an option when clicked this is what i think should work

<select name='members' id="members_select">
<option value=''>Select member</option>
</select>
<button id="add">Add Option</button>
<script>
var current_member = 0; // global variable that tells what part index of the members array we currently are..
add_button = document.getElementById("add");
add_button.addEventListener('click') = function(){
   // i imagine the members array above is already set
  $('#members_select').append(members[current_member]);
  current_member++;
}
</script>


问:
Getting child class info from extends construction
I'm not quite sure how to formulate my question, so sorry in advance for this uninformative title.

So here is the problem. I have a couple of files in the same directory, each of them is a class holder. When i inherit one of the classes i need to know in which file (or more like the folder) i do it.

I don't really like the solution i came to, but still to demonstrate what exactly i mean.

foo.php

```<code>class Foo {
}
</code>```

bar.php

```<code>include_once 'bootstrap.php' ;

class Bar extends Foo {
}

$bar = new Bar() ;
</code>```

bootstrap.php

```<code>function __autoload( $class ) {
    $trace = debug_backtrace() ;
    // Here i've got the directory i need:
    $folder = dirname( $trace[ 0 ][ 'file' ] ) ;
}
</code>```

Is there any other (proper) way to get folder name, cause it debug_backtrace is not actually meant for this kind of operations. And not good from the performance point of view either.

Limitation: should work for php 5.2.12

答:
The magic constant __FILE__ reports the file name (with path) of the file it is called in (see the PHP docs):

__FILE__ : The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.

That means you can create a method that returns the classes file name.

For example, in 'test-folder/Foo.php':

```<code>class Foo {

   function getFile() {
      return __FILE__;
   }

}
</code>```

And in 'Bar.php`:

```<code>include 'test-folder/Foo.php';

class Bar extends Foo {

   function getParentFile() {
      return parent::getFile();
   }

}

$bar = new Bar();

echo dirname($bar ->getParentFile());
// result: C:\wamp\www\test-folder
</code>```

EDIT: Ok, so if you want to find out where the parent class is before creating it, this should work (using Reflection):

```<code>$reflectedBar = new ReflectionClass('Bar');
$reflectedBarParent = $reflectedBar->getParentClass();
$filename = $reflectedBarParent->getFileName();
</code>```

Body:
I'm not quite sure how to formulate my question, so sorry in advance for this uninformative title.

So here is the problem. I have a couple of files in the same directory, each of them is a class holder. When i inherit one of the classes i need to know in which file (or more like the folder) i do it.

I don't really like the solution i came to, but still to demonstrate what exactly i mean.

foo.php

class Foo {
}

bar.php

include_once 'bootstrap.php' ;

class Bar extends Foo {
}

$bar = new Bar() ;

bootstrap.php

function __autoload( $class ) {
    $trace = debug_backtrace() ;
    // Here i've got the directory i need:
    $folder = dirname( $trace[ 0 ][ 'file' ] ) ;
}

Is there any other (proper) way to get folder name, cause it debug_backtrace is not actually meant for this kind of operations. And not good from the performance point of view either.

Limitation: should work for php 5.2.12

Body:
The magic constant __FILE__ reports the file name (with path) of the file it is called in (see the PHP docs):

__FILE__ : The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.

That means you can create a method that returns the classes file name.

For example, in 'test-folder/Foo.php':

class Foo {

   function getFile() {
      return __FILE__;
   }

}

And in 'Bar.php`:

include 'test-folder/Foo.php';

class Bar extends Foo {

   function getParentFile() {
      return parent::getFile();
   }

}

$bar = new Bar();

echo dirname($bar ->getParentFile());
// result: C:\wamp\www\test-folder

EDIT: Ok, so if you want to find out where the parent class is before creating it, this should work (using Reflection):

$reflectedBar = new ReflectionClass('Bar');
$reflectedBarParent = $reflectedBar->getParentClass();
$filename = $reflectedBarParent->getFileName();


问:
Missing platform-tools when installing Android Studio on Mac OSx
I am trying to install Android Studio on Mac OSx, with the goal of learning some Android development. The instructions provided were simply to:

```<code>1. Launch the .dmg file you downloaded.
2. Drag and drop Android Studio into the Applications folder.
3. Open Android Studio and follow the setup wizard to install any necessary SDK tools.
</code>```

I get to the setup wizard, select everything, give it 6 gigs of ram when asked, then it proceeds to download components and install. However, at some point a popup appears:

The following SDK component was not installed: platform-tools

The output shows:

```<code>Ignoring unknown package filter 'platform-tools'
Installing Archives:
  Preparing to install archives
  Installing Google APIs, Android API 23, revision 1
    Installed Google APIs, Android API 23, revision 1
  Installing Google APIs Intel x86 Atom System Image, Google Inc. API 23, revision 12
    Installed Google APIs Intel x86 Atom System Image, Google Inc. API 23, revision 12
    Updated ADB to support the USB devices declared in the SDK add-ons.
  Stopping ADB server failed (code -1).
  Unable to run 'adb': Cannot run program "/Users/me/Library/Android/sdk/platform-tools/adb": error=2, No such file or directory.
  Starting ADB server failed (code -1).
  Done. 2 packages installed.
Ignoring unknown package filter 'platform-tools'
</code>```

If I proceed to click "Finish" button, it opens up the Android Studio. But under Preferences -> Appearance & Behavior -> System Settings -> Android SDK, I see an error:

Please specify a Android SDK Location

There is Standalone SDK Tools, but I was under the impression that Android Studio would come with all packages needed to develop in Android:

Note: If you have not yet downloaded the SDK tools, download them now. For a complete IDE and Android SDK package, we recommend downloading Android Studio.

So I'm kinda lost on what things I should be installing. How can I get my Android Studio to 'work' on my Mac?

答:
Had similar issue (Android studio 3.0).
Happened because I was behind a corporate proxy and the tools were not downloaded during setup.

Solution:

Configure proxy in settings -> HTTP proxy

Re-install Android Studio. proxy configuration will persist and the installation should succeed the second time (got additional window with the tools to download)

Body:
I am trying to install Android Studio on Mac OSx, with the goal of learning some Android development. The instructions provided were simply to:

1. Launch the .dmg file you downloaded.
2. Drag and drop Android Studio into the Applications folder.
3. Open Android Studio and follow the setup wizard to install any necessary SDK tools.

I get to the setup wizard, select everything, give it 6 gigs of ram when asked, then it proceeds to download components and install. However, at some point a popup appears:

The following SDK component was not installed: platform-tools

The output shows:

Ignoring unknown package filter 'platform-tools'
Installing Archives:
  Preparing to install archives
  Installing Google APIs, Android API 23, revision 1
    Installed Google APIs, Android API 23, revision 1
  Installing Google APIs Intel x86 Atom System Image, Google Inc. API 23, revision 12
    Installed Google APIs Intel x86 Atom System Image, Google Inc. API 23, revision 12
    Updated ADB to support the USB devices declared in the SDK add-ons.
  Stopping ADB server failed (code -1).
  Unable to run 'adb': Cannot run program "/Users/me/Library/Android/sdk/platform-tools/adb": error=2, No such file or directory.
  Starting ADB server failed (code -1).
  Done. 2 packages installed.
Ignoring unknown package filter 'platform-tools'

If I proceed to click "Finish" button, it opens up the Android Studio. But under Preferences -> Appearance & Behavior -> System Settings -> Android SDK, I see an error:

Please specify a Android SDK Location

There is Standalone SDK Tools, but I was under the impression that Android Studio would come with all packages needed to develop in Android:

Note: If you have not yet downloaded the SDK tools, download them now. For a complete IDE and Android SDK package, we recommend downloading Android Studio.

So I'm kinda lost on what things I should be installing. How can I get my Android Studio to 'work' on my Mac?


问:
PHP Instagram API - Getting all images for a tag. How to create a pagination with min and max_tag_id
I'm working around the Instagram PHP API to get all images/posts for a specific tag in Instagram.

Here is my code:

```<code><?PHP
 function callInstagram($url)
    {
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $tag = "bulgaria";
    $client_id = "1e0f576fbdb44e299924a93cace24507";
    $Next_URL = $_GET["nexturl"];
    if($Next_URL == ""){
    $url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id.'&count=24';
    } else {
    $url =  $Next_URL;
    }
    $inst_stream = callInstagram($url);
    $results = json_decode($inst_stream, true);
    $maxid = $results['pagination']['next_max_id'];
    $nexturl = $results['pagination']['next_url'];
    //Now parse through the $results array to display your results...
    foreach($results['data'] as $item){
        $image_link = $item['images']['thumbnail']['url'];
        $Profile_name = $item['user']['username'];

        echo '<div style="display:block;float:left;">'.$Profile_name.' <br> <img src="'.$image_link.'" /></div>';
    }

    echo "<div style='display:block;width:100%;clear:both;'>MaxID: $maxid <br>NextURL: <a href='?nexturl=$nexturl'>Next images</a> <br>N: $Next_URL</div>";
</code>```

With this code it seems I'm able to get some images but I can not display the next ones when I click on Next images.

I am trying to create some kind of pagination with the min_tag_id and max_tag_id given here: https://instagram.com/developer/endpoints/

But I seems these two min_tag_id and max_tag_id are not working for me, but why?

答:
As of Nov 2017, Instagram has just changed their policy again and does not allow people to apply for permissions for public content anymore.

The change may haven been made because Instagram plans to allow users to follow hashtags on IG itself. They don't want any (new) third party having a similar feature that they could make money from.

ContentLicense: CC BY-SA 4.0

Body:
I'm working around the Instagram PHP API to get all images/posts for a specific tag in Instagram.

Here is my code:

<?PHP
 function callInstagram($url)
    {
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $tag = "bulgaria";
    $client_id = "1e0f576fbdb44e299924a93cace24507";
    $Next_URL = $_GET["nexturl"];
    if($Next_URL == ""){
    $url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id.'&count=24';
    } else {
    $url =  $Next_URL;
    }
    $inst_stream = callInstagram($url);
    $results = json_decode($inst_stream, true);
    $maxid = $results['pagination']['next_max_id'];
    $nexturl = $results['pagination']['next_url'];
    //Now parse through the $results array to display your results...
    foreach($results['data'] as $item){
        $image_link = $item['images']['thumbnail']['url'];
        $Profile_name = $item['user']['username'];

        echo '
'.$Profile_name.'

';
    }

    echo "
MaxID: $maxid
NextURL: Next images
N: $Next_URL
";

With this code it seems I'm able to get some images but I can not display the next ones when I click on Next images.

I am trying to create some kind of pagination with the min_tag_id and max_tag_id given here: https://instagram.com/developer/endpoints/

But I seems these two min_tag_id and max_tag_id are not working for me, but why?


问:
How to make a pseudo element same height and width in pure CSS?
The .speech height may vary therefore looking for solution to make .speech::after's width same as .speech's height.

ideal result

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  top: 0;
  left: 100%;
  border: 3px solid deepskyblue;
  height: 100%;
  padding-left: 50%;
  background: linear-gradient(45deg, transparent 50%, green 0%);
  transform: translateX(-50%) rotate(45deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div></code>```

答:
This is not what you actually asked for. So please correct me if I'am wrong. You asked for a bubble that grows width the height of the parent container. This is not the case with this answer. But I feel this is the desired effect anyways.

Instead of rotating an element by 45% this is using two pseudo elements and linear backgrounds to have a bubble effect.

The width is fixed and may be set according to your needs. But the bubble itself follows the height of any dynamic content.

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::before,
.speech::after {
  content: '';
  position: absolute;
  left: 100%;
  right: 0;
  top: 0;
  width: 45px;
  height: 50%;
}

.speech::before {
  background: linear-gradient(to top right, tomato 50%, transparent 50%);
}

.speech::after {
  top: 50%;
  background: linear-gradient(to bottom right, tomato 50%, transparent 50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div>

<div class="speech">Very small</div>

<div class="speech">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</p>
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</p>
</div></code>```

Body:
The .speech height may vary therefore looking for solution to make .speech::after's width same as .speech's height.

ideal result

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  top: 0;
  left: 100%;
  border: 3px solid deepskyblue;
  height: 100%;
  padding-left: 50%;
  background: linear-gradient(45deg, transparent 50%, green 0%);
  transform: translateX(-50%) rotate(45deg);
}

Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.

Body:
This is not what you actually asked for. So please correct me if I'am wrong. You asked for a bubble that grows width the height of the parent container. This is not the case with this answer. But I feel this is the desired effect anyways.

Instead of rotating an element by 45% this is using two pseudo elements and linear backgrounds to have a bubble effect.

The width is fixed and may be set according to your needs. But the bubble itself follows the height of any dynamic content.

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::before,
.speech::after {
  content: '';
  position: absolute;
  left: 100%;
  right: 0;
  top: 0;
  width: 45px;
  height: 50%;
}

.speech::before {
  background: linear-gradient(to top right, tomato 50%, transparent 50%);
}

.speech::after {
  top: 50%;
  background: linear-gradient(to bottom right, tomato 50%, transparent 50%);
}

<div class="speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div>

<div class="speech">Very small</div>

<div class="speech">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</p>
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</p>
</div>


问:
RxSwift, How to apply back-pressure to serially display a UIAlertView for each item in a Stream
I have an Observable<Item> that emits a series of items asynchronously. For each Item in the stream I need to display a UIAlertView. Each time the user dismisses the alert (if there is a new item) I need to grab the next item and show a new alert for it.

The problem I have is that the Observable emits items too quickly. While an alert is displayed, several items are emitted and I lose that information.

The stream might produce 10 items in one second, and I want to show 10 popups, that will be opened serially, one at a time, one after the other.

Is there a way to consume the next item in the stream only once I am ready to display the alert?

答:
You can do it like this

Take 2 Observables:

Your existing Observable that emits a value as you described in your answer.

An Observable that emits a value whenever the user dismisses the alert view.

Then use the zip combination operator to create a third Observable out of this 2 Observables. Because of the zip operator this third Observable only emits a value when Observable 1 and Observable 2 both emit a value. In other words it emits a value when there is an event in your stream and the user dismissed the previous alert. Everytime the third (zipped) Observable emits a value you show an alert.

Here is an image on how the zip operator works (stolen from the fabulous RxMarbles):

In this image the first line is your stream. The second line is the user dismissing the alert view. The third line is the signal to show the next alert.

You can see that while alert (1A) is shown there are two more values emitted in your stream ((2) and (3)). The zipping takes care that the next event on the third line is only emitted when the user dismisses the alert (B). Then the zipping "grabs" the next event from your stream and emits (2B) on the third line. Which causes the next alert to be shown.

To make this work you have to start the "alert dismissed" Observable with one event (A). Because otherwise the zip will wait for the first alert to be dismissed before it fires its first event.

In code it would look something like this. (I simply used an Observable<Int> to simulate your stream). The didDismissedAlert Observable is of type Observable<Void>:

```<code>Observable.zip(stream, didDismissAlert.startWith(())) { (streamValue, _) -> Int in
        return streamValue
    }
    .subscribe(onNext: { streamValue in
        // showAlert with the value from the stream
    })
    .disposed(by: disposeBag)
</code>```

Body:
You can do it like this

Take 2 Observables:

Your existing Observable that emits a value as you described in your answer.

An Observable that emits a value whenever the user dismisses the alert view.

Then use the zip combination operator to create a third Observable out of this 2 Observables. Because of the zip operator this third Observable only emits a value when Observable 1 and Observable 2 both emit a value. In other words it emits a value when there is an event in your stream and the user dismissed the previous alert. Everytime the third (zipped) Observable emits a value you show an alert.

Here is an image on how the zip operator works (stolen from the fabulous RxMarbles):

In this image the first line is your stream. The second line is the user dismissing the alert view. The third line is the signal to show the next alert.

You can see that while alert (1A) is shown there are two more values emitted in your stream ((2) and (3)). The zipping takes care that the next event on the third line is only emitted when the user dismisses the alert (B). Then the zipping "grabs" the next event from your stream and emits (2B) on the third line. Which causes the next alert to be shown.

To make this work you have to start the "alert dismissed" Observable with one event (A). Because otherwise the zip will wait for the first alert to be dismissed before it fires its first event.

In code it would look something like this. (I simply used an Observable<Int> to simulate your stream). The didDismissedAlert Observable is of type Observable<Void>:

Observable.zip(stream, didDismissAlert.startWith(())) { (streamValue, _) -> Int in
        return streamValue
    }
    .subscribe(onNext: { streamValue in
        // showAlert with the value from the stream
    })
    .disposed(by: disposeBag)


问:
jQuery load an image and swap by click
I have the following code on start to call the main image:

```<code>$(function () {
   var img = new Image();
   $(img).load(function () {
       //$(this).fadeOut('normal');
       $('#bg div table tr td').removeClass('loading').append(this);
       $(this).fadeIn();
   }).attr('src', 'images/home.jpg');
});
</code>```

Thats working so far. On click of an link i want to fade that one out and than load a second one in there. Somehow i cant get it to work... There are a lot of images that have to be loaded by clicking an element in the navigation, i´m not shure about the code. Any idea?

答:
If I understood you correctly, you can try something like this:

```<code>function ShowImage(src){
   var $imageContainer = $('#bg div table tr td');
   $imageContainer.empty().addClass('loading');
   var $image = $("<img src='" + src + "'/>");
   $image.load(function(){
      $imageContainer.removeClass('loading').append(this);
   });
}
</code>```

And then call this function to show every new image.

Title: jQuery load an image and swap by click

Body:
I have the following code on start to call the main image:

$(function () {
   var img = new Image();
   $(img).load(function () {
       //$(this).fadeOut('normal');
       $('#bg div table tr td').removeClass('loading').append(this);
       $(this).fadeIn();
   }).attr('src', 'images/home.jpg');
});

Thats working so far. On click of an link i want to fade that one out and than load a second one in there. Somehow i cant get it to work... There are a lot of images that have to be loaded by clicking an element in the navigation, i´m not shure about the code. Any idea?

Body:
If I understood you correctly, you can try something like this:

function ShowImage(src){
   var $imageContainer = $('#bg div table tr td');
   $imageContainer.empty().addClass('loading');
   var $image = $("<img src='" + src + "'/>");
   $image.load(function(){
      $imageContainer.removeClass('loading').append(this);
   });
}

And then call this function to show every new image.


问:
PayPal Express Checkout, error when supplying input_fields
I'm using PayPal Express Checkout from JavaScript.

This is the code I have and works (I see the PayPal button, I can click it, and the payment window opens fine):

```<code><div id="paypal-button"></div>

<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
        paypal.Button.render({

            env: 'sandbox',

            client: {
                sandbox: 'xxxxxx',
                production: 'yyyyyy'
            },

            payment: function () {

                var env = this.props.env;
                var client = this.props.client;

                return paypal.rest.payment.create(env, client, {
                    transactions: [
                        {
                            amount: { total: '1.00', currency: 'USD' }
                        }
                    ]

                });
            },

            commit: true,

            onAuthorize: function (data, actions) {

                return actions.payment.execute().then(function() {
                    document.querySelector('#paypal-button-container').innerText = 'Payment Complete!';
                });
            }

        }, '#paypal-button');

</script>
</code>```

But, if I supply input_fields like the code below, it stops working and throws a console error:

```<code>        paypal.Button.render({

            env: 'sandbox',

            client: {
                sandbox: 'xxxxxx',
                production: 'yyyyyy'
            },

            payment: function () {

                var env = this.props.env;
                var client = this.props.client;

                return paypal.rest.payment.create(env, client, {
                    transactions: [
                        {
                            amount: { total: '1.00', currency: 'USD' }
                        }
                    ]

                }, {
                    input_fields: {
                        no_shipping: 1
                    }
                });
            },

            commit: true,

            onAuthorize: function (data, actions) {
                return actions.payment.execute().then(function() {
                    document.querySelector('#paypal-button-container').innerText = 'Payment Complete!';
                });
            }

        }, '#paypal-button');
</code>```

This is the error detail:

In this last case, I see the PayPal button, the window opens when I click on it, but after a few seconds the window closes itself and gives the console error provided here.

What am I missing?

UPDATE

As @bluepnume pointed out, if I switch from sandbox to production environment, the problem disappears.

But, if I also supply first_name and last_name in input_fields, I get another console error no matter if I'm in sandbox or production environment.

This is the code snippet:

```<code>, {
      input_fields: {
          no_shipping: 1,
          first_name: 'Abc',
          last_name: 'Dfg'
      }
 }
</code>```

And this is the error message:

答: Concerning the first issue, it seems everything is working well now. The "no_shipping" option can be used even in test conditions.</p>

Body:
I'm using PayPal Express Checkout from JavaScript.

This is the code I have and works (I see the PayPal button, I can click it, and the payment window opens fine):

But, if I supply input_fields like the code below, it stops working and throws a console error:

        paypal.Button.render({

            env: 'sandbox',

            client: {
                sandbox: 'xxxxxx',
                production: 'yyyyyy'
            },

            payment: function () {

                var env = this.props.env;
                var client = this.props.client;

                return paypal.rest.payment.create(env, client, {
                    transactions: [
                        {
                            amount: { total: '1.00', currency: 'USD' }
                        }
                    ]

                }, {
                    input_fields: {
                        no_shipping: 1
                    }
                });
            },

            commit: true,

            onAuthorize: function (data, actions) {
                return actions.payment.execute().then(function() {
                    document.querySelector('#paypal-button-container').innerText = 'Payment Complete!';
                });
            }

        }, '#paypal-button');

This is the error detail:

In this last case, I see the PayPal button, the window opens when I click on it, but after a few seconds the window closes itself and gives the console error provided here.

What am I missing?

UPDATE

As @bluepnume pointed out, if I switch from sandbox to production environment, the problem disappears.

But, if I also supply first_name and last_name in input_fields, I get another console error no matter if I'm in sandbox or production environment.

This is the code snippet:

, {
      input_fields: {
          no_shipping: 1,
          first_name: 'Abc',
          last_name: 'Dfg'
      }
 }

And this is the error message:


问:
Yii log skip 404 errors
Maybe exist solution to skip 404 exceptions ? I'mean not store this messages in log file ? </p>

```<code>2015/04/09 12:28:52 [error] [exception.CHttpException.404] exception 'CHttpException' with message 'Невозможно обработать запрос "offer/downloadOffer".' in /var/www/yii/framework/web/CWebApplication.php:286
Stack trace:
#0 /var/www/yii/framework/web/CWebApplication.php(141): CWebApplication->runController('offer/downloadO...')
#1 /var/www/yii/framework/base/CApplication.php(184): CWebApplication->processRequest()
#2 /var/www/LAP/www/index.php(16): CApplication->run()
#3 {main}
REQUEST_URI=/offer/downloadOffer
</code>```

答:
For Yii 1.1, the correct way to exclude a category is to use the except key. Prepending a ! in the categories key as per the accepted answer will actually result in only matching categories that start with a !. So whilst it might appear to work, you're actually going to be suppressing all categories. See the filterAllCategories() function of the source code - there's no processing of the ! character, only for the * wildcard: GitHub Source.

I tried the !exception.CHttpException.404 approach in the accepted answer and thought I'd solved the issue of hiding the 404 errors, but then I realised after much hair pulling that this was resulted in no logs being logged!

The correct syntax to ignore a category is:

```<code>array(
   'class' => 'CFileLogRoute',
   'except' => 'exception.CHttpException.404'
)
</code>```

Title: Yii log skip 404 errors

Body:
Maybe exist solution to skip 404 exceptions ? I'mean not store this messages in log file ?

2015/04/09 12:28:52 [error] [exception.CHttpException.404] exception 'CHttpException' with message 'Невозможно обработать запрос "offer/downloadOffer".' in /var/www/yii/framework/web/CWebApplication.php:286
Stack trace:
#0 /var/www/yii/framework/web/CWebApplication.php(141): CWebApplication->runController('offer/downloadO...')
#1 /var/www/yii/framework/base/CApplication.php(184): CWebApplication->processRequest()
#2 /var/www/LAP/www/index.php(16): CApplication->run()
#3 {main}
REQUEST_URI=/offer/downloadOffer

Body:
For Yii 1.1, the correct way to exclude a category is to use the except key. Prepending a ! in the categories key as per the accepted answer will actually result in only matching categories that start with a !. So whilst it might appear to work, you're actually going to be suppressing all categories. See the filterAllCategories() function of the source code - there's no processing of the ! character, only for the * wildcard: GitHub Source.

I tried the !exception.CHttpException.404 approach in the accepted answer and thought I'd solved the issue of hiding the 404 errors, but then I realised after much hair pulling that this was resulted in no logs being logged!

The correct syntax to ignore a category is:

array(
   'class' => 'CFileLogRoute',
   'except' => 'exception.CHttpException.404'
)


问:
Update application installed through InstallShield
So I deployed an application using InstallShield as my installer and after every version I have to uninstall the previous version and install the next version, is there any better way of doing this (updating the application without uninstalling the previous version)

Thanks in advance.

答:
Updating an existing installation works in InstallShield. Which version you are using?
See the included InstallShield help for the ProductCode, PackageCode and UpgradeCode GUID's. There is a detailed explanation, how it works.

Overview for small updates/minor upgrades

For small updates or minor upgrades, the ProductCode in your ISM file remains stable. So, if you execute your setup, the installer looks for an already existing product with that ProductCode.

If not found, it installs the product.

If found, it compares the PackageCodes. If they are equal, it starts the setup in maintenance mode, where you can repair, modify or remove your current installation. If the PackageCodes are not equal, an update of your current installation is provided.

For every change in your setup project you should change the PackageCode.

So, if you change your setup a little bit, create a new PackageCode on the Installation Information/General Information page, increase the ProductVersion and rebuild the setup. Then an update is provided.


问:
Three.js | Is it possible to cast a ray from one object to another using raycaster?
I need to cast a ray from an object to another object in my scene.

Is it possible to do in Three.js as I couldn't found anything in my initial search.

Even casting it from the object to origin( 0, 0, 0 )  will work for me.

Thanks in advance.

I've did this to cast the ray from object to origin.

```<code>var origin = new THREE.Vector3( 0,0,0 );
var pos = mesh.position.clone().sub( origin );

pos.normalize();
raycaster.set( mesh.position , pos.normalize() );

var intersects = raycaster.intersectObjects( scene.children );

for ( var i = 0; i < intersects.length; i ++ ) {

    intersects[i].object.material.color.setHex( 0xffffff );

}
</code>```

答:
Here's an example. Raycaster's ray goes from the red sphere to the blue one. All the objects between them change their color randomly, whilst the ray intersects them.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 10, 15);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.AmbientLight(0xffffff, .5));
var light = new THREE.DirectionalLight(0xffffff, .5);
light.position.set(10, 10, -10);
scene.add(light);

scene.add(new THREE.GridHelper(20, 20, "gray", "gray"));

var objects = [];
for (let i = 0; i < 20; i++) {
  let obj = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshLambertMaterial({
    color: Math.random() * 0xffffff
  }));
  obj.position.set(
    THREE.MathUtils.randInt(-10, 10),
    .5,
    THREE.MathUtils.randInt(-10, 10)
  );
  objects.push(obj);
  scene.add(obj);
}

var objOrigin = new THREE.Mesh(new THREE.SphereGeometry(.5, 16, 12), new THREE.MeshLambertMaterial({
  color: "red"
}));
scene.add(objOrigin);
var objDestin = new THREE.Mesh(new THREE.SphereGeometry(.5, 16, 12), new THREE.MeshLambertMaterial({
  color: "blue"
}));
scene.add(objDestin);

var raycaster = new THREE.Raycaster();
var intersects;
var direction = new THREE.Vector3();
var far = new THREE.Vector3();
var clock = new THREE.Clock();
var time = 0;

render();

function render() {
  time += clock.getDelta();
  requestAnimationFrame(render);
  objOrigin.position.set(
    Math.cos(time) * ( 7 + Math.sin(time * 10)) ,
    .5,
    Math.sin(time) * ( 7 + Math.sin(time * 10))
  );
  objDestin.position.set(
    Math.cos(time + Math.PI) * 7,
    .5,
    Math.sin(time + Math.PI) * 7
  );
  raycaster.set(objOrigin.position, direction.subVectors(objDestin.position, objOrigin.position).normalize());
  raycaster.far = far.subVectors(objDestin.position, objOrigin.position).length(); // comment this line to have an infinite ray
  intersects = raycaster.intersectObjects(objects);
  for (let i = 0; i < intersects.length; i++) {
    intersects[i].object.material.color.set(Math.random() * 0xffffff);
  }
  renderer.render(scene, camera);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  overflow: hidden;
  margin: 0;
}</code>```

```

Body:
I need to cast a ray from an object to another object in my scene.

Is it possible to do in Three.js as I couldn't found anything in my initial search.

Even casting it from the object to origin( 0, 0, 0 )  will work for me.

Thanks in advance.

I've did this to cast the ray from object to origin.

var origin = new THREE.Vector3( 0,0,0 );
var pos = mesh.position.clone().sub( origin );

pos.normalize();
raycaster.set( mesh.position , pos.normalize() );

var intersects = raycaster.intersectObjects( scene.children );

for ( var i = 0; i < intersects.length; i ++ ) {

    intersects[i].object.material.color.setHex( 0xffffff );

}

Body:
Here's an example. Raycaster's ray goes from the red sphere to the blue one. All the objects between them change their color randomly, whilst the ray intersects them.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 10, 15);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.AmbientLight(0xffffff, .5));
var light = new THREE.DirectionalLight(0xffffff, .5);
light.position.set(10, 10, -10);
scene.add(light);

scene.add(new THREE.GridHelper(20, 20, "gray", "gray"));

var objects = [];
for (let i = 0; i < 20; i++) {
  let obj = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshLambertMaterial({
    color: Math.random() * 0xffffff
  }));
  obj.position.set(
    THREE.MathUtils.randInt(-10, 10),
    .5,
    THREE.MathUtils.randInt(-10, 10)
  );
  objects.push(obj);
  scene.add(obj);
}

var objOrigin = new THREE.Mesh(new THREE.SphereGeometry(.5, 16, 12), new THREE.MeshLambertMaterial({
  color: "red"
}));
scene.add(objOrigin);
var objDestin = new THREE.Mesh(new THREE.SphereGeometry(.5, 16, 12), new THREE.MeshLambertMaterial({
  color: "blue"
}));
scene.add(objDestin);

var raycaster = new THREE.Raycaster();
var intersects;
var direction = new THREE.Vector3();
var far = new THREE.Vector3();
var clock = new THREE.Clock();
var time = 0;

render();

function render() {
  time += clock.getDelta();
  requestAnimationFrame(render);
  objOrigin.position.set(
    Math.cos(time) * ( 7 + Math.sin(time * 10)) ,
    .5,
    Math.sin(time) * ( 7 + Math.sin(time * 10))
  );
  objDestin.position.set(
    Math.cos(time + Math.PI) * 7,
    .5,
    Math.sin(time + Math.PI) * 7
  );
  raycaster.set(objOrigin.position, direction.subVectors(objDestin.position, objOrigin.position).normalize());
  raycaster.far = far.subVectors(objDestin.position, objOrigin.position).length(); // comment this line to have an infinite ray
  intersects = raycaster.intersectObjects(objects);
  for (let i = 0; i < intersects.length; i++) {
    intersects[i].object.material.color.set(Math.random() * 0xffffff);
  }
  renderer.render(scene, camera);
}

body {
  overflow: hidden;
  margin: 0;
}

<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>


问:
Rails logging simply doesn't work
I'm trying to do easy logging

```<code>logger.error "ERROR!!!"
</code>```

But nothing is displayed in any of the log files in the /log directory. I tried rescuing an exception, but there's no exception.

What might be the problem here?

答: Did you check that your production.log file has the proper rights? Try running sudo chmod 0666 on your production.log file, that might be the problem.

Title: Rails logging simply doesn't work

Body:
I'm trying to do easy logging

logger.error "ERROR!!!"

But nothing is displayed in any of the log files in the /log directory. I tried rescuing an exception, but there's no exception.

What might be the problem here?


问:
QML: passing JS object to C++ member function
I'm trying to pass a JS object (map) to a C++ member function with a signature

```<code>Q_INVOKABLE virtual bool generate(QObject* context);
</code>```

by using

```<code>a.generate({foo: "bar"});
</code>```

The method is called (detected via breakpoint), but the passed context parameter is NULL. Since the documentation mentions that JS objects will be passed as QVariantMap, I've tried using the signature

```<code>Q_INVOKABLE virtual bool generate(QVariantMap* context);
</code>```

but this failed during MOC. Using

```<code>Q_INVOKABLE virtual bool generate(QVariantMap& context);
</code>```

causes the method to not be found at runtime by QML (error message is "Unknown method parameter type: QVariantMap&").

The documentation only has an example of passing a QVariantMap from C++ to QML, not in the other direction.

Using a public slot instead of a Q_INVOKABLE shows exactly the same behavior and errors.

答:
Don't use references to pass values from QML world to CPP world.
This simple example works:

test.h

```<code>#ifndef TEST_H
#define TEST_H

#include <QObject>
#include <QDebug>
#include <QVariantMap>

class Test : public QObject
{
    Q_OBJECT
public:
    Test(){}

    Q_INVOKABLE bool generate(QVariantMap context)
    {qDebug() << context;}
};

#endif // TEST_H
</code>```

main.cpp

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "test.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty(QStringLiteral("Test"), new Test());

    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}
</code>```

main.qml

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MouseArea
    {
        anchors.fill: parent
        onClicked:
        {
            Test.generate({foo: "bar"});
        }
    }
}
</code>```

click in window, this will print following msg in output console:

```<code>QMap(("foo", QVariant(QString, "bar")))
</code>```

Body:
I'm trying to pass a JS object (map) to a C++ member function with a signature

Q_INVOKABLE virtual bool generate(QObject* context);

by using

a.generate({foo: "bar"});

The method is called (detected via breakpoint), but the passed context parameter is NULL. Since the documentation mentions that JS objects will be passed as QVariantMap, I've tried using the signature

Q_INVOKABLE virtual bool generate(QVariantMap* context);

but this failed during MOC. Using

Q_INVOKABLE virtual bool generate(QVariantMap& context);

causes the method to not be found at runtime by QML (error message is "Unknown method parameter type: QVariantMap&").

The documentation only has an example of passing a QVariantMap from C++ to QML, not in the other direction.

Using a public slot instead of a Q_INVOKABLE shows exactly the same behavior and errors.

Body:
Don't use references to pass values from QML world to CPP world.
This simple example works:

test.h

#ifndef TEST_H
#define TEST_H

#include <QObject>
#include <QDebug>
#include <QVariantMap>

class Test : public QObject
{
    Q_OBJECT
public:
    Test(){}

    Q_INVOKABLE bool generate(QVariantMap context)
    {qDebug() << context;}
};

#endif // TEST_H

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "test.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty(QStringLiteral("Test"), new Test());

    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

main.qml

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MouseArea
    {
        anchors.fill: parent
        onClicked:
        {
            Test.generate({foo: "bar"});
        }
    }
}

click in window, this will print following msg in output console:

QMap(("foo", QVariant(QString, "bar")))


问:
How do I remove the CMS and Media buttons from the Backend interface?
I have many icons across the top of the page when I first log in on the backend. I've been able to remove some icons by disabling plugins like
the Rainlab Blog and Builder, but Dashboard, CMS, and Media remain there. How can I remove them?

From the official documentation on extending plugins I found this:

```<code>Event::listen('backend.menu.extendItems', function($manager) {

    $manager->removeMainMenuItem('October.Cms', 'cms');
    $manager->removeSideMenuItem('October.Cms', 'cms', 'pages');

});
</code>```

But I haven't found which plugin I can add this listener code to, nor the names of the Dashboard and CMS items.

Does someone know? I'll post a solution if I can find one...

答:
You can create your own plugin and within the boot method try:

```<code>public function boot()
{
    Event::listen('backend.menu.extendItems', function($manager) {
        $manager->removeMainMenuItem('October.Cms', 'cms');
        $manager->removeMainMenuItem('October.Backend', 'media');

    });
}
</code>```

The above code will remove cms and media from backend main menu. With this way the authenticated users can access the media and cms page directly by URL. If you want to block them you can do it by creating a group and disallow what you want.

Body:
I have many icons across the top of the page when I first log in on the backend. I've been able to remove some icons by disabling plugins like
the Rainlab Blog and Builder, but Dashboard, CMS, and Media remain there. How can I remove them?

From the official documentation on extending plugins I found this:

Event::listen('backend.menu.extendItems', function($manager) {

    $manager->removeMainMenuItem('October.Cms', 'cms');
    $manager->removeSideMenuItem('October.Cms', 'cms', 'pages');

});

But I haven't found which plugin I can add this listener code to, nor the names of the Dashboard and CMS items.

Does someone know? I'll post a solution if I can find one...

Body:
You can create your own plugin and within the boot method try:

public function boot()
{
    Event::listen('backend.menu.extendItems', function($manager) {
        $manager->removeMainMenuItem('October.Cms', 'cms');
        $manager->removeMainMenuItem('October.Backend', 'media');

    });
}

The above code will remove cms and media from backend main menu. With this way the authenticated users can access the media and cms page directly by URL. If you want to block them you can do it by creating a group and disallow what you want.


问:
File Streaming in Java
I'm currently developing 3D graphics application using JOGL (Java OpenGL binding). In brief, I have a huge landscape binary file. Due to its size, I have to stream terrain chunks in the run-time. Therefore, we explicitly see the random access concern. I have already finished the first (and dirty :)) implementation (perhaps it is multi-threaded), where I'm using a foolish approach...  Here is the initialization of it:

```<code>dataInputStream = new DataInputStream(new BufferedInputStream(fileInputStream,4 * 1024);
dataInputStream.mark(dataInputStream.available());
</code>```

And when I need to read (stream) special chunk (I already know its "offset" in the file) I'm performing the following (shame on me :)):

```<code>dataInputStream.reset();
dataInputStream.skipBytes(offset);
dataInputStream.read(whatever I need...);
</code>```

Since I had little experience that was the first thing I could think about :)
So, until now I have read 3 useful and quite interesting articles (I'm suggesting you to read them, perhaps if you are interested in this topic)

Byte Buffers and Non-Heap Memory - Mr. Gregory seems to be literate in Java NIO.

Java tip: How to read files quickly [http://nadeausoftware.com/articles/2008/02/java_tip_how_read_files_quickly] - That's an interesting benchmark.

Articles: Tuning Java I/O Performance [http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/] - Simple Sun recommendations, but please scroll down and have a look at "Random Access" section there; they show a simple implementation of RandomAccessFile (RAF) with self-buffering improvement.

Mr. Gregory provides several *.java files in the end of his article. One of them is a benchmarking between FileChannel + ByteBuffer + Mapping (FBM) and RAF. He says that he noticed 4x speedup when using FBM compared to RAF. I have ran this benchmark in the following conditions:

The offset (e. g. place of access) is generated randomly (in the file scope, e. g. 0 - file.length());

File size is 220MB;

1 000 000 accesses (75% reads and 25% writes)

The results were stunning:

~ 28 sec for RAF!
~ 0.2 sec for FBM!

However, his implementation of RAF in this benchmark doesn't have self-buffering (the 3rd article tells about one), so I guess it is the "RandomAccessFile.seek" method calling, who drops performance so hard.

Ok, now after all those things I've learnt there is 1 question and 1 dilemma :)

Question: When we are mapping a file using "FileChannel.map" does Java copy the whole file contents into the MappedByteBuffer? Or does it just emulate it? If it copies, then using FBM approach is not suitable for my situation, is it?

Dilemma: Depends on your answers on the question...

If mapping copies a file, then it seems like I have only 2 possible solutions to go: RAF + self-buffering (the one from the 3rd article) or make use of position in FileChannel (not with mapping)... Which one would be better?

If mapping doesn't copy a file, then I have 3 options: two previous ones and FBM itself.

Edit: Here is one more question. Some of you here say that mapping doesn't copy file into MappedByteBuffer. Ok then, why can't I map 1GB file then, I'm getting "failed to map" message...

P. S. I would like to receive a fulfilled answer with advices, since I'm not able to find the consistent information over this topic in the internet.

Thanks :)

答:
For a 220 MB file I would memory map the whole thing into virtual memory.  The reason FBM is so fast is it doesn't actually read the data into memory, it just makes it available.

Note: when you run the test you need to compare like for like i.e. when the file is in the OS cache it will be much faster no matter how you do it. You need to repeat the test multiple times to get a reproduce able result.

Title: File Streaming in Java

Body:
I'm currently developing 3D graphics application using JOGL (Java OpenGL binding). In brief, I have a huge landscape binary file. Due to its size, I have to stream terrain chunks in the run-time. Therefore, we explicitly see the random access concern. I have already finished the first (and dirty :)) implementation (perhaps it is multi-threaded), where I'm using a foolish approach...  Here is the initialization of it:

dataInputStream = new DataInputStream(new BufferedInputStream(fileInputStream,4 * 1024);
dataInputStream.mark(dataInputStream.available());

And when I need to read (stream) special chunk (I already know its "offset" in the file) I'm performing the following (shame on me :)):

dataInputStream.reset();
dataInputStream.skipBytes(offset);
dataInputStream.read(whatever I need...);

Since I had little experience that was the first thing I could think about :)
So, until now I have read 3 useful and quite interesting articles (I'm suggesting you to read them, perhaps if you are interested in this topic)

Byte Buffers and Non-Heap Memory - Mr. Gregory seems to be literate in Java NIO.

Java tip: How to read files quickly [http://nadeausoftware.com/articles/2008/02/java_tip_how_read_files_quickly] - That's an interesting benchmark.

Articles: Tuning Java I/O Performance [http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/] - Simple Sun recommendations, but please scroll down and have a look at "Random Access" section there; they show a simple implementation of RandomAccessFile (RAF) with self-buffering improvement.

Mr. Gregory provides several *.java files in the end of his article. One of them is a benchmarking between FileChannel + ByteBuffer + Mapping (FBM) and RAF. He says that he noticed 4x speedup when using FBM compared to RAF. I have ran this benchmark in the following conditions:

The offset (e. g. place of access) is generated randomly (in the file scope, e. g. 0 - file.length());

File size is 220MB;

1 000 000 accesses (75% reads and 25% writes)

The results were stunning:

~ 28 sec for RAF!
~ 0.2 sec for FBM!

However, his implementation of RAF in this benchmark doesn't have self-buffering (the 3rd article tells about one), so I guess it is the "RandomAccessFile.seek" method calling, who drops performance so hard.

Ok, now after all those things I've learnt there is 1 question and 1 dilemma :)

Question: When we are mapping a file using "FileChannel.map" does Java copy the whole file contents into the MappedByteBuffer? Or does it just emulate it? If it copies, then using FBM approach is not suitable for my situation, is it?

Dilemma: Depends on your answers on the question...

If mapping copies a file, then it seems like I have only 2 possible solutions to go: RAF + self-buffering (the one from the 3rd article) or make use of position in FileChannel (not with mapping)... Which one would be better?

If mapping doesn't copy a file, then I have 3 options: two previous ones and FBM itself.

Edit: Here is one more question. Some of you here say that mapping doesn't copy file into MappedByteBuffer. Ok then, why can't I map 1GB file then, I'm getting "failed to map" message...

P. S. I would like to receive a fulfilled answer with advices, since I'm not able to find the consistent information over this topic in the internet.

Thanks :)


问:
Generate custom documentation (based on SQL table)
I'm currently using a software with its own command-line interface, accepting its own commands with parameters, but these commands are documented in several places and files, so I can't simply run doxygen on it, and its not possible to add documentation to these files now.

Dumping everything in one text document seems a bit annoying to use, so my first idea is to generate a table, SQL for example, and add the documentation there, with several columns, such as command and its description, arguments and description of them, example command, execution time, etc., and add some kind of GUI to easily display the commands.

Are there already solutions for this, especially easy to maintenance ones?
Or is it better to have a different approach for this, such as html based Helpfiles?

答:
you could build one yourself or use some third party tools like REDGATE SQLdoc..

below is one example of how documentation is generated for one sample table as HTML,PDF as well


问:
Ajax Bing Maps version 7 - move and delete push pin - beginner's tutorial
I am currently learning about these maps. Now I would like to create a method which updates my push pin if I already have one.

a. I tried to use setLocation(newLocation) but unfortunately, when I did this, my client side code wasn't even reached (I'm thinking that the code syntax is incorrect, yet no error was given on chrome)

b. I then tried to learn how to delete it and create another one, yet I cannot find any resources from http://msdn.microsoft.com/en-us/library/gg427610.aspx - maybe I am not searching well enough.

Can anyone provide me with some guide on how to move a push pin and how to delete one? Thank you all very very much

```<code>var loc = new Microsoft.Maps.Location(lat, lon);

var pin = new Microsoft.Maps.Pushpin(loc);
</code>```

Edit: partial answer

Removing a push pin:

```<code>if (pin != null)
{
    map.entities.remove(pin)
}
</code>```

答:
The following function can remove all the pushpins from the map:</p>

```<code>//remove all the pushpins
function deletePushpin()
{
  for(var i=map.entities.getLength()-1;i>=0;i--)
  {
      var pushpin= map.entities.get(i);
      if (pushpin instanceof Microsoft.Maps.Pushpin) {
        map.entities.remove(pushpin);
      }
   }
}
</code>```

Body:
I am currently learning about these maps. Now I would like to create a method which updates my push pin if I already have one.

a. I tried to use setLocation(newLocation) but unfortunately, when I did this, my client side code wasn't even reached (I'm thinking that the code syntax is incorrect, yet no error was given on chrome)

b. I then tried to learn how to delete it and create another one, yet I cannot find any resources from http://msdn.microsoft.com/en-us/library/gg427610.aspx - maybe I am not searching well enough.

Can anyone provide me with some guide on how to move a push pin and how to delete one? Thank you all very very much

var loc = new Microsoft.Maps.Location(lat, lon);

var pin = new Microsoft.Maps.Pushpin(loc);

Edit: partial answer

Removing a push pin:

if (pin != null)
{
    map.entities.remove(pin)
}

Body:
The following function can remove all the pushpins from the map:

//remove all the pushpins
function deletePushpin()
{
  for(var i=map.entities.getLength()-1;i>=0;i--)
  {
      var pushpin= map.entities.get(i);
      if (pushpin instanceof Microsoft.Maps.Pushpin) {
        map.entities.remove(pushpin);
      }
   }
}


问:
Python -> TypeError: unsupported operand type(s) for ^
I am struggling with Python code. I want to do this equation.

This my code:

```<code>fs= 5000
T=np.linspace(0,2.2,fs)
n=np.arange(fs*2.2)
u=[]
for x in T:
    if x < 0.2:
        u.append(x * np.sin(34*np.pi*n/fs))
    if (x >= 0.2 and x < 0.8):
        u.append(1/x * np.log10(x+1))
    if x >= 0.8 and x < 1.4:
        u.append((x^2 + 1) * np.sin(12*np.pi*n/fs))
    if x >= 1.4:
        u.append(np.sin(20*np.pi*n/fs + x/3))
</code>```

And python returns:

```<code>  File "D:/Semestr V/Podstawy Transmisji Danych/labki-ZAD3.py", line 20, in <module>
    u.append((x^2 + 1) * np.sin(12*np.pi*n/fs))

TypeError: unsupported operand type(s) for ^: 'numpy.float64' and 'int'
</code>```

答: The power operator is **, ^ is bitwise XOR.

Body:
I am struggling with Python code. I want to do this equation.

This my code:

fs= 5000
T=np.linspace(0,2.2,fs)
n=np.arange(fs*2.2)
u=[]
for x in T:
    if x < 0.2:
        u.append(x * np.sin(34*np.pi*n/fs))
    if (x >= 0.2 and x < 0.8):
        u.append(1/x * np.log10(x+1))
    if x >= 0.8 and x < 1.4:
        u.append((x^2 + 1) * np.sin(12*np.pi*n/fs))
    if x >= 1.4:
        u.append(np.sin(20*np.pi*n/fs + x/3))

And python returns:

  File "D:/Semestr V/Podstawy Transmisji Danych/labki-ZAD3.py", line 20, in <module>
    u.append((x^2 + 1) * np.sin(12*np.pi*n/fs))

TypeError: unsupported operand type(s) for ^: 'numpy.float64' and 'int'