问:
How to find MySQl query type before query execution Zend framework
I am using Zend Framework with MySQL DB as backend.

I want to perform some operations depending on the type of query executed on MySQL server.

I want to perform these operations before query execution.

So my question is can I find the type of query before it is executed using Zend Framework e.g. SELECT , UPDATE, INSERT or DELETE ?

Many thanks in advance.

答:
I think you should look at the code of this class - Zend_Db_Table_Abstract.

Location - Zend/Db/Table/Abstract.php

Whenever I am into doubts about how Zend Framework is executing something, I dig inside the framework and check the code executing in the underlying classes.

Its clears up every question I have in my mind.

Hope this helps.


来源: stackexchange

问:
Changing css background image property by jquery setTimeout
I want to change my header image (which I gave it's source in the css, not in HTML) every 10 seconds Using jQuery.
I may have up to 15 16 images so the code I wrote may be too long for my js file.
I wrote the code below , but I'm looking for much compact code , hopefully using arrays.</p>

```<code>$(function() {
  setTimeout(function() {
    changeHeaderImg3()
  }, 10000);

  setTimeout(function() {
    changeHeaderImg2()
  }, 20000);

  setTimeout(function() {
    changeHeaderImg1()
  }, 30000);

  setTimeout(function() {
    changeHeaderImg4()
  }, 40000);
  setTimeout(function() {
    changeHeaderImg3()
  }, 50000);
});

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg2() {

  $('header').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg1() {

  $('header').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg4() {

  $('header').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};
</code>```

答:
This will work for any number of images as long as you keep following your 'assets/img/bg' + num + '.jpg' format. Just set the number of headers you have at the top and you're good to go.

```<code>$(function() {
    var numHeaders = 4;

    var header = 0;
    setInterval(function() {
        header++;
        if (header > numHeaders) {
            header = 1;
        }
        $('header').css('background', 'url(assets/img/bg' + header + '.jpg) center center').css('background-size', 'cover');
        $('footer').css('background', 'url(assets/img/bg' + header + '.jpg) center center').css('background-size', 'cover');
    }, 10000);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to change my header image (which I gave it's source in the css, not in HTML) every 10 seconds Using jQuery.
I may have up to 15 16 images so the code I wrote may be too long for my js file.
I wrote the code below , but I'm looking for much compact code , hopefully using arrays.

$(function() {
  setTimeout(function() {
    changeHeaderImg3()
  }, 10000);

  setTimeout(function() {
    changeHeaderImg2()
  }, 20000);

  setTimeout(function() {
    changeHeaderImg1()
  }, 30000);

  setTimeout(function() {
    changeHeaderImg4()
  }, 40000);
  setTimeout(function() {
    changeHeaderImg3()
  }, 50000);
});

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg2() {

  $('header').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg1() {

  $('header').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg4() {

  $('header').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover');
};

function changeHeaderImg3() {

  $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
  $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover');
};

Body:
This will work for any number of images as long as you keep following your 'assets/img/bg' + num + '.jpg' format. Just set the number of headers you have at the top and you're good to go.

$(function() {
    var numHeaders = 4;

    var header = 0;
    setInterval(function() {
        header++;
        if (header > numHeaders) {
            header = 1;
        }
        $('header').css('background', 'url(assets/img/bg' + header + '.jpg) center center').css('background-size', 'cover');
        $('footer').css('background', 'url(assets/img/bg' + header + '.jpg) center center').css('background-size', 'cover');
    }, 10000);
});


问:
How can I see cout output in a non-console application?
It seems rather tedious to output to debug window. Where can I find cout output if I am writing a non-console information ?

Like:

```<code>double i = a / b;
cout << b << endl;//I want to check out whether b is zero. It seems the output cannot be found anywhere.
</code>```

答:
I'd like to give my 2 cents.

Given that the maybe is a VS issue about compliancy with the C++ standard or that we could use OutputDebugStringA, if you cannot modify your code base you may like the idea of simply redirect the std::cout to something else, like a file.

So without changing your code base you can do something like suggested here:How to redirect cin and cout to files?

Condensed:

add the include #include <fstream>

at the beginning of your app, in some init, before logging you can use:

```<code>std::ofstream out("out.txt");
std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
</code>```

the at the end of your app/logging:

std::cout.rdbuf(coutbuf); //reset to standard output again

Hope this may help someone, Kudos to Nawaz that provided the answer in the other thread.

ContentLicense: CC BY-SA 4.0

Body:
It seems rather tedious to output to debug window. Where can I find cout output if I am writing a non-console information ?

Like:

double i = a / b;
cout << b << endl;//I want to check out whether b is zero. It seems the output cannot be found anywhere.

Body:
I'd like to give my 2 cents.

Given that the maybe is a VS issue about compliancy with the C++ standard or that we could use OutputDebugStringA, if you cannot modify your code base you may like the idea of simply redirect the std::cout to something else, like a file.

So without changing your code base you can do something like suggested here:How to redirect cin and cout to files?

Condensed:

add the include #include <fstream>

at the beginning of your app, in some init, before logging you can use:

std::ofstream out("out.txt");
std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!

the at the end of your app/logging:

std::cout.rdbuf(coutbuf); //reset to standard output again

Hope this may help someone, Kudos to Nawaz that provided the answer in the other thread.


问:
Alamofire can't access keys of json response
I'm new to using Alamofire and have encountered an issue. I'm able to run the following code to print out all the data from an API endpoint.

```<code>Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        print(JSON)
    }
}
</code>```

The issue is that when I run this:

```<code>Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        print(JSON["firstkey"])
    }
}
</code>```

I get the error:

Type 'Any' has no subscript members

I don't know why this error is happening, it seems as if I'm accessing the data correctly. Any help would be great, thanks!

I have tried formatting it using both:

print(JSON["firstkey"] as String)

and

print(JSON["firstkey"] as [String:Any]

but they still give the same error.

This is the JSON on my endpoint:

```<code>{
    "firstkey":"it worked!",
    "secondkey":["item1", "item2", "item3"]
}
</code>```

答:
This is really simple. You just need to force cast (as!) your JSON. so change your code to this and it will work:

```<code>Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        let json = JSON as! [String: Any]
        print(json["firstkey"])
    }
}
</code>```

Edit 1:
As you said in comments that you are using SwiftyJSON package. Sample code is as follows:

```<code>Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
        if let value = response.result.value {
            let json = JSON(value)
            print(json["firstkey"].stringValue)
        }
    }

Alamofire.request("https://mmcalc.com/api").responseJSON { response in
        if let value = response.result.value {
            let json = JSON(value)
            print(json.arrayValue[0]["uniqueUsers"].stringValue)
        }
    }
</code>```

Body:
I'm new to using Alamofire and have encountered an issue. I'm able to run the following code to print out all the data from an API endpoint.

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        print(JSON)
    }
}

The issue is that when I run this:

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        print(JSON["firstkey"])
    }
}

I get the error:

Type 'Any' has no subscript members

I don't know why this error is happening, it seems as if I'm accessing the data correctly. Any help would be great, thanks!

I have tried formatting it using both:

print(JSON["firstkey"] as String)

and

print(JSON["firstkey"] as [String:Any]

but they still give the same error.

This is the JSON on my endpoint:

{
    "firstkey":"it worked!",
    "secondkey":["item1", "item2", "item3"]
}

Body:
This is really simple. You just need to force cast (as!) your JSON. so change your code to this and it will work:

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        let json = JSON as! [String: Any]
        print(json["firstkey"])
    }
}

Edit 1:
As you said in comments that you are using SwiftyJSON package. Sample code is as follows:

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
        if let value = response.result.value {
            let json = JSON(value)
            print(json["firstkey"].stringValue)
        }
    }

Alamofire.request("https://mmcalc.com/api").responseJSON { response in
        if let value = response.result.value {
            let json = JSON(value)
            print(json.arrayValue[0]["uniqueUsers"].stringValue)
        }
    }


问:
Stopping a blinking cursor at end of css animation
I guys I have tried a lot of things that didn't work. I have a css animation with a blinking cursor. I am trying to use it in this game I'm developing.

Link to game for visual reference: https://code.sololearn.com/WF65X6DEns7o/#css

+++

so here is the code that is a problem

HTML:

```<code>   <div id = "Header"> <b>Real Estate Agent</b> </div>
</code>```

CSS:

```<code>#Header{
font-size:50px; color:darkOrange; text-shadow:3px 3pxblack;
overflow:hidden;
letter-spacing: .15em;
animation: typing 3.5s steps(60, end), blink-caret .65s step-end infinite;
white-space: nowrap;
border-right: .15em solid orange;
width:500px;
}

 @keyframes typing {
  from { width: 0 }
   to { width: 500px }
   }

@keyframes blink-caret {
from, to { border-color: orange }
 50% { border-color: transparent; }
   }
</code>```

+++++++++++++

currently the cursor blinks until all the text is done typing and then it keeps blink at the end of the words.

How can i make the cursor stop blinking at the end of the animation and stop the animation cycle.

As i have said i have tried a few things and nothing is working.

thanks

答:
Try this:</p>

```<code>#Header{
    font-size:50px; color:darkOrange; text-shadow:3px 3px black; overflow: hidden; letter-spacing: .15em;
    animation: typing 3.5s steps(60, end), blink-caret .65s step-end 5; white-space: nowrap;
    width:500px;
}

@keyframes typing {
  from { width: 0 }
  to { width: 500px }
}

@keyframes blink-caret {
  from, to { border-color: transparent; }
  50% { border-right: .15em solid orange; }
}
</code>```

Body:
I guys I have tried a lot of things that didn't work. I have a css animation with a blinking cursor. I am trying to use it in this game I'm developing.

Link to game for visual reference: https://code.sololearn.com/WF65X6DEns7o/#css

+++

so here is the code that is a problem

HTML:

 Real Estate Agent

CSS:

#Header{
font-size:50px; color:darkOrange; text-shadow:3px 3pxblack;
overflow:hidden;
letter-spacing: .15em;
animation: typing 3.5s steps(60, end), blink-caret .65s step-end infinite;
white-space: nowrap;
border-right: .15em solid orange;
width:500px;
}

 @keyframes typing {
  from { width: 0 }
   to { width: 500px }
   }

@keyframes blink-caret {
from, to { border-color: orange }
 50% { border-color: transparent; }
   }

+++++++++++++

currently the cursor blinks until all the text is done typing and then it keeps blink at the end of the words.

How can i make the cursor stop blinking at the end of the animation and stop the animation cycle.

As i have said i have tried a few things and nothing is working.

thanks

Body:
Try this:

#Header{
    font-size:50px; color:darkOrange; text-shadow:3px 3px black; overflow: hidden; letter-spacing: .15em;
    animation: typing 3.5s steps(60, end), blink-caret .65s step-end 5; white-space: nowrap;
    width:500px;
}

@keyframes typing {
  from { width: 0 }
  to { width: 500px }
}

@keyframes blink-caret {
  from, to { border-color: transparent; }
  50% { border-right: .15em solid orange; }
}


问:
Need to display user's name and details in TextView after login
I have a navigation menu as you see in the image. I am able to get the user details from the database and am able to display them on other textviews in the app. But when I try to create the TextView object for the TextViews in the Navigation Menu, I see in the debug values that the reference it is getting is "null".

Navigation Menu

```<code> TextView firstName = (TextView) findViewById(R.id.textview_firstName); firstName.setText("test");
</code>```

I am just trying to set it to "test" for testing purpose.

activity_navigation_main.xml (its not activity. just named it that way)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="200dp"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    tools:context="com.xtremustechnologies.chotu.HomeActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="66dp"
        android:layout_height="wrap_content"
        android:paddingTop="20dp"
        app:srcCompat="@android:drawable/sym_def_app_icon"
        android:layout_weight="0.17" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_lastName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="LAST NAME"
            android:paddingTop="@dimen/nav_header_vertical_spacing"
            android:textAllCaps="true"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"
            android:textSize="20dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="4dp"
            android:text=", "/>

        <TextView
            android:id="@+id/textview_firstName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:hint="First Name"
            android:paddingTop="@dimen/nav_header_vertical_spacing"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"
            android:textSize="20dp" />
    </LinearLayout>

    <TextView
        android:id="@+id/textview_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/email" />

</LinearLayout>
</code>```

Image - activity_navigation_mail.xml

Please suggest.!

答:
You cannot access the views of navigation drawer directly, you need to access them through navigation view reference. Check this:

```<code>//Initializing NavigationView
    NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
    View header = navigationView.getHeaderView(0);

    TextView firstName= (TextView) header.findViewById(R.id.textview_firstName);
</code>```

Hope this will work for you!

Body:
I have a navigation menu as you see in the image. I am able to get the user details from the database and am able to display them on other textviews in the app. But when I try to create the TextView object for the TextViews in the Navigation Menu, I see in the debug values that the reference it is getting is "null".

Navigation Menu

 TextView firstName = (TextView) findViewById(R.id.textview_firstName); firstName.setText("test");

I am just trying to set it to "test" for testing purpose.

activity_navigation_main.xml (its not activity. just named it that way)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="200dp"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    tools:context="com.xtremustechnologies.chotu.HomeActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="66dp"
        android:layout_height="wrap_content"
        android:paddingTop="20dp"
        app:srcCompat="@android:drawable/sym_def_app_icon"
        android:layout_weight="0.17" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_lastName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="LAST NAME"
            android:paddingTop="@dimen/nav_header_vertical_spacing"
            android:textAllCaps="true"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"
            android:textSize="20dp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="4dp"
            android:text=", "/>

        <TextView
            android:id="@+id/textview_firstName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:hint="First Name"
            android:paddingTop="@dimen/nav_header_vertical_spacing"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"
            android:textSize="20dp" />
    </LinearLayout>

    <TextView
        android:id="@+id/textview_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/email" />

</LinearLayout>

Image - activity_navigation_mail.xml

Please suggest.!

Body:
You cannot access the views of navigation drawer directly, you need to access them through navigation view reference. Check this:

//Initializing NavigationView
    NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
    View header = navigationView.getHeaderView(0);

    TextView firstName= (TextView) header.findViewById(R.id.textview_firstName);

Hope this will work for you!


问:
best practice json?
when using spring rest server side generate json, it will looks like below

```<code>{"userInfo":{"id":123,"userFullName":"full name"}}    with nested 'userInfo'
</code>```

should json generate this way is consider best practice or should just generate like below

{"id":88,"userFullName":"dfXXXXXXXXXX"}    without nested 'userinfo'

the reason i asking is, if i use the prior technique, on my client, i would need to Extract the user info as JSONObject then only can get json data . which way is better?

答:
This is like asking which is better between these two xml fragmetns:

```<code><userinfo>
  <id></id>
  <username></username>
</userinfo>
</code>```

or

```<code><id></id>
<username></username>
</code>```

I would prefer the first format because it's more readable, but of course, there's less data generated from the second format. Best practice is to have a code that's maintainable. So just like what yoda answered

"From a code mantainer point of view,
  I would choose the first option"

ContentLicense: CC BY-SA 2.5

Title: best practice json?

Body:
when using spring rest server side generate json, it will looks like below

{"userInfo":{"id":123,"userFullName":"full name"}}    with nested 'userInfo'

should json generate this way is consider best practice or should just generate like below

{"id":88,"userFullName":"dfXXXXXXXXXX"}    without nested 'userinfo'

the reason i asking is, if i use the prior technique, on my client, i would need to Extract the user info as JSONObject then only can get json data . which way is better?

Body:
This is like asking which is better between these two xml fragmetns:

<userinfo>
  <id></id>
  <username></username>
</userinfo>

or

<id></id>
<username></username>

I would prefer the first format because it's more readable, but of course, there's less data generated from the second format. Best practice is to have a code that's maintainable. So just like what yoda answered

"From a code mantainer point of view,
  I would choose the first option"


问:
Auto-fill matrix without row-repetitions
I have a series of numbers:

```<code>test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5]
</code>```

which I want to randomely fill into a 3x5 matrix without having the same number in the same row.

How can I do this in matlab? Potentially I could randomize the test vector and fill it into the 5x3 matrix but I don't know how to do this without getting the same number in the same row.

答:
Here is a brute-force way of doing it

```<code>% data
test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5];

% randomly permute the indices
indices = randperm(numel(test));

% create a random matrix
matrix = reshape(test(indices), 5, 3);

% while number of unique elements in any of the rows is other than 3
while any(arrayfun(@(x) numel(unique(matrix(x,:))), (1:size(matrix,1)).')~=3)
    % keep generating random matrices
    indices = randperm(numel(test));
    matrix = reshape(test(indices), 5, 3);
end;

% here is the result
result=matrix;
</code>```

EDIT : If you want 3x5 like you mentioned in your comment, it is a lot easier. Just one line below.

```<code>[~, result] = sort(rand(3,5),2);
</code>```

Body:
I have a series of numbers:

test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5]

which I want to randomely fill into a 3x5 matrix without having the same number in the same row.

How can I do this in matlab? Potentially I could randomize the test vector and fill it into the 5x3 matrix but I don't know how to do this without getting the same number in the same row.

Body:
Here is a brute-force way of doing it

% data
test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5];

% randomly permute the indices
indices = randperm(numel(test));

% create a random matrix
matrix = reshape(test(indices), 5, 3);

% while number of unique elements in any of the rows is other than 3
while any(arrayfun(@(x) numel(unique(matrix(x,:))), (1:size(matrix,1)).')~=3)
    % keep generating random matrices
    indices = randperm(numel(test));
    matrix = reshape(test(indices), 5, 3);
end;

% here is the result
result=matrix;

EDIT : If you want 3x5 like you mentioned in your comment, it is a lot easier. Just one line below.

[~, result] = sort(rand(3,5),2);


问:
SQL 2005 - quick way to quickly duplicate a database + data
I have my development database, I want to spin off a duplicate for testing.  I want to do this often.

What's the fastest and easiest way to do this often?  I can get the job done by generating scripts w/ data included but I feel like there must be a better way.  Should I back up database 1 then screw around with it so I can restore it as a different name?

答:
One more option to throw in,

Here's a blog entry that talks about using the Database Publishing Wizard and how it's used to export all elements of a database, including data, to an SQL file.  Might be helpful and seems pretty straightforward.

http://blog.sqlauthority.com/2007/11/16/sql-server-2005-generate-script-with-data-from-database-database-publishing-wizard/

OwnerDisplayName: BPAndrew

OwnerDisplayName: Crazy Joe Malloy


答:
I don't believe either solution is universally more correct than the other. I think the more appropriate solution heavily depends on the context.

With that being said, in my humble opinion, while the first solution as you mention requires more processing, it also offers a lot more flexibility. JSON is great for representing data hierarchy and structure. If you ever wanted to add in more data or structure, I believe the first solution (with the nested userInfo) would handle the transition more smoothly.

For example let's say you wanted to support the info for multiple users, then the only switch you would need to make is to have userInfo contain a JSON array of multiple userInfo objects. To take this a step further, let's say you also wanted include a new set of data entirely - say locationInfo - you would benefit from the nested hierarchy to separate out these two different classes of data.

Ultimately, I believe that the right solution is the one that is most appropriate to the context of your application but I would encourage you to be forward thinking in how you approach your design and try to anticipate how you might use this implementation in the future.

Just food for thought.

Good luck!

Title: best practice json?


问:
How can I know if the image is in RGB or BGR format?
Is there any way to know in advance if an image used as an input to a system is in RGB or BGR format?

I am using OpenCV with java API and I would like to convert an input image into grayscale or L*a*b* color space, but in OpenCV you have to specify first whether the image you want to convert is in RGB or BGR.

The type of the image I am using is either .jpg or .png.

答:
If you are reading in the image file, or you have access to the code that reads in the file, know it is:

BGR order if you used cv2.imread()

RGB order if you used mpimg.imread() (assuming import matplotlib.image as mpimg)

If you don't know how the file was opened, the accepted answer BufferedImage is great for Java.

I would like to find a way to do the same in Python!


问:
objective c to swift conversion. (#define and weak)
I am stuck in converting #define and weak from objective c to swift. I tried to use objective c to swift convertor, but I think the result of conversion is not correct.

```<code>#define WeakRef(__obj) __weak typeof(self) __obj = self
#define WeakReturn(__obj) if(__obj ==nil)return;
WeakRef(weakSelf);
WeakReturn(weakSelf);
</code>```

For the second, third and forth lines, I think it should be something like this in Swift

```<code>func WeakReturn(obj: Any?) {
    if obj == nil {
        return
    }
}
WeakRef(self)
WeakReturn(self)
</code>```

In my guess for the first line, it first check the condition of typeof(self) == ??. If true, then set the pointer (__obj) to self. But, I am not sure about what ?? should be.

答:
WeakRef simply gives you a weak reference to some object, and in Swift, that's just weak var foo = obj; it doesn't need a utility method.

WeakReturn can't be replicated in Swift, because the Obj-C macro is used to insert a conditional return in a function. There are no macros in Swift, and the Swift WeakReturn function that you defined does absolutely nothing--it returns whether the object is nil or not; all you've done is make one of those returns explicit. My guess is that this macro was added to the Obj-C code to save some lazy programmer from writing if obj == nil return;.

Body:
I am stuck in converting #define and weak from objective c to swift. I tried to use objective c to swift convertor, but I think the result of conversion is not correct.

#define WeakRef(__obj) __weak typeof(self) __obj = self
#define WeakReturn(__obj) if(__obj ==nil)return;
WeakRef(weakSelf);
WeakReturn(weakSelf);

For the second, third and forth lines, I think it should be something like this in Swift

func WeakReturn(obj: Any?) {
    if obj == nil {
        return
    }
}
WeakRef(self)
WeakReturn(self)

In my guess for the first line, it first check the condition of typeof(self) == ??. If true, then set the pointer (__obj) to self. But, I am not sure about what ?? should be.


问:
Cancel previous asynchronous .load() requests
I have some javascript code that works as follows:

```<code>function updateResults() {
    var user_input = $('input:text').val();

    user_input = encodeURIComponent(user_input);

    div1.html('').load(cog_url); // Just displays a spinning cog while results load
    div2.html('').load(cog_url); // Just displays a spinning cog while results load
    div3.html('').load(cog_url); // Just displays a spinning cog while results load

    $.when(
        div1.html('').load("api/method1?input=" + user_input),
        div2.html('').load("api/method2?input=" + user_input),
        div3.html('').load("api/method3?input=" + user_input)
    ).done(function () {
        return true;
    });
}
</code>```

The API methods just return HTML which contains the desired results to be rendered in the target divs. This all works relatively well, but when I submit multiple times to the system the previous requests don't get canceled so I get a string of responses and the divs keep getting reloaded with all the requests that were sent in order. I'd like to have it so that just the latest request is returned if the previous one(s) hasn't finished. Any suggestions as to how to do this? I'd like to keep the asynchronous aspect of this.

答:
Can you add a sort of flag to determine if it is the last request ?

By example :

```<code>function updateResults(isLastRequest) {
    var user_input = $('input:text').val();

    user_input = encodeURIComponent(user_input);

    div1.html('').load(cog_url); // Just displays a spinning cog while results load
    div2.html('').load(cog_url); // Just displays a spinning cog while results load
    div3.html('').load(cog_url); // Just displays a spinning cog while results load

    $.when(
        if(isLastRequest){
            div1.html('').load("api/method1?input=" + user_input),
            div2.html('').load("api/method2?input=" + user_input),
            div3.html('').load("api/method3?input=" + user_input)

        }
    ).done(function () {
        return true;
    });
}
</code>```

Does it help ?

Body:
I have some javascript code that works as follows:

function updateResults() {
    var user_input = $('input:text').val();

    user_input = encodeURIComponent(user_input);

    div1.html('').load(cog_url); // Just displays a spinning cog while results load
    div2.html('').load(cog_url); // Just displays a spinning cog while results load
    div3.html('').load(cog_url); // Just displays a spinning cog while results load

    $.when(
        div1.html('').load("api/method1?input=" + user_input),
        div2.html('').load("api/method2?input=" + user_input),
        div3.html('').load("api/method3?input=" + user_input)
    ).done(function () {
        return true;
    });
}

The API methods just return HTML which contains the desired results to be rendered in the target divs. This all works relatively well, but when I submit multiple times to the system the previous requests don't get canceled so I get a string of responses and the divs keep getting reloaded with all the requests that were sent in order. I'd like to have it so that just the latest request is returned if the previous one(s) hasn't finished. Any suggestions as to how to do this? I'd like to keep the asynchronous aspect of this.

Body:
Can you add a sort of flag to determine if it is the last request ?

By example :

function updateResults(isLastRequest) {
    var user_input = $('input:text').val();

    user_input = encodeURIComponent(user_input);

    div1.html('').load(cog_url); // Just displays a spinning cog while results load
    div2.html('').load(cog_url); // Just displays a spinning cog while results load
    div3.html('').load(cog_url); // Just displays a spinning cog while results load

    $.when(
        if(isLastRequest){
            div1.html('').load("api/method1?input=" + user_input),
            div2.html('').load("api/method2?input=" + user_input),
            div3.html('').load("api/method3?input=" + user_input)

        }
    ).done(function () {
        return true;
    });
}

Does it help ?


问:
Manipulating Array with Javascript
I am pretty new to javascript so bear with me!

So I have some data that I am pulling out of an AWS DynamoDB via a lambda script tied to an API gateway.

So I have a javascript function on my page that issues a GET request for the data and this works great. I am able to get the data. When I get it, it looks like this:

```<code>{"Items":[{"issue":"my issue","email":"my@email.com","caseDate":1496543576984,"phone":"1234567890","status":"queueing","enterpriseID":"john.smith"},{"issue":"Test issue 02","email":"john.smithy@company.com","caseDate":1496543945585,"phone":"1234567890","status":"queueing","enterpriseID":"john.smithy"}],"Count":2,"ScannedCount":2}
</code>```

So I am trying to build a dynamic table on a web page with the data. This is the code that I have. Notice the map function where I am trying to change the order of the Items.issue, Items.caseDate etc to match up with the column headings.

        var API_URL = 'https://myapi.execute-api.us-west-2.amazonaws.com/dev/cases';
        var table = document.createElement("table");

        $(document).ready(function(){
            $.ajax({
                type: 'GET',
                url: API_URL,

                success: function(data){

                    //alert(data);

                    table.setAttribute("id", "myTable");

                    var tableHeader = document.createElement("thead");

                    var headerNames = ["Date", "Enterprise ID", "Client Phone", "Client Email",
                                      "Case Status", "Client Issue"];

                    headerNames.forEach(function(header){
                        var tableHeaderItem = document.createElement("th");
                        var headerText = document.createTextNode(header.toString());

                        tableHeaderItem.appendChild(headerText);
                        tableHeader.appendChild(tableHeaderItem);

                    });

                    table.appendChild(tableHeader);

                    data.Items.forEach(function(queueItem){

                        var myTableRow = document.createElement("tr");
                        myTableRow.setAttribute("id", queueItem.date);

                        var arr1 = $.map(queueItem, function(value, index) {
                            return [value];
                        });

                        const map =[2,5,3,1,4,0]
                        const arr3 = Array.apply(null, Array(map.length))
                        arr3.map((d, i) => arr3[map[i]] = arr1[i]);

                        arr3.forEach(function(item){
                            var tableItem = document.createElement("td");
                            var itemText = document.createTextNode(item);

                            tableItem.appendChild(itemText);
                            myTableRow.appendChild(tableItem);
                        });

                        table.appendChild(myTableRow);
                    })
                    document.getElementById("queueTable").appendChild(table);
                }
            });
        });```
</div>
</div>
</p>

<p>So the issue is that once I pull the actual data out of one of the items and shove it into an array to iterate over it, its in the wrong order. How can I fix this cause that map function sounds great but it doesn't work. </p>

<p>I should get me:</p>

```mapping["ID","phone","issue","caseDate","status","email"]
```

<p>But it actually gets me:</p>

```mapping["caseDate","ID","phone","email","status","issue"]
```

Help! I have been beating my head against the wall for 3 hours now google searching etc and I just cant quite get what I need.

答:
Instead of headerNames and those internal mappings, could you use a data structure like this instead?:

```<code>const fields = [
  {name: 'caseDate', header: 'Date'},
  {name: 'issue', header: 'Client Issue'},
  {name: 'email', header: 'Client Email'},
  {name: 'phone', header: 'Client Phone'},
  {name: 'status', header: 'Case Status'},
  {name: 'enterpriseID', header: 'Enterprise ID'}
]
</code>```

You could loop over these in order for the headers, pulling off the header property, and for each row, pulling out the named field from the data via something like item[field.name].

That looks cleaner overall.

Title: Manipulating Array with Javascript

Body:
I am pretty new to javascript so bear with me!

So I have some data that I am pulling out of an AWS DynamoDB via a lambda script tied to an API gateway.

So I have a javascript function on my page that issues a GET request for the data and this works great. I am able to get the data. When I get it, it looks like this:

{"Items":[{"issue":"my issue","email":"my@email.com","caseDate":1496543576984,"phone":"1234567890","status":"queueing","enterpriseID":"john.smith"},{"issue":"Test issue 02","email":"john.smithy@company.com","caseDate":1496543945585,"phone":"1234567890","status":"queueing","enterpriseID":"john.smithy"}],"Count":2,"ScannedCount":2}

So I am trying to build a dynamic table on a web page with the data. This is the code that I have. Notice the map function where I am trying to change the order of the Items.issue, Items.caseDate etc to match up with the column headings.

        var API_URL = 'https://myapi.execute-api.us-west-2.amazonaws.com/dev/cases';
        var table = document.createElement("table");

        $(document).ready(function(){
            $.ajax({
                type: 'GET',
                url: API_URL,

                success: function(data){

                    //alert(data);

                    table.setAttribute("id", "myTable");

                    var tableHeader = document.createElement("thead");

                    var headerNames = ["Date", "Enterprise ID", "Client Phone", "Client Email",
                                      "Case Status", "Client Issue"];

                    headerNames.forEach(function(header){
                        var tableHeaderItem = document.createElement("th");
                        var headerText = document.createTextNode(header.toString());

                        tableHeaderItem.appendChild(headerText);
                        tableHeader.appendChild(tableHeaderItem);

                    });

                    table.appendChild(tableHeader);

                    data.Items.forEach(function(queueItem){

                        var myTableRow = document.createElement("tr");
                        myTableRow.setAttribute("id", queueItem.date);

                        var arr1 = $.map(queueItem, function(value, index) {
                            return [value];
                        });

                        const map =[2,5,3,1,4,0]
                        const arr3 = Array.apply(null, Array(map.length))
                        arr3.map((d, i) => arr3[map[i]] = arr1[i]);

                        arr3.forEach(function(item){
                            var tableItem = document.createElement("td");
                            var itemText = document.createTextNode(item);

                            tableItem.appendChild(itemText);
                            myTableRow.appendChild(tableItem);
                        });

                        table.appendChild(myTableRow);
                    })
                    document.getElementById("queueTable").appendChild(table);
                }
            });
        });

So the issue is that once I pull the actual data out of one of the items and shove it into an array to iterate over it, its in the wrong order. How can I fix this cause that map function sounds great but it doesn't work.

I should get me:

mapping["ID","phone","issue","caseDate","status","email"]

But it actually gets me:

mapping["caseDate","ID","phone","email","status","issue"]

Help! I have been beating my head against the wall for 3 hours now google searching etc and I just cant quite get what I need.

Body:
Instead of headerNames and those internal mappings, could you use a data structure like this instead?:

const fields = [
  {name: 'caseDate', header: 'Date'},
  {name: 'issue', header: 'Client Issue'},
  {name: 'email', header: 'Client Email'},
  {name: 'phone', header: 'Client Phone'},
  {name: 'status', header: 'Case Status'},
  {name: 'enterpriseID', header: 'Enterprise ID'}
]

You could loop over these in order for the headers, pulling off the header property, and for each row, pulling out the named field from the data via something like item[field.name].

That looks cleaner overall.


问:
data.frame rows to a list
I have a data.frame which I would like to convert to a list by rows, meaning each row would correspond to its own list elements. In other words, I would like a list that is as long as the data.frame has rows.

So far, I've tackled this problem in the following manner, but I was wondering if there's a better way to approach this.

```<code>xy.df <- data.frame(x = runif(10),  y = runif(10))

# pre-allocate a list and fill it with a loop
xy.list <- vector("list", nrow(xy.df))
for (i in 1:nrow(xy.df)) {
    xy.list[[i]] <- xy.df[i,]
}
</code>```

答:
The best way for me was:

Example data:

```<code>Var1<-c("X1",X2","X3")
Var2<-c("X1",X2","X3")
Var3<-c("X1",X2","X3")

Data<-cbind(Var1,Var2,Var3)

ID    Var1   Var2  Var3
1      X1     X2    X3
2      X4     X5    X6
3      X7     X8    X9
</code>```

We call the  BBmisc library

```<code>library(BBmisc)

data$lists<-convertRowsToList(data[,2:4])
</code>```

And the result will be:

```<code>ID    Var1   Var2  Var3  lists
1      X1     X2    X3   list("X1", "X2", X3")
2      X4     X5    X6   list("X4","X5", "X6")
3      X7     X8    X9   list("X7,"X8,"X9)
</code>```

Title: data.frame rows to a list

Body:
I have a data.frame which I would like to convert to a list by rows, meaning each row would correspond to its own list elements. In other words, I would like a list that is as long as the data.frame has rows.

So far, I've tackled this problem in the following manner, but I was wondering if there's a better way to approach this.

xy.df <- data.frame(x = runif(10),  y = runif(10))

# pre-allocate a list and fill it with a loop
xy.list <- vector("list", nrow(xy.df))
for (i in 1:nrow(xy.df)) {
    xy.list[[i]] <- xy.df[i,]
}

Body:
The best way for me was:

Example data:

Var1<-c("X1",X2","X3")
Var2<-c("X1",X2","X3")
Var3<-c("X1",X2","X3")

Data<-cbind(Var1,Var2,Var3)

ID    Var1   Var2  Var3
1      X1     X2    X3
2      X4     X5    X6
3      X7     X8    X9

We call the  BBmisc library

library(BBmisc)

data$lists<-convertRowsToList(data[,2:4])

And the result will be:

ID    Var1   Var2  Var3  lists
1      X1     X2    X3   list("X1", "X2", X3")
2      X4     X5    X6   list("X4","X5", "X6")
3      X7     X8    X9   list("X7,"X8,"X9)


问:
ASP.NET runtime error: Could not load file or assembly 'Interop.CertEnroll'
I have a ASP.Net 4.0 site that I am editiing in VS2010. Every @ Master and @ Page tag has the blue squiggle lines giving the following error:

ASP.NET runtime error: Could not load file or assembly 'Interop.CertEnroll' or one of its dependencies. An attempt was made to load a program with an incorrect format.

I know it is related to trying to load a 32bit dll into a 64bit application but I am not sure how to control it since I am not sure how this Iterop.CertEnroll client is evening being referenced.

I am targetting Any CPU for my builds.

My application still functions but it bothers me to see all of these warnings and I have seen hints that this may be causing issue with my AjaxToolkit server tags not being recognized.

Thank you!
Karl

答:
TL;DR: Check your master page(s) if the ContentPlaceHolder tags are specified correctly, and your pages to see that the ContentPlaceHolder tag ids are correct.

Long answer:

For anyone facing this issue and if the other solutions do not work, here is another thing you could try. I was getting the same error, with all master and page tags highlighted with the error:

Could not load file or assembly Microsoft.Practices.ServiceLocation,
  Version=1.3.0.0

My packages were all in order and I spent quite a lot of time trying to get it to work. Turns out the error was misdirecting and the actual error was missing ContentPlaceHolder tags in my nested master page.


问:
Variable quantifier in perl6
Suppose i want to match words with at least 4 letters, (and store them in an array), I have written the following regex, which works fine:

```<code>if ( $text ~~ m:g/(\w ** 4..*)/ )
{
  my @words = $/;
  ...
}
</code>```

The quantifier being from 4 to unlimited

```<code>**4..*
</code>```

Now if I try to substitute 4 with a scalar $min_length. Both:

```<code>if ($text ~~ m:g/(\w ** $::min_length..*)/)
</code>```

and:

```<code>if ($text ~~ m:g/(\w ** <$::min_length>..*)/)
</code>```

results in an error at compilation:
Quantifier quantifies nothing

Is there a way for having a scalar as a quantifier?

答:
I think using .split is a more natural fit, together with .grep:

```<code>my $text = "The quick brown fox jumps over the lazy dog.";
my $min-length = 4;
say $text.split(/\W+/).grep(*.chars >= $min-length);
===============
(quick brown jumps over lazy)
</code>```

If you define words as the characters between whitespace, you can even use the .words method:

```<code>say $text.words.grep(*.chars >= $min-length);
===============
(quick brown jumps over lazy dog.)
</code>```

Title: Variable quantifier in perl6

Body:
Suppose i want to match words with at least 4 letters, (and store them in an array), I have written the following regex, which works fine:

if ( $text ~~ m:g/(\w ** 4..*)/ )
{
  my @words = $/;
  ...
}

The quantifier being from 4 to unlimited

**4..*

Now if I try to substitute 4 with a scalar $min_length. Both:

if ($text ~~ m:g/(\w ** $::min_length..*)/)

and:

if ($text ~~ m:g/(\w ** <$::min_length>..*)/)

results in an error at compilation:
Quantifier quantifies nothing

Is there a way for having a scalar as a quantifier?

Body:
I think using .split is a more natural fit, together with .grep:

my $text = "The quick brown fox jumps over the lazy dog.";
my $min-length = 4;
say $text.split(/\W+/).grep(*.chars >= $min-length);
===============
(quick brown jumps over lazy)

If you define words as the characters between whitespace, you can even use the .words method:

say $text.words.grep(*.chars >= $min-length);
===============
(quick brown jumps over lazy dog.)


问:
How to write a result of function in the global environment in R
I have these datasets: A <- 4, B <- 3, C <- 2.

So I put them in a list
D<-list(A,B,C) and want to apply this function:

```<code>s<-function(x) {
    t<-8
    x<-as.data.frame(x*t)
}

lapply(D,s)
</code>```

when I apply the lapply function it just print them.

How can I make it saving the result in the global environment instead of printing them?

So the result should be A with value of 32 B with value of 24 C with value of 16.

答:
It is better to store all your variables "straying" in the global environment in a list (keeps the environment clean/smaller and allows every kind of looping):

```<code>D <- list(A = 4, B = 3, C = 2)

s <- function(x) {
  t <- 8
  x * t   # return just the value
}

result <- lapply(D, s)
names(result) <- names(D)  # rename the results
D <- result  # replace the original values with the "updated" ones

D
D$A  # to access one element
</code>```

Body:
I have these datasets: A <- 4, B <- 3, C <- 2.

So I put them in a list
D<-list(A,B,C) and want to apply this function:

s<-function(x) {
    t<-8
    x<-as.data.frame(x*t)
}

lapply(D,s)

when I apply the lapply function it just print them.

How can I make it saving the result in the global environment instead of printing them?

So the result should be A with value of 32 B with value of 24 C with value of 16.

Body:
It is better to store all your variables "straying" in the global environment in a list (keeps the environment clean/smaller and allows every kind of looping):

D <- list(A = 4, B = 3, C = 2)

s <- function(x) {
  t <- 8
  x * t   # return just the value
}

result <- lapply(D, s)
names(result) <- names(D)  # rename the results
D <- result  # replace the original values with the "updated" ones

D
D$A  # to access one element


问:
How to avoid circular dependency in code first entity framework design
I am trying to create modular (component based) application.

My scenario is so simple, I have a SalesManagement component which contains Invoice, and I have PartyManagement component which contains Customer,

so far so good,
Then I defined a class for Customer as

```<code>public class Customer {
   public int ID {get;set;}
   public string Name {get;set;}
}
</code>```

and Invoice as

```<code>public class Invoice {
   public int ID {get;set;}
   public int CustomerID {get;set;}
   public Customer Customer {get;set;}
}
</code>```

in order to have Customer reference in Invoice I referenced PartyManagement in SalesManagement component

then I tried to add a collection of Invoice under customer as

```<code>public class Customer {
   public int ID {get;set;}
   public string Name {get;set;}
   public virtual ICollection<Invoice> Invoices {get;set;}
}
</code>```

to make it happen I have to reference InvoiceManagement in PartyManagement which makes a circular dependency between assemblies in compile time

Any idea how to resolve this design issue?

p.s If I keep everything in 1 assembly there is no problem, I want to keep them in separate assemblies

答:
If you specifically require linking both ways, then you can use your ORM to handle this by lazy loading any linked entities - which you're already doing with your Customer.Invoices collection, since it has the virtual keyword applied.

If you haven't come across this before, it means that the linked entity or collection will not be loaded until it is referenced, which will prevent the circular reference causing a problem with your data access, but still allows you to use the pattern.

I'm assuming you're using Entity Framework, in which case you can read more about this here: https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx

Edit - what I would do, to avoid circular references*

|Solution

|-- ProjectOne (references Dtos and Repositories)

|-- ProjectTwo (references Dtos and Repositories)

|-- Repositories (references Entities & Dtos, but only returns Dtos)

|-- Entities (doesnt reference any other projects - EF context is here)

|-- Dtos (doesnt reference any other projects)

This means that both ProjectOne & ProjectTwo are decoupled from our DataAccess implementation, and we can easily model our Dto model relationships since they are all in the same Dtos project and also not restricted by our database "Entities" model - meaning we could combine data from different sources or make it more easily consumable by client code.

*There would also be interfaces covering our Repository layer here (and probably a Service layer as well in a larger solution). I've left this out to simplify the layout.

Body:
I am trying to create modular (component based) application.

My scenario is so simple, I have a SalesManagement component which contains Invoice, and I have PartyManagement component which contains Customer,

so far so good,
Then I defined a class for Customer as

public class Customer {
   public int ID {get;set;}
   public string Name {get;set;}
}

and Invoice as

public class Invoice {
   public int ID {get;set;}
   public int CustomerID {get;set;}
   public Customer Customer {get;set;}
}

in order to have Customer reference in Invoice I referenced PartyManagement in SalesManagement component

then I tried to add a collection of Invoice under customer as

public class Customer {
   public int ID {get;set;}
   public string Name {get;set;}
   public virtual ICollection<Invoice> Invoices {get;set;}
}

to make it happen I have to reference InvoiceManagement in PartyManagement which makes a circular dependency between assemblies in compile time

Any idea how to resolve this design issue?

p.s If I keep everything in 1 assembly there is no problem, I want to keep them in separate assemblies


问:
Exception in thread "main" cucumber.runtime.CucumberException: No backends were found
I am developing my Selenium-JVM framework with Cucumber and while running my first feature got below error.

Please help.

How did I launch the feature -

Right click on feature file

Select Run As -> Cucumber Feature

Immediate Exception -

```<code>Exception in thread "main" cucumber.runtime.CucumberException: No backends were found. Please make sure you have a backend module on your CLASSPATH.
    at cucumber.runtime.Runtime.<init>(Runtime.java:78)
    at cucumber.runtime.Runtime.<init>(Runtime.java:67)
    at cucumber.runtime.Runtime.<init>(Runtime.java:63)
    at cucumber.api.cli.Main.run(Main.java:24)
    at cucumber.api.cli.Main.main(Main.java:16)
</code>```

What I have in code -

Launcher.java -

```<code>package cucumber;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(format={"pretty","json:target/"} , features="/src/test/java/cucumber/features")
public class Launcher {

}
</code>```

Feature file -

```<code>Feature: it works demo

  Scenario: First test
    Given this is my step
    When this is my second step
    Then this is my final step
</code>```

List of Dependencies added to list -

```<code>cucumber-core-1.1.8
cucumber-html-0.2.3
cucumber-java-1.1.8
cucumber-junit-1.1.8
cucumber-jvm-deps-1.0.3
gherkin-2.12.2
hamcrest-all-1.3
junit-4.11
selenium-api-2.42.2
selenium-firefox-driver-2.42.2
selenium-java-2.42.2
selenium-remote-driver-2.42.2
selenium-support-2.42.2
</code>```

My JVM - 1.7

Only this much is available in project.

Please help.

答:
I encountered this same error message when trying to run a Cucumber feature file in Eclipse ("No backends were found. Please make sure you have a backend module on your CLASSPATH").

What fixed it for me was going into my pom.xml and changing the cucumber-java and cucumber-junit versions away from 1.2.5 (per their documentation) to 1.2.0.

I'm not 100% sure if I'm ignoring a real issue by doing this or not. Here is more information about my setup:

Windows 10

Eclipse Neon (4.6.0)

Apache Maven 3.5.0

Java 1.8

I verified via quick commands that java and maven are installed successfully and running on my machine. I also verified that Maven pulled in the cucumber-java, and cucumber-core jars in my Eclipse project. Odd.

Body:
I am developing my Selenium-JVM framework with Cucumber and while running my first feature got below error.

Please help.

How did I launch the feature -

Right click on feature file

Select Run As -> Cucumber Feature

Immediate Exception -

Exception in thread "main" cucumber.runtime.CucumberException: No backends were found. Please make sure you have a backend module on your CLASSPATH.
    at cucumber.runtime.Runtime.<init>(Runtime.java:78)
    at cucumber.runtime.Runtime.<init>(Runtime.java:67)
    at cucumber.runtime.Runtime.<init>(Runtime.java:63)
    at cucumber.api.cli.Main.run(Main.java:24)
    at cucumber.api.cli.Main.main(Main.java:16)

What I have in code -

Launcher.java -

package cucumber;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(format={"pretty","json:target/"} , features="/src/test/java/cucumber/features")
public class Launcher {

}

Feature file -

Feature: it works demo

  Scenario: First test
    Given this is my step
    When this is my second step
    Then this is my final step

List of Dependencies added to list -

cucumber-core-1.1.8
cucumber-html-0.2.3
cucumber-java-1.1.8
cucumber-junit-1.1.8
cucumber-jvm-deps-1.0.3
gherkin-2.12.2
hamcrest-all-1.3
junit-4.11
selenium-api-2.42.2
selenium-firefox-driver-2.42.2
selenium-java-2.42.2
selenium-remote-driver-2.42.2
selenium-support-2.42.2

My JVM - 1.7

Only this much is available in project.

Please help.


答:
You are trying to get the value with getting the object, try this:

```<code>Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
if let result = response.result.value {
    let JSON = result as! NSDictionary
    print(JSON["firstkey"])
}
}
</code>```

Hope it will work!

Title: Alamofire can't access keys of json response

Body:
I'm new to using Alamofire and have encountered an issue. I'm able to run the following code to print out all the data from an API endpoint.

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        print(JSON)
    }
}

The issue is that when I run this:

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
    if let JSON = response.result.value {
        print(JSON["firstkey"])
    }
}

I get the error:

Type 'Any' has no subscript members

I don't know why this error is happening, it seems as if I'm accessing the data correctly. Any help would be great, thanks!

I have tried formatting it using both:

print(JSON["firstkey"] as String)

and

print(JSON["firstkey"] as [String:Any]

but they still give the same error.

This is the JSON on my endpoint:

{
    "firstkey":"it worked!",
    "secondkey":["item1", "item2", "item3"]
}

Body:
You are trying to get the value with getting the object, try this:

Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
if let result = response.result.value {
    let JSON = result as! NSDictionary
    print(JSON["firstkey"])
}
}

Hope it will work!


问:
What should be the `IEnumerable<T>` type for the content of a `.csv` file?
I have a .csv file (Book1.csv) including transitions of a finite state machine:

```<code>q_src,eve,q_dst
q0,sig1,q1
q1,sig2,q2
</code>```

I need to write a method to find the result of a transition.

```<code>State FindDestination(State q0, Event s0)
{
    var transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));
    State newq = from t in transitions
                 where t.q_src ==q0 && t.eve == s0
                 select new t.q_dst;
    return newq;
}
</code>```

But it's not efficient because the method will read the file every time for each transition:

Now if I try to read the file once and pass its content to the method, I don't k
now what type should I use for the transitions in the method's argument:

```<code>var transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));

State FindDestination(State q0, Event s0, ? transitions)   //?type
{
    State newq = from t in transitions
                 where t.q_src ==q0 && t.eve == s0
                 select new t.q_dst;
    return newq;
}
</code>```

Furthermore, State and Event classes have only one attribute Name.

I've read that the rough ideas is using IEnumerable<?>, but what is the ? type for a .csv file?

答:
After splitting each line you will end up with IEnumerable<string[]>

```<code>IEnumerable<string[]> transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));
</code>```

Also all the types return would be System.String

```<code>string FindDestination(State q0, Event s0) {
    var transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));
    var newq = from t in transitions
                 where t[0] == q0.Name && t[1] == s0.Name
                 select t[2];

    return newq.FirstOrDefault();
}
</code>```

So pass an IEnumerable<string[]> to the modified method

```<code>string FindDestination(State q0, Event s0, IEnumerable<string[]> transitions) {

    var newq = from t in transitions
                 where t[0] == q0.Name && t[1] == s0.Name
                 select t[2];

    return newq.FirstOrDefault();
}
</code>```

Body:
I have a .csv file (Book1.csv) including transitions of a finite state machine:

q_src,eve,q_dst
q0,sig1,q1
q1,sig2,q2

I need to write a method to find the result of a transition.

State FindDestination(State q0, Event s0)
{
    var transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));
    State newq = from t in transitions
                 where t.q_src ==q0 && t.eve == s0
                 select new t.q_dst;
    return newq;
}

But it's not efficient because the method will read the file every time for each transition:

Now if I try to read the file once and pass its content to the method, I don't k
now what type should I use for the transitions in the method's argument:

var transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));

State FindDestination(State q0, Event s0, ? transitions)   //?type
{
    State newq = from t in transitions
                 where t.q_src ==q0 && t.eve == s0
                 select new t.q_dst;
    return newq;
}

Furthermore, State and Event classes have only one attribute Name.

I've read that the rough ideas is using IEnumerable<?>, but what is the ? type for a .csv file?

Body:
After splitting each line you will end up with IEnumerable<string[]>

IEnumerable<string[]> transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));

Also all the types return would be System.String

string FindDestination(State q0, Event s0) {
    var transitions = File.ReadAllLines(@"Book1.csv").Skip(1).Select(x => x.Split(','));
    var newq = from t in transitions
                 where t[0] == q0.Name && t[1] == s0.Name
                 select t[2];

    return newq.FirstOrDefault();
}

So pass an IEnumerable<string[]> to the modified method

string FindDestination(State q0, Event s0, IEnumerable<string[]> transitions) {

    var newq = from t in transitions
                 where t[0] == q0.Name && t[1] == s0.Name
                 select t[2];

    return newq.FirstOrDefault();
}


问:
How come you don't need to assign a value to an extern const (int) when including it in a header file? in c++
Usually when declaring a const of any sort you're supposed to assign a value to it immediately, but not in header files? why?</p>

答: Remember not only you don't need to, but you shouldn't assign a value to extern declarations because that makes them a definition.


问:
How do I access a specific dictionary element in a Jina2 template?
I have the following dictionary defined in a python config file:

```<code>AUTHORS = {
    u'MyName Here': {
        u'blurb': """ blurb about author""",
        u'friendly_name': "Friendly Name",
        u'url': 'http://example.com'
    }
}
</code>```

I have the following Jinja2 template:

```<code>{% macro article_author(article) %}
    {{ article.author }}
    {{ AUTHORS }}
    {% if article.author %}
        <a itemprop="url" href="{{ AUTHORS[article.author]['url'] }}" rel="author"><span itemprop="name">{{ AUTHORS[article.author]['friendly_name'] }}</span></a> -
        {{ AUTHORS[article.author]['blurb'] }}
    {% endif %}
{% endmacro %}
</code>```

And I call this via:

```<code><div itemprop="author creator" itemscope itemtype="http://schema.org/Person">
    {% from '_includes/article_author.html' import article_author with context %}
    {{ article_author(article) }}
</div>
</code>```

When I generate my Pelican template I get the following error:

```<code>CRITICAL: UndefinedError: dict object has no element <Author u'MyName Here'>
</code>```

If I remove the {% if article.author %} block from my template, the page generates properly with the {{ AUTHORS }} variable displaying correctly. It clearly has a MyName Here key:

```<code><div itemprop="author creator" itemscope itemtype="http://schema.org/Person">
    MyName Here
    {u'MyName Here': {u'url': u'http://example.com', u'friendly_name': u'Friendly Name', u'blurb': u' blurb about author'}}
</div>
</code>```

How do I access the MyName Here element correctly in my template?

答:
The article.author isn't just 'Your Name', it's an Author instance with various properties. In your case, you want:

{% if article.author %}

        {{ AUTHORS[article.author.name].friendly_name }}
     -
    {{ AUTHORS[article.author.name].blurb }}
{% endif %}
```

<p>or, to reduce some of the boilerplate, you can use:</p>

<pre class="lang-html prettyprint-override"><code>{% if article.author %}
    {% with author = AUTHORS[article.author.name] %}

            <span itemprop="name">{{ author.friendly_name }}</span>
         -
        {{ author.blurb }}
    {% endwith %}
{% endif %}
</code>```

as long as you have 'jinja2.ext.with_'in your JINJA_ENVIRONMENT's extensions list.

Note you can use dot.notation rather than index['notation'] in Jinja templates.

Body:
I have the following dictionary defined in a python config file:

AUTHORS = {
    u'MyName Here': {
        u'blurb': """ blurb about author""",
        u'friendly_name': "Friendly Name",
        u'url': 'http://example.com'
    }
}

I have the following Jinja2 template:

{% macro article_author(article) %}
    {{ article.author }}
    {{ AUTHORS }}
    {% if article.author %}
        {{ AUTHORS[article.author]['friendly_name'] }} -
        {{ AUTHORS[article.author]['blurb'] }}
    {% endif %}
{% endmacro %}

And I call this via:

    {% from '_includes/article_author.html' import article_author with context %}
    {{ article_author(article) }}

When I generate my Pelican template I get the following error:

CRITICAL: UndefinedError: dict object has no element <Author u'MyName Here'>

If I remove the {% if article.author %} block from my template, the page generates properly with the {{ AUTHORS }} variable displaying correctly. It clearly has a MyName Here key:

    MyName Here
    {u'MyName Here': {u'url': u'http://example.com', u'friendly_name': u'Friendly Name', u'blurb': u' blurb about author'}}

How do I access the MyName Here element correctly in my template?

Body:
The article.author isn't just 'Your Name', it's an Author instance with various properties. In your case, you want:

{% if article.author %}
    <a itemprop="url" href="{{ AUTHORS[article.author.name].url }}" rel="author">
        <span itemprop="name">{{ AUTHORS[article.author.name].friendly_name }}</span>
    </a> -
    {{ AUTHORS[article.author.name].blurb }}
{% endif %}

or, to reduce some of the boilerplate, you can use:

{% if article.author %}
    {% with author = AUTHORS[article.author.name] %}
        <a itemprop="url" href="{{ author.url }}" rel="author">
            <span itemprop="name">{{ author.friendly_name }}</span>
        </a> -
        {{ author.blurb }}
    {% endwith %}
{% endif %}

as long as you have 'jinja2.ext.with_'in your JINJA_ENVIRONMENT's extensions list.

Note you can use dot.notation rather than index['notation'] in Jinja templates.


问:
Cannot start mosquitto as service on docker container
I created an image from a Dockerfile:

```<code>FROM debian:latest

RUN apt-get update && apt-get install -y \
mosquitto \
&& rm -rf /var/lib/apt/lists/*

# mosquitto setup
EXPOSE 1883
COPY config/broker/conf.d/ /etc/mosquitto/conf.d/
CMD mosquitto
</code>```

This works, but I'd like to start mosquitto as a service (is it recommended at all?). But when I replace the last line with

```<code>CMD service mosquitto start
</code>```

the service doesn't start & I the container isn't running (but I don't get an error message during image creation)

答: Using a container as a way to start a host service seems to me to be missing the point of containers.  Apps that are "containerized" should be such that they can be started/stopped at anytime.  If you are looking to have a long-running container that provides a service that you want to always be running, then add the --restart=always option on to your docker run command.  That way when the host starts/restarts, and the Docker service is started, your container will auto-start as well. A good list of do's & don'ts about containerized apps is The 12 Factor App

Body:
I created an image from a Dockerfile:

FROM debian:latest

RUN apt-get update && apt-get install -y \
mosquitto \
&& rm -rf /var/lib/apt/lists/*

# mosquitto setup
EXPOSE 1883
COPY config/broker/conf.d/ /etc/mosquitto/conf.d/
CMD mosquitto

This works, but I'd like to start mosquitto as a service (is it recommended at all?). But when I replace the last line with

CMD service mosquitto start

the service doesn't start & I the container isn't running (but I don't get an error message during image creation)


问:
Issues with nesting components after upgrading to newer versions of TypeScript
I recently upgraded from TypeScript 2.1 and with all of the newer versions I started getting the error below with all of my React Components that follow the pattern in my example. This pattern of nesting components didn't used to cause any problem before the upgrade.

Component #1:

```<code>interface ISpinnerProps{
    showGlobalSpinner: boolean;
}

class SpinnerClass extends React.Component<ISpinnerProps, undefined> {
    render() {
         return (
         // Some markup
         )
    }
}

export const Spinner = connect((state: State) => {
  return {
    showGlobalSpinner: selectors.showGlobalSpinner(state),
  }
})(SpinnerClass)
</code>```

Component #2:

```<code>interface IProps {
   loginStatus: fb.LoginStatus
}

class AppClass extends React.Component<IProps, undefined> {
    render() {
         return (
         // Some markup
         <Spinner/> // Error is thrown here.
         )
    }
}
export const App = connect(mapStateToProps, actionCreators)(AppClass)
</code>```

This causes the error:
Type '{}' is not assignable to type 'Readonly<ISpinnerProps>'. Property 'showGlobalSpinner' is missing in type '{}

The compiler wants me to set the properties of the children in the parent but these properties are handled by Redux. Has anyone encountered a similar issue?

答:
What you need to do is separate your props into props and actions mapped from redux (IMappedProps and IMappedActions) and props that you expect to be passed into your component from a parent component (IOwnProps).

Then in your connect function you are able to specify which props are which.

```<code>export default connect<IMappedProps, IMappedActions, IOwnProps>(mapStateToProps, mapDistpatchToProps)(SpinnerClass);
</code>```

In your case, the spinner component only has one prop that is mapped from redux. Your connect function could look like this:

```<code>export default connect<ISpinnerProps, null, null>(mapStateToProps, null)(SpinnerClass);
</code>```

Note for clarity I'd suggest renaming ISpnnerProps to IMappedProps.

For further reference see the react-redux typescript definition - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-redux/index.d.ts

Body:
I recently upgraded from TypeScript 2.1 and with all of the newer versions I started getting the error below with all of my React Components that follow the pattern in my example. This pattern of nesting components didn't used to cause any problem before the upgrade.

Component #1:

interface ISpinnerProps{
    showGlobalSpinner: boolean;
}

class SpinnerClass extends React.Component<ISpinnerProps, undefined> {
    render() {
         return (
         // Some markup
         )
    }
}

export const Spinner = connect((state: State) => {
  return {
    showGlobalSpinner: selectors.showGlobalSpinner(state),
  }
})(SpinnerClass)

Component #2:

interface IProps {
   loginStatus: fb.LoginStatus
}

class AppClass extends React.Component<IProps, undefined> {
    render() {
         return (
         // Some markup
         <Spinner/> // Error is thrown here.
         )
    }
}
export const App = connect(mapStateToProps, actionCreators)(AppClass)

This causes the error:
Type '{}' is not assignable to type 'Readonly<ISpinnerProps>'. Property 'showGlobalSpinner' is missing in type '{}

The compiler wants me to set the properties of the children in the parent but these properties are handled by Redux. Has anyone encountered a similar issue?

Body:
What you need to do is separate your props into props and actions mapped from redux (IMappedProps and IMappedActions) and props that you expect to be passed into your component from a parent component (IOwnProps).

Then in your connect function you are able to specify which props are which.

export default connect<IMappedProps, IMappedActions, IOwnProps>(mapStateToProps, mapDistpatchToProps)(SpinnerClass);

In your case, the spinner component only has one prop that is mapped from redux. Your connect function could look like this:

export default connect<ISpinnerProps, null, null>(mapStateToProps, null)(SpinnerClass);

Note for clarity I'd suggest renaming ISpnnerProps to IMappedProps.

For further reference see the react-redux typescript definition - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-redux/index.d.ts


问:
Extract the filename from a path
I want to extract filename from below path:

```D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv```

Now I wrote this code to get filename. This working fine as long as the folder level didn't change. But in case the folder level has been changed, this code need to rewrite. I looking a way to make it more flexible such as the code can always extract filename regardless of the folder level.

($outputFile).split('\')[9].substring(0)
```

答:
Use .NET:

[System.IO.Path]::GetFileName("c:\foo.txt") returns foo.txt.
[System.IO.Path]::GetFileNameWithoutExtension("c:\foo.txt") returns foo

Title: Extract the filename from a path

Body:
I want to extract filename from below path:

D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv

Now I wrote this code to get filename. This working fine as long as the folder level didn't change. But in case the folder level has been changed, this code need to rewrite. I looking a way to make it more flexible such as the code can always extract filename regardless of the folder level.

($outputFile).split('\')[9].substring(0)


问:
npm install jquery error / saveError ENOENT / Invalid dependency
I'm having trouble to resolve this issue. I've searched around but not getting anywhere. I've just started learning MEAN Stack. I'm trying to install all components for the Stack. (I currently have programs installed for Python Stack and Ruby Stack). Not sure if those will have anything to do with my problem. I'm still new to programming. Any info would be greatly appreciated.

Here is what I'm running currently:

MacOS Sierra v10.12.5

Node v8.0.0

npm v5.0.0

I've installed:

```<code>$ npm install nodemon
</code>```

(-g)..global was giving me a problem so I installed without it.

```<code>$ npm install bower
</code>```

(-g)..global was also giving me a problem so I installed without it.

Then when I tried to install:

```<code>$ npm install jquery
</code>```

I was getting errors.
Here is what it says..

```<code>npm WARN saveError ENOENT: no such file or directory, open '/Users/jaepark75/package.json'
npm WARN enoent ENOENT: no such file or directory, open  '/Users/jaepark75/package.json'
npm WARN jaepark75 No description
npm WARN jaepark75 No repository field.
npm WARN jaepark75 No README data
npm WARN jaepark75 No license field.
npm WARN jaepark75 Invalid dependency: balanced-match undefined
npm WARN jaepark75 Invalid dependency: block-stream undefined
npm WARN jaepark75 Invalid dependency: brace-expansion undefined
npm WARN jaepark75 Invalid dependency: concat-map undefined
npm WARN jaepark75 Invalid dependency: fs.realpath undefined
npm WARN jaepark75 Invalid dependency: fstream undefined
npm WARN jaepark75 Invalid dependency: glob undefined
npm WARN jaepark75 Invalid dependency: graceful-fs undefined
npm WARN jaepark75 Invalid dependency: hammerjs undefined
npm WARN jaepark75 Invalid dependency: inflight undefined
npm WARN jaepark75 Invalid dependency: inherits undefined
npm WARN jaepark75 Invalid dependency: materialize-css undefined
npm WARN jaepark75 Invalid dependency: minimatch undefined
npm WARN jaepark75 Invalid dependency: minimist undefined
npm WARN jaepark75 Invalid dependency: mkdirp undefined
npm WARN jaepark75 Invalid dependency: node-archiver undefined
npm WARN jaepark75 Invalid dependency: once undefined
npm WARN jaepark75 Invalid dependency: path-is-absolute undefined
npm WARN jaepark75 Invalid dependency: rimraf undefined
npm WARN jaepark75 Invalid dependency: tar undefined
npm WARN jaepark75 Invalid dependency: wrappy undefined

added 1 package in 2.742s
</code>```

Thank you for taking the time to look at this.

答: So first of all you should use cd C:\ and the Directory to where your server file will be. Then you need to use npm init fill out all infos of your project. Then you can use the npm like above with npm install jquery --save.

Body:
I'm having trouble to resolve this issue. I've searched around but not getting anywhere. I've just started learning MEAN Stack. I'm trying to install all components for the Stack. (I currently have programs installed for Python Stack and Ruby Stack). Not sure if those will have anything to do with my problem. I'm still new to programming. Any info would be greatly appreciated.

Here is what I'm running currently:

MacOS Sierra v10.12.5

Node v8.0.0

npm v5.0.0

I've installed:

$ npm install nodemon

(-g)..global was giving me a problem so I installed without it.

$ npm install bower

(-g)..global was also giving me a problem so I installed without it.

Then when I tried to install:

$ npm install jquery

I was getting errors.
Here is what it says..

npm WARN saveError ENOENT: no such file or directory, open '/Users/jaepark75/package.json'
npm WARN enoent ENOENT: no such file or directory, open  '/Users/jaepark75/package.json'
npm WARN jaepark75 No description
npm WARN jaepark75 No repository field.
npm WARN jaepark75 No README data
npm WARN jaepark75 No license field.
npm WARN jaepark75 Invalid dependency: balanced-match undefined
npm WARN jaepark75 Invalid dependency: block-stream undefined
npm WARN jaepark75 Invalid dependency: brace-expansion undefined
npm WARN jaepark75 Invalid dependency: concat-map undefined
npm WARN jaepark75 Invalid dependency: fs.realpath undefined
npm WARN jaepark75 Invalid dependency: fstream undefined
npm WARN jaepark75 Invalid dependency: glob undefined
npm WARN jaepark75 Invalid dependency: graceful-fs undefined
npm WARN jaepark75 Invalid dependency: hammerjs undefined
npm WARN jaepark75 Invalid dependency: inflight undefined
npm WARN jaepark75 Invalid dependency: inherits undefined
npm WARN jaepark75 Invalid dependency: materialize-css undefined
npm WARN jaepark75 Invalid dependency: minimatch undefined
npm WARN jaepark75 Invalid dependency: minimist undefined
npm WARN jaepark75 Invalid dependency: mkdirp undefined
npm WARN jaepark75 Invalid dependency: node-archiver undefined
npm WARN jaepark75 Invalid dependency: once undefined
npm WARN jaepark75 Invalid dependency: path-is-absolute undefined
npm WARN jaepark75 Invalid dependency: rimraf undefined
npm WARN jaepark75 Invalid dependency: tar undefined
npm WARN jaepark75 Invalid dependency: wrappy undefined

added 1 package in 2.742s

Thank you for taking the time to look at this.


问:
Rename ttf/woff/woff2 file to PostScript Font Name with Script
I am a typographer working with many fonts that have incorrect or incomplete filenames. I am on a Mac and have been using Hazel, AppleScript, and Automator workflows, attempting to automate renaming these files*.  I require a script to replace the existing filename of ttf, woff, or woff2 files in Finder with the font's postscriptName. I know of tools (fc-scan/fontconfig, TTX, etc) which can retrieve the PostScript name-values I require, but lack the programming knowhow to code a script for my purposes. I've only managed to setup a watched directory that can run a script when any files matching certain parameters are added.

*To clarify, I am talking about changing the filename only, not the actual names stored within the font.  Also I am open to a script of any compatible language or workflow of scripts if possible, e.g. this post references embedding AppleScript within Shell scripts via osascript.

StackExchange Posts I've Consulted:

How to get Fontname from OTF or TTF File?

How to get PostScript name of TTF font in OS X?

How to Change Name of Font?

Automate Renaming Files in macOS

Others:

https://github.com/dtinth/JXA-Cookbook/wiki/Using-JavaScript-for-Automation

https://github.com/fonttools/fonttools

https://github.com/devongovett/fontkit

https://www.npmjs.com/package/rename-js

https://opentype.js.org/font-inspector.html

http://www.fontgeek.net/blog/?p=343

https://www.lantean.co/osx-renaming-fonts-for-free

Edit: Added the following by request.

1)  Screenshot of a somewhat typical webfont, illustrating how the form fields for font family and style names are often incomplete, blank, or contain illegal characters.

2)  The woff file depicted (also, as base64).

Thank you all in advance!

答:
Since you mentioned Automator in your question, I thought I'd try and solve this while using that to rename the file, along with standard Mac bash to get the font name. Hopefully, it beats learning a whole programming language.

I don't know what your workflow is so I'll leave any deviations to you but here is a method to select a font file and from Services, rename the file to the font's postscript name… based on Apple's metadata, specifically "com_apple_ats_name_postscript". This is one of the pieces of data retrieved using 'mdls' from the Terminal on the font file. To focus on the postscript name, grep the output for name_postscript. For simplicity here, I'll exclude the path to the selected file.

Font Name Aquisition

So… running this command…

mdls GenBkBasBI.ttf | grep -A1 name_postscript

… generates this output, which contains FontBook's Postscript name. The 'A1' in grep returns the found line and the first line after, which is the one containing the actual font name.

```<code>com_apple_ats_name_postscript  = (
    "GentiumBookBasic-BoldItalic"
</code>```

Clean this up with some more bash (tr, tail)…

```<code>tr -d \  | tail -n 1 | tr -d \"
</code>```

In order, these strip spaces, all lines excepting the last, and quotation marks. So for the first 'tr' instance, there is an extra space after the backslash.

In a single line, it looks like this…

```<code>mdls GenBkBasBI.ttf | grep -A1 name_postscript | tr -d \  | tail -n 1 | tr -d \"
</code>```

…and produces this…

```<code>GentiumBookBasic-BoldItalic
</code>```

Now, here is the workflow that includes the above bash command. I got the idea for variable usage from the answer to this question…

Apple Automator “New PDF from Images” maintaining same filename

Automator Workflow

Automator Workflow screenshot

At the top; Service receives selected 'files or folders' in 'Finder'.

Get Selected Finder Items

This (or Get Specified…) is there to allow testing. It is obviated by using this as a Service.

Set Value of Variable (File)

This is to remember which file you want to rename

Run Shell Script

This is where we use the bash stuff. The $f is the selected/specified file. I'm running 'zsh' for whatever reason. You can set it to whatever you're running, presumably 'bash'.

Set Value of Variable (Text)

Assign the bash output to a variable. This will be used by the last action for the new filename.

Get Value of Variable (File)

Recall the specified/selected file to rename.

Rename Finder Items: Name Single Item

I have it set to 'Basename only' so it will leave the extension alone. Enter the 'Text' variable from action 4 in here.

Body:
Since you mentioned Automator in your question, I thought I'd try and solve this while using that to rename the file, along with standard Mac bash to get the font name. Hopefully, it beats learning a whole programming language.

I don't know what your workflow is so I'll leave any deviations to you but here is a method to select a font file and from Services, rename the file to the font's postscript name… based on Apple's metadata, specifically "com_apple_ats_name_postscript". This is one of the pieces of data retrieved using 'mdls' from the Terminal on the font file. To focus on the postscript name, grep the output for name_postscript. For simplicity here, I'll exclude the path to the selected file.

Font Name Aquisition

So… running this command…

mdls GenBkBasBI.ttf | grep -A1 name_postscript

… generates this output, which contains FontBook's Postscript name. The 'A1' in grep returns the found line and the first line after, which is the one containing the actual font name.

com_apple_ats_name_postscript  = (
    "GentiumBookBasic-BoldItalic"

Clean this up with some more bash (tr, tail)…

tr -d \  | tail -n 1 | tr -d \"

In order, these strip spaces, all lines excepting the last, and quotation marks. So for the first 'tr' instance, there is an extra space after the backslash.

In a single line, it looks like this…

mdls GenBkBasBI.ttf | grep -A1 name_postscript | tr -d \  | tail -n 1 | tr -d \"

…and produces this…

GentiumBookBasic-BoldItalic

Now, here is the workflow that includes the above bash command. I got the idea for variable usage from the answer to this question…

Apple Automator “New PDF from Images” maintaining same filename

Automator Workflow

Automator Workflow screenshot

At the top; Service receives selected 'files or folders' in 'Finder'.

Get Selected Finder Items

This (or Get Specified…) is there to allow testing. It is obviated by using this as a Service.

Set Value of Variable (File)

This is to remember which file you want to rename

Run Shell Script

This is where we use the bash stuff. The $f is the selected/specified file. I'm running 'zsh' for whatever reason. You can set it to whatever you're running, presumably 'bash'.

Set Value of Variable (Text)

Assign the bash output to a variable. This will be used by the last action for the new filename.

Get Value of Variable (File)

Recall the specified/selected file to rename.

Rename Finder Items: Name Single Item

I have it set to 'Basename only' so it will leave the extension alone. Enter the 'Text' variable from action 4 in here.


问:
c++ 2D array row sort based on average row value
Helo,

I'm wondering if there's any working method for this?
I'm trying make this work, but no luck.

```<code>int mat[3][3];

    mat[0][0] = 4;mat[0][1] = 5;mat[0][2] = 3;

    mat[1][0] = 3;mat[1][1] = 2;mat[1][2] = 1;

    mat[2][0] = 1;mat[2][1] = 8;mat[2][2] = 9;
</code>```

Any idea? :)

答:
Following @Peter's suggestion,

```<code>#include <algorithm>
#include <numeric>
#include <vector>
using namespace std;

bool comp(vector<int> a, vector<int> b) {
    if (a.size() == 0 || b.size() == 0) return false;
    int sum_a = accumulate(a.begin(), a.end(), 0);
    int sum_b = accumulate(b.begin(), b.end(), 0);
    return sum_a / (double)a.size() < sum_b / (double)b.size();
}

int main() {
    vector<vector<int> > mat(3, vector<int>(3));
    mat[0][0] = 4; mat[0][1] = 5; mat[0][2] = 3;
    mat[1][0] = 3; mat[1][1] = 2; mat[1][2] = 1;
    mat[2][0] = 1; mat[2][1] = 8; mat[2][2] = 9;
    sort(mat.begin(), mat.end(), comp);
    return 0;
}
</code>```

I wasn't sure of the best way to handle empty vectors, so I just had it return false. Of course you could give comp() a more meaningful name.

EDIT: I think a better way to handle zero-sized vectors is to multiply,

```<code>bool comp(vector<int> a, vector<int> b) {
    int sum_a = accumulate(a.begin(), a.end(), 0);
    int sum_b = accumulate(b.begin(), b.end(), 0);
    return sum_a * b.size() < sum_b * a.size();
}
</code>```

Body:
Helo,

I'm wondering if there's any working method for this?
I'm trying make this work, but no luck.

int mat[3][3];

    mat[0][0] = 4;mat[0][1] = 5;mat[0][2] = 3;

    mat[1][0] = 3;mat[1][1] = 2;mat[1][2] = 1;

    mat[2][0] = 1;mat[2][1] = 8;mat[2][2] = 9;

Any idea? :)

Body:
Following @Peter's suggestion,

#include <algorithm>
#include <numeric>
#include <vector>
using namespace std;

bool comp(vector<int> a, vector<int> b) {
    if (a.size() == 0 || b.size() == 0) return false;
    int sum_a = accumulate(a.begin(), a.end(), 0);
    int sum_b = accumulate(b.begin(), b.end(), 0);
    return sum_a / (double)a.size() < sum_b / (double)b.size();
}

int main() {
    vector<vector<int> > mat(3, vector<int>(3));
    mat[0][0] = 4; mat[0][1] = 5; mat[0][2] = 3;
    mat[1][0] = 3; mat[1][1] = 2; mat[1][2] = 1;
    mat[2][0] = 1; mat[2][1] = 8; mat[2][2] = 9;
    sort(mat.begin(), mat.end(), comp);
    return 0;
}

I wasn't sure of the best way to handle empty vectors, so I just had it return false. Of course you could give comp() a more meaningful name.

EDIT: I think a better way to handle zero-sized vectors is to multiply,

bool comp(vector<int> a, vector<int> b) {
    int sum_a = accumulate(a.begin(), a.end(), 0);
    int sum_b = accumulate(b.begin(), b.end(), 0);
    return sum_a * b.size() < sum_b * a.size();
}


问:
Get the keys with the biggest values from a hashmap?
I have a HashMap defined like this...

```<code>HashMap<String,Integer> uniqueNames = new HashMap<String,Integer>();
</code>```

It stores a name, and the occurence of that name. For example...

```<code>uniqueNames.put("lastname",42);
</code>```

How can I get the name with the highest occurrence?

For some more information, I'm working with a binary search tree of "people", storing the unique names and frequencies in a HashMap. What I want to do is to print the most common last names, and someone told me to use HashMap as I wanted to store a String together with an Integer. Maybe I should use a class to store the name and frequency instead? Could someone please offer some suggestions.

答:
This is my approach.</p>

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class FindWordCounter {

public static void main(String[] args) {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

    try {

        System.out.println("Enter the sentence: ");
        String sentence = bufferedReader.readLine();
        FindWordCounter.countWord(sentence);

    }   catch (IOException e) {

        System.out.println(e);

    }
}

public static void countWord(String sentence) {

    Map<String, Integer> hashMap = new HashMap<String, Integer>();
    String[] word = sentence.toLowerCase().split(" ");

    for (int i=0; i<word.length; i++) {

        if (hashMap.containsKey(word[i])) {

            int count = hashMap.get(word[i]);
            hashMap.put(word[i], count + 1);

        }
        else {
            hashMap.put(word[i], 1);
        }
    }

    Entry<String,Integer> maxCount = null;

    for(Entry<String,Integer> entry : hashMap.entrySet()) {

        if (maxCount == null || entry.getValue() > maxCount.getValue()) {
            maxCount = entry;

        }
    }

    System.out.println("The word with maximum occurence is: " + maxCount.getKey()
                            + " and the number of occurence is: " + maxCount.getValue());
}

}
</code>```

Body:
I have a HashMap defined like this...

HashMap<String,Integer> uniqueNames = new HashMap<String,Integer>();

It stores a name, and the occurence of that name. For example...

uniqueNames.put("lastname",42);

How can I get the name with the highest occurrence?

For some more information, I'm working with a binary search tree of "people", storing the unique names and frequencies in a HashMap. What I want to do is to print the most common last names, and someone told me to use HashMap as I wanted to store a String together with an Integer. Maybe I should use a class to store the name and frequency instead? Could someone please offer some suggestions.

Body:
This is my approach.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class FindWordCounter {

public static void main(String[] args) {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

    try {

        System.out.println("Enter the sentence: ");
        String sentence = bufferedReader.readLine();
        FindWordCounter.countWord(sentence);

    }   catch (IOException e) {

        System.out.println(e);

    }
}

public static void countWord(String sentence) {

    Map<String, Integer> hashMap = new HashMap<String, Integer>();
    String[] word = sentence.toLowerCase().split(" ");

    for (int i=0; i<word.length; i++) {

        if (hashMap.containsKey(word[i])) {

            int count = hashMap.get(word[i]);
            hashMap.put(word[i], count + 1);

        }
        else {
            hashMap.put(word[i], 1);
        }
    }

    Entry<String,Integer> maxCount = null;

    for(Entry<String,Integer> entry : hashMap.entrySet()) {

        if (maxCount == null || entry.getValue() > maxCount.getValue()) {
            maxCount = entry;

        }
    }

    System.out.println("The word with maximum occurence is: " + maxCount.getKey()
                            + " and the number of occurence is: " + maxCount.getValue());
}

}