问:
Annoying IE8 dropdown issue in XP but not windows 7
I have an annoying issue with a select html element that cuts off the text in the dropdown when it is longer then the set width of the select html element.

The select elements need to be a set width to stop the page misalinging, Every browser seems to work except for IE8 running on XP. why? so random and bad compatibility.

please let me know if you need more infomation.

Thanks!

答: i'm not sure of the differences between OS, but just use conditional comments to style the select in IE. style the  as well. </p>


来源: stackexchange

问:
Error compiling a cpp file (ros)
I'm working on knowrob package and I already wrote my ontology(XML file) with Protege.
If I parse the owl.file and send some queries I have right answers.
Now my problem is to make a cpp to parse my xml file.
I already read something about json_prolog to send queries from my program to knowrob but is too muddler(http://www.knowrob.org/doc/interact_with_knowrob_via_ros).
I create my launch file and it works,later when i try to compile this cpp file:

```<code>#include <string>
#include <ros/ros.h>
#include <json_prolog/prolog.h>
using namespace std;
using namespace json_prolog;
int main(int argc, char *argv[])
{
    ros::init(argc, argv, "test_json_prolog");
    Prolog pl;
    PrologQueryProxy bdgs = pl.query("member(A, [1, 2, 3, 4]), B = ['x', A],             C = foo(bar, A, B)");

    for(PrologQueryProxy::iterator it=bdgs.begin();

    it != bdgs.end(); it++)
    {
        PrologBindings bdg = *it;
        cout << "Found solution: " << (bool)(it == bdgs.end()) << endl;
        cout << "A = "<< bdg["A"] << endl;
        cout << "B = " << bdg["B"] << endl;
        cout << "C = " << bdg["C"] << endl;
    }
    return 0;
}code here
</code>```

I have the error:

```<code>/tmp/cccLQk3H.o:test_json_prolog.cpp:function main: error: undefined reference to 'ros::init(int&, char**, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned int)'
</code>```

and other similar error about the undefined reference.

CMakelist :

```<code>cmake_minimum_required(VERSION 2.8.3)
project(json_prolog)
find_package(catkin REQUIRED rosjava_build_tools roscpp rospy json_prolog_msgs)
catkin_rosjava_setup(installApp publishMavenJavaPublicationToMavenRepository writeClasspath)
install(DIRECTORY ${CATKIN_DEVEL_PREFIX}/${CATKIN_GLOBAL_MAVEN_DESTINATION}/org/knowrob/${PROJECT_NAME}/
    DESTINATION ${CATKIN_GLOBAL_MAVEN_DESTINATION}/org/knowrob/${PROJECT_NAME})
catkin_package(INCLUDE_DIRS include LIBRARIES json_prolog CATKIN_DEPENDS json_prolog_msgs )

# find SWI Prolog libraries
include(FindPkgConfig)
pkg_check_modules(SWIPL REQUIRED swipl)
include_directories(${SWIPL_INCLUDE_DIRS})
link_directories(${SWIPL_LIBRARY_DIRS})

# export Python libraries
catkin_python_setup()

# C++ client library

include_directories(include ${catkin_INCLUDE_DIRS})
find_package(PkgConfig)
pkg_check_modules(JSON_GLIB REQUIRED json-glib-1.0)
add_definitions(${JSON_GLIB_CFLAGS})
link_directories(${JSON_GLIB_LIBRARIY_DIRS})
</code>```

How can I solve it?

答:
You can try to compile it directly using g++ compiler.

Please check this answer:
Compile roscpp without ros (using g++)

There a source code is compiled without cmake or catkin_make

ContentLicense: CC BY-SA 3.0

Title: Error compiling a cpp file (ros)

Body:
I'm working on knowrob package and I already wrote my ontology(XML file) with Protege.
If I parse the owl.file and send some queries I have right answers.
Now my problem is to make a cpp to parse my xml file.
I already read something about json_prolog to send queries from my program to knowrob but is too muddler(http://www.knowrob.org/doc/interact_with_knowrob_via_ros).
I create my launch file and it works,later when i try to compile this cpp file:

#include <string>
#include <ros/ros.h>
#include <json_prolog/prolog.h>
using namespace std;
using namespace json_prolog;
int main(int argc, char *argv[])
{
    ros::init(argc, argv, "test_json_prolog");
    Prolog pl;
    PrologQueryProxy bdgs = pl.query("member(A, [1, 2, 3, 4]), B = ['x', A],             C = foo(bar, A, B)");

    for(PrologQueryProxy::iterator it=bdgs.begin();

    it != bdgs.end(); it++)
    {
        PrologBindings bdg = *it;
        cout << "Found solution: " << (bool)(it == bdgs.end()) << endl;
        cout << "A = "<< bdg["A"] << endl;
        cout << "B = " << bdg["B"] << endl;
        cout << "C = " << bdg["C"] << endl;
    }
    return 0;
}code here

I have the error:

/tmp/cccLQk3H.o:test_json_prolog.cpp:function main: error: undefined reference to 'ros::init(int&, char**, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned int)'

and other similar error about the undefined reference.

CMakelist :

cmake_minimum_required(VERSION 2.8.3)
project(json_prolog)
find_package(catkin REQUIRED rosjava_build_tools roscpp rospy json_prolog_msgs)
catkin_rosjava_setup(installApp publishMavenJavaPublicationToMavenRepository writeClasspath)
install(DIRECTORY ${CATKIN_DEVEL_PREFIX}/${CATKIN_GLOBAL_MAVEN_DESTINATION}/org/knowrob/${PROJECT_NAME}/
    DESTINATION ${CATKIN_GLOBAL_MAVEN_DESTINATION}/org/knowrob/${PROJECT_NAME})
catkin_package(INCLUDE_DIRS include LIBRARIES json_prolog CATKIN_DEPENDS json_prolog_msgs )

# find SWI Prolog libraries
include(FindPkgConfig)
pkg_check_modules(SWIPL REQUIRED swipl)
include_directories(${SWIPL_INCLUDE_DIRS})
link_directories(${SWIPL_LIBRARY_DIRS})

# export Python libraries
catkin_python_setup()

# C++ client library

include_directories(include ${catkin_INCLUDE_DIRS})
find_package(PkgConfig)
pkg_check_modules(JSON_GLIB REQUIRED json-glib-1.0)
add_definitions(${JSON_GLIB_CFLAGS})
link_directories(${JSON_GLIB_LIBRARIY_DIRS})

How can I solve it?


问:
"node --debug" and "node --debug-brk" are invalid
I have updated the node (v8.1.2). When I want to debug my previous test project in nodejs using NTVS (in visual studio 2017) I've gotten the following error:

StandardError: (node:5292) [DEP0062] DeprecationWarning: node --debug and node --debug-brk are invalid. Please use node --inspect or node --inspect-brk instead.

The problem is clear. The tool try to run the node --debug to start the project.

The question is, how can I change node --debug to node --inspect in Visual Studio 2017 to running the test?

Also, I should have mentioned that I can't solve the problem by adding --inspect into the Script Arguments.

答: You should update the IDE vsc  to the newest version(v1.13)，my node version is v8.0.0 ;it can solve this problem.</p>


问:
Customizing the Spring Roo generated GWT user interface
How does one go about customizing the GWT user interface that Spring Roo automatically generates?

Am I supposed to change the Roo-generated source files? If so, will that not be clobbered the next time Roo runs?

Or do I need to configure something in Roo and then rebuild the GWT sources?

In this particular case, the column widths of the domain object list view need to be adjusted.

答: May I humbly suggest Metawidget? It generates Spring MVC, GWT and other interfaces at runtime, so there is no regeneration step (and nothing to get 'clobbered') as your entities change.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
android how to scan or take picture using camera and store that pic in our app
how to use camera in app and store the taken  pic in the app..it i  referred many tutorials but i didnt get the proper code..please help me to solve the problem.My code will ask for save option...and when we reopen the app the picture is not saved neither in app nor in gallery....Please help to do that ..my code is...In this code the captured image is stored in that image view...for once  </p>

```<code>  this.imageView = (ImageView)this.findViewById(R.id.imageView1);
    Button photoButton = (Button) this.findViewById(R.id.button1);
    photoButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    }) ;
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);
    }
</code>```

答:
Here is a method to save bitmap to storage. The imageMainDirectory would look like "/MyApp/". The imageDirectory would look like "/MyApp/MyImages/"

```<code> public boolean saveBitmapToStorage(Bitmap bitmap, String imageMainDirectory,
                                       String imageDirectory, String fileName) {
        boolean result = false;
        // This is true if the saving of image to the external storage fails.
        // Then we proceed to the internal storage
        boolean proceedToInternal;

        // You need to check if External Storage is writable/readable
        if (MemoryManager.isExternalStorageWritable()
                && MemoryManager.isExternalStorageReadable()) {
        // Check if Memory is equals or greater than 10mb
            if (MemoryManager.checkSdCardMemory(10)) {
                File imgdir = new File(Environment.getExternalStorageDirectory()
                        + imageDirectory);
                File file = new File(imgdir, fileName);
                // (Optional) replace file if its already existing
                if (file.exists()) file.delete();
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
                    out.flush();
                    out.close();
                    result = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                proceedToInternal = false;
            } else {
                proceedToInternal = true;
            }
        } else {
            proceedToInternal = true;
        }
        if (proceedToInternal) {
            if (MemoryManager.checkInternalMemory(10)) {
                File imgdir = new File(Environment.getDataDirectory()
                        + imageDirectory);
                File file = new File(imgdir, fileName);
                // (Optional) replace file if its already existing
                if (file.exists()) file.delete();
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
                    out.flush();
                    out.close();
                    result = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
</code>```

Here is the Memory Manager class:

```<code>public class MemoryManager {

   public static boolean checkSdCardMemory(long desiredMemory) {
      boolean result = true;

      StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
            .getPath());
      long bytesAvailable = (long) stat.getBlockSize()
            * (long) stat.getAvailableBlocks();
      long megAvailable = bytesAvailable / 1048576;

      if (megAvailable < desiredMemory) {
         result = false;
      }

      return result;
   }

   public static boolean checkInternalMemory(long desiredMemory) {
      boolean result = true;

      StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
      long bytesAvailable = (long) stat.getBlockSize()
            * (long) stat.getAvailableBlocks();
      long megAvailable = bytesAvailable / 1048576;

      if (megAvailable < desiredMemory) {
         result = false;
      }

      return result;
   }

   public static boolean isExternalStorageWritable() {
      String state = Environment.getExternalStorageState();
      if (Environment.MEDIA_MOUNTED.equals(state)) {
         return true;
      }
      return false;
   }

   /* Checks if external storage is available to at least read */
   public static boolean isExternalStorageReadable() {
      String state = Environment.getExternalStorageState();
      if (Environment.MEDIA_MOUNTED.equals(state)
            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
         return true;
      }
      return false;
   }
}
</code>```

Body:
how to use camera in app and store the taken  pic in the app..it i  referred many tutorials but i didnt get the proper code..please help me to solve the problem.My code will ask for save option...and when we reopen the app the picture is not saved neither in app nor in gallery....Please help to do that ..my code is...In this code the captured image is stored in that image view...for once

  this.imageView = (ImageView)this.findViewById(R.id.imageView1);
    Button photoButton = (Button) this.findViewById(R.id.button1);
    photoButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    }) ;
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);
    }

Body:
Here is a method to save bitmap to storage. The imageMainDirectory would look like "/MyApp/". The imageDirectory would look like "/MyApp/MyImages/"

 public boolean saveBitmapToStorage(Bitmap bitmap, String imageMainDirectory,
                                       String imageDirectory, String fileName) {
        boolean result = false;
        // This is true if the saving of image to the external storage fails.
        // Then we proceed to the internal storage
        boolean proceedToInternal;

        // You need to check if External Storage is writable/readable
        if (MemoryManager.isExternalStorageWritable()
                && MemoryManager.isExternalStorageReadable()) {
        // Check if Memory is equals or greater than 10mb
            if (MemoryManager.checkSdCardMemory(10)) {
                File imgdir = new File(Environment.getExternalStorageDirectory()
                        + imageDirectory);
                File file = new File(imgdir, fileName);
                // (Optional) replace file if its already existing
                if (file.exists()) file.delete();
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
                    out.flush();
                    out.close();
                    result = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                proceedToInternal = false;
            } else {
                proceedToInternal = true;
            }
        } else {
            proceedToInternal = true;
        }
        if (proceedToInternal) {
            if (MemoryManager.checkInternalMemory(10)) {
                File imgdir = new File(Environment.getDataDirectory()
                        + imageDirectory);
                File file = new File(imgdir, fileName);
                // (Optional) replace file if its already existing
                if (file.exists()) file.delete();
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
                    out.flush();
                    out.close();
                    result = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

Here is the Memory Manager class:

public class MemoryManager {

   public static boolean checkSdCardMemory(long desiredMemory) {
      boolean result = true;

      StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
            .getPath());
      long bytesAvailable = (long) stat.getBlockSize()
            * (long) stat.getAvailableBlocks();
      long megAvailable = bytesAvailable / 1048576;

      if (megAvailable < desiredMemory) {
         result = false;
      }

      return result;
   }

   public static boolean checkInternalMemory(long desiredMemory) {
      boolean result = true;

      StatFs stat = new StatFs(Environment.getDataDirectory().getPath());
      long bytesAvailable = (long) stat.getBlockSize()
            * (long) stat.getAvailableBlocks();
      long megAvailable = bytesAvailable / 1048576;

      if (megAvailable < desiredMemory) {
         result = false;
      }

      return result;
   }

   public static boolean isExternalStorageWritable() {
      String state = Environment.getExternalStorageState();
      if (Environment.MEDIA_MOUNTED.equals(state)) {
         return true;
      }
      return false;
   }

   /* Checks if external storage is available to at least read */
   public static boolean isExternalStorageReadable() {
      String state = Environment.getExternalStorageState();
      if (Environment.MEDIA_MOUNTED.equals(state)
            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
         return true;
      }
      return false;
   }
}


问:
How to use multiple data types within the same ADT in C?
For example, if I defined a Stack ADT in C, normally my type definition -using an array based implementation- is like this:

```<code>typedef char StackEntry;

typedef struct stack {
    int top;
    StackEntry entry[MAXSTACK];
} Stack;
</code>```

How can I make my Stack such that I can have one Stack for characters and another Stack -in the same program- that handles integers for example ?

答:
Use macros, e.g.

```<code>#define STACK_TYPE(type) struct { int top; type entry[MAXSTACK]; }
</code>```

You may well end up using macros for the stack operations such as push/pop too:

```<code>#define STACK_PUSH(stack, value) \
    do { if ( (top) < MAXSTACK ) (stack).entry[(stack).top++] = (value); } while (0)
</code>```

In most cases you wouldn't need to pass the stack type as a macro parameter, since the same syntax works for all stacks.

Sample usage:

```<code>STACK_TYPE(int) mystack = { 0 };
STACK_PUSH(mystack, 5);
</code>```

Obviously there are a lot of different ways you could do the details.

Body:
For example, if I defined a Stack ADT in C, normally my type definition -using an array based implementation- is like this:

typedef char StackEntry;

typedef struct stack {
    int top;
    StackEntry entry[MAXSTACK];
} Stack;

How can I make my Stack such that I can have one Stack for characters and another Stack -in the same program- that handles integers for example ?

Body:
Use macros, e.g.

#define STACK_TYPE(type) struct { int top; type entry[MAXSTACK]; }

You may well end up using macros for the stack operations such as push/pop too:

#define STACK_PUSH(stack, value) \
    do { if ( (top) < MAXSTACK ) (stack).entry[(stack).top++] = (value); } while (0)

In most cases you wouldn't need to pass the stack type as a macro parameter, since the same syntax works for all stacks.

Sample usage:

STACK_TYPE(int) mystack = { 0 };
STACK_PUSH(mystack, 5);

Obviously there are a lot of different ways you could do the details.


问:
JUnit Exception Testing
Edit: Not JUnit 4 available at this time.

Hi there,

I have a question about "smart" exception testing with JUnit. At this time, I do it like this:

```<code>public void testGet() {

    SoundFileManager sfm = new SoundFileManager();

        // Test adding a sound file and then getting it by id and name.
        try {
            SoundFile addedFile = sfm.addSoundfile("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
            SoundFile sf = sfm.getSoundfile(addedFile.getID());
            assertTrue(sf!=null);
            System.out.println(sf.toString());

            sf = sfm.getSoundfileByName("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
            assertTrue(sf!=null);
            System.out.println(sf.toString());
        } catch (RapsManagerException e) {
            System.out.println(e.getMessage());
        }

        // Test get with invalid id.
        try {
            sfm.getSoundfile(-100);
            fail("Should have raised a RapsManagerException");
        } catch (RapsManagerException e) {
            System.out.println(e.getMessage());
        }

        // Test get by name with invalid name
        try {
            sfm.getSoundfileByName(new String());
            fail("Should have raised a RapsManagerException");
        } catch (RapsManagerException e) {
            System.out.println(e.getMessage());
        }

    }
</code>```

As you can see, I need one try/catch block for each function that is supposed to throw an exception. It seems not to be a good way to do this - or is there no possibility to reduce the use of try/catch?

答:
In Java 8, you can use lambda expressions to get tighter control over when the exception is thrown. If you use the annotations method then you're only asserting that the exception is thrown somewhere in the test method. If you're executing more than one line of code in the test then you risk your test passing when it should fail. Java 8 solution is something like this.

```<code>static void <T extends Exception> expectException(Class<T> type, Runnable runnable) {
    try {
        runnable.run()
    } catch (Exception ex) {
        assertTrue(ex.getClass().equals(type));
        return;
    }
    assertTrue(false);
}
</code>```

Usage:

```<code>@Test
public void test()
    MyClass foo = new MyClass();
    // other setup code here ....
    expectException(MyException.class, () -> foo.bar());
}
</code>```

Title: JUnit Exception Testing

Body:
Edit: Not JUnit 4 available at this time.

Hi there,

I have a question about "smart" exception testing with JUnit. At this time, I do it like this:

public void testGet() {

    SoundFileManager sfm = new SoundFileManager();

        // Test adding a sound file and then getting it by id and name.
        try {
            SoundFile addedFile = sfm.addSoundfile("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
            SoundFile sf = sfm.getSoundfile(addedFile.getID());
            assertTrue(sf!=null);
            System.out.println(sf.toString());

            sf = sfm.getSoundfileByName("E:\\Eclipse_Prj\\pSound\\data\\Adrenaline01.wav");
            assertTrue(sf!=null);
            System.out.println(sf.toString());
        } catch (RapsManagerException e) {
            System.out.println(e.getMessage());
        }

        // Test get with invalid id.
        try {
            sfm.getSoundfile(-100);
            fail("Should have raised a RapsManagerException");
        } catch (RapsManagerException e) {
            System.out.println(e.getMessage());
        }

        // Test get by name with invalid name
        try {
            sfm.getSoundfileByName(new String());
            fail("Should have raised a RapsManagerException");
        } catch (RapsManagerException e) {
            System.out.println(e.getMessage());
        }

    }

As you can see, I need one try/catch block for each function that is supposed to throw an exception. It seems not to be a good way to do this - or is there no possibility to reduce the use of try/catch?

Body:
In Java 8, you can use lambda expressions to get tighter control over when the exception is thrown. If you use the annotations method then you're only asserting that the exception is thrown somewhere in the test method. If you're executing more than one line of code in the test then you risk your test passing when it should fail. Java 8 solution is something like this.

static void <T extends Exception> expectException(Class<T> type, Runnable runnable) {
    try {
        runnable.run()
    } catch (Exception ex) {
        assertTrue(ex.getClass().equals(type));
        return;
    }
    assertTrue(false);
}

Usage:

@Test
public void test()
    MyClass foo = new MyClass();
    // other setup code here ....
    expectException(MyException.class, () -> foo.bar());
}


问:
Databound Content Controls not Updating in Word Online
I have some content controls data-bound to custom XML parts in my document. I use my Office JS add-in in Word to update the custom XML parts.

In Word 2016 for Windows, the content controls refresh and contain the updated values from the custom XML parts.

However, in Word Online, even though the custom XML parts are updated, the content controls remain unchanged.

What am I doing wrong?

EDIT: The new viewer now displays the document correctly. Leaving the below for posterity / future me.

I think it's telling that the new viewer fails to show content controls correctly:

There has still not been any official word yet on this, though. Relevant links:

Office Developer Platform UserVoice suggestion

Microsoft Answers forum post

答: Currently, this feature is not supported in Word Online.</p>


问:
Prevent local changes getting pushed in Git
I have cloned a repository and the master branch in my repo is tracking origin/master. I created a work branch and changed some config files specific to my dev machine to make the app work.

My normal workflow will be to switch to master branch, merge changes made in work branch and push those changes upstream. The problem is that i don't want my specific chnages to get pushed. When i merge my work branch into master those changes are merged also.

The only solution I've found so far is not to commit those changes in work but that's not a satisfactory solution.

答:
What you need is a .gitignore file and add all your config file inside the .gitignore file.

Once your .gitignore file is ready you might need to removed your config files from the Cache

Here's the command:

```<code>(Assume you use linux)
vi .gitignore
//Add all your config file inside

//run the following command to remove your config file from GIT cache if your config files is already track by GIT

git rm --cached myconfig.php
</code>```

Body:
What you need is a .gitignore file and add all your config file inside the .gitignore file.

Once your .gitignore file is ready you might need to removed your config files from the Cache

Here's the command:

(Assume you use linux)
vi .gitignore
//Add all your config file inside

//run the following command to remove your config file from GIT cache if your config files is already track by GIT

git rm --cached myconfig.php


问:
Java KeyStore jks as certificate authority
I'm converting an old app that uses openssl to Java.  I was wondering if there was any downside in using Java's KeyStore as a certificate authority. Like is there any performance loss in using Java's Keystore or any limit on the number of clients' certs that I can store in a Java Keystore?  I want to eventually implement 2 way SSL where the client authenticates and the server knows which clients are allowed to talk to it. </p>

答:
I was wondering if there was any downside in using Java's KeyStore as a certificate authority.

You're not using it as a certificate authority. A Certificate Authority is a trusted entity - a company - that signs certificates. A keystore is a file that stores public/private key pairs, signed certificates, and trusted certificates. Don't misuse terminology.

Like is there any performance loss in using Java's Keystore

Compared to what? It's a pretty pointless question when the only alternative is a PKCS#12 keystore, which is also a file, and when both are loaded into memory, and when the performance characteristics of either aren't rate-determining steps in the first place.

or any limit on the number of clients' certs that I can store in a Java Keystore?

No.


问:
preg_match user validation
Im trying to make a preg_match rule for user validation

to only allow a-z - A-Z - 0-9
and the characters _-=?!@:.,
without spaces

I already tried a lot of combinations but no one seems to work

This is what im trying to get:

```<code>    if(preg_match('idk what to use here', 'Myusername@123?')) {
        return true;
    }

    if(preg_match('idk what to use here', '$Hello')) {
        return false;
    }

    if(preg_match('idk what to use here', 'Hello 123')) {
        return false;
    }
</code>```

Anyone knows the regex for this?
Thanks :)

答:
Use a class, but make sure to either escape the hyphen or put it as the last character, otherwise it signifies a range. Use ^ and $ to require that all input characters match the pattern:

```<code>$regex = "/^[A-Za-z0-9_=?!@:.,-]*$/";

var_dump(preg_match($regex, 'Myusername@123?'));
var_dump(preg_match($regex, '$Hello'));
var_dump(preg_match($regex, 'Hello 123'));
</code>```

Title: preg_match user validation

Body:
Im trying to make a preg_match rule for user validation

to only allow a-z - A-Z - 0-9
and the characters _-=?!@:.,
without spaces

I already tried a lot of combinations but no one seems to work

This is what im trying to get:

    if(preg_match('idk what to use here', 'Myusername@123?')) {
        return true;
    }

    if(preg_match('idk what to use here', '$Hello')) {
        return false;
    }

    if(preg_match('idk what to use here', 'Hello 123')) {
        return false;
    }

Anyone knows the regex for this?
Thanks :)

Body:
Use a class, but make sure to either escape the hyphen or put it as the last character, otherwise it signifies a range. Use ^ and $ to require that all input characters match the pattern:

$regex = "/^[A-Za-z0-9_=?!@:.,-]*$/";

var_dump(preg_match($regex, 'Myusername@123?'));
var_dump(preg_match($regex, '$Hello'));
var_dump(preg_match($regex, 'Hello 123'));


问:
Likens the background color of the label and the sheet column
How to write code for the background color of a label with the color source of the color cells. for example:</p>

```<code>Cmb.backcolor=sheets("sheet1").cells(2,2)
</code>```

答:
If you are interested in using cell object, then you can try -
'Using Cell Object
Cells(3, 2).Interior.ColorIndex = 5 ' 5 indicates Blue Color

Alternatively, if you are familiar with Range object, then you can try -
'Using Range Object
Range("B3").Interior.ColorIndex = 5

You can also write the same code using RGB as follows :
'Using Cell Object
Cells(3, 2).Interior.Color = RGB(0, 0, 250)
'Using Range Object
Range("B3").Interior.Color = RGB(0, 0, 250)

Hope you find this Helpful.

Body:
How to write code for the background color of a label with the color source of the color cells. for example:

Cmb.backcolor=sheets("sheet1").cells(2,2)


问:
TypeError: "this..." is not a function
I define hostService as follows. The senario is I call first hostService.addListener() in the controller, then the controller may emit a message by $rootSceop.$emit, hostService is supposed to handle it.

```<code>app.service('hostService', ['$rootScope', function ($rootScope) {
    this.button = function () {
        Office.context.ui.displayDialogAsync("https://www.google.com", {}, function () {});
    }

    this.addListener = function () {
        $rootScope.$on("message", function (event, data) {
            this.button()
        })
    }
</code>```

However, the problem is the above code raises an error:

```<code>TypeError: this.button is not a function
</code>```

Does anyone know how to fix it?

答:
I solve this creating a self variable with this object, then you can call it from diferent scope:

```<code>app.service('hostService', ['$rootScope', function ($rootScope) {

    var self = this

    this.button = function () {
        Office.context.ui.displayDialogAsync("https://www.google.com", {}, function () {});
    }

    this.addListener = function () {
        $rootScope.$on("message", function (event, data) {
            self.button()
        })
    }
</code>```

Title: TypeError: "this..." is not a function

Body:
I define hostService as follows. The senario is I call first hostService.addListener() in the controller, then the controller may emit a message by $rootSceop.$emit, hostService is supposed to handle it.

app.service('hostService', ['$rootScope', function ($rootScope) {
    this.button = function () {
        Office.context.ui.displayDialogAsync("https://www.google.com", {}, function () {});
    }

    this.addListener = function () {
        $rootScope.$on("message", function (event, data) {
            this.button()
        })
    }

However, the problem is the above code raises an error:

TypeError: this.button is not a function

Does anyone know how to fix it?

Body:
I solve this creating a self variable with this object, then you can call it from diferent scope:

app.service('hostService', ['$rootScope', function ($rootScope) {

    var self = this

    this.button = function () {
        Office.context.ui.displayDialogAsync("https://www.google.com", {}, function () {});
    }

    this.addListener = function () {
        $rootScope.$on("message", function (event, data) {
            self.button()
        })
    }


问:
how to clone a project on heroku
I have a project on heroku working fine.  Now I want to create same project with different url (same code) as the one I have working now.  So that I can give the new url to the customer as a 'test' site.  I know in heroku i can just rename the url but I want to completely separate development from test (database wise).

What is the best solution? Do I start from scratch? cd into new folder on my machine...clone project from github...make new database -test ...push to heroku...etc. etc.

答:
You should check out heroku_san, I designed it specifically for deploying multiple environments to Heroku easily. It also has grown to include a lot of other niceties you'll need to automate when dealing with multiple "apps" like sharing and auto migrating with restarts.

Once you have it setup it's as simple as:

```<code>rake production deploy
</code>```

Title: how to clone a project on heroku

Body:
You should check out heroku_san, I designed it specifically for deploying multiple environments to Heroku easily. It also has grown to include a lot of other niceties you'll need to automate when dealing with multiple "apps" like sharing and auto migrating with restarts.

Once you have it setup it's as simple as:

rake production deploy


问:
How to use different types of References and populate
So i have two schemas, Article and Event
Both have an image field.

For Article,

```<code>featured_image: {
    type: String,
    default: '',
}
</code>```

For Event,

```<code>featured_image: {
    type: Schema.ObjectId,
    ref: 'Medium'
}
</code>```

I have another schema, Card, like this

```<code> type: {
    type: String,
    enum: ['Article', 'Event']
 },
 data: {
    type: Schema.ObjectId,
    refPath: 'type'
 }
</code>```

I am trying to populate the cards, like this

```<code>Card
    .find(query)
    .populate({
            path: 'data',
            populate: [{
                path: 'featured_image',
                model: 'Medium',
                select: 'source type'
            }]
    };)
</code>```

However, it keeps giving me a cast error, because when card is of type Event, it populates fine, but when it's of type 'Article', featured_image field is of string type and hence cannot be populated.

How do i populate featured_image field only if card is of type Event or it's a reference id, instead of string.

答:
Instead of what you are attempting to do you should be using "discriminators", which is in fact the correct way to handle a relationship where the object types vary in the reference given.

You use discriminators by the different way in which you define the model, which instead constructs from a "base model" and schema as in:

```<code>const contentSchema = new Schema({
  name: String
});

const articleSchema = new Schema({
  image: String,
});

const eventSchema = new Schema({
  image: { type: Schema.Types.ObjectId, ref: 'Medium' }
});

const cardSchema = new Schema({
  name: String,
  data: { type: Schema.Types.ObjectId, ref: 'Content' }
});

const Medium = mongoose.model('Medium', mediumSchema);
const Card = mongoose.model('Card', cardSchema )

const Content = mongoose.model('Content', contentSchema);
const Article = Content.discriminator('Article', articleSchema);
const Event = Content.discriminator('Event', eventSchema);
</code>```

So instead you define a "base model" such as Content here which you actually point the references to within Event.

The next part is that the differing schema are actually registered to this model via the .discriminator() method from the base model, as opposed to the .model() method. This registers the schema with the general Content model in such a way that when you refer to any model instance defined with .discriminator() that a special __t field is implied to exist in that data, using the registered model name.

Aside from enabling mongoose to .populate() on different types, this also has the advantage of being a "full schema" attached to the different types of items. So you have have different validation and other methods as well if you like. It is indeed "polymorphism" at work in a database context, with helpful schema objects attached.

Therefore we can demonstrate both the varied "joins" that are done, as well as that you can now both use the individual models for Article and Event which would deal with only those items in all queries and operations. And not only can you use "individually", but since the mechanism for this actually stores the data in the same collection, there is also a Content model which gives access to both these types. Which is in essence how the main relation works in the definition to the Event schema.

As a full listing

```<code>const async = require('async'),
      mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.set('debug',true);
mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost/cards');

const mediumSchema = new Schema({
  title: String
});

const contentSchema = new Schema({
  name: String
});

const articleSchema = new Schema({
  image: String,
});

const eventSchema = new Schema({
  image: { type: Schema.Types.ObjectId, ref: 'Medium' }
});

const cardSchema = new Schema({
  name: String,
  data: { type: Schema.Types.ObjectId, ref: 'Content' }
});

const Medium = mongoose.model('Medium', mediumSchema);
const Card = mongoose.model('Card', cardSchema )

const Content = mongoose.model('Content', contentSchema);
const Article = Content.discriminator('Article', articleSchema);
const Event = Content.discriminator('Event', eventSchema);

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

async.series(
  [
    // Clean data
    (callback) =>
      async.each(mongoose.models,(model,callback) =>
        model.remove({},callback),callback),

    // Insert some data
    (callback) =>
      async.waterfall(
        [
          (callback) =>
            Medium.create({ title: 'An Image' },callback),

          (medium,callback) =>
            Content.create(
              [
                { name: "An Event", image: medium, __t: 'Event' },
                { name: "An Article", image: "A String", __t: 'Article' }
              ],
              callback
            ),

          (content,callback) =>
            Card.create(
              [
                { name: 'Card 1', data: content[0] },
                { name: 'Card 2', data: content[1] }
              ],
              callback
            )
        ],
        callback
      ),

    // Query and populate
    (callback) =>
      Card.find()
        .populate({
          path: 'data',
          populate: [{
            path: 'image'
          }]
        })
        .exec((err,cards) => {
        if (err) callback(err);
        log(cards);
        callback();
      }),

    // Query on the model for the discriminator
    (callback) =>
      Article.findOne({},(err,article) => {
        if (err) callback(err);
        log(article);
        callback();
      }),

    // Query on the general Content model
    (callback) =>
      Content.find({},(err,contents) => {
        if (err) callback(err);
        log(contents);
        callback();
      }),

  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
);
</code>```

And the sample output for different queries

```<code>Mongoose: cards.find({}, { fields: {} })
Mongoose: contents.find({ _id: { '$in': [ ObjectId("595ef117175f6850dcf657d7"), ObjectId("595ef117175f6850dcf657d6") ] } }, { fields: {} })
Mongoose: media.find({ _id: { '$in': [ ObjectId("595ef117175f6850dcf657d5") ] } }, { fields: {} })
[
  {
    "_id": "595ef117175f6850dcf657d9",
    "name": "Card 2",
    "data": {
      "_id": "595ef117175f6850dcf657d7",
      "name": "An Article",
      "image": "A String",
      "__v": 0,
      "__t": "Article"
    },
    "__v": 0
  },
  {
    "_id": "595ef117175f6850dcf657d8",
    "name": "Card 1",
    "data": {
      "_id": "595ef117175f6850dcf657d6",
      "name": "An Event",
      "image": {
        "_id": "595ef117175f6850dcf657d5",
        "title": "An Image",
        "__v": 0
      },
      "__v": 0,
      "__t": "Event"
    },
    "__v": 0
  }
]
Mongoose: contents.findOne({ __t: 'Article' }, { fields: {} })
{
  "_id": "595ef117175f6850dcf657d7",
  "name": "An Article",
  "image": "A String",
  "__v": 0,
  "__t": "Article"
}
Mongoose: contents.find({}, { fields: {} })
[
  {
    "_id": "595ef117175f6850dcf657d6",
    "name": "An Event",
    "image": "595ef117175f6850dcf657d5",
    "__v": 0,
    "__t": "Event"
  },
  {
    "_id": "595ef117175f6850dcf657d7",
    "name": "An Article",
    "image": "A String",
    "__v": 0,
    "__t": "Article"
  }
]
</code>```

Body:
So i have two schemas, Article and Event
Both have an image field.

For Article,

featured_image: {
    type: String,
    default: '',
}

For Event,

featured_image: {
    type: Schema.ObjectId,
    ref: 'Medium'
}

I have another schema, Card, like this

 type: {
    type: String,
    enum: ['Article', 'Event']
 },
 data: {
    type: Schema.ObjectId,
    refPath: 'type'
 }

I am trying to populate the cards, like this

Card
    .find(query)
    .populate({
            path: 'data',
            populate: [{
                path: 'featured_image',
                model: 'Medium',
                select: 'source type'
            }]
    };)

However, it keeps giving me a cast error, because when card is of type Event, it populates fine, but when it's of type 'Article', featured_image field is of string type and hence cannot be populated.

How do i populate featured_image field only if card is of type Event or it's a reference id, instead of string.

Body:
Instead of what you are attempting to do you should be using "discriminators", which is in fact the correct way to handle a relationship where the object types vary in the reference given.

You use discriminators by the different way in which you define the model, which instead constructs from a "base model" and schema as in:

const contentSchema = new Schema({
  name: String
});

const articleSchema = new Schema({
  image: String,
});

const eventSchema = new Schema({
  image: { type: Schema.Types.ObjectId, ref: 'Medium' }
});

const cardSchema = new Schema({
  name: String,
  data: { type: Schema.Types.ObjectId, ref: 'Content' }
});

const Medium = mongoose.model('Medium', mediumSchema);
const Card = mongoose.model('Card', cardSchema )

const Content = mongoose.model('Content', contentSchema);
const Article = Content.discriminator('Article', articleSchema);
const Event = Content.discriminator('Event', eventSchema);

So instead you define a "base model" such as Content here which you actually point the references to within Event.

The next part is that the differing schema are actually registered to this model via the .discriminator() method from the base model, as opposed to the .model() method. This registers the schema with the general Content model in such a way that when you refer to any model instance defined with .discriminator() that a special __t field is implied to exist in that data, using the registered model name.

Aside from enabling mongoose to .populate() on different types, this also has the advantage of being a "full schema" attached to the different types of items. So you have have different validation and other methods as well if you like. It is indeed "polymorphism" at work in a database context, with helpful schema objects attached.

Therefore we can demonstrate both the varied "joins" that are done, as well as that you can now both use the individual models for Article and Event which would deal with only those items in all queries and operations. And not only can you use "individually", but since the mechanism for this actually stores the data in the same collection, there is also a Content model which gives access to both these types. Which is in essence how the main relation works in the definition to the Event schema.

As a full listing

const async = require('async'),
      mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.set('debug',true);
mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost/cards');

const mediumSchema = new Schema({
  title: String
});

const contentSchema = new Schema({
  name: String
});

const articleSchema = new Schema({
  image: String,
});

const eventSchema = new Schema({
  image: { type: Schema.Types.ObjectId, ref: 'Medium' }
});

const cardSchema = new Schema({
  name: String,
  data: { type: Schema.Types.ObjectId, ref: 'Content' }
});

const Medium = mongoose.model('Medium', mediumSchema);
const Card = mongoose.model('Card', cardSchema )

const Content = mongoose.model('Content', contentSchema);
const Article = Content.discriminator('Article', articleSchema);
const Event = Content.discriminator('Event', eventSchema);

function log(data) {
  console.log(JSON.stringify(data, undefined, 2))
}

async.series(
  [
    // Clean data
    (callback) =>
      async.each(mongoose.models,(model,callback) =>
        model.remove({},callback),callback),

    // Insert some data
    (callback) =>
      async.waterfall(
        [
          (callback) =>
            Medium.create({ title: 'An Image' },callback),

          (medium,callback) =>
            Content.create(
              [
                { name: "An Event", image: medium, __t: 'Event' },
                { name: "An Article", image: "A String", __t: 'Article' }
              ],
              callback
            ),

          (content,callback) =>
            Card.create(
              [
                { name: 'Card 1', data: content[0] },
                { name: 'Card 2', data: content[1] }
              ],
              callback
            )
        ],
        callback
      ),

    // Query and populate
    (callback) =>
      Card.find()
        .populate({
          path: 'data',
          populate: [{
            path: 'image'
          }]
        })
        .exec((err,cards) => {
        if (err) callback(err);
        log(cards);
        callback();
      }),

    // Query on the model for the discriminator
    (callback) =>
      Article.findOne({},(err,article) => {
        if (err) callback(err);
        log(article);
        callback();
      }),

    // Query on the general Content model
    (callback) =>
      Content.find({},(err,contents) => {
        if (err) callback(err);
        log(contents);
        callback();
      }),

  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
);

And the sample output for different queries

Mongoose: cards.find({}, { fields: {} })
Mongoose: contents.find({ _id: { '$in': [ ObjectId("595ef117175f6850dcf657d7"), ObjectId("595ef117175f6850dcf657d6") ] } }, { fields: {} })
Mongoose: media.find({ _id: { '$in': [ ObjectId("595ef117175f6850dcf657d5") ] } }, { fields: {} })
[
  {
    "_id": "595ef117175f6850dcf657d9",
    "name": "Card 2",
    "data": {
      "_id": "595ef117175f6850dcf657d7",
      "name": "An Article",
      "image": "A String",
      "__v": 0,
      "__t": "Article"
    },
    "__v": 0
  },
  {
    "_id": "595ef117175f6850dcf657d8",
    "name": "Card 1",
    "data": {
      "_id": "595ef117175f6850dcf657d6",
      "name": "An Event",
      "image": {
        "_id": "595ef117175f6850dcf657d5",
        "title": "An Image",
        "__v": 0
      },
      "__v": 0,
      "__t": "Event"
    },
    "__v": 0
  }
]
Mongoose: contents.findOne({ __t: 'Article' }, { fields: {} })
{
  "_id": "595ef117175f6850dcf657d7",
  "name": "An Article",
  "image": "A String",
  "__v": 0,
  "__t": "Article"
}
Mongoose: contents.find({}, { fields: {} })
[
  {
    "_id": "595ef117175f6850dcf657d6",
    "name": "An Event",
    "image": "595ef117175f6850dcf657d5",
    "__v": 0,
    "__t": "Event"
  },
  {
    "_id": "595ef117175f6850dcf657d7",
    "name": "An Article",
    "image": "A String",
    "__v": 0,
    "__t": "Article"
  }
]


问:
Uncaught SyntaxError: Invalid or unexpected token script.js:
I have a JSON file below that I saved as flipkart.json:

```<code>flipkart = '[{
       "signup1":
        {
                "firstname":  "ravi",
                "lastname" :  "kota",
                "mobileno" :   9555558039,
                "DOB"      :  "19-Mar-1980",
                "emailid"  :  "kota.raavi@gmail.com",
                "password" :  "password"
           }}]';
</code>```

And I wrote a Javascript file as can be seen below, which I saved as script.js:

```<code>function load()
{
  var mydata = JSON.parse(flipkart);
  //alert(mydata[0].firstname);
  //alert(mydata[0].lastname);
  alert(ravikota);

 }
</code>```

And my HTML code is:

```<code><html>
 <head>
    <title>askyb - Load JSON File Locally by Javascript Without
    JQuery</title>
    <script type="text/javascript" src="C:\Users\Kota
      Ravi\Desktop\rainbow\flipkart.json"></script>
    <script type="text/javascript" src="C:\Users\Kota
   Ravi\Desktop\rainbow\script.js"></script>
   </head>
    <body onload="load()">
    askyb - Load JSON File Locally by Javascript Without JQuery
   </body>
</html>
</code>```

When i am trying to open the html file in the same directory, the console of HTML gives the error as:

```<code>Uncaught SyntaxError: Invalid or unexpected token
    script.js:3 Uncaught ReferenceError: flipkart is not defined
    at load (script.js:3)
    at onload (rainbow.html:7)
</code>```

I would like to know why my flipkart.json file is not being identified by the console. Thank you.

答:
Your JSON is invalid and if you want to include it without using Javascript, then you're technically just creating a file with an array of objects inside of it. JSON files cannot be included in the page like scripts and then be referenced as you're trying to accomplish.

Also, if you were to create it as valid JSON it would have to look more like this. But in your case, this won't solve the problem.

```<code>[
  {
    "signup1": {
      "firstname": "ravi",
      "lastname": "kota",
      "mobileno": 9555558039,
      "DOB": "19-Mar-1980",
      "emailid": "kota.raavi@gmail.com",
      "password": "password"
    }
  }
]
</code>```

Let's fix up your code. Firstly, rename flipkart.json to flipkart.js and change the script include in your HTML to include it first:

```<code>flipkart = [{
       "signup1":
        {
                "firstname":  "ravi",
                "lastname" :  "kota",
                "mobileno" :   9555558039,
                "DOB"      :  "19-Mar-1980",
                "emailid"  :  "kota.raavi@gmail.com",
                "password" :  "password"
           }}];
</code>```

This will create a global variable called flipkart which can be accessed from other scripts and anywhere in your page. I recommend reading up on the downsides of global variables, your approach while it will work is flawed.

Inside of it, we are creating an array and populating it with an object. This is just a standard array and Javascript object, it's not JSON.

Then finally, inside of script.js replace this line var mydata = JSON.parse(flipkart); with var mydata = flipkart; or better yet, just reference flipkart directly without creating a mydata variable in your script.

Body:
I have a JSON file below that I saved as flipkart.json:

flipkart = '[{
       "signup1":
        {
                "firstname":  "ravi",
                "lastname" :  "kota",
                "mobileno" :   9555558039,
                "DOB"      :  "19-Mar-1980",
                "emailid"  :  "kota.raavi@gmail.com",
                "password" :  "password"
           }}]';

And I wrote a Javascript file as can be seen below, which I saved as script.js:

function load()
{
  var mydata = JSON.parse(flipkart);
  //alert(mydata[0].firstname);
  //alert(mydata[0].lastname);
  alert(ravikota);

 }

And my HTML code is:

    <title>askyb - Load JSON File Locally by Javascript Without
    JQuery</title>

    askyb - Load JSON File Locally by Javascript Without JQuery

When i am trying to open the html file in the same directory, the console of HTML gives the error as:

Uncaught SyntaxError: Invalid or unexpected token
    script.js:3 Uncaught ReferenceError: flipkart is not defined
    at load (script.js:3)
    at onload (rainbow.html:7)

I would like to know why my flipkart.json file is not being identified by the console. Thank you.

Body:
Your JSON is invalid and if you want to include it without using Javascript, then you're technically just creating a file with an array of objects inside of it. JSON files cannot be included in the page like scripts and then be referenced as you're trying to accomplish.

Also, if you were to create it as valid JSON it would have to look more like this. But in your case, this won't solve the problem.

[
  {
    "signup1": {
      "firstname": "ravi",
      "lastname": "kota",
      "mobileno": 9555558039,
      "DOB": "19-Mar-1980",
      "emailid": "kota.raavi@gmail.com",
      "password": "password"
    }
  }
]

Let's fix up your code. Firstly, rename flipkart.json to flipkart.js and change the script include in your HTML to include it first:

flipkart = [{
       "signup1":
        {
                "firstname":  "ravi",
                "lastname" :  "kota",
                "mobileno" :   9555558039,
                "DOB"      :  "19-Mar-1980",
                "emailid"  :  "kota.raavi@gmail.com",
                "password" :  "password"
           }}];

This will create a global variable called flipkart which can be accessed from other scripts and anywhere in your page. I recommend reading up on the downsides of global variables, your approach while it will work is flawed.

Inside of it, we are creating an array and populating it with an object. This is just a standard array and Javascript object, it's not JSON.

Then finally, inside of script.js replace this line var mydata = JSON.parse(flipkart); with var mydata = flipkart; or better yet, just reference flipkart directly without creating a mydata variable in your script.


问:
How to draw a sector in openlayers?
I try to use ol.style.RegularShape, but it can only draw triangles and squares.

```<code> image: new ol.style.RegularShape({
     radius: radius,
     angle: 90,
     stroke: new ol.style.Stroke({
         color: color
     }),
     fill: new ol.style.Fill({
         color: color
     }),
     points: 3,
     rotation: 0.6
 })
</code>```

How can I solve it?
like
enter image description here

答:
You can use ol.geom.Polygon. put the coordinates of the polygon that you want to draw. If you want to draw the polygon by click, use ol.interaction.draw with type: 'Polygon'

draw sample here

Title: How to draw a sector in openlayers?

Body:
I try to use ol.style.RegularShape, but it can only draw triangles and squares.

 image: new ol.style.RegularShape({
     radius: radius,
     angle: 90,
     stroke: new ol.style.Stroke({
         color: color
     }),
     fill: new ol.style.Fill({
         color: color
     }),
     points: 3,
     rotation: 0.6
 })

How can I solve it?
like
enter image description here


问:
JPA one to one bidirectional mapping is not working
I have the below Employees and Departments classes, when I do a uni directional one to one mapping from employees to departments class its working fine , I am getting the employee details along with the department detail

```<code>@Entity
@Table(name="EMPLOYEES")
public class Employees implements Serializable {

@Id
@Column(name="EMPLOYEE_ID")
private Integer employee_id;

@Column(name="FIRST_NAME")
private String first_name;

@Column(name="LAST_NAME")
private String last_name;

@Column(name="EMAIL")
private String email;

@Column(name="PHONE_NUMBER")
private String phone_number;

@Column(name="HIRE_DATE")
private Date hire_date;

@Column(name="JOB_ID")
private String job_id;

@Column(name="SALARY")
private double salary;

@Column(name="COMMISSION_PCT")
private String commission_pct;

@Column(name="MANAGER_ID")
private String manager_id;

@OneToOne
@JoinColumn(name="department_id")
private Departments departments;

}
</code>```

for the above mapping I am getting the result properly, but when I put the bi directional mapping in Departments class as below, getting error  while accessing the employees

```<code>@Entity
@Table(name="DEPARTMENTS")
public class Departments {
@Id
@Column(name="DEPARTMENT_ID")
private Integer department_id;

@Column(name="DEPARTMENT_NAME")
 private String department_name;

@Column(name="MANAGER_ID")
 private String manager_id;

@Column(name="LOCATION_ID")
 private String location_id;

@OneToOne(mappedBy="departments")
private Employees employees;

public Employees getEmployees() {
    return employees;
}

}

    org.hibernate.event.internal.DefaultLoadEventListener doOnLoad
INFO: HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 90, for class: com.example.demo.entity.Employees
</code>```

Below is the code accessing the employees

```<code>@RequestMapping(value="/getEmployees",method=RequestMethod.GET)
public ResponseEntity<List<Employees>> getEmployees(){
    System.out.println("Employees are ");
    List<Employees> employees =(List<Employees>) employeeRepo.findOne(new Integer(100));
    //System.out.println(employees.getDepartments());
    return new ResponseEntity(employees,HttpStatus.OK);

}
</code>```

similarly below is the code for retreiving the departments which is giving the same result (recursive results ) multiple times with the bidirectional mapping

code for accessing the departments

```<code>@RequestMapping(value="/getDepartments",method=RequestMethod.GET)
    public ResponseEntity<Departments> getDepartments(){
        System.out.println("Departments are ");
        Departments dept = (Departments) departmentRepo.findOne(new Integer(10));

        return new ResponseEntity(dept,HttpStatus.OK);

    }
</code>```

Please someone help me on this ?

答: You're not using the right mapping.  While it may be true that each employee has just 1 department, each department presumably has more than 1 employee.  Thus the error you see on the query.  It's expecting just 1 employee, but got multiple.</p>

Body:
I have the below Employees and Departments classes, when I do a uni directional one to one mapping from employees to departments class its working fine , I am getting the employee details along with the department detail

@Entity
@Table(name="EMPLOYEES")
public class Employees implements Serializable {

@Id
@Column(name="EMPLOYEE_ID")
private Integer employee_id;

@Column(name="FIRST_NAME")
private String first_name;

@Column(name="LAST_NAME")
private String last_name;

@Column(name="EMAIL")
private String email;

@Column(name="PHONE_NUMBER")
private String phone_number;

@Column(name="HIRE_DATE")
private Date hire_date;

@Column(name="JOB_ID")
private String job_id;

@Column(name="SALARY")
private double salary;

@Column(name="COMMISSION_PCT")
private String commission_pct;

@Column(name="MANAGER_ID")
private String manager_id;

@OneToOne
@JoinColumn(name="department_id")
private Departments departments;

}

for the above mapping I am getting the result properly, but when I put the bi directional mapping in Departments class as below, getting error  while accessing the employees

@Entity
@Table(name="DEPARTMENTS")
public class Departments {
@Id
@Column(name="DEPARTMENT_ID")
private Integer department_id;

@Column(name="DEPARTMENT_NAME")
 private String department_name;

@Column(name="MANAGER_ID")
 private String manager_id;

@Column(name="LOCATION_ID")
 private String location_id;

@OneToOne(mappedBy="departments")
private Employees employees;

public Employees getEmployees() {
    return employees;
}

}

    org.hibernate.event.internal.DefaultLoadEventListener doOnLoad
INFO: HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 90, for class: com.example.demo.entity.Employees

Below is the code accessing the employees

@RequestMapping(value="/getEmployees",method=RequestMethod.GET)
public ResponseEntity<List<Employees>> getEmployees(){
    System.out.println("Employees are ");
    List<Employees> employees =(List<Employees>) employeeRepo.findOne(new Integer(100));
    //System.out.println(employees.getDepartments());
    return new ResponseEntity(employees,HttpStatus.OK);

}

similarly below is the code for retreiving the departments which is giving the same result (recursive results ) multiple times with the bidirectional mapping

code for accessing the departments

@RequestMapping(value="/getDepartments",method=RequestMethod.GET)
    public ResponseEntity<Departments> getDepartments(){
        System.out.println("Departments are ");
        Departments dept = (Departments) departmentRepo.findOne(new Integer(10));

        return new ResponseEntity(dept,HttpStatus.OK);

    }

Please someone help me on this ?


问:
ASP.NET C# How to hide and display particular field inside Repeater? (if statement)
Needed some help here,
So I am using repeater and retrieve some data from DB then put into the repeater, the thing is that for certain data value I would like to display it differently in the HTML, basically do IF checking inside Repeater to determine which HTML code to use, can someone help me with that?

I have two different codes

```<code><div class="message-data">
  <span class="message-data-name"><i class="fa fa-circle you"></i> You</span>
</div>
<div class="message you-message">
A new client?!?! I would love to help them, but where are we going to find the time?
</code>```

and

```<code> <li class="clearfix">
    <div class="message-data align-right">
      <span class="message-data-name">Ada, your OperationsAlly</span> <i class="fa fa-circle me"></i>
    </div>
    <div class="message me-message float-right"> We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>
  </li>
</code>```

As you can see, how do I put IF statement, for the first one like if (username == "You") and second one if (Username != "You"). Assume that the DB I retrieve has attribute named "Username"

Thanks

答:
It honestly is going to depend on how you retrieve your data.

You can always create a function and pass the value form your database to the function and have the function return the correct html.

```<code><%#GetHtmlForUserName(Eval("Username"))%>
</code>```

The in your function, perhaps in your code behind:

```<code>protected string GetHtmlForUserName(string userName)
    {
        if (userName == "You")
        {
            return "<div class='message-data'>\n" +
                    "  <span class='message-data-name'><i class='fa fa-circle you'></i> You</span>\n" +
                    "</div>\n" +
                    "<div class='message you-message'>\n" +
                    "A new client?!?! I would love to help them, but where are we going to find the time?";
        }
        else
        {
            return "<li class='clearfix'>\n" +
                    "    <div class='message-data align-right'>\n" +
                    "      <span class='message-data-name'>Ada, your OperationsAlly</span> <i class='fa fa-circle me'></i>\n" +
                    "    </div>\n" +
                    "    <div class='message me-message float-right'> We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>\n" +
                    "  </li>\n";

        }
    }
</code>```

The best approach is to load a custom control that displays the text based on the user name but that is a more advanced topic.

Body:
Needed some help here,
So I am using repeater and retrieve some data from DB then put into the repeater, the thing is that for certain data value I would like to display it differently in the HTML, basically do IF checking inside Repeater to determine which HTML code to use, can someone help me with that?

I have two different codes

   You

A new client?!?! I would love to help them, but where are we going to find the time?

and

      Ada, your OperationsAlly

 We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.

As you can see, how do I put IF statement, for the first one like if (username == "You") and second one if (Username != "You"). Assume that the DB I retrieve has attribute named "Username"

Thanks

Body:
It honestly is going to depend on how you retrieve your data.

You can always create a function and pass the value form your database to the function and have the function return the correct html.

<%#GetHtmlForUserName(Eval("Username"))%>

The in your function, perhaps in your code behind:

protected string GetHtmlForUserName(string userName)
    {
        if (userName == "You")
        {
            return "<div class='message-data'>\n" +
                    "  <span class='message-data-name'><i class='fa fa-circle you'></i> You</span>\n" +
                    "</div>\n" +
                    "<div class='message you-message'>\n" +
                    "A new client?!?! I would love to help them, but where are we going to find the time?";
        }
        else
        {
            return "<li class='clearfix'>\n" +
                    "    <div class='message-data align-right'>\n" +
                    "      <span class='message-data-name'>Ada, your OperationsAlly</span> <i class='fa fa-circle me'></i>\n" +
                    "    </div>\n" +
                    "    <div class='message me-message float-right'> We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>\n" +
                    "  </li>\n";

        }
    }

The best approach is to load a custom control that displays the text based on the user name but that is a more advanced topic.


问:
React + Redux: how to force Loading element to exist at least 0.5 seconds
Let's say it's common for my app to have such component:

```<code>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Loading from './Loading'

export default class Form extends Component {
  componentWillMount () {
    const { propogateValues, isFetching, fetchPath } = this.props
    console.log(this.props)
    if (isFetching) {
      propogateValues(fetchPath)
    }
  }
  render () {
    const { handleSubmit, path, successPush, isFetching } = this.props
    if (isFetching) {
      return (<div> <Loading /></div>)
    } else {
      return (
        <form onSubmit={(e) => { handleSubmit(e, path, successPush) }}>
          {this.props.children}
        </form>
      )
    }
  }
}
</code>```

Where Loading is pure presentational component representing loading animation.

Issue: when receive action is dispatched and component receives new  isFetching: false prop, it rerenders component. However, from interface perspective, I would like Loading to exist at least some time (.5 second), because very fast switch makes it looks worse than without such component at all.

Not sure how to implement it, should I really use redux store here or there is better approach?

答:
Adding react-delay component should help create the effect.

```<code><div>
  <Delay wait={500}>
    <Loading />
  </Delay>
</div>
</code>```

The source code for Delay is quite simple to understand.

Body:
Let's say it's common for my app to have such component:

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Loading from './Loading'

export default class Form extends Component {
  componentWillMount () {
    const { propogateValues, isFetching, fetchPath } = this.props
    console.log(this.props)
    if (isFetching) {
      propogateValues(fetchPath)
    }
  }
  render () {
    const { handleSubmit, path, successPush, isFetching } = this.props
    if (isFetching) {
      return (
 <Loading />
)
    } else {
      return (
        <form onSubmit={(e) => { handleSubmit(e, path, successPush) }}>
          {this.props.children}
        </form>
      )
    }
  }
}

Where Loading is pure presentational component representing loading animation.

Issue: when receive action is dispatched and component receives new  isFetching: false prop, it rerenders component. However, from interface perspective, I would like Loading to exist at least some time (.5 second), because very fast switch makes it looks worse than without such component at all.

Not sure how to implement it, should I really use redux store here or there is better approach?

Body:
Adding react-delay component should help create the effect.

<div>
  <Delay wait={500}>
    <Loading />
  </Delay>
</div>

The source code for Delay is quite simple to understand.


问:
clearInterval not woking and weirdness in an if statement
I'm making a time object but am experiencing something weird with my clearInterval but really the function in general. The relevant code looks like:

```<code>var timer = {
timerStarted: false,

startTimer: function(){
  var howMuchTime = parseInt($('#timer-button-number').text());
  var timesUpAt = Date.now() + howMuchTime*60*1000;
  var start = new Date().getTime();
  var milseccount = timesUpAt - start;

  function sectimer(){
    var remaining = Math.floor(milseccount - (new Date().getTime() -
    start));
    if (remaining <= 0) {
      clearInterval(x);
    }
    var minutes = Math.floor((remaining % (1000*60*60)) / (1000*60));
    var seconds = Math.floor((remaining % (1000*60)) / 1000);
    //display results
    $('#timer-button-number').text(minutes + 'm ' + seconds + 's');
  }

  var x = null;
  if (!timer.timerStarted) {
    x = setInterval(sectimer, 100);
    timer.timerStarted = true;
  } else if (timer.timerStarted){
    clearInterval(x);
    timer.timeStarted = false;
    console.log(timer.timeStarted);
  }
 }

}
</code>```

So on the button click the timer starts, the value of timer.timeStarted switchs to true. But when the button is clicked again the interval doesen't clear. The timer.timeStarted switches to false but when the button is clicked again the second part of the if statment continues to be executed (all but the clearInterval part), as if the if statement doesn't dictate that the interval should be started again (even though it never actually stopped). Could someone help?

答:
Your nulling your variable X every time it runs...

try moving it to the beginning like this:

```<code>x = null;
var timer = {
timerStarted: false,

startTimer: function(){
var howMuchTime = parseInt($('#timer-button-number').text());
var timesUpAt = Date.now() + howMuchTime*60*1000;
var start = new Date().getTime();
var milseccount = timesUpAt - start;

function sectimer(){
var remaining = Math.floor(milseccount - (new Date().getTime() -
start));
if (remaining <= 0) {
  clearInterval(x);
}
var minutes = Math.floor((remaining % (1000*60*60)) / (1000*60));
var seconds = Math.floor((remaining % (1000*60)) / 1000);
//display results
$('#timer-button-number').text(minutes + 'm ' + seconds + 's');
}

if (!timer.timerStarted) {
  x = setInterval(sectimer, 100);
  timer.timerStarted = true;
} else if (timer.timerStarted){
  clearInterval(x);
  timer.timeStarted = false;
  console.log(timer.timeStarted);
}
}

}
</code>```

Body:
I'm making a time object but am experiencing something weird with my clearInterval but really the function in general. The relevant code looks like:

var timer = {
timerStarted: false,

startTimer: function(){
  var howMuchTime = parseInt($('#timer-button-number').text());
  var timesUpAt = Date.now() + howMuchTime*60*1000;
  var start = new Date().getTime();
  var milseccount = timesUpAt - start;

  function sectimer(){
    var remaining = Math.floor(milseccount - (new Date().getTime() -
    start));
    if (remaining <= 0) {
      clearInterval(x);
    }
    var minutes = Math.floor((remaining % (1000*60*60)) / (1000*60));
    var seconds = Math.floor((remaining % (1000*60)) / 1000);
    //display results
    $('#timer-button-number').text(minutes + 'm ' + seconds + 's');
  }

  var x = null;
  if (!timer.timerStarted) {
    x = setInterval(sectimer, 100);
    timer.timerStarted = true;
  } else if (timer.timerStarted){
    clearInterval(x);
    timer.timeStarted = false;
    console.log(timer.timeStarted);
  }
 }

}

So on the button click the timer starts, the value of timer.timeStarted switchs to true. But when the button is clicked again the interval doesen't clear. The timer.timeStarted switches to false but when the button is clicked again the second part of the if statment continues to be executed (all but the clearInterval part), as if the if statement doesn't dictate that the interval should be started again (even though it never actually stopped). Could someone help?

Body:
Your nulling your variable X every time it runs...

try moving it to the beginning like this:

x = null;
var timer = {
timerStarted: false,

startTimer: function(){
var howMuchTime = parseInt($('#timer-button-number').text());
var timesUpAt = Date.now() + howMuchTime*60*1000;
var start = new Date().getTime();
var milseccount = timesUpAt - start;

function sectimer(){
var remaining = Math.floor(milseccount - (new Date().getTime() -
start));
if (remaining <= 0) {
  clearInterval(x);
}
var minutes = Math.floor((remaining % (1000*60*60)) / (1000*60));
var seconds = Math.floor((remaining % (1000*60)) / 1000);
//display results
$('#timer-button-number').text(minutes + 'm ' + seconds + 's');
}

if (!timer.timerStarted) {
  x = setInterval(sectimer, 100);
  timer.timerStarted = true;
} else if (timer.timerStarted){
  clearInterval(x);
  timer.timeStarted = false;
  console.log(timer.timeStarted);
}
}

}


问:
How to tell Firefox to run on particular version in Selenium webdriver?
I want to run my tests on diff versions of Firefox installed on my machine by mentioning the respective versions, I read this link https://stackoverflow.com/questions/12596097/how-to-set-particular-firefox-version-in-selenium-webdriver, but i dont want to create profiles manually and pass the same, is their any way on the run time to decide which version to pick??

答:
And for those using python use FirefoxBinary

Specify path to firefox binary using FirefoxBinary:

```<code>from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

browser = webdriver.Firefox(firefox_binary=FirefoxBinary('path goes here'))
</code>```

Hope it helps someone :)

Body:
And for those using python use FirefoxBinary

Specify path to firefox binary using FirefoxBinary:

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

browser = webdriver.Firefox(firefox_binary=FirefoxBinary('path goes here'))

Hope it helps someone :)


问:
Deleting Characters Before Integer
pe.fdaddress has strange characters before the number. This is preventing my code from joining properly. Is there any way to remove these characters to run my code properly? The addresses results are null because of this. Thanks</p>

```<code>SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, pe.fddob AS DOB
, pe.fdssn AS SSN
, ad.fdaddr1 AS [Address]
FROM OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbperson') AS pe
ON pt.fdperson = pe.fdid
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbaddress') AS ad
ON ad.id = pe.fdaddress
WHERE ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, pt.fdmedrecnum, pe.fdssn, pe.fddob, ad.fdaddr1
</code>```

答:
It's not nice to double post--you should clarify the original question.

Anywho... here is how to avoid that problem. see the change to your query. Also, I have no idea why you are using OPENQUERY here. You should look into LINKED SERVERS

```<code>SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, pe.fddob AS DOB
, pe.fdssn AS SSN
, ad.fdaddr1 AS [Address]
FROM OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbperson') AS pe
ON pt.fdperson = pe.fdid
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbaddress') AS ad
--here is the change
ON ad.id = LEFT(SUBSTRING(pe.fdaddress, PATINDEX('%[0-9.-]%', pe.fdaddress), 8000),PATINDEX('%[^0-9.-]%', SUBSTRING(pe.fdaddress, PATINDEX('%[0-9.-]%', pe.fdaddress), 8000) + 'X') -1)
WHERE ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, pt.fdmedrecnum, pe.fdssn, pe.fddob, ad.fdaddr1
</code>```

Title: Deleting Characters Before Integer

Body:
pe.fdaddress has strange characters before the number. This is preventing my code from joining properly. Is there any way to remove these characters to run my code properly? The addresses results are null because of this. Thanks

SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, pe.fddob AS DOB
, pe.fdssn AS SSN
, ad.fdaddr1 AS [Address]
FROM OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbperson') AS pe
ON pt.fdperson = pe.fdid
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbaddress') AS ad
ON ad.id = pe.fdaddress
WHERE ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, pt.fdmedrecnum, pe.fdssn, pe.fddob, ad.fdaddr1

Body:
It's not nice to double post--you should clarify the original question.

Anywho... here is how to avoid that problem. see the change to your query. Also, I have no idea why you are using OPENQUERY here. You should look into LINKED SERVERS

SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, pe.fddob AS DOB
, pe.fdssn AS SSN
, ad.fdaddr1 AS [Address]
FROM OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbperson') AS pe
ON pt.fdperson = pe.fdid
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbaddress') AS ad
--here is the change
ON ad.id = LEFT(SUBSTRING(pe.fdaddress, PATINDEX('%[0-9.-]%', pe.fdaddress), 8000),PATINDEX('%[^0-9.-]%', SUBSTRING(pe.fdaddress, PATINDEX('%[0-9.-]%', pe.fdaddress), 8000) + 'X') -1)
WHERE ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, pt.fdmedrecnum, pe.fdssn, pe.fddob, ad.fdaddr1


问:
Query Activity of token access from login.windows.net
I am getting an access token from Azure AD B2C via https://login.windows.net/{tenantID}/oauth2/token
using the password grant passing in username and password.

Here is a snippet of my code:

```<code>Resource = https://graph.microsoft.com/&client_id={clientId}&&grant_type=password&username="{username}"&password="{password}"&scope=openid"
</code>```

The token is being returned but how would I pull the activity surrounding these token access activity, from Azure Graph?

Is that possible, if so how?

答: If your requirement is to get the activities(such as query operation) with specific access token using graph api , there is no such rest api supports that  . If i misunderstand your requirement , please feel free to let me know .</p>

Body:
I am getting an access token from Azure AD B2C via https://login.windows.net/{tenantID}/oauth2/token
using the password grant passing in username and password.

Here is a snippet of my code:

Resource = https://graph.microsoft.com/&client_id={clientId}&&grant_type=password&username="{username}"&password="{password}"&scope=openid"

The token is being returned but how would I pull the activity surrounding these token access activity, from Azure Graph?

Is that possible, if so how?


问:
Drop and recreate table (locking)
I need to update a large set of data into a SQL Server table which I use for caching and this happens about every 10 minutes.

I find that rather than using "Insert into ...tableName" that dropping the table and recreating it with "Select * INTO ...tableName" is a lot faster.

My question is though how do I lock the table i.e. prevent users querying the table whilst it is dropping or selecting into?

If I wrap it in a transaction does this work?

Additional
Just clarifying this further as I probably wasnt clear enough to start with.

I was originally using TRUNCATE and then INSERT INTO but this was taking around 8 - 10 seconds.  Which potentially can hold users up.

So what I wanted to do instead was to drop the table and then recreat the table with SELECT INTO which was very much faster.  However, I guess my question was what happens if someone queries the table after the DROP and before the SELECT INTO?  What happens in this instance?

答:
An option for you is to load your data into a table with temporary name, then quickly DROP your main table and RENAME the other.

Those are quite fast operations (atomic?), the unavailability should be minimal.

https://dev.mysql.com/doc/refman/5.7/en/rename-table.html

https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-table-transact-sql

All you have to do is, for the very few users who will need to read the DB during the process, to show them a "please wait message" or similar, so that the user experience stays smooth (use a flag to track when the process starts/finish).

Title: Drop and recreate table (locking)


问:
I want to set a variable 's value from another php file
So i have dashboard.php

```<code>$value1;
$value1 = 1;
</code>```

and file.php

```<code>$value;
echo value;
</code>```

So i want to print "1" on the file file.php. How can i tell file.php to get the variable 's value from dashboard.php

答:
You can simply use include().

```<code>include('dashboard.php');
</code>```

Body:
So i have dashboard.php

$value1;
$value1 = 1;

and file.php

$value;
echo value;

So i want to print "1" on the file file.php. How can i tell file.php to get the variable 's value from dashboard.php

Body:
You can simply use include().

include('dashboard.php');


问:
Dealing with the Done button after Quicklook, Objective C
This has got to be the dumbest question of the day, but I'm just not getting it.
I create a Quicklook, which shows just fine.  When I hit the Done button, it just reappears.  How do I intercept the Done button? Or more generally, control what is displayed in what I assume is a navbar.  Here is the relevant code:

```<code>- (void)viewDidAppear:(BOOL)animated
{

    [super viewDidAppear:animated];

    /*
     *  get the path to the pdf resource.
     */

    NSString *path = [[NSBundle mainBundle] pathForResource:@"article" ofType:@"pdf"];
    NSURL *docURL = [NSURL fileURLWithPath:path];

    /*
     *  create the Quicklook controller.
     */

    QLPreviewController *qlController = [[QLPreviewController alloc] init];

    PreviewItem *item = [[PreviewItem alloc] initPreviewURL:docURL WithTitle:@"Article"];
    self.pdfDatasource = [[PDFDataSource alloc] initWithPreviewItem:item];
    qlController.dataSource = self.pdfDatasource;

    /*
     *  present the document.
     */

    [self presentViewController:qlController animated:YES completion:nil];
}
</code>```

I assume I am missing something obvious.

Thank you,
Ken

答:
The trick was to roll everything back into the original viewcontroller.  That way when I hit the done button it goes back to the original viewcontroller, which is exactly what I wanted.  so instead of having a separate class, I just incorporated the calls right into my main viewcontroller.  I suspect that there is still a way to do with a cunning use of delegates, but in case anyone else is having the same issue, this was a solution that worked for me.

Thank you for your attention and help.
Ken

Body:
This has got to be the dumbest question of the day, but I'm just not getting it.
I create a Quicklook, which shows just fine.  When I hit the Done button, it just reappears.  How do I intercept the Done button? Or more generally, control what is displayed in what I assume is a navbar.  Here is the relevant code:

- (void)viewDidAppear:(BOOL)animated
{

    [super viewDidAppear:animated];

    /*
     *  get the path to the pdf resource.
     */

    NSString *path = [[NSBundle mainBundle] pathForResource:@"article" ofType:@"pdf"];
    NSURL *docURL = [NSURL fileURLWithPath:path];

    /*
     *  create the Quicklook controller.
     */

    QLPreviewController *qlController = [[QLPreviewController alloc] init];

    PreviewItem *item = [[PreviewItem alloc] initPreviewURL:docURL WithTitle:@"Article"];
    self.pdfDatasource = [[PDFDataSource alloc] initWithPreviewItem:item];
    qlController.dataSource = self.pdfDatasource;

    /*
     *  present the document.
     */

    [self presentViewController:qlController animated:YES completion:nil];
}

I assume I am missing something obvious.

Thank you,
Ken


问:
Build executable JAR for Gatling load test
I am new to Gatling (2.1.2) and want to do a small prototype project to show to my colleagues.

According to the quick start page, there are several ways I can run a simulation with Gatling:

decompress the Gatling bundle into a folder and drop my simulation files into user-files/simulations folder.  bin/gatling.sh will compile and run the simulation files.

use the gatling-maven-plugin maven plugin to execute the simulation.

create a project with gatling-highcharts-maven-archetype, and run the Engine class.

and I found those problems

For 1, it is hard to add dependencies for simulation classes.  I have to figure out what the jars are needed and drop them to the lib folder.

For 2, it requires maven to be installed.

For 3, it only runs from an IDE

I just want a simple executable JAR file with all the dependencies bundled together (my simulation, Gatling and third party), and run it from any machine (like EC2 instances).

Is there a way to achieve this?

Update 1:

I tried method 3, but moving all the project files from test folder to main, and used maven-assembly-plugin to build a jar with dependencies.  When I tried to run the file, I got the following error:

```<code>Exception in thread "main" java.lang.ExceptionInInitializerError
    at Engine$.delayedEndpoint$Engine$1(Engine.scala:7)
    at Engine$delayedInit$body.apply(Engine.scala:4)
    at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
    at scala.App$class.main(App.scala:76)
    at Engine$.main(Engine.scala:4)
    at Engine.main(Engine.scala)
Caused by: java.nio.file.FileSystemNotFoundException
    at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
    at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
    at java.nio.file.Paths.get(Paths.java:143)
    at io.gatling.core.util.PathHelper$.uri2path(PathHelper.scala:32)
    at IDEPathHelper$.<init>(IDEPathHelper.scala:7)
    at IDEPathHelper$.<clinit>(IDEPathHelper.scala)
    ... 11 more
</code>```

I guess this is something to do with Gatling configuration, but don't know what has gone wrong.

答: I use IntelliJ Idea  and I got this fixed by right clicking on the scala folder > Mark Directory as > Test Sources Root . Now Execute "Engine" and you will be all good ! </p>

Body:
I am new to Gatling (2.1.2) and want to do a small prototype project to show to my colleagues.

According to the quick start page, there are several ways I can run a simulation with Gatling:

decompress the Gatling bundle into a folder and drop my simulation files into user-files/simulations folder.  bin/gatling.sh will compile and run the simulation files.

use the gatling-maven-plugin maven plugin to execute the simulation.

create a project with gatling-highcharts-maven-archetype, and run the Engine class.

and I found those problems

For 1, it is hard to add dependencies for simulation classes.  I have to figure out what the jars are needed and drop them to the lib folder.

For 2, it requires maven to be installed.

For 3, it only runs from an IDE

I just want a simple executable JAR file with all the dependencies bundled together (my simulation, Gatling and third party), and run it from any machine (like EC2 instances).

Is there a way to achieve this?

Update 1:

I tried method 3, but moving all the project files from test folder to main, and used maven-assembly-plugin to build a jar with dependencies.  When I tried to run the file, I got the following error:

Exception in thread "main" java.lang.ExceptionInInitializerError
    at Engine$.delayedEndpoint$Engine$1(Engine.scala:7)
    at Engine$delayedInit$body.apply(Engine.scala:4)
    at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
    at scala.App$class.main(App.scala:76)
    at Engine$.main(Engine.scala:4)
    at Engine.main(Engine.scala)
Caused by: java.nio.file.FileSystemNotFoundException
    at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
    at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
    at java.nio.file.Paths.get(Paths.java:143)
    at io.gatling.core.util.PathHelper$.uri2path(PathHelper.scala:32)
    at IDEPathHelper$.<init>(IDEPathHelper.scala:7)
    at IDEPathHelper$.<clinit>(IDEPathHelper.scala)
    ... 11 more

I guess this is something to do with Gatling configuration, but don't know what has gone wrong.


问:
How do I set character encoding to UTF-8 for default.html?
I spent the last few hours getting my website to validate HTML 4.01 Strict and I actually have succeeded in that, but there is still one warning which I can't get rid of. The warning is:

Character Encoding mismatch!

The character encoding specified in
the HTTP header (iso-8859-1) is
different from the value in the
element (utf-8). I will use the value
from the HTTP header (iso-8859-1) for
this validation.

The page in question is www.dubiousarray.net/default.html. As you can see from the page source I have the following meta element:

```<code><meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</code>```

and I have made sure that the default.html file is saved with UTF-8 encoding. The strange thing is all the other pages in the site validate without this warning and they have the same meta tag and were saved in exactly the same way. I am pretty sure it is something to do with the server configuration. The .htaccess file looks like this at the moment:

```<code># Use PHP 5 as default
AddHandler application/x-httpd-php5 .php
AddDefaultCharset UTF-8
</code>```

But I have tried all the fixes shown on this page and none of them worked. How can I go about getting rid of this warning?

In Firefox, if you right click on the page and select 'View Page Info', default.html shows as ISO-8859-1, while all the other pages show UTF-8.

All the html file have been created and saved in the exact same way (character encoding set to UTF-8 without BOM), but default.html is the only one which isn't displaying as UTF-8. So I assume the server is doing something special to the default.html file though I am not sure what as there is not sign of it in the .htaccess file.

答:
Include this in your code:

<meta charset="utf-8" />```

Body:
I spent the last few hours getting my website to validate HTML 4.01 Strict and I actually have succeeded in that, but there is still one warning which I can't get rid of. The warning is:

Character Encoding mismatch!

The character encoding specified in
the HTTP header (iso-8859-1) is
different from the value in the
element (utf-8). I will use the value
from the HTTP header (iso-8859-1) for
this validation.

The page in question is www.dubiousarray.net/default.html. As you can see from the page source I have the following meta element:

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

and I have made sure that the default.html file is saved with UTF-8 encoding. The strange thing is all the other pages in the site validate without this warning and they have the same meta tag and were saved in exactly the same way. I am pretty sure it is something to do with the server configuration. The .htaccess file looks like this at the moment:

# Use PHP 5 as default
AddHandler application/x-httpd-php5 .php
AddDefaultCharset UTF-8

But I have tried all the fixes shown on this page and none of them worked. How can I go about getting rid of this warning?

In Firefox, if you right click on the page and select 'View Page Info', default.html shows as ISO-8859-1, while all the other pages show UTF-8.

All the html file have been created and saved in the exact same way (character encoding set to UTF-8 without BOM), but default.html is the only one which isn't displaying as UTF-8. So I assume the server is doing something special to the default.html file though I am not sure what as there is not sign of it in the .htaccess file.


问:
Onsen Carousel Vertical Scroll
I am working on a mobile app using Onsen UI Framework, and wanted the ability to swipe between pages or content.  I added the carousel and placed pages in the div, and it worked for the most part.  The only issue remaining is I cannot scroll the content vertically to see all the writing.

How to fix this?

答:
Use direction="vertical".</p>

```<code><ons-carousel direction="vertical">
...
</ons-carousel>
</code>```

Title: Onsen Carousel Vertical Scroll

Body:
Use direction="vertical".

<ons-carousel direction="vertical">
...
</ons-carousel>


问:
Get multiple element value in jquery
code

HTML

```<code>    <table>

    <tr>
       <td><input type="hidden" name="zxc_0" value="105" quantity="1"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_1" value="155" quantity="3"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_2" value="15" quantity="7"></td>
    </tr>

    </table>

<a id="button-generate" class="button" style="">Generate</a>
</code>```

Question:

The above code is that html store with the data value, so how can I using java script to store the value data into Array once the user click the generate button?

答:
if you re using jquery, maybe you can try this:

$("#button-generate").on("click", function(){

  var vall = [];
  $.each($("input[name^='zxc_']"), function(){
    vall.push($(this).val());
  });
  console.log(vall);
})```
<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>
<table>

    <tr>
       <td><input type="hidden" name="zxc_0" value="105" quantity="1"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_1" value="155" quantity="3"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_2" value="15" quantity="7"></td>
    </tr>

    </table>

Generate</code>```

http://api.jquery.com/category/selectors/attribute-selectors/

Title: Get multiple element value in jquery

Body:
code

HTML

       <input type="hidden" name="zxc_0" value="105" quantity="1">

       <input type="hidden" name="zxc_1" value="155" quantity="3">

       <input type="hidden" name="zxc_2" value="15" quantity="7">

Generate

Question:

The above code is that html store with the data value, so how can I using java script to store the value data into Array once the user click the generate button?

Body:
if you re using jquery, maybe you can try this:

$("#button-generate").on("click", function(){

  var vall = [];
  $.each($("input[name^='zxc_']"), function(){
    vall.push($(this).val());
  });
  console.log(vall);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>

    <tr>
       <td><input type="hidden" name="zxc_0" value="105" quantity="1"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_1" value="155" quantity="3"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_2" value="15" quantity="7"></td>
    </tr>

    </table>

<a id="button-generate" class="button" style="">Generate</a>

http://api.jquery.com/category/selectors/attribute-selectors/