text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Domain Controller without DNS on remote site fails to authenticate
We have a domain controller at our remote site that doesn't have any DNS server or DNS replication. I have just setup a client machine that was using a local account to instead use a domain account. It connected to the domain fine but I couldn't login at first as it could not contact a logon server.
I tried the normal hosts file to link the domain name to the IP of the DC but this didn't work.
I changed the domain controller DNS to look at the primary DC over demand-dial VPN.
I changed the client DNS to look at the domain controller DNS.
Now I can login and authenticate to the domain but it is very slow. I can't configure certain things that rely on the domain such as adding domain users to the remote desktop users and GPupdate is failing too.
If I go to %logonserver% I get to the domain controller I want to be connected to.
I figure I am wrong that I can get DNS from the primary DC by client -> DC(secondary) -> VPN -> DC(primary).
Could you advise on a better DNS configuration? Should I not be reconfiguring the network adapter DNS to do this and instead be using LMhosts to force the client to authenticate to the domain controller.
TIA.
Kind regards,
James
A:
First of all, Windows 2000+ (Active Directory) does not have a concept of primary and secondary domain controllers. Domain Controllers are "equal" (see What is Active Directory Chapter "Availability concerns"
To your problem: I would suggest that you setup your DC in the Branch office as a DNS Server, and your problems are likely going away. Its a good practice to have Domain Controller as well as DNS in branch offices.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I deal with localStorage in jest tests?
I keep getting "localStorage is not defined" in Jest tests which makes sense but what are my options? Hitting brick walls.
A:
Great solution from @chiedo
However, we use ES2015 syntax and I felt it was a little cleaner to write it this way.
class LocalStorageMock {
constructor() {
this.store = {};
}
clear() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = value.toString();
}
removeItem(key) {
delete this.store[key];
}
};
global.localStorage = new LocalStorageMock;
A:
Figured it out with help from this: https://groups.google.com/forum/#!topic/jestjs/9EPhuNWVYTg
Setup a file with the following contents:
var localStorageMock = (function() {
var store = {};
return {
getItem: function(key) {
return store[key];
},
setItem: function(key, value) {
store[key] = value.toString();
},
clear: function() {
store = {};
},
removeItem: function(key) {
delete store[key];
}
};
})();
Object.defineProperty(window, 'localStorage', { value: localStorageMock });
Then you add the following line to your package.json under your Jest configs
"setupTestFrameworkScriptFile":"PATH_TO_YOUR_FILE",
A:
If using create-react-app, there is a simpler and straightforward solution explained in the documentation.
Create src/setupTests.js and put this in it :
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
Tom Mertz contribution in a comment below :
You can then test that your localStorageMock's functions are used by doing something like
expect(localStorage.getItem).toBeCalledWith('token')
// or
expect(localStorage.getItem.mock.calls.length).toBe(1)
inside of your tests if you wanted to make sure it was called. Check out https://facebook.github.io/jest/docs/en/mock-functions.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Accessibility services gets disabled automatically
I have a Gionee p3s. I was trying to use tasker when i observed that the tasker accessibility service gets disabled automatically after a few minutes. Not only with tasker, all apps requiring accessibility services are having the same problem.
My android version is 5.1. It will be helpful if some one can help me with this problem. :-)
A:
I was facing the same issue on my Lenovo vibe k5. I did the followings to solve the issue.
Enable accessibility for the concerned app in the Settings.
In power saving option (in most cases it is inside the "Battery" option) select the concerned app not to be optimized.
Select the app as device administrator (this setting may be found inside "Security" option).
If possible lock the app in Task Manager so that it will not be killed when you kill all the tasks(apps). In "mi" phones you need to slide the app downward to lock it in Task Manager. I don't know how to do it in Gionee p3s. In my device this option is not available so I never kill the concerned app in the Task Manager( Or if I kill the app I re-enable the accessibility, then it remains enabled until I kill that app again).
After doing these the Accessibility option remained enabled even after restarting the phone.
This may not be the exact solution you asking for, but this is all I found after hours of searching.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is ice less dense than water?
I know the traditional explanation, which says that ice has large spaces between $\ce{H2O}$ molecules because hydrogen-bonding gives it an open structure. But what does the open structure have to do with hydrogen-bonding? Why isn't a similar phenomenon observed in other species which exhibit hydrogen-bonding, like $\ce{HF}$ or $\ce{NH3}$?
A:
The following is an image of the hexagonal crystaline form of ordinary ice (Ice I$_h$) taken from S.S. Zumdahl, Chemistry, 3rd ed., copyright © 1993 by D.C. Heath and Company:
Note that the dashed lines represent hydrogen bonds. Liquid water actually has a similar "open" structure also due to hydrogen bonding. But in the case of liquid water, the hydrogen bonds are not rigid and semi-permanent as in ice. So imagine that in the image above, the hydrogen bonding network collapses. This is what happens when enough thermal energy is present to break the rigid hydrogen bonds resulting in melting. Clearly, once this crystaline structure is no longer forced into place by the rigid hydrogen bonding in ice, it can collapse into itself, resulting a greater density of water molecules.
Thus the liquid form of water, although engaged in transient hydrogen bonding, is not as open and expanded as when held into it's solid form by the rigid, semi-permanent hydrogen bonding.
| {
"pile_set_name": "StackExchange"
} |
Q:
Item (Mage_SalesRule_Model_Rule) with the same id "5" already exist
I am trying to debug this error which happens whenever a logged in customer adds a coupon code during checkout.
a:5:{i:0;s:67:"Item (Mage_SalesRule_Model_Rule) with the same id "5" already exist";i:1;s:1977:"#0 /var/www/vhosts/test.devcom/httpdocs/lib/Varien/Data/Collection/Db.php(576): Varien_Data_Collection->addItem(Object(Mage_SalesRule_Model_Rule))
#1 /var/www/vhosts/test.dev.com/httpdocs/app/code/core/Mage/SalesRule/Model/Validator.php(117): Varien_Data_Collection_Db->load()
#2 /var/www/vhosts/test.dev.com/httpdocs/app/code/core/Mage/SalesRule/Model/Quote/Freeshipping.php(60): Mage_SalesRule_Model_Validator->init('1', '1', 'INSTA20')
#3 /var/www/vhosts/test.dev.com/httpdocs/app/code/core/Mage/Sales/Model/Quote/Address.php(1013): Mage_SalesRule_Model_Quote_Freeshipping->collect(Object(Mage_Sales_Model_Quote_Address))
#4 /var/www/vhosts/test.dev.com/httpdocs/app/code/core/Mage/Sales/Model/Quote.php(1331): Mage_Sales_Model_Quote_Address->collectTotals()
#5 /var/www/vhosts/test.dev.com/httpdocs/app/code/core/Mage/Checkout/Model/Cart.php(458): Mage_Sales_Model_Quote->collectTotals()
#6 /var/www/vhosts/test.dev.com/httpdocs/app/code/core/Mage/Checkout/controllers/CartController.php(127): Mage_Checkout_Model_Cart->save()
#7 /var/www/vhosts/test.dev.com/httpdocs/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Checkout_CartController->indexAction()
#8 /var/www/vhosts/test.dev.com/httpdocs/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('index')
#9 /var/www/vhosts/test.dev.com/httpdocs/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#10 /var/www/vhosts/test.dev.com/httpdocs/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#11 /var/www/vhosts/test.dev.com/httpdocs/app/Mage.php(683): Mage_Core_Model_App->run(Array)
#12 /var/www/vhosts/test.dev.com/httpdocs/index.php(87): Mage::run('', 'store')
#13 {main}";s:3:"url";s:15:"/checkout/cart/";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:7:"default";}
I'm not sure what is causing the error since the coupon code works when checking out as a guest.
Has anyone had this error before and know what the cause could be? I'd appreciate any assistance please...
A:
Please do take a backup of code:
Go to file
lib/Varien/Data/Collection.php
Modify this method
public function addItem
With the following code
public function addItem(Varien_Object $item)
{
$itemId = $this->_getItemId($item);
if (!is_null($itemId)) {
if (isset($this->_items[$itemId])) {
// throw new Exception('Item ('.get_class($item).') with the same id "'.$item->getId().'" already exist');
} else {
$this->_items[$itemId] = $item;
}
}
else {
$this->_items[] = $item;
}
return $this;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
filter the table by a search query with search fields is in a dictionary
I have a dictionary & a string value like:
d= {"check-in": "12-04-2016", "check-out": "13-04-2016", "location": "India"}
value = 'india'
search = d['check-in']
Here I am reading the keys which are a column name in my DB table.
Note: Here everything is dynamic that means value of columns are dynamically set.
I want to query with multiple filter in django such a way that i ll get all details set by dictionary(d). That means i want to filter by multiple column values.
Query i wrote:
modelInstance.objects.filter(search = value).
Here i am getting error.
If someone don't understand please tell i ll explain more
Here i a storing the column name in a string like:
field = "check-in"
looping a for loop to get all the column name
Error:
FieldError: Cannot resolve keyword 'field' into field
A:
You can use ** (unpacking argument) to expand dictionary into keyword arguments.
Before doing that, you need to convert query keys to field names, for example check-in to check_in_date (assuming actual field name in check_in_date)
query_to_field_mapping = {
'check-in': 'check_in_date',
'check-out': 'check_out_date',
'location': 'location',
}
d = {"check-in": "12-04-2016", "check-out": "13-04-2016", "location": "India"}
query = {query_to_field_mapping[key]: value for key, value in d.items()}
objects = Model.objects.filter(**query)
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it mandatory to change the Google Map api V1 to V2
In my app, I am using Google Map API V1 and it is in Google play; so is it mandatory to upgrade to V2 or I can go ahead with this for future? Regularly we are upgrading the app?
If I upgrade the Map API to V2, then do I need to change the app signing key?
Please help.
A:
The sad answer is that most of the objects of Google Map API V1 are replaced with new Objects in Google Map API V2.
For example instead of using GeoPoints you are going to use Latlng points. Overlays are gone as well and replaced with Polylines and Polygones.
Take a look at this answer I gave here:
Convert Android App that uses maps API V1 to Maps Android API V2
And have a look at this blog post I wrote that will get you started with Google Map API V2 implementation in your app:
Google Map API V2
So as you can understand most of the code should be rewritten to fit Google Map API V2.
Basically the changes you would have to make are
Replace the MapView object with a MapFragment or SupportMapFragment object (depending on the target SDK of your application)
In additin you will have to repalce the MapActivity with a normal Activity (if you use the MapFragment object) or the FragmentActivity (if you use the SupportMapFragment object).
You will have to change the permissions in the manifest file to new ones, that are described in the guide.
Yes of course you need to change the API key also....
| {
"pile_set_name": "StackExchange"
} |
Q:
How Get Cumulative Sum (with Sum of the Past) in SQL Server
I work with SQL Server 2008.
In my db I have a table items that has this sample data:
id |date |title |price
-----------------------------------
1 |20150310 |A |100
2 |20150201 |B |25
3 |20140812 |C |225
4 |20130406 |D |110
5 |20150607 |E |645
6 |20120410 |F |450
7 |20130501 |G |325
8 |20150208 |H |175
I want to have a cumulative sum of the price column after 20150101 (with sum of the past).
In fact I want the results exactly like this:
date |title |price |cum_sum |before_cum_sum
---------------------------------------------------------------
|sum of past | | |1110
20150201 |B |25 |1135 |
20150208 |H |175 |1310 |
20150310 |A |100 |1410 |
20150607 |E |645 |2055 |
How get the result like that in SQL Server ?
A:
OP wants specific output - so I comply:
DECLARE @items TABLE ([date] DATETIME, title VARCHAR (100), price MONEY)
INSERT @items VALUES ('20150310','A',100), ('20150201','B',25 ), ('20140812','C',225), ('20130406','D',110), ('20150607','E',645), ('20120410','F',450), ('20130501','G',325), ('20150208','H',175)
;WITH p_cte AS (
SELECT
*
, RowNo = ROW_NUMBER() OVER (ORDER BY DATE)
FROM
@items
),
p2_cte AS (
SELECT
p_cte.date
, p_cte.title
, p_cte.price
, p_cte.RowNo
, cum_sum = price
, before_cum_sum = CONVERT (MONEY, 0)
FROM
p_cte
WHERE p_cte.RowNo = 1
UNION ALL
SELECT
cur.date
, cur.title
, cur.price
, cur.RowNo
, cum_sum = cur.price + prev.cum_sum
, before_cum_sum = prev.cum_sum
FROM
p_cte cur
INNER JOIN p2_cte prev ON
prev.RowNo = cur.RowNo - 1
)
SELECT TOP 1
date = CONVERT (DATETIME, NULL)
, title = 'sum of past'
, price = CONVERT (MONEY, NULL)
, rowno = CONVERT (INT, NULL)
, cum_sum = CONVERT (MONEY, NULL)
, p2_cte.before_cum_sum
FROM p2_cte WHERE date > '20150101'
UNION ALL
SELECT
*
FROM p2_cte WHERE date > '20150101'
Output looks like this:
| {
"pile_set_name": "StackExchange"
} |
Q:
What mean this expression in Generic
Can someone please explain to me what this expression in java means:
class BinaryNode<AnyType extends Comparable<? super AnyType>>
What does "AnyType extends Comparable" mean?
A:
This declares a generic type parameter called AnyType. The rest of the declaration, extends Comparable<? super AnyType>, places an upper bound on what AnyType can be. Specifically, whatever AnyType is must be Comparable, and Comparable's type argument can be what AnyType is, or anything that is a superclass of that type. E.g. it could be Integer, because Integer is Comparable<Integer>. However, it could be some class that is Comparable<Object>, because Object is the superclass to all object types.
| {
"pile_set_name": "StackExchange"
} |
Q:
why i cant change contents in column in R?
> data$Accepted.Final.round
[1] NA NA NA NA NA NA NA NA 1 NA NA NA NA 1 1 1 1 0 1 0 0 1 1 1
1
1 NA 1 1 1 1
[32] NA 1 1 0 1 1 1 1 1 1 NA 1 1 0 1 1 0 1 1 1 1 1 1 1
1
NA 1 NA NA NA NA
[63] NA NA NA NA NA NA NA NA NA NA NA NA 1 NA NA NA NA NA NA NA NA NA NA NA
NA
NA NA NA NA NA NA
[94] NA NA NA NA NA NA NA NA NA NA NA NA NA 1 NA NA NA NA NA
I have a dataset column consists of NA, 1, 0. However when I try
data$Accepted.Final.round[data$Accepted.Final.round==NA]<-0
or
ifelse(data$Accepted.Final.round==1,1,0)
to replace NA with 0, both lines cannot work.
Could you guys think of any ways to fix this?
A:
Use is.na() to determine if a value is NA. NA is contagious, meaning that doing operations with NA usually returns NA. That includes checking for equality with ==, i.e. x == NA will always return NA and not TRUE or FALSE.
x <- c(2, NA, 2)
x[is.na(x)] <- 0
| {
"pile_set_name": "StackExchange"
} |
Q:
ListView data deleted and data updated, notifyDataSetChanged called, but no updated of my list
I have a ListView with custom adapter which is populated from local sqlite database. When user long click the item and choose 'delete', dialog will popup to confirm the action again and item will be deleted after confirmed click.
My problem is that the item was deleted from database and the arraylist( dataset for adapter ) was updated, but the ListView isn't updated eventhough I've already called the notifyDataSetChanged().
//The delete method is set on AlertDialog/PositiveButton click listener < ListView ContextMenu listener.
I've checked or tried the following things, but still...
1. Rebuild it (go onCreate), listview will show correctly then, so should be not other issue.
2. I called the same adapter, have confirmed by same hashCode
3. mListView.setAdapter((ListViewAdapter)(ListViewer.mListView.getAdapter()));
4. allResArray.clear(); loadData();
Can anyone help me please? Thanks. I've been stuck on it for 2 days!!
Here is my code:
private static ListView mListView;
private ListViewAdapter mListViewAdapter;
public String[] strListRID;
public List<List<String>> allResArray;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setView(R.layout.listviewer);
init();
}
public void init(){
setTitle(getString(R.string.app_name));
setTitleBar(R.drawable.title_home, 0, R.drawable.title_add, 0,
0, 0, R.drawable.titlebar_title, 0);
initListView();
}
//MainListView initialization
private void initListView(){
boolean SD_STATE = checkSDState();
allResArray = new ArrayList<List<String>>();
loadData();
mListView = (ListView) findViewById(R.id.ListView);
mListViewAdapter = new ListViewAdapter(this, SD_STATE, allResArray);
mListView.setAdapter(mListViewAdapter);
Log.i("mListViewAdapter", String.valueOf(mListViewAdapter.hashCode()));
mListView.setCacheColorHint(0x00000000);
// Click listener to ListView
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
goIntent(5, strListRID[position]);
}
});
// ContextMenu listener to ListView
mListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
menu.setHeaderTitle(R.string.conext_menu_title);
menu.add(0, 0, 0, R.string.conext_menu_edit);
menu.add(0, 1, 0, R.string.conext_menu_delete);
}
});
}
@Override
public boolean onContextItemSelected(MenuItem item){
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case 0: //Edit
goIntent(5, strListRID[menuInfo.position]);
return true;
case 1: //Delete
showDeleteDialog(strListRID[menuInfo.position], menuInfo.position);
break;
default:
break;
}
return super.onContextItemSelected(item);
}
private void loadData() {
allResArray = getAllDatabaseRes();
int size = allResArray.get(0).size();
strListRID = allResArray.get(0).toArray(new String[size]);
}
/**
* AlertDialog: confirm before delete data
* Remove it from ArrayList and notifyDataSetChanged() to adapter
* @param strListRID
*/
private void showDeleteDialog(final String strListRID, final int position) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setIcon(R.drawable.dialog_notice);
dialog.setMessage(R.string.text_delete);
dialog.setPositiveButton(R.string.btn_delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (delRes(Integer.parseInt(strListRID))){
int size =((ListViewAdapter)(mListView.getAdapter())).mResArray.size();
for (int i = 0; i < size; i++){
((ListViewAdapter)(mListView.getAdapter())).mResArray.get(i).remove(position);
}
((ListViewAdapter)(ListViewer.mListView.getAdapter())).notifyDataSetChanged();
Log.i("mListViewAdapter_check", String.valueOf(((ListViewAdapter)(ListViewer.mListView.getAdapter())).hashCode()));
showShortToast((String) getResources().getText(R.string.text_record_delete_ok));
}
else{
showShortToast((String) getResources().getText(R.string.text_record_delete_ng));
}
}
});
dialog.setNegativeButton(R.string.text_no, null);
dialog.show();
}
delRes() code in BaseActivity:
/**
* Delete the specific rid record from database
* @return boolean DEL_OK
* @throws SQLException
*/
protected boolean delRes(int strRID) throws SQLException {
boolean DEL_OK = false;
String deleteWhere = "rid=?";
String[] deleteWhereValue = { String.valueOf(strRID)};
Log.i("rid to delete", deleteWhereValue[0]);
int delrow = dbHelper.delete(tables[0], deleteWhere, deleteWhereValue);
Log.i("delrow", String.valueOf(delrow));
if (delrow == 1){
DEL_OK = true;
}
return DEL_OK;
}
And the logCat:
02-09 15:19:59.744: I/mListViewAdapter(28235): 1163110296
02-09 15:19:59.784: I/tmp(28235): /sdcard/Photo/20120208164204.jpg
02-09 15:19:59.814: I/tmp(28235): /sdcard/Photo/20120208163627.jpg
02-09 15:19:59.854: I/tmp(28235): /sdcard/Photo/20120209151917.jpg
02-09 15:20:05.514: I/menuInfo.position(28235): 1
02-09 15:20:08.634: I/rid to delete(28235): 10
02-09 15:20:08.674: I/delrow(28235): 1
02-09 15:20:08.674: I/mListViewAdapter_check(28235): 1163110296
Current solution: Set a new listviewadapter
/**
* AlertDialog: confirm before delete data
* Remove it from ArrayList and notifyDataSetChanged() to adapter
* @param strListRID
*/
private void showDeleteDialog(final String mRID, final int position) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setIcon(R.drawable.dialog_notice);
dialog.setMessage(R.string.text_delete);
dialog.setPositiveButton(R.string.btn_delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (delRes(Integer.parseInt(mRID))){
int size = allResArray.size();
for (int i = 0; i < size; i++){
allResArray.get(i).remove(position);
}
strListRID = allResArray.get(0).toArray(new String[size-1]);
//((ListViewAdapter)(mListView.getAdapter())).notifyDataSetChanged();
mListView.setAdapter(new ListViewAdapter(getApplicationContext(), true, allResArray));
showShortToast((String) getResources().getText(R.string.text_record_delete_ok));
}
else{
showShortToast((String) getResources().getText(R.string.text_record_delete_ng));
}
}
});
dialog.setNegativeButton(R.string.text_no, null);
dialog.show();
}
A:
Try deleting the row specified directly from your adapter, and then calling notifyDataSetChanged(). Or you can just create new adapter, iterate your ArrayList and adding data to your new adapter, then set this adapter to your ListView.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ошибка: duplicate symbol ... in: ./Debug/tinyxml2.cpp.o в Codelite
Уже была подобная ошибка, когда подключал curl/curl.h, тогда надо было ввести в Linker -lcurl, а-ля g++ -o test filepath -lcurl (Mac OSX). Понимаю, что ошибка из-за того, нужно подключить библиотеку в самом линкере, но не понимаю какую именно. Вот перечень инклудов:
#include "tinyxml2.h"
#include <new> // yes, this one new style header, is in the Android SDK.
#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__)
# include <stddef.h>
# include <stdarg.h>
#else
# include <cstddef>
# include <cstdarg>
#endif
tinyxml2.h - существующий файл в проекте, если что.
Подробней ниже:
main.cpp:
#include <iostream>
#include <string>
#include <tinyxml2.h>
#include <tinyxml2.cpp>
#include <curl/curl.h>
using namespace tinyxml2;
using namespace std;
static string buffer;
static int writer(char* data, size_t size, size_t nmemb, string* buffer)
{
int result = 0;
if(buffer != NULL) {
buffer->append(data, size * nmemb);
result = size * nmemb;
}
return result;
}
int main(int argc, char** argv)
{
char errorBuffer[CURL_ERROR_SIZE];
CURL* curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
curl_easy_setopt(curl, CURLOPT_URL, "https://www.cbr-xml-daily.ru/daily_eng_utf8.xml");
curl_easy_setopt(curl, CURLOPT_NOPROXY, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
res = curl_easy_perform(curl);
if(res == CURLE_OK) {
cout << "Downloaded" << endl;
} else {
cout << "error: " << errorBuffer << endl;
}
} else {
cout << "Оставьте комментарий пж";
}
curl_easy_cleanup(curl);
return 0;
}
tinixml2.cpp есть просьба загуглить ибо 2500 строк
tinixml.h аналогично
То что пишет терминал:
> /bin/sh -c '/usr/bin/make -j8 -e -f Makefile'
----------Building project:[ Money - Debug ]----------
/usr/bin/llvm-g++ -o ./Debug/Money @"Money.txt" -lcurl -lncurses
duplicate symbol __ZN8tinyxml211XMLDocument8SetErrorENS_8XMLErrorEiPKcz in:
./Debug/tinyxml2.cpp.o
./Debug/main.cpp.o
duplicate symbol __ZN8tinyxml210XMLPrinter5PrintEPKcz in:
./Debug/tinyxml2.cpp.o
./Debug/main.cpp.o
duplicate symbol __ZN8tinyxml210XMLPrinter13PushAttributeEPKcx in:
./Debug/tinyxml2.cpp.o
./Debug/main.cpp.o
duplicate symbol __ZNK8tinyxml210XMLElement14Int64AttributeEPKcx in:
./Debug/tinyxml2.cpp.o
./Debug/main.cpp.o
duplicate symbol __ZN8tinyxml27XMLUtil7ToInt64EPKcPx in:
./Debug/tinyxml2.cpp.o
./Debug/main.cpp.o
ld: 227 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[1]: *** [Debug/Money] Error 1
make: *** [All] Error 2
====1 errors, 0 warnings====
A:
Плохо вы читали документацию. Отрывок из документации Readme.md:
The top of tinyxml2.h even has a simple g++ command line if you are are Unix/Linux/BSD and don't want to use a build system.
g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe
Вместо xmltest.cpp пишете main.cpp, вместо gccxmltest.exe название будущей вашей программы.
Из main.cpp уберите инклюд tinyxml2.cpp
| {
"pile_set_name": "StackExchange"
} |
Q:
Correct usage of the possessive in the name "Christiaan Huygens"
I'm writing a lab for a simple diffraction experiment, and I am stuck on this grammatical point:
Is it more appropriate to say "Huygens' Principle" or "Huygens's Principle"*? A cursory glance at Google seems to indicate that the most common usage seems to be "Huygens' Principle"; but as the apostrophe is at the end of the word as in the plural possessive, my inner grammarian is screaming that it should be "Huygens's". Which is correct?
*I know it can also be rendered as the Huygens-Fresnel Principle, obviating the need for my query.
A:
Depends on whom you ask!
Some grammarians say, "If the extra apostrophe s ('s) makes the word difficult to say, then drop it and stick with just an apostrophe (').
That makes sense to me, especially with words such as
Moses's roles as leader, prophet, lawgiver . . ..
Jesus's words of wisdom . . ..
These two leases's conditions state specifically that . . ..
Those italicized words would then become
Moses' roles as leader, prophet, lawgiver . . ..
Jesus' words of wisdom . . ..
These two leases' conditions state specifically that . . ..
Some grammarians say that "Rule are rules. Even if a word ends in s and the resulting apostrophe (which indicates the possessive) creates a tongue twister, you must still attach the apostrophe ('s)."
Still other grammarians say, "Who gives a crap? Do watcha gotta do. Just be consistent."
A:
There is a degree of ambivalence between Huygens' and Huygens's. The Chicago Manual of Style says that either may be used, whereas Professor Strunk (The Elements of Style) insists it is Huygens's.
I personally prefer Huygens's, as it seems to more explicitly indicate the possessive. Your mileage may differ.
See Wikipedia on English possessive.
| {
"pile_set_name": "StackExchange"
} |
Q:
Html.Display extension not outputting value
I use the following code to print user name.
@if (User.Identity.IsAuthenticated)
{
@Html.Display("Welcome, " + User.Identity.Name);
}
But it doesn't print it.
Why?
A:
Html.Display is not meant to display strings, but properties from your model. Try something like this:
@if (User.Identity.IsAuthenticated)
{
@: Welcome, @User.Identity.Name
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set value on object on formbuilder inside another - Typescript
I want to access an existing formBuilder and set value of a specific object.
The problem is that is not a normal formbuilder. It is a formbuilder inside another.
code:
formBuilder.group({
nasty: formBuilder.group({
myobject: ['', []],
})});
How can I set value on myobject?
A:
This is just a FormGroup within a FormGroup.
You could just patchValue whole form object.
this.form.patchValue({ nasty: { myobject: 'POPULATED' }})
Or you could target specific one.
this.form.get('nasty.something').patchValue('AND THIS TOO');
Here is StackBlitz with example -> https://stackblitz.com/edit/angular-3wpxsy
| {
"pile_set_name": "StackExchange"
} |
Q:
Windows Phone 8: Monitoring memory usage in mixed C#/C++
I want to monitor memory usage of a mixed C#/C++ app on Windows Phone 8 which uses Windows Phone Runtime Components. The problem is that when openening the analysis toolkit in Visual Studio (ALT+F1) I have only the option "Execution" (http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202934%28v=vs.105%29.aspx). For "pure" C# project the memory options are available as well.
Are there other more or less easy means to monitor memory usage?
Regards,
A:
Have you considered building your own C# memory monitoring UI? It won't be as fancy or detailed as Visual Studio's memory analyzer, but it was the norm for about a year before WP7.5 introduced memory profiling capability.
I've written about this topic before on Nokia's Wiki under Techniques for memory analysis of Windows Phone apps. Specifically the parts you care about are Add on-screen coding4fun MemoryCounter and Create your own memory profiler.
| {
"pile_set_name": "StackExchange"
} |
Q:
System.IO.Compression and ZipFile - extract and overwrite
I'm using the standard VB.NET libraries for extracting and compressing files. It works as well but the problem comes when I have to extract and files exist already.
Code I use
Imports:
Imports System.IO.Compression
Method I call when it crashes
ZipFile.ExtractToDirectory(archivedir, BaseDir)
archivedir and BaseDir are set as well, in fact it works if there are no files to overwrite. The problem comes exactly when there are.
How can I overwrite files in extraction without use thirdy-part libraries?
(Note I'm using as Reference System.IO.Compression and System.IO.Compression.Filesystem)
Since the files go in multiple folders having already existent files I'd avoid manual
IO.File.Delete(..)
A:
Use ExtractToFile with overwrite as true to overwrite an existing file that has the same name as the destination file
Dim zipPath As String = "c:\example\start.zip"
Dim extractPath As String = "c:\example\extract"
Using archive As ZipArchive = ZipFile.OpenRead(zipPath)
For Each entry As ZipArchiveEntry In archive.Entries
entry.ExtractToFile(Path.Combine(extractPath, entry.FullName), True)
Next
End Using
A:
I found the following implementation fully worked to solve the problems described above, ran without errors and successfully overwrote existing files and created directories as needed.
' Extract the files - v2
Using archive As ZipArchive = ZipFile.OpenRead(fullPath)
For Each entry As ZipArchiveEntry In archive.Entries
Dim entryFullname = Path.Combine(ExtractToPath, entry.FullName)
Dim entryPath = Path.GetDirectoryName(entryFullName)
If (Not (Directory.Exists(entryPath))) Then
Directory.CreateDirectory(entryPath)
End If
Dim entryFn = Path.GetFileName(entryFullname)
If (Not String.IsNullOrEmpty(entryFn)) Then
entry.ExtractToFile(entryFullname, True)
End If
Next
End Using
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Groups in Django To Map Organizations
I am creating a Django app where there will be organizations. Organizations will contain departments –– like human resources/sales –– that will each have their own permissions. The name and roles of groups must be set by the organization itself and won't be known in advance.
There will also be different permissions granted within groups –– a sales manager can do more than a salesperson.
I am unsure to what extent I should use Django's inbuilt groups to handle permissions. Would it be appropriate to make an organization a group? Should a salesperson be a member of two groups –– a departmental group (sales) and a role-based group (salesperson)?
A:
Sounds like the proper usecase for auth groups to me. Some sort of a department head role that can edit the name of a group they belong to (but not the permissions). Whoever IS creating the actual groups and setting permissions is a superuser. Even if you create your own model you can't escape the fact that authority must flow from somewhere. Auth groups has a lot of built-in features around permissions that should save you time.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to ensure specific shared logic is fired before anything else in an MVC web app?
I currently have a partial view that is called within my _Layout.cshtml, and is rendered throughout my whole MVC web application. It's the first item at the top of the page to be rendered, and within the ActionResult method that is responsible for it, I have a call to my service to perform some business logic.
I originally put this service call in this particular ActionResult method as, still being new to MVC, I was falsely under the impression that it would get fired BEFORE any of the main page content, for each page across the site. However, I've just realised that the main view method is being called first, and this ChildActionOnly Method (for the Partial View) is being called afterwards.
Basically, it's essential that the business logic call that Im currently making within the ChildActionOnly Method (associated with my partial view) is made BEFORE any other page processing is carried out (as I need to perform some DB updates upon each page load, which are then reflected in each requested page).
I'm happy to split this business logic out from the current partial views actionmethod, but am unsure where it should be going, or how I should be ensuring that it's called before anything else, for each page request? What would be the norm approach?
A:
You need a global action filter (luckily available starting MVC3).
See an example here:
http://weblogs.asp.net/gunnarpeipman/archive/2010/08/15/asp-net-mvc-3-global-action-filters.aspx
Copying from the sample (with slight modifications):
public class MyActionFilterAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
// Your logic can come here
base.OnResultExecuting(filterContext);
// Your logic can come here
}
}
Applying in global.asax.cs (from the article):
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Register global filter
GlobalFilters.Filters.Add(new MyActionFilterAttribute());
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Соединение с mysql по ssh туннелю в Windows
Есть сервер с MySQL, и к нему надо конектиться на клиенте созданном на php devel studio. Хочу сделать коннект через ssh туннель, на юниксе это можно сделать так:
shell_exec("ssh -f -L 127.0.0.1:3307:127.0.0.1:3306 [email protected] sleep 60 >> logfile");
$db = mysqli_connect("127.0.0.1", "sqluser", "sqlpassword", "rjmadmin", 3307);
Но клиент будет работать на Windows, как можно сделать тоже самое без использования дополнительных прог? Либо возможно есть какой то компонент в devel studio для этой цели?
A:
putty можно использовать из командной строки windows, что-то в таком духе:
shell_exec("putty.exe -ssh [email protected] -L 127.0.0.1:3307:127.0.0.1:3306");
| {
"pile_set_name": "StackExchange"
} |
Q:
get taxonomy terms for parent and child
I have a function set up that prints the taxonomy term name and slug for every products-category taxonomy term present. This works great, but it's just displaying them alphabetically like so (regardless of if they are a parent / child taxonomy term):
Parent Category 2
Parent Category 1
Child Category 3
Parent Category 3
Child Category 2
Child Category 1
etc...
Whereas I'm after a structure more like this:
—Parent Category 1
Child Category 1
Child Category 2
Child Category 3
—Parent Category 2
Child Category 1
Child Category 2
Child Category 3
—Parent Category 3
Child Category 1
Child Category 2
Child Category 3
So the children terms of each taxonomy term sit underneath, so you know what parent they belong to. My markup is as follows:
<?php
$args = array(
'hide_empty' => false
);
$terms = get_terms("products-category");
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
foreach ( $terms as $term ) { ?>
<option value=".<?php echo $term->slug; ?>" data-hook="<?php echo $term->slug; ?>"><?php echo $term->name; ?></option>
<?php }
} ?>
Any suggestions on how to achieve this would be greatly appreciated!
A:
You should have two foreach loops. One for getting parent taxonomy terms, and second for getting child taxonomy terms.
In the second foreach you need to specify the parent taxonomy term ID which is $parent_term->term_id from the first foreach loop.
foreach( get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => 0 ) ) as $parent_term ) {
// display top level term name
echo $parent_term->name . '<br>';
foreach( get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) ) as $child_term ) {
// display name of all childs of the parent term
echo $child_term->name . '<br>';
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Google+ integration - repeated UserRecoverableAuthException
We have contacted Google about this and we are on chat
The issue seems to be fixed for devices except Samsung phones.
I'm adding a Google+ sign in option to an app per the official instructions. Once the user has selected their account I would like my server to retrieve their Google+ profile info and update their profile on our site to match.
The first part - having the user select a Google account locally - seems to work just fine. When I try to request a token for the selected account, the Google auth dialog displays with the appropriate parameters; however, when I authorize the app using that dialog and re-request the token, GoogleAuthUtil.getToken(...) again throws a UserRecoverableAuthException (NeedPermission, not GooglePlayServicesAvailabilityException) and I get the same dialog asking me to approve!
This behavior is present on a Samsung S3 running Android 4.1.1 (with 3 Google accounts) and an Acer A100 running 4.0.3. It is NOT present on an HTC Glacier running 2.3.4. Instead, the HTC Glacier gives me a valid auth code. All devices have the latest iteration of Google Play Services installed and are using different Google+ accounts.
Anyone seen this before? Where can I start with debugging?
Here's the complete code - is anything obviously awry?
public class MyGooglePlusClient {
private static final String LOG_TAG = "GPlus";
private static final String SCOPES_LOGIN = Scopes.PLUS_LOGIN + " " + Scopes.PLUS_PROFILE;
private static final String ACTIVITIES_LOGIN = "http://schemas.google.com/AddActivity";
private static MyGooglePlusClient myGPlus = null;
private BaseActivity mRequestingActivity = null;
private String mSelectedAccount = null;
/**
* Get the GPlus singleton
* @return GPlus
*/
public synchronized static MyGooglePlusClient getInstance() {
if (myGPlus == null)
myGPlus = new MyGooglePlusClient();
return myGPlus;
}
public boolean login(BaseActivity requester) {
Log.w(LOG_TAG, "Starting login...");
if (mRequestingActivity != null) {
Log.w(LOG_TAG, "Login attempt already in progress.");
return false; // Cannot launch a new request; already in progress
}
mRequestingActivity = requester;
if (mSelectedAccount == null) {
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE}, false,
null, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE, null, null);
mRequestingActivity.startActivityForResult(intent, BaseActivity.REQUEST_GPLUS_SELECT);
}
return true;
}
public void loginCallback(String accountName) {
mSelectedAccount = accountName;
authorizeCallback();
}
public void logout() {
Log.w(LOG_TAG, "Logging out...");
mSelectedAccount = null;
}
public void authorizeCallback() {
Log.w(LOG_TAG, "User authorized");
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String token = null;
try {
Bundle b = new Bundle();
b.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES, ACTIVITIES_LOGIN);
token = GoogleAuthUtil.getToken(mRequestingActivity,
mSelectedAccount,
"oauth2:server:client_id:"+Constants.GOOGLE_PLUS_SERVER_OAUTH_CLIENT
+":api_scope:" + SCOPES_LOGIN,
b);
} catch (IOException transientEx) {
// Network or server error, try later
Log.w(LOG_TAG, transientEx.toString());
onCompletedLoginAttempt(false);
} catch (GooglePlayServicesAvailabilityException e) {
Log.w(LOG_TAG, "Google Play services not available.");
Intent recover = e.getIntent();
mRequestingActivity.startActivityForResult(recover, BaseActivity.REQUEST_GPLUS_AUTHORIZE);
} catch (UserRecoverableAuthException e) {
// Recover (with e.getIntent())
Log.w(LOG_TAG, "User must approve "+e.toString());
Intent recover = e.getIntent();
mRequestingActivity.startActivityForResult(recover, BaseActivity.REQUEST_GPLUS_AUTHORIZE);
} catch (GoogleAuthException authEx) {
// The call is not ever expected to succeed
Log.w(LOG_TAG, authEx.toString());
onCompletedLoginAttempt(false);
}
Log.w(LOG_TAG, "Finished with task; token is "+token);
if (token != null) {
authorizeCallback(token);
}
return token;
}
};
task.execute();
}
public void authorizeCallback(String token) {
Log.w(LOG_TAG, "Token obtained: "+token);
// <snipped - do some more stuff involving connecting to the server and resetting the state locally>
}
public void onCompletedLoginAttempt(boolean success) {
Log.w(LOG_TAG, "Login attempt "+(success ? "succeeded" : "failed"));
mRequestingActivity.hideProgressDialog();
mRequestingActivity = null;
}
}
A:
I've had this issue for a while and came up with a proper solution.
String token = GoogleAuthUtil.getToken(this, accountName, scopeString, appActivities);
This line will either return the one time token or will trigger the UserRecoverableAuthException.
On the Google Plus Sign In guide, it says to open the proper recovery activity.
startActivityForResult(e.getIntent(), RECOVERABLE_REQUEST_CODE);
When the activity returns with the result, it will come back with few extras in the intent and that is where the new token resides :
@Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == RECOVERABLE_REQUEST_CODE && responseCode == RESULT_OK) {
Bundle extra = intent.getExtras();
String oneTimeToken = extra.getString("authtoken");
}
}
With the new oneTimeToken given from the extra, you can submit to the server to connect properly.
I hope this helps!
A:
Its too late to reply but it may help to people having same concern in future.
They have mentioned in the tutorial that it will always throw UserRecoverableAuthException
when you invoke GoogleAuthUtil.getToken() for the first time. Second time it will succeed.
catch (UserRecoverableAuthException e) {
// Requesting an authorization code will always throw
// UserRecoverableAuthException on the first call to GoogleAuthUtil.getToken
// because the user must consent to offline access to their data. After
// consent is granted control is returned to your activity in onActivityResult
// and the second call to GoogleAuthUtil.getToken will succeed.
startActivityForResult(e.getIntent(), AUTH_CODE_REQUEST_CODE);
return;
}
i used below code to get access code from google.
execute this new GetAuthTokenFromGoogle().execute(); once from public void onConnected(Bundle connectionHint) and once from protected void onActivityResult(int requestCode, int responseCode, Intent intent)
private class GetAuthTokenFromGoogle extends AsyncTask<Void, Integer, Void>{
@Override
protected void onPreExecute()
{
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
accessCode = GoogleAuthUtil.getToken(mContext, Plus.AccountApi.getAccountName(mGoogleApiClient), SCOPE);
new ValidateTokenWithPhoneOmega().execute();
Log.d("Token -- ", accessCode);
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
return null;
} catch (UserRecoverableAuthException e) {
// Recover
startActivityForResult(e.getIntent(), RC_ACCESS_CODE);
e.printStackTrace();
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
authEx.printStackTrace();
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to listen for Project deletes in Eclipse?
I have a project with an incremental builder. The builder writes into a model representations of all resources and their changes, given that the project has a certain nature. This runs pretty well. But the incremental builder is not called if a whole project is deleted from the workspace. What is the best way to create an event handler for that?
I know that I could create an IResourceChangeListener and attach it to all projects with my nature. But than I would have to start my plugin with the start of the IDE and that is rather messy.
So, what is the best way to catch "Project deleted" events?
A:
You can use an IResourceChangeListener to receive notifications about changes in the workspace. The IResourceChangelistener API is very versatile and can give you change info about many different kinds of changes. Here's an example of how you can use it specifically to detect project deletion.
public class ProjectDeletionListenerManager implements IResourceChangeListener {
public interface ProjectDeletionListener {
void projectAboutToBeDeleted(IProject project);
}
private IWorkspace workspace;
private ProjectDeletionListener listener;
public ProjectDeletionListenerManager(ProjectDeletionListener listener) {
this.workspace = ResourcesPlugin.getWorkspace();
this.listener = listener;
this.workspace.addResourceChangeListener(this,
IResourceChangeEvent.PRE_DELETE);
}
@Override
public void resourceChanged(IResourceChangeEvent event) {
IResource rsrc = event.getResource();
if (rsrc instanceof IProject) {
listener.projectAboutToBeDeleted((IProject) rsrc);
}
}
public void dispose() {
if (listener!=null) {
workspace.removeResourceChangeListener(this);
listener = null;
}
}
}
Note: code snippet based on this code.
A:
IResourceChangeListener is the way to do this. You don't attach it to projects, it always gets called for all changes.
You can use the org.eclipse.ui.startup extension point to get your plug-in started during Eclipse startup.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# return keyword appears to not be working or am I loosing my mind AND tips on tree view traversing
where I have the return statement it should exit the function however when debugging it reaches the return statement and then goes out to the last curly brackets of this function and then literally jumps to the else statement of the if statement and then will recurse this function again however will throw an exception since the listview1.selecteditems[0].tag is null! :-S
Am I doing something wrong, loosing my mind or both?
(please ignore the functioncount variable, just there temporarily)
EDIT: One person said the return statement is behaving exactly as it should because it ends only the current invocation of the function and not any other subsequent functions. I agree with what hes saying but my problem is I've only called this function once. The fact that once it returns it immediately jumps to the else statement which seems to me like its bypassing the entire function? I'm not too sure...
int functionCount = 0;
private void openTreeViewNodeBasedOnListViewItem(string treeViewNodeToOpen,TreeNodeCollection nodes)
{
Console.WriteLine(functionCount);
functionCount++;
//if (treeViewNodeToOpen.Contains(@"\"))
//{
// treeViewNodeToOpen = treeViewNodeToOpen.Substring(treeViewNodeToOpen.LastIndexOf(@"\") + 1);
// string[] fullNodePath = treeViewNodeToOpen.Split('\\');
//}
//Console.WriteLine("index {0}",listView1.SelectedItems[0].Index);
string listViewItemAddress = listView1.SelectedItems[0].Tag.ToString();
string treeViewItemAddress = "";
listViewItemAddress = listViewItemAddress.Substring(listViewItemAddress.IndexOf('\\'));
listViewItemAddress = @"Y:\" + listViewItemAddress;
//Console.WriteLine("List view address {0}",listViewItemAddress);
foreach (TreeNode node in nodes)
{
treeViewItemAddress = node.FullPath.ToString();
if (node.Text == treeViewNodeToOpen && treeViewItemAddress == listViewItemAddress)
{
//Console.WriteLine("Tree view address {0}",node.FullPath.ToString());
functionCount = 0;
Console.WriteLine("list view {0} match found, navigating to tree node : {1}", listViewItemAddress, node.FullPath);
treeView1_NodeMouseClickACTION(node);
return; //when you return here it should exit the function however when debugging it goes out to the last curly brackets of this function and then jumps to the else statement of THIS if statement and then will recurse this function again however will throw an exception since the listview1.selecteditems[0].tag is null! :-S
}
else
{
Console.WriteLine("tree view node {1} does not match the node were looking for {0}", listViewItemAddress, node.FullPath);
openTreeViewNodeBasedOnListViewItem(treeViewNodeToOpen, node.Nodes);
}
}
} //after successfully finding a match and running the return statement, the debugger takes me here and then literally jumps to the else statement and I'm not quite sure why.
A:
It is working exactly as it should. return ends the current invocation of the function, and not every single invocation of the function on the call stack. There is no keyword that would do that.
As for your specific solution, it can be re-designed to separate out some of the different tasks you're trying to accomplish, rather than doing them all in a single method, which is a part of what's giving you troubles.
One thing that you're doing is traversing a tree to get all of the nodes within it. First write a method that does that, without doing anything else. Here is one implementation of a tree traversal:
public static IEnumerable<T> Traverse<T>(T item, Func<T, IEnumerable<T>> childSelector)
{
var stack = new Stack<T>();
stack.Push(item);
while (stack.Any())
{
var next = stack.Pop();
yield return next;
foreach (var child in childSelector(next))
stack.Push(child);
}
}
We can then invoke it like so, to get a flat sequence of all of the nodes in the tree:
Traverse(root, node => node.Nodes.Cast<TreeNode>())
Then we can find the first item in that sequence that has the text that we're looking for, and do something with that node:
TreeNode root = GetRootNode();
var result = Traverse(root, node => node.Nodes.Cast<TreeNode>())
.First(node => node.Text == "some text");
DoSomethingWithNode(result);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use NSArray and NSDictionary?
I'm learning iOS from iTunes U and trying to build a programmable calculator. I have added three variables which the user can use to allot values. I understand that the variables would be passed as NSString objects and then the user would touch the numbers which would be passed as NSNumbers and allotted to the variables. I don't understand how to use NSArrays and NSDictionary to allot the numbers to these variables. Sorry for being a complete newbie, but I am not comfortable with the Documentation right now, so it is kind of fuzzy! This is my code for appending digits on a UILabel and then using it for calculations:
- (IBAction)digitPressed:(UIButton *)sender {
NSString *digit = [sender currentTitle];
if (self.userIsInTheMiddleOfEnteringANumber) {
self.display.text = [self.display.text stringByAppendingFormat:digit];
everythingBrainLabel.text = [self.everythingBrainLabel.text stringByAppendingFormat:digit];
} else {
self.display.text = digit;
self.everythingBrainLabel.text = [self.everythingBrainLabel.text stringByAppendingFormat:@" %@", digit];
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
I can get the values of the variables in an NSMutableArray but how to allot numbers here by simply pressing the digits after pressing the variable? I added NSLog just to check if variables were being passed and they show up in the console after I press the respective variable.
- (IBAction)variablePressed:(UIButton *)sender {
NSString *variablePressed = [sender currentTitle];
NSMutableArray *variableValues = [NSMutableArray arrayWithObjects:variablePressed, nil];
for(int i = 0; i < [variableValues count]; i++) {
NSLog(@"%@",[variableValues objectAtIndex:i]);
}
}
A:
To set specific value for specific keys, you could add an NSMutableDictionary to your current class
Add it as a property in your class and synthesize it
Now when you want to assign a value for "x" you would do the following
//Add this var in your .h file create a property around it
NSMutableDictionary *variables;
//in the .m @synthesize variables;
When assigning the variable "x"
//for example you want to set varialbe "x" = 20
int xValue = 20;
NSString *xVariable = @"x";
[variables setObject:[NSNumber numberWithInt:xValue] forKey:xVariable];
Getting value for "x"
//Later on if you want to get x
NSString *xVariable = @"x";
int xValue = [[variables valueForKey:xVariable] intValue];
| {
"pile_set_name": "StackExchange"
} |
Q:
Python only prints the last list in a 2d list
I have a 2D array of vocabulary words that I scraped from a website. Now what I am trying to do is, print each list of the 2D array in it's own .txt file but, when it writes it, it only writes the last list in the 2D array. This is my first time trying to write a 2D array to a .txt file. Not sure what I am doing wrong.
I'm trying to write 20 of the lists in the 2d list to 20 different .txt files.
This is what I am using to write the .txt file with the 2D array
So far I've tried using 'a' instead of 'w' but that writes the whole 2d list to the .txt file (IE it makes 20 .txt files with all of the contents of the 2d list)
for words in souparray:
with open(path + sublink + '.txt', 'w', encoding='utf-8') as txtf:
str1 = ''.join(words)
txtf.write(str1)
str1 = ""
A:
It seems that you write everything to the same file. You need to change the name files you write to:
for words in souparray:
with open(path + sublink + '.txt', 'w', encoding='utf-8') as txtf:
str1 = ''.join(words)
txtf.write(str1)
str1 = ""
The sublink should change with each iteration. Or you need to add some counter if the sublink part does not change.
For instance:
...
count = 0
for words in souparray:
with open(path + sublink + count + '.txt', 'w', encoding='utf-8') as txtf:
str1 = ''.join(words)
txtf.write(str1)
str1 = ""
count+=1
txtf.close()
| {
"pile_set_name": "StackExchange"
} |
Q:
Chromecast support for HLS, CORS error on Amazon S3
I am trying to integrate HLS streams in my chromecast app.
The receiver part is fine because i checked it with multiple HLS Stream urls.
i just cant get the CORS bit to operate correctly.
I am using Amazon AWS S3. I have set the CORS for my bucket.
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
in my assumption this should allow access from all domains to access the resources inside this bucket.
But still i am getting the following error in javascript from Chromecast.
XMLHttpRequest cannot load http://s3-eu-west-1.amazonaws.com/interactive-encoding-out/watermark-sintel-test/playlist.m3u8. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://s3-eu-west-1.amazonaws.com' is therefore not allowed access.
A:
Right now i have used corsproxy as a reversed proxy that adds cors headers to my request. Really recommand this solution. No need for a custom receiver app this way. just install the corsproxy somewhere on your server
run the cors proxy:
$ corsproxy <SERVER_IP> <DESIRED_PORT>
and run the request like :
http://<SERVER_IP>:<DESIRED_PORT>/<YOUR REQUEST>
install from:
https://www.npmjs.org/package/corsproxy
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot create two-dimensional unordered_map with user-defined class as key
As stated in the title, I am having trouble getting the VC++ compiler to work when using a two-dimensional map with a user-defined class as a key.
Here is the map I am trying to declare:
std::unordered_map<tag, std::map<tag, std::pair<bool, bool>>> transitRights;
And here are the declarations of class tag and the specialisation of the std::hash function:
class tag
{
public:
tag();
tag(const char[3]);
tag(const std::string&);
void operator=(const tag&);
const bool operator==(const tag&)const;
operator const std::string()const;
const char& getA()const { return a; }
const char& getB()const { return b; }
const char& getC()const { return c; }
private:
char a, b, c;
};
namespace std
{
template<> class hash<tag>
{
public:
size_t operator()(const tag& _tag) const
{
return hash<char>()(_tag.getA()) ^ hash<char>()(_tag.getB()) ^ hash<char>()(_tag.getC());
}
};
};
When attempting to compile, Visual Studio throws a bunch of these cryptic error messages at me:
1>C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(600): error C2664: 'std::pair<const _Kty,_Ty>::pair(const std::pair<const _Kty,_Ty> &)' : cannot convert argument 1 from 'const tag' to 'const std::pair<const _Kty,_Ty> &'
1> with
1> [
1> _Kty=int
1> , _Ty=std::pair<bool,bool>
1> ]
1> Reason: cannot convert from 'const tag' to 'const std::pair<const _Kty,_Ty>'
1> with
1> [
1> _Kty=int
1> , _Ty=std::pair<bool,bool>
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1> C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(723) : see reference to function template instantiation 'void std::allocator<_Other>::construct<_Objty,const tag&>(_Objty *,const tag &)' being compiled
1> with
1> [
1> _Other=std::_Tree_node<std::pair<const int,std::pair<bool,bool>>,void *>
1> , _Objty=std::pair<const int,std::pair<bool,bool>>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(723) : see reference to function template instantiation 'void std::allocator<_Other>::construct<_Objty,const tag&>(_Objty *,const tag &)' being compiled
1> with
1> [
1> _Other=std::_Tree_node<std::pair<const int,std::pair<bool,bool>>,void *>
1> , _Objty=std::pair<const int,std::pair<bool,bool>>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(872) : see reference to function template instantiation 'void std::allocator_traits<_Alloc>::construct<_Ty,const tag&>(std::allocator<_Other> &,_Objty *,const tag &)' being compiled
1> with
1> [
1> _Alloc=std::allocator<std::_Tree_node<std::pair<const int,std::pair<bool,bool>>,void *>>
1> , _Ty=std::pair<const int,std::pair<bool,bool>>
1> , _Other=std::_Tree_node<std::pair<const int,std::pair<bool,bool>>,void *>
1> , _Objty=std::pair<const int,std::pair<bool,bool>>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(872) : see reference to function template instantiation 'void std::allocator_traits<_Alloc>::construct<_Ty,const tag&>(std::allocator<_Other> &,_Objty *,const tag &)' being compiled
1> with
1> [
1> _Alloc=std::allocator<std::_Tree_node<std::pair<const int,std::pair<bool,bool>>,void *>>
1> , _Ty=std::pair<const int,std::pair<bool,bool>>
1> , _Other=std::_Tree_node<std::pair<const int,std::pair<bool,bool>>,void *>
1> , _Objty=std::pair<const int,std::pair<bool,bool>>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xtree(933) : see reference to function template instantiation 'void std::_Wrap_alloc<std::allocator<_Other>>::construct<_Ty,const tag&>(_Ty *,const tag &)' being compiled
1> with
1> [
1> _Other=std::_Tree_node<std::pair<const int,std::pair<bool,bool>>,void *>
1> , _Ty=std::pair<const int,std::pair<bool,bool>>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xtree(933) : see reference to function template instantiation 'void std::_Wrap_alloc<std::allocator<_Other>>::construct<_Ty,const tag&>(_Ty *,const tag &)' being compiled
1> with
1> [
1> _Other=std::_Tree_node<std::pair<const int,std::pair<bool,bool>>,void *>
1> , _Ty=std::pair<const int,std::pair<bool,bool>>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xtree(1176) : see reference to function template instantiation 'std::_Tree_node<std::pair<const _Kty,_Ty>,void *> *std::_Tree_buy<std::pair<const _Kty,_Ty>,std::allocator<std::pair<const _Kty,_Ty>>>::_Buynode<const tag&>(const tag &)' being compiled
1> with
1> [
1> _Kty=int
1> , _Ty=std::pair<bool,bool>
1> ]
1> C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xtree(1176) : see reference to function template instantiation 'std::_Tree_node<std::pair<const _Kty,_Ty>,void *> *std::_Tree_buy<std::pair<const _Kty,_Ty>,std::allocator<std::pair<const _Kty,_Ty>>>::_Buynode<const tag&>(const tag &)' being compiled
1> with
1> [
1> _Kty=int
1> , _Ty=std::pair<bool,bool>
1> ]
1> nation.cpp(600) : see reference to function template instantiation 'std::pair<std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const _Kty,_Ty>>>>,bool> std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::emplace<const tag&>(const tag &)' being compiled
1> with
1> [
1> _Kty=int
1> , _Ty=std::pair<bool,bool>
1> , _Pr=std::less<int>
1> , _Alloc=std::allocator<std::pair<const int,std::pair<bool,bool>>>
1> ]
1> nation.cpp(600) : see reference to function template instantiation 'std::pair<std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const _Kty,_Ty>>>>,bool> std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::emplace<const tag&>(const tag &)' being compiled
1> with
1> [
1> _Kty=int
1> , _Ty=std::pair<bool,bool>
1> , _Pr=std::less<int>
1> , _Alloc=std::allocator<std::pair<const int,std::pair<bool,bool>>>
1> ]
Any insight into what I am doing wrong here would be greatly appreaciated.
A:
The problem is that the nested object is a std::map (not an unordered_map) and for that you need a less-than comparison for tag.
You should be able to build an unordered_map of unordered_maps, however.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to disable the HTML class warning "class not found" in Netbeans 11.0
I would like to disable the warnings Netbeans is throwing when it's not finding classes because it's flooding my IDE.
For example, for this bit of code:
<div class="portlet light">
<a class="navigation" href="/home">Home page</a>
</div>
I have 3 warnings about the class being not defined.
A:
Go to: Tools > Options > Editor > Hints
Then in Language select HTML
Under CSS, uncheck Missing CSS Class and Missing CSS Class In Partials
| {
"pile_set_name": "StackExchange"
} |
Q:
Constant in-place array of strings and records in Delphi
Is something like this possible with Delphi? (with dynamic arrays of strings and records)
type
TStringArray = array of String;
TRecArray = array of TMyRecord;
procedure DoSomethingWithStrings(Strings : TStringArray);
procedure DoSomethingWithRecords(Records : TRecArray);
function BuildRecord(const Value : String) : TMyRecord;
DoSomethingWithStrings(['hello', 'world']);
DoSomethingWithRecords([BuildRecord('hello'), BuildRecord('world')]);
I know that it does not compile like that. Just wanted to ask if there's a trick to get something similar to that.
A:
If you don't have to change the length of the arrays inside your DoSomethingWith* routines, I suggest using open arrays instead of dynamic ones, e.g. like this:
procedure DoSomethingWithStrings(const Strings: array of string);
var
i: Integer;
begin
for i := Low(Strings) to High(Strings) do
Writeln(Strings[i]);
end;
procedure DoSomethingWithRecords(const Records: array of TMyRecord);
var
i: Integer;
begin
for i := Low(Records) to High(Records) do
Writeln(Records[i].s);
end;
procedure Test;
begin
DoSomethingWithStrings(['hello', 'world']);
DoSomethingWithRecords([BuildRecord('hello'), BuildRecord('world')]);
end;
Please note the array of string in the parameter list - not TStringArray! See the article "Open array parameters and array of const", especially the section about "Confusion", for more information.
| {
"pile_set_name": "StackExchange"
} |
Q:
$addToSet for hashes?
$addToSet seems to add to arrays only, is it possible to add a hash to a hash?
{
"a"=>"1",
"b"=>"2",
"c"=>{"d"=>"3"}
}
to
{
"a"=>"1",
"b"=>"2",
"c"=>{"d"=>"3","e"=>"4"}
}
And in ruby would be pref. But I'm okay with anything atm that'll help me solve this.
A:
Yes, $addToSet was meant to be used on arrays. You need $set and dot notation
db.collection.update(query, {$set: {'c.e': '4'}});
| {
"pile_set_name": "StackExchange"
} |
Q:
Compile angular2+ component to dynamically created DOM element
I have a 3rd party library which dynamically creates a DOM element, I need to compile a component and insert it to the created DOM element.
I'm using component factory resolver and i know i can insert it to ViewContainerRef, but i'm not sure how to insert to plain DOM element created by outside angular lib.
onDynamicDomCreate: (e: GridChangeEvent) => {
let factory = this.componentFactoryResolver.resolveComponentFactory(UserDetailsComponent);
e.sender.element.createComponent(factory); // <--- how to properly create component here?
}
A:
You need to pass a DOM element when creating a component like this:
let factory = this.componentFactoryResolver.resolveComponentFactory(UserDetailsComponent);
const compRef = factory.create(injector, [], e.sender.element);
And also register the created view in the ApplicationRef, otherwise you won't have change detection for the component:
appRef.attachView(compRef.hostView);
| {
"pile_set_name": "StackExchange"
} |
Q:
How does ASP.net web API determine which function to call?
My ASP.NET web api has two functions : one which returns a list of all products and another which returns a list depending on a condition.
public class ProductsController : ApiController
{
List<Product> lst = new List<Product>
{
new Product(){ Id = 1, Name = "a Soup", Category = "Groceries", Price = 1 },
new Product(){Id = 2, Name = "b Soup", Category = "stat", Price = 4 },
new Product(){ Id = 3, Name = "c Soup", Category = "Groceries", Price = 1 }
};
public List<Product> GetAllProducts()
{
return lst;
}
public List<Product> GetProducts(int k)
{
return lst.Where(p => p.Price == k).ToList();
}
}
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I am using a GET method from jQuery as below:
<script type="text/javascript">
function getProducts() {
$.getJSON("api/products/1",
function (data) {
debugger;
});
}
$(document).ready(getProducts);
</script>
This function invokes the first function which is GetAllProducts even if I invoke it by calling
"api/products/1"
My question is how does it determine which function to call when invoking from the client?
A:
If you're using the latest version of Web API, you could look at Attribute Routing. This will allow you to decorate the methods with a relevant pattern.
[Route("products/getAll")]
public List<Product> GetAllProducts()
{
return lst;
}
[Route("products/getByPrice/{price}")]
public List<Product> GetProducts(int price)
{
return lst.Where(p => p.Price == price).ToList();
}
Above is just an example, so you select what suits your needs. If you're using an old version, you can get the AttributeRouting library here.
You also have an ActionPresedence, see my question here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Decrypting coldfusion encrypted string in PHP
I have a string encrypted in Coldfusion which needs to be decrypted in PHP for usage.
So i am looking for a method which corresponds to:
Decrypt(stringToDecrypt,"2450RDSET0C","CFMX_COMPAT","HEX")
Here,
stringToDecrypt = the string to be decrypted,
"2450RDSET0C" = the seed that was used to encrypt the string
CFMX_COMPAT = encryption algorithm
HEX = encoding used
https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-c-d/Decrypt.html
example string to be decrypted: 6A968A969DEB9A16549C61EE2EFE40A6515E
A:
I was able to use the following code to decrypt your example string.
<?php
require __DIR__ . '/vendor/autoload.php';
use AwkwardIdeas\PHPCFEncrypt\Encrypt;
$stringToDecrypt = '6A968A969DEB9A16549C61EE2EFE40A6515E';
$key = '2450RDSET0C';
$decrypted = Encrypt::decrypt($stringToDecrypt, $key, 'CFMX_COMPAT', 'hex');
var_dump($decrypted);
$ php main.php
string(18) "SofortUeberweisung"
After installing the dependency with composer.
composer require awkwardideas/phpcfencrypt
Here's a GitHub Gist you can use to test with.
https://gist.github.com/AlexanderOMara/b9bb6ff2a57bd0cf61fa8f0823d9a2a0
Just run composer install first.
NOTE: This encryption scheme is rather weak!
Hopefully you are using this decryption code as part of a migration process to move to a stronger encryption scheme, like AES (or a password hash like bcrypt if this is for passwords).
| {
"pile_set_name": "StackExchange"
} |
Q:
Extension disappeared from backend without error
I developed a extension where you can also set settings in the backend. It randomly disappeared somehow and I don't know why.
There are no errors, the extension in enabled and the output is alos enabled.
The extension still works and makes changes to the frontend, but it does not show in the backend.
What is going on?
A:
I found the reason. There was a opening tag in the file etc/system.xml of my extension which had no matching ending tag. <user_backend><user_backend_text>
<user_backend>
<label>Benutzer-Backend Texte/Farben</label>
<frontend_type>text</frontend_type>
<sort_order>50</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<description>
<label>Bearbeiten Beschreibung</label>
<frontend_type>text</frontend_type>
<sort_order>10</sort_order>
<validate>required-entry</validate>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</description>
<subscribe_text>
<label>Anmelden</label>
<frontend_type>text</frontend_type>
<validate>required-entry</validate>
<sort_order>20</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</subscribe_text>
<unsubscribe_text>
<label>Abmelden</label>
<frontend_type>text</frontend_type>
<validate>required-entry</validate>
<sort_order>30</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</unsubscribe_text>
</fields>
</user_backend_text>
The error was hard to find because no error was thrown and my IDE (NetBeans) did not showed a warning.
| {
"pile_set_name": "StackExchange"
} |
Q:
Task вернуть null, не прерывая задачу
Одна задача, ожидает выполнение другой задачи, как только возвращаем null из ожидаемой задачи, происходит прерывание выполнения другой.
Как вернуть null из Task<T>, при этом не прервать выполнение родительского Task<T>, и продолжить выполнение в штатном режиме?
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public class TaskOperation
{
public bool GetNUll { get; set; }
}
public class SomeTasks
{
public async Task<ObservableCollection<TaskOperation>> GetAllTasks()
{
ObservableCollection<TaskOperation> taskOperations = new ObservableCollection<TaskOperation>();
for (int i = 0; i < 120; i++)
{
taskOperations.Add(new TaskOperation { GetNUll = i % 2 == 0 });
}
int t = 0;
foreach (var taskOperation in taskOperations)
{
if (!(await GetTask(taskOperation)).GetNUll)
{
Console.WriteLine($"{t}");
}
}
return taskOperations;
}
public Task<TaskOperation> GetTask(TaskOperation operation)
{
return operation.GetNUll ? null : Task.Factory.StartNew(() => operation);
}
}
static void Main(string[] args)
{
SomeTasks someTasks = new SomeTasks();
Task.Run(async () => await someTasks.GetAllTasks());
Console.Read();
}
}
}
Данная задача будет прервана на первой же итерации цикла.
A:
Поглядим на код:
async Task ParentTask()
{
await ChildTask(); // ожидаем Task<T>, всё хорошо
await ChildTaskNull(); // await null - ошибка
}
Task<string> ChildTask()
{
return Task.FromResult<string>(null);
}
Task<string> ChildTaskNull()
{
return null;
}
Смотрим что тут происходит:
У нас есть родительская функция и 2 дочерние. В родительской мы сначала вызываем ChildTask(), который возвращает экземпляр Task<string>, который мы можем ожидать. Потому await ChildTask(); работает нормально.
Далее, ChildTaskNull() возвращает NULL, но NULL - это не экземпляр задачи, это просто пустой указатель. потому await ChildTaskNull(); превращается в await null, что и порождает исключение в родительской задаче.
Как вывод, если ваша функция НЕ асинхронная и просто возвращает Task<T>, и вам надо вернуть null как результат операции, используйте return Task.FromResult<T>(null) или Task.FromResult((T)null)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display List contents as a joined string
I have a FormView that has a datasource bind as a object which is a WCF service. In the WCF Service i have a Object PublicationDetail which has a attribute List authors;
I want to join the contents of the list and print them out in the form view however i fall on the following error:
Unable to cast object of type 'System.String[]' to type
'System.Collections.Generic.List`1[System.String]'.
And the code:
<asp:Label ID="AuthorsLabel" runat="server" Text='<%# String.Join( ",", ((List<string>)Eval("Authors")).ToArray()) %>' />
A:
Just use
String.Join( ",", ((string[])Eval("Authors")))
WCF serializes List<T> as T[] in messages, so your bound property is an array.
See Why does WCF return myObject[] instead of List<T> like I was expecting?
| {
"pile_set_name": "StackExchange"
} |
Q:
unable to create a C++ ruby extension
I have problems creating a ruby extension to export a C++ library I wrote to ruby under OSX. This simple example:
#include <boost/regex.hpp>
extern "C" void Init_bayeux()
{
boost::regex expression("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
}
results in a bad_cast exception being thrown:
#0 0x00000001014663bd in __cxa_throw ()
#1 0x00000001014cf6b2 in __cxa_bad_cast ()
#2 0x00000001014986f9 in std::use_facet<std::collate<char> > ()
#3 0x0000000101135a4f in boost::re_detail::cpp_regex_traits_base<char>::imbue (this=0x7fff5fbfe4d0, l=@0x7fff5fbfe520) at cpp_regex_traits.hpp:218
#4 0x0000000101138d42 in cpp_regex_traits_base (this=0x7fff5fbfe4d0, l=@0x7fff5fbfe520) at cpp_regex_traits.hpp:173
#5 0x000000010113eda6 in boost::re_detail::create_cpp_regex_traits<char> (l=@0x7fff5fbfe520) at cpp_regex_traits.hpp:859
#6 0x0000000101149bee in cpp_regex_traits (this=0x101600200) at cpp_regex_traits.hpp:880
#7 0x0000000101142758 in regex_traits (this=0x101600200) at regex_traits.hpp:75
#8 0x000000010113d68c in regex_traits_wrapper (this=0x101600200) at regex_traits.hpp:169
#9 0x000000010113bae1 in regex_data (this=0x101600060) at basic_regex.hpp:166
#10 0x000000010113981e in basic_regex_implementation (this=0x101600060) at basic_regex.hpp:202
#11 0x0000000101136e1a in boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign (this=0x7fff5fbfe710, p1=0x100540ae0 "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?", p2=0x100540b19 "", f=0) at basic_regex.hpp:652
#12 0x0000000100540a66 in boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::assign (this=0x7fff5fbfe710, p1=0x100540ae0 "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?", p2=0x100540b19 "", f=0) at basic_regex.hpp:379
#13 0x0000000100540a13 in boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::assign (this=0x7fff5fbfe710, p=0x100540ae0 "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?", f=0) at basic_regex.hpp:364
#14 0x000000010054096e in basic_regex (this=0x7fff5fbfe710, p=0x100540ae0 "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?", f=0) at basic_regex.hpp:333
#15 0x00000001005407e2 in Init_bayeux () at bayeux.cpp:10
#16 0x0000000100004593 in dln_load (file=0x1008bc000 "/Users/todi/sioux/lib/debug/rack/bayeux.bundle") at dln.c:1293
I compile the extension with:
g++ ./source/rack/bayeux.cpp -o /Users/todi/sioux/obj/debug/rack/bayeux.o -Wall -pedantic -Wno-parentheses -Wno-sign-compare -fno-common -c -pipe -I/Users/todi/sioux/source -ggdb -O0
And finally link the dynamic library with:
g++ -o /Users/todi/sioux/lib/debug/rack/bayeux.bundle -bundle -ggdb /Users/todi/sioux/obj/debug/rack/bayeux.o -L/Users/todi/sioux/lib/debug -lrack -lboost_regex-mt-d -lruby
I've searched the web and tried all kind of link and compiler switches. If I build a executable there is no such problem. Does someone else had such a problem and found a solution?
I've further investigated this and found that the function causing the exception looks like this:
std::locale loc = std::locale("C");
std::use_facet< std::collate<char> >( loc );
In the source of std::collate<> I found the throw statment:
use_facet(const locale& __loc)
{
const size_t __i = _Facet::id._M_id();
const locale::facet** __facets = __loc._M_impl->_M_facets;
if (__i >= __loc._M_impl->_M_facets_size || !__facets[__i])
__throw_bad_cast();
#ifdef __GXX_RTTI
return dynamic_cast<const _Facet&>(*__facets[__i]);
#else
return static_cast<const _Facet&>(*__facets[__i]);
#endif
}
Does this makes any sense to you?
Update: I've tried Jan's suggestion:
Todis-MacBook-Pro:rack todi$ g++ -shared -fpic -o bayeux.bundle bayeux.cpp
Todis-MacBook-Pro:rack todi$ ruby -I. -rbayeux -e 'puts :ok'
terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast
Abort trap
versions:
Todis-MacBook-Pro:rack todi$ ruby -v
ruby 1.9.2p136 (2010-12-25 revision 30365) [x86_64-darwin10.6.0]
Todis-MacBook-Pro:rack todi$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/opt/local/libexec/gcc/x86_64-apple-darwin10/4.5.2/lto-wrapper
Target: x86_64-apple-darwin10
Configured with: ../gcc-4.5.2/configure --prefix=/opt/local --build=x86_64-apple-darwin10 --enable-languages=c,c++,objc,obj-c++,fortran,java --libdir=/opt/local/lib/gcc45 --includedir=/opt/local/include/gcc45 --infodir=/opt/local/share/info --mandir=/opt/local/share/man --datarootdir=/opt/local/share/gcc-4.5 --with-local-prefix=/opt/local --with-system-zlib --disable-nls --program-suffix=-mp-4.5 --with-gxx-include-dir=/opt/local/include/gcc45/c++/ --with-gmp=/opt/local --with-mpfr=/opt/local --with-mpc=/opt/local --enable-stage1-checking --disable-multilib --enable-fully-dynamic-string
Thread model: posix
gcc version 4.5.2 (GCC)
Update:
It's not the bound-check in use_facet() that throws, but the next line, that actually does a dynamic cast. This example boils it down to maybe something with RTTI:
#define private public
#include <locale>
#include <iostream>
#include <typeinfo>
extern "C" void Init_bayeux()
{
std::locale loc = std::locale("C");
printf( "size: %i\n", loc._M_impl->_M_facets_size );
printf( "id: %i\n", std::collate< char >::id._M_id() );
const std::locale::facet& fac = *loc._M_impl->_M_facets[ std::collate< char >::id._M_id() ];
printf( "name: %s\n", typeid( fac ).name());
printf( "name: %s\n", typeid( std::collate<char> ).name());
const std::type_info& a = typeid( fac );
const std::type_info& b = typeid( std::collate<char> );
printf( "equal: %i\n", !a.before( b ) && !b.before( a ) );
dynamic_cast< const std::collate< char >& >( fac );
}
I've used printf() because usage of cout also fails. The output of the code above is:
size: 28
id: 5
name: St7collateIcE
name: St7collateIcE
equal: 1
terminate called after throwing an instance of 'std::bad_cast'
what(): std::bad_cast
Abort trap
Build with:
g++ -shared -fpic -o bayeux.bundle bayeux.cpp && ruby -I. -rbayeux -e 'puts :ok'
Update:
If I rename Init_bayeux to main() and link it to an executable, the output is the same, but no call to terminate.
Update:
When I write a little program to load the shared library and to execute Init_bayeux(), again, no exception is thrown:
#include <dlfcn.h>
int main()
{
void* handle = dlopen("bayeux.bundle", RTLD_LAZY|RTLD_GLOBAL );
void(*f)(void) = (void(*)(void)) dlsym( handle, "Init_bayeux" ) ;
f();
}
So it looks to me, that it might be a problem with how the ruby.exe was build. Does that make sense?
Update:
I had a look at the addresses containing the names of the two type_info objects. Same content, but different addresses. I added the -flat_namespace switch to the link command. Now the dynamic_cast works. The original Problem with the boost regex library still exists, but I think this might be solvable by linking boost statically into the shared library or by rebuilding the boost libraries with the -flat_namespace switch.
Update:
Now I'm back to the very first example with the boost regex expression, build with this command:
g++ -shared -flat_namespace -fPIC -o bayeux.bundle /Users/todi/boost_1_49_0/stage/lib/libboost_regex.a bayeux.cpp
But when loading the extension into the ruby interpreter, initializing of static symbols fails:
ruby(59384,0x7fff712b8cc0) malloc: *** error for object 0x7fff70b19500: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Program received signal SIGABRT, Aborted.
0x00007fff8a6ab0b6 in __kill ()
(gdb) bt
#0 0x00007fff8a6ab0b6 in __kill ()
#1 0x00007fff8a74b9f6 in abort ()
#2 0x00007fff8a663195 in free ()
#3 0x0000000100541023 in boost::re_detail::cpp_regex_traits_char_layer<char>::init (this=0x10060be50) at basic_string.h:237
#4 0x0000000100543904 in boost::object_cache<boost::re_detail::cpp_regex_traits_base<char>, boost::re_detail::cpp_regex_traits_implementation<char> >::do_get (k=@0x7fff5fbfddd0) at cpp_regex_traits.hpp:366
#5 0x000000010056005b in create_cpp_regex_traits<char> (l=<value temporarily unavailable, due to optimizations>) at pending/object_cache.hpp:69
#6 0x0000000100544c33 in boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign (this=0x7fff5fbfe090, p1=0x100567158 "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?", p2=0x100567191 "", f=0) at cpp_regex_traits.hpp:880
#7 0x0000000100566280 in boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::assign ()
#8 0x000000010056622d in boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::assign ()
#9 0x0000000100566188 in boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::basic_regex ()
#10 0x0000000100566025 in Init_bayeux ()
#11 0x0000000100003a23 in dln_load (file=0x10201a000 "/Users/todi/sioux/source/rack/bayeux.bundle") at dln.c:1293
#12 0x000000010016569d in vm_pop_frame [inlined] () at /Users/todi/.rvm/src/ruby-1.9.2-p320/vm_insnhelper.c:1465
#13 0x000000010016569d in rb_vm_call_cfunc (recv=4303980440, func=0x100042520 <load_ext>, arg=4303803000, blockptr=0x1, filename=<value temporarily unavailable, due to optimizations>, filepath=<value temporarily unavailable, due to optimizations>) at vm.c:1467
#14 0x0000000100043382 in rb_require_safe (fname=4303904640, safe=0) at load.c:602
#15 0x000000010017cbf3 in vm_call_cfunc [inlined] () at /Users/todi/.rvm/src/ruby-1.9.2-p320/vm_insnhelper.c:402
#16 0x000000010017cbf3 in vm_call_method (th=0x1003016b0, cfp=0x1004ffef8, num=1, blockptr=0x1, flag=8, id=<value temporarily unavailable, due to optimizations>, me=0x10182cfa0, recv=4303980440) at vm_insnhelper.c:528
...
Again, this doesn't fail, when I load the shared library by the little c program from above.
Update:
Now I link the first example static:
g++ -shared -fPIC -flat_namespace -nodefaultlibs -o bayeux.bundle -static -lstdc++ -lpthread -lgcc_eh -lboost_regex-mt bayeux.cpp
With the same error:
ruby(15197,0x7fff708aecc0) malloc: *** error for object 0x7fff7027e500: pointer being freed was not allocated
otool -L confirmed that every library is linked static:
bayeux.bundle:
bayeux.bundle (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.11)
debug:
If I link against the boost debug version, then it works like expected.
A:
For the records: I've now build boost and my application with the very same compiler (version 4.2.1 [official apple version]). No problems so far. Why it will not work as expected when the ruby extension links all libraries statically is a miracle to me. Thank to all who put time into this issue.
Kind regards
Torsten
| {
"pile_set_name": "StackExchange"
} |
Q:
'What one didn't see was anything' is weird. So why has it persisted?
John McWhorter PhD Linguistics (Stanford). The Power of Babel (2003). pp. 226-227.
I don't know how to replicate the format on the para. on p. 227 on Old English.
I didn't spot the red underline overhead before, but I now agree with McWhorter that it feels illogical to say "what one didn't see was anything", to express nothing as anything or something, or "that one saw nothing".
But why have this illogical weirdness persisted? Why have humans acclimated to this illogical syntax, rather than a more logical alternative?
A:
I think McWhorter is exaggerating his point a bit to try to make English speakers who are used to prescription against "double negatives" rethink their possible prejudices. As far as I know, the use of a word like "anything" in a negative clause is not actually that unusual, and I don't think it makes any more sense to think of it as "illogical" than it does to think of negative concord as illogical.
According to "On the typology of negative concord", by Johan van der Auwera & Lauren Van Alsenoy, negation constructions like "I saw nothing" (with a special negative word, like the negative pronoun "nothing", but not the usual clause negator) are actually more unusual than negative constructions like "I didn't see anything" (with the usual clause negator--the negative word "don't"--and a negative polarity indefinite word).
A wide variety of languages apparently make use of "negative polarity" indefinite words or neutral indefinite words in negative contexts.
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery image show/hide not functioning
I have a supposedly-simple jquery task in my app that changes an image based on which thumbnail is clicked. The HTML/erb is like this:
<img src="https://lagunagreenworks.s3-us-west-1.amazonaws.com/Images/Airblades.png" id="#main1" class="main-image">
<img src="https://lagunagreenworks.s3-us-west-1.amazonaws.com/Images/HU02+V+(Sprayed+Nickel).jpg" id="#main2" class="main-image hidden">
<img src="https://lagunagreenworks.s3-us-west-1.amazonaws.com/Images/AB14+White+LV+(301854-01).jpg" id="#main3" class="main-image hidden">
<img src="https://lagunagreenworks.s3-us-west-1.amazonaws.com/Images/WD05+Long+(247663-01).jpg" id="#main4" class="main-image hidden">
<img src="https://lagunagreenworks.s3-us-west-1.amazonaws.com/Images/9kJ+Steel+Front.jpg" id="#main5" class="main-image hidden">
<div class="row thumb-container">
<div class="col">
<img src="https://lagunagreenworks.s3-us-west-1.amazonaws.com/Images/Airblades.png" id="#thumb1" class="thumbnail active">
</div> <!-- col -->
<div class="col">
<img src="https://lagunagreenworks.s3-us-west-1.amazonaws.com/Images/HU02+V+(Sprayed+Nickel).jpg" id="#thumb2" class="thumbnail">
</div> <!-- col -->
<div class="col">
<img src="https://lagunagreenworks.s3-us-west-1.amazonaws.com/Images/AB14+White+LV+(301854-01).jpg" id="#thumb3" class="thumbnail">
</div> <!-- col -->
<div class="col">
<img src="https://lagunagreenworks.s3-us-west-1.amazonaws.com/Images/WD05+Long+(247663-01).jpg" id="#thumb4" class="thumbnail">
</div> <!-- col -->
<div class="col">
<img src="https://lagunagreenworks.s3-us-west-1.amazonaws.com/Images/9kJ+Steel+Front.jpg" id="#thumb5" class="thumbnail">
</div> <!-- col -->
</div> <!-- row -->
And the jquery is like this:
<script>
$(document).ready(function() {
$("#thumb1").click(function(){
$(".main-image").addClass("hidden");
$(".thumbnail").removeClass("active");
$("#thumb1").addClass("active");
$('#main1').removeClass("hidden");
});
$("#thumb2").click(function(){
$(".main-image").addClass("hidden");
$(".thumbnail").removeClass("active");
$("#thumb2").addClass("active");
$('#main2').removeClass("hidden");
});
$("#thumb3").click(function(){
$(".main-image").addClass("hidden");
$(".thumbnail").removeClass("active");
$("#thumb3").addClass("active");
$('#main3').removeClass("hidden");
});
$("#thumb4").click(function(){
$(".main-image").addClass("hidden");
$(".thumbnail").removeClass("active");
$("#thumb4").addClass("active");
$('#main4').removeClass("hidden");
});
$("#thumb5").click(function(){
$(".main-image").addClass("hidden");
$(".thumbnail").removeClass("active");
$("#thumb5").addClass("active");
$('#main5').removeClass("hidden");
});
});
</script>
The CSS doesn't really affect the problem as it's working fine on the initial page load, but here it is:
.product-page .main-image {
max-width: 100%;
max-height: 350px;
}
.product-page .thumb-container {
position: absolute;
bottom: 0;
padding: 0 25px;
}
.product-page .thumbnail {
max-height: 50px;
max-width: 100%;
padding: 5px;
cursor: pointer;
}
.product-page .thumbnail.active {
border: thin $color-light-grey solid;
}
Here's a jsfiddle of my issue. Can anyone see what I'm doing wrong?
A:
So first problem that I see is way You are reffering to an DOM element You are using:
$("#thumb2").click(function()...
$('#id') notation is looking for element with id="id" You are looking for element with id="thumb2" but in Your code there is an element with id="#thumb2"
do You see it now ? I didn't test rest of the code but this is certainly one of the issues here.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the purpose of the delegates are immutable in c#?
I was reading a book illustrated C # 2012 in the section Combining Delegates point not notice that? Purpose of the delegates are immutable.
Combining Delegates
All the delegates you’ve seen so far have had only
a single method in their invocation lists. Delegates can be “combined”
by using the addition operator. The result of the operation is the
creation of a new delegate, with an invocation list that is the
concatenation of copies of the invocation lists of the two operand
delegates. For example, the following code creates three delegates.
The third delegate is created from the combination of the first two.
MyDel delA = myInstObj.MyM1;
MyDel delB = SClass.OtherM2;
MyDel delC = delA + delB; // Has combined invocation list
Although the term combining delegates might give the impression that
the operand delegates are modified, they are not changed at all. In
fact, delegates are immutable. After a delegate object is created, it
cannot be changed. Figure 15-6 illustrates the results of the
preceding code. Notice that the operand delegates remain unchanged.
A:
Thread-safety and speed are the primary concerns here. A delegate update is not atomic, it requires updating 6 fields and a list. Making it atomic so it cannot get corrupted requires a lock, far too expensive for such a basic operation that rarely needs to be thread-safe.
By making it immutable, the delegate object cannot get corrupted since it always sets fields on an object that nobody has a reference to yet. Reassigning the delegate object reference is atomic, a basic .NET memory model guarantee. So no need for a lock anymore. The trade-off is less efficient memory use, it is a small penalty.
Do keep in mind that the thread-safe delegate update does not automatically make your code thread-safe as well. The test-and-fire code needs to copy the reference to avoid NRE and you can make a callback to a method that was already unsubscribed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parsing XML Elements in JAVA
I want to parse XML in java. It will be DOM or SAX. Read in a book JAXP is good one. Also when i google out found XERCES/XALAN. Which parser is commonly used?
In SAX Parser if i register for a single element event will the SAX parse stops processing the XML message after encountering the element. Read in a book DOM reads the entire XML and loads into memory even if i want to know single element value.
A:
I want to parse XML in java. It will be DOM or SAX. Read in a book
JAXP is good one. Also when i google out found XERCES/XALAN. Which
parser is commonly used?
Xerces is an implementation of both DOM and SAX, and it is built into the JDK. See javax.xml.parsers.
In SAX Parser if i register for a single element event will the SAX
parse stops processing the XML message after encountering the element.
No.
Read in a book DOM reads the entire XML and loads into memory even if
i want to know single element value.
Yes.
A:
All of the above parsers you mention are excellent. My personal preference would be XERCES if the application did a lot of XML processing, otherwise, the "built in" parsers are more than good enough.
You will need to process every event from the SAX parser and ignore the ones you are not interested in. You can stop parsing at any point by "destroying" the parser object. If you are only interested in one or two elements of a large message then SAX is the way to go. If you are interested in all or most of the elements then use the DOM parser, you take a slight performance hit, but, the "give me what I want" API makes for much clearer code than the "take what I give you" SAX API.
| {
"pile_set_name": "StackExchange"
} |
Q:
Switch statement over ReadOnlySpan is not supported?
I am playing with Span in C#.
Am I right that I cannot use switch statement with span I have to write methods like this?
private int GetNumberOfLegs(ReadOnlySpan<char> animal)
{
if (animal.SequenceEqual("dog".AsSpan()))
return 4;
if (animal.SequenceEqual("cat".AsSpan()))
return 4;
if (animal.SequenceEqual("spider".AsSpan()))
return 8;
if (animal.SequenceEqual("bird".AsSpan()))
return 2;
throw new NotSupportedException($"Uknown animal {animal.ToString()}");
}
Is there better way to express this algorithm with Span?
A:
Abusing pattern matching could help:
private int GetNumberOfLegs(ReadOnlySpan<char> animal)
{
switch (animal)
{
case var dog when dog.SequenceEqual("dog".AsSpan()):
return 4;
case var cat when cat.SequenceEqual("cat".AsSpan()):
return 4;
case var spider when spider.SequenceEqual("spider".AsSpan()):
return 8;
case var bird when bird.SequenceEqual("bird".AsSpan()):
return 2;
}
throw new NotSupportedException($"Uknown animal {animal.ToString()}");
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Numbering of groups in dplyr?
I have question about numbering the groups in a data.frame.
I found only one similar approach here dplyr-how-to-number-label-data-table-by-group-number-from-group-by
but it didnt worked to me. I dont know why.
S <- rep(letters[1:12],each=6)
R = sort(replicate(9, sample(5000:6000,4)))
df <- data.frame(R,S)
get_next_integer = function(){
i = 0
function(S){ i <<- i+1 }
}
get_integer = get_next_integer()
result <- df %>% group_by(S) %>% mutate(label = get_integer())
result
Source: local data frame [72 x 3]
Groups: S [12]
R S label
(int) (fctr) (dbl)
1 5058 a 1
2 5121 a 1
3 5129 a 1
4 5143 a 1
5 5202 a 1
6 5213 a 1
7 5239 b 1
8 5245 b 1
9 5269 b 1
10 5324 b 1
.. ... ... ...
I look for elegant solution in dplyr. Numbering each letters from 1 to 12 etc.
A:
Using as.numeric will do the trick.
S <- rep(letters[1:12],each=6)
R = sort(replicate(9, sample(5000:6000,4)))
df <- data.frame(R,S)
result <- df %>% mutate(label = as.numeric(S)) %>% group_by(S)
result
Source: local data frame [72 x 3]
Groups: S
R S label
1 5018 a 1
2 5042 a 1
3 5055 a 1
4 5066 a 1
5 5081 a 1
6 5133 a 1
7 5149 b 2
8 5191 b 2
9 5197 b 2
10 5248 b 2
.. ... . ...
A:
No need to use dplyr at all.
S <- rep(letters[1:12],each=6)
R = sort(replicate(9, sample(5000:6000,4)))
df <- data.frame(R,S)
df$label <- as.numeric(factor(df$S))
| {
"pile_set_name": "StackExchange"
} |
Q:
Div unnaligned with other content but still in the wrapper
Hello I am working on this shopify theme that i want to customize. I took the footer and copied them to be between the menu and the picture slider. I did not change anything in the css nor the html ( I just renamed the id's and classes that affected the footer and renamed them). But the borders of the div and possibly the div goes out of alignment and is a bit more wider than the rest of the content. Here is the code and the demo:
<div id="footer1" >
<div id="big-footer1" class="row">
<div class="desktop-4 tablet-2 mobile-3 alpha">
<a href="/Shop/List/Gym_and_Fitness?cm_sp=homepage-_-fitnesst1-_-10-06-14" id="A_4"><img src="/mrporter/content/2014/home/100614/t1.jpg" alt="" id="IMG_5" /></a>
<h2 id="H2_6">
A SPORTING SUMMER:<br id="BR_7" />WHAT TO WEAR
</h2>
</div>
<div class="desktop-4 tablet-2 mobile-3">
<a href="/Shop/List/Gym_and_Fitness?cm_sp=homepage-_-fitnesst1-_-10-06-14" id="A_4"><img src="/mrporter/content/2014/home/100614/t1.jpg" alt="" id="IMG_5" /> </a>
<h2 id="H2_6">
A SPORTING SUMMER:<br id="BR_7" />WHAT TO WEAR
</h2>
</div>
<div id="" class="desktop-4 tablet-2 mobile-3 omega">
<a href="/Shop/List/Gym_and_Fitness?cm_sp=homepage-_-fitnesst1-_-10-06-14" id="A_4"><img src="/mrporter/content/2014/home/100614/t1.jpg" alt="" id="IMG_5" /></a>
<h2 id="H2_6">
A SPORTING SUMMER:<br id="BR_7" />WHAT TO WEAR
</h2>
</div>
</div>
And here is the css:
#big-footer1 {
border-left: 1px solid {{ settings.footer-top-border }};
border-right: 1px solid {{ settings.footer-top-border }};
margin-bottom: 0px;
margin-top: 0px;
border-bottom: 0px solid {{ settings.footer-bottom-border }};
list-style-type: none;
}
#big-footer1 .alpha { border-right: 1px solid {{ settings.dotted_color }}; }
#big-footer1 .omega { border-left: 1px solid {{ settings.dotted_color }}; }
@media screen and (max-width: 740px) {
#big-footer1 .alpha { border-right: 0px solid {{ settings.dotted_color }}; }
#big-footer1 .omega { border-left: 0px solid {{ settings.dotted_color }}; }
}
#big-footer1 { color: {{ settings.footer-text-color }}; }
#big-footer1 a { color: {{ settings.footer-text-color }}; }
#big-footer1 > div { padding: 0 20px; min-height: 120px;}
#big-footer1 ul {
list-style: none;
margin: 0;
line-height: 34px;
}
#big-footer1 ul li { display: inline-block; margin: 0 5px; }
#footer1 { background: {{ settings.footer-background }}; padding-bottom: 20px; text-align: center; }
A:
The code has a width set to over 100%, which is why it is not aligned properly. The line of code you are looking for is: .gridlock .row .row 102.083%, which according to my browser is on line 19 of stylesheet.css. This is affecting the width of <div id="big-footer1" class="row">
| {
"pile_set_name": "StackExchange"
} |
Q:
First word on each volume of a dictionary
Suppose you have to write a dictionary of a language with 27 letters (Spanish): 5 vowels and 22 consonants (yes, Ñ is included). Each word of this new language is made of two letters one wowel and one consonant. Find what would be the first letter on each volume, knowing that the order is alphabetical and there will be 4 volumes.
Knowing how many words there will be in total (220) and in each volume (55) is an easy task, finding the first word of each book seems to be not straightforward (at least to me). I want to know if there is an easy method other than writing the dictionary.
A:
Write the alphabet ${\tt a}$-${\tt z}$ in a first column. Begin the second column with $22$ and add $5$ at each consonant, $22$ at each vowel. If done correctly you end up with $220$. These numbers indicate the total number of words from the beginning of the dictionary until the end of the corresponding letter as first letter. Now find the letter-combinations that would be at positions $1$, $56$, $111$, $166$. By coincidence not much counting back will be necessary, and you get $\ {\tt ab}$, $\ {\tt ew}$,$\ {\tt lu}$,$\ {\tt si}$.
There is no "structural" approach to this problem since the data defining the particular instance not only consist of the numbers $5$ and $22$, but also incorporate a certain "random" $5$-element-subset of $[27]$, which is $1$ of $74\,750$.
| {
"pile_set_name": "StackExchange"
} |
Q:
tkinter entry widget textvariable will not update with .set method
My problem is, I cant get the Entry field to display anything.
I have been working with Tk for Python and Ruby for a few years on and off at work making tools for my group. the current tool that I am developing requires some popup windows with Entry widget fields in them. I have employed Entry fields with textvariable attributes in many previous applications, however in this case I am using a Class definition to create generic window instances. I am using StringVar to provide the object for holding and managing the value in the Entry field however no-matter what I set the value of the StringVar to the field will not update. Also setting the Entry to display with text="something" on initialization doesn't display anything in the Entry field either.
here is a simplified example script exhibiting my problem.
import Tkinter
from Tkinter import *
window_list = []
class popup_window:
def __init__(self):
self.popup = Tk()
Entry(self.popup, textvariable=entry_value, width=60, bg="blue", foreground="cyan").grid(row=1, column=1)
def spawner():
window_list.append(popup_window())
main_window = Tk()
entry_value = StringVar()
entry_value.set("test")
spawn_window = Button(main_window, text='spawn', command=spawner).grid(row=1, column=1)
main_window.mainloop()
When run this script's Entry field does not display "test".
A:
You cannot create more than once instance of Tk, because of exactly this type of behavior. If you need a new window, create an instance of Toplevel.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to dump remote database without using mysqlDump
I have a similar problem from this question How to dump remote database without mysqldump?
How ever when I run
ssh -f L 3306:localhost:3306 user@remoteserver -N
I am receive the following error
bind: Address already in use
channel_setup_fwd_listener: cannot listen to port: 3306
Could not result local forwarding
A:
You are likely already running a local MySQL server that's using port 3306.
You can just change the local port for the tunneling like so:
ssh -f -L 33306:localhost:3306 user@remoteserver -N
but of course you must point your local tools to port 33306 then.
| {
"pile_set_name": "StackExchange"
} |
Q:
Align infobox to marker in Google Maps
I am using the InfoBox plugin, and I have the following code:
Gmaps.map.infobox = function(boxText) {
return {
content: boxText
,disableAutoPan: false
,maxWidth: 0
,pixelOffset: new google.maps.Size(-140, 0)
,zIndex: null
,boxStyle: {
background: "url('http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.5/examples/tipbox.gif') no-repeat"
,opacity: 0.75
,width: "280px"
}
,closeBoxMargin: "10px 2px 2px 2px"
,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,enableEventPropagation: false
}};
With a marker of dimensions 77x80 pixels, when the InfoWindow is shown, it aligns correctly at the bottom of the marker, as you can see here:
However, if I change the size of the marker to 35x44 px, the InfoWindow is not exactly aligned at the bottom of the marker, as you can see here:
Any thoughts on how can I make it completely aligned at the bottom?
EDIT: For the small markers, I created them by setting this in the library I use (gmaps4rails):
marker.picture({
:picture => "assets/juice-pin-small.png",
:width => 35,
:height => 44,
})
For the big markers, I create them by setting this:
marker.picture({
:picture => "assets/juice-pin-small.png",
:width => 70,
:height => 88,
:marker_anchor => [23,78]
})
A:
What I know is definitely not the best solution, because you need two sets of options if you will use both sized markers.
Anyway, the positioning of the infobox can be changed with pixelOffset: new google.maps.Size(-140, 0);, in your case, to move the box left, make the first number more negative (like, -145).
Thought of something else: edit the marker itself and shift it a few pixels.
| {
"pile_set_name": "StackExchange"
} |
Q:
Difference between Travel and Commute
So I am taking some english lessons on grammar and vocabulary and the teacher said that there was a difference between the meaning of travelling and commuting. He did explain it but I can't seem to remember it now and even when I did hear it, couldnt understand it properly. Could someone kindly help me out with this.
A:
Commuting is a special kind of traveling. You do it regularly in order to get back and forth to school, to your job, or to your family.
Think of a commuter train. Such a train picks passengers up in the morning in the outskirts of the city, has no runs between approximately 10 am and 3 pm, and then starts delivering passengers back to the outskirts again starting around 4 pm.
This is related to the commutative law of addition -- a + b = b + a. a and b trade places! When you commute to work, you just go back and forth between points A and B, over and over again. This is a boring kind of traveling.
When someone says, "I like to travel," they are imagining going to A, B, C, D, E -- and this is not boring!
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there an application or website where I can practice trading US stocks with virtual money?
For somebody that doesn't know much about the stock market and this type of investing, I was looking to see if anybody knew about an application/website where you can use "virtual" money (in other words, fake) to invest in stocks and see gains/losses and simply just learn.
The reason I want to do this is because I feel it would be a great exercise to learning the market, investing, and stocks without risking real money.
A:
I traded futures for a brief period in school using the BrokersXpress platform (now part of OptionsXpress, which is in turn now part of Charles Schwab). They had a virtual trading platform, and apparently still do, and it was excellent. Since my main account was enabled for futures, this carried over to the virtual account, so I could trade a whole range of futures, options, stocks, etc. I spoke with OptionsXpress, and you don't need to fund your acount to use the virtual trading platform. However, they will cancel your account after an arbitrary period of time if you don't log in every few days. According to their customer service, there is no inactivity fee on your main account if you don't fund it and make no trades.
I also used Stock-Trak for a class and despite finding the occasional bug or website performance issue, it provided a good experience. I received a discount because I used it through an educational institution, and customer service was quite good (probably for the same reason), but I don't know if those same benefits would apply to an individual signing up for it.
I signed up for top10traders about seven years ago when I was in secondary school, and it's completely free. Unfortunately, you get what you pay for, and the interface was poorly designed and slow. Furthermore, at that time, there were no restrictions that limited the number of shares you could buy to the number of outstanding shares, so you could buy as many as you could afford, even if you exceeded the number that physically existed. While this isn't an issue for large companies, it meant you could earn a killing trading highly illiquid pink sheet stocks because you could purchase billions of shares of companies with only a few thousand shares actually outstanding. I don't know if these issues have been corrected or not, but at the time, I and several other users took advantage of these oversights to rack up hundreds of trillions of dollars in a matter of days, so if you want a realistic simulation, this isn't it.
Investopedia also has a stock simulator that I've heard positive things about, although I haven't used it personally.
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL JOIN - Return NULL for duplicate results in left table
I believe this is a pretty simple thing, and I swear I've done it before but I can't remember how.
So let's say I have a one-to-many relationship. I want to JOIN the two tables, but not allow duplicates for the left table.
SQLFIDDLE
So based on the above SQLFiddle, my results would be:
categories.title | items.NAME | items.category_id
-----------------------------------------------------
red | apple | 1
red | car | 1
red | paper | 1
yellow | lego | 2
yellow | banana | 2
blue | pen | 3
I want it to be:
categories.title | items.NAME | items.category_id
-----------------------------------------------------
red | apple | 1
NULL | car | 1
NULL | paper | 1
yellow | lego | 2
NULL | banana | 2
blue | pen | 3
My reasoning is that this way, I can easily loop over the results without having to do any further processing with PHP.
A:
You can replace the values with something like this:
select
case when rownum = 1 then title else null end title,
name,
category_id
from
(
SELECT c.title,
i.name,
i.category_id,
@row:=(case when @prev=title and @precat=category_id
then @row else 0 end) + 1 as rownum,
@prev:=title ptitle,
@precat:=category_id pcat
FROM items AS i
INNER JOIN categories AS c
ON c.id = i.category_id
order by i.category_id, c.title
) src
order by category_id, rownum
See SQL Fiddle with Demo
The result is:
| TITLE | NAME | CATEGORY_ID |
---------------------------------
| red | apple | 1 |
| (null) | car | 1 |
| (null) | paper | 1 |
| yellow | lego | 2 |
| (null) | banana | 2 |
| blue | pen | 3 |
| {
"pile_set_name": "StackExchange"
} |
Q:
Specify dependency implementation in constructor parameter
Suppose I have an interface IA, two implementations A1 and A2 and a dependent class B that depends on IA. Two implementations of the same interface in Windsor container are registered like this:
container.Register(Component.For<IA>()
.ImplementedBy<A1>());
container.Register(Component.For<IA>()
.ImplementedBy<A2>());
Is there are way to specify which implementation to use inside the dependent class B?
For example in Autofac, I could use KeyFilterAttribute like this:
class B
{
...
public B([KeyFilter("A1")]IA a)
{
...
}
}
A:
There's a few ways to achieve this, and which one is most suitable depends on the bigger context.
If you register the components one by one, like in the sample code in question Windsor uses the first component registered as the default for the service. So inside your B you're guaranteed to get the service implemented by A1.
To be explicit you can force a component to be the default (works for registering by convention too
.
container.Register(
Component.For<IA>().ImplementedBy<A1>(),
Component.For<IA>().ImplementedBy<A2>().IsDefault());
Or, looking at it from the consuming-end's perspective you can configure B to pick either A1 or A2 regardless of the defaults (which would be the closest to the Autofac
.
container.Register(
Component.For<B>()
.DependsOn(Dependency.OnComponent<IA, A1>))
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the method addSubview of NSView inherently slow? (Cocoa OSX)
I am trying to speed my gui that loads very slow slow when I am loading a large project (the gui is a representation of groups and sub groups and is made up of many views). During this process I was looking at how long certain code segments take to execute and I have found that a call to addsubview is taking between 10 and 20 milliseconds most of the time. The subview I was looking at is a disclosure button. I am wondering if this method is just inherently slow or is their some other factor at work here? Is the time it takes to add the subview dependent on the complexity of the subview or is that not a factor? Also, is there some other method that can be used to add a subview that might be faster?
A:
You could try -setSubviews: which takes an array of subviews. This may be faster then calling -addSubview: multiple times yourself.
Otherwise, -addSubview: and -addSubview:positioned:relativeTo: are the only other methods for inserting subviews.
I'm curious, though, why is 10 - 20 ms to slow for a single subview?
How many subviews are you trying to add?
It is possible there is an alternative design using NSCell's that may be faster, but without know more details about what you are trying to accomplish, it is difficult to know.
| {
"pile_set_name": "StackExchange"
} |
Q:
console.log shows original array after foreach
let words = ["[hello", "]bye", "", "lol-"];
words.forEach((item, index) => {
item = item.replace(/\[|\]|\-/g, "");
if (item == "") words.splice(index, 1);
});
console.log(words);
Why I always get Array(3) [ "[hello", "]bye", "lol-" ]?
I tried to console.log item after replace() and it returns correct item.
A:
forEach only iterates through array. If you want to change elements of array use map() and to remove the empty string use filter()
let words = ["[hello", "]bye", "", "lol-"];
words = words.map((item, index) => item.replace(/\[|\]|\-/g, "")).filter(x => x !== '');
console.log(words);
| {
"pile_set_name": "StackExchange"
} |
Q:
Application on server crashes when accessed via browser - after full system upgrade
After a recent full-system upgrade one of my applications stopped working. It's Fatrat 1.2.0_beta2-11 on Archlinux (installed from community repository).
Without enabling web access the application works just fine, but when web access is enabled and accessed via browser, the app on server crashes:
[pi@raspberrypi data]$ fatrat -n
Current locale "C"
Locating the Java VM for Java-based plugins...
Loading queues
HttpService::applySettings()
Listening on port 2233
FatRat is up and running now
Floating point exception (core dumped)
I tried downgrading the application to beta2_10 from cache but it didn't help. I also cleared all fatrat .conf files and reinstalled to the latest version, it didn't help either so I suspect there must be a problem with some upgraded dependency.
How can I check the fatrat dumped core? Or what else I can do to fix this?
A:
More logging
Given it's a Java application there should be a stack trace that the JVM dumped along with this error. Is there a log file that fatrat is generating? You might need to specify this via switches when you run he above command to get access to this log file or the stack trace.
libtorrent changed?
Also looking through the FAQ for fatrat there is this bullet:
Q: I have installed a new version of libtorrent and FatRat doesn't download anything and/or crashes. Fix it!
A: Please recompile FatRat against the newly installed libtorrent before reporting bugs. Libtorrent's API/ABI tends to change frequently and even between minor versions.
Getting more information
Anytime I run into an issue such as this I almost always put an strace in front of it so that I can get some insight into what libraries and system calls an application is making. This usually gives you good leads to follow when chasing down problems such as this.
$ strace -o fatrat_strace.log fatrat -n
After it dies you should have a complete transcript of what the application was doing from the time you invoked it until the coredump.
| {
"pile_set_name": "StackExchange"
} |
Q:
R: plotting distinctive lines with for loop
dat <- list(c(1.12157347682574, 1.33192942183165, 2.08170603538164,
3.21936891077735, 3.87674160966784, 4.01222877372179, 3.97721253044977,
3.92748085243377, 3.89422132704385, 3.87554992373411, 3.86571722337484,
3.86066855038186, 3.85810016465002, 3.85679624059312, 3.85613341785451,
3.85579555076542, 3.85562274484616, 3.85553404933868, 3.85548836742791,
3.85546476209749, 3.85545252710548), c(1.10529328957704, 1.31478057418982,
2.05843350413484, 3.21445290319435, 3.93127780496161, 4.10019570732597,
4.0548974496435, 3.97577600575589, 3.91388817353566, 3.87397233241435,
3.85011420707963, 3.83631205949334, 3.82843188274012, 3.82395020512325,
3.82139984806649, 3.81994467228049, 3.81911146133043, 3.81863258400429,
3.81835633714707, 3.81819642258335, 3.81810355018493), c(1.08732237015566,
1.29744314553374, 2.03681100176799, 3.18820303674863, 3.90649946705568,
4.08059333708303, 4.04639279053423, 3.98156199908701, 3.93264549967637,
3.90244185986869, 3.88514800191734, 3.87554934102343, 3.87028551934942,
3.86740818622607, 3.86583394198314, 3.86497024645408, 3.86449471113229,
3.86423191258367, 3.86408614948732, 3.86400502180298, 3.86395972379237
), c(1.30161877569605, 1.46553776200827, 2.10197173547206, 3.06930201699535,
3.66250999070993, 3.85723600464989, 3.8942042549933, 3.88392091929778,
3.8605155020708, 3.83375521970562, 3.80643844775653, 3.77938071354659,
3.75282366570479, 3.72683925144018, 3.70144788585054, 3.67665362718513,
3.65245483803303, 3.62884749589963, 3.60582627074711, 3.58338491537713,
3.5615164406438), c(1.08469594718265, 1.29546127452487, 2.03810539840721,
3.18905959610048, 3.89746111531108, 4.06513051117241, 4.03208432847638,
3.97188967237102, 3.92762525203426, 3.90089820027383, 3.88590086923236,
3.87773268456738, 3.87333409971113, 3.87097228241208, 3.8697027802883,
3.86901848471182, 3.86864832970741, 3.86844736049309, 3.86833785249504,
3.86827797747177, 3.86824513600819), c(1.07964052838977, 1.29190777425215,
2.04231250239992, 3.19798917985082, 3.89723898066506, 4.05757629447758,
4.02387699444488, 3.96603112527963, 3.9243602259927, 3.89958493083309,
3.88586527520208, 3.87848244531751, 3.87455196717863, 3.87246483056295,
3.87135520285416, 3.87076356341284, 3.87044698746471, 3.87027696477127,
3.87018532072631, 3.87013575499355, 3.87010886245731), c(1.08933181649253,
1.29901388665636, 2.03604356337407, 3.18580149536436, 3.9065276727864,
4.08284397088934, 4.04915431500807, 3.9839665676791, 3.93452404770496,
3.90388767912571, 3.88629572919666, 3.87650700142078, 3.8711264587724,
3.8681788052111, 3.86656261507012, 3.86567402891195, 3.86518376322719,
3.86491225889191, 3.86476135376567, 3.86467718966398, 3.86463009866786
), c(1.12459738833516, 1.33429622029097, 2.08134547519017, 3.21607128232391,
3.87334654404529, 4.0092794872425, 3.97432485460807, 3.92449513705583,
3.89113365765329, 3.87239201995412, 3.86251706226948, 3.85744441841396,
3.85486281767585, 3.85355171294798, 3.85288501684111, 3.8525450675694,
3.85237114377774, 3.85228184815236, 3.8522358438795, 3.85221206522138,
3.85219973692982), c(1.08152696725377, 1.29354595382903, 2.04268473144721,
3.19946254279135, 3.90444884340271, 4.06790786857492, 4.0329743488585,
3.9721635966533, 3.92774092720633, 3.9009926112924, 3.88600650759486,
3.87785240458544, 3.87346429522664, 3.87110919016533, 3.86984371655882,
3.869161759929, 3.86879293902871, 3.86859272357885, 3.86848363941323,
3.86842400221486, 3.86839129414273), c(1.08197483401857, 1.29359825225018,
2.04082955314597, 3.19437482098117, 3.89680650725515, 4.05972606592981,
4.02617525912275, 3.96741176617648, 3.92476392035391, 3.89926386772869,
3.88507394855001, 3.87740396348501, 3.87330326448182, 3.87111672936341,
3.86994950869332, 3.86932463408538, 3.86898891944037, 3.86880788736096,
3.86870991350275, 3.86865670925241, 3.86862772534133), c(1.08216196424983,
1.29413465287689, 2.04304891046787, 3.19856102707185, 3.90114775913897,
4.0634953181634, 4.02931505555857, 3.97000974912286, 3.92696706310058,
3.90120957987481, 3.88686190905547, 3.87909827895443, 3.87494285145371,
3.87272456890303, 3.8715389950979, 3.87090352665212, 3.87056170077119,
3.87037714404976, 3.87027713742418, 3.87022276077104, 3.87019310063444
), c(1.08208080422425, 1.29409482026275, 2.04322281433486, 3.19877157213528,
3.90088920797055, 4.06293059188269, 4.02879633885981, 3.96968626960857,
3.92683419521334, 3.90121559093586, 3.88695769522339, 3.879248936171,
3.87512613020615, 3.87292696985694, 3.87175252322308, 3.87112350463803,
3.87078540971225, 3.87060300879754, 3.87050424709519, 3.87045058912723,
3.87042134381434), c(1.08220050068092, 1.29416045954134, 2.04300889772717,
3.19847760351553, 3.90113372450959, 4.06353948547856, 4.02936728462705,
3.97004710522954, 3.92698700475469, 3.90121623176852, 3.88685981428833,
3.87909079476742, 3.87493215130221, 3.87271198077119, 3.87152530797643,
3.87088920267017, 3.87054700860192, 3.87036223928244, 3.8702621099747,
3.87020766254669, 3.87017796158474), c(1.08207245581171, 1.29409069738142,
2.04324072847744, 3.1987945048703, 3.90086667118013, 4.06287780648447,
4.02874718343757, 3.96965515642479, 3.92682083928555, 3.90121519699921,
3.88696568414963, 3.87926204867567, 3.87514228806757, 3.87294491227269,
3.87177150366836, 3.87114308652571, 3.87080533935571, 3.87062313929028,
3.87052449352086, 3.87047090244975, 3.87044169573205), c(1.08218708599303,
1.29415164868573, 2.0430238507559, 3.19850707937143, 3.90113545482259,
4.06351892102187, 4.02934466379532, 3.97003155465113, 3.92697929062447,
3.90121442227887, 3.88686187260142, 3.87909523146381, 3.87493800601191,
3.87271866772437, 3.87153247939674, 3.87089665489438, 3.87055462321291,
3.87036994768823, 3.87026987252343, 3.87021545634019, 3.87018577340675
))
par(mfrow = c(1, 1))
plot(NA, ylim = c(0, 7), xlim = c(0, 20))
for(i in 1:15){
lines(dat[[i]], type = "l", col = colorRampPalette(c("blue", "red"))(i))
}
I'm trying to plot 15 curves onto the same graph within a for loop. Ideally, I would want to be able to distinguish between them easily. I've tried lines(dat[[i]], type = "l", col = rainbow(i)) as well but that was no luck. I just want a plot with 15 curves, each with its own distinctive color.
A:
Here it is with rainbow(), plus a legend..
par(mfrow = c(1, 1))
plot(NA, ylim = c(0, 7), xlim = c(0, 20))
cols <- rainbow(15)
# cols <- heat.colors(15)
# cols <- terrain.colors(15)
# cols <- cm.colors(15)
# I like a darker rainbow
# darkerizer <- function(colors, dark=.85) adjustcolor(colors, red.f=dark, green.f=dark, blue.f=dark)
# cols <- darkerizer(rainbow(15), dark=.85)
for(i in 1:15) lines(dat[[i]], col = cols[i], lwd=2)
legend("topleft", legend=paste("number",1:15), lwd=2, col=cols)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does Watir WebDriver need regex to find text unless path to tag is specified?
I have a table that is being very difficult to work with in terms of finding elements using Watir WebDriver. Here is a screen shot of the table:
In order to check the box next to "Email: " I am first searching for the email text, using .parent to go up to the tr tag, then down to the checkbox.
The tricky thing is locating the "Email: " text on the screen.
Note the following observations:
The text inside the label tag includes a space after the colon. <label for="enabledEmail17">Email: </label>
This works: browser.div(:aria_labelledby, 'ui-id-74').label(:text, 'Email:').present?
=> true
This does not work: browser.label(:text, 'Email:').present?
=> false
This does not work: browser.label(:text, 'Email: ').present?
=> false
This works but is extremely slow: browser.label(:text, /Email:/).present?
=> true
The problem is that I cannot use the parent div(:aria_labelledby, 'ui-id-74') to help locate the desired row because the ui-id number changes for each "Lessee" in my database. (For the same reason I cannot use the checkbox id enabledEmail17 or any other numbered attribute on the page.) And while using a regex will work as shown above, it takes Watir Webdriver about 2 minutes to fill out the form (vs under 10 seconds without a regex).
So the question is, why do #2 and #5 above work while #3 and #4 do not? I will add that all the other tables for the other Lessees are hidden in the HTML for this page, but given that #5 works as desired, I don't think this is the problem. Plus, I am getting false returned; the problem is not that I am finding the wrong element.
Any assistance will be greatly appreciated.
Here is a relevant portion of HTML:
<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-dialog-buttons ui-draggable ui-resizable" tabindex="-1" role="dialog" style="position: absolute; height: auto; width: 600px; top: 59px; left: 497px; display: block; z-index: 102;" aria-describedby="ttDefaultRoleDialog17" aria-labelledby="ui-id-74">
<table class="ui-widget-content po-widget-content fullWidth">
<tbody><tr>
<td class="bold ttBrandedCBTD">Branded</td>
<td class="bold">Information</td>
<td class="bold">Value</td>
</tr>
<tr>
<td class="ttBrandedCBTD"></td>
<td><label>Role: </label></td>
<td>Lessee</td>
</tr>
<tr>
<td class="center ttBrandedCBTD"><input type="checkbox" id="enabledEmail17" class="enableRoleField" data-field-class="aliasEmail"></td>
<td>
<span class="required-red required-info-toggle eo-hidden">*</span><label for="enabledEmail17">Email: </label></td>
<td>
<div id="wwgrp_email17" class="wwgrp text-left align-left">
<div id="wwctrl_email17" class="wwctrl">
<input type="email" name="roleMappings[17].email" maxlength="255" value="" id="email17" class="singleUser role-info aliasEmail addressBook ui-autocomplete-input" data-index="17" data-invalid-email="mapusers.email.valid" autocomplete="off"></div> </div>
</td>
</tr>
</tbody></table>
</div>
A:
Problem
The behaviours observed are due to the page containing multiple labels with the same text. These behaviours can be seen with the page simplified to:
<html>
<body>
<label style="display:none;">Email: </label>
<div aria-labelledby="ui-id-74">
<label>Email: </label>
</div>
</body>
</html>
Running the same examples:
browser.div(:aria_labelledby, 'ui-id-74').label(:text, 'Email:').present?
#=> true
browser.label(:text, 'Email:').present?
#=> false
browser.label(:text, 'Email: ').present?
#=> false
browser.label(:text, /Email:/).present?
#=> true
This behaviour is expected because:
For the second scenario: Watir returns the first matching element, which, in this case, is not displayed. Since the present? method checks that the element exists and is visible, false is expected.
For the third scenario: Watir normalizes the space in the text being compared against. In other words, Watir considers the label's text to actually be "Email:". This is why the element will never be found.
For the fourth scenario: When matching text against a regular expression, Watir checks against the visible text. The first label has no visible text and therefore does not get matched. As a result, you get the second label. This is a [known issue that is currently being discussed].
Solution
You need to find a way to differentiate the visible fields from the hidden fields. From the HTML, it looks like each table is displayed like a dialog, but with only one displayed at a time. I would try isolating the locating to the visible dialog.
Try:
dialog = browser.divs(:class, 'ui-dialog').find(&:visible?)
dialog.label(:text, 'Email:').present?
It looks like the dialogs might be generated by jQueryUI, which means you might be able to avoid iterating through the dialogs by inspecting the style attribute:
dialog = browser.div(:css, 'div.ui-dialog[style*="display: block;"]')
dialog.label(:text, 'Email:').present?
Note that instead of iterating from the label to the checkbox, you can use the :label locator:
dialog.checkbox(:label, 'Email:').present?
| {
"pile_set_name": "StackExchange"
} |
Q:
VS2010: run command when solution configuration changes
We're writing Python modules in C++ using Visual Studio 2010 Professional. We output Debug and Release modules in a different directory, and a configuration file for the Python part of our code determines which version is loaded.
During development in C++ I often switch between Release and Debug configurations. Sometimes I forget to update the Python config file, and then I build in Debug but the Release version is still being loaded.
What I would like is to automatically update the configuration file, so that when I switch the VS2010 Solution configuration from Release to Debug (and the other way around), the Python configuration file is automatically updated accordingly.
Update: the solution consists of roughly two dozen projects, and there is no single project that will always be built. I could use a pre-buld command, but I would have to add it to each and every project, which I'm trying to avoid.
Is this possible, and if so, how?
Kind regards,
Sybren
A:
Visual Studio has pre- and post-build events. Those give access macro's that also give you the build mode (ConfigurationName).
You could update the Python config file in the pre-build command.
Things like
if $(ConfigurationName) == Debug
are possible.
In some projects I used this in combination with batch/cmd files that take the $(ConfigurationName) as a parameter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it true that if $h\circ R_{\tau}=R_{\tau}\circ h$, then $h$ is a rotation?
Note: Every map mentioned in this problem is a homeomorphism $S^1\to S^1$.
I'm working on a problem from Katok/Hasselblatt, which is
Show that if $f$ is topologically conjugate to an irrational rotation $R_{\tau}$, then the conjugating homeomorphism is unique up to a rotation. That is, if $h_i\circ f=R_{\tau}\circ h_i$ for $i=1,2$, then $h_1\circ h_2^{-1}$ is a rotation.
Now, in the back of the book there is the following hint:
Hint: Show that $h_1\circ h_2^{-1}\circ R_{\tau}=R_{\tau}\circ h_1\circ h_2^{-1}$.
Now, this isn't difficult, because we can write by assumption
$$h_1^{-1}\circ R_{\tau}\circ h_1=f=h_2^{-1}\circ R_{\tau}\circ h_2,$$
from which rearranging gives us $h_1\circ h_2^{-1}\circ R_{\tau}=R_{\tau}\circ h_1\circ h_2^{-1}$.
Now, I have no idea how to see that $h_1\circ h_2^{-1}$ is a rotation matrix from this fact. There doesn't seem to be anything special about $h_1\circ h_2^{-1}$ here, so I guess the problem boils down to
If $h\circ R_{\tau}=R_{\tau}\circ h$, then $h$ is a rotation.
However, I don't know how to show this. I haven't used at all the fact that $\tau$ is irrational, so that must be important. But I don't know how to use that fact. Can somebody help?
A:
Hint: a conjugacy takes orbits to orbits.
And in this case all orbits are dense. So, if you start with one and then with another one, the images, say $p$ and $q$, of the two initial points of the two orbits are sufficient to determine the two conjugacies (you take the image of an orbit and the rest is obtained using densedness).
Now, $p-q$ (seen in the line) is how much you rotate from one orbit to the next, that is, $$h_1\circ h_2^{-1}=R_{p-q}.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to activate Xcode's Emulator Spotlight
After I activate the Xcode iOS emulator how can I open the Spotlight Search in the Menu so that I can see the application icon?
Thank you!
A:
On iOS7 simulator, you need to pull the home screen icons down to reveal the Spotlight search bar. On iOS6 simulator, you need to swipe right on the homescreen icons.
| {
"pile_set_name": "StackExchange"
} |
Q:
OpenOffice add entry in one index and not in another
There are two indexes in an OpenOffice document (Writter): one is for all contents and another is for only tables of document.
When I added an entry in an Index (e.g. Revision History which is above main Index) with these steps:
Select heading, which we want to add in the Index
Menu > Insert
Indexes and Tables > Entry
Select "Table of Contents" from Index dropdown menu and Insert
After that, if I update both Indexes, the entry is added to both Indexes. I don't want that entry in Index of tables but only in Index of main content.
Can anybody help please?
A:
I found a way for now. As the topic was above the main Content Index which I wanted to exclude from one Index, I followed these steps:
Right click on Index of Tables
Edit Index/Table
Create index/table for Chapter (instead of Entire Document)
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get text from span in python using scrapy?
I'm placing here HTML code :
<div class="rendering rendering_person rendering_short rendering_person_short">
<h3 class="title">
<a rel="Person" href="https://moh-it.pure.elsevier.com/en/persons/massimo-eraldo-abate" class="link person"><span>Massimo Eraldo Abate</span></a>
</h3>
<ul class="relations email">
<li class="email"><a href="[email protected]" class="link"><span>[email protected]</span></a></li>
</ul>
<p class="type"><span class="family">Person: </span>Academic</p>
</div>
From above code how to extract Massimo Eraldo Abate?
Please help me.
A:
You can extract the name using
response.xpath('//h3[@class="title"]/a/span/text()').extract_first()
Also, look at this Scrapinghub's blogpost for introduction to XPath.
| {
"pile_set_name": "StackExchange"
} |
Q:
WIX error with The document element name 'Wix' is invalid
I have multiple wxs files that are generated by heat.exe. Each file has a root element Wix, two children Fragment, and each of the Fragment elements have a DirectoryRef and ComponentGroup element respectively. Sample is hereunder:
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Fragment>
<DirectoryRef Id="ANEXMCM">
<Component Id="cmp06C5225B7EE36AAEA9ADB0AF882F1053" Guid="2924A2A0-D7A2-407E-B9B8-B40AAE1204ED">
<File Id="filABF39DC4BC6ED4474A2C2DB1C1681980" KeyPath="yes" Source="SourceDir\content.txt" />
</Component>
</DirectoryRef>
</Fragment>
<Fragment>
<ComponentGroup Id="ANEXMCM_CID">
<ComponentRef Id="cmp06C5225B7EE36AAEA9ADB0AF882F1053" />
</ComponentGroup>
</Fragment>
</Wix>
I included the files to the main WIX file as <?include wixfile.wxs?> . When I tried to build my project ( I tried on both Visual Studio and SharpDevelop, I even tried the command line), the error I get is "The document element name 'Wix' is invalid. A Windows Installer XML include file must use 'Include' as the document element name. (CNDL0048) - C:\WorkingDir\anexmcmsetup.wxs:2". I don't how to get this error fixed. I appreciate your immediate help. Thanks!
A:
I had a similar problem and it was because I wasn't implementing fragments correctly...
A good basic explanation of fragments can be found here...
http://wix.tramontana.co.hu/tutorial/upgrades-and-modularization/fragments
In my instance
In my specific scenario I had split my installer into two wxs files.
Product.wxs - main xml file)
FilesFragment.wxs - xml file containing all the files I got from heat).
Where I went wrong was that I thought I needed to have some sort of include reference in Product.wxs that would reference to FilesFragment.wxs. Similar to how you would do in a c++ project. For instance I assumed if I wanted to include a additional wxs file called wixfile.wxs in my main installation I would need some sort of
<?include wixfile.wxs?>
This was an incorrect assumption. This relationship is set up in your project file (ending with .wixproj), by virtue of having it there, it knows the file exists.
In the Product.wxs file I then needed to set up a Feature that had a ComponentGroupRef with an Id that referenced the ComponentGroup ID in my FilesFragment.wxs file.
Example of file contents...
Product.wxs file
<Feature Id="ProductFeature" Title="Setup MaxCut" Level="1">
<ComponentGroupRef Id="FilesFragment" />
</Feature>
FilesFragment.wxs file
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
<Fragment>
<DirectoryRef Id="APPLICATIONFOLDER">
<Component Id="xyz" Guid="{abc...}">
<File ... />
</Component>
...
</DirectoryRef>
</Fragment>
...
<Fragment>
<ComponentGroup Id="FilesFragment">
<ComponentRef Id="xyz" />
</ComponentGroup>
</Fragment>
This achieved what I needed. I think it is what you are trying to do as well?
| {
"pile_set_name": "StackExchange"
} |
Q:
oracle sqlplus command line question
Is there a way to detect missing command line parameters from the oracle script
for example my oracle script test.sql expects 3 parameters to run. my script is executed from the install program like this
sqlplus /NOLOG @test.sql userid pw tablespace
When one of the parameters is missing, the sqlplus prompting for the userinput. This cannot be recognized from install program. I need to find the missing param inside the script and exit with error code. Is it feasible ?
A:
I don't think there is a way to do this directly with sqlplus. You can wrap the sqlplus execution in a command/shell script that checks the parameters, then calls sqlplus with the validated parameter list.
A:
Wrapping the call to sqlplus in a shell script seems like the easiest way to do this but could you also call the script using:
sqlplus /NOLOG @test.sql <userid> <pw> <tablespace> empty empty empty
and check inside the script if any of the values are equal to "empty"? That way the script won't hang even if no parameters are passed because you'll still have the three filler parameters.
You could check using something like this: (using && instead of & means you will only be prompted for the value once)
var status number;
set verify on
whenever sqlerror exit 1;
begin
:status := 0;
select decode('&&1','empty',1,:status) into :status from dual;
select decode('&&2','empty',2,:status) into :status from dual;
select decode('&&3','empty',3,:status) into :status from dual;
IF :status != 0 THEN
RAISE_APPLICATION_ERROR (
-20000+-1*:status,'parameter '|| :status || ' is missing');
END IF;
end;
/
The return value when the inputs are invalid will be 1. Without knowing what valid values are for the parameters, it's hard to know which one was omitted.
| {
"pile_set_name": "StackExchange"
} |
Q:
PageObject "wait element" method don't work
I'm working on test automation with cucumber, selenium-webdriver and page-object gem.
When I try to run simple test cucumber catch the following error:
Scenario: Going to billing # features/test.feature:10
When I click 'Платные услуги' # features/step_definitions/test_steps.rb:13
Unable to locate element: {"method":"link text","selector":"Платные услуги"} (Selenium::WebDriver::Error::NoSuchElementError)
[remote server] file:///tmp/webdriver-profile20130412-21410-z4p1ez/extensions/[email protected]/components/driver_component.js:8405:in `FirefoxDriver.prototype.findElementInternal_'
[remote server] file:///tmp/webdriver-profile20130412-21410-z4p1ez/extensions/[email protected]/components/driver_component.js:8414:in `FirefoxDriver.prototype.findElement'
[remote server] file:///tmp/webdriver-profile20130412-21410-z4p1ez/extensions/[email protected]/components/command_processor.js:10421:in `DelayedCommand.prototype.executeInternal_/h'
[remote server] file:///tmp/webdriver-profile20130412-21410-z4p1ez/extensions/[email protected]/components/command_processor.js:10426:in `DelayedCommand.prototype.executeInternal_'
[remote server] file:///tmp/webdriver-profile20130412-21410-z4p1ez/extensions/[email protected]/components/command_processor.js:10366:in `DelayedCommand.prototype.execute/<'
./features/pages/job_main_page.rb:38:in `go_to_billing'
./features/step_definitions/test_steps.rb:14:in `/^I click 'Платные услуги'$/'
features/test.feature:11:in `When I click 'Платные услуги''
Here is the cucumber feature:
Scenario: Going to billing
When I click 'Платные услуги'
Then I should see "Коммерческие услуги"
Step definition where test falls:
When(/^I go to billing$/) do
@job_myroom_billing = @job_myroom.billing_element.when_visible.go_to_billing
end
And page object:
class BasePage
include PageObject
include RSpec::Matchers
end
class JobMyroom < BasePage
link :billing, link: 'Платные услуги'
def go_to_billing
billing
JobMyroomBilling.new @browser
end
end
class JobMyroomBilling < JobMyroom
#some code
end
Whats wrong? Driver don't wait the element's presence
A:
I think Sheg is giving some good advice here although I would tend to do it slightly different:
wait_until do
billing_element.visible?
end
Another thing you can do that is very similar is to replace the code in your method with this:
def go_to_billing
billing_element.when_present.click
JobMyroomBilling.new @browser
end
In this case we are waiting until the link is present and when it is the when_present method returns the element and we simply click on it.
Another thing I might suggest is using watir-webdriver as the driver instead of selenium-webdriver. watir-webdriver is built on top of selenium-webdriver but seems the have far better handling of waiting for items to actually be loaded on the DOM. If your link is being added dynamically using Ajax then you will have to write some code to wait until it is there before actually interacting with it. The only thing you will have to do to use the other gem is change the code in your Before block to this:
Before do
@browser = Watir::Browser.new :firefox
end
Another pointer I would give you is to not have one page object return an instance of the next page object. I am eating my own words here because a few years ago this is how I did it but I have found over time that this is a brittle approach. Instead, I would use the PageObject::PageFactory to manage the creation of the correct pages and when you have a step that is a generic step you can simply use the @current_page instance variable.
The last pointer I will give you is to remove the assertions from your page object. I would have the page object simply provide the abstraction and perform all verification in the step definitions. This is a much cleaner separation of concerns and will make maintaining your tests easier over time.
| {
"pile_set_name": "StackExchange"
} |
Q:
IReliableReadWriteDocumentClient is missing PartitionResolver in Document DB
When returned DocumentClient AsReliable, it doesn't have PartitionResolvers. Any way to get around this?
var documentClient = new DocumentClient(new Uri(endPointUrl), authorizationKey);
var documentRetryStrategy = new DocumentDbRetryStrategy(RetryStrategy.DefaultExponential) { FastFirstRetry = true };
return documentClient.AsReliable(documentRetryStrategy);
A:
The IReliableReadWriteDocumentClient implementation that you get from .AsReliable(..) is just a wrapper around the original DocumentClient, which executes every method of the original (underlying) client in a retry block by using provided retry strategy. No magic. Built-in DocumentDbRetryStrategy is design to eliminate majority of the transient network/service/throttling issues.
Answering your initial question - you can either set PartitionResolvers on the original client before wrapping it with .AsReliable(..) or you can access the collection later through UnderlyingClient property. UnderlyingClient property holds the same instance that was passed to the .AsReliable(..) extension method.
Regarding best practices around using DocumentClient vs IReliableReadWriteDocumentClient: if you need to have more reliable communication between the client and the server, that will automatically retry on transient failures described above - then you should consider using .AsReliable(..). If your scenario does not require all documents to be persisted in the storage (in case of a logging/trace, for example) and you will "swallow" all exceptions anyway - then there is nothing wrong with using DocumentClient directly to reduce the time spent in additional retries.
A:
You can access the underlying DocumentClient object to register the PartitionResolvers.
| {
"pile_set_name": "StackExchange"
} |
Q:
scope of do-catch in swift - cannot assign value to outside variable
I have made some code to make POST request to my php script which is placed on my servers. I have tested and that part is working fine. I got the problem with the returning result from the server - I get it in JSON format, and print in inside do-catch statement - its OK. I assign the returning variable to variable which is declared outside of the do-catch and its not "visible". Let me show my code, it will be more simplier to explain when you see the code:
//sending inputs to server and receiving info from server
let json:[String:AnyObject] = [ "username" : username!, "password" : password!, "iphone" : "1" ]
var link = "http://www.pnc.hr/rfid/login.php"
var novi:String = ""
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
// create post request
let url = NSURL(string: link)!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
// insert json data to the request
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error 55 -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("FIRST PRINT -> \(result!["password"])")
novi = String(result!["password"])
//return result
} catch {
print("Error 43-> \(error)")
}
}
task.resume()
}
catch {
//handle error. Probably return or mark function as throws
print(error)
}
print("SECOND PRINT -> \(novi)")
If you see print("FIRST PRINT -> \(result!["password"])") - it executes normally and output all the variables. Then if you see print("SECOND PRINT -> \(novi)") at the end of the code it outputs empty sting - like I haven't assigned variable to it.
A:
You are using an asynchronous block. The print statement will get run before your block has a chance to set novi.
This issue is not a problem with do-catch it is a asynchronous issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remote autocomplete query
I'm new in Angular and try to make a autocomplete form with content filtered in back-end. I have class and Interface for Terminal:
export class Terminal {
constructor(
public id: number,
public name: string,
public city: string,
public country: string) {}
}
export interface ITermianlResponse {
results: Terminal[];
Then I have a Service:
@Injectable()
export class Service {
constructor(private http: HttpClient) {}
search(value): Observable<ITermianlResponse> {
return this.http.get<ITermianlResponse>('http://127.0.0.1:8000/api/v1/public/terminal_ac/?q=' + value)
.pipe(
tap((response: ITermianlResponse) => {
response.results = response.results
.map(terminal => new Terminal(terminal.id, terminal.name, terminal.city, terminal.country))
return response;
})
);
}
}
Back-end side receive my request and give an answer, as for Shan:
{"results": [{"id": "1", "name": "Shanghai Terminal", "city": "Shanghai", "country": "China"}], "pagination": {"more": false}}
My component is below:
export class SearchComponent implements OnInit {
filteredTerminals: ITermianlResponse;
terminalsForm: FormGroup;
constructor(private fb: FormBuilder, private Service: Service) {}
ngOnInit() {
this.terminalsForm = this.fb.group({
terminalInput: null
})
this.terminalsForm.get('terminalInput').valueChanges
.pipe(
debounceTime(300),
switchMap(value => this.Service.search(value)),
).subscribe(result => this.filteredTerminals = result);
}
displayFn(terminal: Terminal) {
if (terminal) { return terminal.name; }
}
}
And finally my html:
<form class="example-form" [formGroup]='terminalsForm'>
<mat-form-field class="example-full-width">
<input matInput placeholder="Choose a terminal" [matAutocomplete]="auto" formControlName='terminalInput'>
</mat-form-field>
<span>Your choice is: {{terminalsForm.get('terminalInput').value | json}}</span>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let terminal of (filteredTerminals | async)?.results" [value]="terminal">
<span>{{ terminal.name }}</span>
<small> | ID: {{terminal.id}}</small>
</mat-option>
</mat-autocomplete>
</form>
As I said back-end receives my request, but browser console raise and error SearchComponent.html:9 ERROR Error: InvalidPipeArgument:. What am I doing wrong? Thanks!
A:
Like I wrote down,
your problem was in the async pipe you used in
let terminal of (filteredTerminals | async)?.results
and of-course its because the filteredTerminals
are not observable or promise.
| {
"pile_set_name": "StackExchange"
} |
Q:
Plot a graph point to point python
I wonder if there is some way to plot a waveform point to point at a certain rate through the matplotlib so that the graph appears slowly in the window. Or another method to graph appears at a certain speed in the window and not all the points simultaneously. I've been tried this but I can only plot a section of points at a time
import numpy as np
import matplotlib.pyplot as plt
import time
x = np.arange(0,5,0.001)
y = np.sin(2*np.pi*x)
ind_i = 0
ind_f = 300
while ind_f <= len(x):
xtemp = x[ind_i:ind_f]
ytemp = y[ind_i:ind_f]
plt.hold(True)
plt.plot(xtemp,ytemp)
plt.show()
time.sleep(1)
ind_i = ind_f
ind_f = ind_f + 300
A:
You can also do this with Matplotlib's FuncAnimation function. Adapting one of the matplotlib examples:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.arange(0,5,0.001)
y = np.sin(2*np.pi*x)
def update_line(num, data, line):
line.set_data(data[..., :num])
return line,
fig = plt.figure()
data = np.vstack((x,y))
l, = plt.plot([], [], 'r-')
plt.xlim(0, 5)
plt.ylim(-1, 1)
line_ani = animation.FuncAnimation(fig, update_line, frames=1000,
fargs=(data, l), interval=20, blit=False)
plt.show()
| {
"pile_set_name": "StackExchange"
} |
Q:
How to serve static files with apache on openshift official python cartridge?
I have scalable openshift online app with official python-2.7 cartridge. By default everything is served with mod_wsgi handler. How do I configure my app and/or Apache to serve some static files in my repo (like images, css and javascript) with Apache instead of python backend?
A:
Just figured it out by examining the cartridge source. Files in $OPENSHIFT_REPO_DIR/wsgi/static folder are served by Apache directly. Its completely undocumented though, and may break in the future.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding a new folder/item does not appear in target DB when published via workflow
Added a new folder and item in it with WorkFlow and published it via workflow, but it doesn't appear in the next level db. Any thoughts
Master db:
Preview db: missing the test folder and content
A:
By default sitecore workflow doesnt publish the parent folder. We need to first publish the folder and then the WF Item.
As its not a good practice to have WF to the folder, we have written a method which is triggered in the sitecore publish event(publish:itemProcessed), so whenever an item is published this method checks to see if the item exists in the next environment and the folder path matches, if in any of those cases fail this method will go ahead and publish the folder or move the file path accordingly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Array Access of Object Javascript
In coffee script i have this little code snippet.
class Collection
construct:(@collection=[])
Now i want to access that object as if it was an array but i want to get the collection variable when i do so. In other languages i would implements an ArrayAccess of some type and code the next, current etc methods
obj= new Collection([1,2,3])
obj[0] # this should equal 1
How can i do this in javascript or coffeescript either will do
A:
That's impossible. You would need some kind of proxy for that. There is no "ArrayAccess" declaration feature, as bracket notation is just property access on your Collection instance (like obj["collection"]).
Instead, you can:
implement a getter function, like
class Collection
construct:(@collection=[])
at: (i) ->
@collection[i]
obj.at 0 # 1
use the Collection object itself as a holder of the elements (like e.g. jQuery does it). You loose the native array features, though. You might even subclass Array to some extent (.length does not update automatically).
class Collection
constructor: (col = []) ->
@length = 0
for el in col
Array::push.call(@, el)
obj[0] # 1
| {
"pile_set_name": "StackExchange"
} |
Q:
Pass user input from C to Assembler
I am new to ARM Assembler. Using qemu emulator.
This solution didn't work for me.
I have this C file md1_main.c:
#include <stdio.h>
#include <stdlib.h>
#include "md1.h"
int main (void)
{
int n;
scanf("%d", &n);
printf("Result = %u\n", asum(n));
return 0;
}
and .h file contains function prototype unsigned int asum(unsigned int n);
I am really confused, how to pass n into the assembler code.
Assembler code is md1.s:
.text
.align 2
.global asum
.type asum, %function
asum:
mov r1, #0
mov r2, #1
loop:
cmp r2, #3 ; instead of 3 there should be my input
bgt end
add r1, r1, r2
add r2, r2, #1
b loop
end:
mov r0, r1
bx lr
Just can't get it.
A:
OP has mentioned the architecture as ARM 64. So I will answer according the calling convention.
The first 4 arguments are passed in r0, r1, r2, r3.
That is what the compiler will also do for you when compiling the C file. So you can expect your parameter n in the r0 register and you can directly use it.
I also see that your function returns an unsigned value. That will be returned in the r0 register.
See this, for a more detailed description of the calling convention.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to transform text with characters to HTML Entities with Ruby on Rails?
I Want to use an URL to call a method but i need it to be written with HTML Entities:
so if i have http://www.myurl.com/foobar for example using a Ruby on Rails helper i can get something like:
http%3A%2F%2Fwww.myurl.com%2Ffoobar
A:
I don't know if there's anything built directly into rails to do all of that escaping, but if you require 'cgi' you can use CGI::escape.
ruby-1.8.7-p174 :001 > require 'cgi'
=> true
ruby-1.8.7-p174 :002 > s = "http://www.myurl.com/foobar"
=> "http://www.myurl.com/foobar"
ruby-1.8.7-p174 :003 > CGI::escape(s)
=> "http%3A%2F%2Fwww.myurl.com%2Ffoobar"
Obviously, to make it look a little nicer in your views, or wherever, you could wrap that method in a helper.
| {
"pile_set_name": "StackExchange"
} |
Q:
Conditional property in wix script
I used the below property so i could avoid the add or remove option in the control panel
<Property Id="ARPSYSTEMCOMPONENT" Value="1" />
But i need to make it dynamic .I want to read the value in the registry. If a value mathes my condition i will include this orelse i wont include this line my partial code is as follows
<Property Id="NETFRAMEWORK20">
<RegistrySearch Id="NetFramework20"
Root="HKLM"
Key="Software\Microsoft\NET Framework Setup\NDP\v2.0.50727"
Name="Install"
Type="raw" />
</Property>
//Some Conditon
<Condition Message="I will create the Add or remove option since the softwar i look for s not present">
<![CDATA[Installed OR NETFRAMEWORK20]]>
</Condition>
<Property Id="ARPSYSTEMCOMPONENT" Value="1" />
//or else
Thank in Advance
A:
Try sing SetProperty. Means, instead of:
<Property Id="ARPSYSTEMCOMPONENT" Value="1" />
try:
<SetProperty Id="ARPSYSTEMCOMPONENT" After="InstallInitialize" Value="1">
<![CDATA[~~~CONDITION~~~]]>
</SetProperty>
As a side note, I would recommend first, not to hide staff you install from add/remove, and second, use standard .NET framework extension for checking if .NET framework is installed instead of inventing your own method with registry search.
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove Queued Bulk Actions
I'm using 2.3.2 and having the issue outlined in this post:
Magento 2 Bulk Actions not Starting
And now I'm needing to remove the "Not Started" actions from the queue (as listed in the Bulk Actions Log). How would I accomplish this safely?
(edit: I did implement the fix from the linked thread, and it seemed to be successful, but seemed to be blocked by other bulk actions in the queue that haven't started)
A:
Delete the records you want to remove via the database directly in the magento_bulk table.
If you want to delete records of bulk operations that have already be execute you'd do the same with the magento_acknowledged_bulk table.
| {
"pile_set_name": "StackExchange"
} |
Q:
Online poker game in Java
I have to implement a multiplayer poker game which can play only by two players. I have to use java. And it should be a online game. What i want want to know is how to communicate between these two players. I mean what kind of methods and technologies i have to refer ? Can someone please help me.
A:
I think of a server and two client apps. That requires knowledge about sockets, serversockets. Basically a socket is a connection, you use it to communicate with server.
There is a good explanation of sockets in the Java Head First 2nd edition book, there you are taught to make something similar to a chat app.
You need a server socket on your server, that listens for connections(you will need threading there), and a socket on your client, via which you send messages to the server.
| {
"pile_set_name": "StackExchange"
} |
Q:
value <= maximum
I wonder, is it possible to achieve similar using bit operations:
if a > maximum: a = maximum
Where 'maximum' can be a random number?
Have many similar lines in my current code. Of course could have used:
def foo(a, max=512): return a if a<max else max
Just curious if there's a more elegant and efficient way.
A:
There's no need to define your own function for this, min and max are already built-in:
a = min(maximum, a)
As per Raymond's answer, it is also possible to use bit operations:
a = maximum ^ ((a ^ maximum) & -(a < maximum))
But in the vast majority of cases, the performance benefit isn't really worth making the code very hard to understand. Also, this only works for integers, whereas the min function can be used for all comparable types.
| {
"pile_set_name": "StackExchange"
} |
Q:
Node: Callback was already called
I know that here are few duplicate questions about this. However, I don't know how to solve this problem. My code is this:
/**
* DEFINE
* @connection_kill
*/
apiRoutes.post('/balancer_connection_drop', function(req, res) {
/* BALANCER - connection kill */
async.auto({
decrypt_kill: function(callback, drop, user, stream) {
/* DROP - decrypt */
try {
/* DEFINE - drop */
var drop = JSON.parse(decrypt(Object.keys(req.body)[0], encryption));
/* DROP - user & stream */
callback(null, drop['drop'], drop['user'], drop['stream']);
} catch(s) {
/* CLOSE - connection */
res.end();
}
},
remove_connection: ['decrypt_kill', function(results, callback) {
/* DROP - balancer || user & stream */
if ((results[Object.keys(results)[0]])[0] !== 'null') {
/* DROP - balancer users */
if (results[Object.keys(results)[0]][0] == 'balancer') {
console.log('callback users...');
/* DROP - balancer users */
pool.query('UPDATE live SET remove=?',[1], function(err, results) {
/* DROP - failed */
if (err) return callback('Could NOT Drop Users From Live Table!');
})
} else {
console.log('callback user...');
/* DROP - balancer user */
pool.query('UPDATE live SET remove=? WHERE user=? AND stream=?',[1, results[Object.keys(results)[0]][1], results[Object.keys(results)[0]][2]], function(err, results) {
/* DROP - failed */
if (err) return callback('Could NOT Drop Users From Live Table!');
})
}
} else {
console.log('failed to kill data empty...');
return callback('Balancer Connection Kill Data Empty!');
}
console.log('callback...');
callback();
}]
}, function(err, results) {
/* CHECK - error */
if (err) return res.send(encrypt(JSON.stringify({'status': 'false'}), encryption));
/* DROP - success */
res.send(encrypt(JSON.stringify({'status': 'true'}), encryption));
/* END - connection */
res.end();
})
})
Now when I call this api C get this error from node:
Callback was already called
So I put in code console.log to see what is twice called and I get this from console.log before it throws error that is twice called:
callback user...
callback...
So I see that I made mistake that I call it twice but I don't know how to rewrite above code to work as it should be so when callback user... is called. I need to go to
function(err, results) {
function and in that function return json to my server api, but I don't know how to rewrite it. I try using this code above to move callback outside functions but then callback is never called.
A:
You make a callback after you handle err in pool.query
The problem is that pool.query is an async task and node jumps over
that async task after pushing it to libuv
it reaches the last callback() before pool.query callback function;
the last callback is called after your code reaches
pool.query callback function
apiRoutes.post('/balancer_connection_drop', function(req, res) {
/* BALANCER - connection kill /
async.auto({
decrypt_kill: function(callback, drop, user, stream) {
/ DROP - decrypt /
try {
/ DEFINE - drop */
var drop = JSON.parse(decrypt(Object.keys(req.body)[0], encryption));
/* DROP - user & stream */
callback(null, drop['drop'], drop['user'], drop['stream']);
} catch(s) {
/* CLOSE - connection */
res.end();
}
},
remove_connection: ['decrypt_kill', function(results, callback) {
/* DROP - balancer || user & stream */
if ((results[Object.keys(results)[0]])[0] !== 'null') {
/* DROP - balancer users */
if (results[Object.keys(results)[0]][0] == 'balancer') {
console.log('callback users...');
/* DROP - balancer users */
pool.query('UPDATE live SET remove=?',[1], function(err, results) {
/* DROP - failed */
if (err){ return callback('Could NOT Drop Users From Live Table!');}
return callback();
})
} else {
console.log('callback user...');
/* DROP - balancer user */
pool.query('UPDATE live SET remove=? WHERE user=? AND stream=?',[1, results[Object.keys(results)[0]][1], results[Object.keys(results)[0]][2]], function(err, results) {
/* DROP - failed */
if (err){ return callback('Could NOT Drop Users From Live Table!');}
return callback();
})
}
} else {
console.log('failed to kill data empty...');
return callback('Balancer Connection Kill Data Empty!');
}
}]
}, function(err, results) {
/* CHECK - error /
if (err) return res.send(encrypt(JSON.stringify({'status': 'false'}), encryption));
/ DROP - success /
res.send(encrypt(JSON.stringify({'status': 'true'}), encryption));
/ END - connection */
res.end();
})
})
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the meaning of SVM model train output in libSVM
I am conducting a small experiment to figure out how actually SVMs works rather than just messy mathematical equations
Now i searched google and found out several parameters but i am still not sure with few of them
The top output is like this below
svm_type c_svc
kernel_type linear
nr_class 2
total_sv 417
rho -0.215616
label 1 2
nr_sv 222 195
SV
I know the meaning of them except rho. For what task it is used for? Like it is a threshold and if the predicted value lesser than that class 2 or something? or it is the b static parameter in the original formula?
Also i want to learn especially this parameter
For first class
1.015964637640586(?) 1:0.24665231 4:0.14476547 15:0.20357756 16:0.18792053 17:0.24857121 56:0.08635193 130:0.29008309 192:0.3327738 205:0.1299556 538:0.3327738 819:0.40555177 1166:0.24665231 1484:0.23615943 2382:0.4106203
1.855735328446067(?) 76:0.1757074 108:0.26389822 547:0.26088058 648:0.26916638 765:0.87119196
For the second class
-0.1420833389096254(?) 1:0.06239991 29:0.021063915 47:0.028132803 316:0.057096583 999:0.069383082 1379:0.075283916 1530:0.081629601 1724:0.98528953 1917:0.060585087
-2.331507968370806(?) 4:0.18457891 33:0.15922398 150:0.17287198 291:0.21749933 324:0.38461278 349:0.25831757 397:0.26342762 398:0.37451304 483:0.36544162 680:0.30979207 1122:0.33032278 1328:0.31693334
What are those first parameters? For what task they are being used?
I did put ? at the end of first parameters
The other parameters are attributes and their values
So when we do prediction, the attribute weights are multiplied with each one of the SVs and summed
Then how is the final class decision is made?
Thank you
A:
This is the SVM formula from wikipedia:
rho is equal to -b.
The number in front of the support vectors is the coefficient. This is the weight with which the dot product of the support vector and the input vector is multiplied with. In the formula this is the combination of c and y.
After the weighted dot products are summed up and rho has been subtracted the decision is made by looking at the sign of this computed score. If it is positive it is the first class, if it is negative it is the second class.
| {
"pile_set_name": "StackExchange"
} |
Q:
USB permission obtained via android.hardware.usb does not apply to NDK
I was able to obtain a permission to communicate with a device via Android's USB Host API.
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
protected void execute(Context ctxt) {
UsbManager manager = (UsbManager) viewer.getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
UsbDevice d = null;
for (String s : deviceList.keySet()) {
d = deviceList.get(s);
}
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(ctxt, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
viewer.registerReceiver(mUsbReceiver, filter);
manager.requestPermission(d, mPermissionIntent);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
Log.d(TAG, "Permission granted!");
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
Unfortunately that doesn't give my NDK code permission to directly communicate with this device (which is needed for libusb). Is there any way to "transfer" the permissions from Java to NDK without root?
P.S.
I ended up using UNIX sockets to transfer the original File Descirptor from Java to an Android native executable (I have GNU-ed the project at https://github.com/martinmarinov/rtl_tcp_andro- ).
For some people it would be even easier since they might be using NDK to connect with the device directly (not a third party app) and therefore the pointer that they use in Java may be still accessible by the NDK without having to mess around with UNIX sockets.
A:
There is no "transfer" of permissions possible because the Android security model demands that each application statically declare its required permissions and the user approves the permission set at install time. No dynamic permissions are supported. Each app maps to a single UID, with its statically declared permissions in the manifest. Java is not a permission boundary, and the Dalvik VM is no barrier to running native code via NDK. All the permissions must be listed in the manifest, and the apk may contain no Java (dex) code at all.
http://developer.android.com/guide/topics/security/permissions.html
http://osdir.com/ml/android-ndk/2012-09/msg00094.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Android Fragments : Inheritance vs Composition
In short, I'm trying to wrap a fragment inside a wrapper class, and then add the wrapper to the view pager. I'm having trouble with null pointers later on in the running of the app with this (as opposed to inheriting from the fragment, and adding the inherited fragment to the viewpager).
Description
Basically, I'm adding fragments to a viewpager, and before adding the fragment, I've been inheriting from it, and wrapping it in another view that adds a boarder around it (page splits).
Each page/fragment is a distinct class that represents the view to be displayed.
The problem with this approach is that I need to extend each fragment and add the same boilerplate functionality, which isn't ideal. I also don't want to make a baseclass, say "boardered-fragment" because then the fragments then be aware of the boarder when they derive from it (i think).
So, I figured that maybe I would just use composition, where I would make a generic wrapper class, that would contain a fragment data member typed as T. The problem with this is that I can't seem to get the current activities "activity" reference into the context of the fragment data member (composed in the wrapper).
I did some ad-hoc tweaking and hid the getActivity() that returns a copy of the activity reference I manually store. However the program crash's randomly (as I suspected it would). I've tried overriding all possible lifetime methods in my wrapper, and then inside would call that lifetime method on the data-member fragment
public override void OnSomething()
{
base.OnSomething()
mFragment.OnSomething()
}
but that doesn't seem to help. I'm guessing that because the composed fragment is "hidden" from the current activities context, that I'm going to need to do all necessary operation manually. I'm just not sure what they all are ?
Here is a quick code example of what I'm trying to accomplish, and the elaboration is below. Please let me know if more code is needed, and I will adapt what I have into an example format.
Composition (having many issues/null pointers throughout app)
public class Frag1 : Fragment
{
...
}
public class Activity1 : Activity
{
public override void OnCreate(Bundle bundle)
{
...
List<Fragment> fragments = new List<Fragment>();
fragments.Add(FragmentWrapper.NewInstance(Activity, typeof(FragmentWrapper))
MyAdapter pagerAdapter = new MyAdapter(FragmentManager, fragments);
ViewPager viewPager = FindViewById<ViewPager>(Resource.Id.view_pager);
viewPager.Adapter = pagerAdapter;
}
public class FragmentWrapper
{
Fragment mFragment; // How to successfully wrap a fragment, but still behave properly ????
public static FragmentWrapper NewInstance(Activity activity, string type)
{
FragmentWrapper thisFrag = new FragmentWrapper();
...
thisFrag.mFragment = Fragment.Instantiate(activity, type);
return thisFrag;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle)
{
// add boarder around mFragment and return new view
}
}
public class MyAdapter : Android.Support.V13.App.FragmentStatePagerAdapter
{
....
}
}
Inheritance (can do, ok)
public class Frag1 : Fragment
{
...
}
public class Activity1 : Activity
{
public override void OnCreate(Bundle bundle)
{
...
List<Fragment> fragments = new List<Fragment>();
fragments.Add(FragmentExtender.NewInstance(Activity, typeof(FragmentExtender))
MyAdapter pagerAdapter = new MyAdapter(FragmentManager, fragments);
ViewPager viewPager = FindViewById<ViewPager>(Resource.Id.view_pager);
viewPager.Adapter = pagerAdapter;
}
public class FragmentExtender : Frag1
{
public static FragmentExtender NewInstance()
{
FragmentExtender thisFrag = new FragmentExtender();
...
return thisFrag;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle)
{
// add boarder around mFragment and return new view
}
}
public class MyAdapter : Android.Support.V13.App.FragmentStatePagerAdapter
{
....
}
}
Any help with this is much appreciated. Thanks.
A:
If all you want is add a border between the fragments then you should check out ViewPager.setPageMargin() and ViewPager.setPageMarginDrawable().
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP Restart Lighttpd doesn't return
I have a php script which needs to restart lighttpd. The php page never returns to the client. I believe that is because the call doesn't return. Here is my code:
<?php
exec("/etc/init.d/lighttpd restart");
echo "Restarted!";
?>
If I comment out the exec line it returns as expected.
How can I get this call to return?
Thanks,
EV
A:
If you restart you httpd process your scripts will be terminated, no matter what you do!
You will never make any scripts to return a value directly from PHP. To make that work you should add a javascript and check for a 200 Status Code.
| {
"pile_set_name": "StackExchange"
} |
Q:
Modify req.user or use req.account?
I'm developing a mean application with passport, and I'm running through this issue:
I have a LocalStrategy to log on the user based on the application database. I need, however to login the user simultaneously on another service with possible multiple accounts. The thing is, once I route to authorize these logins, and set the variables to req.account, I cannot access them in other routes. Note that I can get the data I want, I just want to access it from somewhere other than this route, like req.user. I will post some of my code to clarify the situation.
Local Login route
app.post('/login', function (req, res, next) {
passport.authenticate('local-login', function (err, user) {
if (err)
return next(err);
if (!user)
return res.status(400).json({status: 'Invalid Username'});
req.login(user, function (err) {
if (err)
return next(err);
res.status(200).json({status: 'User successfully authenticated'});
});
})(req, res, next);
});
Local login passport config
passport.use('local-login', new LocalStrategy(function (user, pswd, done) {
User.findOne({'username': user}, function (err, user) {
if (err)
return done(err);
if (!user || !user.validPassword(pswd))
return done(null, false);
return done(null, user);
});
}));
The other service passport config
passport.use('other-login', new OtherStrategy(function (docs, done) {
if (docs.length === 0)
return done(null, false);
var accounts = [];
var user, pswd, data;
var counter = docs.length;
for (var i = 0; i < docs.length; i++) {
user = docs[i]._id;
pswd = docs[i].password;
request.post(<serviceurl>, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: qs.stringify({
grant_type: 'password',
username: user,
password: pswd,
client_id: process.env.API_KEY
})
}, function (err, res, body) {
if (err)
return done(err);
data = JSON.parse(body);
data.username = docs[docs.length - counter]._id;
accounts.push(data);
counter--;
if (counter === 0)
return done(null, accounts);
});
}
}));
Other Service route
router.get('/otherservice', passport.authorize('other-login', {}) , function (req, res) {
console.log(req.account);
res.sendStatus(200);
});
Other Service authentication (from custom Strategy)
ServiceStrategy.prototype.authenticate = function (req) {
var self = this;
var id = req.user.master_id || req.user.id;
Service.find({master_id: id}, function (err, docs){
if (err)
return self.error(err);
function verified(err, data, info) {
if (err) { return self.error(err); }
if (!data) { return self.fail(info); }
self.success(data, info);
}
try {
if (self._passReqToCallback) {
self._verify(req, docs, verified);
} else {
self._verify(docs, verified);
}
} catch (ex) {
return self.error(ex);
}
});};
A:
I found the solution! On the User Model, I added an accounts property to store the data returned on the authorization. Then, on the authorization route, I updated the user with this info, and saved. It wasn't that hard at all.
app.post('/api/login', function (req, res, next) {
passport.authenticate('local-login', function (err, user) {
if (err)
return next(err);
if (!user)
return res.status(400).json({status: 'Invalid Username'});
req.login(user, function (err) {
if (err)
return next(err);
var id = req.user.master_id || req.user.id;
Service.findOne({master_id: id}, function (err, doc) {
if (doc == null)
res.status(200).json({
status: 'User successfully authenticated',
accounts: false
});
else
return next();
});
});
})(req, res, next);
}, passport.authorize('other-login', {}), function (req, res) {
var accounts = req.account;
var user = req.user;
user.accounts = accounts;
user.save(function (err, newUser) {
if (err)
throw err;
res.status(200).json({
status: 'User sucessfully authenticated',
accounts: true
});
})
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Looping through a text file using islice
I want to read the lines of a text file multiple times using islice. The aim is to try, every time, to get the lines which contain an index contained in a list and, later write the file containing these lines only. I tried the following script but I realized (by printing the row numbers) that the program read the file once only despite my for loop. Why?
with open(input,'r') as inp,:
sliced_file = islice(inp,None)
for ind in listOfInd:
print('ind ' + ind)
for line_number, line in enumerate(sliced_file,start=1):
print(line_number)
number, rest = line.split('\t',1)
A:
The first time the enumerate function is called on sliced_file iterator object, end of file will be reached. So next time for it to iterate through the file again, the file pointer has to be reset to the start of the file.
Also in your snippet, flow control moves out of the with block, the file will be closed and won't be available for reading.
Here is a fixed code.
inp = open(input,'r')
sliced_file = islice(inp,None)
for ind in listOfInd:
print('ind ' + ind)
for line_number, line in enumerate(sliced_file,start=1):
print(line_number)
number, rest = line.split('\t',1)
inp.seek(0)
| {
"pile_set_name": "StackExchange"
} |
Q:
#load "unix.cma" causes syntax error
I'm trying to compile / run in interpreter a program written by another programmer. This program uses this construct:
#load "unix.cma"
which I haven't encountered before. I've found this page: http://ocamlunix.forge.ocamlcore.org/generalities.html which mentions it, but typing this code into interpreter results in syntax error. Same thing happens when I run the file with this instruction through ocamlc. What am I missing?
ocamlc -v
The Objective Caml compiler, version 3.12.1
Standard library directory: /usr/lib64/ocaml
A:
#load is a toplevel directive, which is not available in ocamlc nor ocamlopt compilers but only in OCaml toplevel (REPL) ocaml. See http://caml.inria.fr/pub/docs/manual-ocaml/manual023.html#toc91. Use the toplevel to run the program:
ocaml blahblah.ml
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i create a String object from literal in Java ? e.g. string with special characters
how can i create a String object from literal ? e.g. i have
String s = " `<div id="top_bin">` ";
this gives an error syntax error on token
A:
You have to escape the quotes used inside the String. Use \" for that:
String s = " <div id=\"top_bin\"> ";
^ ^
| {
"pile_set_name": "StackExchange"
} |
Q:
System Account Logon Failures every 30 seconds
We have two Windows 2008 R2 SP1 servers running in a SQL failover cluster. On one of them we are getting the following events in the security log every 30 seconds. The parts that are blank are actually blank. Has anyone seen similar issues, or assist in tracking down the cause of these events? No other event logs show anything relevant that I can tell.
Log Name: Security
Source: Microsoft-Windows-Security-Auditing
Date: 10/17/2012 10:02:04 PM
Event ID: 4625
Task Category: Logon
Level: Information
Keywords: Audit Failure
User: N/A
Computer: SERVERNAME.domainname.local
Description:
An account failed to log on.
Subject:
Security ID: SYSTEM
Account Name: SERVERNAME$
Account Domain: DOMAINNAME
Logon ID: 0x3e7
Logon Type: 3
Account For Which Logon Failed:
Security ID: NULL SID
Account Name:
Account Domain:
Failure Information:
Failure Reason: Unknown user name or bad password.
Status: 0xc000006d
Sub Status: 0xc0000064
Process Information:
Caller Process ID: 0x238
Caller Process Name: C:\Windows\System32\lsass.exe
Network Information:
Workstation Name: SERVERNAME
Source Network Address: -
Source Port: -
Detailed Authentication Information:
Logon Process: Schannel
Authentication Package: Kerberos
Transited Services: -
Package Name (NTLM only): -
Key Length: 0
Second event which follows every one of the above events
Log Name: Security
Source: Microsoft-Windows-Security-Auditing
Date: 10/17/2012 10:02:04 PM
Event ID: 4625
Task Category: Logon
Level: Information
Keywords: Audit Failure
User: N/A
Computer: SERVERNAME.domainname.local
Description:
An account failed to log on.
Subject:
Security ID: NULL SID
Account Name: -
Account Domain: -
Logon ID: 0x0
Logon Type: 3
Account For Which Logon Failed:
Security ID: NULL SID
Account Name:
Account Domain:
Failure Information:
Failure Reason: An Error occured during Logon.
Status: 0xc000006d
Sub Status: 0x80090325
Process Information:
Caller Process ID: 0x0
Caller Process Name: -
Network Information:
Workstation Name: -
Source Network Address: -
Source Port: -
Detailed Authentication Information:
Logon Process: Schannel
Authentication Package: Microsoft Unified Security Protocol Provider
Transited Services: -
Package Name (NTLM only): -
Key Length: 0
EDIT UPDATE: I have a bit more information to add. I installed Network Monitor on this machine and did a filter for Kerberos traffic and found the following which corresponds to the timestamps in the security audit log.
A Kerberos AS_Request Cname: CN=SQLInstanceName Realm:domain.local Sname krbtgt/domain.local
Reply from DC: KRB_ERROR: KDC_ERR_C_PRINCIPAL_UNKOWN
I then checked the security audit logs of the DC which responded and found the following:
A Kerberos authentication ticket (TGT) was requested.
Account Information:
Account Name: X509N:<S>CN=SQLInstanceName
Supplied Realm Name: domain.local
User ID: NULL SID
Service Information:
Service Name: krbtgt/domain.local
Service ID: NULL SID
Network Information:
Client Address: ::ffff:10.240.42.101
Client Port: 58207
Additional Information:
Ticket Options: 0x40810010
Result Code: 0x6
Ticket Encryption Type: 0xffffffff
Pre-Authentication Type: -
Certificate Information:
Certificate Issuer Name:
Certificate Serial Number:
Certificate Thumbprint:
So appears to be related to a certificate installed on the SQL machine, still dont have any clue why or whats wrong with said certificate. It's not expired etc.
A:
I used Microsoft Network Monitor to find the traffic causing this and found traffic between this SQL server and our AD2 server. The SQL server was sending a Kerberos AS_REQ for the computer account of the SQL Instance Name. The AD server would respond with a KDC_ERR_C_PRINCIPAL_UNKNOWN. I looked at the security logs on the AD2 server and discovered failure audits like the following:
A Kerberos authentication ticket (TGT) was requested.
Account Information:
Account Name: X509N:<S>CN=SQLInstanceName
Supplied Realm Name: domain.local
User ID: NULL SID
Service Information:
Service Name: krbtgt/domain.local
Service ID: NULL SID
Which seems to be some certificate request. I then used SysInternals Process Monitor and found traffic from a custom service with the same timestamps. It was querying all of the certificate stores and not finding anything.
Disabling this service would stop the security events.
| {
"pile_set_name": "StackExchange"
} |
Q:
facebook developer toolkit - RequiredPermissions not working
I am using facebook developer toolkit along with c#.
I would like to require my users to allow me offline and email access. I am using the following code, but it does nothing...
RequiredPermissions = new System.Collections.Generic.List<Facebook.Schema.Enums.ExtendedPermissions>();
RequiredPermissions.Add(Facebook.Schema.Enums.ExtendedPermissions.email);
RequiredPermissions.Add(Facebook.Schema.Enums.ExtendedPermissions.offline_access);
RequireLogin = true;
Any Ideas?
A:
If you are using Canvas (FBML or Iframe), you must put your code in the constructor of your page. Then Facebook will redirect you to get permissions page. Saludos
| {
"pile_set_name": "StackExchange"
} |
Q:
How to show image path in image view
Dears
I am Making a movie app that have two activities first activity have gridview that
shows grid of movie posters and whenever you click on any poster it will take you
to the other activity which is suppose to show the poster of the movie you clicked on
and detail text.
what is my problem?
when the second activity starts the movie detail is displayed but the poster is
not showing, how to display an image using an image path like this
"6bCplVkhowCjTHXWv49UjRPn0eK.jpg"? below the related code:
First Activity:
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String movieDetailText = "ID:" + movieId[i] + " \n" + "Title:\n" + movieTitle[i] + "\n"
+ "Over View:\n" + movieOverview[i] + "\n" + "Release Date:\n" +
movieReleaseDate[i] + "\n" + "Rating:\n" + movieVoteAverage[i];
String movieDetailImage = moviePosterPath[i];
Intent intent = new Intent(getActivity(),DetailActivity.class);
intent.putExtra(Intent.EXTRA_TEXT,movieDetailText);
intent.putExtra("image_path", movieDetailImage);
startActivity(intent);
}
});
Second Activity:
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String movieDetail = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text))
.setText(movieDetail);
String posterImage = intent.getStringExtra("image_path");
Bitmap bitmap = BitmapFactory.decodeFile(posterImage);
((ImageView) rootView.findViewById(R.id.detail_image))
.setImageBitmap(bitmap);
A:
I needed to add the following to fix my issue:
String imagePath = intent.getStringExtra("image_path");
String posterImage = "http://image.tmdb.org/t/p/w185/" + imagePath;
| {
"pile_set_name": "StackExchange"
} |
Q:
About Encapsulation : properties
Case I :
class example
{
private int roll;
public int Roll
{
get {
return roll;
}
set{
if (value > 0)
{ roll = value; }
}
}
//public example()
//{
// roll = 500;
//}
}
class practice_4
{
static void Main(string[] args)
{
example ABC = new example();
Console.WriteLine(ABC.Roll = -1);
Console.ReadLine();
}
}
Output : -1
I have set a business logic that does not contain any illegal value and gives me by default value "0"..
Case II:
class example
{
private byte roll;
public byte Roll
{
get {
return roll;
}
set{
if (value > 0)
{ roll = value; }
}
}
//public example()
//{
// roll = 500;
//}
}
class practice_4
{
static void Main(string[] args)
{
example ABC = new example();
Console.WriteLine(ABC.Roll = -1);
Console.ReadLine();
}
}
Above code is displaying compile time error as I just change valuetype Int to byte
error: constant value -1 cannot converted to byte ...
what Console.WriteLine Method really do ?
A:
It's because assigment expression returns the value that is being assigned which is -1 in this case. it doesn't return the ABC.Roll, you can verify that by outputting the property value after the assignment:
Console.WriteLine(ABC.Roll = -1); //-1
Console.WriteLine(ABC.Roll); //0
So the ABC.Roll actually never changes cause of the validation logic in setter method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Type is one of several concrete functions
Is there a mechanism in Typescript for statically declaring that an argument is one of several concrete non-primitive values? For example, the function route() can only be called with one of the functions home(), about(), or contact(), none of which have a specific unique type signature.
function home () { return <h1>Home</h1>; }
function about () { return <h1>About</h1>; }
function contact() { return <h1>Contact</h1>; }
type Paths = /* one of home, about, or contact */
function route(path: Paths) {/* ... */}
Enums are the spirit of my wish, but they are not the answer because they can only serialize primitive values:
enum Paths {
HOME = home /* home cannot be assigned */
ABOUT = "about" /* only works for strings */
}
A:
TypeScript doesn't have general dependent types, which is what you'd need to specify a type as a union of arbitrary values. As defined, your home, about, and contact functions are all of type () => JSX.Element and cannot be distinguished from each other or other functions of the same type. If you can't change the type definitions of these functions, then you're stuck.
Assuming that you can alter the definitions of these functions, though, you can use string literal types or unique symbol types to brand values so that their types can be distinguished from otherwise-identical types. Unit types like primitive literal and unique symbol types in TypeScript can be used to get some of the expressiveness of dependent types.
For example, we can dynamically add a brand property to each one:
const idProp = Symbol("idProp");
function home() { return <h1>Home</h1>; }
home[idProp] = "home" as const;
function about() { return <h1>About</h1>; }
about[idProp] = "about" as const;
function contact() { return <h1>Contact</h1>; }
contact[idProp] = "contact" as const;
Here, idProp is a unique symbol (that you will presumably not export to others) and for each function we've added a property whose key is idProp and whose value is a different string literal. This allows us to distinguish home, about and contact from each other as well as from unbranded functions. If you don't care about distinguishing them from each other, you can make them all true or some other property value.
Now we can write
type Paths = typeof home | typeof about | typeof contact;
function route(path: Paths) {/* ... */ }
And you can see that it works on your branded functions:
route(home); // okay
But doesn't work on unbranded functions of otherwise identical types:
function nope() { return <h1>Nope</h1>;};
route(nope); // error!
If a malicious actor gets their hands on idProp and adds the right property with that key to their own function, they can fool the compiler into allowing their own function to be passed to route(). Of course, a malicious actor can go through even less effort and just assert that their function is of type Paths. Thus, like the rest of the type system, this branding method does not guarantee type safety; it just makes it more probable.
Okay, hope that helps; good luck!
Playground link to code
| {
"pile_set_name": "StackExchange"
} |
Q:
Differences of using Component template vs templateUrl
Angular 2 allows to write multi-line templates by using ` characters to enquote them. It is also possible to put multi-line template into .html file and reference it by templateUrl.
It seems comfortable for me to put the template directly into component as then it's all in one place, but is there any drawback of doing so?
1st approach:
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `
<h1>My First Angular 2 multiline template</h1>
<p>Second line</p>
`
})
export class AppComponent { }
vs
2nd approach:
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
templateUrl: 'multi-line.html'
})
export class AppComponent { }
together with multi-line.html:
<h1>My First Angular 2 multiline template</h1>
<p>Second line</p>
A:
In terms of how the final application will perform, there's no real difference between having an embedded template and an external template.
For the developer, however, there are a number of differences that you have to consider.
You get better code completion and inline support in your editor/IDE in most cases when the HTML is in a separate .html file. (IntelliJ IDEA, at least, supports HTML for inline templates and strings)
There is a convenience factor to having code and the associated HTML in the same file. It's easier to see how the two relate to each other.
These two things will be of equal value for many people, so you'd just pick your favorite and move ahead with life if this were all there was to it.
But that leads us to the reasons you should keep your templates in your components, in my opinion:
It is difficult to make use of relative filepaths for external templates as it currently stands in Angular 2.
Using non-relative paths for external templates makes your components far less portable, since you need to manage all of the /where/is/my/template type references from the root that change depending on how deep your component is.
That's why I would suggest that you keep your templates inside your components where they are easily found. Also, if you find that your inline template is getting large and unwieldy, then it is probably a sign that you should be breaking your component down into several smaller components, anyway.
A:
The drawbacks are that the IDE tooling isn't as strong as mentioned above, and putting large chunks of html into your components makes them harder to read.
Also, if you are following the angular2 style guide, it recommends that you do extract templates into a separate file when longer than 3 lines.
From the angular2 style guide :
Do extract templates and styles into a separate file, when more than 3
lines.
Why? Syntax hints for inline templates in (.js and .ts) code files are
not supported by some editors.
Why? A component file's logic is easier to read when not mixed with
inline template and styles.
Source
| {
"pile_set_name": "StackExchange"
} |
Q:
This tiny Tkinter program works in Python 2 and 3, but why the odd behaviour in Python 3?
New to Tkinter, I 'wrote' the code below to draw a page of squared paper with bold lines at 10-square intervals.
It runs OK in Python 2 (with the change from 'tkinter' to 'Tkinter'). In Python 3 it runs, but the emboldening is only applied to vertical lines.
Not the most urgent problem in the world, I'm hoping it might raise a bit of interest matching my own curiosity...
'''
SquaredPaper app, based on Canvas example from
http://effbot.org/tkinterbook/tkinter-index.htm
'''
# CONSTANTS
A4Hmm = 297
A4Wmm = 210
PXperMM = 3
A4_HEIGHT = A4Hmm * PXperMM
A4_WIDTH = A4Wmm * PXperMM
SQUARE_SIDE = 5*PXperMM
NSQUARES_H = A4_HEIGHT/SQUARE_SIDE
NSQUARES_W = A4_WIDTH/SQUARE_SIDE
from tkinter import *
master = Tk()
w = Canvas(master, width=A4_WIDTH, height=A4_HEIGHT)
w.pack()
paper = w.create_rectangle(0, 0, A4_WIDTH, A4_HEIGHT)
count = NSQUARES_H
pos = 0
while count > 0:
lw = 1 if count%10 else 2
w.create_line(0, pos, A4_WIDTH, pos, width=lw)
pos += SQUARE_SIDE
count -= 1
count = NSQUARES_W
pos = 0
while count > 0:
lw = 1 if count%10 else 2
w.create_line(pos, 0, pos, A4_HEIGHT, width=lw)
pos += SQUARE_SIDE
count -= 1
mainloop()
A:
The problem arises due the way division is handled in each version.
In Python 2.7, the division operator / outputs an integer value, if the 2 inputs are integers.
Whereas, in Python 3, a float value is returned for the same.
This makes the code usable in Python 2.7 and not in 3, as the variable NSQUARES_H is returned as a float and hence the else condition in lw = 1 if count%10 else 2 is never executed.
If you want to run the same in Python 3, round the value of NSQUARES_H or convert it into an int
| {
"pile_set_name": "StackExchange"
} |
Q:
How to remove dateT~~ in javascript?
I wrote code for getting the coming Saturday. So I wrote like this and the result is 2020-03-07T04:00:48.306Z. I found the dateT~~. I just only need the date. I can use the split method, but I don't wanna use this. is there any other way?
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff));
}
A:
Try with substr,
function getSaturday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate()+5 - day + (day == 5 ? 7:1);
console.log(diff);
return new Date(d.setDate(diff)).toISOString.substr(0,10);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
store tableview data into an array
I have made an iphone application, in which I have put tableview , the data in tableview is added by selecting datetime picker ,whenever we select any date time from picker it will get add into the tableview. Now I want to put all these added value of datetime into an array.
how can I do this. I am searching this concept from last many days. But got no answer. Please if some one know, help me.
Thanks alot.
A:
NSMutableArray is what you'll want. It provides a method called addObject:, so you can add these date values to your array with ease.
Edit: You asked for an example, very well. Here's how you can do it and how you should approach such problems in the future:
1) You said you had a UIDatePicker instance that you wanted to save the date of. So how do we get the date? The first thing you should always do is consult the Apple Developer Documentation, in this case for UIDatePicker. A short read reveals that this class has a date property.
Aah UIDatePicker, is there anything you can't do?
Now that we have the date we want, you'll want to put it into an NSMutableArray, as I have suggested. So we do it the same way again - open the Apple Developer Documentation and look up NSMutableArray. That reveals to us that there is in fact a addObject: method but wait...there's more?? Yep, NSMutableArray is damn powerful, so have a look through the entire document and see what you can use.
The documentation reveals that we can use addObject: to add an object to the array, so let's start:
NSMutableArray*myDates = [NSMutableArray array];
Now we've initalised our array. Now let's add an object:
[myDates addObject:[datePicker date]];
Done. We've now added an object. If you want to save this disc at a later stage, use NSMutableArray's writeToFile:atomically: method. For more details, read the documentation.
Now don't just go ahead and copy and paste the code. Read Apple's documents on these classes, they are really helpful and will enable you to resolve such problems in the future.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to sort List> by key1 descending order and key2 ascending order if key1 has same values
I have a List
List<Map<String,String>> list = new ArrayList<>();
Map<String,String> map = new HashMap<>();
Map<String,String> map1 = new HashMap<>();
Map<String,String> map2 = new HashMap<>();
map.put("productNumber", "107-001");
map1.put("productNumber", "108-001");
map2.put("productNumber", "109-001");
map.put("price", "1.99");
map1.put("price", "1.02");
map2.put("price", "1.99");
list.add(map);
list.add(map1);
list.add(map2);
I sort it by price and revers result
formattedResult = list.stream().sorted(Comparator.comparing(m -> Double.parseDouble(m.get("price")))).collect(Collectors.toList());
Collections.reverse(formattedResult);
The result of this :
**price productNumber**
1.99 109-001
1.99 107-001
1.02 108-001
I want to sort it like
**price productNumber**
1.99 107-001
1.99 109-001
1.02 108-001
If prices equal - compare by product number, end first should be productNumber with a lower value.
Please help!
A:
You don't need to reverse result if you use the right comparator (and you can chain comparators, too):
final Comparator<Map<String, String>> byPrice = Comparator.comparing(m -> Double.parseDouble(m.get("price")), Comparator.reverseOrder());
formattedResult = list.stream().sorted(byPrice.thenComparing(m -> m.get("productNumber"))).collect(Collectors.toList());
A:
It's easier if you build your Comparator in two steps. So try this and print them out. It works like this.
first it sorts the price in reversed order.
Then t sorts the product number in regular order for equal prices.
Comparator<Map<String, String>> comp = Comparator
.comparing(m ->Double.parseDouble(m.get("price"))
,Comparator.reverseOrder());
comp = comp.thenComparing(m -> m.get("productNumber"));
Apply it like so.
List<Map<String, String>> formattedResult =
list.stream().sorted(comp)
.collect(Collectors.toList());
formattedResult.forEach(m -> System.out.println(
m.get("price") + " : " + m.get("productNumber")));
This prints
1.99 : 107-001
1.99 : 109-001
1.02 : 108-001
| {
"pile_set_name": "StackExchange"
} |
Q:
Tips for cooking seared tuna just right?
I'm awfully fond of seared tuna, and I have the recipe down pat. However, I'm rarely 100% satisfied with the results searing part- I typically overshoot on the thickness of the cooked layer. For the record, I use a sesame-crusted recipe, and usually use previously-frozen tuna that I've let thaw completely. Any tips or suggestions?
A:
With seared Tuna the point is to create a charred crust while leaving the inside mostly raw. It's very similar to cooking a steak rare in that the secret is a very hot pan and a short amount of time. So get your pan as hot as you can, coat the cooking surfaces of the tuna steaks with a bit of oil with a high smoke point (corn, canola, peanut - not olive oil or walnut oil), then fry the tuna for as little time as you can get away with. I'd think 45-60 seconds per side. In case you are wondering the oil forms a good heat contact with the tuna, improving conductivity, it's not for any flavor effect.
Now you may have a stove that doesn't get the pan hot enough in which case it takes too long to form a crust and the inside cooks more than you like, in which case you can try:
Not letting the tuna thaw completely. If it's still a teensy bit frozen in the middle the heat from the cooking will thaw it, not cook it. You could also try it straight out of the fridge
Use a cooking torch. You can also use a plumbing torch, it's the same thing except much cheaper
| {
"pile_set_name": "StackExchange"
} |
Q:
Comma separating namespace name - how to use it?
I want to use a namespace in this format "name1:name2:name3", but when I try to use it in my vb class like this
Namespace name1:name2:name3
Partial Public Class Message
End class
End namespave
I get an error: Declaration expected.
I have no control over the namespace so I can not change it.
Thanks in advance!
EDIT
I use xsd.exe to autogenerate a class fromn an xsd. I use the n switch to set the namespace. I get the namespace from the organization who provides the xsd and the namespace is on the form "ukm:sst:collection:detail". I have to use it in my class to get the xml i serialize from the class validated.
My xml should look like this
<?xml version="1.0" encoding="UTF-8" ?>
<message xmlns="ukm:sst:collection:detail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xsi:schemaLocation="ukm:sst:collection:detail">
EDIT2
My class:
<System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929"), _
System.SerializableAttribute(), _
System.Diagnostics.DebuggerStepThroughAttribute(), _
System.ComponentModel.DesignerCategoryAttribute("code"), _
System.Xml.Serialization.XmlTypeAttribute([Namespace]:="ukm:sst:collection:detail"), _
System.Xml.Serialization.XmlRootAttribute("melding", [Namespace]:="ukm:sst:collection:detail", IsNullable:=False)> _
Partial Public Class Message
But my xml is missing the xsi:schemaLocation attribute
my xml looks like:
<?xml version="1.0" encoding="utf-8"?>
<message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="ukm:sst:collection:detail">
but the xml should look like:
<?xml version="1.0" encoding="UTF-8" ?>
<message xmlns="ukm:sst:collection:detail" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xsi:schemaLocation="ukm:sst:collection:detail test_v2_0.xsd">
I have the Imports System.Xml.Serialization in my autogenerated class.
What is it I'm doing wrong?
A:
I think you are confusing the VB.Net Class Namespace, with the Xml namespace. The two are not one and the same thing.
If you want a namespace in your Xml Output from the class, you should use the XmlRoot Attribute, and specify the namespace in there:
<XmlRoot(Namespace:="ukm:sst:collection:detail")>
Public Class Message
End Class
NB: You will want to import System.Xml.Serialization in your class page.
Based on your Edit2, In order to get SchemaLocation in, it appears that you need to add a property to the class that contains it, and specify it using XmlAttribute (Found from this answer):
<XmlRoot(Namespace:="ukm:sst:collection:detail")>
Public Class Message
<XmlAttribute("schemalocation", Namespace:=XmlSchema.InstanceNamespace)>
public string SchemaLocation = "ukm:sst:collection:detail test_v2_0.xsd"
End Class
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.