问:
Triangle in layout - Android UI
I need to add/design the next triangle in an Android layout.

Above the triangle the layout background is gray, and below is white.

Basically is a gray triangle with a dark border and a red border, but i dont know which is the best way to archieve this.

I dont want to add static images to the layout, and i dont know how to do this with shapes,xml,drawables.

答:
You'll have to do some tweaking for your particular layout but here's an example.  (The heights & widths come from something else I was working on.  That's one of the things you'll have determine for your layout).

triangle_background.xml

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="96dp"
    android:width="64dp"

    android:viewportWidth="400"
    android:viewportHeight="600">

    <!-- upper white area -->
    <path android:pathData="M 0 112 l 200,50 200,-50 V 0 H 0 z"
        android:fillColor="#ffffff" android:strokeColor="#ffffff" android:strokeWidth="2" />

    <!-- black line -->
    <path android:pathData="M 0 117 l 200,50 200,-50"
        android:strokeColor="#000000" android:strokeWidth="5" />

    <!-- red line -->
    <path android:pathData="M 0 130 l 200,50 200,-50"
        android:strokeColor="#ff0000" android:strokeWidth="20" />

    <!-- lower grey area -->
    <path android:pathData="M 0 135 l 200,50 200,-50 V 600 H 0 z"
        android:fillColor="#aaaaaa" android:strokeColor="#aaaaaa" android:strokeWidth="2" />
</vector>
</code>```

And here is the layout file.

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/triangle_background"
    >

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="24dp"
        android:src="@drawable/logo"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="48dp"
        android:text="button"
        />
</RelativeLayout>
</code>```

And here is the result

Title: Triangle in layout - Android UI

Body:
You'll have to do some tweaking for your particular layout but here's an example.  (The heights & widths come from something else I was working on.  That's one of the things you'll have determine for your layout).

triangle_background.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="96dp"
    android:width="64dp"

    android:viewportWidth="400"
    android:viewportHeight="600">

    <!-- upper white area -->
    <path android:pathData="M 0 112 l 200,50 200,-50 V 0 H 0 z"
        android:fillColor="#ffffff" android:strokeColor="#ffffff" android:strokeWidth="2" />

    <!-- black line -->
    <path android:pathData="M 0 117 l 200,50 200,-50"
        android:strokeColor="#000000" android:strokeWidth="5" />

    <!-- red line -->
    <path android:pathData="M 0 130 l 200,50 200,-50"
        android:strokeColor="#ff0000" android:strokeWidth="20" />

    <!-- lower grey area -->
    <path android:pathData="M 0 135 l 200,50 200,-50 V 600 H 0 z"
        android:fillColor="#aaaaaa" android:strokeColor="#aaaaaa" android:strokeWidth="2" />
</vector>

And here is the layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/triangle_background"
    >

    <ImageView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="24dp"
        android:src="@drawable/logo"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="48dp"
        android:text="button"
        />
</RelativeLayout>

And here is the result


来源: stackexchange

问:
Transpose dynamic values using Excel VBA in a loop
I am new to excel VBA, and I need help to figure out how to transpose values from one sheet to another sheet.

Below are the images on how my data is before and how I need the data transposed:

BEFORE TRANSPOSE

COUNT OF CHARACTERISTICS    |CLASS    |CHAR 1    |CHAR 2      |CHAR 3    |CHAR 4    |CHAR 5    |CHAR 6    |

3    |ABSORBER    |TYPE    |SIZE    |MATERIAL

5    |ADAPTOR    |TYPE    |SIZE_A    |CONNECTION_A    |SIZE_B    |CONNECTION_B
   |MATERIAL

AFTER TRANSPOSE

|CLASS |CHAR|

ABSORBER   |TYPE

ABSORBER   |SIZE

ABSORBER   |MATERIAL

ADAPTOR    |TYPE

ADAPTOR    |SIZE_A

ADAPTOR    |CONNECTION_A

ADAPTOR    |SIZE_B

ADAPTOR    |CONNECTION_B

ADAPTOR    |MATERIAL

I have more than 1000 rows of data that needs to be transposed.

Sorry, this is the best I could do with regards to the table.

答:
I think this function will work based on the sample data in your question. This assumes a few things ("Count" is the first column in the raw data, no blank "Char" fields, ect.), so I can help adjust it more specifically to your exact scenario if needed. We could also probably eliminate a few lines if everything is in one workbook and you don't need/want to set workbook and worksheet objects as variables.

```<code>Public Sub Transpose()

Dim Row1 As Long
Dim Column1 As Long
Dim Row2 As Long
Dim CurrentWB As Workbook
Dim CurrentWS As Worksheet
Dim TransposeWB As Workbook
Dim TransposeWS As Worksheet
Dim CurrentClass As String

'Set workbook(s) and worksheets as variables just to make it easier to reference them
'Replace necessary workbooks and worksheets with what holds your actual data
Set CurrentWB = ActiveWorkbook
Set CurrentWS = CurrentWB.Worksheets("Sheet1")
Set TransposeWB = ActiveWorkbook
Set TransposeWS = CurrentWB.Worksheets("Sheet2")

'Set the starting row for the worksheet in which the transposed data will go
Row2 = 1

'Adjust as needed for the row in which your raw data starts and ends
For Row1 = 1 To 1000

    'Store the current class
    CurrentClass = CurrentWS.Cells(Row1, 2)

    'Assuming first "Char" column is 3
    Column1 = 3

    While CurrentWS.Cells(Row1, Column1) <> ""

        TransposeWS.Cells(Row2, 1) = CurrentClass
        TransposeWS.Cells(Row2, 2) = CurrentWS.Cells(Row1, Column1)

        'Move to the next "Char" column in untransposed sheet
        Column1 = Column1 + 1

        'Move to the next row in transposed sheet
        Row2 = Row2 + 1
    Wend

Next Row1
</code>```

End Sub

ContentLicense: CC BY-SA 3.0

Body:
I think this function will work based on the sample data in your question. This assumes a few things ("Count" is the first column in the raw data, no blank "Char" fields, ect.), so I can help adjust it more specifically to your exact scenario if needed. We could also probably eliminate a few lines if everything is in one workbook and you don't need/want to set workbook and worksheet objects as variables.

Public Sub Transpose()

Dim Row1 As Long
Dim Column1 As Long
Dim Row2 As Long
Dim CurrentWB As Workbook
Dim CurrentWS As Worksheet
Dim TransposeWB As Workbook
Dim TransposeWS As Worksheet
Dim CurrentClass As String

'Set workbook(s) and worksheets as variables just to make it easier to reference them
'Replace necessary workbooks and worksheets with what holds your actual data
Set CurrentWB = ActiveWorkbook
Set CurrentWS = CurrentWB.Worksheets("Sheet1")
Set TransposeWB = ActiveWorkbook
Set TransposeWS = CurrentWB.Worksheets("Sheet2")

'Set the starting row for the worksheet in which the transposed data will go
Row2 = 1

'Adjust as needed for the row in which your raw data starts and ends
For Row1 = 1 To 1000

    'Store the current class
    CurrentClass = CurrentWS.Cells(Row1, 2)

    'Assuming first "Char" column is 3
    Column1 = 3

    While CurrentWS.Cells(Row1, Column1) <> ""

        TransposeWS.Cells(Row2, 1) = CurrentClass
        TransposeWS.Cells(Row2, 2) = CurrentWS.Cells(Row1, Column1)

        'Move to the next "Char" column in untransposed sheet
        Column1 = Column1 + 1

        'Move to the next row in transposed sheet
        Row2 = Row2 + 1
    Wend

Next Row1

End Sub


问:
How to get the height of an element and use it in a function?
I'm trying to use jquery to determine the height of an element and then determine if a user has scrolled that distance. The application is that I have a header followed by a navbar. As the user scrolls down the page the header will disappear and the navbar will stay fixed to the top of the screen. I have this working using the following code:

```<code>    <script type="text/javascript">
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > 100 ) {
    jQuery("#top-header").hide(300);
} else {
    jQuery("#top-header").show(300);
}
</code>```

});

But I want to use media queries to change the height of #top-header based on screen size instead of leaving it the same. So what I'd like to do is determine the height of #top-header (or some element within it) and then use that value in the function to hide it. I know I can use some form of $('#top-header).height but I'm not sure how to incorporate it into the function.

Thanks,
CJ

答:
Based on the answers provided above I was able to tweak my original code to get it to work as intended. Here's what I did:

```<code><script type="text/javascript">

jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > (jQuery("#top-header").height())) {
    jQuery("#top-header").hide(300);
} else {
    jQuery("#top-header").show(300);
}
});
</script>
</code>```

Bear in mind this is within a joomla page that has jquery loaded by default.

Body:
Based on the answers provided above I was able to tweak my original code to get it to work as intended. Here's what I did:

<script type="text/javascript">

jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > (jQuery("#top-header").height())) {
    jQuery("#top-header").hide(300);
} else {
    jQuery("#top-header").show(300);
}
});
</script>

Bear in mind this is within a joomla page that has jquery loaded by default.


问:
How to check if Python app is running within AWS lambda function?
I've got a Python application that connects to a database and I would like the db credentials to be different when it's running in local env (for testing) or within a lambda function (for production).

Is there any way, from the Python app, to detect that it is running inside the lambda function?

答:
For unit testing I use the structure:

```<code>+ my_function/
+- __init__.py - empty files
+- code/
   +- __init__.py
   +- lambda_function.py
+- unittest/
   +- __init__.py
   +- tests.py - from ..code.lambda_function import *
</code>```

When running unit tests with python -m my_function.unittest.tests, in lambda_function.py the __name__ == 'my_function.code.lambda_function'.

When running in the Lambda running, __name__ == 'lambda_function'. Note that you'll get the same value if you run with python -m my_function.code.lambda_function so you'll always need a wrapper.

Body:
For unit testing I use the structure:

+ my_function/
+- __init__.py - empty files
+- code/
   +- __init__.py
   +- lambda_function.py
+- unittest/
   +- __init__.py
   +- tests.py - from ..code.lambda_function import *

When running unit tests with python -m my_function.unittest.tests, in lambda_function.py the __name__ == 'my_function.code.lambda_function'.

When running in the Lambda running, __name__ == 'lambda_function'. Note that you'll get the same value if you run with python -m my_function.code.lambda_function so you'll always need a wrapper.


问:
Sourcemap not mapping the correct line
I am using angular2-webpack-starter. I use VSCode and debbuger for chrome.
After hours trying to make debbuger working, I finally managed to have a breakpoint working, but it seems that it is not mapping the correct line.
It is the same problem in Chrome Devtool as my breakpoint is in a TS file et mapping work with js files.

Any ideas to make it work ?

答:
Basically, using source-map instead of cheap-module-source-map fixed my issue. (in webpack config)

https://github.com/angular/angular-cli/issues/2811

Title: Sourcemap not mapping the correct line


问:
Add elements to sub-array recursively
I'm trying to add elements to a sub array of the sub array where they were added in the previous iteration, i.e. transforming this:

```<code>$a = array('a', 'b', 'c');
</code>```

Into this:

```<code>$new_array = array(
    'a' => array(
        'b' => array(
            'c' => array()
        )
    )
);
</code>```

答:
```<code>function makeArrayChain($chain)
{
    $key = array_shift($chain);

    if ($key === NULL) {
        return array();
    } else {
        return array($key => makeArrayChain($chain));
    }
}

var_dump(makeArrayChain(array('a', 'b', 'c'));

array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    array(1) {
      ["c"]=>
      array(0) {
      }
    }
  }
}
</code>```

Title: Add elements to sub-array recursively

Body:
I'm trying to add elements to a sub array of the sub array where they were added in the previous iteration, i.e. transforming this:

$a = array('a', 'b', 'c');

Into this:

$new_array = array(
    'a' => array(
        'b' => array(
            'c' => array()
        )
    )
);

ContentLicense: CC BY-SA 2.5


问:
How to subtract days from a plain Date?
Is there an easy way of taking a olain JavaScript Date (e.g. today) and going back X days?

So, for example, if I want to calculate the date 5 days before today.

答:
I like the following because it is one line.  Not perfect with DST changes but usually good enough for my needs.</p>

```<code>var fiveDaysAgo = new Date(new Date() - (1000*60*60*24*5));
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to subtract days from a plain Date?

Body:
I like the following because it is one line.  Not perfect with DST changes but usually good enough for my needs.

var fiveDaysAgo = new Date(new Date() - (1000*60*60*24*5));


问:
NSManagedObjects created on background turning into faults on main thread
I'm dealing with a strange case. I'm getting some data from a API, transform the response JSON into NSManagedObjects and saving them, all that in a background thread and using a NSPrivateQueueConcurrencyType context whose parent is a NSMainQueueConcurrencyType.

At the same time I'm creating the NSManagedObjects, I'm placing them inside an array to use it in my view controller via a completion block executed on the main therad. Here's a simplified version of what I'm doing.

```<code>- (void)getObjectFromAPIWithCompletion:((^)(NSArray *objects, NSError *error))completion
{
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

    NSManagedObjectContext *backgroundMoc = [[CoreDataStack sharedManager] newChildContextWithConcurrencyType:NSPrivateQueueConcurrencyType];

    NSArray *items = [self processToParseResponseFromAPIAndSaveInCoreDataUsingContext:backgroundContext];
    [backgroundMoc save:nil];

    dispatch_async(dispatch_get_main_queue(), ^{
      //Beyond this point, all properties of items are nil or 0 (if integer)
      if(completion) completion(items, error);
    });

  });
}
</code>```

The weird thing happens inside the completion block. I put a breakpoint on the first line of that block and print the items array on the console. Everything looks fine, with all the items (50 in this case) and their properties are OK.

The problem is when that after that line (where I'm not changing anything on the items array) all objects turn into faults and I'm not getting any data on the properties.

Don't know what is the cause of this rare behaviour. Any idea?

Thanks.

EDIT: Hal's answer put me on the right track so here's what I did to fix this problem. Just before calling the block that will be executed on the main thread I "move" the managed objects from the background context to the main context, fetching with their objectIDs. Like  this:

```<code>NSArray *objects = //Objects created on background thread with Private queue

NSMutableArray *objectsIDs = [NSMutableArray array];
for (Object *object in object) {
  [objectsIDs addObject:object.objectID];
}

//Save on private managed object context and on completion...
[self.managedObjectContext saveWithCompletion:^(NSError *error) {

  NSManagedObjectContext *mainMOC = [[CoreDataManager sharedManager] mainContext];
  NSMutableArray *fetchedObjects = [NSMutableArray array];
  for (NSManagedObjectID *objectID in objectsIDs) {
    [fetchedArticles addObject:[mainMOC objectWithID:objectID]];
  }

  if (completion) completion(fetchedObjects, pagination, nil);
}];
</code>```

This way, all objects are not faults on the main thread.

答:
If those objects (the contents of items) have been created on the background thread, you can't use them in the main thread. You can't pass NSManagedObject instances between threads.

You'll have to pass NSManagedObjectIDs (which won't be permanent until you've saved the background MOC), or use an NSFetchedResultsController (pointing to the main MOC) on the main thread. This is one of the cases that NSFetchedResultsController was designed for, so I recommend you go that route.

Body:
I'm dealing with a strange case. I'm getting some data from a API, transform the response JSON into NSManagedObjects and saving them, all that in a background thread and using a NSPrivateQueueConcurrencyType context whose parent is a NSMainQueueConcurrencyType.

At the same time I'm creating the NSManagedObjects, I'm placing them inside an array to use it in my view controller via a completion block executed on the main therad. Here's a simplified version of what I'm doing.

- (void)getObjectFromAPIWithCompletion:((^)(NSArray *objects, NSError *error))completion
{
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

    NSManagedObjectContext *backgroundMoc = [[CoreDataStack sharedManager] newChildContextWithConcurrencyType:NSPrivateQueueConcurrencyType];

    NSArray *items = [self processToParseResponseFromAPIAndSaveInCoreDataUsingContext:backgroundContext];
    [backgroundMoc save:nil];

    dispatch_async(dispatch_get_main_queue(), ^{
      //Beyond this point, all properties of items are nil or 0 (if integer)
      if(completion) completion(items, error);
    });

  });
}

The weird thing happens inside the completion block. I put a breakpoint on the first line of that block and print the items array on the console. Everything looks fine, with all the items (50 in this case) and their properties are OK.

The problem is when that after that line (where I'm not changing anything on the items array) all objects turn into faults and I'm not getting any data on the properties.

Don't know what is the cause of this rare behaviour. Any idea?

Thanks.

EDIT: Hal's answer put me on the right track so here's what I did to fix this problem. Just before calling the block that will be executed on the main thread I "move" the managed objects from the background context to the main context, fetching with their objectIDs. Like  this:

NSArray *objects = //Objects created on background thread with Private queue

NSMutableArray *objectsIDs = [NSMutableArray array];
for (Object *object in object) {
  [objectsIDs addObject:object.objectID];
}

//Save on private managed object context and on completion...
[self.managedObjectContext saveWithCompletion:^(NSError *error) {

  NSManagedObjectContext *mainMOC = [[CoreDataManager sharedManager] mainContext];
  NSMutableArray *fetchedObjects = [NSMutableArray array];
  for (NSManagedObjectID *objectID in objectsIDs) {
    [fetchedArticles addObject:[mainMOC objectWithID:objectID]];
  }

  if (completion) completion(fetchedObjects, pagination, nil);
}];

This way, all objects are not faults on the main thread.


问:
Errors caused by write statements when running f2py-wrapped, PETSc-based fortran code in OpenMDAO
I am using f2py to wrap my PETSc-based fortran analysis code for use in OpenMDAO (as suggested in this post). Rather than use f2py directly, I'm instead using it to generate the relevant .c, .pyc, etc. files and then linking them myself using mpif90.

In a simple python environment, I can import my .so and run the code without any problems:

```<code>>>> import module_name
>>> module_name.execute()

expected code output...
</code>```

However, when trying to do the same thing in an OpenMDAO component, I get the following error:

```<code>At line 72 of file driver.F90
Internal Error: list_formatted_write(): Bad type
</code>```

This happens even when running in serial and the error appears to the first place in the fortran code where I use write(*,*). What could be different about running under OpenMDAO that might cause this issue? Might it have something to do with the need to pass a comm object, as mentioned in the answer to my original question? I am not doing that at the moment as it was not clear to me from the the relevant OpenMDAO example how that should be done in my case.

When I try to find specific information about the error I'm getting, search results almost always point to the mpif90 or gfortran libraries and possibly needing to recompile or update the libraries. However, that doesn't explain to me why my analysis would work perfectly well in a simple python code but not in OpenMDAO.

UPDATE: Per some others' suggestions, I've tried a few more things. Firstly, I get the error regardless of if I'm running using mpiexec python

答:
I've never quite seen anything like this before and we've used network-X with compiled fortran wrapped in F2py, running under MPI many many times.

I suggest that you remove and re-install your network-x package.

Which python are you using and what os are you running on? We've had very good luck running the anaconda python installation. You have to be a bit careful when installing petsc though. Building from source and running the PETSc tests is the safest way.

Body:
I am using f2py to wrap my PETSc-based fortran analysis code for use in OpenMDAO (as suggested in this post). Rather than use f2py directly, I'm instead using it to generate the relevant .c, .pyc, etc. files and then linking them myself using mpif90.

In a simple python environment, I can import my .so and run the code without any problems:

>>> import module_name
>>> module_name.execute()

expected code output...

However, when trying to do the same thing in an OpenMDAO component, I get the following error:

At line 72 of file driver.F90
Internal Error: list_formatted_write(): Bad type

This happens even when running in serial and the error appears to the first place in the fortran code where I use write(*,*). What could be different about running under OpenMDAO that might cause this issue? Might it have something to do with the need to pass a comm object, as mentioned in the answer to my original question? I am not doing that at the moment as it was not clear to me from the the relevant OpenMDAO example how that should be done in my case.

When I try to find specific information about the error I'm getting, search results almost always point to the mpif90 or gfortran libraries and possibly needing to recompile or update the libraries. However, that doesn't explain to me why my analysis would work perfectly well in a simple python code but not in OpenMDAO.

UPDATE: Per some others' suggestions, I've tried a few more things. Firstly, I get the error regardless of if I'm running using mpiexec python


问:
Nginx/php-fpm umask setting
When I was using apache2 server, setting default umask in /etc/apache2/envvars to 0002 used to solve all my permissions problems. Now that I am trying to setup nginx/php-fpm, I have come across the same problems when files are created with improper permissions.

Is there umask setting in nginx or php-fpm?

答:
Taken from the other answer's linked question:

if you use systemd [i.e. Ubuntu 16.04], then edit /lib/systemd/system/php5-fpm.service

And edit chapter "Service":

```<code>[Service]
UMask=0002
</code>```

Title: Nginx/php-fpm umask setting

Body:
Taken from the other answer's linked question:

if you use systemd [i.e. Ubuntu 16.04], then edit /lib/systemd/system/php5-fpm.service

And edit chapter "Service":

[Service]
UMask=0002


问:
Using GRID and PACK in the same GUI
I've been looking around slack and lots of people saying it is possible but no examples of how to do it.

I'm looking to use both pack and grid within the same GUI. I have setup 2 different frames 1 using pack the other grid but I still get an error when trying to run the GUI.

I was under the impression you could use the different commands as long as there were in different frames?

here is my code

```<code>from tkinter import*

root = Tk()
root.title("UKIND Industry Tool")
root.geometry("600x600")
root.resizable(width=False, height=False)

# ----- Top Frame -----
topFrame = Frame(root, bg="grey", width=600, height=25, pady=1)
topFrame.pack(side=TOP, fill=X)

# ----- Top Frame Label -----

oreCalc = Button(topFrame, text= "Ore Calculator")
minCalc = Button(topFrame, text= "Mineral Calculator")
oreCalc.pack(side=LEFT)
#minCalc.pack(side=LEFT)

# ----- Bottom Frame -----

bottomFrame = Frame(root, bg="green", width=600, height=585, pady=1)
bottomFrame.grid()

root.mainloop()
</code>```

And here is the trace back error:

Traceback (most recent call last):
    File "C:/Users/Ganjena/Desktop/Course/Projects/helloworld/test.py", line 22, in
      bottomFrame.grid()
    File "C:\Users\Ganjena\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py", line 2220, in grid_configure
      + self._options(cnf, kw))
  _tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack

Process finished with exit code 1

答:
Both topFrame and bottomFrame are children of your root window, but you called .pack() on one, and .grid() on the other.  In other words, THE ERROR MESSAGE MEANS EXACTLY WHAT IT SAYS!

What you can actually do is use .grid() on children of bottomFrame; that doesn't conflict with the use of .pack() on the children of topFrame, or on bottomFrame itself.  But any two widgets that share a parent must share a geometry manager.

Title: Using GRID and PACK in the same GUI

Body:
I've been looking around slack and lots of people saying it is possible but no examples of how to do it.

I'm looking to use both pack and grid within the same GUI. I have setup 2 different frames 1 using pack the other grid but I still get an error when trying to run the GUI.

I was under the impression you could use the different commands as long as there were in different frames?

here is my code

from tkinter import*

root = Tk()
root.title("UKIND Industry Tool")
root.geometry("600x600")
root.resizable(width=False, height=False)

# ----- Top Frame -----
topFrame = Frame(root, bg="grey", width=600, height=25, pady=1)
topFrame.pack(side=TOP, fill=X)

# ----- Top Frame Label -----

oreCalc = Button(topFrame, text= "Ore Calculator")
minCalc = Button(topFrame, text= "Mineral Calculator")
oreCalc.pack(side=LEFT)
#minCalc.pack(side=LEFT)

# ----- Bottom Frame -----

bottomFrame = Frame(root, bg="green", width=600, height=585, pady=1)
bottomFrame.grid()

root.mainloop()

And here is the trace back error:

Traceback (most recent call last):
    File "C:/Users/Ganjena/Desktop/Course/Projects/helloworld/test.py", line 22, in
      bottomFrame.grid()
    File "C:\Users\Ganjena\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py", line 2220, in grid_configure
      + self._options(cnf, kw))
  _tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack

Process finished with exit code 1


问:
jQuery input mask for phone number
I want a user's input to autofill the punctuation of a phone number in order to look like this (xxx) xxx-xxxx. This is my HTML code:

```<code>  <div class="form-group">
    <label class="control-label col-sm-2">Phone Number:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" name="phoneNumber"
           id="phoneNumber" value="<?php echo $row["phoneNumber"];?>">
    </div>
  </div>
</code>```

What else do I need to do to complete this task? I am trying to use jQuery and an input mask.

答:
You can accomplish this by using the Input Mask jQuery extension.

$('#phoneNumber').inputmask("(999) 999-9999");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>

<label class="control-label col-sm-2">Phone Number:</label>
  <div class="col-sm-10">
  <input type="text" class="form-control" name="phoneNumber" id="phoneNumber" value="">
</div></code>```

Title: jQuery input mask for phone number

Body:
I want a user's input to autofill the punctuation of a phone number in order to look like this (xxx) xxx-xxxx. This is my HTML code:

    Phone Number:

      <input type="text" class="form-control" name="phoneNumber"
           id="phoneNumber" value="<?php echo $row["phoneNumber"];?>">

What else do I need to do to complete this task? I am trying to use jQuery and an input mask.

Body:
You can accomplish this by using the Input Mask jQuery extension.

$('#phoneNumber').inputmask("(999) 999-9999");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>

<label class="control-label col-sm-2">Phone Number:</label>
  <div class="col-sm-10">
  <input type="text" class="form-control" name="phoneNumber" id="phoneNumber" value="">
</div>


问:
How to add more metadata to user context on Bugsnag?
Apparently the Bugsnag setUser method only accepts three params: id, name and e-mail. How to attach my custom metadata to the user, like the Sentry setUserContext method?

I believe it's somehow possible because I see this image on Custom Filters page and it has a custom subscription_level field:

答:
Bugsnag Employee here.  You can do this! Here are the docs for react native and javascript

https://docs.bugsnag.com/platforms/react-native/#attaching-custom-diagnostics

https://docs.bugsnag.com/platforms/browsers/#custom-diagnostics


问:
Grafana webhooks - failed to send
I'm trying to set up Grafana to send webhooks to Microsoft Teams. I'm able to curl via terminal to the address but it's not possible via Grafanas interface.

I add the URL to Grafanas "webhook" and when I click "Test" it only shows me an error. Anyone know the solution?

I have not entered username/password since i don't know what to supply.

答:
I tried this also.
With a variety of settings (post, put, slack, webhook)
Long story short, Grafana doesn't support the team webhook format.

I Can curl the webhook and get the hello world example to work (without credentials so it isn't the username and password).

Error grafana gives is:

```<code> Webhook response status 400 Bad Request
</code>```

Getting started with connectors

Action reference

Title: Grafana webhooks - failed to send

Body:
I tried this also.
With a variety of settings (post, put, slack, webhook)
Long story short, Grafana doesn't support the team webhook format.

I Can curl the webhook and get the hello world example to work (without credentials so it isn't the username and password).

Error grafana gives is:

 Webhook response status 400 Bad Request

Getting started with connectors

Action reference


问:
Run two websites with one laravel installation
How we can use multiple applications with one Laravel installation.

For example:
www.apple.com
www.orange.com

both website will use ONE CORE laravel installation with separate database and all other separate stuff.

Is that possible?
If yes then how?

Also I have done the same thing for CodeIgniter but not sure how i can do with
laravel.

答:
You can use route group for this, it's something like this:

```<code>Route::group(['domain' => 'myapp.com'], function () {
    Route::get('user/{id}', 'Controller@Method');
});
</code>```

Official documentation: Sub-domain routing

Body:
You can use route group for this, it's something like this:

Route::group(['domain' => 'myapp.com'], function () {
    Route::get('user/{id}', 'Controller@Method');
});

Official documentation: Sub-domain routing


问:
Return non- string number from the output of hex to binary conversion?
How can i get return value after converting hex value to binary string?

I'm always getting string binary which is not useful for bit operation.

i.e
bin(int(str('0x460001'), 16)) is always 0b10001100000000000000001, instead I want 0b10001100000000000000001 as my output.

For that binary value I want to perform an operation which requires non string value, like:

```<code>0b10001100000000000000001 | 0b10001100100000000000001
</code>```

Please let me know if there is any option or library I can use for it.

答:
Probably to your surprise the problem you see isn't a problem at all because:

```<code>print( type(0b10001100100011000000001) )

# gives: <class 'int'> (or int in Python 2)
</code>```

0b10001100100011000000001 IS a NUMBER, not a string ...
so you can do binary operations directly with it.

Just try this:

```<code>print( 0x460001 == 0b10001100000000000000001 ) # gives True
print( 0x460001 == 4587521 )                   # gives also True
print( 4587521  == 0b10001100000000000000001 ) # gives True
</code>```

or this:

```<code>print( type(0x460001), type(0b10001100000000000000001), type(4587521) )
# gives <class 'int'> <class 'int'> <class 'int'>
</code>```

It doesn't matter HOW you write a number it will be the same number, but

```<code>print( "0x460001" == 0b10001100000000000000001 ) # gives False
</code>```

will give you False as "0x460001" is a string not a number.

Anyway, until you understand the above, you can play around with following code snippets:

```<code>def bitwiseORforBinaryNumbers(bin1, bin2):
  return bin( bin1 | bin2 )

print( bitwiseORforBinaryNumbers(
   0b10001100000011000000001,
   0b10001100100000000000001) )
#  0b10001100100011000000001
</code>```

or just written directly:

```<code>print(
  bin( 0b10001100000011000000001 |
       0b10001100100000000000001 ) )
#      0b10001100100011000000001
</code>```

The same for strings with binary representations of a number look like:

```<code>def bitwiseORforStringsWithBinaryValue(binStr1, binStr2):
  return bin(int(binStr1,2) | int(binStr2,2))

print( bitwiseORforStringsWithBinaryValue("0b10001100000011000000001", "0b10001100100000000000001") )
# gives:
0b10001100100011000000001
</code>```

or just done directly in code:

```<code>print( bin( int("0b10001100000011000000001",2) | int("0b10001100100000000000001",2) ) )
</code>```

Body:
How can i get return value after converting hex value to binary string?

I'm always getting string binary which is not useful for bit operation.

i.e
bin(int(str('0x460001'), 16)) is always 0b10001100000000000000001, instead I want 0b10001100000000000000001 as my output.

For that binary value I want to perform an operation which requires non string value, like:

0b10001100000000000000001 | 0b10001100100000000000001

Please let me know if there is any option or library I can use for it.

Body:
Probably to your surprise the problem you see isn't a problem at all because:

print( type(0b10001100100011000000001) )

# gives: <class 'int'> (or int in Python 2)

0b10001100100011000000001 IS a NUMBER, not a string ...
so you can do binary operations directly with it.

Just try this:

print( 0x460001 == 0b10001100000000000000001 ) # gives True
print( 0x460001 == 4587521 )                   # gives also True
print( 4587521  == 0b10001100000000000000001 ) # gives True

or this:

print( type(0x460001), type(0b10001100000000000000001), type(4587521) )
# gives <class 'int'> <class 'int'> <class 'int'>

It doesn't matter HOW you write a number it will be the same number, but

print( "0x460001" == 0b10001100000000000000001 ) # gives False

will give you False as "0x460001" is a string not a number.

Anyway, until you understand the above, you can play around with following code snippets:

def bitwiseORforBinaryNumbers(bin1, bin2):
  return bin( bin1 | bin2 )

print( bitwiseORforBinaryNumbers(
   0b10001100000011000000001,
   0b10001100100000000000001) )
#  0b10001100100011000000001

or just written directly:

print(
  bin( 0b10001100000011000000001 |
       0b10001100100000000000001 ) )
#      0b10001100100011000000001

The same for strings with binary representations of a number look like:

def bitwiseORforStringsWithBinaryValue(binStr1, binStr2):
  return bin(int(binStr1,2) | int(binStr2,2))

print( bitwiseORforStringsWithBinaryValue("0b10001100000011000000001", "0b10001100100000000000001") )
# gives:
0b10001100100011000000001

or just done directly in code:

print( bin( int("0b10001100000011000000001",2) | int("0b10001100100000000000001",2) ) )


问:
How to save Date Time without the time?
How would i save the date time, with no time or preferably with a time stamp of 12:00, no matter what the time is at that moment?

I dont want to use .ToString("dd/MM/yyyy");, because it will open up a whole lot of new  possible errors.

答:
Take a look at this http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx

If you want the current date, there is a slightly more readable:

```<code>DateTime.Today
</code>```

but for a specific DateTime instance, then:

```<code>myDateTime.Date
</code>```

Title: How to save Date Time without the time?

Body:
Take a look at this http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx

If you want the current date, there is a slightly more readable:

DateTime.Today

but for a specific DateTime instance, then:

myDateTime.Date


问:
Declaring array in Header file
I am trying to optimize a life game.
I need to change this code from the header file:

```<code>  #define MASK(col) (0x80 >> ((col) & 7))
</code>```

(The variable "col" is a variable that will save the column, it goes from 0 to 8)

To something like this:

```<code>int array[9] = { 0, 64, 32, 16, 8, 4, 2, 1};
  #define MASK(col) (array[col])

(((0) & 7) = 0, ((1) & 7) = 64, ((2) & 7) = 32, ((3) & 16)...)
</code>```

The error I am getting with this code is the following:

```<code>"#10010 errors encountered during linking "life.out" not built"
"#10056 "array" redefined: first defined in './lifelib.obj', redefined in
'./life.obj'"
</code>```

(Ps.: I've changed the name of the array to something like: "OKDPSAdiahodakDSA" and I still got the same error)

PS: This error only happens when I make this change. The entire code is working fine.

答:
Thank you so much. My code basically doubled the speed. Everyone here helped A TON. I wish I could give the "best answer" check mark to everyone.

I did was the following:
I changed this part of my 'life.h' file:

```<code>#define MASK(col) (0x80 >> ((col) % 8))
</code>```

To this one:

```<code>  #define MASK(col) (0x80 >> ((col) & 7))
</code>```

So I deleted/erase/commented it out the '#define MASK' and did the following:

On my 'life.c' file I created the following array:

```<code>int __life_mask_array[] = { 128, 64, 32, 16, 8, 4, 2, 1 };
</code>```

And on my 'life.h' file had the following:

```<code>extern int __life_mask_array[]
#define MASK(col) (array[(col)&7])
</code>```

Title: Declaring array in Header file

Body:
I am trying to optimize a life game.
I need to change this code from the header file:

  #define MASK(col) (0x80 >> ((col) & 7))

(The variable "col" is a variable that will save the column, it goes from 0 to 8)

To something like this:

int array[9] = { 0, 64, 32, 16, 8, 4, 2, 1};
  #define MASK(col) (array[col])

(((0) & 7) = 0, ((1) & 7) = 64, ((2) & 7) = 32, ((3) & 16)...)

The error I am getting with this code is the following:

"#10010 errors encountered during linking "life.out" not built"
"#10056 "array" redefined: first defined in './lifelib.obj', redefined in
'./life.obj'"

(Ps.: I've changed the name of the array to something like: "OKDPSAdiahodakDSA" and I still got the same error)

PS: This error only happens when I make this change. The entire code is working fine.

Body:
Thank you so much. My code basically doubled the speed. Everyone here helped A TON. I wish I could give the "best answer" check mark to everyone.

I did was the following:
I changed this part of my 'life.h' file:

#define MASK(col) (0x80 >> ((col) % 8))

To this one:

  #define MASK(col) (0x80 >> ((col) & 7))

So I deleted/erase/commented it out the '#define MASK' and did the following:

On my 'life.c' file I created the following array:

int __life_mask_array[] = { 128, 64, 32, 16, 8, 4, 2, 1 };

And on my 'life.h' file had the following:

extern int __life_mask_array[]
#define MASK(col) (array[(col)&7])


问:
use object in my queries @query java spring
I get an error when I tried to reference an object in my query

```<code>@Query("select o from Account o where o.ownerId=:owner AND o.name like :#{#customer.name}") public List<Account> findBusinessObjectsForCurrentUserById(@Param("owner") String owner,@Param("customer") Customer customer);
</code>```

Error message :

```<code>No parameter binding found for name customer!; nested exception is java.lang.IllegalArgumentException: No parameter binding found for name customer!
</code>```

Thanks

答:
Try Like this.</p>

```<code> @Query("select o from Account o where o.ownerId=:owner AND o.name like CONCAT('%',:customer.name,'%')")
 public List<Account> findBusinessObjectsForCurrentUserById(@Param("owner") String owner,@Param("customer") Customer customer);
</code>```

Body:
I get an error when I tried to reference an object in my query

@Query("select o from Account o where o.ownerId=:owner AND o.name like :#{#customer.name}") public List<Account> findBusinessObjectsForCurrentUserById(@Param("owner") String owner,@Param("customer") Customer customer);

Error message :

No parameter binding found for name customer!; nested exception is java.lang.IllegalArgumentException: No parameter binding found for name customer!

Thanks

Body:
Try Like this.

 @Query("select o from Account o where o.ownerId=:owner AND o.name like CONCAT('%',:customer.name,'%')")
 public List<Account> findBusinessObjectsForCurrentUserById(@Param("owner") String owner,@Param("customer") Customer customer);


问:
Make multiple rest get requests and save output
I need to call a REST-ful webservice in using a GET method with some parameters and save the output of the same.

My first approach was to make some requests in JavaScript and log the output using console.log(), but the server doesn't allow CORS. So I can't make it that way.

I am pretty sure this might be a common thing but I can't seem to find a simple way to do it. What would be the simplest way to do it? Is there any software that would allow me to make an array, let's say with 100 parameters, save 100 calls or what would be a better way to do it? PHP script?

p.s. I can't activate CORS in the server, nor can I place code in the same domain. So far I have an example I can call in the browser and have the XML return.

答:
As far as CORS is concerned, that has to do with the API you're running on not allowing requests to be made from a different domain. This could be fixed by allowing CORS in the API you are developing on.

CORS Link: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

The other option would be to have your website on the same domain as the API.

Once you have done that, you can simply make multiple AJAX requests to the API.

AJAX HTTP GET example: HTTP GET request in JavaScript?

EDIT:

You might also have to enable CORS in the HTTP header of your request. This would have to be added to an AJAX request:

```<code> Access-Control-Request-Headers: x-requested-with
</code>```

Here is a helpful link for jquery in particular: How to get a cross-origin resource sharing (CORS) post request working

Body:
As far as CORS is concerned, that has to do with the API you're running on not allowing requests to be made from a different domain. This could be fixed by allowing CORS in the API you are developing on.

CORS Link: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

The other option would be to have your website on the same domain as the API.

Once you have done that, you can simply make multiple AJAX requests to the API.

AJAX HTTP GET example: HTTP GET request in JavaScript?

EDIT:

You might also have to enable CORS in the HTTP header of your request. This would have to be added to an AJAX request:

 Access-Control-Request-Headers: x-requested-with

Here is a helpful link for jquery in particular: How to get a cross-origin resource sharing (CORS) post request working


问:
bower support in visual studio 2012
I am trying to integrate angular-formly with visual studio 2012 and for that I did following steps:

Problem

Not able to integrate bower in Visual Studio 2012

So far approach taken

downloaded node.js and install bower using install -g bower.

from the project directory I installed angular-formly packages via

$ bower install angular api-check angular-formly --save

using requirejs I then plugged-in the generated .js files (inside bower_component folder) in my project.

I ran the project and I get following error.

Uncaught TypeError: Cannot read property 'version' of undefined   (in formly.js)

Questions:

Is there some web plugin for Visual Studio 2012 to read and parse packages downloaded via bower.

I read some of the articles which suggests that bower support is provided VS-2013 onwards, does that mean in order to use bower I have to upgrade to VS-2013?

Thank you.

答: Bower has been pretty much discontinued meaning you probably should not be using it and using npm instead</p>

Title: bower support in visual studio 2012


问:
Extracting a URL from a string in Python
I have a string like

```<code><dd>TF-AIDN, "Proposal for something...", Version 3.4, 18 November 2015 https://www.something.org/en/system/files/files/file-18nov15-en.pdf</dd>
</code>```

How can I modify the following statement to extract URL from such a string?

```<code>urlfinder = re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", re.MULTILINE|re.UNICODE)
</code>```

I am not able to figure out how can I modify the regular expression so that it takes < as the end mark of a URL instead of a space.

答:
You can use this regex instead:

```<code>(http[^<]+)
</code>```

Working demo

This will match a pattern having http and everything but <

Body:
I have a string like

TF-AIDN, "Proposal for something...", Version 3.4, 18 November 2015 https://www.something.org/en/system/files/files/file-18nov15-en.pdf

How can I modify the following statement to extract URL from such a string?

urlfinder = re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)", re.MULTILINE|re.UNICODE)

I am not able to figure out how can I modify the regular expression so that it takes < as the end mark of a URL instead of a space.

Body:
You can use this regex instead:

(http[^<]+)

Working demo

This will match a pattern having http and everything but <


问:
Split string without split function in c
So I'm writing a program that takes a persons name and splits it into their first and last name so for example if you enter JonSnow it should print:
First: Jon
Last: Snow

This is the code, please ignore the comments, I was testing a bunch of different ways to do it.

```<code>#include <stdio.h>
#include <string.h>

int main()
{
    char name[50],first[25],last[25];
    int i;

    printf("What is your name? ");
    scanf("%s",name);

    strcpy(first," ");
    strcpy(last," ");
    for(i=0;i<strlen(name);i++){
        strcat(first,name[i]);              //for(j=i+1;strlen(name);j++){
        if(name[i+1]>=65 && name[i+1]<=90){
            strcat(last,name[i]);
            strcat(last,name[i+1]);
        }
        //}
    }

    printf("First name: %s \n",first);
    printf("Last name: %s \n",last);
}
</code>```

When I run it in the terminal, I get this:

```<code>What is your name? JonSnow

Segmentation fault (core dumped)
</code>```

What is the problem, please help...

答:
I think your code is close, you're just messing up how to use strcat trying to add a single character to the end of a string, which it doesn't do.  Perhaps you can do something like this:

```<code>#include <stdio.h>
#include <string.h>

int main() {

char name[50],first[25] = {0},last[25] = {0};
int i;

    printf("What is your name? ");
    scanf("%s",name);

    for(i=0;i<strlen(name);i++) {
        if(name[i+1]>=65 && name[i+1]<=90) {
            strncpy(first,name,i+1);
            strcpy(last,&name[i+1]);
        }
    }
    printf("First name: %s \n",first);
    printf("Last name: %s \n",last);
}
</code>```

strncpy copies the number of characters specified by i+1 into first.

Body:
So I'm writing a program that takes a persons name and splits it into their first and last name so for example if you enter JonSnow it should print:
First: Jon
Last: Snow

This is the code, please ignore the comments, I was testing a bunch of different ways to do it.

#include <stdio.h>
#include <string.h>

int main()
{
    char name[50],first[25],last[25];
    int i;

    printf("What is your name? ");
    scanf("%s",name);

    strcpy(first," ");
    strcpy(last," ");
    for(i=0;i<strlen(name);i++){
        strcat(first,name[i]);              //for(j=i+1;strlen(name);j++){
        if(name[i+1]>=65 && name[i+1]<=90){
            strcat(last,name[i]);
            strcat(last,name[i+1]);
        }
        //}
    }

    printf("First name: %s \n",first);
    printf("Last name: %s \n",last);
}

When I run it in the terminal, I get this:

What is your name? JonSnow

Segmentation fault (core dumped)

What is the problem, please help...

Body:
I think your code is close, you're just messing up how to use strcat trying to add a single character to the end of a string, which it doesn't do.  Perhaps you can do something like this:

#include <stdio.h>
#include <string.h>

int main() {

char name[50],first[25] = {0},last[25] = {0};
int i;

    printf("What is your name? ");
    scanf("%s",name);

    for(i=0;i<strlen(name);i++) {
        if(name[i+1]>=65 && name[i+1]<=90) {
            strncpy(first,name,i+1);
            strcpy(last,&name[i+1]);
        }
    }
    printf("First name: %s \n",first);
    printf("Last name: %s \n",last);
}

strncpy copies the number of characters specified by i+1 into first.


问:
Time Series Stata date convert daily to quarterly returns scientific notation
I have data with daily frequency from 01Jan2000 to 30Dec2015, this series was formatted as date (format date %d). I was able to extract day, month and year using day(date), month(date), and year(date).

I also need to generate a variable indicating its quarter, I used gen quarterly=dofq(date), and then format quarterly %tq. Instead of returning the format 2000q1, I got bunches of scientific notations (eg. 1.2e+06). Does anyone know why and how I can fix that?

Thanks in advance!

答:
Here is some sample code that may point you in the direction you seek.</p>

```<code>. clear

. set obs 1
number of observations (_N) was 0, now 1

. generate test = td(21nov2016)

. format %d test

. generate qtr = quarter(test)

. generate yq = qofd(test)

. format %tq yq

. list

     +--------------------------+
     |      test   qtr       yq |
     |--------------------------|
  1. | 21nov2016     4   2016q4 |
     +--------------------------+
</code>```

Body:
Here is some sample code that may point you in the direction you seek.

. clear

. set obs 1
number of observations (_N) was 0, now 1

. generate test = td(21nov2016)

. format %d test

. generate qtr = quarter(test)

. generate yq = qofd(test)

. format %tq yq

. list

     +--------------------------+
     |      test   qtr       yq |
     |--------------------------|
  1. | 21nov2016     4   2016q4 |
     +--------------------------+


问:
Uncaught SyntaxError: Invalid or unexpected token ï»¿
I am trying to upgrade my project to webpack version 2.

After I got all my typescript compiling and webpack building I tried to run my site.  I ended up getting this error:

Uncaught SyntaxError: Invalid or unexpected token

This is in my webpack bundle.js file.  I went to the file to see what it is and found these chars:

ï»¿

The cursor was in between the ï and the ».

Those chars are at the start of a few of the npm packages I downloaded.  (I downloaded them with yarn.)

Searching bundle.js I can see those chars are in my bundle a few times:

At the start of jquery-color

At the start of jquery-inputmask

At the start of jquery-mask (yes I have both masks..)

One more that I don't recognize (about getSignedRequest).

How did these strange symbols get there, and how I can get rid of them?

答:
I added the webpack-utf8-bom plugin and it took care of it for me.

This is the npm page for the plugin: https://www.npmjs.com/package/webpack-utf8-bom

This is the usage from that page:

```<code>// import plugin
var BomPlugin = require('webpack-utf8-bom');

module.exports = {
  ...
  plugins: [
    // Add plugin in plugins list
    // true for adding bom
    // false for removing bom
    new BomPlugin(true)
  ],

 ...
};
</code>```

The key part is that it worked backwards from what I would have expected.  I would have thought that false would have gotten rid of the BOM chars, but actually using true got rid of the error.

```<code>new BomPlugin(true)
</code>```

I when I looked the chars had been replaced by a red dot.  My guess is that the plugin formatted them correctly so that they did not confuse the browser.

Body:
I added the webpack-utf8-bom plugin and it took care of it for me.

This is the npm page for the plugin: https://www.npmjs.com/package/webpack-utf8-bom

This is the usage from that page:

// import plugin
var BomPlugin = require('webpack-utf8-bom');

module.exports = {
  ...
  plugins: [
    // Add plugin in plugins list
    // true for adding bom
    // false for removing bom
    new BomPlugin(true)
  ],

 ...
};

The key part is that it worked backwards from what I would have expected.  I would have thought that false would have gotten rid of the BOM chars, but actually using true got rid of the error.

new BomPlugin(true)

I when I looked the chars had been replaced by a red dot.  My guess is that the plugin formatted them correctly so that they did not confuse the browser.


问:
warning 10 : this expression should have type unit
I'm writing a program in ocaml containing some loops "for", my problem is that for each of these cycles you receive this message: "warning 10 : this expression should have type unit. "

Example :

```<code>    let f q p rho=

       let x = [] in
       if q > p then
          for i=0 to rho do
              x= q :: x
          done;
    x;;
</code>```

this every time I use a cycle "for" ,how can I solve this problem?

答:
There are several problems with your code.

The error is because the for does not return anything, and so the inside of the loop to be purely for side-effect. So it should have unit type. Your use of = does not have unit type, because = is in fact the equality operator, comparing two values, and returning true or false.

So you are using the wrong operator. It appears that you are trying to "assign" to x. But in ML, you cannot assign to "variables", because they are bound to a value when they are defined and cannot change. One way to get mutability, is to use a mutable cell (called a "reference"): you use the ref function to create the mutable cell from an initial value; the ! operator to get its value out; and the := operator to change the value inside.

So for example:

```<code>let f q p rho=

   let x = ref [] in
   if q > p then
      for i=0 to rho do
          x := q :: !x
      done;
   !x;;
</code>```

Body:
I'm writing a program in ocaml containing some loops "for", my problem is that for each of these cycles you receive this message: "warning 10 : this expression should have type unit. "

Example :

    let f q p rho=

       let x = [] in
       if q > p then
          for i=0 to rho do
              x= q :: x
          done;
    x;;

this every time I use a cycle "for" ,how can I solve this problem?

Body:
There are several problems with your code.

The error is because the for does not return anything, and so the inside of the loop to be purely for side-effect. So it should have unit type. Your use of = does not have unit type, because = is in fact the equality operator, comparing two values, and returning true or false.

So you are using the wrong operator. It appears that you are trying to "assign" to x. But in ML, you cannot assign to "variables", because they are bound to a value when they are defined and cannot change. One way to get mutability, is to use a mutable cell (called a "reference"): you use the ref function to create the mutable cell from an initial value; the ! operator to get its value out; and the := operator to change the value inside.

So for example:

let f q p rho=

   let x = ref [] in
   if q > p then
      for i=0 to rho do
          x := q :: !x
      done;
   !x;;


问:
sql using offset row fetch not enough results
when requesting results using OFFSET row fetch, what happens if there are less than the m number of results found? How would you handle it efficiently?</p>

```<code>SELECT column-names
FROM table-name
ORDER BY column-names
OFFSET n ROWS
FETCH NEXT m ROWS ONLY
</code>```

答:
It's always possible for a result set to contain fewer rows than expected. A wise programmer never assumes a result set will have a precise predicted number of rows, but always uses a loop based on whether any rows remain. You keep reading rows until you've read them all.

Some perfectly normal result sets might contain no rows at all. Consider the case where the table contains exactly 20 rows and you read them 10 at a time. The third chunk of 10 rows will be empty.

The example in the documentation for mysqli's fetch_row() method makes this clear.

```<code>if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row()) {
        /* process the row ... */
    }
    /* free result set */
    $result->close();
}
</code>```

Body:
when requesting results using OFFSET row fetch, what happens if there are less than the m number of results found? How would you handle it efficiently?

SELECT column-names
FROM table-name
ORDER BY column-names
OFFSET n ROWS
FETCH NEXT m ROWS ONLY

Body:
It's always possible for a result set to contain fewer rows than expected. A wise programmer never assumes a result set will have a precise predicted number of rows, but always uses a loop based on whether any rows remain. You keep reading rows until you've read them all.

Some perfectly normal result sets might contain no rows at all. Consider the case where the table contains exactly 20 rows and you read them 10 at a time. The third chunk of 10 rows will be empty.

The example in the documentation for mysqli's fetch_row() method makes this clear.

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row()) {
        /* process the row ... */
    }
    /* free result set */
    $result->close();
}


问:
Unwrap a div in react, something similar to jQuery unwrap method
I am using React JSX. I have a div with className="shadow" as shown below.

```<code><div className="main">
  <div className="shadow" style={{backgroundColor: "#FFFFFF"}}>
    <div id="wrapper">
      Hello
    </div>
  </div>
</div>
</code>```

Based on a certain condition being true or false, I want to remove the div with className="shadow", but want to keep every div including the div with id="wrapper" intact. Something like unwrap() method of jQuery.
Something to the effect of what is written below, but without so many lines of code.

```<code>  if ( currentPage==="login") {
   <div className="main">
     <div id="wrapper">
       Hello
     </div>
   </div>
}
else {
    <div className="main">
  <div className="shadow" style={{backgroundColor: "#FFFFFF"}}>
    <div id="wrapper">
      Hello
    </div>
  </div>
</div>
}
</code>```

I checked React.js: Wrapping one component into another and How to pass in a react component into another react component to transclude the first component's content?, but didn't get what I am looking for.

答:
Maybe what can help you is to change the className based on the page you are on, because what you try to do would be better using react-router to display different components based on the path you are on.

Use something similar to this code, I hope I can help you.

const App = React.createClass({
  changePage(nextPage) {
    this.setState({ page: nextPage })
  },
  getInitialState() {
    return({
      page: 'Login'
    })
  },
  render() {
    return(

            Hello from { this.state.page } page.

          <button onClick={ this.changePage.bind(null, 'Login') }>Go to Login page.</button>
          <button onClick={ this.changePage.bind(null, 'Home') }>Go to Home page.</button>

    )
  }
})

ReactDOM.render(<App />, document.getElementById('app'))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.shadow{ background-color: #000000; color: #ffffff}</code>```

```

Body:
I am using React JSX. I have a div with className="shadow" as shown below.

      Hello

Based on a certain condition being true or false, I want to remove the div with className="shadow", but want to keep every div including the div with id="wrapper" intact. Something like unwrap() method of jQuery.
Something to the effect of what is written below, but without so many lines of code.

  if ( currentPage==="login") {

       Hello

}
else {

      Hello

}

I checked React.js: Wrapping one component into another and How to pass in a react component into another react component to transclude the first component's content?, but didn't get what I am looking for.

Body:
Maybe what can help you is to change the className based on the page you are on, because what you try to do would be better using react-router to display different components based on the path you are on.

Use something similar to this code, I hope I can help you.

const App = React.createClass({
  changePage(nextPage) {
    this.setState({ page: nextPage })
  },
  getInitialState() {
    return({
      page: 'Login'
    })
  },
  render() {
    return(
      <div className="main">
        <div className={ this.state.page === 'Login' ? 'shadow' : '' }>
          <div id="wrapper">
            Hello from { this.state.page } page.
          </div>
          <button onClick={ this.changePage.bind(null, 'Login') }>Go to Login page.</button>
          <button onClick={ this.changePage.bind(null, 'Home') }>Go to Home page.</button>
        </div>
      </div>
    )
  }
})

ReactDOM.render(<App />, document.getElementById('app'))

div.shadow{ background-color: #000000; color: #ffffff}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'></div>


问:
How to use from_json to allow for messages to have different fields?
I am trying to process data from Kafka using Spark Structured Streaming. The code for ingesting the data is as follows:

val enriched = df.select($"value" cast "string" as "json")
  .select(from_json($"json", schema) as "data")
  .select("data.*")
```

ds is a DataFrame with the data consumed from Kafka.

The problem comes when I try to read is as JSON in order to do faster queries. the function that comes from org.apache.spark.sql.functions from_json() is asking obligatory for a schema. What if the messages have some different fields?

答:
As @zero323 and the answer he or she referenced suggest, you are asking a contradictory question: essentially how does one impose a schema when one doesn't know the schema? One can't of course. I think the idea to use open-ended collection types is your best option.

Ultimately though, it is almost certainly true that you can represent your data with a case class even if it means using a lot of Options, strings you need to parse, and maps you need to interrogate. Invest in the effort to define that case class. Otherwise, your Spark jobs will essentially a lot of ad hoc, time-consuming busywork.

Body:
I am trying to process data from Kafka using Spark Structured Streaming. The code for ingesting the data is as follows:

val enriched = df.select($"value" cast "string" as "json")
  .select(from_json($"json", schema) as "data")
  .select("data.*")

ds is a DataFrame with the data consumed from Kafka.

The problem comes when I try to read is as JSON in order to do faster queries. the function that comes from org.apache.spark.sql.functions from_json() is asking obligatory for a schema. What if the messages have some different fields?


问:
How to get distinct records in the quickviewer?
I would like to get distinct record values as a result in the quickviewer.  Is there any way to do that?</p>

答:
This is not an answer (I would comment, but i can't, yet).

Do you mean distinct records from a single db table?
Since queries query a db table, which presumably has unique keys, the only thing to do is enforcing as input to the query all the required keys.

Or do you mean fields of different records having different (distinct) values? I haven't tried that, but what about injecting some extra code, from transaction SQ02, and deleting/collecting rows based on your criteria, thus ensuring distinct non-key fields in your records.


问:
How to add NSTextFields to NSScrollView
I want to add multiple NSTextFields to NSScrollView dynamically.

Code:

```<code>func addLabel(data: String)
{
    let offset = labelCount*20
    let label = NSTextField(frame: NSMakeRect(0, CGFloat(offset), 200, 20))
    label.stringValue = data
    scrollView.documentView?.addSubview(label)
    labelCount += 1

    // scrollView is IBOutlet
    // labelCount is var to keep record of number of labels
}
</code>```

Problem:

It adds the NSTextFields correctly to the NSScrollView but they are only added till the visible part is available. After the visible part of NSScrollView is full, no more NSTextFields are added to it.

I need to add NSTextFields even though the visible part is full and scroll to find others.

How can I do it?

答:
It's something like the following.</p>

```<code>scrollView.documentView?.setFrameSize(CGSize(width: CGFloat(labelCount) * 200, height: 20))
</code>```

Title: How to add NSTextFields to NSScrollView

Body:
I want to add multiple NSTextFields to NSScrollView dynamically.

Code:

func addLabel(data: String)
{
    let offset = labelCount*20
    let label = NSTextField(frame: NSMakeRect(0, CGFloat(offset), 200, 20))
    label.stringValue = data
    scrollView.documentView?.addSubview(label)
    labelCount += 1

    // scrollView is IBOutlet
    // labelCount is var to keep record of number of labels
}

Problem:

It adds the NSTextFields correctly to the NSScrollView but they are only added till the visible part is available. After the visible part of NSScrollView is full, no more NSTextFields are added to it.

I need to add NSTextFields even though the visible part is full and scroll to find others.

How can I do it?

Body:
It's something like the following.

scrollView.documentView?.setFrameSize(CGSize(width: CGFloat(labelCount) * 200, height: 20))


问:
Show/Hide events on fullcalendar using javascript
I'm making a religious calendar for a project that shows different events for all major religions. I'm using full calendar, and I have a "religion key" at the top of the calendar, and I want to make it so that when I click, for example, Jewish, it will hide all religious events/holidays on the calendar that don't pertain to the Jewish faith. I'm having some trouble. My thinking was that I would set the ".fc-event" class in css to display:none" and then have a class called .show that would be display:block. and toggle that class / remove that class when the user clicks the menu item that pertains to the holiday. Is there a better / easier way to do this? would love some guidance/tips/help :) thank you.

Here is my code for the calendar js (using made up dates obviously):

```<code>events: [
        {
            title: 'xmas',
            start: '2017-03-19',
            className: 'catholic show',
            description: 'blablablablabla'
        },
        {
            title: 'Hanukkah',
            start: '2017-03-19',
            className: 'jewish show',
            description: 'blablablabla'
        },
        {
            title: 'Hindu Holiday',
            start: '2017-03-24',
            end: '2017-03-27',
            className: 'hindu show',
            description: 'blablablabla'
        }
    ]
});

$('.calendar-nav a').each(function() {

    $(this).on('click', function(e) {
        e.preventDefault();

        var x = $(this).attr('rel');

        $('.fc-event-container').each(function() {

            $(this).removeClass('show');

            if($(this).hasClass(x)) {

                $(this).addClass('show');
            }
        });
    })
});

$('.show-all a').on('click', function() {
    $('.fc-event-container').each(function() {
        if(!$(this).hasClass('show')) {
            $(this).toggleClass('show');
        }
    });
});
});
</code>```

And the php code for the calendar and calendar-key:

```<code><nav class="calendar-nav">
<ul class="menu">
    <li class="christianity-text"><a href="#" rel="christian">><img src="/images/calendar/christianity.png" />CHRISTIAN</a>
        <ul class="sub-menu">
            <li><a href="#">Catholic</a></li>
            <li><a href="#">Protestant</a></li>
            <li><a href="#">Coptic</a></li>
            <li><a href="#">Mormon</a></li>
            <li><a href="#">Neo</a></li>
            <li><a href="#">Anglican</a></li>
            <li><a href="#">Celtic</a></li>
            <li><a href="#">Jehova's Witness</a></li>
        </ul>
    </li>
    <li class="buddhist-text"><a  href="#" rel="buddhist"><img src="/images/calendar/buddhism.png" />BUDDHIST</a></li>
    <li class="hindu-text"><a  href="#" rel="hindu"><img src="/images/calendar/hindu.png" />HINDU</a></li>
    <li class="jewish-text"><a  href="#" rel="jewish"><img src="/images/calendar/jewish.png" />JEWISH</a></li>
    <li class="islam-text"><a  href="#" rel="islam"><img src="/images/calendar/islam.png" />ISLAM</a></li>
    <li class="sikh-text"><a  href="#" rel="sikh"><img src="/images/calendar/sikh.png" />SIKH</a></li>

    <li class="pagan-text"><a  href="#" rel="pagan"><img src="/images/calendar/pagan.png" />PAGAN</a></li>
    <li class="wiccan-text"><a  href="#" rel="wiccan"><img src="/images/calendar/wiccan.png" />WICCAN</a></li>
    <li class="other-text"><a  href="#" rel="other"><img src="/images/calendar/other.png" />OTHER</a></li>
    <li class="all-text"><a href="#" rel="all">ALL</a></li>
</ul>
</nav>

<div id='calendar'></div>
</code>```

答:
Think this sort of thing is a lot easier to manage with CSS and a tiny bit of JS. The example below is a sort of minimal use case version but the idea is the same.

/*
Listen for clicks on the nav. Use each 's "data-show"
property to determine which class to add to the #calendar.

That class, along with the CSS will determine which to show (hide, actually).

By default, all events are shown. Only when the #calendar element
gets a class associated with our CSS does anything change.

Since we're using the :not() selector to _hide_ everything else
(instead of showing something specific) there's no need for
any 'show all'. Once #calendar has 'show-all', the default CSS comes through.
*/

$('.calendar-nav').on('click', 'a', function(evt) {
  var showType = $(this).data('show');
  var $calendar = $('#calendar');
  if(showType !== undefined) {
    $calendar.attr('class', '').attr('class', 'show-' + showType);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.show-hindu li:not(.hindu),
.show-pagan li:not(.pagan)
/* ... continue ... */ {
  display: none;
}</code>```

  Hindu
  Pagan
  All

Hindu 1

Pagan 1

Hindu 2

Pagan 2

Hindu 3

Pagan 3

```

Body:
I'm making a religious calendar for a project that shows different events for all major religions. I'm using full calendar, and I have a "religion key" at the top of the calendar, and I want to make it so that when I click, for example, Jewish, it will hide all religious events/holidays on the calendar that don't pertain to the Jewish faith. I'm having some trouble. My thinking was that I would set the ".fc-event" class in css to display:none" and then have a class called .show that would be display:block. and toggle that class / remove that class when the user clicks the menu item that pertains to the holiday. Is there a better / easier way to do this? would love some guidance/tips/help :) thank you.

Here is my code for the calendar js (using made up dates obviously):

events: [
        {
            title: 'xmas',
            start: '2017-03-19',
            className: 'catholic show',
            description: 'blablablablabla'
        },
        {
            title: 'Hanukkah',
            start: '2017-03-19',
            className: 'jewish show',
            description: 'blablablabla'
        },
        {
            title: 'Hindu Holiday',
            start: '2017-03-24',
            end: '2017-03-27',
            className: 'hindu show',
            description: 'blablablabla'
        }
    ]
});

$('.calendar-nav a').each(function() {

    $(this).on('click', function(e) {
        e.preventDefault();

        var x = $(this).attr('rel');

        $('.fc-event-container').each(function() {

            $(this).removeClass('show');

            if($(this).hasClass(x)) {

                $(this).addClass('show');
            }
        });
    })
});

$('.show-all a').on('click', function() {
    $('.fc-event-container').each(function() {
        if(!$(this).hasClass('show')) {
            $(this).toggleClass('show');
        }
    });
});
});

And the php code for the calendar and calendar-key:

>CHRISTIAN

Catholic

Protestant

Coptic

Mormon

Neo

Anglican

Celtic

Jehova's Witness

BUDDHIST

HINDU

JEWISH

ISLAM

SIKH

PAGAN

WICCAN

OTHER

ALL

Body:
Think this sort of thing is a lot easier to manage with CSS and a tiny bit of JS. The example below is a sort of minimal use case version but the idea is the same.

/*
Listen for clicks on the nav. Use each <a>'s "data-show"
property to determine which class to add to the #calendar.

That class, along with the CSS will determine which to show (hide, actually).

By default, all events are shown. Only when the #calendar element
gets a class associated with our CSS does anything change.

Since we're using the :not() selector to _hide_ everything else
(instead of showing something specific) there's no need for
any 'show all'. Once #calendar has 'show-all', the default CSS comes through.
*/

$('.calendar-nav').on('click', 'a', function(evt) {
  var showType = $(this).data('show');
  var $calendar = $('#calendar');
  if(showType !== undefined) {
    $calendar.attr('class', '').attr('class', 'show-' + showType);
  }
});

.show-hindu li:not(.hindu),
.show-pagan li:not(.pagan)
/* ... continue ... */ {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="calendar-nav">
  <a href="#" data-show="hindu">Hindu</a>
  <a href="#" data-show="pagan">Pagan</a>
  <a href="#" data-show="all">All</a>
</nav>

<div id="calendar">
  <ul class="events">
    <li class="hindu">Hindu 1</li>
    <li class="pagan">Pagan 1</li>
    <li class="hindu">Hindu 2</li>
    <li class="pagan">Pagan 2</li>
    <li class="hindu">Hindu 3</li>
    <li class="pagan">Pagan 3</li>
  </ul>
</div>


问:
Redirect subdomain using htaccess
I am trying to set up a subdomain so that it will redirect to a specific file. EG. register.mydomain.com should show the page at www.mydomain.com/includes/register.php but still show register.mydomain.com in the browser.

The site is currently set up to not show extensions in the address bar eg. www.mydomain.com/register using the htaccess file as below and this works fine.

```<code>RewriteEngine On
RewriteRule ^register$ includes/register.php
</code>```

答:
The first thing to notice here, is the files should be in same document root. This means, your .htaccess file and includes/register.php files should be in same root folder for application. You can then rewrite the rule -

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^register\.mydomain\.com$ [NC]
RewriteRule ^$ includes/register.php [L]
</code>```

This might work, reload Apache after changing .htaccess files.

Title: Redirect subdomain using htaccess

Body:
I am trying to set up a subdomain so that it will redirect to a specific file. EG. register.mydomain.com should show the page at www.mydomain.com/includes/register.php but still show register.mydomain.com in the browser.

The site is currently set up to not show extensions in the address bar eg. www.mydomain.com/register using the htaccess file as below and this works fine.

RewriteEngine On
RewriteRule ^register$ includes/register.php

Body:
The first thing to notice here, is the files should be in same document root. This means, your .htaccess file and includes/register.php files should be in same root folder for application. You can then rewrite the rule -

RewriteEngine On
RewriteCond %{HTTP_HOST} ^register\.mydomain\.com$ [NC]
RewriteRule ^$ includes/register.php [L]

This might work, reload Apache after changing .htaccess files.


问:
Razor - Converting Json result from controller to a complex object
i have a partial view "_SearchPanel" that has year list dropdown, a classes multiselect control, (some other drop downs - ommitted) and a search button.

I want that when i change selection in year list drop down, only my classes list is refreshed/updated, and not the whole partial view on page.

So i use a JsonResult action in my controller (as opposed to the first time load)

```<code> public JsonResult BindClasses(int yearId)
    {
        ClassRepository repClass = new ClassRepository("name=ge");
        YearRepository repYear = new YearRepository("name=ge");

        var dataClass = repClass.GetClassesByYear(yearId);
        var groupedClassOptions = dataClass.GroupBy(x => x.grade).Select(x => new OptionGroupVM()
        {
            GroupName = "Grade " + x.Key.ToString(),
            Options = x.Select(y => new OptionVM()
            {
                Value = y.classID.ToString(),
                Text = y.classname
            })
        });

        return Json(groupedClassOptions);

    }
</code>```

My javascript

```<code>var dropDownYear = $('#ddlYear');
    dropDownYear.change(function(){
        $("#classList").load(url, {yearId: $(this).val()}, function(result){

            setOptions($('#classList'), @Html.Raw(Json.Encode(new List<int>(){})), result);
        });

    });
</code>```

now the problem is this result is not considered as an object as was the first time (onpageload) here:

```<code>jQuery(function ($) {
   setOptions($('#classList'), @Html.Raw(Json.Encode(Model.SelectedClasses)), @Html.Raw(Json.Encode(Model.ClassOptions)));
 }
</code>```

How do i correct/cast it to be considered as Model.ClassOptions(type: GroupOptionsVM List) object instead of a Json

What I have tried

```<code>    var url = '@Url.Action("BindClasses", "Maps")';
    var dropDownYear = $('#ddlYear');
    dropDownYear.change(function(){
        $("#classList").load(url, {yearId: $(this).val()}, function(result){
            @{var x = new List<OptionGroupVM>();}
            x = result;
            setOptions($('#classList'), @Html.Raw(Json.Encode(new List<int>(){})), x);

        });

    });
</code>```

this gives me some syntax errors!!

UPDATE

[Referring to the previous question Stephen linked in comments]
Since i had to do it for two dropdown lists with slight difference i had created setOptions function in my script

```<code>function setOptions(listBox, selected, groups) {

    // Generate options
    createGroupedOptions(listBox, selected, groups);

    // Attach plug-in
    listBox.multiselect({ enableClickableOptGroups: true, onChange: function(){
        var selectedClassItems = this.$select.val();

    } });

}

function createGroupedOptions(element, selected, groups) {

    for (var i = 0; i < groups.length; i++) {
        var group = groups[i];
        var groupElement = $('<optgroup></optgroup>').attr('label', group.GroupName);
        for (var j = 0; j < group.Options.length; j++) {
            var option = group.Options[j];
            var optionElement = $('<option></option>').val(option.Value).text(option.Text);
            if (selected) {
                if (selected.toString().indexOf(option.Value) >= 0) {
                    optionElement.attr('selected', 'selected')
                }
            } else {
                if (option.IsSelected) {
                    optionElement.attr('selected', 'selected')
                }
            }

            $(groupElement).append(optionElement);
        }
        $(element).append(groupElement);
    }

}
</code>```

CALLING setOptions function

```<code>setOptions($('#classList'), @Html.Raw(Json.Encode(Model.SelectedClasses)), @Html.Raw(Json.Encode(Model.ClassOptions)));
    setOptions($('#indicatorList'), @Html.Raw(Json.Encode(Model.SelectedIndicators)), @Html.Raw(Json.Encode(Model.IndicatorOptions)));
</code>```

答:
You are trying to mix client side code (jQuery) with server side code (.NET) and it won't work.  @Html.Raw and JsonEncode are server side methods.  You can't use them after the page loads.

In essence, you need to either use jQuery for all of your page interaction and manage the state of the page on the client side or use full MVC (postback) and do everything on the server.

There are technically other options but I just wanted to address the fundamental issue with what you have tried so far.

Body:
i have a partial view "_SearchPanel" that has year list dropdown, a classes multiselect control, (some other drop downs - ommitted) and a search button.

I want that when i change selection in year list drop down, only my classes list is refreshed/updated, and not the whole partial view on page.

So i use a JsonResult action in my controller (as opposed to the first time load)

 public JsonResult BindClasses(int yearId)
    {
        ClassRepository repClass = new ClassRepository("name=ge");
        YearRepository repYear = new YearRepository("name=ge");

        var dataClass = repClass.GetClassesByYear(yearId);
        var groupedClassOptions = dataClass.GroupBy(x => x.grade).Select(x => new OptionGroupVM()
        {
            GroupName = "Grade " + x.Key.ToString(),
            Options = x.Select(y => new OptionVM()
            {
                Value = y.classID.ToString(),
                Text = y.classname
            })
        });

        return Json(groupedClassOptions);

    }

My javascript

var dropDownYear = $('#ddlYear');
    dropDownYear.change(function(){
        $("#classList").load(url, {yearId: $(this).val()}, function(result){

            setOptions($('#classList'), @Html.Raw(Json.Encode(new List<int>(){})), result);
        });

    });

now the problem is this result is not considered as an object as was the first time (onpageload) here:

jQuery(function ($) {
   setOptions($('#classList'), @Html.Raw(Json.Encode(Model.SelectedClasses)), @Html.Raw(Json.Encode(Model.ClassOptions)));
 }

How do i correct/cast it to be considered as Model.ClassOptions(type: GroupOptionsVM List) object instead of a Json

What I have tried

    var url = '@Url.Action("BindClasses", "Maps")';
    var dropDownYear = $('#ddlYear');
    dropDownYear.change(function(){
        $("#classList").load(url, {yearId: $(this).val()}, function(result){
            @{var x = new List<OptionGroupVM>();}
            x = result;
            setOptions($('#classList'), @Html.Raw(Json.Encode(new List<int>(){})), x);

        });

    });

this gives me some syntax errors!!

UPDATE

[Referring to the previous question Stephen linked in comments]
Since i had to do it for two dropdown lists with slight difference i had created setOptions function in my script

function setOptions(listBox, selected, groups) {

    // Generate options
    createGroupedOptions(listBox, selected, groups);

    // Attach plug-in
    listBox.multiselect({ enableClickableOptGroups: true, onChange: function(){
        var selectedClassItems = this.$select.val();

    } });

}

function createGroupedOptions(element, selected, groups) {

    for (var i = 0; i < groups.length; i++) {
        var group = groups[i];
        var groupElement = $('<optgroup></optgroup>').attr('label', group.GroupName);
        for (var j = 0; j < group.Options.length; j++) {
            var option = group.Options[j];
            var optionElement = $('<option></option>').val(option.Value).text(option.Text);
            if (selected) {
                if (selected.toString().indexOf(option.Value) >= 0) {
                    optionElement.attr('selected', 'selected')
                }
            } else {
                if (option.IsSelected) {
                    optionElement.attr('selected', 'selected')
                }
            }

            $(groupElement).append(optionElement);
        }
        $(element).append(groupElement);
    }

}

CALLING setOptions function

setOptions($('#classList'), @Html.Raw(Json.Encode(Model.SelectedClasses)), @Html.Raw(Json.Encode(Model.ClassOptions)));
    setOptions($('#indicatorList'), @Html.Raw(Json.Encode(Model.SelectedIndicators)), @Html.Raw(Json.Encode(Model.IndicatorOptions)));


问:
Javascript Injection with Xamarin forms WebView
I want to change the value of an element inside a Xamarin forms WebView

I created a new project and added a WebView page that loads https://www.google.com/

I have used .Eval

m_GoogleWebView.Eval("alert('coolness!');");

This alerts fine for me. However if I try to access the dom at all, it just replaces the WebView with the text 'test text'

```<code>m_GoogleWebView.Eval("document.getElementById('lst-ib').value='test text';");
</code>```

How should I manipulate elements from Xamarin Forms?

答:
This is an issue with any WebView on Android after 4.1.

What you need to do, is assign your script to a variable like this

```<code>m_GoogleWebView.Eval("var x = document.getElementById('lst-ib').value='test text';");
</code>```

This still runs the script but now just assigns the result to the variable instead of the DOM.

Body:
I want to change the value of an element inside a Xamarin forms WebView

I created a new project and added a WebView page that loads https://www.google.com/

I have used .Eval

m_GoogleWebView.Eval("alert('coolness!');");

This alerts fine for me. However if I try to access the dom at all, it just replaces the WebView with the text 'test text'

m_GoogleWebView.Eval("document.getElementById('lst-ib').value='test text';");

How should I manipulate elements from Xamarin Forms?

Body:
This is an issue with any WebView on Android after 4.1.

What you need to do, is assign your script to a variable like this

m_GoogleWebView.Eval("var x = document.getElementById('lst-ib').value='test text';");

This still runs the script but now just assigns the result to the variable instead of the DOM.


问:
Getting device's local timezone
2010-06-14 02:21:49+0400 or 2010-06-14 02:21:49-0400

is there a way to convert this string to the date according to the local machine time zone with format 2010-06-14 02:21 AM

答:
Adding to what @org.life.java and @Erica said, here's what you should do

```<code>String dateStr = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
Date date = sdf.parse(dateStr);

sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String newDateStr = sdf.format(date);

System.out.println(newDateStr);
</code>```

Then newDateStr will be your new date formatted string.

UPDATE @xydev, the example I gave you works, see the full source code below:

```<code>/**
 *
 */
package testcases;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author The Elite Gentleman
 *
 */
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            String dateStr = "2010-06-14 02:21:49-0400";
            SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
            TimeZone tz = TimeZone.getDefault();
            sdf.setTimeZone(tz);
            Date date = sdf.parse(dateStr);

            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
            String newDateStr = sdf.format(date);

            System.out.println(newDateStr);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

Output: 2010-06-14 08:21:49 AM

Title: Getting device's local timezone

Body:
Adding to what @org.life.java and @Erica said, here's what you should do

String dateStr = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
Date date = sdf.parse(dateStr);

sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String newDateStr = sdf.format(date);

System.out.println(newDateStr);

Then newDateStr will be your new date formatted string.

UPDATE @xydev, the example I gave you works, see the full source code below:

/**
 *
 */
package testcases;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author The Elite Gentleman
 *
 */
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            String dateStr = "2010-06-14 02:21:49-0400";
            SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
            TimeZone tz = TimeZone.getDefault();
            sdf.setTimeZone(tz);
            Date date = sdf.parse(dateStr);

            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
            String newDateStr = sdf.format(date);

            System.out.println(newDateStr);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Output: 2010-06-14 08:21:49 AM