问:
Returning JS var from ajax request Laravel
I keep reading about this but still don't' get it

I need to send a variable to controller. The form data is being send but not the js variable

JS

```<code>$('#form').submit(function(e){
    e.preventDefault();
    var hash = '9999';
    $('#form').append('hash', hash);
    var form_input = $('#form').serialize()+'&_token={{csrf_token()}}';

$.ajax({
     url : '{{route('pag_submit')}}',
     type: "POST",
     data: form_input,
     success : function (data) {
      if (data.success == 1){
         alert (data.msg);
      }
     },
     error   : function ( jqXhr, json, errorThrown ) {
      var errors = jqXhr.responseJSON;
      var errorsHtml= '';
      $.each( errors, function( key, value ) {
           errorsHtml += '<li>' + value[0] + '</li>';
      });
       toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
                    }
                });
       });
</code>```

CONTROLLER

```<code>public function pag(Request $request){

        $name= $request->name;
        $date= $request->date;
        $test = $request->test;
        $hash = $request->hash;

        return ['success'=>1, 'msg'=> [$name, $date, $test, $hash], 'response' => $this->payment_success_html()];
    }
</code>```

Only hash returns as null, can someone help me with this?

答:
Try to append input to a form

$('#form').append('<input type="hidden" name="hash" value=' + hash + '/>');

Body:
I keep reading about this but still don't' get it

I need to send a variable to controller. The form data is being send but not the js variable

JS

$('#form').submit(function(e){
    e.preventDefault();
    var hash = '9999';
    $('#form').append('hash', hash);
    var form_input = $('#form').serialize()+'&_token={{csrf_token()}}';

$.ajax({
     url : '{{route('pag_submit')}}',
     type: "POST",
     data: form_input,
     success : function (data) {
      if (data.success == 1){
         alert (data.msg);
      }
     },
     error   : function ( jqXhr, json, errorThrown ) {
      var errors = jqXhr.responseJSON;
      var errorsHtml= '';
      $.each( errors, function( key, value ) {
           errorsHtml += '
' + value[0] + '
';
      });
       toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
                    }
                });
       });

CONTROLLER

public function pag(Request $request){

        $name= $request->name;
        $date= $request->date;
        $test = $request->test;
        $hash = $request->hash;

        return ['success'=>1, 'msg'=> [$name, $date, $test, $hash], 'response' => $this->payment_success_html()];
    }

Only hash returns as null, can someone help me with this?


来源: stackexchange

问:
or_like not working in codeIgniter
I am trying to run a query with multiple like combined using or in mysql query from code Igniter.
I have following code for that purpose.

```<code>$this->db->group_start();
                    foreach ($active['result'] as $outcode) {
                        $this->db->or_like('postcode',$outcode['outcode']);

                    }
                    $this->db->group_end();
</code>```

It does create the query as expected apart from the problem that it contains ESCAPE '!' between each part.
here is query printed.

```<code>SELECT * FROM `tbl_service_providers` WHERE `is_active` >= 1 AND ( `postcode` LIKE '%SS13%' ESCAPE '!' OR `postcode` LIKE '%SS14%' ESCAPE '!')
</code>```

答:
You could try something like this : </p>

```<code> $this->db->group_start();
 foreach ($active['result'] as $k=>$outcode)
 {
   if($k == 0)
    {
        $this->db->like('postcode',$outcode['outcode']);
    }
    else
    {
       $this->db->or_like('postcode',$outcode['outcode']);
    }
 }
 $this->db->group_end();
</code>```

ContentLicense: CC BY-SA 3.0

Title: or_like not working in codeIgniter

Body:
I am trying to run a query with multiple like combined using or in mysql query from code Igniter.
I have following code for that purpose.

$this->db->group_start();
                    foreach ($active['result'] as $outcode) {
                        $this->db->or_like('postcode',$outcode['outcode']);

                    }
                    $this->db->group_end();

It does create the query as expected apart from the problem that it contains ESCAPE '!' between each part.
here is query printed.

SELECT * FROM `tbl_service_providers` WHERE `is_active` >= 1 AND ( `postcode` LIKE '%SS13%' ESCAPE '!' OR `postcode` LIKE '%SS14%' ESCAPE '!')

Body:
You could try something like this :

 $this->db->group_start();
 foreach ($active['result'] as $k=>$outcode)
 {
   if($k == 0)
    {
        $this->db->like('postcode',$outcode['outcode']);
    }
    else
    {
       $this->db->or_like('postcode',$outcode['outcode']);
    }
 }
 $this->db->group_end();


问:
EnumResourceNames issue - unknown error
I was recently working with resources from secondary libraries/binary modules and encountered a strange error.

I have two native WinAPI references:

```<code>[DllImport("kernel32.dll", SetLastError = true)]
public extern static bool EnumResourceNames(IntPtr hModule, int lpszType, EnumResNameProc lpEnumFunc, IntPtr lParam);

[DllImport("kernel32.dll", SetLastError=true)]
public extern static IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, int dwFlags);
</code>```

When I call LoadLibraryEx, I am getting the IntPtr instance - just what I need:

```<code>IntPtr x = WinApi.LoadLibraryEx(@"D:\Software\Reflector\Reflector.exe",IntPtr.Zero,2);
Debug.WriteLine(x.ToInt32());
</code>```

However, when I try to enumerate icon resources (defined by the ID = 3):

```<code>Debug.WriteLine(WinApi.EnumResourceNames(x, 3, new EnumResNameProc(ListCallback), IntPtr.Zero));
Debug.WriteLine(Marshal.GetLastWin32Error());
</code>```

I am getting this error code (returned by GetLastError):

-532462766

This usually means there is an unknown error, as far as I know, but I am just curious - what could be the problem with listing resources from the executable?

答:
-532462766 == 0xe0434352.  The last three hex pairs spell "CCR", a common trick that Microsoft programmers use to try to come up with an easily recognizable exception code.  The exact meaning is quite mysterious, beyond it being commonly associated with managed code and seemingly being very low level in a sub-system that doesn't normally fail to produce a meaningful managed exception.

There is an excellent candidate reason for that mysterious exception, your EnumResources pinvoke declaration is wrong.  The 2nd argument is IntPtr, not int.  That has some odds of going kaboom on a 64-bit operating system.

Please post back if you ever figure out what CCR means.

```<code>using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;

class Program {
    static void Main(string[] args) {
        try {
            IntPtr module = LoadLibraryEx(@"C:\windows\system32\user32.dll", IntPtr.Zero, 2);
            if (module == IntPtr.Zero) throw new Win32Exception();
            if (!EnumResourceNames(module, (IntPtr)3, new EnumResNameProc(ListCallback), IntPtr.Zero))
                throw new Win32Exception();
        }
        catch (Win32Exception ex) {
            Console.WriteLine(ex.Message);
        }
        Console.ReadLine();
    }

    static bool ListCallback(IntPtr hModule, IntPtr type, IntPtr name, IntPtr lp) {
        long idorname = (long)name;
        if (idorname >> 16 == 0) Console.WriteLine("#{0}", idorname);
        else Console.WriteLine(Marshal.PtrToStringAnsi(name));
        return true;
    }

    public delegate bool EnumResNameProc(IntPtr hModule, IntPtr type, IntPtr name, IntPtr lp);
    [DllImport("kernel32.dll", SetLastError = true)]
    public extern static bool EnumResourceNames(IntPtr hModule, IntPtr type, EnumResNameProc lpEnumFunc, IntPtr lParam);
    [DllImport("kernel32.dll", SetLastError = true)]
    public extern static IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, int dwFlags);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: EnumResourceNames issue - unknown error

Body:
I was recently working with resources from secondary libraries/binary modules and encountered a strange error.

I have two native WinAPI references:

[DllImport("kernel32.dll", SetLastError = true)]
public extern static bool EnumResourceNames(IntPtr hModule, int lpszType, EnumResNameProc lpEnumFunc, IntPtr lParam);

[DllImport("kernel32.dll", SetLastError=true)]
public extern static IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, int dwFlags);

When I call LoadLibraryEx, I am getting the IntPtr instance - just what I need:

IntPtr x = WinApi.LoadLibraryEx(@"D:\Software\Reflector\Reflector.exe",IntPtr.Zero,2);
Debug.WriteLine(x.ToInt32());

However, when I try to enumerate icon resources (defined by the ID = 3):

Debug.WriteLine(WinApi.EnumResourceNames(x, 3, new EnumResNameProc(ListCallback), IntPtr.Zero));
Debug.WriteLine(Marshal.GetLastWin32Error());

I am getting this error code (returned by GetLastError):

-532462766

This usually means there is an unknown error, as far as I know, but I am just curious - what could be the problem with listing resources from the executable?

Body:
-532462766 == 0xe0434352.  The last three hex pairs spell "CCR", a common trick that Microsoft programmers use to try to come up with an easily recognizable exception code.  The exact meaning is quite mysterious, beyond it being commonly associated with managed code and seemingly being very low level in a sub-system that doesn't normally fail to produce a meaningful managed exception.

There is an excellent candidate reason for that mysterious exception, your EnumResources pinvoke declaration is wrong.  The 2nd argument is IntPtr, not int.  That has some odds of going kaboom on a 64-bit operating system.

Please post back if you ever figure out what CCR means.

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;

class Program {
    static void Main(string[] args) {
        try {
            IntPtr module = LoadLibraryEx(@"C:\windows\system32\user32.dll", IntPtr.Zero, 2);
            if (module == IntPtr.Zero) throw new Win32Exception();
            if (!EnumResourceNames(module, (IntPtr)3, new EnumResNameProc(ListCallback), IntPtr.Zero))
                throw new Win32Exception();
        }
        catch (Win32Exception ex) {
            Console.WriteLine(ex.Message);
        }
        Console.ReadLine();
    }

    static bool ListCallback(IntPtr hModule, IntPtr type, IntPtr name, IntPtr lp) {
        long idorname = (long)name;
        if (idorname >> 16 == 0) Console.WriteLine("#{0}", idorname);
        else Console.WriteLine(Marshal.PtrToStringAnsi(name));
        return true;
    }

    public delegate bool EnumResNameProc(IntPtr hModule, IntPtr type, IntPtr name, IntPtr lp);
    [DllImport("kernel32.dll", SetLastError = true)]
    public extern static bool EnumResourceNames(IntPtr hModule, IntPtr type, EnumResNameProc lpEnumFunc, IntPtr lParam);
    [DllImport("kernel32.dll", SetLastError = true)]
    public extern static IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, int dwFlags);
}


问:
Checking if X-Y co-ordinate lies within bounds of a control saved in a dictionary
I am saving the extents of a control on a WinForm in a dictionary such as:

```<code>Dictionary<Tuple<int, int>, Control> dictionary =
    new Dictionary<Tuple<int, int>, Control>();
</code>```

And I am drawing controls on the WinForm programmatically. Whenever I draw each control I save the bounds of that control in this dictionary such as:

```<code>dictionary.Add(Tuple.Create(myControl.X, myControl.Y), myControl);
dictionary.Add(Tuple.Create(myControl.X + myControl.Length, myControl.Y), myControl);
dictionary.Add(Tuple.Create(myControl.X + myControl.Length, myControl.Y + myControl.Width), myControl);
dictionary.Add(Tuple.Create(myControl.X, myControl.Y + myControl.Width), myControl);
</code>```

Now, what I want to achieve is that whenever there is a mouse click on the WinForm for MouseEventArgs e, I want to check whether Point(e.X, e.Y) lies within the bounds of a control or not??

I am aware that I can iterate through the Key value pairs of the dictionary and calculate whether the Point(e.X,e.Y) lies within the bound or not. But I want to avoid iterating through the Keys of the dictionary and get the solution.

Any idea how I can achieve it without iterating through the dictionary and calculate for each point?

答:
Try this. If you want, you can replace the int id with a Control.

```<code>using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reactive.Linq;
using System.Windows.Forms;

namespace Anything
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var random = new Random();
            var bounds = Screen.PrimaryScreen.Bounds;
            var extents = new Dictionary<int, Rectangle>();

            for (var i = 0; i < 300; i++)
            {
                var x = random.Next(bounds.Width);
                var y = random.Next(bounds.Height);
                var w = random.Next(bounds.Width - x);
                var h = random.Next(bounds.Height - y);

                extents[i] = new Rectangle(x, y, w, h);
            }

            var domains = from time in Observable.Interval(TimeSpan.FromMilliseconds(100))
                          from extent in extents
                          where extent.Value.Contains(Control.MousePosition)
                          select extent.Key;

            var subscription = domains.Subscribe(id => Console.Write($"{id},"));

            Console.ReadKey();

            subscription.Dispose();
        }
    }
}
</code>```

Body:
I am saving the extents of a control on a WinForm in a dictionary such as:

Dictionary<Tuple<int, int>, Control> dictionary =
    new Dictionary<Tuple<int, int>, Control>();

And I am drawing controls on the WinForm programmatically. Whenever I draw each control I save the bounds of that control in this dictionary such as:

dictionary.Add(Tuple.Create(myControl.X, myControl.Y), myControl);
dictionary.Add(Tuple.Create(myControl.X + myControl.Length, myControl.Y), myControl);
dictionary.Add(Tuple.Create(myControl.X + myControl.Length, myControl.Y + myControl.Width), myControl);
dictionary.Add(Tuple.Create(myControl.X, myControl.Y + myControl.Width), myControl);

Now, what I want to achieve is that whenever there is a mouse click on the WinForm for MouseEventArgs e, I want to check whether Point(e.X, e.Y) lies within the bounds of a control or not??

I am aware that I can iterate through the Key value pairs of the dictionary and calculate whether the Point(e.X,e.Y) lies within the bound or not. But I want to avoid iterating through the Keys of the dictionary and get the solution.

Any idea how I can achieve it without iterating through the dictionary and calculate for each point?

Body:
Try this. If you want, you can replace the int id with a Control.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reactive.Linq;
using System.Windows.Forms;

namespace Anything
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var random = new Random();
            var bounds = Screen.PrimaryScreen.Bounds;
            var extents = new Dictionary<int, Rectangle>();

            for (var i = 0; i < 300; i++)
            {
                var x = random.Next(bounds.Width);
                var y = random.Next(bounds.Height);
                var w = random.Next(bounds.Width - x);
                var h = random.Next(bounds.Height - y);

                extents[i] = new Rectangle(x, y, w, h);
            }

            var domains = from time in Observable.Interval(TimeSpan.FromMilliseconds(100))
                          from extent in extents
                          where extent.Value.Contains(Control.MousePosition)
                          select extent.Key;

            var subscription = domains.Subscribe(id => Console.Write($"{id},"));

            Console.ReadKey();

            subscription.Dispose();
        }
    }
}


问:
Mysql select rows except first row
I have issue there with select from table. I want to select all rows except for first row. So .. There is my code

```<code>SELECT * FROM table ORDER BY id DESC
</code>```

So this code select and order id's from table which give me id feedback "5>4>3>2>1". And there is issue .. How I can select and echo just 4>3>2>1 rows.
So if I had rows with id's 1,2,6,8,10 , echo will be 10,8,6,2,1 and I want select to echo just 8,6,2,1.

There is my full wrong code for select.

```<code>$other = mysql_query("SELECT * FROM table ORDER BY id DESC LIMIT 1, 1");
</code>```

答:
This should do it.    </p>

```<code>SELECT * FROM table WHERE id NOT IN (SELECT MAX(id) FROM table) ORDER BY id DESC
</code>```

Title: Mysql select rows except first row

Body:
I have issue there with select from table. I want to select all rows except for first row. So .. There is my code

SELECT * FROM table ORDER BY id DESC

So this code select and order id's from table which give me id feedback "5>4>3>2>1". And there is issue .. How I can select and echo just 4>3>2>1 rows.
So if I had rows with id's 1,2,6,8,10 , echo will be 10,8,6,2,1 and I want select to echo just 8,6,2,1.

There is my full wrong code for select.

$other = mysql_query("SELECT * FROM table ORDER BY id DESC LIMIT 1, 1");

Body:
This should do it.

SELECT * FROM table WHERE id NOT IN (SELECT MAX(id) FROM table) ORDER BY id DESC


问:
protractor-jasmine2-html-reporter doesn't create html report
I have the following configuration in protractor config.js, but it is generating only the screenshots in the specified folder not the HTML report.

I have gone through the steps followed here

https://www.npmjs.com/package/protractor-jasmine2-html-reporter

```<code>var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');

onPrepare() {

    jasmine.getEnv().addReporter(new Jasmine2HtmlReporter({
            savePath: './test/reports/',
            fileName: 'MyReportName'
        }));
  }
</code>```

Can someone specify where I'm missing or is there any version specific issue?

I'm using
Protractor Version 5.2.0,
Node v6.11.2

答:
I have issues with spec file which is causing the html report generation.

If we didn't provide expect and finish the it function, html report is not generating.

Always expect is mandatory

Body:
I have the following configuration in protractor config.js, but it is generating only the screenshots in the specified folder not the HTML report.

I have gone through the steps followed here

https://www.npmjs.com/package/protractor-jasmine2-html-reporter

var Jasmine2HtmlReporter = require('protractor-jasmine2-html-reporter');

onPrepare() {

    jasmine.getEnv().addReporter(new Jasmine2HtmlReporter({
            savePath: './test/reports/',
            fileName: 'MyReportName'
        }));
  }

Can someone specify where I'm missing or is there any version specific issue?

I'm using
Protractor Version 5.2.0,
Node v6.11.2


问:
How do I filter rows of an array so that only records with a particular value are displayed?
Imagine I am running 2 queries each one against a different database.

The query result from source #1 will be stored in an array.
The query result from source #2 will also be stored in an array.

Source #2 records will contain a foreign key that may or may not match up with particular records in an ID field in source #1.

So if I were to loop through source #1 and then I wanted to display only the source #2 records that matched the ID of source #1 is there a handy command within PHP that will allow me to get the filtered results that I could run once each time I ran the loop.

What I would like to avoid is having a loop within a loop to check the result before determining if it should be displayed (hopefully a built in filter command if available will have less overhead).

Any suggestions on commands that filter an array within PHP?

答:
That depends on what you're optimizing for.

Lines of code: use array_intersect as mentioned by Matt V (possibly after some preprocessing).

Memory / performance: create a dictionary (associative array) where the keys are the IDs of source #1. If memory is a concern, discard the rows once they are processed. Values can be anything, say TRUE. You can now filter the array from source #2 using isset($dict[$id]), which runs in near constant time. array_filter can be useful here.


问:
How to send low-level escape sequences to a printer on OS X?
I have a string of printer escape sequences (ESC/P) that I need to send to a printer (either USB or network) on Mac OS X. How can I do that? Is using CUPS directly the best way? Is there a "higher level" way?

And before you ask: I really do need to send escape sequences and can't simply use the high-level printing system.

Edit: These are some projects and resources that provide similar functionality in other languages like Java:

http://code.google.com/p/escprinter/

http://code.google.com/p/escprinter/source/browse/trunk/net/drayah/matrixprinter/ESCPrinter.java

http://code.google.com/p/jzebra/

答:
We are printing from Mac bash shell using scripting (in professional automated End Of Line product tester).

Very simplified "Hello" label prints like this:

```<code>data="\x1Bia\x00"
data="${data}\x1B@"
data="${data}\x1BX\x32"
data="${data}Hello"
data="${data}\x0C"

# Check your own binary for debugging:
echo -ne $data | hexdump -C

# print the actual label
echo -ne $data | lp -d Brother_PT_P900W
</code>```

Note, that you must replace the printer name with your own printer name.

Body:
We are printing from Mac bash shell using scripting (in professional automated End Of Line product tester).

Very simplified "Hello" label prints like this:

data="\x1Bia\x00"
data="${data}\x1B@"
data="${data}\x1BX\x32"
data="${data}Hello"
data="${data}\x0C"

# Check your own binary for debugging:
echo -ne $data | hexdump -C

# print the actual label
echo -ne $data | lp -d Brother_PT_P900W

Note, that you must replace the printer name with your own printer name.


问:
How to close a modal popup window when pressing the escape key
I have an ABAP Z-report which shows a modal popup window(screen). Is it possible to close it when user presses an escape key?

I'm showing the popup using the next screen call

```<code>call screen 0100 STARTING AT 10 10 ENDING AT 110 30.
</code>```

The screen has the next PAI module:

```<code>MODULE USER_COMMAND_0100 INPUT.

  clear gv_ok.

  case sy-ucomm.

      when 'BTN_OK'.
          gv_ok = 'X'.
          LEAVE TO SCREEN 0.

    when 'BTN_CANC'.
      perform clean.
      LEAVE TO SCREEN 0.
  endcase.

ENDMODULE.                 " USER_COMMAND_0100  INPUT
</code>```

But the PAI module is not called whe the user presses an escape key.

The flow logic section is

```<code>PROCESS BEFORE OUTPUT.
  MODULE STATUS_0100.
*
PROCESS AFTER INPUT.
  MODULE USER_COMMAND_0100.
  module exit at exit-command.
</code>```

Nothing from PAI modules is called while Esc key is being pressed.

答:
Here is what you have to check in the GUI status:

The escape key is assigned automatically to this, you only need to assign the command (BUT_CANC, it is ZCANC in my example).

Body:
I have an ABAP Z-report which shows a modal popup window(screen). Is it possible to close it when user presses an escape key?

I'm showing the popup using the next screen call

call screen 0100 STARTING AT 10 10 ENDING AT 110 30.

The screen has the next PAI module:

MODULE USER_COMMAND_0100 INPUT.

  clear gv_ok.

  case sy-ucomm.

      when 'BTN_OK'.
          gv_ok = 'X'.
          LEAVE TO SCREEN 0.

    when 'BTN_CANC'.
      perform clean.
      LEAVE TO SCREEN 0.
  endcase.

ENDMODULE.                 " USER_COMMAND_0100  INPUT

But the PAI module is not called whe the user presses an escape key.

The flow logic section is

PROCESS BEFORE OUTPUT.
  MODULE STATUS_0100.
*
PROCESS AFTER INPUT.
  MODULE USER_COMMAND_0100.
  module exit at exit-command.

Nothing from PAI modules is called while Esc key is being pressed.


问:
Processing large xml files
I am having a large xml file which contains many sub elements. I want to able to run some xpath queries. I tried using vtd-xml in java, but I get outofmemory error sometimes, because the xml is so large to fit into memory. Is there an alternative way of processing such large xml's.</p>

答:
try http://code.google.com/p/jlibs/wiki/XMLDog

it executes xpaths using sax without creating in-memory representation of xml documents.

Title: Processing large xml files


问:
Audible notifications using alarm stream when ring volume is silenced (Android Oreo)
I have an existing app that was able to produce an audible notification sound even when the device had its ring volume silenced by using the Alarm audio stream (assuming the Alarm volume was non-zero).  This worked fine on Android 7.1.2

After upgrading my device to Oreo (8.0.0), the notification is no longer audible unless the ring volume is non-zero. The app was unchanged.

So my attempt to fix this was to recompile against Oreo (SDK 26) APIs and include the new NotificationChannel stuff just to see if that helped, which it did not.

Note that this code is executing from within a Service.

Here is a code excerpt:

```<code>int importance = NotificationManager.IMPORTANCE_MAX;
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

NotificationChannel mChannel = new NotificationChannel("channel1", "Alarms", importance);
mChannel.setDescription("Alarms that alert you immediately");
mChannel.enableLights(true);

mChannel.enableVibration(true);
mChannel.setSound(defaultSoundUri,
   new AudioAttributes.Builder()
      .setUsage(AudioAttributes.USAGE_ALARM)
      .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
      .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
   .build()
);

notificationManager.createNotificationChannel(mChannel);

Notification.Builder notificationBuilder = new Notification.Builder(this,"channel1")
        .setSmallIcon(R.drawable.ic_stat_ic_notification)
        .setContentTitle("Alarm Message")
        .setContentText(messageBody)
        .setAutoCancel(true)
        .setSound(defaultSoundUri, new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ALARM)
                .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build())
        .setContentIntent(pendingIntent)
        .setCategory(Notification.CATEGORY_ALARM)
        .setPriority(Notification.PRIORITY_MAX);

Notification n = notificationBuilder.build();
n.flags = n.flags | Notification.FLAG_INSISTENT;
notificationManager.notify(0 /* ID of notification */, n);
</code>```

Any ideas?

答:
I also struggled with this issue. I haven't found out why this is happening, but I worked around this issue using the MediaPlayer. I removed the part where the sound is added to the notification and replaced that part with this:

```<code>        Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        final MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(this.getApplicationContext(), ringtoneUri);
        mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setLegacyStreamType(AudioManager.STREAM_ALARM).build());
        mediaPlayer.setLooping(false);
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
           public final void onCompletion(MediaPlayer it) {
              mediaPlayer.stop();
              mediaPlayer.release();
           }
        });
        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
           public final void onPrepared(MediaPlayer it) {
              mediaPlayer.start();
           }
        });
        mediaPlayer.prepareAsync();
</code>```

Body:
I have an existing app that was able to produce an audible notification sound even when the device had its ring volume silenced by using the Alarm audio stream (assuming the Alarm volume was non-zero).  This worked fine on Android 7.1.2

After upgrading my device to Oreo (8.0.0), the notification is no longer audible unless the ring volume is non-zero. The app was unchanged.

So my attempt to fix this was to recompile against Oreo (SDK 26) APIs and include the new NotificationChannel stuff just to see if that helped, which it did not.

Note that this code is executing from within a Service.

Here is a code excerpt:

int importance = NotificationManager.IMPORTANCE_MAX;
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);

NotificationChannel mChannel = new NotificationChannel("channel1", "Alarms", importance);
mChannel.setDescription("Alarms that alert you immediately");
mChannel.enableLights(true);

mChannel.enableVibration(true);
mChannel.setSound(defaultSoundUri,
   new AudioAttributes.Builder()
      .setUsage(AudioAttributes.USAGE_ALARM)
      .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
      .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
   .build()
);

notificationManager.createNotificationChannel(mChannel);

Notification.Builder notificationBuilder = new Notification.Builder(this,"channel1")
        .setSmallIcon(R.drawable.ic_stat_ic_notification)
        .setContentTitle("Alarm Message")
        .setContentText(messageBody)
        .setAutoCancel(true)
        .setSound(defaultSoundUri, new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ALARM)
                .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build())
        .setContentIntent(pendingIntent)
        .setCategory(Notification.CATEGORY_ALARM)
        .setPriority(Notification.PRIORITY_MAX);

Notification n = notificationBuilder.build();
n.flags = n.flags | Notification.FLAG_INSISTENT;
notificationManager.notify(0 /* ID of notification */, n);

Any ideas?

Body:
I also struggled with this issue. I haven't found out why this is happening, but I worked around this issue using the MediaPlayer. I removed the part where the sound is added to the notification and replaced that part with this:

        Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        final MediaPlayer mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(this.getApplicationContext(), ringtoneUri);
        mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setLegacyStreamType(AudioManager.STREAM_ALARM).build());
        mediaPlayer.setLooping(false);
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
           public final void onCompletion(MediaPlayer it) {
              mediaPlayer.stop();
              mediaPlayer.release();
           }
        });
        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
           public final void onPrepared(MediaPlayer it) {
              mediaPlayer.start();
           }
        });
        mediaPlayer.prepareAsync();


问:
How to return a Promise Function in For loop?
I have a function (sendEmail) as you see here:

```<code>public async sendEmail (log: LogMessage): Promise<void> {
nodemailer.createTestAccount(async () => {
      return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => {
....
</code>```

I want to use it in a for loop:

```<code>for (const log of logs) {
          const timestamp = moment(log.creationDate)
          const startTime = new Date(Date.now())
          if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {

            return this.sendEmail(log)
          }
        }
</code>```

I cannot delete "return this.sendEmail(log)", because the function returns Promise. But the loop works just one time and with the first log, it would be terminated.
How can I use the function in this loop?

答:
You need to put all the promises in an array and create a promise that completes when all the sendEmail promises complete.

```<code>sendAll() {
    let allMails: Promise<void>[] = [];
    for (const log of logs) {
        const timestamp = moment(log.creationDate)
        const startTime = new Date(Date.now())
        if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {

            allMails.push(this.sendEmail(log));
        }
    }
    return Promise.all(allMails);
}
</code>```

The version above launches all the requests in parallel. If you want to run sendEmail sequentially you can use async/await to wait while an email is ent before you send the next:

```<code>async sendAll() : Promise<void>{
    for (const log of logs) {
        const timestamp = moment(log.creationDate)
        const startTime = new Date(Date.now())
        if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {

            await this.sendEmail(log);
        }
    }
}
</code>```

Body:
I have a function (sendEmail) as you see here:

public async sendEmail (log: LogMessage): Promise<void> {
nodemailer.createTestAccount(async () => {
      return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => {
....

I want to use it in a for loop:

for (const log of logs) {
          const timestamp = moment(log.creationDate)
          const startTime = new Date(Date.now())
          if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {

            return this.sendEmail(log)
          }
        }

I cannot delete "return this.sendEmail(log)", because the function returns Promise. But the loop works just one time and with the first log, it would be terminated.
How can I use the function in this loop?

Body:
You need to put all the promises in an array and create a promise that completes when all the sendEmail promises complete.

sendAll() {
    let allMails: Promise<void>[] = [];
    for (const log of logs) {
        const timestamp = moment(log.creationDate)
        const startTime = new Date(Date.now())
        if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {

            allMails.push(this.sendEmail(log));
        }
    }
    return Promise.all(allMails);
}

The version above launches all the requests in parallel. If you want to run sendEmail sequentially you can use async/await to wait while an email is ent before you send the next:

async sendAll() : Promise<void>{
    for (const log of logs) {
        const timestamp = moment(log.creationDate)
        const startTime = new Date(Date.now())
        if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {

            await this.sendEmail(log);
        }
    }
}


问:
Difference in days between two dates in Impala
I am trying to find a date difference In Impala. I have tried a few options. my most recent is below

ABS(dayofyear(CAST(firstdate AS TIMESTAMP)-dayofyear(CAST(seconddate AS TIMESTAMP)

an example of data looks like:

firstDate:
  2017-11-25
  secondDate: 2017-11-30

The solution that I am looking for in the above scenario would be five. The provided code would give me this answer, but the trouble comes in when the first date is in december and the second one ends in January.

Firstdate: 2016-12-30 seconddate:2017-12-30

with the above code this gives me an output of 358 days,the outcome that I would want to see is 8 days. This code is only looking at what day of the year this falls on, and is not able to consider moving from year to year. I know that there is no datediff function on Impala and I've also tried using just subtraction on the two timestamps but that didn't work either. I have scoured google and have come back empty any suggestions would be greatly appreciated

答:
SQL

```<code>SELECT DATEDIFF(TO_DATE(firstdate), TO_DATE(seconddate));
</code>```

Is this what you are looking for?

Body:
SQL

SELECT DATEDIFF(TO_DATE(firstdate), TO_DATE(seconddate));

Is this what you are looking for?


问:
Google Earth Engine: Finding the right image dimensions to get max resolution on satellite imagery
I am new to Google Earth Engine, and was trying to get Landsat imagery for the entire Democratic Republic of Congo. The project involves some computer vision and image segmentation, so I need to get the highest resolution possible.

I have some code that I developed from the earth engine to make a composite from 1 year of landsat imagery posted below.

```<code>var geometry = ee.Geometry.Polygon(
    [[[29.70703125, -3.3160183381615123],
      [24.609375, -3.4476246666468526],
      [24.8291015625, -7.732765062729807],
      [29.970703125, -7.645664723491028]]]);

// Composite 6 months of Landsat 8.

Map.setCenter(  26.362312, -4.643601, 5);
var boundingBox = geometry.bounds(1)
var L8 = ee.ImageCollection('LANDSAT/LC08/C01/T1');
var composite = ee.Algorithms.Landsat.simpleComposite({
  collection: L8.filterDate('2015-1-1', '2015-7-1').filterBounds(geometry),
  asFloat: true});
var region = ee.Geometry(geometry.getInfo())
                        .toGeoJSONString()
var params ={
      crs: 'EPSG:4326',
      region:region
    }
Export.image(composite,'congo_test',params);
</code>```

The problem is that each time I run the script it asks me for the scale value. So I ask for the highest resolution, but the query keeps erroring out because it says that I have exceeded the maximum pixel limit for the image export.

So basically I need to figure out how to carve up congo into a set of blocks for which Earth Engine allows me to pull max resolution composite imagery. Does anyone know how I can calculate the correct size polygons to fit the bill?

答: You should specify a scale in the export parameters.  Composites don't have a native scale anymore, so they default to 1 degree per pixel.  Since you started with landsat, you probably want a scale of 30.</p>

Body:
I am new to Google Earth Engine, and was trying to get Landsat imagery for the entire Democratic Republic of Congo. The project involves some computer vision and image segmentation, so I need to get the highest resolution possible.

I have some code that I developed from the earth engine to make a composite from 1 year of landsat imagery posted below.

var geometry = ee.Geometry.Polygon(
    [[[29.70703125, -3.3160183381615123],
      [24.609375, -3.4476246666468526],
      [24.8291015625, -7.732765062729807],
      [29.970703125, -7.645664723491028]]]);

// Composite 6 months of Landsat 8.

Map.setCenter(  26.362312, -4.643601, 5);
var boundingBox = geometry.bounds(1)
var L8 = ee.ImageCollection('LANDSAT/LC08/C01/T1');
var composite = ee.Algorithms.Landsat.simpleComposite({
  collection: L8.filterDate('2015-1-1', '2015-7-1').filterBounds(geometry),
  asFloat: true});
var region = ee.Geometry(geometry.getInfo())
                        .toGeoJSONString()
var params ={
      crs: 'EPSG:4326',
      region:region
    }
Export.image(composite,'congo_test',params);

The problem is that each time I run the script it asks me for the scale value. So I ask for the highest resolution, but the query keeps erroring out because it says that I have exceeded the maximum pixel limit for the image export.

So basically I need to figure out how to carve up congo into a set of blocks for which Earth Engine allows me to pull max resolution composite imagery. Does anyone know how I can calculate the correct size polygons to fit the bill?


问:
Excel sumifs entries in current week
I have the following table that calculates the total hours worked each day

Total (real) = End (real) - LUNCH - START

I need to calculate the number of hours worked so far only in the current week.  I have tried SUMIFS() to compare the weeknum and year of the data to only sum data from the current week.  I am saving this to a cell off the screenshot.

This is the jist of what I would like to achieve.  I recognize the syntax is off:
=SUMIFS(G:G,A:A,WEEKNUM(A:A)==WEEKNUM(TODAY()),year(A:A)==year(today()))

Where is my syntax heading off track?

Note - Not using a pivot table for this application.  So I need this to be formula-based.

答:
Use this that finds the date of Sunday before and Saturday after and uses them as brackets:</p>

```<code>=SUMIFS(G:G,A:A,">=" & INT((TODAY()-1)/7)*7+1,A:A,"<" & INT((TODAY()-1)/7)*7+8)
</code>```

Title: Excel sumifs entries in current week

Body:
Use this that finds the date of Sunday before and Saturday after and uses them as brackets:

=SUMIFS(G:G,A:A,">=" & INT((TODAY()-1)/7)*7+1,A:A,"<" & INT((TODAY()-1)/7)*7+8)


问:
Android OpenGL ES Color Byte Order
I'm having the problem that my textures are rendering incorrect colors and based on this it seems like Android's reading the colors in reverse order.

I tried solving the problem as the reference says but GL_BGR_EXT is not defined in the Android NDK nor is GL_UNSIGNED_SHORT_5_6_5_REV. How can I reverse the color byte order in the Android NDK?

答: You should do it, swapping the R and B channels of your texture. OpenGL supported that feature, but it was removed in OpenGL ES to make drivers more simple.</p>

Title: Android OpenGL ES Color Byte Order


问:
JSON parse on a JSON string throws "Cannot convert object to primitive value"
server.js

uses the body parser middleware, handlebars and express

route

```<code>module.exports = function (app) {
    app.post('/questionnaire/submit', function (req, res) { // Ajax Call
        var data = JSON.parse(req.body);
        res.send({});
    });
};
</code>```

client

```<code>function submitData() { // Send a data object to the server
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: "text 1",
            improvement: "text 2",
            rating: 0.7
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}
</code>```

when logging req.body I get a JSON string

{ '{"satisfactory":"text 1","improvement":"text 2","rating":0.7}': '' }

and I try to parse this string to an object. When I do so, I get this error message

```<code>     TypeError: Cannot convert object to primitive value
     at JSON.parse (<anonymous>)
     at C:\Users\mah\Desktop\FeedbackTool\Server\Routes\questionnaire.js:12:25
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at next (C:\Users\mah\node_modules\express\lib\router\route.js:137:13)
     at Route.dispatch (C:\Users\mah\node_modules\express\lib\router\route.js:112:3)
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at C:\Users\mah\node_modules\express\lib\router\index.js:281:22
     at Function.process_params (C:\Users\mah\node_modules\express\lib\router\index.js:335:12)
     at next (C:\Users\mah\node_modules\express\lib\router\index.js:275:10)
     at C:\Users\mah\node_modules\body-parser\lib\read.js:130:5
</code>```

so how can I parse the string to an object?

Normally I would execute JSON.parse(req.body).

答:
You need to setup correct contentType:

```<code>$.ajax({
    type: 'POST',
    url: '/questionnaire/submit',
    contentType: 'application/json',
    data: JSON.stringify({ satisfactory: "text 1", rating: 0.7 })
});

app.post('/questionnaire/submit', function (req, res) { // Ajax Call
    var data = JSON.parse(req.body);
    console.log(data.rating); // 0.7
    res.send(data);
});
</code>```

Also, with body-parser you may avoid JSON.parse calls on the server side, the link.

Body:
server.js

uses the body parser middleware, handlebars and express

route

module.exports = function (app) {
    app.post('/questionnaire/submit', function (req, res) { // Ajax Call
        var data = JSON.parse(req.body);
        res.send({});
    });
};

client

function submitData() { // Send a data object to the server
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: "text 1",
            improvement: "text 2",
            rating: 0.7
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

when logging req.body I get a JSON string

{ '{"satisfactory":"text 1","improvement":"text 2","rating":0.7}': '' }

and I try to parse this string to an object. When I do so, I get this error message

     TypeError: Cannot convert object to primitive value
     at JSON.parse (<anonymous>)
     at C:\Users\mah\Desktop\FeedbackTool\Server\Routes\questionnaire.js:12:25
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at next (C:\Users\mah\node_modules\express\lib\router\route.js:137:13)
     at Route.dispatch (C:\Users\mah\node_modules\express\lib\router\route.js:112:3)
     at Layer.handle [as handle_request] (C:\Users\mah\node_modules\express\lib\router\layer.js:95:5)
     at C:\Users\mah\node_modules\express\lib\router\index.js:281:22
     at Function.process_params (C:\Users\mah\node_modules\express\lib\router\index.js:335:12)
     at next (C:\Users\mah\node_modules\express\lib\router\index.js:275:10)
     at C:\Users\mah\node_modules\body-parser\lib\read.js:130:5

so how can I parse the string to an object?

Normally I would execute JSON.parse(req.body).

Body:
You need to setup correct contentType:

$.ajax({
    type: 'POST',
    url: '/questionnaire/submit',
    contentType: 'application/json',
    data: JSON.stringify({ satisfactory: "text 1", rating: 0.7 })
});

app.post('/questionnaire/submit', function (req, res) { // Ajax Call
    var data = JSON.parse(req.body);
    console.log(data.rating); // 0.7
    res.send(data);
});

Also, with body-parser you may avoid JSON.parse calls on the server side, the link.


问:
Content of unmatched string
I am parsing input from stdin, which is in the following format:

```<code>1
2
3
done
</code>```

My current code is:

```<code>while(<> =~ /(\d+)/) {
    # do something with $1
}
# I want to access the line following the last number here
</code>```

which is fine for the 1st part of the file (with the list of numbers).
However, I would like the content of the line immediately following the last number.

Is there any elegant way to do it?

答:
You can do it this way

```<code>my $var = <>;
chomp $var;

while($var =~ /^(\d+)$/)
{
    #here do stuff with $var, containing only numbers

    $var = <>;
    chomp $var;
}

# here do stuff with $var, containing now a word
</code>```

other thing: by changing /(\d+)/ for /^(\d+)$/ you make sure your entry contains ONLY numbers ;)

Title: Content of unmatched string

Body:
I am parsing input from stdin, which is in the following format:

1
2
3
done

My current code is:

while(<> =~ /(\d+)/) {
    # do something with $1
}
# I want to access the line following the last number here

which is fine for the 1st part of the file (with the list of numbers).
However, I would like the content of the line immediately following the last number.

Is there any elegant way to do it?

Body:
You can do it this way

my $var = <>;
chomp $var;

while($var =~ /^(\d+)$/)
{
    #here do stuff with $var, containing only numbers

    $var = <>;
    chomp $var;
}

# here do stuff with $var, containing now a word

other thing: by changing /(\d+)/ for /^(\d+)$/ you make sure your entry contains ONLY numbers ;)


问:
npm run dev doesn't work
enter image description hereI run npm run dev but I get this:

0 info it worked if it ends with ok
 1 verbose cli [ 'C:\Program
  Files\nodejs\node.exe',
 1 verbose cli   'C:\Program
  Files\nodejs\node_modules\npm\bin\npm-cli.js',
 1 verbose cli
  'run',
 1 verbose cli   'dev' ]
 2 info using npm@5.5.1
 3
  info using node@v8.9.1
 4 verbose run-script [ 'predev', 'dev',
  'postdev' ]
 5 info lifecycle @~predev: @
 6 info lifecycle
  @~dev: @
 7 verbose lifecycle @~dev: unsafe-perm in lifecycle
  true
 8 verbose lifecycle @~dev: PATH: C:\Program
  Files\nodejs\node_modules\npm\bin\node-gyp-bin;c:\xampp\htdocs\laravelapp\node_modules.bin;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program
  Files (x86)\Skype\Phone\;E:\Java\bin;C:\Program Files\Microsoft SQL
  Server\130\Tools\Binn\;C:\Program Files\dotnet\;C:\Program Files
  (x86)\Brackets\command;C:\ProgramData\ComposerSetup\bin;C:\Program
  Files\PuTTY\;C:\Program Files (x86)\WinSCP\;C:\Program
  Files\Git\cmd;C:\Program Files\nodejs\;C:\Program
  Files\Java\jdk1.8.0_112\bin;L:\Microsof3t VS
  Code\bin;C:\Users\SuperServer\AppData\Local\GitHubDesktop\bin;C:\Users\SuperServer\AppData\Local\atom\bin;C:\Xampp\php;C:\Users\SuperServer\AppData\Roaming\Composer\vendor\bin;E:\nodeJs\npm;E:\NodeJS\node_modules\npm;C:\Users\SuperServer\AppData\Roaming\npm;C:\Program
  Files\nodejs\node_modules\npm\bin;
 9 verbose lifecycle @~dev:
  CWD: c:\xampp\htdocs\laravelapp
 10 silly lifecycle @~dev: Args: [
  '/d /s /c', 'npm run development' ]
 11 info lifecycle @~dev:
  Failed to exec dev script
 12 silly lifecycle @~dev: Returned:
  code: -4058  signal: null
 13 info lifecycle @~dev: Failed to exec
  dev script
 14 verbose stack Error: @ dev: npm run
  development
 14 verbose stack spawn C:\Windows\system32\cmd.exe;
  E:\Java\bin ENOENT
 14 verbose stack     at _errnoException
  (util.js:1024:11)
 14 verbose stack     at
  Process.ChildProcess._handle.onexit
  (internal/child_process.js:190:19)
 14 verbose stack     at
  onErrorNT (internal/child_process.js:372:16)
 14 verbose stack

  at _combinedTickCallback (internal/process/next_tick.js:138:11)

  14 verbose stack     at process._tickCallback
  (internal/process/next_tick.js:180:9)
 15 verbose pkgid @
 16
  verbose cwd c:\xampp\htdocs\laravelapp
 17 verbose Windows_NT
  6.1.7601
 18 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "run"
  "dev"
 19 verbose node v8.9.1
 20 verbose npm  v5.5.1
 21
  error file C:\Windows\system32\cmd.exe; E:\Java\bin
 22 error path
  C:\Windows\system32\cmd.exe; E:\Java\bin
 23 error code
  ELIFECYCLE
 24 error errno ENOENT
 25 error syscall spawn
  C:\Windows\system32\cmd.exe; E:\Java\bin
 26 error @ dev: npm run
  development
 26 error spawn C:\Windows\system32\cmd.exe;
  E:\Java\bin ENOENT
 27 error Failed at the @ dev script.
 27
  error This is probably not a problem with npm. There is likely
  additional logging output above.
 28 verbose exit [ 1, true ]

Can anyone help me with this?

答: It seems that your "dev" task errors because it tries to spawn a new java process with the java binary located at E:\Java\bin but this binary doesn't exist (ENOENT). Can you add an excerpt of the "package.json" file with definition of your "dev" script?

Title: npm run dev doesn't work


问:
Preventing a UITabBar from applying a gradient to its icon images
When I make icons for a UITabBar, it applies a gradient to the images. I need to know how to prevent it from having this gradient.</p>

答:
It's been almost a year but here is the code. Add this as a category to UIImage or convert to class-wide. Remember, the image you are passing (self) has to be an alpha only image (the mask is created based on the visible parts of the image).

```<code>

- (UIImage *) imageWithBackgroundColor:(UIColor *)bgColor
                           shadeAlpha1:(CGFloat)alpha1
                           shadeAlpha2:(CGFloat)alpha2
                           shadeAlpha3:(CGFloat)alpha3
                           shadowColor:(UIColor *)shadowColor
                          shadowOffset:(CGSize)shadowOffset
                            shadowBlur:(CGFloat)shadowBlur {

    UIImage *image = self;

    CGColorRef cgColor = [bgColor CGColor];
    CGColorRef cgShadowColor = [shadowColor CGColor];

    CGFloat components[16] = {1,1,1,alpha1,1,1,1,alpha1,1,1,1,alpha2,1,1,1,alpha3};
    CGFloat locations[4] = {0,0.5,0.6,1};

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGGradientRef colorGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, (size_t)4);

    CGRect contextRect;
    contextRect.origin.x = 0.0f;
    contextRect.origin.y = 0.0f;
    contextRect.size = [image size];
    //contextRect.size = CGSizeMake([image size].width+5,[image size].height+5);
    // Retrieve source image and begin image context
    UIImage *itemImage = image;
    CGSize itemImageSize = [itemImage size];
    CGPoint itemImagePosition;
    itemImagePosition.x = ceilf((contextRect.size.width - itemImageSize.width) / 2);
    itemImagePosition.y = ceilf((contextRect.size.height - itemImageSize.height) / 2);
    UIGraphicsBeginImageContext(contextRect.size);
    CGContextRef c = UIGraphicsGetCurrentContext();
    // Setup shadow
    CGContextSetShadowWithColor(c, shadowOffset, shadowBlur, cgShadowColor);
    // Setup transparency layer and clip to mask
    CGContextBeginTransparencyLayer(c, NULL);
    CGContextScaleCTM(c, 1.0, -1.0);
    CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [itemImage CGImage]);
    // Fill and end the transparency layer
    CGContextSetFillColorWithColor(c, cgColor);
    contextRect.size.height = -contextRect.size.height;
    CGContextFillRect(c, contextRect);
    CGContextDrawLinearGradient(c, colorGradient,CGPointZero,CGPointMake(contextRect.size.width*1.0/4.0,contextRect.size.height),0);
    CGContextEndTransparencyLayer(c);
    //CGPointMake(contextRect.size.width*3.0/4.0, 0)
    // Set selected image and end context
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGColorSpaceRelease(colorSpace);
    CGGradientRelease(colorGradient);

    return resultImage;

}
</code>```

For example, the following will produce an effect very similar to what the native tabbar does:

```<code>

UIImage *niceImage = [[UIImage imageNamed:@"image_name"] imageWithBackgroundColor:[UIColor colorWithRed:41.0/255.0 green:147.0/255.0 blue:239.0/255.0 alpha:1.0]
                                                                      shadeAlpha1:0.6
                                                                      shadeAlpha2:0.0
                                                                      shadeAlpha3:0.4
                                                                      shadowColor:[UIColor blackColor]
                                                                     shadowOffset:CGSizeMake(0.0f, -1.0f)
                                                                       shadowBlur:3.0];

</code>```

Body:
It's been almost a year but here is the code. Add this as a category to UIImage or convert to class-wide. Remember, the image you are passing (self) has to be an alpha only image (the mask is created based on the visible parts of the image).

- (UIImage *) imageWithBackgroundColor:(UIColor *)bgColor
                           shadeAlpha1:(CGFloat)alpha1
                           shadeAlpha2:(CGFloat)alpha2
                           shadeAlpha3:(CGFloat)alpha3
                           shadowColor:(UIColor *)shadowColor
                          shadowOffset:(CGSize)shadowOffset
                            shadowBlur:(CGFloat)shadowBlur {

    UIImage *image = self;

    CGColorRef cgColor = [bgColor CGColor];
    CGColorRef cgShadowColor = [shadowColor CGColor];

    CGFloat components[16] = {1,1,1,alpha1,1,1,1,alpha1,1,1,1,alpha2,1,1,1,alpha3};
    CGFloat locations[4] = {0,0.5,0.6,1};

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGGradientRef colorGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, (size_t)4);

    CGRect contextRect;
    contextRect.origin.x = 0.0f;
    contextRect.origin.y = 0.0f;
    contextRect.size = [image size];
    //contextRect.size = CGSizeMake([image size].width+5,[image size].height+5);
    // Retrieve source image and begin image context
    UIImage *itemImage = image;
    CGSize itemImageSize = [itemImage size];
    CGPoint itemImagePosition;
    itemImagePosition.x = ceilf((contextRect.size.width - itemImageSize.width) / 2);
    itemImagePosition.y = ceilf((contextRect.size.height - itemImageSize.height) / 2);
    UIGraphicsBeginImageContext(contextRect.size);
    CGContextRef c = UIGraphicsGetCurrentContext();
    // Setup shadow
    CGContextSetShadowWithColor(c, shadowOffset, shadowBlur, cgShadowColor);
    // Setup transparency layer and clip to mask
    CGContextBeginTransparencyLayer(c, NULL);
    CGContextScaleCTM(c, 1.0, -1.0);
    CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [itemImage CGImage]);
    // Fill and end the transparency layer
    CGContextSetFillColorWithColor(c, cgColor);
    contextRect.size.height = -contextRect.size.height;
    CGContextFillRect(c, contextRect);
    CGContextDrawLinearGradient(c, colorGradient,CGPointZero,CGPointMake(contextRect.size.width*1.0/4.0,contextRect.size.height),0);
    CGContextEndTransparencyLayer(c);
    //CGPointMake(contextRect.size.width*3.0/4.0, 0)
    // Set selected image and end context
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    CGColorSpaceRelease(colorSpace);
    CGGradientRelease(colorGradient);

    return resultImage;

}

For example, the following will produce an effect very similar to what the native tabbar does:

UIImage *niceImage = [[UIImage imageNamed:@"image_name"] imageWithBackgroundColor:[UIColor colorWithRed:41.0/255.0 green:147.0/255.0 blue:239.0/255.0 alpha:1.0]
                                                                      shadeAlpha1:0.6
                                                                      shadeAlpha2:0.0
                                                                      shadeAlpha3:0.4
                                                                      shadowColor:[UIColor blackColor]
                                                                     shadowOffset:CGSizeMake(0.0f, -1.0f)
                                                                       shadowBlur:3.0];


问:
How can I launch powershell.exe with the "default" colours from the PowerShell shortcut?
I'm attached to the nice blue colour of the PowerShell window when you launch it from one of the pre-installed shortcuts. However, if you manually launch powershell.exe, you don't get these colours, you get black/white :(

This is because the default settings are set on the shortcut (.lnk) file:

I've got a "PowerShell Prompt Here" entry in Explorer context menu, and I'd like it to launch PowerShell using the same nice colours as the usual shortcut; black sucks, and it's confusing to have different coloured windows (especially when I have some old-school command windows open frequently that are also black!).

I've found two problems with trying to set this so far:

Setting the colour from within PowerShell seems to only allow certain values (ConsoleColor enum), none of which match the one on the default shortcut.

Setting the colour within the PS Profile causes only text written afterwards to honour the new background colour. Adding "cls" causes a nasty flash of the original colour as it starts.

Is there any way to launch PowerShell from a command line (ie. that I can embed in the registry as an Explorer context menu item) that will use the same settings as the shortcut?

答:
Run regedit command to open registry editor

Track down HKEY_CURRENT_USER > CONSOLE and Backup entire folder by exporting just in case

Delete the folder

Restart your Powershell, the color scheme must have reset to defaults.

Note: If you have any other settings related to PowerShell (or Command Prompt, Git Bash etc) which you might want to keep, please further explore Console Folder to delete appropriate keys


问:
Im developing a Spring Java Project and I can not find the way to load static resources
I'm trying to use an image that I have saved in WEB-INF but I can not. I don't know why. I have tried several ways, but for some reason, I can not find the file. I have already tried Servlet Context, FileReader, and other methods, but always with unsuccessful results. I'm so tired. Any help would be greatly appreciated.

And this is the last code im using:

```<code>    FileReader fr = new FileReader("/WEB-INF/static/css/images/FotosDeUsuarios/FotoDeUsuario - " + unUsuario.getSsoId() + ".jpg");
    BufferedReader br = new BufferedReader(fr);
    String fotoDeUsuarioContenido = br.readLine();
    br.close();

    Image imgSc = Image.getInstance(fotoDeUsuarioContenido);

    imgSc.scaleAbsolute(50f, 50f);

    encabezadoCelda = new PdfPCell(imgSc);

    tabla.addCell(encabezadoCelda);
</code>```

答:
Have you tried  org.springframework.core.io.ClassPathResource

i.e.

FileReader fr = new FileReader(new ClassPathResource("/static/css/images/FotosDeUsuarios/FotoDeUsuario - " + unUsuario.getSsoId() + ".jpg").getFile())      ;

Body:
I'm trying to use an image that I have saved in WEB-INF but I can not. I don't know why. I have tried several ways, but for some reason, I can not find the file. I have already tried Servlet Context, FileReader, and other methods, but always with unsuccessful results. I'm so tired. Any help would be greatly appreciated.

And this is the last code im using:

    FileReader fr = new FileReader("/WEB-INF/static/css/images/FotosDeUsuarios/FotoDeUsuario - " + unUsuario.getSsoId() + ".jpg");
    BufferedReader br = new BufferedReader(fr);
    String fotoDeUsuarioContenido = br.readLine();
    br.close();

    Image imgSc = Image.getInstance(fotoDeUsuarioContenido);

    imgSc.scaleAbsolute(50f, 50f);

    encabezadoCelda = new PdfPCell(imgSc);

    tabla.addCell(encabezadoCelda);


问:
Copy only new data from one workbook to a separate 'master' copy
I have a worksheet where i need to add turnarounds times for each assessment. I might do 20+ assessments in a day and there will be a new row for each assessment.
At the end of each day i need to click a command button which will update a master copy my boss will have only new data entered from that day or the day before if i forget...

```<code>Sub CompareArrays()

Dim arr1() As Variant, arr2() As Variant, arr3() As Variant
Dim i As Long, j As Long, k As Long, nextRow As Long
Dim wb1 As Workbook, wb2 As Workbook
Dim x As Boolean

Set wb1 = Workbooks("Workbook1.xlsm") 'Name of first workbook
Set wb2 = Workbooks("Workbook2.xlsx") 'Name of second workbook
arr1 = wb1.Sheets(1).Range("A2:O" & wb1.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row).Value
arr2 = wb2.Sheets(1).Range("A2:O" & wb2.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row).Value
k = 1
For i = LBound(arr1) To UBound(arr1)
    x = True
    For j = LBound(arr2) To UBound(arr2)
        If arr1(i, 1) = arr2(j, 1) Then
            x = False
            Exit For
        End If
    Next j
    If x = True Then
        k = k + 1
        pos = Application.Match(arr1(i, 1), arr1, False) + 1
        nextRow = wb2.Sheets(1).Cells(Rows.Count, "A").End(xlUp).Row + 1
        wb2.Sheets(1).Rows(nextRow).EntireRow.Value = wb1.Sheets(1).Rows(pos).EntireRow.Value
    End If
Next i

End Sub
</code>```

The above code does not work at all but its the best i can figure out...I just need all new data from the last time i hit that commandbutton to be copied From A:O into a master workbook.

all i'm getting at the moment no matter that kind of code i try (and i have tried a good few!) keeps kicking back a script 9 error!!!

PLEASE HELP!

Thank you!!!!

答:
If you simply add to column P of wb1 the words "Sent" or "Not Sent" and then use the following code:</p>

```<code>Sub CompareArrays()
Dim i As Long
Dim wb1 As Workbook, wb2 As Workbook
Set wb1 = Workbooks("Workbook1.xlsm") 'Name of first workbook
Set wb2 = Workbooks("Workbook2.xlsx") 'Name of second workbook
LastRow = wb1.Cells(wb1.Rows.Count, "A").End(xlUp).Row 'check last row of wb1

For i = 2 To LastRow ' loop through wb1 to check if sent or not
    If wb1.Cells(i, 16).Value = "Not Sent" Then 'if not sent then copy the range from A to O, not including the helper column P
        NextfreeRow = wb2.Cells(wb2.Rows.Count, "A").End(xlUp).Row + 1
        wb2.Sheets(1).Range("A" & NextfreeRow & ":O" & NextfreeRow) = wb1.Sheets(1).Range("A" & i & ":O" & i).Value
        wb1.Cells(i, 16).Value = "Sent"
    End If
Next i
End Sub
</code>```

Body:
I have a worksheet where i need to add turnarounds times for each assessment. I might do 20+ assessments in a day and there will be a new row for each assessment.
At the end of each day i need to click a command button which will update a master copy my boss will have only new data entered from that day or the day before if i forget...

Sub CompareArrays()

Dim arr1() As Variant, arr2() As Variant, arr3() As Variant
Dim i As Long, j As Long, k As Long, nextRow As Long
Dim wb1 As Workbook, wb2 As Workbook
Dim x As Boolean

Set wb1 = Workbooks("Workbook1.xlsm") 'Name of first workbook
Set wb2 = Workbooks("Workbook2.xlsx") 'Name of second workbook
arr1 = wb1.Sheets(1).Range("A2:O" & wb1.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row).Value
arr2 = wb2.Sheets(1).Range("A2:O" & wb2.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row).Value
k = 1
For i = LBound(arr1) To UBound(arr1)
    x = True
    For j = LBound(arr2) To UBound(arr2)
        If arr1(i, 1) = arr2(j, 1) Then
            x = False
            Exit For
        End If
    Next j
    If x = True Then
        k = k + 1
        pos = Application.Match(arr1(i, 1), arr1, False) + 1
        nextRow = wb2.Sheets(1).Cells(Rows.Count, "A").End(xlUp).Row + 1
        wb2.Sheets(1).Rows(nextRow).EntireRow.Value = wb1.Sheets(1).Rows(pos).EntireRow.Value
    End If
Next i

End Sub

The above code does not work at all but its the best i can figure out...I just need all new data from the last time i hit that commandbutton to be copied From A:O into a master workbook.

all i'm getting at the moment no matter that kind of code i try (and i have tried a good few!) keeps kicking back a script 9 error!!!

PLEASE HELP!

Thank you!!!!

Body:
If you simply add to column P of wb1 the words "Sent" or "Not Sent" and then use the following code:

Sub CompareArrays()
Dim i As Long
Dim wb1 As Workbook, wb2 As Workbook
Set wb1 = Workbooks("Workbook1.xlsm") 'Name of first workbook
Set wb2 = Workbooks("Workbook2.xlsx") 'Name of second workbook
LastRow = wb1.Cells(wb1.Rows.Count, "A").End(xlUp).Row 'check last row of wb1

For i = 2 To LastRow ' loop through wb1 to check if sent or not
    If wb1.Cells(i, 16).Value = "Not Sent" Then 'if not sent then copy the range from A to O, not including the helper column P
        NextfreeRow = wb2.Cells(wb2.Rows.Count, "A").End(xlUp).Row + 1
        wb2.Sheets(1).Range("A" & NextfreeRow & ":O" & NextfreeRow) = wb1.Sheets(1).Range("A" & i & ":O" & i).Value
        wb1.Cells(i, 16).Value = "Sent"
    End If
Next i
End Sub


问:
ActiveRecord query across three models?
I have three models:

```<code>class User < ActiveRecord::Base
 has_many :projects, :through => :permissions

class Permission < ActiveRecord::Base
 belongs_to :user
 belongs_to :project
 belongs_to :role

class Project < ActiveRecord::Base
 has_many :users, :through => :permissions
</code>```

It's very easy with the above to get all of a Project's users: @project.users

But what I want to do is get something like this: Get all the Users in all of the user's projects.

So if a user has 3 projects, each with 5 users. I want to query to get all 15 users across all of the user's groups.

I'm trying that with.

```<code> current_user.projects.users
</code>```

but Rails isn't liking that much. current_user.projects works great, but not users.

Suggestions? Ideas? thanks!

UPDATED CODE 3 based on noodl's comments

```<code>  scope :suggestedContacts, lambda { |user|
    users_from_projects = user.projects.reduce([]) {|all_users,prj|
      all_users + prj.users
    }.uniq
  }
</code>```

ERRORS:

NoMethodError (undefined method `includes_values' for #):

答:
To your User class add:

```<code> has_many :users, :through => :permissions
</code>```

So it will look like:

```<code> class User < ActiveRecord::Base
   has_many :projects, :through => :permissions
   has_many :users, :through => :permissions
</code>```

Title: ActiveRecord query across three models?

Body:
I have three models:

class User < ActiveRecord::Base
 has_many :projects, :through => :permissions

class Permission < ActiveRecord::Base
 belongs_to :user
 belongs_to :project
 belongs_to :role

class Project < ActiveRecord::Base
 has_many :users, :through => :permissions

It's very easy with the above to get all of a Project's users: @project.users

But what I want to do is get something like this: Get all the Users in all of the user's projects.

So if a user has 3 projects, each with 5 users. I want to query to get all 15 users across all of the user's groups.

I'm trying that with.

 current_user.projects.users

but Rails isn't liking that much. current_user.projects works great, but not users.

Suggestions? Ideas? thanks!

UPDATED CODE 3 based on noodl's comments

  scope :suggestedContacts, lambda { |user|
    users_from_projects = user.projects.reduce([]) {|all_users,prj|
      all_users + prj.users
    }.uniq
  }

ERRORS:

NoMethodError (undefined method `includes_values' for #):

Body:
To your User class add:

 has_many :users, :through => :permissions

So it will look like:

 class User < ActiveRecord::Base
   has_many :projects, :through => :permissions
   has_many :users, :through => :permissions


问:
Leaflet.js centerOn function issue
I have an issue with Leaflet. I'm trying to add a function which permits to pan to given coordinates. It's working but the map automatically reverts to its initial position (after a few milliseconds). I'm afraid I can't find my mistake here.

Here is the code:

.btn {
  background: #3498db;
  background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
  background-image: -moz-linear-gradient(top, #3498db, #2980b9);
  background-image: -ms-linear-gradient(top, #3498db, #2980b9);
  background-image: -o-linear-gradient(top, #3498db, #2980b9);
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  -webkit-border-radius: 6;
  -moz-border-radius: 6;
  border-radius: 6px;
  font-family: Arial;
  color: #ffffff;
  font-size: 14px;
  padding: 5px 10px 5px 10px;
  text-decoration: none;
}

.btn:hover {
  background: #2b8ecc;
  background-image: -webkit-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -moz-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -ms-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -o-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: linear-gradient(to bottom, #2b8ecc, #4d687a);
  text-decoration: none;
}

.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropdown {
    position: relative;
    display: inline-block;
    z-index: 10;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

.dropdown:hover .dropbtn {
    background-color: #3e8e41;
}

.latlng{
    position: fixed;
    top:20px;
    right: 12px;
    color: white;
    font-Family: Arial;
    font-size: 14px;
}

.latlng input[type="submit"]{
    background-color: #4CAF50;
    color: white;
    cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html style="overflow-y: hidden; background: #666666;">
    <head>
        <title>WIMP</title>
        <link rel="stylesheet" href="style.css">
        <meta name="description" content="Geo Tactical System">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
    </head>
    <div id="mapid" style="position: fixed; width: 98.5vw; height: 90vh; bottom: 12px;"></div>
    <script>
        var mymap = L.map('mapid', { zoomControl:false }).setView([48.866, 2.3333], 13);

        L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
            maxZoom: 18,
            attribution: 'Map data © OpenStreetMap contributors, ' +
                    'CC-BY-SA, ' +
                    'Imagery © Mapbox',
            id: 'mapbox.streets'
        }).addTo(mymap);
    </script>
    <body>
        <div class="dropdown">
            <button class="dropbtn">Dropdown</button>
            <div class="dropdown-content">

            </div>
        </div>
        <form class="latlng" onsubmit="centerOn(document.getElementById('lat').value, document.getElementById('lng').value);">
            Lattitude:
            <input type="text" name="lat" id="lat" />
            Longitude:
            <input type="text" name="lng" id="lng" />
            <input type="submit" value="Centrer" />
        </form>
        <script>
            function centerOn(lat, lng){
                //mymap.setView({lat:lat, lng:lng}, mymap.getZoom());
                mymap.panTo([lat, lng]);
                //alert("Lattitude: " + lat + " longitude: " + lng);
            }

            function onMapHover(e){
                document.getElementById("lat").value = e.latlng.lat;
                document.getElementById("lng").value = e.latlng.lng;
            }
            mymap.on("mousemove", onMapHover);
        </script>
    </body>
</html></code>```

答:
You need to stop postback to prevent it from resetting. Each time you click on center, your page is posted back to server which loads the page again.

You can fix this by doing following steps:

modify

```<code>onsubmit="centerOn(
</code>```

to

```<code>onsubmit="return centerOn(
</code>```

and change

```<code>function centerOn(lat, lng){
  //mymap.setView({lat:lat, lng:lng}, mymap.getZoom());
  mymap.panTo([lat, lng]);
  //alert("Lattitude: " + lat + " longitude: " + lng);
}
</code>```

to

```<code>function centerOn(lat, lng){
  //mymap.setView({lat:lat, lng:lng}, mymap.getZoom());
  mymap.panTo([lat, lng]);
  return false;
  //alert("Lattitude: " + lat + " longitude: " + lng);
}
</code>```

See working sample below

.btn {
  background: #3498db;
  background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
  background-image: -moz-linear-gradient(top, #3498db, #2980b9);
  background-image: -ms-linear-gradient(top, #3498db, #2980b9);
  background-image: -o-linear-gradient(top, #3498db, #2980b9);
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  -webkit-border-radius: 6;
  -moz-border-radius: 6;
  border-radius: 6px;
  font-family: Arial;
  color: #ffffff;
  font-size: 14px;
  padding: 5px 10px 5px 10px;
  text-decoration: none;
}

.btn:hover {
  background: #2b8ecc;
  background-image: -webkit-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -moz-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -ms-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -o-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: linear-gradient(to bottom, #2b8ecc, #4d687a);
  text-decoration: none;
}

.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropdown {
    position: relative;
    display: inline-block;
    z-index: 10;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

.dropdown:hover .dropbtn {
    background-color: #3e8e41;
}

.latlng{
    position: fixed;
    top:20px;
    right: 12px;
    color: white;
    font-Family: Arial;
    font-size: 14px;
}

.latlng input[type="submit"]{
    background-color: #4CAF50;
    color: white;
    cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html style="overflow-y: hidden; background: #666666;">
    <head>
        <title>WIMP</title>
        <link rel="stylesheet" href="style.css">
        <meta name="description" content="Geo Tactical System">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
    </head>
    <div id="mapid" style="position: fixed; width: 98.5vw; height: 90vh; bottom: 12px;"></div>
    <script>
        var mymap = L.map('mapid', { zoomControl:false }).setView([48.866, 2.3333], 13);

        L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
            maxZoom: 18,
            attribution: 'Map data © OpenStreetMap contributors, ' +
                    'CC-BY-SA, ' +
                    'Imagery © Mapbox',
            id: 'mapbox.streets'
        }).addTo(mymap);
    </script>
    <body>
        <div class="dropdown">
            <button class="dropbtn">Dropdown</button>
            <div class="dropdown-content">

            </div>
        </div>
        <form class="latlng" onsubmit="return centerOn(document.getElementById('lat').value, document.getElementById('lng').value);">
            Lattitude:
            <input type="text" name="lat" id="lat" />
            Longitude:
            <input type="text" name="lng" id="lng" />
            <input type="submit" value="Centrer" />
        </form>
        <script>
            function centerOn(lat, lng){
                //mymap.setView({lat:lat, lng:lng}, mymap.getZoom());
                mymap.panTo([lat, lng]);
                return false;
                //alert("Lattitude: " + lat + " longitude: " + lng);
            }

            function onMapHover(e){
                document.getElementById("lat").value = e.latlng.lat;
                document.getElementById("lng").value = e.latlng.lng;
            }
            mymap.on("mousemove", onMapHover);
        </script>
    </body>
</html></code>```

Title: Leaflet.js centerOn function issue

Body:
I have an issue with Leaflet. I'm trying to add a function which permits to pan to given coordinates. It's working but the map automatically reverts to its initial position (after a few milliseconds). I'm afraid I can't find my mistake here.

Here is the code:

.btn {
  background: #3498db;
  background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
  background-image: -moz-linear-gradient(top, #3498db, #2980b9);
  background-image: -ms-linear-gradient(top, #3498db, #2980b9);
  background-image: -o-linear-gradient(top, #3498db, #2980b9);
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  -webkit-border-radius: 6;
  -moz-border-radius: 6;
  border-radius: 6px;
  font-family: Arial;
  color: #ffffff;
  font-size: 14px;
  padding: 5px 10px 5px 10px;
  text-decoration: none;
}

.btn:hover {
  background: #2b8ecc;
  background-image: -webkit-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -moz-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -ms-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -o-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: linear-gradient(to bottom, #2b8ecc, #4d687a);
  text-decoration: none;
}

.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropdown {
    position: relative;
    display: inline-block;
    z-index: 10;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

.dropdown:hover .dropbtn {
    background-color: #3e8e41;
}

.latlng{
    position: fixed;
    top:20px;
    right: 12px;
    color: white;
    font-Family: Arial;
    font-size: 14px;
}

.latlng input[type="submit"]{
    background-color: #4CAF50;
    color: white;
    cursor: pointer;
}

<!DOCTYPE html>

        <title>WIMP</title>
        <link rel="stylesheet" href="style.css">
        <meta name="description" content="Geo Tactical System">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>

            <button class="dropbtn">Dropdown</button>

        <form class="latlng" onsubmit="centerOn(document.getElementById('lat').value, document.getElementById('lng').value);">
            Lattitude:
            <input type="text" name="lat" id="lat" />
            Longitude:
            <input type="text" name="lng" id="lng" />
            <input type="submit" value="Centrer" />
        </form>

Body:
You need to stop postback to prevent it from resetting. Each time you click on center, your page is posted back to server which loads the page again.

You can fix this by doing following steps:

modify

onsubmit="centerOn(

to

onsubmit="return centerOn(

and change

function centerOn(lat, lng){
  //mymap.setView({lat:lat, lng:lng}, mymap.getZoom());
  mymap.panTo([lat, lng]);
  //alert("Lattitude: " + lat + " longitude: " + lng);
}

to

function centerOn(lat, lng){
  //mymap.setView({lat:lat, lng:lng}, mymap.getZoom());
  mymap.panTo([lat, lng]);
  return false;
  //alert("Lattitude: " + lat + " longitude: " + lng);
}

See working sample below

.btn {
  background: #3498db;
  background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
  background-image: -moz-linear-gradient(top, #3498db, #2980b9);
  background-image: -ms-linear-gradient(top, #3498db, #2980b9);
  background-image: -o-linear-gradient(top, #3498db, #2980b9);
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  -webkit-border-radius: 6;
  -moz-border-radius: 6;
  border-radius: 6px;
  font-family: Arial;
  color: #ffffff;
  font-size: 14px;
  padding: 5px 10px 5px 10px;
  text-decoration: none;
}

.btn:hover {
  background: #2b8ecc;
  background-image: -webkit-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -moz-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -ms-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: -o-linear-gradient(top, #2b8ecc, #4d687a);
  background-image: linear-gradient(to bottom, #2b8ecc, #4d687a);
  text-decoration: none;
}

.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropdown {
    position: relative;
    display: inline-block;
    z-index: 10;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

.dropdown:hover .dropbtn {
    background-color: #3e8e41;
}

.latlng{
    position: fixed;
    top:20px;
    right: 12px;
    color: white;
    font-Family: Arial;
    font-size: 14px;
}

.latlng input[type="submit"]{
    background-color: #4CAF50;
    color: white;
    cursor: pointer;
}

<!DOCTYPE html>
<html style="overflow-y: hidden; background: #666666;">
    <head>
        <title>WIMP</title>
        <link rel="stylesheet" href="style.css">
        <meta name="description" content="Geo Tactical System">
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
        <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
    </head>
    <div id="mapid" style="position: fixed; width: 98.5vw; height: 90vh; bottom: 12px;"></div>
    <script>
        var mymap = L.map('mapid', { zoomControl:false }).setView([48.866, 2.3333], 13);

        L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
            maxZoom: 18,
            attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
                    '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
                    'Imagery © <a href="http://mapbox.com">Mapbox</a>',
            id: 'mapbox.streets'
        }).addTo(mymap);
    </script>
    <body>
        <div class="dropdown">
            <button class="dropbtn">Dropdown</button>
            <div class="dropdown-content">
                <a href="#"></a>
                <a href="#"></a>
                <a href="#"></a>
            </div>
        </div>
        <form class="latlng" onsubmit="return centerOn(document.getElementById('lat').value, document.getElementById('lng').value);">
            Lattitude:
            <input type="text" name="lat" id="lat" />
            Longitude:
            <input type="text" name="lng" id="lng" />
            <input type="submit" value="Centrer" />
        </form>
        <script>
            function centerOn(lat, lng){
                //mymap.setView({lat:lat, lng:lng}, mymap.getZoom());
                mymap.panTo([lat, lng]);
                return false;
                //alert("Lattitude: " + lat + " longitude: " + lng);
            }

            function onMapHover(e){
                document.getElementById("lat").value = e.latlng.lat;
                document.getElementById("lng").value = e.latlng.lng;
            }
            mymap.on("mousemove", onMapHover);
        </script>
    </body>
</html>


问:
findRooms API limit of 100 rooms
The /findRooms API states:

"You can get up to the first 100 rooms in the tenant".

Is there a way to increase this limit?

I tried /findRooms?$top=1000&$count=true but I am not able to make these query parameters work with findRooms.

As stated in this ticket, I am not able to get $filter to work either.

答:
The API doesn't currently support things like $top or $skip. While I cannot make any promises, I would expect that those will get implemented before the API moves out of beta :).

You might want to log it at https://officespdev.uservoice.com/ just to make sure the engineering team hears the feedback.

Title: findRooms API limit of 100 rooms


问:
win cmd: batch string replacement deletes "!"
I have stitched, w/o any deeper cmd knowledge, a script that searches for certain string in specified files in a directory and replaces it with another. (at least should)

Goes like

```<code>  set "search=readed"
  set "replace=read"
  set "myfiles=.\*.tex"

for %%f in (%myfiles%) do (
  set /p val=<%%f
  echo "fullname: %%f"

  for /f "delims=" %%i in ('type %%f ^& break ^> %%f ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>%%f echo(!line:%search%=%replace%!)
        endlocal

  )
)
pause
</code>```

Almost works. It has two issues.
1st - the less important: deletes whitespace lines.
2nd - deletes exclamations.
before:

```<code>% !TEX root = TechRep.tex
</code>```

after:

```<code>% TEX root = TechRep.tex
</code>```

May I ask for a help? Thanks!

答:
There are two problems:

Skipped blank lines. This is caused by a restriction in the for /f command. You can use the old findstr trick to get around that.

Removed exclamation marks. This is caused by an errant closing parenthesis ) in your echo command. The opening parenthesis in echo( on the same line is ignored, and is not matched with the closing parenthesis. Instead, the closing parenthesis is matched with the start of the do loop. The next line, containing the endlocal command, is outside the loop. This seems to cause problems as there is a setlocal inside a loop and an endlocal outside; by some strange mechanism, this somehow causes the exclamation marks to be removed. Remove the ) from the echo line and this problem disappears.

Body:
I have stitched, w/o any deeper cmd knowledge, a script that searches for certain string in specified files in a directory and replaces it with another. (at least should)

Goes like

  set "search=readed"
  set "replace=read"
  set "myfiles=.\*.tex"

for %%f in (%myfiles%) do (
  set /p val=<%%f
  echo "fullname: %%f"

  for /f "delims=" %%i in ('type %%f ^& break ^> %%f ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>%%f echo(!line:%search%=%replace%!)
        endlocal

  )
)
pause

Almost works. It has two issues.
1st - the less important: deletes whitespace lines.
2nd - deletes exclamations.
before:

% !TEX root = TechRep.tex

after:

% TEX root = TechRep.tex

May I ask for a help? Thanks!


问:
WPF Binding default mode
in one of my apps I have a code like this:

```<code><ProgressBar Grid.Column="0" Grid.Row="0" HorizontalAlignment="Stretch" Height="27" Margin="5,0,5,0" Maximum="{Binding TabuProgressEnd}" Value="{Binding TabuProgress}" />
</code>```

While I was testing this everything is ok, but when my client opened this under VS and run this code threw an exception:

```<code>An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

Additional information: A TwoWay or OneWayToSource binding cannot work on the read-only property 'TabuProgress' of type 'TSPLib.TabuEngine'.
</code>```

Usually I would think this is some kind of hoax, but I know that the guy has no idea about coding and making the "Mode=OneWay" explicit helped. How is it possible that the default binding mode differs on different machines?

答:
The Value property in ProgressBar binds TwoWay by default so the exception should occur unless you explicitly set Mode to OneWay. However I can't explain why it doesn't occur on your machine. I tried using Reflector with .NET versions 4.0, 3.5 and 3.0 and as far as I can tell, the default binding mode hasn't changed in a while.

If you have Reflector installed, it would be interesting to see what the ValueProperty (inherited from RangeBase) looks like on your machine

```<code>public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register(
        "Value",
        typeof(double),
        typeof(RangeBase),
        new FrameworkPropertyMetadata(
            0.0,
            FrameworkPropertyMetadataOptions.Journal |
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            new PropertyChangedCallback(RangeBase.OnValueChanged),
            new CoerceValueCallback(RangeBase.ConstrainToRange)),
        new ValidateValueCallback(RangeBase.IsValidDoubleValue));
</code>```

Title: WPF Binding default mode

Body:
in one of my apps I have a code like this:

<ProgressBar Grid.Column="0" Grid.Row="0" HorizontalAlignment="Stretch" Height="27" Margin="5,0,5,0" Maximum="{Binding TabuProgressEnd}" Value="{Binding TabuProgress}" />

While I was testing this everything is ok, but when my client opened this under VS and run this code threw an exception:

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

Additional information: A TwoWay or OneWayToSource binding cannot work on the read-only property 'TabuProgress' of type 'TSPLib.TabuEngine'.

Usually I would think this is some kind of hoax, but I know that the guy has no idea about coding and making the "Mode=OneWay" explicit helped. How is it possible that the default binding mode differs on different machines?

Body:
The Value property in ProgressBar binds TwoWay by default so the exception should occur unless you explicitly set Mode to OneWay. However I can't explain why it doesn't occur on your machine. I tried using Reflector with .NET versions 4.0, 3.5 and 3.0 and as far as I can tell, the default binding mode hasn't changed in a while.

If you have Reflector installed, it would be interesting to see what the ValueProperty (inherited from RangeBase) looks like on your machine

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register(
        "Value",
        typeof(double),
        typeof(RangeBase),
        new FrameworkPropertyMetadata(
            0.0,
            FrameworkPropertyMetadataOptions.Journal |
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            new PropertyChangedCallback(RangeBase.OnValueChanged),
            new CoerceValueCallback(RangeBase.ConstrainToRange)),
        new ValidateValueCallback(RangeBase.IsValidDoubleValue));


问:
Should I install MariaDB to my git repo, or locally / individually to all development computers?
I am starting work on a website that will use MariaDB for storing information  (no sensitive information), and would like to keep everything in my git repo.

Originally, I planned on installing MariaDB to the separate computers that I plan to develop on (my desktop and laptop), but decided that it may be easier to store all of MariaDB (the program and the databases) in the git repo, so that one would just need to clone the repo and run MariaDB from the repo just like they would run Node, but I have not found any information on how to do this.

My questions are (1) should I install MariaDB and its databases to my git repo, instead of installing MariaDB in /usr, and the database in /var/lib/mysql, and (2) how would one do that?

答:
Instead of attempting to put a mariadb runtime environment inside your version control, consider using docker to describe how to configure an appropriate mariaDB installation.  I use makefiles atop that to contain the commands I use to build and run the docker but you coould just as easily use a shell script.  Finally, provide a dataabase load script that loads your test database from a text file within the repo.

using docker to describe runtime environments for your application and dependencies is awesome.  It strikes a great balance between having an incomplete git repo, and having to put binaries and database data in your version control.  You wouldn't want to track changes to the underlying maria db files, anyway, so best not to commit them.  You can build the docker containers you need on every workstation you use without much trouble, your automation around creating them provides a mechanism to ensure consistency, and by loading a database with the correct test data every time you develop your app, you'll have a better development process and less schema and data related changes.  It works great, I do nothing but docker driven development these days.


问:
Convert number to date in Ruby
I get a number representing date from a back-end, and I'm trying to convert it to a date this way:

```<code>number = item["created"].to_i
number #=> 1512387277084
DateTime.strptime(number.to_s ,'%s') #=> 49895-08-24T08:58:04+00:00
Time.at(number).utc #=> 49895-08-24 08:58:04 UTC
Time.at(number) #=> 49895-08-24 11:58:04 +0300
</code>```

But this is a wrong result.

If I use Epoch & Unix Timestamp Conversion Tools, I get this result:

```<code>1512387277084
Assuming that this timestamp is in milliseconds:
GMT: Monday, December 4, 2017 11:34:37.084 AM
Your time zone: Monday, December 4, 2017 2:34:37.084 PM GMT+03:00
</code>```

Time.at(number) doesn't work.

How to convert it correctly?

Title: Convert number to date in Ruby

Body:
I get a number representing date from a back-end, and I'm trying to convert it to a date this way:

number = item["created"].to_i
number #=> 1512387277084
DateTime.strptime(number.to_s ,'%s') #=> 49895-08-24T08:58:04+00:00
Time.at(number).utc #=> 49895-08-24 08:58:04 UTC
Time.at(number) #=> 49895-08-24 11:58:04 +0300

But this is a wrong result.

If I use Epoch & Unix Timestamp Conversion Tools, I get this result:

1512387277084
Assuming that this timestamp is in milliseconds:
GMT: Monday, December 4, 2017 11:34:37.084 AM
Your time zone: Monday, December 4, 2017 2:34:37.084 PM GMT+03:00

Time.at(number) doesn't work.

How to convert it correctly?

Body:
DateTime.strptime('1512387277084', '%Q')
#⇒ #<DateTime: 2017-12-04T11:34:37+00:00
#       ((2458092j,41677s,84000000n),+0s,2299161j)>

DateTime formatting.


问:
Matlab: Add folder and subfolders persistent to path
I have a Matlab directory in my Code folder like this:
~/Code/Matlab/

I want the whole content of this folder (and its subfolders) added permanently to the Matlab-path. So that, when I add a new file/ folder into this folder or its subfolders it gets added automatically to the path.

I know how to add a folder permanent to the path but when I add subfolders/ files to it, they are getting not added.

Is this possible and if yes how?

答:
You can use the following commands:

```<code>addpath(genpath('~/Code/Matlab/'));
savepath
</code>```

This will add your folder, and all its subfolders, to the path. However, if you subsequently add a new subfolder, it will not automatically be added to the path, and you'll need to run the commands again.

I'm afraid there is no "add this folder, its subfolder, and all future subfolders" command.

If this starts to feel repetitive, you could consider creating a shortcut with those commands, and adding it to the MATLAB toolstrip.

ContentLicense: CC BY-SA 4.0

Body:
You can use the following commands:

addpath(genpath('~/Code/Matlab/'));
savepath

This will add your folder, and all its subfolders, to the path. However, if you subsequently add a new subfolder, it will not automatically be added to the path, and you'll need to run the commands again.

I'm afraid there is no "add this folder, its subfolder, and all future subfolders" command.

If this starts to feel repetitive, you could consider creating a shortcut with those commands, and adding it to the MATLAB toolstrip.