问:
Second spinner does not update values
If i change or add first spinner's (spinnerBreeds) values - works ok. But Second spinner does not update values. I tried  call the notifyDataSetChanged() on the adapter, but still does not work.

My code is:

```<code>    public class MainActivity extends Activity {

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

            // Create DataHelper object and insert some sample data
            DataHelper datahelper = new DataHelper(this);
            datahelper.insertBreed ("Beagle");
            datahelper.insertBreed ("Bulldog");
            datahelper.insertBreed ("Chow Chow");

            // Get sample data from the database and display them in the spinner
            Spinner spinnerBreeds = (Spinner) findViewById(R.id.spinnerBreeds);
            ArrayList<String> list = datahelper.getAllBreeds();
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
            spinnerBreeds.setAdapter(adapter);

            //Init second spinner
            DataHelper2 datahelper2 = new DataHelper2(this);
            datahelper2.insertAge("1 year");
            datahelper2.insertAge ("2-3 years");
            datahelper2.insertAge("4-5 years");
            datahelper2.insertAge("6-9 years");
            datahelper2.insertAge("10+ years");

            // Get sample data from the database and display them in the spinner
            Spinner spinnerAge = (Spinner) findViewById(R.id.spinnerAge);
            ArrayList<String> list2 = datahelper2.getAllAge();
            ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list2);
            spinnerAge.setAdapter(adapter2);

    }
</code>```

答:
```<code>Try this code........
spinnerBreeds.setOnItemSelectedListener(new OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view,
                            int position, long id) {
                        // TODO Auto-generated method stub

 ArrayList<String> list2 = datahelper2.getAllAge();
  ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, list2);

                spinnerAge.setAdapter(adapter2);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        // TODO Auto-generated method stub

                    }
                });
</code>```

Title: Second spinner does not update values

Body:
If i change or add first spinner's (spinnerBreeds) values - works ok. But Second spinner does not update values. I tried  call the notifyDataSetChanged() on the adapter, but still does not work.

My code is:

    public class MainActivity extends Activity {

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

            // Create DataHelper object and insert some sample data
            DataHelper datahelper = new DataHelper(this);
            datahelper.insertBreed ("Beagle");
            datahelper.insertBreed ("Bulldog");
            datahelper.insertBreed ("Chow Chow");

            // Get sample data from the database and display them in the spinner
            Spinner spinnerBreeds = (Spinner) findViewById(R.id.spinnerBreeds);
            ArrayList<String> list = datahelper.getAllBreeds();
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
            spinnerBreeds.setAdapter(adapter);

            //Init second spinner
            DataHelper2 datahelper2 = new DataHelper2(this);
            datahelper2.insertAge("1 year");
            datahelper2.insertAge ("2-3 years");
            datahelper2.insertAge("4-5 years");
            datahelper2.insertAge("6-9 years");
            datahelper2.insertAge("10+ years");

            // Get sample data from the database and display them in the spinner
            Spinner spinnerAge = (Spinner) findViewById(R.id.spinnerAge);
            ArrayList<String> list2 = datahelper2.getAllAge();
            ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list2);
            spinnerAge.setAdapter(adapter2);

    }


来源: stackexchange

问:
Eclipse Update Failing with Message "Insufficient access privileges to apply this update"
I'm running Eclipse under a Windows 7, 64-bit installation on which I have administrator privileges.

Since I first installed Eclipse many months ago, I've been able to keep it up to date with the Help > Check for Updates function—but starting a couple of weeks ago, it gave the message

Insufficient access privileges to apply this update.

Even when I ran Eclipse as an administrator, I continued to get this message. How can I fix it?

答: I found a workaround for this stupid bug in Eclipse. Selecting updates one-by-one is disabled, but if you click Select all and then deselect the ones you do not need, you can proceed.</p>

ContentLicense: CC BY-SA 3.0


问:
Multiple index properties on a type?
Is it possible to have something like this in C#? I am not very sure:

```<code>class Library
{
    public string Books[string title]
    {
        get{return this.GetBookByName(string title);}
    }

    public DateTime PublishingDates[string title]
    {
        get{return this.GetBookByName(string title).PublishingDate;}
    }
}
</code>```

So it could be used as such:

```<code>myLibrary.Books["V For Vendetta"]
myLibrary.PublishingDates["V For Vendetta"] = ...
</code>```

So my complete member methods that I need to implement in my framework (by calling them) are:

```<code>GetCustomStringValue (key)
GetCustomIntValue (key)
GetCustomBoolValue (key)
GetCustomFloatValue (key)
SetCustomStringValue (key)
SetCustomIntValue (key)
SetCustomBoolValue (key)
SetCustomFloatValue (key)
</code>```

I want to implement them cleaner in my own type.

答:
C# doesn't support it, unfortunately. It only recognises the this[] property, which is really just an indexable property named Item when compiled. The CLI supports any number of indexable properties though, and that can be reflected in some other languages like F#, where you can define your own.

Even when you do define your own in CIL or otherwise though, you still can't call them from C# like you would want to, you need to make a manual call to get_Books(index); for a property named Books. All properties are just syntactic sugar for method calls like that. C# only recognises the property named Item as indexable.

ContentLicense: CC BY-SA 2.5

Title: Multiple index properties on a type?

Body:
Is it possible to have something like this in C#? I am not very sure:

class Library
{
    public string Books[string title]
    {
        get{return this.GetBookByName(string title);}
    }

    public DateTime PublishingDates[string title]
    {
        get{return this.GetBookByName(string title).PublishingDate;}
    }
}

So it could be used as such:

myLibrary.Books["V For Vendetta"]
myLibrary.PublishingDates["V For Vendetta"] = ...

So my complete member methods that I need to implement in my framework (by calling them) are:

GetCustomStringValue (key)
GetCustomIntValue (key)
GetCustomBoolValue (key)
GetCustomFloatValue (key)
SetCustomStringValue (key)
SetCustomIntValue (key)
SetCustomBoolValue (key)
SetCustomFloatValue (key)

I want to implement them cleaner in my own type.


问:
create function that will accept multiple arguments
I am trying to modify my function to accept a different number of arguments, so for example the arguments could be (poly1, poly2) or (poly1, poly2, poly3) and so on.

The problem I have is that I'm not sure how to increment the variable name

How can I turn the function below into a function that will accept a number of different arguments and loop through them. I would prefer a functional way to do this rather than using a for loop if possible

```<code>function UseWicketToGoFromGooglePolysToWKT(poly1, poly2, poly3, poly4) {
    var wicket = new Wkt.Wkt();

    wicket.fromObject(poly1);
    var wkt1 = wicket.write();

    wicket.fromObject(poly2);
    var wkt2 = wicket.write();

    wicket.fromObject(poly3);
    var wkt3 = wicket.write();

    wicket.fromObject(poly4);
    var wkt4 = wicket.write();

   return [wkt1, wkt2, wkt3, wkt4];
}
</code>```

My attempt

```<code>function UseWicketToGoFromGooglePolysToWKT(...args) {
  args.map(item, i => {
    wicket.fromObject(`poly${i}`);
    var wkt + i = wicket.write();
  })
</code>```

答:
You were close.

You just needed to return the result from .write(), and return the array resulting from .map().

You were also missing the new Wkt.Wkt(); call:

```<code>function UseWicketToGoFromGooglePolysToWKT(...args) {
  var wicket = new Wkt.Wkt(); // this was missing

  return args.map(item => {   // return this. Also, the `i` isn't necessary.
    wicket.fromObject(item);  // pass `item` here.
    return wicket.write();    // return instead of variable assignment
  });
}
</code>```

Body:
I am trying to modify my function to accept a different number of arguments, so for example the arguments could be (poly1, poly2) or (poly1, poly2, poly3) and so on.

The problem I have is that I'm not sure how to increment the variable name

How can I turn the function below into a function that will accept a number of different arguments and loop through them. I would prefer a functional way to do this rather than using a for loop if possible

function UseWicketToGoFromGooglePolysToWKT(poly1, poly2, poly3, poly4) {
    var wicket = new Wkt.Wkt();

    wicket.fromObject(poly1);
    var wkt1 = wicket.write();

    wicket.fromObject(poly2);
    var wkt2 = wicket.write();

    wicket.fromObject(poly3);
    var wkt3 = wicket.write();

    wicket.fromObject(poly4);
    var wkt4 = wicket.write();

   return [wkt1, wkt2, wkt3, wkt4];
}

My attempt

function UseWicketToGoFromGooglePolysToWKT(...args) {
  args.map(item, i => {
    wicket.fromObject(`poly${i}`);
    var wkt + i = wicket.write();
  })

Body:
You were close.

You just needed to return the result from .write(), and return the array resulting from .map().

You were also missing the new Wkt.Wkt(); call:

function UseWicketToGoFromGooglePolysToWKT(...args) {
  var wicket = new Wkt.Wkt(); // this was missing

  return args.map(item => {   // return this. Also, the `i` isn't necessary.
    wicket.fromObject(item);  // pass `item` here.
    return wicket.write();    // return instead of variable assignment
  });
}


问:
NodeJS MYSQL Query result Buffer?
mysql select query result ...

```<code>//nodejs database.js
var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'me',
    database : 'test',
    password : '1234'
});

// nodejs app.js
app.get('/api/v0.1/getPostList', function(req, res) {
        limit_count = 5;
        db.query(postModel.postList(limit_count) , function(err, rows) {
            if (err) throw err;
            console.log(rows)
            res.json(rows);
        });
    });

//result
RowDataPacket {
    POST_SEQ: 13,
    POST_TYPE: <Buffer 31 31 30 30>,
    CATEGORY: <Buffer 49 54 20 2f 20 4d 4f 42 49 4c 45>, ...
</code>```

why query data buffer type?

I do not know the cause.

java query data success

[DEBUG][2016-10-28 19:20:24,160] <== Row: 13, 1100, GAME ...

答:
but this would cause performance issue if you are having a lot of records and fields. You would have to iterate and tostring all buffer fields.
It should receive data in the predefined datatypes. ie VARCHAR -> String</p>

Title: NodeJS MYSQL Query result Buffer?

Body:
mysql select query result ...

//nodejs database.js
var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'me',
    database : 'test',
    password : '1234'
});

// nodejs app.js
app.get('/api/v0.1/getPostList', function(req, res) {
        limit_count = 5;
        db.query(postModel.postList(limit_count) , function(err, rows) {
            if (err) throw err;
            console.log(rows)
            res.json(rows);
        });
    });

//result
RowDataPacket {
    POST_SEQ: 13,
    POST_TYPE: <Buffer 31 31 30 30>,
    CATEGORY: <Buffer 49 54 20 2f 20 4d 4f 42 49 4c 45>, ...

why query data buffer type?

I do not know the cause.

java query data success

[DEBUG][2016-10-28 19:20:24,160] <== Row: 13, 1100, GAME ...


问:
Error C1083 Cannot open include file: 'vtkGUISupportQtOpenGLModule.h': No such file or directory
I'm trying to link VTK library to my project on Windows 7. The error I get is:

Error  C1083   Cannot open include file: 'vtkGUISupportQtOpenGLModule.h': No such file or directory

The thing in my code that provokes the error is #include<QVTKWidget2.h>.

Src and build directories of my VTK copy are separate. The linking tool I use is cmake. The build tool: VS 2015.

My CMakeLists.txt and VTK's cache u can see below.

Thanks in advance for any suggestions.

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 2.8)
set(PROJECT Pro)
project(${PROJECT})

set(BUILD_SHARED_LIBS false)
message("  BUILD_SHARED_LIBS " ${BUILD_SHARED_LIBS})
list(APPEND CMAKE_EXE_LINKER_FLAGS -static)

find_package(VTK REQUIRED)
include(${VTK_USE_FILE})

set(VTK_INCLUDE_DIRS
    "D:/libs/VTK-7.1.1"
    )

set(VTK_QT_INCLUDE_DIR
    "D:/libs/VTK-7.1.1/GUISupport/QtOpenGL"
    )

include_directories(${VTK_INCLUDE_DIRS} ${VTK_QT_INCLUDE_DIR})

# ... Local src declaration

add_executable(${PROJECT} ${PRO_APP_HEADERS}${PRO_APP_SOURCES})

if(VTK_LIBRARIES)
  message("VTK_LIBRARIES is set.")
  target_link_libraries(${PROJECT} ${VTK_LIBRARIES})
else(VTK_LIBRARIES)
  message("! VTK_LIBRARIES are not set completely")
  target_link_libraries(${PROJECT} vtkHybrid vtkWidgets)
endif(VTK_LIBRARIES)
</code>```

VTK's cache
enter image description here

答:
Click on "Advanced" in the VTK's CMake (on the top, next to the search bar), you will see many more options. One of them is Module_vtkGUISupportQtOpenGL, make sure it is checked.

In your CMake, I don't think your include_directories clause does anything. The paths you are linking to are not to the library, but rather to the sources of the library, the actual path to the library would be D:\VTK_build_directory\include\vtk-7.1.1\, where VTK_build_directory is wherever you build VTK (I recommend using INSTALL to build VTK, then the result will be in the CMAKE_INSTALL_PREFIX directory, which you can specify in VTK's CMake). However, in any case it is not needed anyway since you are already using the include(${VTK_USE_FILE}), which will setup all include files. So, unless there is some other use not apparent from your example, you can delete the whole

```<code>set(VTK_INCLUDE_DIRS
    "D:/libs/VTK-7.1.1"
)

set(VTK_QT_INCLUDE_DIR
    "D:/libs/VTK-7.1.1/GUISupport/QtOpenGL"
)

include_directories(${VTK_INCLUDE_DIRS} ${VTK_QT_INCLUDE_DIR})
</code>```

Body:
I'm trying to link VTK library to my project on Windows 7. The error I get is:

Error  C1083   Cannot open include file: 'vtkGUISupportQtOpenGLModule.h': No such file or directory

The thing in my code that provokes the error is #include<QVTKWidget2.h>.

Src and build directories of my VTK copy are separate. The linking tool I use is cmake. The build tool: VS 2015.

My CMakeLists.txt and VTK's cache u can see below.

Thanks in advance for any suggestions.

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
set(PROJECT Pro)
project(${PROJECT})

set(BUILD_SHARED_LIBS false)
message("  BUILD_SHARED_LIBS " ${BUILD_SHARED_LIBS})
list(APPEND CMAKE_EXE_LINKER_FLAGS -static)

find_package(VTK REQUIRED)
include(${VTK_USE_FILE})

set(VTK_INCLUDE_DIRS
    "D:/libs/VTK-7.1.1"
    )

set(VTK_QT_INCLUDE_DIR
    "D:/libs/VTK-7.1.1/GUISupport/QtOpenGL"
    )

include_directories(${VTK_INCLUDE_DIRS} ${VTK_QT_INCLUDE_DIR})

# ... Local src declaration

add_executable(${PROJECT} ${PRO_APP_HEADERS}${PRO_APP_SOURCES})

if(VTK_LIBRARIES)
  message("VTK_LIBRARIES is set.")
  target_link_libraries(${PROJECT} ${VTK_LIBRARIES})
else(VTK_LIBRARIES)
  message("! VTK_LIBRARIES are not set completely")
  target_link_libraries(${PROJECT} vtkHybrid vtkWidgets)
endif(VTK_LIBRARIES)

VTK's cache
enter image description here

Body:
Click on "Advanced" in the VTK's CMake (on the top, next to the search bar), you will see many more options. One of them is Module_vtkGUISupportQtOpenGL, make sure it is checked.

In your CMake, I don't think your include_directories clause does anything. The paths you are linking to are not to the library, but rather to the sources of the library, the actual path to the library would be D:\VTK_build_directory\include\vtk-7.1.1\, where VTK_build_directory is wherever you build VTK (I recommend using INSTALL to build VTK, then the result will be in the CMAKE_INSTALL_PREFIX directory, which you can specify in VTK's CMake). However, in any case it is not needed anyway since you are already using the include(${VTK_USE_FILE}), which will setup all include files. So, unless there is some other use not apparent from your example, you can delete the whole

set(VTK_INCLUDE_DIRS
    "D:/libs/VTK-7.1.1"
)

set(VTK_QT_INCLUDE_DIR
    "D:/libs/VTK-7.1.1/GUISupport/QtOpenGL"
)

include_directories(${VTK_INCLUDE_DIRS} ${VTK_QT_INCLUDE_DIR})


问:
jQuery to change style sheet (like a theme switcher), doesn't load CSS in IE
So the page is here: http://www.sumsy.com/testing/1/login.html

It works in FF, but no IE.

The problem is:

Click on Change Theme, select the second box(blue box), the site should switch to a new theme,

However, in IE, it just doesn't load any CSS style. I did some debugging. The style sheet link attr is actually changed.

Can you guys please shed some light?

You can see the JS (mainly theme-switcher.js) and HTML code from view source. If you need me to paste the code here, please let me know.

答:
Updating link elements dynamically has highly variable behaviour.  I found the same issue when (for some crazy reason) I wanted to dynamically change favicon links.  The best solution is to remove the old link and replace it with a new one:

```<code>$('#active-theme').replaceWith($('<link>', {
    id: 'active-theme',
    href: 'themes/' + get_cookie + '/_css/main.css',
    type: 'text/css',
    rel: 'stylesheet'
}));
</code>```

Body:
Updating link elements dynamically has highly variable behaviour.  I found the same issue when (for some crazy reason) I wanted to dynamically change favicon links.  The best solution is to remove the old link and replace it with a new one:

$('#active-theme').replaceWith($('<link>', {
    id: 'active-theme',
    href: 'themes/' + get_cookie + '/_css/main.css',
    type: 'text/css',
    rel: 'stylesheet'
}));


问:
Changes not showing in front end when modifying .twig file?
I am trying to stop the auto-scrolling of the carousel on my page. I navigated to /catalog/view/theme/default/template/extension/module and deleted the autoPlay function off of carousel.twig. However, when I go to my website, the carousel still moves as usual.
I've tried resetting my cache, and even visited the website with other devices.
My host doesn't seem to use any sort of caching. And I doubt it's because of that as all other changes usually show instantly.
I also have the same problem with the stylesheet.css; when I change the .body color attribute, the background color of the site doesn't change from white.
Can someone tell me what I'm doing wrong?
Thank you!</p>

答:
The reason could be from twig caching
system/library/template/Twig/Environment.php
set this value  $this->debug to  (bool) true

```<code>$this->debug = (bool) true;
</code>```

it will disable caching during development
this helped me solve caching problem,
https://twig.symfony.com/doc/2.x/api.html#environment-options

Body:
The reason could be from twig caching
system/library/template/Twig/Environment.php
set this value  $this->debug to  (bool) true

$this->debug = (bool) true;

it will disable caching during development
this helped me solve caching problem,
https://twig.symfony.com/doc/2.x/api.html#environment-options


问:
Very slow building time of Webpack on production, fast on development
After switch to webpack (resp. Rails + Webpacker gem) compiling bundle on production server is more then 10 times longer than on development.

Production machine is better than development, required modules are the same.

答:
We finally found that resolve-url-loader module (https://www.npmjs.com/package/resolve-url-loader) + folder with many uploaded images (into separate folders) was the brake.

resolve-url-loader searches for CSS url('my_image') in whole folder from which webpack was run. And one of subfolders was the million-subfolders-folder. So loader try to search in every corner.

I do not find any option to exclude this folder from search by config.
But! If loader finds file package.json or bower.json in folder, it will stop searching. So solution was to touch million-subfolders-folder/package.json.
It is not perfect, loader still search content of folder for each, not yet founded, image. But just once, not searching trough million subfolders.


问:
Unity 3D Rotate object smoothly during time
I'm programming a game where a cube has to rotate smoothly around itself 90 degrees each time a metronome is beating.

Each time the metronome is beating, my method call a coroutine :

```<code>IEnumerator moveCoroutine()
{
    if (!isCollided && canRotate) {
        for (float i = 0; i < 10; i++) {
            transform.RotateAround(pivot, direction, 90 / 10);
            yield return null;
        }
    }
}
</code>```

and the cube rotates rather smoothly, but the rotation is done long time before the next tick of the metronome, and I want it to rotate from the beginning to the end, in a smooth move.

I imagine that I've to use the time between two metronome ticks (which is the var 'Metronome.manager.delay') but I'm not finding how.

Thanks for your help

答:
Other answers might work .. but I use this setup for smooth Coroutines in Unity not depending on the framerate but the actual time
(necessary changes for movement should be trivial):

public IEnumerator RotateCoroutine(Vector3 rotationEulerAngles, float rotationDuration)
{

    /* Set the current goal Rotation to animate between them */
    Quaternion currentRotation = transform.localRotation;
    Quaternion goalRotation = currentRotation * Quaternion.Euler(rotationEulerAngles);

    /* Set control variables */
    float timePassed = 0.0f;
    float fracTime = 0.0f;

    /* Begin the animation, end after rotationDuration seconds */
    while (fracTime < 1)
    {
        /* Set Rotation between current and goal depending on fracTime */
        transform.transform.localRotation = Quaternion.Lerp(currentRotation, goalRotation, fracTime);

        /* Update timePassed and fracTime */
        timePassed += Time.deltaTime;

        /* On this way fracTime will always be a value between
        * 0 - start of animation and
        * 1 - end of animation after rotationDuration seconds */
        fracTime = timePassed / rotationDuration;

        /* yield return so the actual state gets printed */
        yield return null;
    }

    /* Just to be sure after the animation set yourGameObject
     * to exactly the tranformation value(s) you want */
    transform.localRotation = goalRotation;
}
```

<p>With this you can way esier control how long an animation takes and setting exact values for your rotation makes sure nothing goes strange while rotating.</p>

<p>you can call this Coroutine than by e.g.</p>

<pre class="lang-c# prettyprint-override"><code>StartCoroutine(RotateCoroutine(new Vector3(0,90,0), 2.0f));
</code>```

for rotating the Object in 2 seconds about 90° in its local Y-Axis

Body:
I'm programming a game where a cube has to rotate smoothly around itself 90 degrees each time a metronome is beating.

Each time the metronome is beating, my method call a coroutine :

IEnumerator moveCoroutine()
{
    if (!isCollided && canRotate) {
        for (float i = 0; i < 10; i++) {
            transform.RotateAround(pivot, direction, 90 / 10);
            yield return null;
        }
    }
}

and the cube rotates rather smoothly, but the rotation is done long time before the next tick of the metronome, and I want it to rotate from the beginning to the end, in a smooth move.

I imagine that I've to use the time between two metronome ticks (which is the var 'Metronome.manager.delay') but I'm not finding how.

Thanks for your help

Body:
Other answers might work .. but I use this setup for smooth Coroutines in Unity not depending on the framerate but the actual time
(necessary changes for movement should be trivial):

public IEnumerator RotateCoroutine(Vector3 rotationEulerAngles, float rotationDuration)
{

    /* Set the current goal Rotation to animate between them */
    Quaternion currentRotation = transform.localRotation;
    Quaternion goalRotation = currentRotation * Quaternion.Euler(rotationEulerAngles);

    /* Set control variables */
    float timePassed = 0.0f;
    float fracTime = 0.0f;

    /* Begin the animation, end after rotationDuration seconds */
    while (fracTime < 1)
    {
        /* Set Rotation between current and goal depending on fracTime */
        transform.transform.localRotation = Quaternion.Lerp(currentRotation, goalRotation, fracTime);

        /* Update timePassed and fracTime */
        timePassed += Time.deltaTime;

        /* On this way fracTime will always be a value between
        * 0 - start of animation and
        * 1 - end of animation after rotationDuration seconds */
        fracTime = timePassed / rotationDuration;

        /* yield return so the actual state gets printed */
        yield return null;
    }

    /* Just to be sure after the animation set yourGameObject
     * to exactly the tranformation value(s) you want */
    transform.localRotation = goalRotation;
}

With this you can way esier control how long an animation takes and setting exact values for your rotation makes sure nothing goes strange while rotating.

you can call this Coroutine than by e.g.

StartCoroutine(RotateCoroutine(new Vector3(0,90,0), 2.0f));

for rotating the Object in 2 seconds about 90° in its local Y-Axis


问:
Python - Update Dictionary With User Input
For this part of my program, I need to write code that will allow the user to update the dictionary. The key is the employee ID, and the updatable fields are their name, department, and title. So that when the updated record is viewed it would display the new name, title, and department. Where Employees is the dictionary. This is what i have so far:

```<code>while Choice == '2':

    dict_key = input('Enter the employee ID of the employee to change the record: ')

    if dict_key in Employees:
        n = 3
        print('Enter the new Name, Department, and Title')
        for i in range(n):
            updates = input().split(' ')

        Employees[dict_key] = updates[0][1][2]
        print('\n')
    else:
        print('ERROR: That record does not exist!')
        print('\n')

    Continue = input('Press 1 to update another employee record or 2 to exit: ')
    print('\n')

    if Continue == '2':
        print('*' * 80)
        break
</code>```

When running this code i get the following error:

```<code>Traceback (most recent call last):
line 43, in <module>
  Employees[dict_key] = updates[0][1][2]
IndexError: string index out of range
</code>```

Desired output for ex:
If employee ID 1234 = John,IT,Programmer
and the updates were: John Doe, IT, Manager.

Employee ID 1234 should = John Doe,IT,Manager after the update entries.

Edit
I was trying to program this in a way where the user could enter the updates individually (name first, title second..) and update the dictionary for the key value (1234) with all three inputs to get my desired output.

Sorry if my code is a mess, I am learning python at the moment. Also sorry if my post is a mess, first time here as well.

答:
You .split method isn't working, as the user isn't inputting any spaces (' '). Instead change your code to updates = input().split(',')

that should fix one of the issues

Body:
For this part of my program, I need to write code that will allow the user to update the dictionary. The key is the employee ID, and the updatable fields are their name, department, and title. So that when the updated record is viewed it would display the new name, title, and department. Where Employees is the dictionary. This is what i have so far:

while Choice == '2':

    dict_key = input('Enter the employee ID of the employee to change the record: ')

    if dict_key in Employees:
        n = 3
        print('Enter the new Name, Department, and Title')
        for i in range(n):
            updates = input().split(' ')

        Employees[dict_key] = updates[0][1][2]
        print('\n')
    else:
        print('ERROR: That record does not exist!')
        print('\n')

    Continue = input('Press 1 to update another employee record or 2 to exit: ')
    print('\n')

    if Continue == '2':
        print('*' * 80)
        break

When running this code i get the following error:

Traceback (most recent call last):
line 43, in <module>
  Employees[dict_key] = updates[0][1][2]
IndexError: string index out of range

Desired output for ex:
If employee ID 1234 = John,IT,Programmer
and the updates were: John Doe, IT, Manager.

Employee ID 1234 should = John Doe,IT,Manager after the update entries.

Edit
I was trying to program this in a way where the user could enter the updates individually (name first, title second..) and update the dictionary for the key value (1234) with all three inputs to get my desired output.

Sorry if my code is a mess, I am learning python at the moment. Also sorry if my post is a mess, first time here as well.


问:
Why ImageView is not crossing the relativelayout
I have a ImageView within a RelativeLayout. RelativeLayout Height is fixed as 50dp and ImageView height is bigger that 50dp. I want my ImageView to cross the RelativeLayout.

I attach a screen that i want to implement.

```<code><RelativeLayout
android:id="@+id/btnMenu"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#000000"
            android:clipChildren="false"
            android:clipToPadding="false">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:background="@drawable/home_menu"
                android:layout_alignParentLeft="true"/>

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:background="@drawable/home_logo_bottom"
                android:layout_alignParentRight="true"/>

        </RelativeLayout>
</code>```

答:
RelativeLayout is the Parent and ImageView is a child inside it. The rule is, if the child is larger than the parent, the child will be clipped so that only whatever fits the parent is visible. So if the parent's height is 50dp, and the child's height is 100dp, You will only see the 50dp content of the child.

If you want to see (in this case) the full ImageView's content, then change the layout_height of the RelativeLayout to wrap_content. If you want to accomplish the layout as in the image, don't make the ImageView as a child of the RelativeLayout.

Body:
I have a ImageView within a RelativeLayout. RelativeLayout Height is fixed as 50dp and ImageView height is bigger that 50dp. I want my ImageView to cross the RelativeLayout.

I attach a screen that i want to implement.

<RelativeLayout
android:id="@+id/btnMenu"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#000000"
            android:clipChildren="false"
            android:clipToPadding="false">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:background="@drawable/home_menu"
                android:layout_alignParentLeft="true"/>

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:background="@drawable/home_logo_bottom"
                android:layout_alignParentRight="true"/>

        </RelativeLayout>


问:
navigation bar right bar button items spacing
I have created a
 with left bar button item added from storyboard, titleView and three right bar button items from code.

Here is the code:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    var screenWidth = UIScreen.mainScreen().bounds.width
    // custom title view
    var navBarWidth: CGFloat = self.navigationController!.navigationBar.frame.size.width
    let customTitleView = UIView(frame: CGRectMake(0, 0, navBarWidth, 44))
    titleLabel = UILabel(frame: CGRectMake(20, 0, navBarWidth, 40))
    titleLabel.text = conversationName
    if let titleFont = UIFont(name: "Roboto-Regular", size: 20) {
        titleLabel.font = titleFont
    }
    titleLabel.textColor = UIColor.whiteColor()

    customTitleView.addSubview(titleLabel)
    self.navigationItem.titleView = customTitleView

    // right bar buttons
    var searchImage = UIImage(named: "search")!
    var clipImage = UIImage(named: "clip")!
    var pencilImage = UIImage(named: "pencil")!

    var searchBtn = UIBarButtonItem(image: searchImage, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("searchBtnPressed"))
    searchBtn.tintColor = UIColor.whiteColor()
    var clipBtn = UIBarButtonItem(image: clipImage, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("clipBtnPressed"))
    clipBtn.tintColor = UIColor.whiteColor()
    var pencilBtn = UIBarButtonItem(image: pencilImage, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("pencilBtnPressed"))
    pencilBtn.tintColor = UIColor.whiteColor()

    self.navigationItem.setRightBarButtonItems([pencilBtn, clipBtn, searchBtn], animated: false)
}
</code>```

My problem is that I want to change the spacing between right buttons but I don't know how.

I've tried to add a fixedButton between them but it just increased the existing space.

Can some one help me? Thanks.

答:
Try to change the constraintEqualToConstant

```<code>[myUIButton.widthAnchor constraintEqualToConstant:24].active = YES;
[myUIButton.heightAnchor constraintEqualToConstant:24].active = YES;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created a
 with left bar button item added from storyboard, titleView and three right bar button items from code.

Here is the code:

override func viewDidLoad() {
    super.viewDidLoad()

    var screenWidth = UIScreen.mainScreen().bounds.width
    // custom title view
    var navBarWidth: CGFloat = self.navigationController!.navigationBar.frame.size.width
    let customTitleView = UIView(frame: CGRectMake(0, 0, navBarWidth, 44))
    titleLabel = UILabel(frame: CGRectMake(20, 0, navBarWidth, 40))
    titleLabel.text = conversationName
    if let titleFont = UIFont(name: "Roboto-Regular", size: 20) {
        titleLabel.font = titleFont
    }
    titleLabel.textColor = UIColor.whiteColor()

    customTitleView.addSubview(titleLabel)
    self.navigationItem.titleView = customTitleView

    // right bar buttons
    var searchImage = UIImage(named: "search")!
    var clipImage = UIImage(named: "clip")!
    var pencilImage = UIImage(named: "pencil")!

    var searchBtn = UIBarButtonItem(image: searchImage, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("searchBtnPressed"))
    searchBtn.tintColor = UIColor.whiteColor()
    var clipBtn = UIBarButtonItem(image: clipImage, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("clipBtnPressed"))
    clipBtn.tintColor = UIColor.whiteColor()
    var pencilBtn = UIBarButtonItem(image: pencilImage, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("pencilBtnPressed"))
    pencilBtn.tintColor = UIColor.whiteColor()

    self.navigationItem.setRightBarButtonItems([pencilBtn, clipBtn, searchBtn], animated: false)
}

My problem is that I want to change the spacing between right buttons but I don't know how.

I've tried to add a fixedButton between them but it just increased the existing space.

Can some one help me? Thanks.

Body:
Try to change the constraintEqualToConstant

[myUIButton.widthAnchor constraintEqualToConstant:24].active = YES;
[myUIButton.heightAnchor constraintEqualToConstant:24].active = YES;


问:
Is there a simple way to repeat a php mysql query?
I'm hoping there's a little trick to php that will save me 100's of copy>paste>change-number - thanks for taking a look!

I've got a relatively large dataset in a MySQL db.

There are just two columns: Models (about 7000 unique entries) and Manufacturers (about 100 unique ones, i.e. the models are from just 100 different manufacturers)

At the moment (well, as I am writing the very slow, repetitious way), I have a huge list of PHP database queries along the lines of:

$result = mysql_query("SELECT * FROM products WHERE manufacturer ='3M'" );

  while ($row = mysql_fetch_array($result)) {

  echo $row['manufacturer'] . " " . $row['model']; }

What I'm doing is working, but is there perhaps a way of getting a list of all manufacturers then running the php above on the list?

Or maybe something different I haven't thought about?

Thanks heaps,

(The actual outputting is done into a javascript accordian - so displaying it on a single page isn't an issue)

答:
Unique manufacturers

```<code>SELECT manufacturer
FROM products
GROUP BY manufacturer
</code>```

But I'm not positive what you want the end result to be. Can you elaborate on that, and I'll provide a more concise answer?

EDIT This should do what you're looking for (or at least is a good base for you to play with). This will place manufacturers as the header of the accordion, then list the models within.

```<code>$sql = "SELECT * FROM products ORDER BY manufacturer,product";
$lastMfg = null;
if (($result = mysql_query($sql)) !== false)
{
  echo '<div id="accordion">';
  while (($row = mysql_fetch_array($result)) !== false)
  {
    if ($row['manufacturer'] != $lastMfg)
    {
      if (!is_null($lastMfg))
        echo '</div>';
      echo '<h3><a href="#">'.$row['manufacturer'].'</a></h3>';
      echo '<div>';
      $lastMfg = $row['manufacturer'];
    }
    echo '<p>'.$row['model'].'</p>';
  }
  echo '</div></div>';
}
else
{
  echo '<p>MySQL Error: Unable to fetch products</p>';
}
</code>```

Again, if you can be more clear, a better solution can probably be concluded.

Body:
Unique manufacturers

SELECT manufacturer
FROM products
GROUP BY manufacturer

But I'm not positive what you want the end result to be. Can you elaborate on that, and I'll provide a more concise answer?

EDIT This should do what you're looking for (or at least is a good base for you to play with). This will place manufacturers as the header of the accordion, then list the models within.

$sql = "SELECT * FROM products ORDER BY manufacturer,product";
$lastMfg = null;
if (($result = mysql_query($sql)) !== false)
{
  echo '<div id="accordion">';
  while (($row = mysql_fetch_array($result)) !== false)
  {
    if ($row['manufacturer'] != $lastMfg)
    {
      if (!is_null($lastMfg))
        echo '</div>';
      echo '<h3><a href="#">'.$row['manufacturer'].'</a></h3>';
      echo '<div>';
      $lastMfg = $row['manufacturer'];
    }
    echo '<p>'.$row['model'].'</p>';
  }
  echo '</div></div>';
}
else
{
  echo '<p>MySQL Error: Unable to fetch products</p>';
}

Again, if you can be more clear, a better solution can probably be concluded.


问:
UWP - Reference StaticResource from different style resource dictionary: Failed to assign to property 'Windows.UI.Xaml.ResourceDictionary.Source'
Hello my team and I recently started developing an win10 uwp application. Application will have a lot of views and components so heavy use of styles is expected, so we need to organize our styles through file/folder structure we did this using following structure (unfortunately I cannot embed images yet see the link):

Anyways my Resource.xaml merges all other dictionaries as following:

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/Resources/Colors.xaml" />
        <ResourceDictionary Source="/Resources/Icons.xaml" />
        <ResourceDictionary Source="/Resources/Fonts.xaml" />
        <ResourceDictionary Source="/Resources/Converters.xaml" />
        <ResourceDictionary Source="/Resources/Buttons.xaml" />
        <ResourceDictionary Source="/Resources/RadioButton.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</code>```

And in my App.xaml I reference this dictionary:

```<code><Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/Resources.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
    </ResourceDictionary>
</Application.Resources>
</code>```

Now I managed to find the source of the problem in my RadioButton.xaml I reference a brush defined in Colors.xaml using StaticResource lookup:

```<code><Setter Property="Foreground" Value="{StaticResource TopMenuTextBrush}" />
</code>```

If I remove this line everything will start but with it I get following exception:

Exception   {Windows.UI.Xaml.Markup.XamlParseException: The text associated with this error code could not be found.

Failed to assign to property
  'Windows.UI.Xaml.ResourceDictionary.Source' because the type
  'Windows.Foundation.String' cannot be assigned to the type
  'Windows.Foundation.Uri'. [Line: 28 Position: 37]}    System.Exception
  {Windows.UI.Xaml.Markup.XamlParseException}

Interesting thing is when I start the app with this line commented and uncomment it visual studio will recognize the brush and apply it correctly, it only breaks on application start.
We used same approach before when developing WPF, so I'm thinking it might have to do with something regarding application deployment.

All help is greatly appreciated.

答:
Exception = {Windows.UI.Xaml.Markup.XamlParseException: The text associated with this error code could not be found.

The problem is that you have used wrong ResourceDictionary source . I found the Resources.xaml and other xaml file stored in the  same level directory in your screenshot. So you could not declare the parent directory of these xaml files within source. Please modify ResourceDictionary  like the following

```<code><ResourceDictionary Source="Colors.xaml"/>
</code>```

For more you could refer to ResourceDictionary and XAML resource references.

Body:
Hello my team and I recently started developing an win10 uwp application. Application will have a lot of views and components so heavy use of styles is expected, so we need to organize our styles through file/folder structure we did this using following structure (unfortunately I cannot embed images yet see the link):

Anyways my Resource.xaml merges all other dictionaries as following:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/Resources/Colors.xaml" />
        <ResourceDictionary Source="/Resources/Icons.xaml" />
        <ResourceDictionary Source="/Resources/Fonts.xaml" />
        <ResourceDictionary Source="/Resources/Converters.xaml" />
        <ResourceDictionary Source="/Resources/Buttons.xaml" />
        <ResourceDictionary Source="/Resources/RadioButton.xaml" />
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

And in my App.xaml I reference this dictionary:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/Resources.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
    </ResourceDictionary>
</Application.Resources>

Now I managed to find the source of the problem in my RadioButton.xaml I reference a brush defined in Colors.xaml using StaticResource lookup:

<Setter Property="Foreground" Value="{StaticResource TopMenuTextBrush}" />

If I remove this line everything will start but with it I get following exception:

Exception   {Windows.UI.Xaml.Markup.XamlParseException: The text associated with this error code could not be found.

Failed to assign to property
  'Windows.UI.Xaml.ResourceDictionary.Source' because the type
  'Windows.Foundation.String' cannot be assigned to the type
  'Windows.Foundation.Uri'. [Line: 28 Position: 37]}    System.Exception
  {Windows.UI.Xaml.Markup.XamlParseException}

Interesting thing is when I start the app with this line commented and uncomment it visual studio will recognize the brush and apply it correctly, it only breaks on application start.
We used same approach before when developing WPF, so I'm thinking it might have to do with something regarding application deployment.

All help is greatly appreciated.

Body:
Exception = {Windows.UI.Xaml.Markup.XamlParseException: The text associated with this error code could not be found.

The problem is that you have used wrong ResourceDictionary source . I found the Resources.xaml and other xaml file stored in the  same level directory in your screenshot. So you could not declare the parent directory of these xaml files within source. Please modify ResourceDictionary  like the following

<ResourceDictionary Source="Colors.xaml"/>

For more you could refer to ResourceDictionary and XAML resource references.


问:
In same expression, simultaneously use value and assign variable in Scala
Is there a way in Scala to assign a variable a value and at the same time use the value in the expression?  Like so...

```<code>java.lang.Math.abs(scala.util.Random.nextInt()) / {val num = java.lang.Math.pow(10, (java.lang.Math.abs(scala.util.Random.nextInt() % 5) + 1)) } * num
</code>```

I got this error...

```<code>cannot be applied to (Unit)
       java.lang.Math.abs(scala.util.Random.nextInt()) / {val num = java.lang.Math.pow(10, java.lang.Math.abs(scala.util.Random.nextInt() % 7)) } * num
</code>```

In order to round down to a variable exponentiation of the value '10', I want to assign some random integer to the variable "num" use the same value in an expression at same time. So then I can make sure num will be the same value for the divisor will be the same as the multiplier. I know I have seen something in scala that made me think I can do this...

答:
You might put your nums in a 2-element collection and then reduce() it.

```<code>Seq(Math.abs(util.Random.nextInt())
   ,Math.pow(10, Math.abs(util.Random.nextInt() % 5) + 1))
  .reduce((a,b) => /*use as many a's and b's as needed*/)
</code>```

Body:
Is there a way in Scala to assign a variable a value and at the same time use the value in the expression?  Like so...

java.lang.Math.abs(scala.util.Random.nextInt()) / {val num = java.lang.Math.pow(10, (java.lang.Math.abs(scala.util.Random.nextInt() % 5) + 1)) } * num

I got this error...

cannot be applied to (Unit)
       java.lang.Math.abs(scala.util.Random.nextInt()) / {val num = java.lang.Math.pow(10, java.lang.Math.abs(scala.util.Random.nextInt() % 7)) } * num

In order to round down to a variable exponentiation of the value '10', I want to assign some random integer to the variable "num" use the same value in an expression at same time. So then I can make sure num will be the same value for the divisor will be the same as the multiplier. I know I have seen something in scala that made me think I can do this...

Body:
You might put your nums in a 2-element collection and then reduce() it.

Seq(Math.abs(util.Random.nextInt())
   ,Math.pow(10, Math.abs(util.Random.nextInt() % 5) + 1))
  .reduce((a,b) => /*use as many a's and b's as needed*/)


问:
Java syntax in android studio
What I want to do is to click a space on the screen, get the coordinates and paint the image here. I did this using paintIcon and mouseListener in eclipse but how to do the same thing in android studio? Thanks!    </p>

```<code>public static Game game = new Game();

public Control(){
    this.setLayout(null);
    this.setBounds(0, 0, 780, 780);
    addMouseListener(this);
}

public void paint(Graphics g){
    setBackground(Color.GREEN);
    board.paintIcon(this, g, 0, 0);

    for(int i = 0; i < 19; i++){
        for(int j = 0; j < 19; j++){
            if(game.gameBoard.board[i][j] != 'E'){
                if(game.gameBoard.board[i][j] == 'B'){
                    black.paintIcon(this, g, j * 40, i * 40);
                }
                if(game.gameBoard.board[i][j] == 'W'){
                    white.paintIcon(this, g, j * 40, i * 40);
                }
            }
        }
    }
}

@Override
public void mouseClicked(MouseEvent e) {
    // TODO Auto-generated method stub
    mouseX = e.getX();
    mouseY = e.getY();
    int targetX = mouseX / 40;
    int targetY = mouseY / 40;
    game.move(targetX, targetY);
    repaint();
}
</code>```

答:
In Android you use a different system than in "Java"(you know Android is Java), for instance as is clear from your code you do not have a Mouse but a Touch event.
The first thing you should do is to study this official link that explains the concept of Canvas. Then you will learn how to integrate the "tap" into your app that is instead this official link

This is an excellent post to learn ho to do it.

You begin extending the View and overriding the method onDraw(Canvas canvas) then you need to override a listener that say you when the user clicked the screen onTouchEvent(MotionEvent event) usually there are three motion events you want to cover MotionEvent ACTION_DOWN(you tap and the screen recognizes the X,Y coordinates, that is the one you need),ACTION_MOVE(if you drag your finger maintaining pressure on the screen) and ACTION_UP(when you release your finger)

Just remember you need to call invalidate() if you have an animation or something changes on the screen. Basically is a "forced" call to the "onDraw" method. On the basis of the three links I sent you can cover all thebasis of the 2d graphics in Android that is a bit different by Java because of the different features but also the Android dependency on the specific SDK classes

what I want to do is to click a space on the screen, get the coordinates and paint the image here

Here is an example of how  you can obtain that in Android instead of "just" Java, please see the notes comments I did below with the double slashes //

```<code>public class YourBoard extends View {//EXTENDS VIEW this is important because you override methods

Drawable editIcon = getResources().getDrawable(R.drawable.icon);
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background);

float xPos = 0;
float yPos = 0;

public YourBoard (Context context) {//HERE THE CONSTRUCTOR YOU CAN INITIALIZE THINGS HERE

    super (context);
}
@Override
protected void onDraw (Canvas canvas) {//This was your paint(Graphics g)
    super.onDraw(canvas);

    canvas.save();
    canvas.drawBitmap(mBitmap, 0, 0, null);
    canvas.translate(xPos, yPos);
    editIcon.draw(canvas);
    canvas.restore();

}
@Override
public boolean onTouchEvent (MotionEvent event) {//THIS WAS YOUR MOUSE LISTENER

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN :
            xPos = event.getX();
            yPos = event.getY();
            invalidate();//NOTICE THE INVALIDATE I MENTIONED
            break;
    }

    return true;

}
}
}
</code>```

Title: Java syntax in android studio

Body:
What I want to do is to click a space on the screen, get the coordinates and paint the image here. I did this using paintIcon and mouseListener in eclipse but how to do the same thing in android studio? Thanks!

public static Game game = new Game();

public Control(){
    this.setLayout(null);
    this.setBounds(0, 0, 780, 780);
    addMouseListener(this);
}

public void paint(Graphics g){
    setBackground(Color.GREEN);
    board.paintIcon(this, g, 0, 0);

    for(int i = 0; i < 19; i++){
        for(int j = 0; j < 19; j++){
            if(game.gameBoard.board[i][j] != 'E'){
                if(game.gameBoard.board[i][j] == 'B'){
                    black.paintIcon(this, g, j * 40, i * 40);
                }
                if(game.gameBoard.board[i][j] == 'W'){
                    white.paintIcon(this, g, j * 40, i * 40);
                }
            }
        }
    }
}

@Override
public void mouseClicked(MouseEvent e) {
    // TODO Auto-generated method stub
    mouseX = e.getX();
    mouseY = e.getY();
    int targetX = mouseX / 40;
    int targetY = mouseY / 40;
    game.move(targetX, targetY);
    repaint();
}

Body:
In Android you use a different system than in "Java"(you know Android is Java), for instance as is clear from your code you do not have a Mouse but a Touch event.
The first thing you should do is to study this official link that explains the concept of Canvas. Then you will learn how to integrate the "tap" into your app that is instead this official link

This is an excellent post to learn ho to do it.

You begin extending the View and overriding the method onDraw(Canvas canvas) then you need to override a listener that say you when the user clicked the screen onTouchEvent(MotionEvent event) usually there are three motion events you want to cover MotionEvent ACTION_DOWN(you tap and the screen recognizes the X,Y coordinates, that is the one you need),ACTION_MOVE(if you drag your finger maintaining pressure on the screen) and ACTION_UP(when you release your finger)

Just remember you need to call invalidate() if you have an animation or something changes on the screen. Basically is a "forced" call to the "onDraw" method. On the basis of the three links I sent you can cover all thebasis of the 2d graphics in Android that is a bit different by Java because of the different features but also the Android dependency on the specific SDK classes

what I want to do is to click a space on the screen, get the coordinates and paint the image here

Here is an example of how  you can obtain that in Android instead of "just" Java, please see the notes comments I did below with the double slashes //

public class YourBoard extends View {//EXTENDS VIEW this is important because you override methods

Drawable editIcon = getResources().getDrawable(R.drawable.icon);
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background);

float xPos = 0;
float yPos = 0;

public YourBoard (Context context) {//HERE THE CONSTRUCTOR YOU CAN INITIALIZE THINGS HERE

    super (context);
}
@Override
protected void onDraw (Canvas canvas) {//This was your paint(Graphics g)
    super.onDraw(canvas);

    canvas.save();
    canvas.drawBitmap(mBitmap, 0, 0, null);
    canvas.translate(xPos, yPos);
    editIcon.draw(canvas);
    canvas.restore();

}
@Override
public boolean onTouchEvent (MotionEvent event) {//THIS WAS YOUR MOUSE LISTENER

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN :
            xPos = event.getX();
            yPos = event.getY();
            invalidate();//NOTICE THE INVALIDATE I MENTIONED
            break;
    }

    return true;

}
}
}


问:
Uncaught ReferenceError: FirebaseApp is not defined or Uncaught ReferenceError: firebase is not defined
I am declaring the namespaces like:

```<code>declare namespace firebase.database.ServerValue {
    var TIMESTAMP: any
}
</code>```

and getting this error

Uncaught ReferenceError: firebase is not defined

```<code>declare namespace FirebaseApp.Timestamp{
    var TIMESTAMP: any;
}
</code>```

and getting error:

Uncaught ReferenceError: FirebaseApp is not defined

angularFire2 and firebase version:

```<code>"angularfire2": "^4.0.0-rc.1",
"firebase": "^4.1.3",
</code>```

cli packages:

```<code>@ionic/cli-plugin-cordova       : 1.5.0 (C:\....\node_modules\@ionic\cli-plugin-cordova)
@ionic/cli-plugin-ionic-angular : 1.4.0 (C:\....\node_modules\@ionic\cli-plugin-ionic-angular)
@ionic/cli-utils                : 1.6.0 (C:\....\node_modules\@ionic\cli-utils)
ionic (Ionic CLI)               : 3.6.0 (C:\....\node_modules\ionic)
</code>```

global packages:

```<code>Cordova CLI : 7.0.1
</code>```

local packages:

```<code>@ionic/app-scripts : 2.1.4
Cordova Platforms  : android 6.3.0
Ionic Framework    : ionic-angular 3.6.0
</code>```

System:

```<code>Android SDK Tools : 25.2.5
Node              : v6.11.1
OS                : Windows 7
npm               : 5.1.0
</code>```

How to solve these issue? because I want to get the value of TIMESTEMP by declaring any of above mentioned namespace.

答:
Problem solved!

step1- Upgrading to AngularFire 5.0

Step2 -

```<code>.......
......
.....

import * as firebase from 'firebase';
export class .....  {
lastMessageTime: any;
   consturctor(){
      lastMessageTime = firebase.database.ServerValue.TIMESTAMP;
    }
}
</code>```

Body:
I am declaring the namespaces like:

declare namespace firebase.database.ServerValue {
    var TIMESTAMP: any
}

and getting this error

Uncaught ReferenceError: firebase is not defined

declare namespace FirebaseApp.Timestamp{
    var TIMESTAMP: any;
}

and getting error:

Uncaught ReferenceError: FirebaseApp is not defined

angularFire2 and firebase version:

"angularfire2": "^4.0.0-rc.1",
"firebase": "^4.1.3",

cli packages:

@ionic/cli-plugin-cordova       : 1.5.0 (C:\....\node_modules\@ionic\cli-plugin-cordova)
@ionic/cli-plugin-ionic-angular : 1.4.0 (C:\....\node_modules\@ionic\cli-plugin-ionic-angular)
@ionic/cli-utils                : 1.6.0 (C:\....\node_modules\@ionic\cli-utils)
ionic (Ionic CLI)               : 3.6.0 (C:\....\node_modules\ionic)

global packages:

Cordova CLI : 7.0.1

local packages:

@ionic/app-scripts : 2.1.4
Cordova Platforms  : android 6.3.0
Ionic Framework    : ionic-angular 3.6.0

System:

Android SDK Tools : 25.2.5
Node              : v6.11.1
OS                : Windows 7
npm               : 5.1.0

How to solve these issue? because I want to get the value of TIMESTEMP by declaring any of above mentioned namespace.

Body:
Problem solved!

step1- Upgrading to AngularFire 5.0

Step2 -

.......
......
.....

import * as firebase from 'firebase';
export class .....  {
lastMessageTime: any;
   consturctor(){
      lastMessageTime = firebase.database.ServerValue.TIMESTAMP;
    }
}


问:
Coding Standard Wiki
At my place of work I've been put in charge of creating a coding standards document. Generally we follow what FxCop and StyleCop tools report to some degree but what we really require is document that will explain when to use a convention, why and maybe even a simple example.

This could be extended in the future for other purposes as well.

The first thing that came to my mind is to have an internal wiki site that we could build up and change easily over time but I've never used a wiki-based engine before and would like some recommendations.

If possible the engine should be in C# so we're able to tweak it to our needs if required.

If you think a wiki solution is the wrong way to go about this then please give an alternative :)

Update

I've just been informed, although we do have a php server it wont be staying, so I'm afraid php-based wiki ideas are off the table.

Update 2

Could you also (if possible) let me know if any of these solutions work with Active Directory?

Cheers
Tony

答: ScrewTurn Wiki is an free and open-source wiki made in C# and ASP.Net. Different database back-ends can be used, like MSSQL and MySQL, but also works without any database. It has several plugins to work with Active Directory.</p>

Title: Coding Standard Wiki

OwnerDisplayName: Lars Truijens


问:
remove link from the l() function in drupal after the first click
How does one remove the hyperlink from the l() function after the first click. A working example would be helpful.
 My link is of the form

  l(25,$_GET['q'],array('query'=>array("itemcount"=>"25")));

答: You...don't use the l() function then? It's for creating a link.</p>


问:
Finding the largest possible bit for a specific type
What is the cleanest method for finding the largest possible bit of a specific type in C?

I have found two methods that seem to work thus far:

```<code>type value = ~(((type) - 1) >> 1);
</code>```

and

```<code>type value = 1 << ((sizeof(type) * CHAR_BIT) - 1);
</code>```

What I'm trying to do here is get a value that represents the largest bit that you can set in any type, ie, for char (8 bits), that would be:

```<code>10000000b
</code>```

Which is what the above two lines do. Is there any better way of handling this? Are there any obvious downsides to using either of the above lines to calculate this?

答:
Your methods work almost for unsigned types.
In the second case, you just forgot to convert the 1 to the target type before doing the shift.

```<code>type value = ((type)1) << ((sizeof(type) * CHAR_BIT) - 1);
</code>```

For signed types they are not portable:

the first because the sign representation might not be two's complement

the second because shifting into the sign bit is undefined

For a signed type the easiest should be to bit-complement the maximal value, e.g

```<code>~INT_MAX
</code>```

"Usually" this is the same value as INT_MIN (and similar for other types), but on weird architectures it might be a negative 0 or even a trap.

Body:
What is the cleanest method for finding the largest possible bit of a specific type in C?

I have found two methods that seem to work thus far:

type value = ~(((type) - 1) >> 1);

and

type value = 1 << ((sizeof(type) * CHAR_BIT) - 1);

What I'm trying to do here is get a value that represents the largest bit that you can set in any type, ie, for char (8 bits), that would be:

10000000b

Which is what the above two lines do. Is there any better way of handling this? Are there any obvious downsides to using either of the above lines to calculate this?

Body:
Your methods work almost for unsigned types.
In the second case, you just forgot to convert the 1 to the target type before doing the shift.

type value = ((type)1) << ((sizeof(type) * CHAR_BIT) - 1);

For signed types they are not portable:

the first because the sign representation might not be two's complement

the second because shifting into the sign bit is undefined

For a signed type the easiest should be to bit-complement the maximal value, e.g

~INT_MAX

"Usually" this is the same value as INT_MIN (and similar for other types), but on weird architectures it might be a negative 0 or even a trap.


问:
trace patterns such that each node is visited only once(eulerian path) using opencv
Here is my problem which I am trying to solve since one complete year. With no success till end of the year. I have to seek help and a concrete solutions from the stackoverflow experts.

My problem statement:

I have been working with some design patterns which I want to trace if eulerian path exist(as shown in below gifs), programmatically. Below are the patterns and the way I wanna draw them(gifs).

What I wanna achieve:

Give the design pattern images as input. I want trace the design pattern image in a single stroke as shown in the gifs(gifs animations are just examples of how the patterns is drawn in single stroke). Once I get the x and y coordinates of the image in single stroke fashion(eulerian path). I will feed those coordinates to my program to just trace those coordinates.

Thing to be noted in the animation:

1) basically its an undetected graph (the nodes being the vertices of your shapes, the edges if exists being the strokes between 2 vertices). (eulerian path)

Here are the 15 unique shapes which I used to build the patterns with:

I have more then 400 patterns(3 patterns already shown below) and till now I am not able to find a generic solution for this. I have manually got the x y coordinates of the patterns and placed it in sequence. But that is not at all scalable.

How to trace the patterns such that each node is visited only once ?:

1st kind of pattern and the way it should be drawn:

2nd kind of pattern and the way it should be drawn:

3rd kind of pattern and the way it should be drawn:

答:
Perhaps you can look into the traveling salesman problem if your still struggling with the above. TSP visits cities only once. And if in your case each node is a crossing for your strike-through then this might help.

Check here for the python code to look at. I've checked and the print statement looks nice and structured. Well done cMinor!

Edit based on discussion: file 1, file2, file3.


问:
Cassandra: Error: code=2200 [Invalid query] message="PRIMARY KEY column cannot be restricted as preceding column
Table Schema:

```<code>CREATE TABLE com (
    receiverid text,
    senderid text,
    commatriid text,
    comtype tinyint,
    comid text,
    displaystatus tinyint,
    comdate timestamp,
    cominfoid bigint,
    comstatus tinyint,
    dateactioned timestamp,
    datedeleted timestamp,
    dateread timestamp,
    dateupdated timestamp,
    disclosedmatriid tinyint,
    filteredmsg tinyint,
    message text,
    recentstatus tinyint,
    regionallang tinyint,
    transmsg text,
    PRIMARY KEY (receiverid, senderid, commatriid, comtype, comid, displaystatus, comdate)
) WITH CLUSTERING ORDER BY (senderid ASC, commatriid ASC, comtype ASC, comid ASC, displaystatus ASC, comdate ASC);
</code>```

Select query with where clause:

```<code>SELECT ComInfoId,ComId,ComType,SenderId,ReceiverId,ComMatriId,ComDate,ComStatus FROM com WHERE ComMatriId='M1'AND SenderId='M79984222' and ReceiverId='M2' and ComDate <= '2017-11-14 09:20:05+0000';
</code>```

ERROR:

InvalidRequest: Error from server: code=2200 [Invalid query]
  message="PRIMARY KEY column "comdate" cannot be restricted as
  preceding column "comtype" is not restricted"

what is primary key column restricted as proceding column?
if remove the comDate date in where clause ,i m able to retrive the data

答:
Delete commatriid from where clause in select query and then check the output once..
I guess, a query like this should not happen with multiple clustering keys in the query search keys. Correct me if I am wrong.

This may help you:  https://www.datastax.com/dev/blog/a-deep-look-to-the-cql-where-clause

Body:
Table Schema:

CREATE TABLE com (
    receiverid text,
    senderid text,
    commatriid text,
    comtype tinyint,
    comid text,
    displaystatus tinyint,
    comdate timestamp,
    cominfoid bigint,
    comstatus tinyint,
    dateactioned timestamp,
    datedeleted timestamp,
    dateread timestamp,
    dateupdated timestamp,
    disclosedmatriid tinyint,
    filteredmsg tinyint,
    message text,
    recentstatus tinyint,
    regionallang tinyint,
    transmsg text,
    PRIMARY KEY (receiverid, senderid, commatriid, comtype, comid, displaystatus, comdate)
) WITH CLUSTERING ORDER BY (senderid ASC, commatriid ASC, comtype ASC, comid ASC, displaystatus ASC, comdate ASC);

Select query with where clause:

SELECT ComInfoId,ComId,ComType,SenderId,ReceiverId,ComMatriId,ComDate,ComStatus FROM com WHERE ComMatriId='M1'AND SenderId='M79984222' and ReceiverId='M2' and ComDate <= '2017-11-14 09:20:05+0000';

ERROR:

InvalidRequest: Error from server: code=2200 [Invalid query]
  message="PRIMARY KEY column "comdate" cannot be restricted as
  preceding column "comtype" is not restricted"

what is primary key column restricted as proceding column?
if remove the comDate date in where clause ,i m able to retrive the data


问:
How to prevent Core NLP Pos Tagger from tokenizing?
I use the the core NLP Parser to tokenize my text. Example "...dem späteren Papst Benedikt XVI., in der Glaubenskongergation..."

Now the problem is, when I use the parser to tokenize my text I get a token with "XVI." which is correct. But when I use this token with the Core NLP Pos Tagger, I get two tokens back [u'XVI', u'NE'], [u'.', u'$.'] which I don't want. Can I somehow restict the tagger to the original tokens?

答:
If you run a pipeline on that text it should tokenize properly.

Here is the sample command:

```<code>java -Xmx8g edu.stanford.nlp.pipeline.StanfordCoreNLP -props StanfordCoreNLP-german.properties -file example-1.txt -outputFormat text
</code>```

You need the full Stanford CoreNLP release to do this, and you need the German models jar.

Those resources are all available here: https://stanfordnlp.github.io/CoreNLP/download.html

For reference, these are the German properties (which get used when you specify using the German properties file as in the command above):

```<code>annotators = tokenize, ssplit, pos, ner, parse

tokenize.language = de

pos.model = edu/stanford/nlp/models/pos-tagger/german/german-hgc.tagger

ner.model = edu/stanford/nlp/models/ner/german.conll.hgc_175m_600.crf.ser.gz
ner.applyNumericClassifiers = false
ner.useSUTime = false

parse.model = edu/stanford/nlp/models/lexparser/germanFactored.ser.gz

# depparse
depparse.model    = edu/stanford/nlp/models/parser/nndep/UD_German.gz
depparse.language = german
</code>```

The command above will create a human readable output file with both the parse tree and all of the pos tags.  There are a variety of ways to run a pipeline.  One is the command line command shown above, you can also run one with the Java API.

More details here: https://stanfordnlp.github.io/CoreNLP/cmdline.html
and here: https://stanfordnlp.github.io/CoreNLP/api.html

Body:
If you run a pipeline on that text it should tokenize properly.

Here is the sample command:

java -Xmx8g edu.stanford.nlp.pipeline.StanfordCoreNLP -props StanfordCoreNLP-german.properties -file example-1.txt -outputFormat text

You need the full Stanford CoreNLP release to do this, and you need the German models jar.

Those resources are all available here: https://stanfordnlp.github.io/CoreNLP/download.html

For reference, these are the German properties (which get used when you specify using the German properties file as in the command above):

annotators = tokenize, ssplit, pos, ner, parse

tokenize.language = de

pos.model = edu/stanford/nlp/models/pos-tagger/german/german-hgc.tagger

ner.model = edu/stanford/nlp/models/ner/german.conll.hgc_175m_600.crf.ser.gz
ner.applyNumericClassifiers = false
ner.useSUTime = false

parse.model = edu/stanford/nlp/models/lexparser/germanFactored.ser.gz

# depparse
depparse.model    = edu/stanford/nlp/models/parser/nndep/UD_German.gz
depparse.language = german

The command above will create a human readable output file with both the parse tree and all of the pos tags.  There are a variety of ways to run a pipeline.  One is the command line command shown above, you can also run one with the Java API.

More details here: https://stanfordnlp.github.io/CoreNLP/cmdline.html
and here: https://stanfordnlp.github.io/CoreNLP/api.html


问:
Disabling a form based on the other form's input
I am currently working on 2 drop down forms, say form1 and form2. I have a certain list of values in form1 clicking which form2 would be disabled and for some it would not be disabled. I am working on Angular 4 with TypeScript. Any place where I could start figuring out how to achieve this?

Below is my form code

```<code>  <div class="form-group" style="width: 350px">
      <label for="form_periodicity"><b>Periodicity</b></label><br>
      <select class="form-control" id="periodicity" style="width: 222px">
        <option>EOD</option>
        <option>Daily</option>
        <option>Weekly</option>
        <option>Monthly</option>
        <option>Strict run</option>
      </select>
  </div>
  <div class="form-group" style="width: 350px">
      <label for="form_timeofexecution"><b>Time of execution</b></label><br>
      <select class="form-control" id="timeofexecution" style="width: 222px">
        <option>0:00</option>
        <option>0:30</option>
        <option>1:00</option>
        <option>4:00</option>
        <option>5:00</option>
      </select>
  </div>
</code>```

So I want to disable the second form group when Strict run is selected from the first form.

答:
You can do this with a simple JS event listener.

I assume this is what you wanna do:

window.addEventListener('load', function(){
  document.getElementById('periodicity').addEventListener('click', function(e){
    if(e.target.value == 'Strict run' )
      document.getElementById('dayofexecution').disabled = true;
    else
      document.getElementById('dayofexecution').disabled = false;
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="form-group" style="width: 350px">
      <label for="form_periodicity"><b>Periodicity</b></label><br>
      <select class="form-control" id="periodicity" style="width: 222px">
        <option>EOD</option>
        <option>Daily</option>
        <option>Weekly</option>
        <option>Monthly</option>
        <option>Strict run</option>
      </select>
  </div>
  <div class="form-group" style="width: 350px">
      <label for="form_dayofexecution"><b>Time of execution</b></label><br>
      <select class="form-control" id="dayofexecution" style="width: 222px">
        <option>0:00</option>
        <option>0:30</option>
        <option>1:00</option>
        <option>4:00</option>
        <option>5:00</option>
      </select>
  </div></code>```

Body:
I am currently working on 2 drop down forms, say form1 and form2. I have a certain list of values in form1 clicking which form2 would be disabled and for some it would not be disabled. I am working on Angular 4 with TypeScript. Any place where I could start figuring out how to achieve this?

Below is my form code

      Periodicity

      <select class="form-control" id="periodicity" style="width: 222px">
        <option>EOD</option>
        <option>Daily</option>
        <option>Weekly</option>
        <option>Monthly</option>
        <option>Strict run</option>
      </select>

      Time of execution

      <select class="form-control" id="timeofexecution" style="width: 222px">
        <option>0:00</option>
        <option>0:30</option>
        <option>1:00</option>
        <option>4:00</option>
        <option>5:00</option>
      </select>

So I want to disable the second form group when Strict run is selected from the first form.

Body:
You can do this with a simple JS event listener.

I assume this is what you wanna do:

window.addEventListener('load', function(){
  document.getElementById('periodicity').addEventListener('click', function(e){
    if(e.target.value == 'Strict run' )
      document.getElementById('dayofexecution').disabled = true;
    else
      document.getElementById('dayofexecution').disabled = false;
  })
});

  <div class="form-group" style="width: 350px">
      <label for="form_periodicity"><b>Periodicity</b></label><br>
      <select class="form-control" id="periodicity" style="width: 222px">
        <option>EOD</option>
        <option>Daily</option>
        <option>Weekly</option>
        <option>Monthly</option>
        <option>Strict run</option>
      </select>
  </div>
  <div class="form-group" style="width: 350px">
      <label for="form_dayofexecution"><b>Time of execution</b></label><br>
      <select class="form-control" id="dayofexecution" style="width: 222px">
        <option>0:00</option>
        <option>0:30</option>
        <option>1:00</option>
        <option>4:00</option>
        <option>5:00</option>
      </select>
  </div>


问:
Passing the navigation object down the nested react component
My react component hierarchy looks like

```<code>StackNavigation
  - MainScreen
      - List
          - Row
              - Button
</code>```

My usecase involves go to a new screen on click of the button. My main screen receives react-navigation's navigation props. How do I pass it down to my button in a sane manner.

答: You'd better pass a callback to your button through all the hierarchy and call it when button is pressed. Afterwards when you know which button is pressed (on which row) you can navigate to necessary screen from your MainScreen.</p>

Body:
My react component hierarchy looks like

StackNavigation
  - MainScreen
      - List
          - Row
              - Button

My usecase involves go to a new screen on click of the button. My main screen receives react-navigation's navigation props. How do I pass it down to my button in a sane manner.


问:
Element-wise mutiplication .* of vectors gives matrix in Matlab
Given two vectors

```<code>a = 1:3;
b = 2:4;
</code>```

it's well known that the element-wise mutiplication a.*b produces

```<code>[ 2  6  12 ]
</code>```

Calling that result c, we have c(i) = a(i)*b(i)

But I don't understand how a.*b', b'.*a and b'*a all produce

```<code>[ 2     4     6
  3     6     9
  4     8    12 ]
</code>```

For the matrix multiplication b'*a, we know c(i,j) = b(i)*a(j).

But why do the other two also produce the same result?

答:
Due to implicit expansion (introduced in 2016b) it's essentially the same as using bsxfun.

But what does that mean?

Setup:

```<code>a = 1:3;
b = 2:4;
</code>```

All MATLAB versions:

```<code>c = a.*b;
% c = [2 6 12], element-wise multiplication c(j) = a(j)*b(j)

c = b'*a;
% c = [2 4 5; 3 6 9; 4 8 12]
% standard matrix multiplication of vectors
% c(i,j) = a(i) + b(j)

c = bsxfun(@times, b', a)
% c = [2 4 5; 3 6 9; 4 8 12]
% bsxfun applies the function (in this case @times) to b' and a
</code>```

By definition, bsxfun "applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled". This means that singleton dimensions (dimensions whose size is 1) are expanded row-wise/column-wise to match the size of the other argument supplied to bsxfun.

So, bsxfun(@times, b', a) is equivalent to

```<code> % b' in singleton in the 2nd dimension, a is singleton in the 1st dimension
 % Use repmat to perform the expansion to the correct size
 repmat(b', 1, size(a,2)) .* repmat(a, size(b',1), 1)
 % Equivalent to...
 repmat(b', 1, 3) .* repmat(a, 3, 1)
 % Equivalent to...
 [2 2 2; 3 3 3; 4 4 4] .* [1 2 3; 1 2 3; 1 2 3]
 % = [2 4 5; 3 6 9; 4 8 12] the same as b'*a
</code>```

Before R2016b

```<code>c = a.*b'; % Error: Matrix dimensions must agree.
c = b'.*a; % Error: Matrix dimensions must agree.
</code>```

Since R2016b

Newer MATLAB versions use implicit expansion, which basically means that a bsxfun equivalent is called 'under the hood' if necessary for a valid operation.

```<code>c = a.*b'; % [2 4 5; 3 6 9; 4 8 12] the same as bsxfun(@times, a, b')
c = b'.*a; % [2 4 5; 3 6 9; 4 8 12] the same as bsxfun(@times, b', a)
% These two are equivalent also because order of operations is irrelevant
% We can see this by thinking about the expansion discussed above
</code>```

As you've noticed, this can be confusing if you don't keep track of your vector orientations! If you ever want to get a 1D output (without expansion), then you can ensure your inputs are 1D column vectors by using the colon operator like so

```<code>c = a(:).*b(:); % c = [2; 6; 12] always a column vector
</code>```

Body:
Given two vectors

a = 1:3;
b = 2:4;

it's well known that the element-wise mutiplication a.*b produces

[ 2  6  12 ]

Calling that result c, we have c(i) = a(i)*b(i)

But I don't understand how a.*b', b'.*a and b'*a all produce

[ 2     4     6
  3     6     9
  4     8    12 ]

For the matrix multiplication b'*a, we know c(i,j) = b(i)*a(j).

But why do the other two also produce the same result?

Body:
Due to implicit expansion (introduced in 2016b) it's essentially the same as using bsxfun.

But what does that mean?

Setup:

a = 1:3;
b = 2:4;

All MATLAB versions:

c = a.*b;
% c = [2 6 12], element-wise multiplication c(j) = a(j)*b(j)

c = b'*a;
% c = [2 4 5; 3 6 9; 4 8 12]
% standard matrix multiplication of vectors
% c(i,j) = a(i) + b(j)

c = bsxfun(@times, b', a)
% c = [2 4 5; 3 6 9; 4 8 12]
% bsxfun applies the function (in this case @times) to b' and a

By definition, bsxfun "applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled". This means that singleton dimensions (dimensions whose size is 1) are expanded row-wise/column-wise to match the size of the other argument supplied to bsxfun.

So, bsxfun(@times, b', a) is equivalent to

 % b' in singleton in the 2nd dimension, a is singleton in the 1st dimension
 % Use repmat to perform the expansion to the correct size
 repmat(b', 1, size(a,2)) .* repmat(a, size(b',1), 1)
 % Equivalent to...
 repmat(b', 1, 3) .* repmat(a, 3, 1)
 % Equivalent to...
 [2 2 2; 3 3 3; 4 4 4] .* [1 2 3; 1 2 3; 1 2 3]
 % = [2 4 5; 3 6 9; 4 8 12] the same as b'*a

Before R2016b

c = a.*b'; % Error: Matrix dimensions must agree.
c = b'.*a; % Error: Matrix dimensions must agree.

Since R2016b

Newer MATLAB versions use implicit expansion, which basically means that a bsxfun equivalent is called 'under the hood' if necessary for a valid operation.

c = a.*b'; % [2 4 5; 3 6 9; 4 8 12] the same as bsxfun(@times, a, b')
c = b'.*a; % [2 4 5; 3 6 9; 4 8 12] the same as bsxfun(@times, b', a)
% These two are equivalent also because order of operations is irrelevant
% We can see this by thinking about the expansion discussed above

As you've noticed, this can be confusing if you don't keep track of your vector orientations! If you ever want to get a 1D output (without expansion), then you can ensure your inputs are 1D column vectors by using the colon operator like so

c = a(:).*b(:); % c = [2; 6; 12] always a column vector


问:
babelfy.properties is missing in Java
I am trying to disambiguate a list of words using BabelFy. I started with the example provided in API page of Babelfy. but I got the Error about the "key" that I got from Babelfy.
I already filled the file with the key. but it says it it empty.

```<code>Nov 02, 2017 4:23:03 PM it.uniroma1.lcl.babelfy.commons.BabelfyConfiguration <init>
INFO: babelfy.properties is missing. Please check that the file is available
in the config folder.
Nov 02, 2017 4:23:03 PM it.uniroma1.lcl.babelfy.commons.BabelfyConfiguration
<init>
INFO: Babelfy starts with empty configuration
Exception in thread "main" java.lang.IllegalArgumentException: Please define
the parameter babelfy.key in babelfy.properties in the config folder.
</code>```

here is my code:

```<code>public class WSDBabelfy {
    public static void main (String args[]){
        String inputText = "BabelNet is both a multilingual encyclopedic dictionary and a semantic network";
        BabelfyConstraints constraints = new BabelfyConstraints();
        SemanticAnnotation a = new SemanticAnnotation(new TokenOffsetFragment(0, 0), "<the key>",
                "http://dbpedia.org/resource/BabelNet", SemanticAnnotation.Source.OTHER);

        constraints.addAnnotatedFragments(a);
        BabelfyParameters bp = new BabelfyParameters();
        bp.setAnnotationResource(BabelfyParameters.SemanticAnnotationResource.BN);
        bp.setMCS(BabelfyParameters.MCS.ON_WITH_STOPWORDS);
        bp.setScoredCandidates(BabelfyParameters.ScoredCandidates.ALL);
        Babelfy bfy = new Babelfy(bp);
        List<SemanticAnnotation> bfyAnnotations = bfy.babelfy(inputText, Language.EN, constraints);
    //bfyAnnotations is the result of Babelfy.babelfy() call
        for (SemanticAnnotation annotation : bfyAnnotations)
        {
            //splitting the input text using the CharOffsetFragment start and end anchors
            String frag = inputText.substring(annotation.getCharOffsetFragment().getStart(),
                    annotation.getCharOffsetFragment().getEnd() + 1);
            System.out.println(frag + "\t" + annotation.getBabelSynsetID());
            System.out.println("\t" + annotation.getBabelNetURL());
            System.out.println("\t" + annotation.getDBpediaURL());
            System.out.println("\t" + annotation.getSource());
        }
    }
}
</code>```

and here is properties file

```<code>babelfy.key=<the key>
</code>```

答:
I did experience the same issue, is the config folder well at the root of the project? Also, do you include it in the classpath as in the example below (or in your IDE)?

java -classpath lib/*:babelfy-online-1.0.jar:config it.uniroma1.lcl.babelfy.demo.BabelfyDemo

Title: babelfy.properties is missing in Java

Body:
I am trying to disambiguate a list of words using BabelFy. I started with the example provided in API page of Babelfy. but I got the Error about the "key" that I got from Babelfy.
I already filled the file with the key. but it says it it empty.

Nov 02, 2017 4:23:03 PM it.uniroma1.lcl.babelfy.commons.BabelfyConfiguration <init>
INFO: babelfy.properties is missing. Please check that the file is available
in the config folder.
Nov 02, 2017 4:23:03 PM it.uniroma1.lcl.babelfy.commons.BabelfyConfiguration
<init>
INFO: Babelfy starts with empty configuration
Exception in thread "main" java.lang.IllegalArgumentException: Please define
the parameter babelfy.key in babelfy.properties in the config folder.

here is my code:

public class WSDBabelfy {
    public static void main (String args[]){
        String inputText = "BabelNet is both a multilingual encyclopedic dictionary and a semantic network";
        BabelfyConstraints constraints = new BabelfyConstraints();
        SemanticAnnotation a = new SemanticAnnotation(new TokenOffsetFragment(0, 0), "<the key>",
                "http://dbpedia.org/resource/BabelNet", SemanticAnnotation.Source.OTHER);

        constraints.addAnnotatedFragments(a);
        BabelfyParameters bp = new BabelfyParameters();
        bp.setAnnotationResource(BabelfyParameters.SemanticAnnotationResource.BN);
        bp.setMCS(BabelfyParameters.MCS.ON_WITH_STOPWORDS);
        bp.setScoredCandidates(BabelfyParameters.ScoredCandidates.ALL);
        Babelfy bfy = new Babelfy(bp);
        List<SemanticAnnotation> bfyAnnotations = bfy.babelfy(inputText, Language.EN, constraints);
    //bfyAnnotations is the result of Babelfy.babelfy() call
        for (SemanticAnnotation annotation : bfyAnnotations)
        {
            //splitting the input text using the CharOffsetFragment start and end anchors
            String frag = inputText.substring(annotation.getCharOffsetFragment().getStart(),
                    annotation.getCharOffsetFragment().getEnd() + 1);
            System.out.println(frag + "\t" + annotation.getBabelSynsetID());
            System.out.println("\t" + annotation.getBabelNetURL());
            System.out.println("\t" + annotation.getDBpediaURL());
            System.out.println("\t" + annotation.getSource());
        }
    }
}

and here is properties file

babelfy.key=<the key>


问:
Convert : to comma separated value
I came across a row which has multiple values separated by a colon (:).
SQL considers the values to be one and throws an error" Cannot fine the requested Privilege". Example of the row shown below.

```<code>Servername  Instancename    Databasename Environment userid      access
ITSUSMPW01430   ITSUSMPW01430   ALL        DEV       userid SYSADMIN:SERVERADMIN
</code>```

Here 2 roles are requested seperated by :
Need some assistance on how can we make SQL consider the values different?

答:
I resolved the issue by modifying the below code.

```<code>where ':'  + access + ':' like '%:' + 'SERVERADMIN' + ':%'
</code>```

Since we need to differentiate the roles seperated by : in the same column, I used the below query and it worked successfully for 2 as well as more values.

```<code>select access from table1 where access like '%:' and access like ':%';
</code>```

Thank you Gordon for the pseudo code.

Title: Convert : to comma separated value

Body:
I came across a row which has multiple values separated by a colon (:).
SQL considers the values to be one and throws an error" Cannot fine the requested Privilege". Example of the row shown below.

Servername  Instancename    Databasename Environment userid      access
ITSUSMPW01430   ITSUSMPW01430   ALL        DEV       userid SYSADMIN:SERVERADMIN

Here 2 roles are requested seperated by :
Need some assistance on how can we make SQL consider the values different?

Body:
I resolved the issue by modifying the below code.

where ':'  + access + ':' like '%:' + 'SERVERADMIN' + ':%'

Since we need to differentiate the roles seperated by : in the same column, I used the below query and it worked successfully for 2 as well as more values.

select access from table1 where access like '%:' and access like ':%';

Thank you Gordon for the pseudo code.


问:
My Python regular expression is not matching any data in my text file for YYYY date format
I have a text file that contains dates in different formats. e.g.

2014

2015

January 7, 2015

6th January 2012

.

.

etc.

Now, I am trying to write a regular expression to print all the dates that are in YYYY format in the .txt file such as 2014, 2015.

However, I am not getting any matches from the code I executed. Could anyone please help with the problem ? Thanks.

My Python Code:

```<code>import re

for i in "file.txt":

    match = re.match(r'\d{2}-\d{2}-(\d{4})', i)

    print(match)
</code>```

Current Output:

```<code>None

None

None

None

None

None
</code>```

答:
Try this peace of code.

dates.txt looks like this

```<code>2014
2015
January 7, 2015
6th January 2012
</code>```

and here is the code to extract only year in YYYY format.

```<code>>>> f = open("/Users/kgowda/Desktop/my_work/play/dates.txt",'r')
>>> [re.search(r'\d{4}', x).group() for x in f.readlines() if x]
['2014', '2015', '2015', '2012']
</code>```

If you want to remove duplicates, use set

```<code>>>> set([re.search(r'\d{4}', x).group() for x in f.readlines() if x])
set(['2015', '2014', '2012'])
</code>```

If you text file contents like below

```<code>2014
2015
January 7, 2015
6th January 2012
0,2006 1,2007 2,2008 3,4 March 2014 4,"April 10, 2013" 5,7 August 2007
</code>```

Use findall to get YYYY.

```<code>>>> [re.findall(r'\d{4}', x) for x in f.readlines() if x]
[['2014'], ['2015'], ['2015'], ['2012'], ['2006', '2007', '2008', '2014', '2013', '2007']]
</code>```

Body:
I have a text file that contains dates in different formats. e.g.

2014

2015

January 7, 2015

6th January 2012

.

.

etc.

Now, I am trying to write a regular expression to print all the dates that are in YYYY format in the .txt file such as 2014, 2015.

However, I am not getting any matches from the code I executed. Could anyone please help with the problem ? Thanks.

My Python Code:

import re

for i in "file.txt":

    match = re.match(r'\d{2}-\d{2}-(\d{4})', i)

    print(match)

Current Output:

None

None

None

None

None

None

Body:
Try this peace of code.

dates.txt looks like this

2014
2015
January 7, 2015
6th January 2012

and here is the code to extract only year in YYYY format.

>>> f = open("/Users/kgowda/Desktop/my_work/play/dates.txt",'r')
>>> [re.search(r'\d{4}', x).group() for x in f.readlines() if x]
['2014', '2015', '2015', '2012']

If you want to remove duplicates, use set

>>> set([re.search(r'\d{4}', x).group() for x in f.readlines() if x])
set(['2015', '2014', '2012'])

If you text file contents like below

2014
2015
January 7, 2015
6th January 2012
0,2006 1,2007 2,2008 3,4 March 2014 4,"April 10, 2013" 5,7 August 2007

Use findall to get YYYY.

>>> [re.findall(r'\d{4}', x) for x in f.readlines() if x]
[['2014'], ['2015'], ['2015'], ['2012'], ['2006', '2007', '2008', '2014', '2013', '2007']]


问:
Azure / U-SQL - convert string to float
I'm having some issues while loading files in Azure data lake / U-SQL.  I think there might be an issue with some of the values in one of the columns (I can load them with the column as a string but not as a float) so I'd like to load them as a string, make some changes using CASE statements on the offending values and then convert the new values to floats.  However, I can't find how to do this outside of an EXTRACT statement.

Below is how I'd do it in SQL.

Any suggestions?

```<code>@inputInfo =
EXTRACT
var1 string,
var2 string,
var3 string
FROM "~/infile.txt"
USING Extractors.Text(quoting : false, delimiter : '|');

@t1 =
SELECT CASE WHEN var1 == "-0" THEN 0 ELSE var1 END AS var1
       , var2
       , var3
FROM @inputInfo;

@t2 =
SELECT CAST(var1 AS FLOAT) AS var1
        , var2
        , var3
FROM @t1;
</code>```

答:
You  could try casting it, eg

```<code>@departments =
    SELECT * FROM
        ( VALUES
        ("Newton",  23.00m),
        ("Susan",   25.1234m),
        ("Emma",    25.9999m),
        ("Bradley", 25.9900m)
        ) AS T(Cutomer, Balance);

@result =
    SELECT Cutomer,
           (float)Balance AS Balance1
    FROM @departments;

OUTPUT @result
TO "/output/output.txt"
USING Outputters.Tsv();
</code>```

If that does not work for you, please provide some sample data and expected results.

Title: Azure / U-SQL - convert string to float

Body:
I'm having some issues while loading files in Azure data lake / U-SQL.  I think there might be an issue with some of the values in one of the columns (I can load them with the column as a string but not as a float) so I'd like to load them as a string, make some changes using CASE statements on the offending values and then convert the new values to floats.  However, I can't find how to do this outside of an EXTRACT statement.

Below is how I'd do it in SQL.

Any suggestions?

@inputInfo =
EXTRACT
var1 string,
var2 string,
var3 string
FROM "~/infile.txt"
USING Extractors.Text(quoting : false, delimiter : '|');

@t1 =
SELECT CASE WHEN var1 == "-0" THEN 0 ELSE var1 END AS var1
       , var2
       , var3
FROM @inputInfo;

@t2 =
SELECT CAST(var1 AS FLOAT) AS var1
        , var2
        , var3
FROM @t1;

Body:
You  could try casting it, eg

@departments =
    SELECT * FROM
        ( VALUES
        ("Newton",  23.00m),
        ("Susan",   25.1234m),
        ("Emma",    25.9999m),
        ("Bradley", 25.9900m)
        ) AS T(Cutomer, Balance);

@result =
    SELECT Cutomer,
           (float)Balance AS Balance1
    FROM @departments;

OUTPUT @result
TO "/output/output.txt"
USING Outputters.Tsv();

If that does not work for you, please provide some sample data and expected results.


问:
Open source code for voice detection and discrimination
I have 15 audio tapes, one of which I believe contains an old recording of my grandmother and myself talking.  A quick attempt to find the right place didn't turn it up.  I don't want to listen to 20 hours of tape to find it.  The location may not be at the start of one of the tapes.  Most of the content seems to fall into three categories -- in order of total length, longest first: silence, speech radio, and music.

I plan to convert all of the tapes to digital format, and then look again for the recording.  The obvious way is to play them all in the background while I'm doing other things.  That's far too straightforward for me, so: Are there any open source libraries, or other code, that would allow me to find, in order of increasing sophistication and usefulness:

Non-silent regions

Regions containing human speech

Regions containing my own speech (and that of my grandmother)

My preference is for Python, Java, or C.

Failing answers, hints about search terms would be appreciated since I know nothing about the field.

I understand that I could easily spend more than 20 hours on this.

答:
I'd start here,

http://alize.univ-avignon.fr/

http://www-lium.univ-lemans.fr/diarization/doku.php/quick_start

codeblocks:: is good for gcc


问:
Hiding elements and categories for custom controls
I have a question please. Is it possible to hide some of the elements and categories of the base control (for a custom control). I want only the properties I defined to be shown. Thanks for your time.</p>

答:
Shadow the properties and add [Browsable(false)].

For example:

```<code>[Browsable(false)]
public new SomeType SomeProperty {
    get { return base.SomeProperty; }
    set { base.SomeProperty = value; }
}
</code>```

Body:
Shadow the properties and add [Browsable(false)].

For example:

[Browsable(false)]
public new SomeType SomeProperty {
    get { return base.SomeProperty; }
    set { base.SomeProperty = value; }
}