text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Need Help OpenGL + C
im tring to implement C code in openGl to show date in my solor system program. but im getting error
which basically sayed as follow:
error: invalic operands to binary * (have 'char *' and 'char *')
My code as follow :
void showDate(void)
{
int days, years;
char str[30];
char *ch;
// ....... some code
// and here it's giving that error in for statment
for( ch * str; *ch; ch++){
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, (int) *cha
}
}
A:
Your loop is wrong. It should look like this:
for (ch = str; *ch; ch++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, (int) *ch);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
NullPointerException while selecting image from the storage for the Second time onwards, No NullPointerException while selecting First time
I have set up a button that is meant to check for READ_EXTERNAL_STORAGE permissions, and then open the users phone storage display images. I've done this successfully via the following code:
All of this works perfectly on the first try. The user sees the permission dialog box, presses agree and the image selector opens displaying images on their phone! However, the second time we try to use the same button the app crashes. So basically after the permissions are granted the app crashes every time the button is pressed.
The following error is displayed:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.memory.pod.debug, PID: 26684
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:98)
at com.memory.pod.camerax.ui.home.HomeActivity.selectImage(HomeActivity.java:144)
at com.memory.pod.camerax.ui.home.HomeActivity.openFileChooser(HomeActivity.java:137)
at com.memory.pod.view.BottomTabView$4.onClick(BottomTabView.java:84)
at android.view.View.performClick(View.java:7259)
at android.view.View.performClickInternal(View.java:7236)
at android.view.View.access$3600(View.java:801)
at android.view.View$PerformClick.run(View.java:27892)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
BottomTabView.java
public class BottomTabView extends FrameLayout implements ViewPager.OnPageChangeListener {
// Initialize content
private ImageView mCenterImageView;
private ImageView mBottomImageView;
private LinearLayout mStartImageView;
private LinearLayout mEndImageView;
private View mIndicator;
private ArgbEvaluator mArgbEvaluator;
private int mCenterColor;
private int mSideColor;
private int mEndViewsTranslationX;
private int mIndicatorTranslationX;
private int mCenterTranslationY;
public BottomTabView(@NonNull Context context) {
this(context, null);
}
public BottomTabView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomTabView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setUpWithViewPager(ViewPager viewPager) {
viewPager.addOnPageChangeListener(this);
mStartImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 0)
viewPager.setCurrentItem(0);
}
});
mCenterImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 1)
viewPager.setCurrentItem(1);
}
});
mEndImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 2)
viewPager.setCurrentItem(2);
}
});
mBottomImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() == 1) {
HomeActivity.openFileChooser(getContext());
}
}
});
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.view_bottom_tabs, this, true);
// Initialize bottom tab view content
mCenterImageView = findViewById(R.id.view_bottom_tabs_camera_iv);
mStartImageView = findViewById(R.id.view_bottom_tabs_start_linear_layout);
mEndImageView = findViewById(R.id.view_bottom_tabs_end_linear_layout);
mBottomImageView = findViewById(R.id.view_bottom_tabs_gallery_iv);
// Initialize bottom tab view indicator, meant to indicate the current tab in view
mIndicator = findViewById(R.id.view_bottom_tabs_indicator);
// Set start color and end color for tab view icons
mCenterColor = ContextCompat.getColor(getContext(), R.color.white);
mSideColor = ContextCompat.getColor(getContext(), R.color.black);
// Evaluate the difference between colors
mArgbEvaluator = new ArgbEvaluator();
// Change the padding of tab icons based on view
// This is the min padding accepted (0)
mIndicatorTranslationX = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 140, getResources().getDisplayMetrics());
// Wait till GalleryImageView has been drawn, once GalleryImageView is drawn then proceed with relative padding calculation
mBottomImageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Change padding relative to other icons
mEndViewsTranslationX = (int)((mBottomImageView.getX() - mStartImageView.getX()) - mIndicatorTranslationX);
mBottomImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Change the position of the center image
mCenterTranslationY = getHeight() - mBottomImageView.getBottom();
}
});
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
// Change color of icons based on view
setColor(1 - positionOffset);
// Move the start and end images
moveViews(1 - positionOffset);
// Change indicator position
mIndicator.setTranslationX((positionOffset - 1) * mIndicatorTranslationX);
// Change scale of center image
moveAndScaleCenter(1 - positionOffset);
} else if (position == 1) {
// Change color of icons based on view
setColor(positionOffset);
// Move the start and end images
moveViews(positionOffset);
// Change indicator position
mIndicator.setTranslationX(positionOffset * mIndicatorTranslationX);
// Change scale of center image
moveAndScaleCenter(positionOffset);
}
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
private void moveAndScaleCenter(float fractionFromCenter) {
float scale = .7 f + ((1 - fractionFromCenter) * .3 f);
// Change scale of center image
mCenterImageView.setScaleX(scale);
mCenterImageView.setScaleY(scale);
int translation = (int)(fractionFromCenter * mCenterTranslationY * 2);
// Move center image down
mCenterImageView.setTranslationY(translation);
mBottomImageView.setTranslationY(translation);
// Fadeout bottom image
mBottomImageView.setAlpha(1 - fractionFromCenter);
}
private void moveViews(float fractionFromCenter) {
mStartImageView.setTranslationX(fractionFromCenter * mEndViewsTranslationX);
mEndImageView.setTranslationX(-fractionFromCenter * mEndViewsTranslationX);
mIndicator.setAlpha(fractionFromCenter);
mIndicator.setScaleX(fractionFromCenter);
}
private void setColor(float fractionFromCenter) {
int color = (int) mArgbEvaluator.evaluate(fractionFromCenter, mCenterColor, mSideColor);
/* mCenterImageView.setColorFilter(color);
mStartImageView.setColorFilter(color);
mEndImageView.setColorFilter(color);
mBottomImageView.setColorFilter(color); */
}
}
I did a log.d to identify where it fails, please refer to previous code to see log.d.
How can I overcome this issue?
EDIT:
HomeActivity:
public class HomeActivity extends AppCompatActivity {
// Initialize image picker
private static final int PICK_IMAGE_REQUEST = 1;
private static final int REQUEST_CODE_STORAGE_PERMISSION = 1;
private static final int REQUEST_CODE_SELECT_IMAGE = 2;
// TODO: FIREBASE TEMPORARY LOGOUT
private static FirebaseAuth mAuth;
private static final String TAG = "HomeActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Initialize views
View background = findViewById(R.id.background_view);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
// Initialize adapter
HomePagerAdapter adapter = new HomePagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
// Initialize BottomTabView
BottomTabView bottomTabView = findViewById(R.id.bottom_tabs);
bottomTabView.setUpWithViewPager(viewPager);
// Initialize TopSearchView
TopSearchView topSearchView = findViewById(R.id.top_search);
topSearchView.setUpWithViewPager(viewPager);
// Initialize TopProfilePictureView
TopProfilePictureView topProfilePictureView = findViewById(R.id.top_profile_picture);
topProfilePictureView.setUpWithViewPager(viewPager);
// Initialize TopVariableFunctionalityButtonView
TopVariableFunctionalityButtonView topVariableFunctionalityButtonView = findViewById(R.id.top_variable_functionality_button);
topVariableFunctionalityButtonView.setUpWithViewPager(viewPager);
// Initialize color for fade effect
final int windowBackgroundColor = ContextCompat.getColor(this, R.color.windowBackground);
final int blackBackgroundColor = ContextCompat.getColor(this, R.color.black);
// Set the default position of the viewPager
viewPager.setCurrentItem(1);
// TODO: Initialize Firebase (TEMPORARY)
//Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
bottomTabView.setOnBottomTabViewClickListener(new BottomTabViewClickListener() {
@Override
public void onClick(View v) {
// call your openFileChooser from here,
//REMOVE THE STATIC
openFileChooser(HomeActivity.this);
}
});
// Callback each time the fragment is changed
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
background.setBackgroundColor(windowBackgroundColor);
background.setAlpha(1 - positionOffset);
} else if (position == 1) {
background.setBackgroundColor(blackBackgroundColor);
background.setAlpha(positionOffset);
}
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
// Choose file extended from BottomTabView, opens all images on device
// Check for permissions before hand
public void openFileChooser(Context context) {
Log.d("HomeActivity", "This is the last place a log is observed");
if (ContextCompat.checkSelfPermission(getInstance().getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
((Activity) context),
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
},
REQUEST_CODE_STORAGE_PERMISSION
);
} else {
selectImage();
}
}
// Open image selector via phone storage
private void selectImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE);
}
}
// Request permission results
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_STORAGE_PERMISSION && grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
selectImage();
} else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
}
}
}
// TODO: Is it better to use bitmap or URI
// Check if user has selected file and describe next step
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_SELECT_IMAGE && resultCode == RESULT_OK) {
if (data != null) {
// Get image URI
Uri selectedImageUri = data.getData();
if (selectedImageUri != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// Do something with image
// Identify the selected image file, pass onto firebase
File selectedImageFile = new File(getPathFormUri(selectedImageUri));
} catch (Exception exception) {
Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
}
private String getPathFormUri(Uri contentUri) {
String filePath;
Cursor cursor = getContentResolver()
.query(contentUri, null, null, null, null);
if (cursor == null) {
filePath = contentUri.getPath();
} else {
cursor.moveToFirst();
int index = cursor.getColumnIndex("_data");
filePath = cursor.getString(index);
cursor.close();
}
return filePath;
}
// TODO: TEMPORARY LOGOUT
public static void logoutUser(Context context) {
mAuth.signOut();
}
}
BottomTabActivity:
public class BottomTabView extends FrameLayout implements ViewPager.OnPageChangeListener {
// Initialize content
BottomTabViewClickListener bottomTabViewClickListener;
private ImageView mCenterImageView;
private ImageView mBottomImageView;
private LinearLayout mStartImageView;
private LinearLayout mEndImageView;
private View mIndicator;
private ArgbEvaluator mArgbEvaluator;
private int mCenterColor;
private int mSideColor;
private int mEndViewsTranslationX;
private int mIndicatorTranslationX;
private int mCenterTranslationY;
//add this function somewhere
public void setOnBottomTabViewClickListener(BottomTabViewClickListener bottomTabViewClickListener) {
this.bottomTabViewClickListener = bottomTabViewClickListener;
}
public BottomTabView(@NonNull Context context) {
this(context, null);
}
public BottomTabView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BottomTabView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setUpWithViewPager(ViewPager viewPager) {
viewPager.addOnPageChangeListener(this);
mStartImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 0)
viewPager.setCurrentItem(0);
}
});
mCenterImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 1)
viewPager.setCurrentItem(1);
}
});
mEndImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() != 2)
viewPager.setCurrentItem(2);
}
});
mBottomImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() == 1) {
}
}
});
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.view_bottom_tabs, this, true);
// Initialize bottom tab view content
mCenterImageView = findViewById(R.id.view_bottom_tabs_camera_iv);
mStartImageView = findViewById(R.id.view_bottom_tabs_start_linear_layout);
mEndImageView = findViewById(R.id.view_bottom_tabs_end_linear_layout);
mBottomImageView = findViewById(R.id.view_bottom_tabs_gallery_iv);
// Initialize bottom tab view indicator, meant to indicate the current tab in view
mIndicator = findViewById(R.id.view_bottom_tabs_indicator);
// Set start color and end color for tab view icons
mCenterColor = ContextCompat.getColor(getContext(), R.color.white);
mSideColor = ContextCompat.getColor(getContext(), R.color.black);
// Evaluate the difference between colors
mArgbEvaluator = new ArgbEvaluator();
// Change the padding of tab icons based on view
// This is the min padding accepted (0)
mIndicatorTranslationX = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 140, getResources().getDisplayMetrics());
// Wait till GalleryImageView has been drawn, once GalleryImageView is drawn then proceed with relative padding calculation
mBottomImageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Change padding relative to other icons
mEndViewsTranslationX = (int)((mBottomImageView.getX() - mStartImageView.getX()) - mIndicatorTranslationX);
mBottomImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Change the position of the center image
mCenterTranslationY = getHeight() - mBottomImageView.getBottom();
}
});
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
// Change color of icons based on view
setColor(1 - positionOffset);
// Move the start and end images
moveViews(1 - positionOffset);
// Change indicator position
mIndicator.setTranslationX((positionOffset - 1) * mIndicatorTranslationX);
// Change scale of center image
moveAndScaleCenter(1 - positionOffset);
} else if (position == 1) {
// Change color of icons based on view
setColor(positionOffset);
// Move the start and end images
moveViews(positionOffset);
// Change indicator position
mIndicator.setTranslationX(positionOffset * mIndicatorTranslationX);
// Change scale of center image
moveAndScaleCenter(positionOffset);
}
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
private void moveAndScaleCenter(float fractionFromCenter) {
float scale = .7 f + ((1 - fractionFromCenter) * .3 f);
// Change scale of center image
mCenterImageView.setScaleX(scale);
mCenterImageView.setScaleY(scale);
int translation = (int)(fractionFromCenter * mCenterTranslationY * 2);
// Move center image down
mCenterImageView.setTranslationY(translation);
mBottomImageView.setTranslationY(translation);
// Fadeout bottom image
mBottomImageView.setAlpha(1 - fractionFromCenter);
}
private void moveViews(float fractionFromCenter) {
mStartImageView.setTranslationX(fractionFromCenter * mEndViewsTranslationX);
mEndImageView.setTranslationX(-fractionFromCenter * mEndViewsTranslationX);
mIndicator.setAlpha(fractionFromCenter);
mIndicator.setScaleX(fractionFromCenter);
}
private void setColor(float fractionFromCenter) {
int color = (int) mArgbEvaluator.evaluate(fractionFromCenter, mCenterColor, mSideColor);
/* mCenterImageView.setColorFilter(color);
mStartImageView.setColorFilter(color);
mEndImageView.setColorFilter(color);
mBottomImageView.setColorFilter(color); */
}
}
interface BottomTabViewClickListener {
public void onClick();
}
A:
Your else statement is currently like this, which means you are trying to create a new instance of HomeActivity and call selectimage(), and it does not work that way.
else {
new HomeActivity().selectImage();
}
Please, change it to
else{
selectImage();
}
Please, try this, this should solve your problem.
EDIT: Use of interface and listener pattern
In your BottomTabView add the following
public class BottomTabView extends FrameLayout implements ViewPager.OnPageChangeListener {
// Initialize content
// add this at top level.
BottomTabViewClickListener bottomTabViewClickListener;
//add this function somewhere
public void setOnBottomTabViewClickListener(BottomTabViewClickListener bottomTabViewClickListener){
this.bottomTabViewClickListener = bottomTabViewClickListener;
}
// replace HomeActivity.openFileChooser(getContext());
mBottomImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (viewPager.getCurrentItem() == 1) {
bottomTabViewClickListener.onClick();
}
}
});
}
//end of BottomTab View
//add this after your BottomTabView not inside
interface BottomTabViewClickListener{
public void onClick();
}
Add the following in your HomeActivity
// Initialize BottomTabView
BottomTabView bottomTabView = findViewById(R.id.bottom_tabs);
bottomTabView.setUpWithViewPager(viewPager);
bottomTabView.setOnBottomTabViewClickListener(new BottomTabViewClickListener() {
@Override
public void onClick() {
// call your openFileChooser from here,
//REMOVE THE STATIC
openFileChooser(HomeActivity.this)
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieving EC2 Instance RSA Fingerprint
I am trying to automate the complete process of initiating an EC2 instance and then performing some executions over it and then closing it. Everything is working fine except one problem.
I cant SSH into my EC2 instance. To SSH into the EC2 just created i need the RSA fingerprint of that particular instance, which is not available. Now i can extract the log by using aws cli but it is very complex to extract it from there, as the extracted file contain no new line character. Is there any direct command through which we can know what the fingerprint of EC2 Instance is, without logging in it ?
I am using winscp to log in to the system by following command
"open sftp://ec2-user@%varPublicIp% -timeout=120 -privatekey="D:\subham_ec2key\privateKey-us-west-1.ppk" -hostkey="<RSA FINGERPRINT>""
A:
Following code snippet will solve the problem. The code snippet is for batch script.
aws ec2 get-console-output --output table --instance-id "i-256789"> InstanceId.txt
findstr "(RSA)" varInstanceId.txt>RSAFingerprint.txt
for /f "tokens=3 delims= " %%G in (RSAFingerprint.txt) do @echo %%G>RSAFingerprint.txt
for /f "delims=" %%G in (RSAFingerprint.txt) do set varRSAFingerprint=%%G
echo varRSAFingerprint: %varRSAFingerprint%
Now lets understand the above code line by line
aws ec2 get-console-output --output table --instance-id "i-256789"> InstanceId.txt
ec2 console output will provide the system log for the EC2 Instance. It is very essential to take the output in table format otherwise the json output doesn't provide any CRLF in the file making it impossible to extract the RSA Fingerprint.
findstr "(RSA)" varInstanceId.txt>RSAFingerprint.txt
finding (RSA) keyword from the syslog file generated, when it will find the (RSA) keyword on that file it will return the complete line containing the keyword and will put it into the RSAFingerprint.txt.
for /f "tokens=3 delims= " %%G in (RSAFingerprint.txt) do @echo %%G>RSAFingerprint.txt
Above line will extract the fingerprint only from the line earlier extracted.
for /f "delims=" %%G in (RSAFingerprint.txt) do set varRSAFingerprint=%%G
above line will put the fingerprint in the variable varRSAFingerprint.
| {
"pile_set_name": "StackExchange"
} |
Q:
Помогите с sql запросом из трех таблиц
Добрый вечер!
Есть три таблицы:
users(user_id int),
deps (dep_id int)
и соединительная:
depusers (user_id int, dep_id int, data int).
Хочу получить список всех user_id, dep_id, count (data) из соединительной таблицы. Если данных по user или для dep нет - вывести null. Понимаю что нужно полное объединение, но что-то не получается.
A:
Например, так:
SELECT
T.user_id,
T.dep_id,
depusers.data
FROM
(SELECT
users.user_id,
deps.dep_id
FROM users CROSS JOIN deps) AS T
LEFT JOIN depusers ON (T.user_id = depusers.user_id AND
T.dep_id = depusers.dep_id);
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL errors when attempting to test Symfony 2 app - columns already exist, tables missing
I'm following the test setup described here and also here. When I attempt to run my tests, and the test db is in the process of being created, I get the following errors:
[Doctrine\ORM\Tools\ToolsException]
Schema-Tool failed with Error 'An exception occurred while executing 'CREATE INDEX deletedAtidx ON SurveyHash (deletedAt)':
SQLSTATE[HY000]: General error: 1 index deletedAtidx already exists' while executing DDL: CREATE INDEX deletedAtidx ON SurveyHash (deletedAt)
[Doctrine\DBAL\Exception\TableExistsException]
An exception occurred while executing 'CREATE INDEX deletedAtidx ON SurveyHash (deletedAt)':
SQLSTATE[HY000]: General error: 1 index deletedAtidx already exists
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000]: General error: 1 index deletedAtidx already exists
[PDOException]
SQLSTATE[HY000]: General error: 1 index deletedAtidx already exists
doctrine:schema:create [--dump-sql] [--em[="..."]]
purging database
[Doctrine\DBAL\DBALException]
An exception occurred while executing 'DELETE FROM PageImage':
SQLSTATE[HY000]: General error: 1 no such table: PageImage
[PDOException]
SQLSTATE[HY000]: General error: 1 no such table: PageImage
doctrine:fixtures:load [--fixtures[="..."]] [--append] [--em="..."] [--purge-with-truncate]
Doctrine\DBAL\Exception\TableNotFoundException : An exception occurred while executing 'SELECT t0.label AS label_1, t0.value AS value_2 FROM Setting t0 WHERE t0.label = ? LIMIT 1' with params ["webservice"]:
SQLSTATE[HY000]: General error: 1 no such table: Setting
Looking at my entities, the deletedAt index is not declared twice in my SurveyHash entity, and I have entities for both PageImage and Setting, yet those tables aren't being created, as verified by sqliteman. Futher testing (see the comments in one of the answers below) show that it's throwing an error due to multiple tables using the same index name.
My config_test.yml has the following:
doctrine:
dbal:
driver: pdo_sqlite
path: %kernel.cache_dir%/test.db
charset: UTF8
orm:
auto_generate_proxy_classes: true
auto_mapping: true
I'm a bit limited in the database info I can share due to a NDA, so I'm hoping these errors are a result of something in the links above or my config_test.yml. I'm using Symfony 2.4.6, if that makes a difference.
A:
I think that you're trying to do a doctrine:schema:update on tables where the datasets have foreign keys or you're trying to add multiple datasets.
What you could try is so to drop the database schema, recreate it and then refill it with the data.
So first do a php app/console doctrine:schema:drop --force, then php app/console doctrine:schema:create and then doctrine:fixtures:load.
I had the same issues and this works for me.
I just flown over the first link and what you're doing is to call doctrine:schema:create multiple times, which of course won't work because you've already created them. You only could doctrine:schema:update --force them or recreate with drop/create!
ANSWER
According to the comments below this Answer the Error was that he gave differnet indexes on different tables the same name, but the names from index MUST be unique!
| {
"pile_set_name": "StackExchange"
} |
Q:
Suppressing SSL errors
I want to be able to read the headers sent back from a webpage in SSL mode. My Qt app however can't reach the webpage because it's in SSL mode I am gathering? Normal webview browsing in SSL is possible in my app using this connect:
connect(view->page()->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> & )),
this, SLOT(onSslErrors(QNetworkReply*, const QList<QSslError> & )));
This suppresses the SSL errors in the webview but I have a separate function which get's the headers using this method:
//Send a request to validate URL
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QNetworkRequest request;
request.setUrl(QUrl(text));
request.setRawHeader("User-Agent", "MyApp1.0");
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
QNetworkReply *reply = manager->get(request);
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
qDebug() << "QLoop: " << reply->rawHeader("My-Application");
if(reply->rawHeader("My-Application") == "1"){
appUrl = text;
}
I need this method because I set a config file with our webapps URL in it before the the app will connect to it using webview->load(QURL(appUrl )). Just not sure how to supress/handle SSL errors using QNetworkAccessManager?
A:
You need to connect your QNAM objects signal sslErrors(QNetworkReply *, QList<QSslError>) to a slot where you set QNetworkReply::ignoreSslErrors() and that'll allow QNAM to continue running. Qt Docs on it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to show tooltip on Onclick event Using Javascript
How to show tooltip on onclick event by using javascript
Here is my code
html
<div class="tooltip">Hover over me
<div class="tooltiptext">
<button>click me</button>
<span >Tooltip text
</span>
</div>
</div>
css
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
The tooltip is showing while doing hover. But I want to show tolltip while using onclick event using only JavaScript how will I do that. Please help me
A:
Try the following setup:
html
<button id="button1">click me</button>
<div class="tooltiptext">
<span >Tooltip text</span>
</div>
css
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
js
var button1 = document.querySelectorAll('#button1');
button1.onclick = buttonClicked;
function buttonClicked(){
var tooltip = document.querySelectorAll('.tooltiptext');
tooltip.style.visibility = 'visible';
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Nested getcmsfields_forpopup showing in same popup in silverstripe
I have form in getcmsfields_forpopup for backend(admin panel) in silverstrip. In that form, I have added nested dataobjectmanager field to enter multiple dates(has_many relation). When main form open in popup window and I click on add date link, then second popup form open in the same window not in separate one. That means after entering date data and saving it, when I click on close button, whole form is closed rather going back to main form. Please help in this regard.
A:
This can't be done using SilverStripe's default popup form unless, maybe, you extended the DataObject Manager field and had it render itself in an iFrame.
The best option would be to manage your parent DataObjects with DataObjectManger as well. DataObjectManager supports nested DataObjectManager fields. See this tutorial "Nested DataObjectManager" (on YouTube).
| {
"pile_set_name": "StackExchange"
} |
Q:
Linux alternative for FreeBSD systat tool
I'm looking for a Linux alternative for systat tool that is avalaible only for FreeBSD.
What do you recommend?
A:
Linux Sysstat: http://sebastien.godard.pagesperso-orange.fr/documentation.html
Try google with "linux sysstat" keywords
A:
I am also quite fond of dstat.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to reuse layout set in setContentView? Android
I am trying to use android:configChanges="keyboardHidden|orientation|screenSize" in my Manifest so that I cannot lose state of my VideoView when configuration changes happen. This means I need to choose the layouts myself on the configuration. The problem I am having is that when I first initialize which view to use in onCreate, here:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.activity_make_photo_video_land);
} else if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_make_photo_video);
}
}
It chooses the right layout. But when I need to adjust the layout on the configuration change like here:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.activity_make_photo_video_land);
} else if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_make_photo_video);
}
}
It does not use the same instance of the layout, but rather reloads it, which makes my VideoView go black. Then I am unable to press any buttons after that.
Is there a way to reuse the initial layouts? I have tried to set the views like this one setContentView(R.layout.activity_make_photo_video_land); to an Activity activity object, but IDE won't let me, it says Activity is incompatible with void. Because if I could get a reference to that view, then I could reuse it. Or is there a simpler way of doing this that I am not seeing?
Thanks.
A:
Thanks to @Kushal suggestion, I looked into the 2 methods of onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) to save my VideoView state on configuration change (since this was the root of my problem, and using setContentView was just a hack idea). Turns out I found some code out there. Here is what I did:
Make sure I had a landscape xml and a regular xml. In my layout-land and layout folder respectively with the same name.
Overrode those 2 methods like this:
private int position = 0;
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// use onSaveInstanceState in order to store the video
// playback position for orientation change
savedInstanceState.putInt("Position", videoView.getCurrentPosition());
videoView.pause();
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// use onRestoreInstanceState in order to play the video playback
// from the stored position
position = savedInstanceState.getInt("Position");
videoView.seekTo(position);
}
Took the android:configChanges="keyboardHidden|orientation|screenSize" out of my Manifest.
Deleted the onConfigurationChanged(Configuration newConfig) method (didn't need it anymore with #3 gone).
This did it! I was able to change orientation at anytime, and record my video at anytime. Upon returning from recoding the video, it would easily display in either landscape or portrait, without losing the video (screen never went black).
The only problem I have now is my OnTouchListener is disabled, but that's another issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Django DRF API one time session/token/pass authentication without a username/password
I have a Django and django rest framework project where I want a mobile to be able to request a token and then use that token for x minutes before they're disconnected. I do not want to create a user for each mobile device, I just want a one time password.
I tried using the auth system built into drf, however it required a user.
So I was thinking about just using the onetimepass package to generate a one time token.
A:
You can create a view that generates a time-based OTP and then use it in a custom auth module to authenticate against a single user. You can also use JWT with an expiry time to authenticate against a single user.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create a slideshow for top stories
I am looking to create a object that scrolls through different pictures with links to the stories that go with the picture. I am not sure what they are called, but its pretty much a news slideshow with links. Much like the one on leagueoflegends.com, espn.com, liverpoolfc.tv.
Does anyone know where to find a tutorial or something like that? I have not worked with Javascript much before.
A:
You seem to be describing a carousel. There are hundreds of these available for use, including this one that I wrote a while back (it's primarily for video, but is perfectly usable with pictures, too) or JCarousel.
| {
"pile_set_name": "StackExchange"
} |
Q:
rsync с правами sudo
Есть задача - синхронизировать содержимое папки /home/* между двумя серверами.
Команда выглядит следующим образом:
rsync --archive --acls --xattrs --one-file-system -e "ssh -T -c arcfour -o Compression=no -x" --exclude=".*" --size-only --log-file=/home/backup/rsync.log remote@server_dns.ru:/home/* /home/backup/
Бэкап сервер ходит на удаленный сервер через ssh-key под юзера backup.
Но, на удаленном сервере в папке /home/* много пользователей у которых могут быть разные права на чтение их файлов и не принадлежат эти файлы соответственно юзеру или группе backup.
Как выполнить rsync с командой sudo на этом сервере, что бы можно было копировать файлы независимо от их владельца и прав.
Как вариант пробовал всех пользователей добавлять в группу backup и менял всем файлам права на возможность чтения группе. Но за этим нужно постоянно следить и выглядит костыльно.
A:
можно воспользоваться опцией --rsync-path со значением "sudo rsync" (предварительно разрешив на отдалённой машине пользователю, под именем которого подключаемся, выполнять sudo rsync без ввода пароля).
согласно man rsync:
--rsync-path=PROGRAM
Use this to specify what program is to be run on the remote machine to start-up rsync.
вольный перевод:
используйте для указания программы, которая будет выполнена на отдалённом компьютере для запуска rsync.
пример:
на удалённом компьютере создаём файл и делаем его нечитабельным для всех:
$ touch /tmp/file; chmod ugo= /tmp/file
на локальной машине пытаемся скопировать его (от имени рядового пользователя user) и получаем ошибку:
$ rsync user@host:/tmp/file /tmp
rsync: send_files failed to open "/tmp/file": Permission denied (13)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1536) [generator=3.0.9]
а теперь воспользуемся описанной опцией (предварительно разрешив на отдалённой машине пользователю user выполнять sudo rsync без ввода пароля) — и копирование произойдёт успешно:
$ rsync --rsync-path="sudo rsync" user@host:/tmp/file /tmp
| {
"pile_set_name": "StackExchange"
} |
Q:
Почему не печатается часть данных
Есть код в котором из БД берется поле data с архивными и не архивным json строками(1я строка архив, 2я и до 5й json текст, 6я архив. С помощью zlib разархивируется и выводится 1я, 6я строка, а вот json строки пропускает. Надо чтоб выводилось все вместе на экран. Знаю что надо повторно вызвать json.Unmarshal, но все равно не получается. Если кто может, подскажите.Спасибо.
package main
import (
"database/sql"
"log"
_"github.com/go-sql-driver/mysql"
"compress/zlib"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
)
func main() {
db, err := sql.Open("mysql", "name:password@tcp(127.0.0.1:port)/database")
if err != nil {
panic(err.Error())
}
defer db.Close()
rows, err := db.Query(`SELECT data FROM user_stats ORDER BY created_at LIMIT 6`)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var data []byte
err := rows.Scan(&data)
if err != nil {
log.Fatal(err)
}
type UserStatsData struct {
Revenue float64 `json:"r"`
Gold int `json:"g"`
}
userStatsData := UserStatsData{}
if err := json.Unmarshal(data, &userStatsData); err != nil {
r, err := zlib.NewReader(bytes.NewReader(data))
if err != nil {
log.Panicf("\nCannot read archive %v", err);
}
r.Close()
output, _ := ioutil.ReadAll(r)
fmt.Printf("%s\n", output)
}
}
A:
в куске
if err := json.Unmarshal(data, &userStatsData); err != nil {
r, err := zlib.NewReader(bytes.NewReader(data))
у вас дальнейшая обработка происходит только если при чтении json произошло ошибка, т.е. если данные заархивированы.
Я думаю вам нужно что-то примерно следующее:
userStatsData := UserStatsData{}
if err := json.Unmarshal(data, &userStatsData); err != nil {
r, err := zlib.NewReader(bytes.NewReader(data))
if err != nil {
log.Panicf("\nCannot read archive %v", err);
}
r.Close()
data, _ = ioutil.ReadAll(r)
}
fmt.Printf("%s\n", data)
я тут:
Вынес вывод данных за пределы условия о проверке json-валидности
При распаковывании архива подменяю данные из базы на распакованные данные
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a standard for corresponding restful PHP functions?
In a restful API for fruit, the request assumes something like this:
api/fruit
api/fruit?limit=100
api/fruit/1
api/fruit?color=red
I think there must be a standard for functions that do the work. For instance, something may easily translate to fruit.class.php.
fruit.class.php
function get ($id, $params, $limit) {
// query, etc.
}
So for my above examples, the code would look like
api/fruit
$fruit = $oFruit->get();
api/fruit?limit=100
$fruit = $oFruit->get(NULL, NULL, 100);
api/fruit/1
$fruit = $oFruit->get(1);
api/fruit?color=red
$fruit = $oFruit->get(NULL, array('color' => 'red'));
Is there an industry standard like this or are API/database functions always a mess? I’d really like to standardize my functions.
A:
No, there is no standard as others have already answered...however, in answer to your issue about creating too many methods...I usually only have a single search() method that returns 1 or more results based on my search criteria. I usually create a "search object" that contains my where conditions in an OOP fashion that can then be parsed by the data layer...but that's probably more than you want to get into...many people would build their DQL for their data-layer, etc. There are a lot of ways to avoid getById, getByColor, getByTexture, getByColorAndTexture. If you start seeing lots of methods to cover every single possible combination of search, then you're probably doing it wrong.
As to rest method naming...ZF2 is not the answer, but it's the one I"m currently using on my project at work, and its methods are laid out like so (please note, this is HORRIBLE, dangerous code...open to SQL injection...just doing it for example):
// for GET URL: /api/fruit?color=red
public function getList() {
$where = array();
if( isset($_GET['color']) ) {
$where[] = "color='{$_GET['color']}'";
}
if( isset($_GET['texture']) ) {
$where[] = "texture='{$_GET['texture']}'";
}
return search( implode(' AND ',$where) );
}
// for GET URL: /api/fruit/3
public function get( $id ) {
return getById( $id );
}
// for POST URL /api/fruit
public function create( $postArray ) {
$fruit = new Fruit();
$fruit->color = $postArray['color'];
save($fruit);
}
// for PUT URL /api/fruit/3
public function update( $id, $putArray ) {
$fruit = getById($id);
$fruit->color = $putArray['color'];
save($fruit);
}
// for DELETE /api/fruit/3
public function delete( $id ) {
$fruit = getById($id);
delete($fruit);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Trigger a Click event in javascript using c#(WebBrowser control)
Is there any way to call the click function from the c# application
Here's the code that set the function:
$('#connectbtn').unbind('click').attr('disabled', false);
$('#connectbtn').bind('click', function() {
//CODE TO BE EXECUTED
}).removeAttr('disabled');
A:
try it,
ClientScript.RegisterStartupScript(this.GetType(), "DateTimeFromServer", string.Format(@"<script>
$(function () {{
$('#connectbtn').trigger('click','{0}');
}});
</script>", DateTime.Now));
| {
"pile_set_name": "StackExchange"
} |
Q:
Thymeleaf-Spring th:block and th:each does not run again if an error occurs
I am validating a field that is where the name of a role is defined. This is in a form is sent via post. The point is that when an error occurs and call again:
modelAndView.setViewName ("admin/role");
return modelAndView;
It does not regenerate the list of <td> within th: block. But when the process is done correctly, it shows me my normal page.
Successful process:
If an error occurs:
GET METHOD:
@RequestMapping(value = "/admin/role", method = RequestMethod.GET)
public ModelAndView role(Model model){
ModelAndView modelAndView = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
List<Page> pages = pageService.getAllPages();
Role role = new Role();
modelAndView.addObject("role", role);
modelAndView.addObject("pages", pages);
modelAndView.addObject("userName", user.getName());
modelAndView.setViewName("admin/role");
return modelAndView;
}
POST METHOD:
@RequestMapping(value = "/admin/role", method = RequestMethod.POST)
public ModelAndView createNewRole(@Valid Role role,BindingResult bindingResult,
@RequestParam(value = "pgids" , required = false) Integer [] pgids
){
ModelAndView modelAndView = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
modelAndView.addObject("userName", user.getName());
Role roleExist = roleService.findByAuthority(role.getAuthority());
if (roleExist != null){
bindingResult
.rejectValue("authority","error.app_role", "There is already a role registered with the name provided");
}
if (bindingResult.hasErrors()){
modelAndView.setViewName("admin/role");
}else{
if(pgids != null) {
for (int i = 0; i < pgids.length; i++) {
System.out.println(pgids[i]);
}
}
roleService.saveRole(role, pgids);
List<Page> pages = pageService.getAllPages();
modelAndView.addObject("successMessage", "Role has been created successfully");
modelAndView.addObject("role", new Role());
modelAndView.addObject("pages", pages);
modelAndView.setViewName("admin/role");
}
return modelAndView;
}
HTML Form
<form autocomplete="off" action="#" th:action="@{/admin/role}" method="post" role="form">
<div class="row">
<div class="col-md-12 bottommargin-sm">
<label>Name of the Role</label>
<label class="errormsg" th:if="${#fields.hasErrors('role.authority')}" th:errors="${role.authority}"></label>
<input type="text" th:field="${role.authority}" class="sm-form-control"
placeholder="Example Name"/>
</div>
<div class="col-md-12">
<label>Catalogue of Pages</label>
<table class="table table-hover">
<thead>
<tr>
<th class="col-sm-2 center">Asign</th>
<th class="col-sm-4 center">Name</th>
<th class="col-sm-6 center">URL</th>
</tr>
</thead>
<tbody>
<th:block th:each="page : ${pages}">
<tr>
<td class="col-sm-2 center">
<input type="checkbox" name="pgids" th:value="${page.id}"/>
</td>
<td class="col-sm-4 center" th:utext="${page.name}"></td>
<td class="col-sm-6 center" th:utext="${page.url}"></td>
</tr>
</th:block>
</tbody>
</table>
<button type="submit" class="button nomargin rightmargin-sm button-reef-blue">Create
</button>
</div>
<div class="col-sm-12">
<label th:utext="${successMessage}" class="successmsg"></label>
</div>
</div>
UPDATE
As mentioned in the bottom, it was my mistake not to add the variable pages once it enters bindingResult.hasErrors (). So that 'if' is as follows:
if (bindingResult.hasErrors()){
List<Page> pages = pageService.getAllPages();
modelAndView.addObject("pages", pages);
modelAndView.setViewName("admin/role");
}
A:
When you submit the form with invalid data
bindingResult.hasErrors()
will return true and you do not enter the section of code where you add the pages due to your if/else clause.
So the variable
pages
contains no data and your th:each loop will do nothing.
If you want to print the pages even when invalid data was entered you could just remove your else.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bluez crashes after pairing an with my BLE Remote
I have a Bluetooth remote that I have used before on another system and now running the 4.52 BLUEZ I get an error in bluetoothctl as soon as I paired with the remote.
Connecting to the bluetooth ctl
pi@marcophone:~$ sudo bluetoothctl
Agent registered
[CHG] Controller B8:27:EB:1B:C4:00 Pairable: yes
[CHG] Device 20:C3:8F:BD:93:40 Connected: yes
[Remote RC]# trust
Changing 20:C3:8F:BD:93:40 trust succeeded
Here I successfully connected to the remote
[RC]# pair
Attempting to pair with 20:C3:8F:BD:93:40
[CHG] Device 20:C3:8F:BD:93:40 Paired: yes
Pairing successful
Right after this the bluetoothctl looses the connection
[DEL] Descriptor (Handle 0x2ec8)
/org/bluez/hci0/dev_20_C3_8F_BD_93_40/service0008/char0009/desc000b
00002902-0000-1000-8000-00805f9b34fb
Client Characteristic Configuration
[DEL] Characteristic (Handle 0x4cf0)
/org/bluez/hci0/dev_20_C3_8F_BD_93_40/service0008/char0009
00002a05-0000-1000-8000-00805f9b34fb
Service Changed
[DEL] Primary Service (Handle 0x0073)
/org/bluez/hci0/dev_20_C3_8F_BD_93_40/service0008
00001801-0000-1000-8000-00805f9b34fb
Generic Attribute Profile
[DEL] Characteristic (Handle 0x4cf0)
/org/bluez/hci0/dev_20_C3_8F_BD_93_40/service000c/char000d
00002a50-0000-1000-8000-00805f9b34fb
PnP ID
[DEL] Primary Service (Handle 0x0073)
/org/bluez/hci0/dev_20_C3_8F_BD_93_40/service000c
0000180a-0000-1000-8000-00805f9b34fb
Device Information
Agent unregistered
[DEL] Controller B8:27:EB:1B:C4:00 marcophone [default]
Waiting to connect to bluetoothd...con
The Logs:
pi@marcophone:~$ cat /var/log/syslog | grep bluetooth -a
Jan 27 18:39:40 marcophone bluetoothd[1048]: Bluetooth daemon 5.52
Jan 27 18:39:40 marcophone bluetoothd[1048]: Starting SDP server
Jan 27 18:39:40 marcophone systemd[1]: Started Raspberry Pi bluetooth helper.
Jan 27 18:39:40 marcophone bluetoothd[1048]: Bluetooth management interface 1.14 initialized
Jan 27 18:39:40 marcophone bluetoothd[1048]: Endpoint registered: sender=:1.21 path=/A2DP/SBC/Source/1
Jan 27 18:39:40 marcophone bluetoothd[1048]: Failed to set privacy: Rejected (0x0b)
Jan 27 18:41:07 marcophone bluetoothd[1048]: No cache for 20:C3:8F:BD:93:40
Jan 27 18:41:12 marcophone bluetoothd[1048]: Protocol Mode characteristic read failed: Request attribute has encountered an unlikely error
Jan 27 18:41:13 marcophone bluetoothd[1048]: Report Map read failed: Request attribute has encountered an unlikely error
Jan 27 18:41:13 marcophone bluetoothd[1048]: Read External Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:13 marcophone bluetoothd[1048]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:13 marcophone bluetoothd[1048]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:13 marcophone bluetoothd[1048]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:13 marcophone bluetoothd[1048]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:13 marcophone bluetoothd[1048]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:13 marcophone bluetoothd[1048]: HID Information read failed: Request attribute has encountered an unlikely error
Jan 27 18:41:24 marcophone bluetoothd[1048]: Protocol Mode characteristic read failed: Request attribute has encountered an unlikely error
Jan 27 18:41:24 marcophone bluetoothd[1048]: Report Map read failed: Request attribute has encountered an unlikely error
Jan 27 18:41:24 marcophone bluetoothd[1048]: Read External Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:24 marcophone bluetoothd[1048]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:24 marcophone bluetoothd[1048]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:24 marcophone bluetoothd[1048]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:24 marcophone bluetoothd[1048]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:24 marcophone bluetoothd[1048]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:41:24 marcophone bluetoothd[1048]: Error storing included service - can't find it
Jan 27 18:41:24 marcophone systemd[1]: bluetooth.service: Main process exited, code=killed, status=11/SEGV
Jan 27 18:41:24 marcophone systemd[1]: bluetooth.service: Unit entered failed state.
Jan 27 18:41:24 marcophone systemd[1]: bluetooth.service: Failed with result 'signal'.
Jan 27 18:43:07 marcophone bluetoothd[356]: Bluetooth daemon 5.52
Jan 27 18:43:07 marcophone bluetoothd[356]: Starting SDP server
Jan 27 18:43:08 marcophone systemd[1]: Started Raspberry Pi bluetooth helper.
Jan 27 18:43:08 marcophone bluetoothd[356]: Bluetooth management interface 1.14 initialized
Jan 27 18:43:08 marcophone bluetoothd[356]: Endpoint registered: sender=:1.5 path=/A2DP/SBC/Source/1
Jan 27 18:43:08 marcophone bluetoothd[356]: Failed to set privacy: Rejected (0x0b)
Jan 27 18:45:11 marcophone bluetoothd[356]: No cache for 20:C3:8F:BD:93:40
Jan 27 18:45:11 marcophone bluetoothd[356]: BATT attribute not found
Jan 27 18:45:11 marcophone bluetoothd[356]: batt-profile profile accept failed for 20:C3:8F:BD:93:40
Jan 27 18:45:11 marcophone bluetoothd[356]: GAP attribute not found
Jan 27 18:45:11 marcophone bluetoothd[356]: gap-profile profile accept failed for 20:C3:8F:BD:93:40
Jan 27 18:45:11 marcophone bluetoothd[356]: input-hog profile accept failed for 20:C3:8F:BD:93:40
Jan 27 18:45:14 marcophone bluetoothd[356]: HID Information read failed: Request attribute has encountered an unlikely error
Jan 27 18:45:14 marcophone bluetoothd[356]: Protocol Mode characteristic read failed: Request attribute has encountered an unlikely error
Jan 27 18:45:14 marcophone bluetoothd[356]: Report Map read failed: Request attribute has encountered an unlikely error
Jan 27 18:45:14 marcophone bluetoothd[356]: Read External Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:14 marcophone bluetoothd[356]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:14 marcophone bluetoothd[356]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:14 marcophone bluetoothd[356]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:14 marcophone bluetoothd[356]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:14 marcophone bluetoothd[356]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:17 marcophone bluetoothd[356]: HID Information read failed: Request attribute has encountered an unlikely error
Jan 27 18:45:17 marcophone bluetoothd[356]: Protocol Mode characteristic read failed: Request attribute has encountered an unlikely error
Jan 27 18:45:17 marcophone bluetoothd[356]: Report Map read failed: Request attribute has encountered an unlikely error
Jan 27 18:45:17 marcophone bluetoothd[356]: Read External Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:17 marcophone bluetoothd[356]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:18 marcophone bluetoothd[356]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:18 marcophone bluetoothd[356]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:18 marcophone bluetoothd[356]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:18 marcophone bluetoothd[356]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:45:18 marcophone bluetoothd[356]: Error storing included service - can't find it
Jan 27 18:45:18 marcophone systemd[1]: bluetooth.service: Main process exited, code=killed, status=11/SEGV
Jan 27 18:45:18 marcophone systemd[1]: bluetooth.service: Unit entered failed state.
Jan 27 18:45:18 marcophone systemd[1]: bluetooth.service: Failed with result 'signal'.
Jan 27 18:54:00 marcophone bluetoothd[358]: Bluetooth daemon 5.52
Jan 27 18:54:00 marcophone bluetoothd[358]: Starting SDP server
Jan 27 18:54:00 marcophone systemd[1]: Started Raspberry Pi bluetooth helper.
Jan 27 18:54:00 marcophone bluetoothd[358]: Bluetooth management interface 1.14 initialized
Jan 27 18:54:01 marcophone bluetoothd[358]: Endpoint registered: sender=:1.5 path=/A2DP/SBC/Source/1
Jan 27 18:54:01 marcophone bluetoothd[358]: Failed to set privacy: Rejected (0x0b)
Jan 27 18:55:30 marcophone bluetoothd[358]: No cache for 20:C3:8F:BD:93:40
Jan 27 18:55:30 marcophone bluetoothd[358]: BATT attribute not found
Jan 27 18:55:30 marcophone bluetoothd[358]: batt-profile profile accept failed for 20:C3:8F:BD:93:40
Jan 27 18:55:30 marcophone bluetoothd[358]: GAP attribute not found
Jan 27 18:55:31 marcophone bluetoothd[358]: gap-profile profile accept failed for 20:C3:8F:BD:93:40
Jan 27 18:55:31 marcophone bluetoothd[358]: input-hog profile accept failed for 20:C3:8F:BD:93:40
Jan 27 18:55:36 marcophone bluetoothd[358]: Protocol Mode characteristic read failed: Request attribute has encountered an unlikely error
Jan 27 18:55:36 marcophone bluetoothd[358]: Report Map read failed: Request attribute has encountered an unlikely error
Jan 27 18:55:36 marcophone bluetoothd[358]: Read External Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:36 marcophone bluetoothd[358]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:36 marcophone bluetoothd[358]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:36 marcophone bluetoothd[358]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:36 marcophone bluetoothd[358]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:36 marcophone bluetoothd[358]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:36 marcophone bluetoothd[358]: HID Information read failed: Request attribute has encountered an unlikely error
Jan 27 18:55:47 marcophone bluetoothd[358]: Protocol Mode characteristic read failed: Request attribute has encountered an unlikely error
Jan 27 18:55:47 marcophone bluetoothd[358]: Report Map read failed: Request attribute has encountered an unlikely error
Jan 27 18:55:47 marcophone bluetoothd[358]: Read External Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:47 marcophone bluetoothd[358]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:47 marcophone bluetoothd[358]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:47 marcophone bluetoothd[358]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:47 marcophone bluetoothd[358]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:47 marcophone bluetoothd[358]: Read Report Reference descriptor failed: Request attribute has encountered an unlikely error
Jan 27 18:55:48 marcophone bluetoothd[358]: Error storing included service - can't find it
Jan 27 18:55:48 marcophone systemd[1]: bluetooth.service: Main process exited, code=killed, status=11/SEGV
Jan 27 18:55:48 marcophone systemd[1]: bluetooth.service: Unit entered failed state.
Jan 27 18:55:48 marcophone systemd[1]: bluetooth.service: Failed with result 'signal'.
Hciconfig
pi@marcophone:~$ hciconfig -a
hci0: Type: Primary Bus: UART
BD Address: B8:27:EB:1B:C4:00 ACL MTU: 1021:8 SCO MTU: 64:1
UP RUNNING
RX bytes:2850 acl:94 sco:0 events:117 errors:0
TX bytes:3820 acl:92 sco:0 commands:62 errors:0
Features: 0xbf 0xfe 0xcf 0xfe 0xdb 0xff 0x7b 0x87
Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
Link policy: RSWITCH SNIFF
Link mode: SLAVE ACCEPT
Name: 'marcophone'
Class: 0x480000
Service Classes: Capturing, Telephony
Device Class: Miscellaneous,
HCI Version: 4.1 (0x7) Revision: 0x168
LMP Version: 4.1 (0x7) Subversion: 0x2209
Manufacturer: Broadcom Corporation (15)
Versions:
pi@marcophone:~$ sudo bluetoothctl -v
sudo: Hostname marcophone kann nicht aufgelöst werden
bluetoothctl: 5.52
pi@marcophone:~$
Also I should see an entry here: /dev/input/event* but there is only /dev/input/mice.
I know that I got this working in bluez 5.50 so it could be an issue in bluez 5.52.
Doing the research I did add the following three options to my /lib/systemd/system/bluetooth.service:
ExecStart=/usr/libexec/bluetooth/bluetoothd --compat --noplugin=sap -E
A:
I got this working on another machine. However that machine runs raspbian buster (4.19.97+ #1294 Thu Jan 30 13:10:54 GMT 2020 armv6l GNU/Linux).
I got some troubles connecting and paring with the remote so I did the following which finally got it working:
Update the system
sudo apt update && sudo apt upgrade
Update to the latest bluez stack
sudo apt-get remove bluez
date && sudo apt-get update && sudo apt-get install libdbus-1-dev libglib2.0-dev libudev-dev libical-dev libreadline-dev -y &&
date && wget www.kernel.org/pub/linux/bluetooth/bluez-5.52.tar.xz && tar xvf bluez-5.52.tar.xz &&
date && cd bluez-5.52 && ./configure --prefix=/usr --mandir=/usr/share/man --sysconfdir=/etc --localstatedir=/var --enable-experimental && make -j4 && sudo make install && date && sudo reboot
Now update the ExecStart part of the service /lib/systemd/system/bluetooth.service as follows:
ExecStart=/usr/lib/bluetooth/bluetoothd --compat --noplugin=sap -E
Also update the /etc/bluetooth/main.conf and set Privacy = off in [General] section.
| {
"pile_set_name": "StackExchange"
} |
Q:
Ubuntu Heating Up, Continuos Fan, Hadoop Installation Worries on AMD 64
I have a laptop,
Model: Compaq Presario CQ40, RAM: 2.7 GB RAM, Processor: AMD Athlon X2 Dual Core QL - 64*2, Ubuntu 12.04.3 LTS 64 bit and Windows Vista 32 bit (Factory Installed)
My laptop gets heated up a lot when I am using Ubuntu and the fan runs continuously (I have not chosen "Continuously On" mode for the fan in BIOS settings) .
I am using Jupiter with Power Saving mode as of now, and the heat has reduced a bit. Also I am using Ubuntu2D instead of the default option while logging in.
The temperature is 65+ degrees C when I am not doing much on my machine and gradually increases to 75+ when doing several things at once. I intend to use CDH Hadoop in Pseudo Distributed mode on my machine. I can guess what the temperature will shoot up to then because it uses JVMs. What are the possible things I can do to reduce heat and the fan noise?
Note:
My laptop model is not listed at www.linux-laptop.net, does that mean my laptop is "Linux-challenged"?
My main intention is to use Hadoop, I ll be happy if anyone can guide me which distro is compatible with my machine.
A:
Power management in general is not as good as Linux as it is on Windows in my experience. However, here are some things you can try:
Install TLP: http://www.webupd8.org/2013/04/improve-power-usage-battery-life-in.html
Incorporate appropriate changes from vodik powersave: https://github.com/vodik/powersave
Use sudo powertop and make sure all the tunables are "Good"
Try searching on net for power optimisations for your specific laptop model
If you have hybrid graphics, enable power saving by disabling the discrete card when not required: https://wiki.archlinux.org/index.php/hybrid_graphics#ATI_Dynamic_Switchable_Graphics
Even after all this, my laptop runs slightly warmer than on Windows, and battery life is not as good. However, it's not that bad, certainly usable. Your mileage may vary.
| {
"pile_set_name": "StackExchange"
} |
Q:
sending https request with socket in python
I'm trying to send an https requests using socket in python, however I'm facing this error even when I tried to use the snippet in the documentations to test if the issue is in my code or maybe somewhere else. here is the snippet I took from the documentations :
import socket
import ssl
hostname = 'www.python.org'
context = ssl.create_default_context()
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
print(ssock.version())
and here is the error I'm getting :
Traceback (most recent call last):
File "file.py", line 7, in <module>
with socket.create_connection((hostname, 443)) as sock:
AttributeError: __exit__
am I missing something here ? , I need to use sockets not requests or any other library
A:
For python 2.7 you need to do the following:
import socket
import ssl
hostname = 'www.python.org'
context = ssl.create_default_context()
sock = socket.create_connection((hostname, 443))
ssock = context.wrap_socket(sock, server_hostname=hostname)
print(ssock.version())
| {
"pile_set_name": "StackExchange"
} |
Q:
escribir en un edit text y que automaticamente se refleje en un edittext
Voy a comenzar un nuevo proyecto, en el cual el usuario escribe en un edittext y automaticamente lo que pone se ve reflejado en el textview.
Se os ocurre alguna manera de llevarlo a cabo?
A:
Haciendo uso de TextWatcher:
tuEdittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
if(editText.getText().length() >= 0) {
tuTextView.setText(editText.getText().toString())
}
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Responsive web design - Bootstrap
This may be so basic but I like to be certain about this.
I am using bootstrap for my frontend. But after testing my page, it realize it is not responsive in a way since some of the elements are flying else where when I reduce the size of my browser.
I thought bootstrap automatically makes the web page responsive. Do I have to use standard class name for my forms to make it accurately responsive?
PS: Learning how to make web pages responsive
A:
You need to learn to use the bootstrap grid system. Bootstrap does not make it responsive on its own.
check out these links:
https://www.w3schools.com/bootstrap/bootstrap_grid_basic.asp
https://v4-alpha.getbootstrap.com/layout/responsive-utilities/
| {
"pile_set_name": "StackExchange"
} |
Q:
Props is still empty after mapStateToProps
I'm working in a mern stack app and when I try to pass the state to specific component's props I get errors.
I get the error:
TypeError: Cannot read property 'items' of undefined
D:/Mohammed/project/mern-app/client/src/components/ShoppingList.js:19
16 | this.props.deleteItem(id);
17 | }
18 |
> 19 | render() {
| ^ 20 | const { items } = this.props.item;
21 | return (
22 | <div>
here's the repo for my code:
https://github.com/mohamedsaad4/mern-app
Here's mern-app/client/src/App.js
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Navbars } from './components/Navbar';
import { ShoppingList } from './components/ShoppingList';
import { Provider } from 'react-redux';
import store from './store';
class App extends Component {
render() {
return (
<Provider store={store}>
<div className="App">
<Navbars />
<ShoppingList />
</div>
</Provider>
);
}
}
export default App;
and here's mern-app/client/src/components/ShoppingList.js
import React, { Component } from 'react';
import { Container, ListGroup, ListGroupItem, Button } from 'reactstrap';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import { connect } from 'react-redux';
import { getItems, deleteItem } from '../actions/itemActions';
import PropTypes from 'prop-types';
export class ShoppingList extends Component {
componentDidMount() {
this.props.getItems();
}
deleteClick = (id) => {
this.props.deleteItem(id);
}
render() {
const { items } = this.props.item;
return (
<div>
<Container>
<ListGroup>
<TransitionGroup className="shopping-list">
{
items.map(({id, name}) => (
<CSSTransition key={id} timeout={500} classNames='fade'>
<ListGroupItem>
<Button
className='remove-btn'
color='danger'
size='sm'
onClick={this.deleteClick.bind(this, id)}
>×</Button>
{name}
</ListGroupItem>
</CSSTransition>
))
}
</TransitionGroup>
</ListGroup>
</Container>
</div>
)
}
}
ShoppingList.propTypes = {
getItems: PropTypes.func.isRequired,
item: PropTypes.object.isRequired
}
const mapStateToProps = (state) => {
return {
item: state.item
}
}
export default connect(mapStateToProps, { getItems, deleteItem })(ShoppingList);
and here's mern-app/client/src/store.js
import { compose, applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const initialState = {};
const middleware = [thunk];
const store = createStore(rootReducer, initialState, compose(
applyMiddleware(...middleware)
));
export default store;
and here's mern-app/client/src/actions/itemActions.js
import { GET_ITEMS, ADD_ITEM, DELETE_ITEM } from './types';
export const getItems = () => {
return {
type: GET_ITEMS
};
};
export const deleteItem = (id) => {
return {
type: DELETE_ITEM,
payload: id
};
};
and here's mern-app/client/src/actions/types.js
export const GET_ITEMS = 'GET_ITEMS';
export const ADD_ITEM = 'ADD_ITEM';
export const DELETE_ITEM = 'DELETE_ITEM';
and here's mern-app/client/src/reducers/index.js
import { combineReducers } from 'redux';
import itemReducer from './itemReducer';
export default combineReducers({
item: itemReducer
});
and finally here's mern-app/client/src/reducers/itemReducer.js
import uuid from 'uuid';
import { GET_ITEMS, ADD_ITEM, DELETE_ITEM } from '../actions/types';
const initialState = {
items: [
{id: uuid(), name: 'ali'},
{id: uuid(), name: 'amgad'},
{id: uuid(), name: 'nour'},
]
};
export default function(state = initialState, action) {
switch(action.type) {
case GET_ITEMS:
return {
...state
}
case DELETE_ITEM:
return {
...state,
items: state.items.filter(item => item.id !== action.payload)
}
default:
return state;
}
}
A:
You're mismatching the connected component imports and exports.
In ShoppingList.js, you have:
// Named export
export class ShoppingList extends Component {}
// Default export
export default connect(mapStateToProps, { getItems, deleteItem })(ShoppingList);
In App.js, you have:
// Named import
import { ShoppingList } from './components/ShoppingList';
So, you're importing the unconnected version of ShoppingList and using it.
Change that to be a default import so that you get the connected version of the component, and it should work:
import ShoppingList from './components/ShoppingList';
| {
"pile_set_name": "StackExchange"
} |
Q:
Text Clause Explanation
I'm working with the following code which I discovered on a third party website to help with concatenating some data (the code works, I'm just attempting to understand it better). However, I'm having trouble (new to SQL) discerning the purposes of the "[text()]" clause in line 4, and (' ') in line 8.
SELECT DISTINCT ST2.[Financial Number],
SUBSTRING(
(
SELECT ','+ST1.[Clinical Event Result] AS [text()]
FROM ED_FCT_Q1_FY19 ST1
WHERE ST1.[Financial Number] = ST2.[Financial Number]
Order BY [Financial Number]
FOR XML PATH ('')
), 2, 1000) [Clinical]
FROM ED_FCT_Q1_FY19 ST2
A:
According to the documentation, when using PATH mode of FOR XML,
For a column with the name of text(), the string value in that column
is added as a text node
So in this case, the column is not treated as an column name alias as it would be in a normal SELECT query, but used for the purpose of XML mapping.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set selected item for Spinner in Android
In an Android app, I have a SpinnerAdapter that I am using to display expiration years of credit cards. My variable expirationYears contains an array of Strings with years from "2020" to "2029". It was declared as String[] expirationYears = new String[10]; and then with a function I set the ten years as Strings, from current year and then the nine subsequent years after that for a total of ten elements in the array. When I run it, this is what I see:
Everything is perfect so far. The only problem is that when as you see in the image above, 2020 is the year selected by default. That is the first element in the expirationYears array. But I want to set 2021 as default (the second element of the array). This is what my code has:
Spinner spinnerYearCreditCardPayment;
SpinnerAdapter creditCardYearAdapter = new SpinnerAdapter(Payment.this, expirationYears);
creditCardYearAdapter
.setDropDownViewResource(android.R.layout.spinner_dropdown_item);
spinnerYearCreditCardPayment.setAdapter(creditCardYearAdapter);
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
..........
});
I was expecting to have some property available to define which element I want to show by default. Something like creditCardYearAdapter.setSelectedItem(INDEX_NUMBER). But that property does not exist. Do you know how I could set the default selected item so that it is not the first element of the array (2020) but the second (2021)? Thank you.
UPDATE 1:
Following The_Martian's answer, this was what I did:
spinnerYearCreditCardPayment
.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
arg0.setSelection(1);
cardYear = (String) spinnerYearCreditCardPayment
.getSelectedItem();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Now I correctly see the second element of the array ("2021") as the default selection.
The problem is that when I use arg0.setSelection(1);, I choose another year and it does not respond. The selected year remains "2021" even thought I am trying to change the year.
A:
You can do similar to the following. I am just giving you an idea here.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.setSelection(position + 1);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Would anybody know why these elements appear in mobile site?
I'm trying to find a way to get rid of two elements from the mobile version of my page https://newsotuniverse.blogspot.ca/ to no avail. The two elements 'Newsletter' and 'Threetabs' continue to appear on my mobile site no matter what I do. Anybody got any ideas how I can get rid of them (on the mobile site) while having them show up on the desktop site?
Just a little snippet of the code (take a full glance on my page by inspecting the elements):
<form action='https://feedburner.google.com/fb/a/mailverify?uri=NewsOfTheUniverse&loc=en_US' class='sub-dd' method='post' onsubmit='window.open('https://feedburner.google.com/fb/a/mailverify?uri=NewsOfTheUniverse&loc=en_US, 'popupwindow', scrollbars=yes,width=550,height=520');return true' target='popupwindow'>
<h5><b>Subscribe</b> <i>to</i> Newsletter </h5>
<input class='lite' name='email' placeholder='Enter your Email' type='text'/> <input name='uri' type='hidden' value='News of the Universe'/><input name='loc' type='hidden' value='en_US'/>
<input class='buter' type='submit' value='Submit'/> </form>
<div class='threetabs' >
<ul class='tabber wrap-tabs'>
<li class='keez'><a href='#id2'>Popular Posts</a></li>
<li class='keez'><a href='#id3'>Comments</a></li>
<li class='keez'><a href='#id4'>Category</a></li>
</ul>
<div class='clear'/>
Here's the CSS:
.ct-wrapper {background:#fff; padding:0px 0px; position:relative; margin: 0px;}
.outer-wrapper {background-image: url("https://cdn.spacetelescope.org/archives/images/screen/potw1209a.jpg"); position: relative; padding:0px 0 }
.header-wrapper {display: inline-block; float: left; padding: 0; width: 100%; -moz-box-sizing: -webkit-border-box; box-sizing: border-box; }
.main-wrapper {background:#fff; width:75%; float:left;}
#content { box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; position: relative;}
.main-inner-wrap {padding:0 16px; margin: 0px; border-right:1px solid #eee; border-left:1px solid #eee; background:$(post.background.color); float:right; position: relative; width:76.2%;}
.sidebar-wrapper { background:#fff; width:325px; float: right;}
.leftbar-wrapper{width:160px; float: left;}
.container {margin: 0 auto; margin-top: 100px padding: 0 15px; position: relative; max-width: 1300px; display:flex;}
.containerr {margin: 0 auto; margin-top: 100px padding: 0 15px; position: relative; max-width: 1300px;}
body#layout #top-nav { margin-top: 40px; }
body#layout #header, body#layout .header-right { width: 46%; }
body#layout .main-wrapper {width:69%; }
body#layout .main-inner-wrap {width:64%; }
body#layout .sidebar-wrapper {width:30%; }
body#layout .widget-content { margin: 0; }
body#layout .footer {width:30%;}
body#layout .outer-wrapper, body#layout .main-inner-wrap, body#layout .sidebar-wrapper, body#layout .ct-wrapper { margin: 0; padding: 0; }
.ct-wrapper, .crosscol, .post, .sidebar-wrapper, .buzed{overflow:hidden;}
And here's the Mobile code:
@media screen and (-webkit-min-device-pixel-ratio:0) {
#peekar button {padding:5px 9px;}
.post-meat :after {right: -7px;}
}
@media (max-width: 1180px) {
.ct-wrapper{margin:0 auto;}
#header {width: 25%;}
.main-wrapper{width:71.3%;}
.main-inner-wrap{width:73%;}
.doze li:first-child{width:46%;}
.ganed li{width:31.2%;}
blockquote:before{margin: 2% 14px 0 0;}
.bukshan{width:34%;}
.btf-thumb li{width:24% !important;}
.footer{width:31.2%;}
.post-title{font-size:22px}
#related-article ul li{width:31.9%;}
#related-article img {height: 120px;}
}
@media (max-width: 1040px) {
.main-wrapper {width: 69.4%;}
.main-inner-wrap {width: 71.8%; border:0;}
.doze li:first-child{width:44%;}
.ganed li {width: 30.8%;}
.bukshan{width:38%; margin-right:12px;}
#related-article ul li{width:31.6%;}
}
@media (max-width: 1000px) {
#header {width: 30%;}
.menu li a{padding:13px 13px;}
.main-wrapper {width:100%}
.main-inner-wrap {width: 79.9%; padding:25px 0px 0 14px;}
.sidebar-wrapper{float:left;}
.bukshan{width:34%;}
.doze li:first-child{width:46%;}
.doze li{width:47.4%;}
.ganed li {width: 31.6%;}
#related-article ul li{width:32.2%;}
.footer{width:31%;}
.footer-credits .attribution{text-align:center;}
.deen{float:none;}
}
@media (max-width: 970px) {
.btf-thumb li{width:23.4% !important;}
#related-article ul li{width:32%;}
}
@media (max-width: 800px) {
.menu, .Pagemenu {display: none;}
.resp-desk,.resp-desk1 {display: block; margin-top:0px;}
.mainWrap {width: 768px;}
#navigation.fixed-nav{position:unset;}
nav {margin: 0; background: none;}
.main-nav{background:none; border-bottom:none;}
.Pagemenu li a, .Pagemenu li a:hover, .Pagemenu li a.home{background:rgb(42,46,49); color:#fff; border:0; margin:0;}
.menu {width:100%; text-align:center;}
.menu li, .Pagemenu li{display: block; margin: 0;}
.menu ul li a{margin-left:25px; border:0; color:#909090;}
.menu li a{border:0; color: #909090;}
.menu li a:hover,.menu li:hover>a, .menu ul li a, .menu ul li a:hover,.menu ul li:hover>a {background:rgb(54, 59, 63); color: #909090;}
.menu ul {visibility: hidden; border-bottom:0; opacity: 0; top: 0; left: 0; padding:0; width: 100%; background:none; transform: initial;}
.menu li:hover>ul {visibility: visible; opacity: 1; position: relative; transform: initial;}
.menu ul ul {left: 0; transform: initial;}
.menu li>ul ul:hover {transform: initial;}
.with-ul::after{top:auto; margin:7px 0 0 6px; border-color: #909090 transparent transparent;}
.menu ul::after, .menu ul ul::after{border:0;}
.btf-thumb{display:none;}
.boped{float:none;}
#peekar{}
.social-ico{margin-top:-42px;}
}
@media (max-width: 800px) {
#header {width: 45%;}
.header-right {display:block; }
.ct-wrapper{ padding:0 0px;}
.main-wrapper {}
.main-inner-wrap {width: 75.4%;}
.doze li:first-child{width:44%;}
.ganed li {width: 31%;}
#related-article ul li {width: 31.8%;}
.bukshan{width: 32%;}
.footer{width:30.6%;}
}
@media (max-width: 700px) {
#header{width: 70%;}
.header-right{display:none;}
.sidebar-wrapper{}
.main-wrapper {width: 100%;}
.main-inner-wrap{padding:25px 0 0; width:100%;}
.bukshan{width: 38%;}
.footer{width:46.4%;}
#bont{width:20%;}
.fence{display:none;}
.doze li:first-child{width:45%;}
.doze li{width:47%;}
#related-article ul li{width:31.9%;}
}
@media (max-width: 600px) {
}
@media (max-width: 500px) {
.bukshan {width: 34%; height:100px; margin-right:12px;}
.doze li:first-child{width:100%; padding:0; background:none;}
.doze li{width:100%;}
.doze li:first-child .inner-content h2 a{color:#444;}
.doze li:first-child .inner-content h2 a:hover{color:$(link.color);}
.sit{display:none;}
.footer {width: 96%;}
.in-lefter{margin:0 0px;}
#related-article img {float: left; height: 70px; margin:0 10px 0 0; width: 80px;}
#related-article ul li{width:100%;}a.related-title{text-align:left;}
.ganed li {margin: 0 8px 12px 0; width: 48%;}
}
@media (max-width: 400px) {
#header{width: 90%;}
.container{padding:0 8px;}
.bukshan {width:38%}
#peekar input{}
#carousel ul li{width:310px !important;}
.footer {width: 94%;}
.ganed li {margin: 0 0px 12px; width: 100%;}
span.categi{display:none;}
}
@media (max-width: 300px) {
#header img{width:100%;}
.sidebar-wrapper{}
.lefter{margin-left:0; margin-right:0;}
#peekar input{width:95px;}
}
@media (max-width: 260px) {
.container{padding:0 3px;}
.sidebar-wrapper{width:240px;}
#peekar{display:none;}
#carousel ul li{width:240px !important;}
.bukshan{width:100%; margin-bottom:5px;}
A:
Just do this:
@media (max-width: 500px) {
/* .threetabs, .newsletter{
display:none; // or opacity 0, but then the space will still be taken
}*/
.sidebar-wrapper { display: none !important;}
@media (min-width: 500px) {
.sidebar-wrapper {
display:block; // or opacity 1
}
You can also set this in JS, but this will do.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I pull a Python package from private authenticated Artifactory PyPI repository?
I'm trying to pip or pipenv install a Python package I pushed to my organisation's private PyPI repository hosted on JFrog Artifactory.
From the Artifactory documentation http://<username>:<password>@hostname... should work. I've tried my login password and the one that gets derived from it in the Set Me Up tool within the Artifact Repository Browser.
The following commands ask for username and password but I don't want to enter them from the command line as these are going to be passed into the CI pipeline with environment variables. If I type the username and password at the prompt then it works OK.
$ pip search package-name --index https://user:[email protected]/organisation/api/pypi/pypi/simple
User for organisation.jfrog.io:
$ pip install --extra-index-url https://user:[email protected]/organisation/api/pypi/pypi/simple package-name
Looking in indexes: https://pypi.org/simple, https://user:[email protected]/organisation/api/pypi/pypi/simple
Collecting package-name
User for organisation.jfrog.io:
Using curl to attempt HTTP authentication also does not work.
$ curl -i https://user:[email protected]/organisation/api/pypi/pypi/simple/
HTTP/1.1 401 Unauthorized
Content-Type: application/json;charset=ISO-8859-1
Date: Thu, 26 Apr 2018 18:03:39 GMT
Server: Artifactory/5.10.1
WWW-Authenticate: Basic realm="Artifactory Realm"
X-Artifactory-Id: aolshared3a-organisation
X-Node: nginx2a.prod-euw1
Content-Length: 91
Cache-Control: proxy-revalidate
Connection: Keep-Alive
Set-Cookie: BCSI-CS-a61288137a7d35f7=1; Path=/
{
"errors" : [ {
"status" : 401,
"message" : "Authentication is required"
} ]
}
A:
It seems this was a temporary problem with Artifactory. When I run all the code in my original question I get success - no asking for username/password, curl returns results, installing works. Getting in contact with someone in their support team may have helped.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP: If not selecting correctly
I am building a list based off of a CSV file. Here are the two most common lines in the CSV file:
10,11,12,13,14,15,16
12,13,14,15,16,0,0
The file is read line-by-line and stored into the list. Here is the code:
while(($current_line = fgets($find_products, 4096)) !== false) {
list($weight1, $weight2, $weight3, $weight4, $weight5, $weight6, $weight7) = explode(",", $current_line);
}
I look at the value of each item in the list, and print if the value is not 0. Here is the code:
if($weight1 != '0') {
print '<option>'.$weight1.' lb.</option>';
}
if($weight2 != '0') {
print '<option>'.$weight2.' lb.</option>';
}
if($weight3 != '0') {
print '<option>'.$weight3.' lb.</option>';
}
if($weight4 != '0') {
print '<option>'.$weight4.' lb.</option>';
}
if($weight5 != '0') {
print '<option>'.$weight5.' lb.</option>';
}
if($weight6 != '0') {
print '<option>'.$weight6.' lb.</option>';
}
if($weight7 != '0') {
print '<option>'.$weight7.' lb.</option>';
}
Here are the results of the code after it is run on a CSV file with the above two lines:
10 lb.
11 lb.
12 lb.
13 lb.
14 lb.
15 lb.
16 lb.
AND
12 lb.
13 lb.
14 lb.
15 lb.
16 lb.
0 lb.
The 0 lb. should not be showing up based on the value of $weight6 and $weight7. I have printed the values of these two variables, and they appropriately show up as 0. I can also confirm through testing that the if-statement for $weight7 is the culprit, but I have no idea what is causing the issue. Any help would be greatly appreciated!
A:
The reason is that fgets() returns the line with a newline at the end. So $weight7 is "0\r\n" (that's why var_dump says the length is 3), not "\0". You should trim the line before you split it, to remove this.
while(($current_line = fgets($find_products, 4096)) !== false) {
$current_line = trim($current_line);
list($weight1, $weight2, $weight3, $weight4, $weight5, $weight6, $weight7) = explode(",", $current_line);
}
Or you could instead use fgetcsv() rather than fgets(). It automatically trims the line and splits it at the separator, returning an array that you can iterate over.
while ($weights = fgetcsv($find_products)) {
foreach ($weights as $w) {
if ($w != '0') {
echo "<option>$w lb.</option>";
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to pass Bound properties as parameters without manual setup
Here is my App.xaml.cs
protected override Task OnInitializeAsync(IActivatedEventArgs args) {
Container.RegisterInstance(SessionStateService);
Container.RegisterInstance(NavigationService);
Container.RegisterType<IUserRepository, UserRespository>(new ContainerControlledLifetimeManager());
Container.RegisterType<UserSettingsContext>(new ContainerControlledLifetimeManager());
Container.RegisterType<IUserSettings, UserSettings>(new ContainerControlledLifetimeManager());
var userSettings = this.Container.Resolve<UserSettingsContext>();
userSettings.Database.EnsureCreated();
return base.OnInitializeAsync(args);
}
This is my UserSettings
using using Prism.Windows.Validation;
public class UserSettings : ValidatableBindableBase, IUserSettings {
private string _firstName;
public string FirstName {
get { return _firstName; }
set { SetProperty(ref _firstName, value); }
}
private string _lastName;
public string LastName {
get { return _lastName; }
set { SetProperty(ref _lastName, value); }
}
private UserType _userType;
public UserType UserType {
get { return _userType; }
set { SetProperty(ref _userType, value); }
}
private string _username;
[Required(ErrorMessage = "Required.")]
public string Username {
get { return _username; }
set { SetProperty(ref _username, value); }
}
private string _password;
[Required(ErrorMessage = "Required.")]
public string Password {
get { return _password; }
set { SetProperty(ref _password, value); }
}
}
ViewModel:
public class TestViewModel : UserSettings {
private UserSettings user;
public UserSettings User => user;
public async void SaveSettings() {
//It will work with this line
// var user = new UserSettings() {
// Username= this.Username,
// Password= this.Password,
// UserType= this.UserType,
// FirstName= this.FirstName,
// LastName= this.LastName
// };
//null properties
await loginService.SaveUserSettings(user);
}
}
When I tried to pass the 'user' the properties are null ,even user input data from UI(View), It will work if I setup the UserSettings using the code above, but I want to simplify this without that, how can I do that?
Thanks
A:
You want to write await loginService.SaveUserSettings(this); because this seems to be the target that's filled with data.
| {
"pile_set_name": "StackExchange"
} |
Q:
Xamarin Android app out of the box shows undefined Android.Support, Android.Views, Android.Content in MainActivity
I needed to rebuild my fairly ancient Xamarin Forms app from scratch and in the process arrived at a situation where I had a new working iOS app but had needed to delete the draft Android app and start it again. So as a next step I added a vanilla Android app project out of the box and immediately what I saw was that (in MainActivity) Android.Support, Android.Views and Android.Content were undefined with wiggy red lines beneath -- for example in a reference to Android.Support.V7.Widget.Toolbar.
Trying to solve the problem, I set each of Target Framework, Minimum Android Version and Target Android Version to Android 9.0 Pie (API Level 28). In SDK Manager I checked that Android SDK Location and Java SDK Location were 'Found' and that Android SDK Platform 28 was installed.
The following NuGets came installed along with the project, I deleted them and reinstalled them (removing bin/obj folders in between): Xamarin.Android.Support.Core.Utils, Xamarin.Android.Support.CustomTabs and Xamarin.Android.Support.Design.
I tried installing NuGets Xamarin.Android.Support.v7.*. And I added the Xamarin.Forms NuGet. I tried adding 'use' declarations.
None of this helped.
For comparison I separately installed a blank Android app solution-- it worked perfectly out of the box.
Android is pretty new to me - would be grateful for suggestions on fixing this.
The app has a .NET Standard 2.0 project, an iOS project, the (vanilla) Android project (all three with Xamarin Forms), and a .NET Standard 2.0 library project.
I'm using Visual Studio for Mac V8.5.4 (stable) on MacOS 10.15.3.
A:
I noticed that the content of MainActivity.cs is quite different, depending whether the Android project is created separately or as part of a Xamarin Forms solution. Also the provided NuGets are different. So perhaps what I was trying to do, adding an Android app to an existing XF solution, is simply not allowed.
To fix the problem, I created an empty Xamarin Forms solution with Android and iOS projects, added a further empty library project, then in Finder replaced the content of all the project folders, except the Android one, with the content of the corresponding folders in my working solution (the one with a working iOS app).
Migrating to AndroidX is a good idea though.
| {
"pile_set_name": "StackExchange"
} |
Q:
changing rally basic dropdown menus after display
I have a rally.sdk.ui.basic.Dropdown menu in a Rally App that I would like to change based on user input. So I will call display() on the dropdown menu, and then later I want to change the contents of that menu.
Has anybody done this? When I try, it crashes. I've also tried calling destroy() on the dropdown menu and then calling display() on a new menu that I allocate, but that crashes as well with an obscure dojo error.
Any suggestions on how to change dropdown menus on the fly?
I've included a very stripped down example below of trying to destroy and then re-display the menu:
<html>
<head>
<title>Incoming Defects by Severity</title>
<meta http-equiv="X-UA-Compatible" content="IE=7" >
<meta name="Name" content="Defects by Severity" />
<script type="text/javascript" src="https://rally1.rallydev.com/apps/1.29/sdk.js"></script>
<script type="text/javascript">
function DefectChart() {
this.display = function() {
var defectVersionDropdown;
var count = 1;
function makeDefectChart(results){
initDefectVersionDropdown();
};
function renderPage() {
var queryConfig = [];
var startDate = '2011-06-06';
var endDate = '2012-02-02';
var queryArray = ['CreatedDate >= "' + startDate + '"', 'CreatedDate <= "' + endDate + '"'];
var versionFilter = defectVersionDropdown ? defectVersionDropdown.getDisplayedValue() : 'ALL';
if (versionFilter != 'ALL') {
queryArray.push('FoundInBuild contains "' + versionFilter + '"');
}
// console.log(queryArray);
queryConfig.push({
type : 'Defects',
key : 'defects',
query: rally.sdk.util.Query.and(queryArray),
fetch: 'Severity,State,LastUpdateDate,CreationDate,OpenedDate,AcceptedDate,LastUpdateDate,ClosedDate,Environment,FoundInBuild'
});
rallyDataSource.findAll(queryConfig, makeDefectChart);
}
function defectVersionChange(sender, eventArgs) {
var version = eventArgs.value;
renderPage();
}
function initDefectVersionDropdown() {
if (defectVersionDropdown != null) {
defectVersionDropdown.destroy();
defectVersionDropdown = null;
}
if (defectVersionDropdown == null) {
console.log('initDefectVersionDropdown');
count++;
var menuItems = [{label: "ALL", value: "ALL"}];
for (var i=0; i < count; i++) {
menuItems.push({label: count, value: count});
}
var config = {
label: "Found In Version:",
items: menuItems
};
defectVersionDropdown = new rally.sdk.ui.basic.Dropdown(config);
defectVersionDropdown.addEventListener("onChange", defectVersionChange);
defectVersionDropdown.display("defectVersionDiv");
}
}
var workspaceOid = '__WORKSPACE_OID__'; if (workspaceOid.toString().match(/__/)) { workspaceOid = XXX; }
var projectOid = '__PROJECT_OID__'; if (projectOid.toString().match(/__/)) { projectOid = XXX; }
rallyDataSource = new rally.sdk.data.RallyDataSource( workspaceOid,
projectOid,
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
initDefectVersionDropdown();
renderPage();
}
}
function getDataAndShow() {
var defectChart = new DefectChart();
defectChart.display();
}
function loadRally() {
rally.addOnLoad(getDataAndShow);
}
loadRally();
</script>
</head>
<body>
<div id="defectVersionDiv"></div>
</body>
</html>
A:
Destroying the old one creating and displaying a new one is the correct way to do this. This is a common pattern when developing apps using the App SDK. If you provide a code snipped along with the dojo error you are getting the community can probably be of better assistance.
| {
"pile_set_name": "StackExchange"
} |
Q:
Arabic Problem Replace أً with just ا
How to replace the alf bel tanween with a normal alf
A:
I don't know C#, but that's more a UNICODE question. I would do it by means of UNICODE normalization, using this function.
First, normalize to decomposed form. Next, filter out all characters from the "Mark, Nonspacing" category [Mn]. Finally, normalize back to composed form.
If I see correctly, your glyph is represented in UNICODE by ARABIC LETTER ALEF WITH HAMZA ABOVE (U+0623, [Lo]) followed by ARABIC FATHATAN (U+064B, [Mn]). The first character decomposes to ARABIC LETTER ALEF (U+0627, [Lo]) + ARABIC HAMZA ABOVE (U+0654, [Mn]).
Here's the chain of transformations (the first arrow indicates a decomposition, the second – filtering out nonspacing marks, the third – a composition):
U+0623 + U+064B → U+0627 + U+0654 + U+064B → U+0627 → U+0627
After you decompose, remove all the characters from the [Mn] category, and compose back, you're left with ARABIC LETTER ALEF only.
A:
Thanks to Bolo's enlightment
after a couple of minutes of searching i did it like that:
string s = "";
foreach (Char c in x)
{
if (((int)c).ToString("x").ToLower() != "64b")
s += c.ToString();
}
where x is my string
Like that I excluded the ARABIC FATHATAN from the string
| {
"pile_set_name": "StackExchange"
} |
Q:
Measure voltage of 2 different batteries on Arduino
Currently I'm using a resistor divider to measure the voltage of a 6v battery that is connected to an Arduino via a 5v power regulator. I also want to be able to measure the voltage of another battery (7.2v) on a separate circuit with the same Arduino.
The issue is that the batteries will be on separate circuits, and thus, have no common ground (batteries are not in series or parallel). Is this possible?
A:
The simplest solution is to create a common ground. Since you want to measure two batteries, you have to connect their grounds to the Arduino ground. If you do that to both, the Arduino ground has become the common ground.
| {
"pile_set_name": "StackExchange"
} |
Q:
Перебор массива в php
Есть массив, как его правильно перебрать?Пробовал с помощью
foreach ($string as $value){
echo $value;
}
Не получается
$string = [
{
"id": "1",
"children": [],
"text": "Понедельник",
"level": null,
"data": {},
"type": "video"
},
{
"id": "2",
"children": [],
"text": "Вторник",
"level": null,
"data": {},
"type": "video"
},
{
"id": "3",
"children": [],
"text": "Среда",
"level": null,
"data": {},
"type": "video"
},
{
"id": "1",
"children": [],
"text": "Пятница",
"level": null,
"data": {},
"type": "video"
}
]
A:
Вы вероятно получаете где-то JSON строку, и пытаетесь сразу именно ее перебрать, но это не верное, сначала сделайте из строки строку, таким образом.
$string = '[
{
"id": "1",
"children": [],
"text": "Понедельник",
"level": null,
"data": {},
"type": "video"
},
{
"id": "2",
"children": [],
"text": "Вторник",
"level": null,
"data": {},
"type": "video"
},
{
"id": "3",
"children": [],
"text": "Среда",
"level": null,
"data": {},
"type": "video"
},
{
"id": "1",
"children": [],
"text": "Пятница",
"level": null,
"data": {},
"type": "video"
}
]'
Далее преобразуйте JSON строку в массив
$arr = json_decode($string, true);
А потом перебирайте
foreach ($arr as $value){
print_r($value);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Almost finished with my first Android application made with Ice Cream Sandwich and was wondering about backwards comptibility
Hello I have developed my first application for Android using the Ice Cream Sandwich SDK and I was wondering if there was a way to make this compatible for devices also running Gingerbread without having to re-do the entire program. I have tried to find the answer to this from other sources but haven't found anything yet. Thank you for your time.
A:
Congratulations for the development of your first application ;)
It's difficult to answer to your questions without knowing what your application is using. If your application use new features of the Android ICS API, you have to implements some compatibility code (see Support package). If not, you just need to add this in your AndroidManifest.xml :
<uses-sdk
android:targetSdkVersion="14"
android:minSdkVersion="7"
/>
Note that 7 is for Android 2.1
The best way to know if you use specific API of Android 4 (ICS) is to try to launch your project on an emulator under a lower version. If this give you error(s), it's because you have compatibility problems.
| {
"pile_set_name": "StackExchange"
} |
Q:
Azure Resource Manager template in Visual Studio for Azure Service Fabric
When you create a new Azure Service Fabric solution in Visual Studio, when built and run, you can navigate to the fabric explorer, and in the Manifest tab, it shows the script generated. This looks to me like an Azure Resource Manager (ARM) template.
To enable reverse proxy in my service fabric application, I need to modify this ARM template, or create a new one based on a sample template, and then bring that into Visual Studio somehow. Basically I'm looking for assistance to find where that connection is made.
A:
The cluster manifest the you see in Service Fabric Explorer is not the ARM template, but you change the manifest through ARM, if running Service Fabric in Azure.
To enable the reverse proxy in ARM see here: https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-reverseproxy#setup-and-configuration
To get the current ARM template for your cluster deployment, go to the Azure Portal and download the template to VS: How can I download template json for an Azure Resource Group that I created in the portal?
Finally update the deployment from PowerShell: https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-cluster-creation-via-arm#create-the-cluster
| {
"pile_set_name": "StackExchange"
} |
Q:
i3: enabling fullscreen by default
With i3, is it possible to have all new windows open in fullscreen by default?
As far as I have been able to find, this is only possible for specified programmes.
A:
You can use the following configuration setting:
for_window [class=".*"] fullscreen enable
The for_window [CRITERIA] COMMAND setting runs COMMAND for each new window matching CRITERIA. i3 uses PCRE (Perl-compatible regular expressions) for pattern matching, so the pattern .* matches any number of arbitrary characters. Meaning it matches any possible class name, even empty ones.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python internal database use
Say I have a database of recipes that I have online, and I want to use this database in a program, but I want to store the information from the database internally to the program and only have to connect to the online database when I want to update, however I don't want my end-users to have to have a database(MySql, MSSQL, etc..) installed to their machine. What would be the best way to efficiently do this?
A:
sqlite is the most common way to use databases without a database server.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to upgrade crypto-utils on fedora 14 to fc21 version
I'm using Fedora 14 to generate a self-signed certificate for our internal webserver serving our bugzilla bug tracking system.
Fedora 14 crypto-utils generates a SHA1 signature, which current version chrome rejects as being insecure (It works OK in IE).
This was updated in Fedora 21 crypto-utils (2.4.1-56) https://bugzilla.redhat.com/show_bug.cgi?id=1062444
My current version is 2.4.1-27
# yum list crypto-utils
....
Installed Packages
crypto-utils.x86_64 2.4.1-27 @fedora
I don't want to upgrade the full system, but instead do want to get the newer version of crypto-utils installed.
I tried:
yum update crypto-utils
but this tells me "No Packages marked for update"
What are the steps I need to take to get the newer version of crypto-utils running on my machine?
EDIT: I followed NoAngel's guide below (thanks), but it looks like my version of Fedora is too old to allow an easy upgrade. I needed newer versions of three other packages to build the Fedora21 version of crypto-utils.
$ rpm -i tmp/crypto-utils-2.4.1-56.fc21.src.rpm
...
$ rpmbuild -ba crypto-utils.spec
error: Failed build dependencies:
nss-devel >= 3.13.1 is needed by crypto-utils-2.4.1-56.fc14.x86_64
nss-util-devel >= 3.13.1 is needed by crypto-utils-2.4.1-56.fc14.x86_64
xmlto is needed by crypto-utils-2.4.1-56.fc14.x86_64
Instead I just used an online http://www.selfsignedcertificate.com/ tool to generate what I needed.
A:
First, You are using outdated unsupported old OS, which have many security problems, and You need upgrade or fix them by yourself.
If You still want to do it, thats how:
Download a source code for crypto-utils. Extract it. Then run from source extracted folder:
./configure
make
make install
| {
"pile_set_name": "StackExchange"
} |
Q:
reduce array of objects
I have an array of objects. I would concatenate items as follow:
obj2 = [{ rowNumber:33, rows:[{item1:'ItemOne'}]}, { rowNumber:44, rows:[{item2:'ItemTwo'}]}]
===> new obj = [{ rowNumber:77, rows:[{item1:'ItemOne'},{item2:'ItemTwo'}]}]
Here's my code
let newobj=obj2.reduce((current , next)=> {
current.rowNumber+next.rowNumber;
current.rows.push(next.rows);
return next;
});
console.log(JSON.stringify(newobj))
What actually get this only the second element
{"rowNumber":44,"rows":[{"item2":"ItemTwo"}]}
PS: I'm using Typescript
A:
You are not updating the current object (which should actually be called accumulator). Also, you're pushing to current but returning next. Here's a fixed version.
let obj2 = [{ rowNumber:33, rows:[{item1:'ItemOne'}]}, { rowNumber:44, rows:[{item2:'ItemTwo'}]}];
let newobj = obj2.reduce((current , next) => {
current.rowNumber += next.rowNumber;
current.rows.push(...next.rows);
return current;
});
console.log(JSON.stringify(newobj))
I would fix the variable names in the reduce function to (acc, current) => {...} just to adhere to convention and so that it's clear that you want to use current to update acc and then return acc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is this a correct iText design?
I´m making some pdf reports to be used on a web app.
I wonder if the way I´m taking to make the designs is appropriated.
This would be a screenshot of the way I´m doing the things.
As you can see, I´m using tables to position everything in the document. I think this is a pretty much similar design to HTML. But I want to know is there is a better way to get the same result I got.
This is the document without cell borders:
I could post the code if necessary. By the way, why should I spend long hours programming these kind of stuff with iText tool when I could do things faster and maybe better looking with iReport? I like iText, it´s just a question.
Sorry for my english and thanks!
A:
I think with iText using a table like you have done is going to be the best route. Looks good, nice job.
| {
"pile_set_name": "StackExchange"
} |
Q:
Git применение изменений
Есть основая ветка (master) и есть ветка, которая от нее когда то наследовалась (design). Так же эта ветка лежит на remote стороне.
После в мастер мержились коммиты (из других веток). И в ветку design комитились и пушились изменения.
Визуально выглядит примерно так
Красная линия - мастер, зеленая - design
Я хочу, чтобы в ветке desing были все изменения, сделанные в мастере. ( после комита design3 были все изменения из master6)
Делаю следующее :
git checkout design // она же указывает на origin/desing
git pull origin master
И после этого мне предлагает смержить ветки, и после при пуше у меня есть комиты, которые были сделаны в ветке мастер.
Как мне применить все измениния из мастера в desing? ( при этом не хочется комитить те комиты, которые были в мастере. Или это нереально?)
A:
Если Вы хотите в коммите design3 иметь все изменения ветки master, то после объединения веток Вы не сможете через git push отправить на удалённый репозиторий коммиты только design или только master.
Чтобы все изменения из master были в ветке design, Вам нужно сначала переключиться в ветку design:
git checkout design
Затем, выполнить перемещение:
git rebase master
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get additive blending in cycles?
I want a semi transparent particle that adds to the color behind it. Stack enough on them on top of each other it will be brighter and brighter until it is pure white. It is of course volumetrics I really want.
Example image:
I have tried this but it only decreases transparency. Not much surprise there. Is it at all possible?
My result with the Add shader. Light isn't added (then it would be white). It is only the transparency that goes away.
My node setup with the Add shader. I have also tried it with reversing the colors of the two shaders I add. Similar result.
Start of a solution
Thanks to Gandalf3, I have begun to solve this with only a shader. This is the shader.
This is a test render. I need more geometry, tweek the alphas and some more, but basicly, it is what I want.
I had to increase bounces in light path settings. This is experimental values but work for now. If not changed, the central part of the flames would be black.
A:
This setup will add the transparent shader to itself when seen by the camera. To avoid excess fireflies, an emission shader is used for non-camera rays.
I used two transparent shaders in this case, but if you don't need to control them separately then only one is needed.
Result with three overlapping objects:
Note that with many overlapping objects you may need to increase the max number of Transparent bounces in Render settings > Light Paths to avoid getting black spots where there are more overlapping transparent surfaces than the specified number of bounces.
Update
With the new transparent depth output of the light path node, you can avoid getting black when you run out of transparent bounces. This setup will replace the transparent shaders with an emission shader when the max number of bounces is reached:
This way you can use lower numbers of transparent bounces and not have annoying black spots.
Original answer:
This will make the emission shader become brighter the longer a ray travels through the object:
However, this only works with a single object, so it doesn't look too good with many overlapping particles.
A:
I think the only way to make a material add to what's behind it is to use compositing. To separate the added material from the rest of the scene, your going to have to use RenderLayers.
Move the add object to a separate layer (M).
In the RenderLayer tab select the layer that the add object is on:
Select all layers (`) and hit render.
Open the compositor and Select your two render layers:
Add a mix node and set the Blend Type to Add:
Final Result:
A:
And here is another way how to make additive material. Possibly it will be helpful for someone.
| {
"pile_set_name": "StackExchange"
} |
Q:
Uncheck AlertDialog check list box programmaticaly
I need to uncheck checked checkbox programmaticaly, but the check list is in dialog. Does this changes solution? What I have so far:
CharSequence[] items = itemList.toArray(new CharSequence[itemList.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select categories");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked){
if(chosenCat.size() < 10){
chosenCat.add(items[which].toString());
}else{
Toast.makeText(getApplicationContext(), "Max 10 categories to compare.", Toast.LENGTH_SHORT).show();
//uncheck
items.isChecked = false; // --> wrong
chosenCat.remove(items[which].toString());
}
}else{
chosenCat.remove(items[which].toString());
}
}
});
A:
I've missed this line
((AlertDialog) dialog).getListView().setItemChecked(which, false);
after
checkboxStatusArray[1] = false;
| {
"pile_set_name": "StackExchange"
} |
Q:
Confused on how Prolog assigns values. Why doesn't Prolog bind X when there isn't any parenthesis?
I'm using SWI for Windows and I'm trying out an exercise in Learn Prolog Now!
travel(Start,Dest,X) :-
(byCar(Start,Dest); byTrain(Start,Dest); byPlane(Start,Dest)),
X = go(Start,Dest).
In this code if the you can reach Dest from Start, Prolog says:
true.
X = go(Start,Dest).
and just says false otherwise.
However in this code when I removed the parenthesis it only says true if valid and false if invalid. The answer is correct but why doesn't it output X?
travel(Start,Dest,X) :-
byCar(Start,Dest); byTrain(Start,Dest); byPlane(Start,Dest),
X = go(Start,Dest).
Is it because of operator precedence in which AND gets evaluated first? Even if thats the case shouldn't X still be equal to go(Start,Dest)?
The way Prolog assigns values to variables confuses me.
A:
you're right, precedence of and is lower that or. When unsure, you can use write_canonical
4 ?- write_canonical((travel(Start,Dest,X) :-
byCar(Start,Dest); byTrain(Start,Dest); byPlane(Start,Dest),
X = go(Start,Dest))).
:-(travel(A,B,C),;(byCar(A,B),;(byTrain(A,B),','(byPlane(A,B),=(C,go(A,B))))))
true.
5 ?- write_canonical((travel(Start,Dest,X) :-
(byCar(Start,Dest); byTrain(Start,Dest); byPlane(Start,Dest)),
X = go(Start,Dest))).
:-(travel(A,B,C),','(;(byCar(A,B),;(byTrain(A,B),byPlane(A,B))),=(C,go(A,B))))
true.
and current_op to check beforehand
6 ?- current_op(P,A,(,)).
P = 1000,
A = xfy.
7 ?- current_op(P,A,(;)).
P = 1100,
A = xfy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Porque JSON não é considerado uma linguagem de marcação? E porque XML é?
Estava pesquisando as diferenças entre JSON e XML então li que XML é uma linguagem de marcação mas não li nada a respeito sobre JSON.
A:
Nem sempre esse tipo de categorização é tão rígida, mas na minha opinião seria forçar a barra querer definir JSON como uma linguagem de marcação.
Não consigo imaginar pegar um documento arbitrário e "marcá-lo" usando JSON. É até possível, em teoria. Afinal, tanto XML quanto HTML foram criados para serem interpretados como uma árvore, e JSON organiza as coisas em árvore. Mas repare que já é um grau de abstração acima. Um documento marcado com XML é relativamente legível por humanos antes de ser transformado em árvore. HTML é mais legível ainda. Já JSON não é tão legível.
Vamos tomar como exemplo um trecho bem simples de HTML:
texto <strong>texto destacado</strong> texto
O jeito mais simples que consigo imaginar isso em JSON seria:
{
txt: 'texto ',
strong: 'texto destacado',
txt: ' texto'
}
Isso é relativamente legível, mas claramente menos que o original. Já o HTML seria muito mais próximo do original. Fora isso, em JSON não há garantia quanto à ordem das chaves de um objeto. Então, a representação acima não é confiável. Seria necessário algo ainda mais complexo, como:
[
{ type: 'text', value: 'texto ' },
{ type: 'strong', value: 'texto destacado' },
{ type: 'text', value: ' texto' }
]
Minha conclusão: seria até possível considerar formalmente JSON como uma linguagem de marcação. JSON foi criado com um objetivo um pouco distinto (com mais foco em troca entre sistemas do que na legibilidade, apesar de ser relativamente legível), e por isso não é a solução mais simples para os casos de uso de linguagens de marcação – cujo exemplo mais conhecido é o próprio HTML.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proof of the existence of an optimal MDP with a stochastic reward signal?
I'm following Sutton's book on Reinforcement Learning, and he casually states that "There is always at least one policy that is better than
or equal to all other policies" for a given finite MDP. This is trivially the case for deterministic policies, since there is a finite number of policies. Is there any proof when one allows for stochastic policies? Or any proof that a stochastic policy can always be improved by a deterministic one?
The value function is bounded and real-valued and therefore there is a least upper bound, but how can we know it is achieved by a valid policy?
A:
Old question, but I will try to answer anyway: It depends.
If the search space only allows policies that have at least one state for which a non-deterministic action selection takes place, then no; trivially there is no (fully) deterministic policy that is better then the optimal stochastic policy.
If you allow all stochastic policies in the sense that $\pi(a|s)\neq 0$ for any number ($\geq 1$) of $a$ available in $s$ and further $\forall a,s~:\pi(a|s)\in [0,1] $ (there is no restriction on the probability value for a state-action pair) then yes, deterministic policies are at least equally good.
Proof:
Let $\pi^*$ be an optimal, non-deterministic policy. This means that $\exists \hat{s}~ \exists a : \pi^*(a|\hat{s}) \in (0,1)$, where $\pi^*(\cdot|s)$ is the probability distribution function for the optimal policy $\pi^*$ in state $s$.
We can find a value function $V^*$ as well as a Q-function $Q^*$ that correspond to $\pi^*$ and a relationship between them
\begin{equation}
V^*(s) = \sum_{i=0}^N\pi^*(a_i|s)Q^*(s,a_i)
\end{equation}
W.l.o.g. $Q^*(s,a_1)\geq Q^*(s,a_2)\geq\dots\geq Q^*(s,a_N)$. Choosing $\alpha_i \in [0,1]$, we can now construct a family of policies $\pi^{\alpha_2,\dots,\alpha_N}$ such that:
\begin{equation}
\pi^{\alpha_2,\dots,\alpha_N}(a|s) =
\begin{cases}
\pi^*(a|s) +\sum_{i=2}^N \alpha_i&,~\textrm{if}~a=a_1~\textrm{and}~ s = \hat{s}\\
\pi^*(a|s) - \alpha_i&,~\textrm{if}~a=a_i~\textrm{and}~ s = \hat{s}~\textrm{for}~i\geq 2\\
\pi^*(a|s)&,~\textrm{otherwise}
\end{cases}.
\end{equation}
Choose $\alpha_N = \pi^*(a_N|\hat{s})~,~\alpha_i = 0$ otherwise; we can compare
\begin{align}
V^*(s) &= \sum_{i=0}^{N-1}\pi^*(a_i|s)Q^*(s,a_i) + \pi^*(a_N|s)Q^*(s,a_N)\\
&\leq \sum_{i=0}^{N-1}\pi^*(a_i|s)Q^*(s,a_i) + \pi^*(a_N|s)Q^*(s,a_1) \\
&= \sum_{i=0}^{N-1}\pi^*(a_i|s)Q^*(s,a_i) + \alpha_N Q^*(s,a_1) \\
&= V^{0,\dots,0,\pi^*(a_N|s)}(s)
\end{align}
(Note: for [my] convenience I've written s instead of $\hat{s}$ here.)
Analogous for $\alpha_i=\pi^*(a_i|s)$ and we arrive at
\begin{equation}
V^*(s) \leq V^{\pi^*(a_2|\hat{s}),\dots,\pi^*(a_n|\hat{s})}~\forall s
\end{equation}
meaning that the policy $\pi^{\pi^*(a_2|\hat{s}),\dots,\pi^*(a_n|\hat{s})}$ which is deterministic in $\hat{s}$ is at least as good as $\pi^*$.
Doing this for each stochastic state in $\pi^*$ constructs a new policy which is at least as good as the previous optimal policy, but deterministic.
A shorter, but I think less insightful, proof following the same line of thought (sketch):
W.l.o.g. $Q^*(s,a_1)\geq Q^*(s,a_2)\geq\dots\geq Q^*(s,a_N)$.
\begin{equation}
V^*(s) = \sum_{i=0}^N\pi^*(a_i|s)Q^*(s,a_i) \leq \underbrace{\sum_{i=0}^N\pi^*(a_i|s)}_{=1}Q^*(s,a_1) = Q^*(s,a_1)
\end{equation}
Choosing
\begin{equation}
\pi(a|s) =
\begin{cases}
1&,~\textrm{if}~a = a_1\\
0&,~\textrm{otherwise}
\end{cases}
\end{equation}
follows that $V^*(s)\leq V^\pi(s)~\forall s$. $\pi$ is deterministic by construction.
| {
"pile_set_name": "StackExchange"
} |
Q:
Re-connect adb to Android emulator after "toggle cell network" (F8) or airplane mode?
If I accidentally press F8 key while Android emulator has the keyboard focus, it looses Internet connection as this is the "toggle cell network" keyboard shortcut. That's fine, press F8 again and Internet is up again in the emulator, but its connection to adb is lost. The only way to recover is to shut-down the emulator and restart it. Same thing happens if I select "airplane mode" in an emulator, then exit the airplane mode.
It's easy for me to press accidentally F8, as it's a "step over" debugger key in IntelliJ Idea environment that I use. I know I can change keyboard shortcut in idea, so don't send me this answer... Another reason to use F8 or airplane mode on/off is that sometimes Internet connection dies in an emulator, and toggling the airplane mode restores it - but adb connection is dead...
Will appreciate any help with this, or help with logging a bug to Google developers to fix this issue, if we can't find a good work-around.
Greg
A:
I think I found the answer. After pressing F8 again to re-enable Internet access in the emulator, it is enough to execute:
adb kill-server
on my PC, then use adb start-server or just any other adb command and it restores the connection to the emulator. Great!
It would be nice to change the F8 key in the emulator to something else to avoid conflict with IntelliJ Idea environment, or disable it completely.
Greg
| {
"pile_set_name": "StackExchange"
} |
Q:
Install elementary OS in dual boot with 'something else' option
How to install elementary OS using the 'Something else' option at the partitioning step.
A:
Note : This can also be used to reinstall elementary OS. To reinstall skip the partition steps.
Partitoning :
Before using something else option allocate space to install elementary OS.
Open Gparted then select partiton you want to allocate for elementary OS.
Right click --> Delete.
Step1: Now right click on the partition --> New --> extended partition. and ext4 File system.
Step2 : Make Partitions for swap, /root and /home.
Now Right click on the /sda2 and select Resize/Move
Here -- sda2 extended
sda5 format swap -
sda6 format ext4 -
sda7 format ext4 -
Note:
You can choose swap size same as size of your RAM. Generally 4GB swap is enough.
20 GiB is enough for /root.
See system specifications, at least 15 GB of disk space needed.
/home is the filesystem for your user's files: documents, images, music and videos
Now your partition table similar to like this:
Installation:
Now start installing and then select something else option.
Now,
select /sda5 --> click on change button (at left corner) you will see popup like this:
Now click on drop down button select swap area.
Similarly for /sda6 and /sda7 select ext4 / and ext4 /home respectively.
Now click on Install Now
| {
"pile_set_name": "StackExchange"
} |
Q:
Flash support on Android
I have seen at least 20-30 posts on SO regarding this but still haven't got the answer. Can we load an swf file in Android webview or not? I have an HTML page with swf object embedded in it. All HTML content loads except the swf file. I have also installed the Flash Player from Adobe archives on Android device(2.3) but it doesn't work.
In this post, it doesn't work. But the same method is working on this post. Why?
My aim is to run a sencha app on Android device containing the above HTML file, but first I'm unable to load that HTML file with swf content using a native app.
A:
Short answer: when Flash was supported on Android, it required to enable plugins support on the WebView. But it's not supported anymore since Android 4.1 (Jellybean). And Android 4.4 devices use a new WebView implementation which is garanteed to not support any plugin.
If you want this to work, you have to install Flash on an older device with Android 4 or lower.
| {
"pile_set_name": "StackExchange"
} |
Q:
NAudio pitch shifting
I am using the NAudio DLL and I am looking for example code for pitch shifting sound.
A:
There is an example of using NAudio for pitch shifting in the open source Skype Voice Changer project. See my article on Coding4Fun for more information on the project. The pitch shifter code itself is found in the SuperPitch class.
| {
"pile_set_name": "StackExchange"
} |
Q:
Breaking out unit tests into another project
I used to have a Tests folders in my main project where a unit test had this line of code:
Foo foo = new Foo(Environment.CurrentDirectory + @"\XML\FooData.xml" );
I have an XML directory in the Foo project that has a FooData.xml
In the post build event of my projects i have the following line
copy "$(ProjectDir)Foo\Currencies.xml" "$(TargetDir)\XML"
I now have broke all unit tests into another projects to separate them out and i now get the following error when running these unit tests.
Could not find a part of the path 'C:\svncheckout\Foo.Tests\bin\Debug\XML\FooData.xml'
A:
Rather than having a post-build step, can you not just make it a "content" item in Visual Studio, telling it to copy it to the target directory? I usually either do that, or make it an embedded resource and use streams and Assembly.GetManifestResourceStream.
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Studio 2013 dark theme collapsed text color almost invisible
The Visual Studio 2013 dark theme collapsed text color is black (as shown at the figure below), because the background is almost pure black, The text becomes very hard to see.
I tried to change the collapsed text color at Tools > Options > Environment > Fonts and colors > Collapsed text (Collapsed). I also have looked almost all others items and I was not able to find one that changes the collapsed text color.
Is that a bug? What is the correct item to change this color?
EDIT:
I was using edmuffin.MultiAdornment extension. It overwrites the collapsed text color, that is why even after a restart the text color was not changing.
A:
I also faced the same issue and the trick is that you have to restart Visual Studio for the changes to be applied after you have made the necessary changes.(No idea why or what is the exact reason for this but this has worked for me)
| {
"pile_set_name": "StackExchange"
} |
Q:
Does Hinduism allow Guru-Shishya Marriage?
I have seen in a Vikram and Betal story that the prince is not allowed to marry the princess since prince has secretly learnt Archery from the princess in that way the princess is his Guru and Guru-Shishya Marriage is not allowed.
Is Guru-Shishya marriage prohibited in Hinduism?
Has it been written somewhere that Guru-Shishya marriage is prohibited in Hinduism?
A:
Guru and Sishya relationship may not always ends in SPIRITUALITY as explained in this answer.
In Kacha and Devayani story Kacha tells Devayani that she is like a sister to him as she was the daughter of his guru.
In Mahabharata Arjuna spent one full year in the inner women apartments of King Virata as a dance teacher of Uttara. After his victory over Kauravas, Virata offers his daughter to Arjuna in marriage. Then Arjuna says as follows:
Residing in thy inner apartments, I had occasion always to behold thy
daughter, and she too, alone or in company trusted me as her father.
Well-versed in singing and dancing, I was liked and regarded by her,
and, indeed, thy daughter always regardeth me as her protector.
O king, I lived for one whole year with her though she had attained the
age of puberty. Under these circumstances, thyself or other men may
not without reason, entertain suspicions against her or me. Therefore,
O king, myself who am pure, and have my senses under control, beg to
thee, O monarch, thy daughter as my daughter-in-law. Thus do I attest her purity. There is no difference between a daughter-in-law and a daughter, as also between a son and son's own-self.
Arjuna was not saying that scriptures prohibit Guru to marry his disciple, but it was because Uttara regarded him as his protector, and thus he regarded her as his daughter.
I do not know about other areas, but in Hindu telugu people's marriage, both bride and bridegroom will keep a mixture of Jaggery and Cumin, kept on a betel leaf, on the head of the other, at Muhurtha.
This is done to indicate that each will act as a guide or Guru to the other in achieving 4 purusharthas, ie., Dharma, Artha, Kaama and Moksha.
So it is only the feeling that counts.
| {
"pile_set_name": "StackExchange"
} |
Q:
1054 Unknown column 'extra_query'
I have a new Joomla installation with this error:
1054 Unknown column 'extra_query' in 'field list' SQL=SELECT DISTINCT update_site_id, type, location, last_check_timestamp, extra_query FROM no3a2_update_sites WHERE enabled = 1
The error is displayed when I want to open my template settings. The template is from RocketTheme.
What can I do?
A:
You give very little information to give a good answer, but there are a couple of things you can try:
Make sure both Joomla and your template is up to date
Re-upload your template if possible
Fix your database by going to Extension manager -> Database, and click the Fix button in the upper left corner
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I make a chloropleth based on zip codes?
I want to use d3 to create a chloropleth that assigns different colors to different zip code regions in the United States. Similar to this, except with zip codes:
http://bl.ocks.org/mbostock/4060606
However, I can't find a topojson of US zip codes. This offers a way to generate the topojson for zip codess:https://github.com/mbostock/us-atlas
but my Mac has been running their script for hours on end. Oddly, I can't find anyone on the Internet who has successfully generated the file of zip codes.
I could also use zip3 regions - basically zip code regions characterized by the first 3 digits. However, I can't find any topojson for this division.
Where can I find topojsons or files containing the shapes of either US zip codes or zip3 regions?
A:
A zip code topojson is going to be too large to work with. A Zip3 geoJSON file is over 550MB with no simplification. With a simplification of 0.00001 it's over 370MB. If I take it to a simplification of 0.001 then you can get 39MB.Which will get down to 1.1MB after running it through topojson but you end up with a USA map that looks like a polygon from Everquest Texas is massively deformed. I think the happy medium is is 0.0001 this gives you a topojson file of bout 4.8MB. Here is the process.
Download your Zip3 file here
Extract to your working directory
Run ogr2ogr -simplify 0.0001 -f GeoJSON zip3.json zip3.shp
Run topojson --id-property ZIP3 -o zip3topo.json -- zip3.json
The ogr2ogr will take some time but now you have a topojson file that will render to look like this.
| {
"pile_set_name": "StackExchange"
} |
Q:
Event for a Storyboard repeatedly in WP8
I wrote a storyboard which make a ball (imgBall) running repeatedly on a process bar (imgBar) - with repeat behavior = "forever", but I don't see event which occur when single turn start or end, It only have Completed event (which occur when the whole storyboard finished)
<Grid Margin="20,0,0,0">
<Canvas Canvas.ZIndex="1" >
<Canvas.Resources>
<Storyboard x:Name="myStoryboard" Completed="myStoryboard_Completed">
<!-- Animate the center point of the ellipse. -->
<DoubleAnimation Storyboard.TargetName="imgBall"
Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)"
Duration="0:0:2"
From="10" To="350"
RepeatBehavior="Forever"
></DoubleAnimation>
</Storyboard>
</Canvas.Resources>
<Image Source="/Assets/Image/processball.png" x:Name="imgBall">
<Image.RenderTransform>
<CompositeTransform TranslateX="10" TranslateY="2"/>
</Image.RenderTransform>
</Image>
</Canvas>
<Image Source="/Assets/Image/imgBar.png"/>
</Grid>
</StackPanel>
A:
You can remove RepeatBehavior="Forever" and repeat your Storyboard from code behind in Completed event Handler using .Begin() method.
| {
"pile_set_name": "StackExchange"
} |
Q:
How is $\chi^2$ value converted to p-value?
I'm brand new to statistics and am studying the math behind split testing (A/B and multivariate). I've learned how to calculate $\chi^2$ with given test data, and I understand how to translate this into a probability via a table, but I'd like to be able to calculate the probability myself. I've read through a couple of explanations online, but I'm not getting it.
Does anyone know of a resource or book that breaks this down?
A:
The $p$-value is the area under the $\chi^2$ density to the right of the observed test statistic. Therefore, to calculate the $p$-value by hand you need to calculate an integral.
In particular, a $\chi^2$ random variable with $k$ degrees of freedom has probability density
$$f(x;\,k) =
\begin{cases}
\frac{x^{(k/2)-1} e^{-x/2}}{2^{k/2} \Gamma\left(\frac{k}{2}\right)}, & x \geq 0; \\ 0, & \text{otherwise}.
\end{cases}$$
Suppose you observe a test statistic $\lambda$. Then, the $p$-value corresponding to $\lambda$ is
$$
p = \int_{\lambda}^{\infty}
\frac{x^{(k/2)-1} e^{-x/2}}{2^{k/2} \Gamma\left(\frac{k}{2}\right)}
dx $$
After trying to evaluate this integral by hand, it may become clear to you why people use tables (and computers) for calculating such things.
Edit: (This was in the comments but seemed important enough to add here) Note that you can write the $p$-value using special functions:
$$ p = 1−\frac{γ(k/2,λ/2)}{Γ(k/2)} $$
where $\gamma(\cdot,\cdot)$ is the lower incomplete gamma function.
| {
"pile_set_name": "StackExchange"
} |
Q:
Integral check $\int \frac{6x+4}{x^4+3x^2+5} \ \text{dx}$
$$\int \frac{6x+4}{x^4+3x^2+5} \ \text{dx}$$ Partial fraction decomposition of $\frac{6x+4}{x^4+3x^2+5}$ is of the following form: $$\frac{Ax+B}{x^2+2}+\frac{Cx+D}{x^2+1}$$ We need to find $A,B,C$ and $D$ \ $$\frac{6x+4}{x^4+3x^2+5}=\frac{Ax+B}{x^2+2}+\frac{Cx+D}{x^2+1}$$ Or, $$6x+4=x^3(A+C)+x^2(B+D)+x(2A+C)+2B+D$$ By solving: $$\begin{cases} A+C=0 \\ B+D=0 \\ 2A+C=6 \\2B+D=4 \end{cases}$$ We get $$A=-6,B=-4,C=6,D=4$$ Hence $$\frac{6x+4}{x^4+3x^2+5}=-\frac{6x+4}{x^2+2}+\frac{6x+4}{x^2+1}$$ Now, by linearity, $$\int \frac{6x+4}{x^4+3x^2+5} \ \text{dx}=-\int\frac{6x+4}{x^2+2}\ \text{dx}+\int\frac{6x+4}{x^2+1}\ \text{dx}$$ Or,
$$-3\int\frac{2x}{x^2+2}\ \text{dx}-4\int\frac{1}{x^2+2}\ \text{dx}+3\int\frac{2x}{x^2+1}\ \text{dx}+4\int\frac{1}{x^2+1}\ \text{dx}$$ Which equals to:
$$-3\ln(x^2+2)+\frac{4}{\sqrt{2}}\text{arctan}(\frac{x}{\sqrt{2}})+3\ln(x^2+1)+4\text{arctan}(x)+C$$
A:
All the signs of all your letters are switched. This is because $A+A+C=A+0=A=6$, $B+B+D=B+0=B=4$, etc. Also, $$(x^2+1)(x^2+2)=x^4+3x^3+2\neq x^2+3x+5$$ Your polynomial has no real roots, so you'll have to do some manipulation in $\Bbb C$, as follows:
Let $x^2=u$. Then $$u^2+3u+5=0$$ has solutions $$u_1=\frac{-3+i\sqrt 11}{2}$$
$$u_2=\frac{-3-i\sqrt 11}{2}$$
Thus $$u^2+3u+5=\left(u-\frac{-3-i\sqrt 11}{2}\right)\left(u-\frac{-3+i\sqrt 11}{2}\right)$$
We can write then $${u^2} + 3u + 5 = \left( {u + {3 \over 2} + {{i\sqrt 1 1} \over 2}} \right)\left( {u + {3 \over 2} - {{i\sqrt 1 1} \over 2}} \right)$$ and using the difference of squares factorization $${u^2} + 3u + 5 = {\left( {u + {3 \over 2}} \right)^2} - {{{i^2}11} \over 4} = {\left( {u + {3 \over 2}} \right)^2} + {{11} \over 4}$$ Thus $${x^4} + 3{x^2} + 5 = {\left( {{x^2} + {3 \over 2}} \right)^2} + {{11} \over 4}$$
You can move on from that.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I discover/control the level of internal buffering in a C++ fstream?
Say I do this (a contrived example):
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream ifs(argv[1]);
char ch;
while(ifs.read(&ch, 1)) {
cout << ch;
}
}
I assume(hope) that the iostream library does some internal buffering here and doesn't turn this into gazillions of one-byte file-read operations at the OS level.
Is there a way of:
a) Finding out the size of ifstream's internal buffer?
b) Changing the size of ifstream's internal buffer?
I'm writing a file filter that needs to read multi-gigabyte files in small chunks and I'd like to experiment with different buffer sizes to see if it affects performance.
A:
You can use ios::rdbuf() to get a pointer to a streambuf object. This object represents the internal buffer for the stream.
You can call streambuf::pubsetbuf(char * s, streamsize n) to set a new internal buffer with a given size.
See this link for more details.
edit: Here is how it would look in your case:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argCount, char ** argList[])
{
ifstream inStream(argList[1]);
char myBuffer [512];
inStream.rdbuf()->pubsetbuf(myBuffer, sizeof(myBuffer));
char ch;
while(inStream.read(&ch, 1))
{
cout << ch;
}
}
edit: as pointed out by litb, the actual behavior of streambuf::pubsetbuf is "implementation-defined".
If you really want to play around with the buffers, you may have to roll your own buffering class that inherits from streambuf.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to detect that code is running in colaboratory as opposed to "classic jupyter"
Does anyone know if there is a way to programatically determine that we're running in colaboratory as opposed to "classic jupyter"?
Following this great article about using Scala on Colaboratory, I tried using plotly.
However, I ran into this issue. Although I found a work around (as detailed in the issue). One of the comments suggests that there is a generic work around that could be applied if our code could detect that it was running in Colaboratory.
Thanks for any pointers!
A:
There are several module imports typical of Colab. For example, in Python:
import sys
'google.colab' in sys.modules
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS CIFilters which actually do work?
I am currently trying to populate a collection view with a picture which is filtered by different CIFilters.
I used apples way to get an array of filters.
let filterNames = CIFilter.filterNamesInCategories([kCICategoryStillImage,kCICategoryBuiltIn])
I thought this should give me all filters which are applicable to still images on the iPhone.
But it kinda doesn't work.
This are (some) of the filters i get from the method above:
["CIAccordionFoldTransition", "CIAdditionCompositing", "CIAffineClamp", "CIAffineTile", "CIAffineTransform", "CIAreaAverage", "CIAreaHistogram", "CIAreaMaximum", "CIAreaMaximumAlpha", "CIAreaMinimum", "CIAreaMinimumAlpha", "CIAztecCodeGenerator", "CIBarsSwipeTransition", "CIBlendWithAlphaMask", "CIBlendWithMask", "CIBloom", "CIBoxBlur", "CIBumpDistortion", "CIBumpDistortionLinear", "CICheckerboardGenerator", "CICircleSplashDistortion", "CICircularScreen", "CICircularWrap", "CICMYKHalftone",
plus A LOT more.
I apply the filters with this method:
func applyFilter(image: UIImage, filterName: String) -> UIImage {
let beginImage = CIImage(CGImage: image.CGImage!)
let filter = CIFilter(name: filterName)!
filter.setValue(beginImage, forKey: kCIInputImageKey)
filter.setDefaults()
let context = CIContext(options: nil)
let imageRef = context.createCGImage(filter.outputImage!, fromRect: beginImage.extent)
let newImage = UIImage(CGImage: imageRef)
return newImage
}
The first two filters wont work because the resulting image is a nil, then some work, and then i get:
[<CIAztecCodeGenerator 0x7fb89c775460> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key inputImage.'
*** First throw call stack:
(
0 CoreFoundation 0x000000010cd5de65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010efebdeb objc_exception_throw + 48
2 CoreFoundation 0x000000010cd5daa9 - [NSException raise] + 9
3 CoreImage 0x000000010d33eea2 -[CIFilter setValue:forUndefinedKey:] + 137
4 CoreImage 0x000000010d4093ce -[CIAztecCodeGenerator setValue:forUndefinedKey:] + 335
5 Foundation 0x000000010d6749bb -[NSObject(NSKeyValueCoding) setValue:forKey:] + 288
6 DrawIt 0x000000010cb55088 _TFC6DrawIt25applyFilterViewController11applyFilterfS0_FTCSo7UIImage10filterNameSS_S1_ + 552
7 DrawIt 0x000000010cb54b52 _TFC6DrawIt25applyFilterViewController14collectionViewfS0_FTCSo16UICollectionView22cellForItemAtIndexPathCSo11NSIndexPath_CSo20UICollectionViewCell + 1186
8 DrawIt 0x000000010cb54e3f _TToFC6DrawIt25applyFilterViewController14collectionViewfS0_FTCSo16UICollectionView22cellForItemAtIndexPathCSo11NSIndexPath_CSo20UICollectionViewCell + 79
9 UIKit 0x000000010e31d5ba -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:isFocused:] + 483
10 UIKit 0x000000010e31fae0 -[UICollectionView _updateVisibleCellsNow:] + 4431
11 UIKit 0x000000010e32423b -[UICollectionView layoutSubviews] + 247
12 UIKit 0x000000010db7f4a3 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 703
13 QuartzCore 0x0000000113d0059a -[CALayer layoutSublayers] + 146
14 QuartzCore 0x0000000113cf4e70 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
15 QuartzCore 0x0000000113cf4cee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
16 QuartzCore 0x0000000113ce9475 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 277
17 QuartzCore 0x0000000113d16c0a _ZN2CA11Transaction6commitEv + 486
18 QuartzCore 0x0000000113d259f4 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy + 576
19 CoreFoundation 0x000000010ccbdc84 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
20 CoreFoundation 0x000000010ccbd831 __CFRunLoopDoTimer + 1089
21 CoreFoundation 0x000000010cc7f241 __CFRunLoopRun + 1937
22 CoreFoundation 0x000000010cc7e828 CFRunLoopRunSpecific + 488
23 GraphicsServices 0x0000000113bc8ad2 GSEventRunModal + 161
24 UIKit 0x000000010dac8610 UIApplicationMain + 171
25 DrawIt 0x000000010cb569fd main + 109
26 libdyld.dylib 0x000000010faf492d start + 1
27 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
I did not check all the rest of the filters.
I thought that the array SHOULD only contain flters which are applicable easy as that.
Is it the code thats wrong or the array of Filters I use?
But e.g. the first Filter (CIAccordionFoldTransition) seems to be a transition not really a filter. So it makes sense that it has a nil as output.
Is there a way to get all filters which are applicable to a single picture just like that?
I am pretty fresh in iOs and I hope my question isn't to stupid for this homepage, be kind!
Greetings and thanks in advance.
A:
Some of the filters returned by CIFilter.filterNamesInCategories have an inputImage attribute, and some do not.
For example, the attributes understood by CIAztecCodeGenerator (mentioned in your exception report) are listed here, and inputImage isn't one of them.
A filter reports the keys for its input attributes through its inputKeys property. It describes all of its attributes through its attributes property.
Perhaps you want to restrict your filters to those that have an inputImage attributes:
let filterNames = CIFilter.filterNamesInCategories([kCICategoryStillImage,kCICategoryBuiltIn])
.filter { CIFilter(name: $0)?.inputKeys.contains("inputImage") ?? false }
| {
"pile_set_name": "StackExchange"
} |
Q:
Spark Transformers [Scala]: Knowing schema transformation result before feeding the full data
Is there a method I could use If I want to know how a Transformer changes the schema; without providing the data? For example I have a large DataFrame but I don't want to use it with the transformer; I just want to know the occurring schema transformation without using the full data.
A:
Transfomer's are lazy (there is no fit stage) so even if you pass the data, there should be no significant delay.
However all PipelineStages (which include both Transfromers and Estimators) provide transformSchema method, which can be called directly, with StructType as an argument. For example if you have StringIndexer like this one
import org.apache.spark.ml.feature.StringIndexer
val indexer = new StringIndexer().setInputCol("foo").setOutputCol("foo_indexed")
and schema like this one
import org.apache.spark.sql.types._
val schema = StructType(Seq(StructField("foo", StringType)))
you can apply it as follows:
indexer.transformSchema(schema)
and get
org.apache.spark.sql.types.StructType = StructType(StructField(foo,StringType,true), StructField(foo_indexed,DoubleType,false))
| {
"pile_set_name": "StackExchange"
} |
Q:
How would you write a custom class in python using different objects?
I'm trying to learn how to code in python, but am having trouble on finding ways to create custom classes online. I wrote a program in java and I am trying to convert it in python. I think I have the custom class down (I'm not sure), and I'm definitely having trouble with the driver.
my custom class (python):
class CostCalculator:
__item = ""
__costOfItem = 0.0
__tax = 0.0
__tip = 0.0
def set_item(self, item):
self.__item = item
def get_name(self):
return self.__item
def set_costOfItem(self, costOfItem):
self.__costOfItem = costOfItem
def get_costOfItem(self):
return self.__costOfItem
def get_tax(self):
__tax = self.__costOfItem * .0875
return self.__tax
def get_tip(self):
__tip = self.__costOfItem * .15
return self.__tip
My python driver attempt
import sys
from CostCalculator import CostCalculator
item = ""
cost = 0.0
totalTip = 0.0
totalTax = 0.0
overallTotal = 0.0
subtotal = 0.0
print("Enter the name of 3 items and their respective costs to get the total value of your meal")
print ("\n Enter the name of your first item: ")
item = sys.stdin.readline()
print("How much is " + item + "?")
cost = sys.stdin.readLine()
My java custom class and driver:
public class TotalCost
{
String item = " ";
double costOfItem = 0;
double tax = 0;
double tip = 0;
public void setItem ( String i )
{
item = i;
}
public String getItem()
{
return item;
}
public void setCostOfItem ( double c )
{
costOfItem = c;
}
public double getCostOfItem ()
{
return costOfItem;
}
public double getTax ()
{
double tax = costOfItem * .0875;
return tax;
}
public double getTip()
{
double tip = costOfItem * .15;
return tip;
}
public String toString()
{
String str;
str = "\nMeal: " + getItem() +
"\nCost of " + getItem() + ": " + getCostOfItem() +
"\nTax of " + getItem() + ": " + getTax() +
"\nTip of " + getItem() + ": " + getTip();
return str;
}
}
import java.util.Scanner;
public class Driver
{
public static void main (String args[])
{
Scanner input = new Scanner (System.in);
String item ;
double cost ;
double totalTip = 0;
double totalTax = 0;
double OverallTotal = 0;
double subtotal;
TotalCost a = new TotalCost ();
TotalCost b = new TotalCost ();
TotalCost c = new TotalCost ();
System.out.println("Enter the name of 3 items and their respective costs to get the total value of your meal");
System.out.println("Enter the name of your first item: ");
item = input.nextLine();
a.setItem ( item );
System.out.println("How much is " + a.getItem() + "?" );
cost = input.nextDouble();
a.setCostOfItem (cost);
input.nextLine();
System.out.println("Enter the name of your second item: ");
item = input.nextLine();
b.setItem (item);
System.out.println("How much is a " + b.getItem() + "?");
cost = input.nextDouble();
b.setCostOfItem (cost);
input.nextLine();
System.out.println("Enter the name of your third item: ");
item = input.nextLine();
c.setItem (item);
System.out.println("How much is a " +c.getItem() + "?" );
cost = input.nextDouble();
c.setCostOfItem(cost);
System.out.println(a + "\n" + b + "\n" + c);
subtotal = a.getCostOfItem() + b.getCostOfItem() + c.getCostOfItem();
totalTip = a.getTip() + b.getTip() + c.getTip();
totalTax = a.getTax() + b.getTax() + c.getTax();
OverallTotal = subtotal + totalTip + totalTax;
System.out.println("\n\tSubtotal: $" + subtotal);
System.out.println("\tTax: $" + totalTax);
System.out.println("\tTip: $" + totalTip);
System.out.println("\tMeal Total: $" + OverallTotal);
}
}
A:
In Python, there is no notion of public vs private, everything is public so you do not need setters or getters.
What you do need is the __init__ function, which is similar to a constructor. You can initialize the member variables here so they are not static and shared among all instances of your class. You can also add default arguments so you many pass in any, all, or none of the arguments to the class upon instantiation.
class CostCalculator:
def __init__(self, item = "", cost = 0.0):
self.item = item
self.cost = cost
def __str__(self):
return 'Meal: {item}\nCost of {item}: {cost}\nTax of {item}: {tax}\nTip of {item}: {tip}'.format(item = self.item, cost = self.cost, tax = self.calc_tax(), tip = self.calc_tip())
def calc_tax(self):
return self.cost * 0.0875
def calc_tip(self):
return self.cost * 0.15
def calc_total(self):
return self.cost + self.calc_tax() + self.calc_tip()
Then you can create an instance of this class. Again note that you can directly access the members without setters or getters, for better or worse ;)
>>> c = CostCalculator('cheese', 1.0)
>>> c.item
'cheese'
>>> c.calc_tip()
0.15
Now you can invoke print on your object
>>> c = CostCalculator('cheese', 1.0)
>>> print(c)
Meal: cheese
Cost of cheese: 1.0
Tax of cheese: 0.085
Tip of cheese: 0.15
Lastly, the way you accept input from a user is generally via input (although messing around with stdin isn't necessarily wrong)
>>> tax = input('how much does this thing cost? ')
how much does this thing cost? 15.0
>>> tax
'15.0'
| {
"pile_set_name": "StackExchange"
} |
Q:
Keystore does not work on Java 9
I've converted a JKS keystore to the P12 format using portecle, but it probably didn't go well. The keystore works with Java 8 (various versions), but with Java 9 (OpenJDK 64-Bit Server VM (build 9-internal+0-2016-04-14-195246.buildd.src, mixed mode), I'm getting
java.io.IOException: Invalid keystore format
at sun.security.provider.JavaKeyStore.engineLoad(java.base@9-internal/JavaKeyStore.java:659)
at sun.security.util.KeyStoreDelegator.engineLoad(java.base@9-internal/KeyStoreDelegator.java:219)
at java.security.KeyStore.load(java.base@9-internal/KeyStore.java:1466)
at org.eclipse.jetty.util.security.CertificateUtils.getKeyStore(CertificateUtils.java:52)
at org.eclipse.jetty.util.ssl.SslContextFactory.loadKeyStore(SslContextFactory.java:998)
at org.eclipse.jetty.util.ssl.SslContextFactory.load(SslContextFactory.java:252)
at org.eclipse.jetty.util.ssl.SslContextFactory.doStart(SslContextFactory.java:219)
The funny thing is that Java 8 keytool shows
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 5 entries
... entries listed
while the one from Java 9 shows
Keystore type: PKCS12
Keystore provider: SUN
Your keystore contains 5 entries
... entries listed
I'm aware of JEP 229 and I've read the related issues, but I can't see any related problem.
A:
The JDK keytool utility can convert a JKS keystore into a PKCS12 keystore.
For example, using JDK 9,
$ keytool -importkeystore -srckeystore ks.jks -destkeystore ks.p12
Also, there have been several keystore enhancements since 2016 so you should use a more recent release of JDK 9, see http://jdk.java.net/9/
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I deal with Function and ellipsis/varargs in this case?
One of my project is throwing-lambdas; in it I aim to ease the use of potential @FunctionalInterfaces in Streams, whose only "defect" for being used in streams is that they throw checked exceptions (on my part I'd rather call defective the fact that you can't throw checked exceptions from streams but that's another story).
So, for Function<T, R> I define this:
@FunctionalInterface
public interface ThrowingFunction<T, R>
extends Function<T, R>
{
R doApply(T t)
throws Throwable;
default R apply(T t)
{
try {
return doApply(t);
} catch (Error | RuntimeException e) {
throw e;
} catch (Throwable throwable) {
throw new ThrownByLambdaException(throwable);
}
}
}
This allows me to define, for instance:
final ThrowingFunction<Path, Path> = Path::toRealPath;
(why Path::toRealPath... Well, precisely because it has an ellipsis).
Not wanting to stop here I want to be able to write stuff like:
Throwing.function(Path::toRealPath).fallbackTo(Path::toAbsolutePath)
The above NEARLY works... Read on.
I also define this:
public abstract class Chainer<N, T extends N, C extends Chainer<N, T, C>>
{
protected final T throwing;
protected Chainer(final T throwing)
{
this.throwing = throwing;
}
public abstract C orTryWith(T other);
public abstract <E extends RuntimeException> T orThrow(
final Class<E> exclass);
public abstract N fallbackTo(N fallback);
public final <E extends RuntimeException> T as(final Class<E> exclass)
{
return orThrow(exclass);
}
}
And this is the implementation of it for Functions:
public final class ThrowingFunctionChain<T, R>
extends Chainer<Function<T, R>, ThrowingFunction<T, R>, ThrowingFunctionChain<T, R>>
implements ThrowingFunction<T, R>
{
public ThrowingFunctionChain(final ThrowingFunction<T, R> function)
{
super(function);
}
@Override
public R doApply(final T t)
throws Throwable
{
return throwing.doApply(t);
}
@Override
public ThrowingFunctionChain<T, R> orTryWith(
final ThrowingFunction<T, R> other)
{
final ThrowingFunction<T, R> function = t -> {
try {
return throwing.doApply(t);
} catch (Error | RuntimeException e) {
throw e;
} catch (Throwable ignored) {
return other.doApply(t);
}
};
return new ThrowingFunctionChain<>(function);
}
@Override
public <E extends RuntimeException> ThrowingFunction<T, R> orThrow(
final Class<E> exclass)
{
return t -> {
try {
return throwing.doApply(t);
} catch (Error | RuntimeException e) {
throw e;
} catch (Throwable throwable) {
throw ThrowablesFactory.INSTANCE.get(exclass, throwable);
}
};
}
@Override
public Function<T, R> fallbackTo(final Function<T, R> fallback)
{
return t -> {
try {
return doApply(t);
} catch (Error | RuntimeException e) {
throw e;
} catch (Throwable ignored) {
return fallback.apply(t);
}
};
}
}
So far so good (although IDEA fails to recognize the code of orTryWith() as valid, but that's another story).
I also define a utility class called Throwing and the problem lies in the main() of this class which I wrote as a test:
public final class Throwing
{
private Throwing()
{
throw new Error("nice try!");
}
public static <T, R> ThrowingFunctionChain<T, R> function(
final ThrowingFunction<T, R> function)
{
return new ThrowingFunctionChain<>(function);
}
public static void main(final String... args)
{
// FAILS TO COMPILE
final Function<Path, Path> f = function(Path::toRealPath)
.fallbackTo(Path::toAbsolutePath);
}
}
Now, the error message for the code above is:
Error:(29, 48) java: incompatible types: cannot infer type-variable(s) T,R
(argument mismatch; invalid method reference
method toRealPath in interface java.nio.file.Path cannot be applied to given types
required: java.nio.file.LinkOption[]
found: java.lang.Object
reason: varargs mismatch; java.lang.Object cannot be converted to java.nio.file.LinkOption)
Error:(29, 49) java: invalid method reference
non-static method toRealPath(java.nio.file.LinkOption...) cannot be referenced from a static context
Error:(30, 25) java: invalid method reference
non-static method toAbsolutePath() cannot be referenced from a static context
I can't diagnose the exact cause of the error here, but to me it just looks like ellipsis gets in the way; in fact, if I do:
final ThrowingFunctionChain<Path, Path> f = function(Path::toRealPath);
try (
final Stream<Path> stream = Files.list(Paths.get(""));
) {
stream.map(f.fallbackTo(Path::toAbsolutePath))
.forEach(System.out::println);
}
then it compiles: so it means that Stream.map() does acknowledge the result as being a Function...
So why won't Throwing.function(Path::toRealPath).fallbackTo(Path::toAbsolutePath) compile?
A:
As Holger has stated in the comments, the compiler is limited in its type inference when chaining methods. Just provide an explicit type argument
final Function<Path, Path> f = Throwing.<Path, Path>function(Path::toRealPath).fallbackTo(Path::toAbsolutePath);
A:
Your code fragment
Function<Path, Path> f = function(Path::toRealPath).fallbackTo(Path::toAbsolutePath);
is hitting a limitation of Java 8’s type inference which is contained in the specification, so it’s not a compiler bug. Target typing does not work when you chain method invocations. Since the first method of the chain is a varargs method, its target type is required to find the intended invocation signature. This situation similar to when you write p->p.toRealPath(), where the number of parameters of the invocation is unambiguous but the type of p is not known. Both won’t work in an invocation chain (besides in the last invocation)
This can be resolved by either making the type of the first invocation explicit,
Function<Path, Path> f = Throwing.<Path,Path>function(Path::toRealPath)
.fallbackTo(Path::toAbsolutePath);
or
ThrowingFunctionChain<Path, Path> f0 = function(Path::toRealPath);
Function<Path, Path> f = f0.fallbackTo(Path::toAbsolutePath);
or
Function<Path, Path> f = function((Path p)->p.toRealPath())
.fallbackTo(Path::toAbsolutePath);
or by converting the method invocation chain into unchained method invocations as described here:
public static <T, R> ThrowingFunctionChain<T, R> function(
final ThrowingFunction<T, R> function)
{
return new ThrowingFunctionChain<>(function);
}
public static <T, R> Function<T, R> function(
final ThrowingFunction<T, R> function, Function<T, R> fallBack)
{
return new ThrowingFunctionChain<>(function).fallbackTo(fallBack);
}
public static void main(final String... args)
{
Function<Path, Path> f = function(Path::toRealPath, Path::toAbsolutePath);
}
The specification deliberately denied the type inference for two invocations when one invocation targets the result of the other but it works if the same expressions are just parameters of another invocation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Powershell. Как выполнить экспорт полученного массива в Excel?
Добрый день.
Выполняю парсинг с помощью Powershell+Selenium.
С помощью команды $fullstory = $ie.FindElementByClassName("comment")
Получаю вывод:
Исполнитель: Pink Floyd
Название альбома: Dark Side Of the Moon
Стиль: Rock
Год выпуска: 2016
Как сделать вывод Excel чтобы соответственно "Исполнитель:", "Название альбома:" и.т.д стали столбцами, а то что после двоеточия - значениями столбцом?
Спасибо заранее.
A:
Можете вывести все в Csv файл, а затем открыть его через Excel
$fullstory | Export-Csv .\out.csv -Delimiter ":" -NoTypeInformation
Invoke-Item .\out.csv
| {
"pile_set_name": "StackExchange"
} |
Q:
WM_TOUCH vs WM_POINTER
Which one should I use? I'm only using Windows 8.x, so I don't care about the fact that WM_POINTER is not backwards compatible with Windows 7 etc. I also don't care about gestures; only about raw touches. WM_POINTER's only clear advantage seems to be that it unifies touch and mouse input (but that's easy to work around with WM_TOUCH because mouse events can be checked with GetMessageExtraInfo()). Ease of use is also not an issue; I've been using WM_TOUCH already and I'm just wondering if I should switch to WM_POINTER. My overriding concern is latency and efficiency (game-related application). I can't tell whether WM_POINTER is a wrapper over WM_TOUCH that has extra overhead. Any comments?
A:
WM_TOUCH is obsolete. Use WM_POINTER exclusively. (WM_TOUCH is actually a wrapper over WM_POINTER.)
GetMessageExtraInfo is also notoriously fragile. You have to call it immediately after calling GetMessage, or else you run the risk of intermediate function calls making a COM call or doing something else that results in calling GetMessage.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get list of documents with defined value of custom property in Alfresco
We use Alfresco Enterprise 4.2.2.5 platform for our projects.
Our users create contracts in Alfresco folder "../contracts_def" and then start process of approvement.
For a example, folder "contracts_def" has the following structure:
Contracts_def (Folder)
|
|---- contract_name1 (Folder)
| |--- contract_name1.docx (main document)
| |--- ext_file1.docx (document)
|
|---- contract_name2 (Folder)
|--- contract_name2.docx (main document)
|--- ext_file2.docx (document)
Each main document has set of properties, including status of approvement.
In Alfresco Node browser property's full name is {httр://www.mytest.ru/model/test/contract/1.0}status.
I'd like to fetch list of documents with status "on-sign" within folder "contracts_def".
I've wrote simple script for running in Java Script Console:
var rs = search.query
({ query:
"SELECT * FROM cmis:document WHERE CONTAINS('PATH:\"/app:company_home/st:sites/cm:contracts/cm:documentLibrary/cm:contracts/cm:contracts_def//*\"')",
language:"cmis-alfresco" });
for (var r in rs)
{ logger.log(rs[r].parent.name + "/" + rs[r].name + "\t" + rs[r].properties.status); }
There are 3 questions:
1) Script works, but Instead of document's status I get "NULL". How I understand, script doesn't return custom property of documents - {httр://www.mytest.ru/model/test/contract/1.0}status, but I can get only none-custom properties, for example {httр://www.alfresco.org/model/content/1.0}creator.
2) I'd like to fetch list of documents which have only status "on-sign", but script will return all specified properties without filtering.
How can I change code for my requirements?
3) Can I get this information using built-in web-scripts of Alfresco?
Thanks in advance.
A:
It is not clear why you want to use CMIS for this if you are running the code in the server-side JavaScript console which has full access to the JavaScript API and native search.
Rather than using JavaScript and CMIS, you might find it easier to first just get a query working by using the Node Browser available in the admin console.
Go to the admin console, then the node browser, and put this in the search box:
PATH:"/app:company_home/st:sites/cm:contracts/cm:documentLibrary/cm:contracts/cm:contracts_def//*" =test:status:"on-sign"
Make sure "fts-alfresco" is selected.
Now that you have a working query, you can go back to the JS console and use it in your search.query call.
| {
"pile_set_name": "StackExchange"
} |
Q:
Hide a div on completion of password
I have a basic input box that once a password is entered, it shows a div. This works fine but I would also like the password input box to disappear. I thought I could just use the same code and change the toggle to hide but the div hides as soon as a letter is pressed.
Question - how do I get it to hide once the password is complete (and correct).
I think I need in if statement saying that 'if the password matches then hide the div' but I'm not sure...
I would also like to put a 1sec delay on hiding the input div too. This is done with the .delay function isn't it?
Any help would be appreciated.
//this shows the div
$(document).ready(function() {
'use strict';
$('#ae').on('keyup', function() {
$('#ae-form').toggle(this.value.trim().toLowerCase() == 'allerganemployee');
});
});
//this needs to hide the input box
$(document).ready(function() {
'use strict';
$('#ae').on('keyup', function() {
$('#ae-input').hide(this.value.trim().toLowerCase() == 'allerganemployee');
});
});
#ae-form {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="allergan box">
<h2>Registration for Employees</h2>
<div id="ae-input">
<p>Please enter your password</p>
<input type="password" id="ae" />
</div>
<div id="ae-form">
This is the form
</div>
</div>
A:
//this shows the div
$(document).ready(function() {
'use strict';
$('#ae').on('keyup', function() {
$('#ae-form').toggle(this.value.trim().toLowerCase() == 'allerganemployee');
if(this.value.trim().toLowerCase() == 'allerganemployee'){
$('#ae-input').hide();
}
});
});
#ae-form {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="allergan box">
<h2>Registration for Employees</h2>
<div id="ae-input">
<p>Please enter your password</p>
<input type="password" id="ae" />
</div>
<div id="ae-form">
This is the form
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Change the bullet of each \item
Sorry, may be the title is not clear. In fact, I need to make a list of advantages and disadvantages and I want to note the advantages as + and disadvantages as -. How can I change the full circle of item to + or - sign?
\documentclass[compress,red]{beamer}
\usepackage{etex}
\mode<presentation>
\usetheme{Warsaw}
\usepackage[applemac]{inputenc}%les accents pour mac
\usepackage{subfigure}
\usepackage{amsmath}
\usepackage{epsfig}
\usepackage{graphicx}
\usepackage[all,knot]{xy}
\xyoption{arc}
\usepackage{setspace}
\begin{document}
\section{section1 }
\frame[shrink]{\frametitle{Titre de la fenetre}
\begin{itemize}
\item point1
\item point2
\item point3
\item point4
\item point5
\end{itemize}
}
A:
As Sigur commented, you can use the optional argument to \item to specify the bullet:
\item[+] Some positive point
\item[$-$] Some negative point %use $-$ instead of - for a real minus sign.
\item Some neutral point
In my opinion the minus sign isn't great for this (not very clear), but you can use almost anything for your bullet, including colour commands (e.g. \item[\textcolor{red}{-}]). The comprehensive LaTeX symbols list may help you to find something good, such as \oplus and \ominus (circled versions, normally used as binary operators) from the mathabx package.
EDIT: code updated thanks to comment from Przemysław Scherwentke, but I can't easily updated the image from here.
A:
Just an addition to @Sigur's answer. You can define macros, say \pro and \con,
\newcommand\pro{\item[$+$]}
\newcommand\con{\item[$-$]}
to save some repetitive typing, and make the source code more readable.
MWE
\documentclass{beamer}
\usetheme{Warsaw}
\begin{document}
\newcommand\pro{\item[$+$]}
\newcommand\con{\item[$-$]}
\frame{
\begin{itemize}
\pro advantage
\con disadvantage
\item neutral
\end{itemize}
}
\end{document}
Output
| {
"pile_set_name": "StackExchange"
} |
Q:
The only option is to include that block of code into each of my functions?
Several of my functions require the UniversalXPConnect privilege to be enabled.
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
So, my functions look like this:
function oneOfMyFunctions() {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
// ...
}
Actually, I also try to catch the exception when the privilege is denied. Looks as follows:
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
// ...
} catch (e) {
// ...
}
I'd rather to make that a separate function and call it from within my functions as follows:
function oneOfMyFunctions() {
if (enablePrivilege()) {
// ...
} else {
// ...
}
}
Given that the enablePrivilege function would be as follows:
function enablePrivilege() {
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
} catch (e) {
return false;
}
return true;
}
But, for security reasons, that is impossible as the privilege is granted only in the scope of the requesting function.
So, the only option is to include that block of code into each of my functions?
UPDATE:
As I am going to also try to catch some other exceptions I've ended up with the following design:
function readFile(path, start, length) {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var file = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(path);
var istream = Components.classes['@mozilla.org/network/file-input-stream;1'].createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, -1, -1, false);
istream.QueryInterface(Components.interfaces.nsISeekableStream);
istream.seek(0, start);
var bstream = Components.classes['@mozilla.org/binaryinputstream;1'].createInstance(Components.interfaces.nsIBinaryInputStream);
bstream.setInputStream(istream);
return bstream.readBytes(length);
}
var filepath = 'C:\\test.txt', start = 440, length = 5;
try {
console.log(readFile(filepath, start, length));
} catch (e) {
if (e.name == 'Error') console.log('The privilege to read the file is not granted.');
else console.log('An error happened trying to read the file.');
}
A:
You could make enablePrivilege a sort of wrapper function that accepts a function as a parameter that it then calls inside itself, like so
function enablePrivilege(funcParam) {
//enable privileges, in try-catch
funcParam();
}
so that when you call it like so
enablePrivilege(oneOfMyFunctions);
the function that needs the privileges should have them since it is called inside the scope of enablePrivilege.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP Code: Trying to link to a MYSQL table
I have a PHP file which is designed to link to a test SQL table which I've set up. The problem is that entering data into my search box isn't getting the results I'm after.
First, the PHP code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, FirstName, LastName FROM 'create'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result)>0) {
// output data of each row
while($row=mysqli_fetch_assoc($result)) {
echo "ID: " . $row["ID"]. " - Name: " . $row["FirstName"]. " " . $row["LastName"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
And the SQL file, copied and pasted from the CSV version, in order of ID, FirstName, LastName...
1,"Ryan","Butler"
2,"Ryan","Butler"
3,"Brent","Callahan"
4,"Harry","Callahan","[email protected]"
5,"Luke","Cage","[email protected]",
6,"Jessica","Jones","[email protected]",
The result of entering any of the above words in my search box should give me a result of 6. Jessica. Jones. (I'm not bothering to search for the emails, I don't know why I included them.) Instead, I get "0 results" no matter what I type.
There's probably just one thing that I have wrong, but I'll be damned if I know what it is. Then again, PHP is not my forté.
A:
Your table name should be in backticks, not quotes.
$sql = "SELECT ID, FirstName, LastName FROM `create`";
| {
"pile_set_name": "StackExchange"
} |
Q:
CSS Sprite Doesn't Work Because Width/Height defines container
So, on my website RedRoll.com I'm trying to implement CSS sprites.
(If you scroll down you will see a scrolling container under "Exclusive!")
.simply-scroll-btn-left {
left: 0px;
top: 0px;
width: 34px;
height: 100%;
background: #000 url('https://www.redroll.com/wp-content/themes/steam/images/arrow-left.png') no-repeat center center;
background-size: 7px 12px !important;
}
As you can see, there is a black background behind the current arrow. The background is 34px x 100%.
But here's the problem. The width and height defined in the CSS creates the black container around it, so if I try to specify the width/height of the icon in my sprite, it also changes the size of the container.
How do I keep the black background size the same but specify the size of the icon? Also, how do I center the sprite in the middle of the black background like it is currently?
A:
If I understand your question correctly, and your constraints, this problem may be solvable using pseudo elements.
One approach might be to slightly modify the styles for the existing CSS as below, and add a floating icon via a pseudo element.
This should give you the control you need to size, and select unique icons from your icon sprint/atlas:
[UPDATED] Sorry, just noticed my original answer was missing: content:'' in the pseudo selector - please ensure this is added
/* Leave existing styling for box sizing mostly untouched, with minor adjustments */
.simply-scroll-btn-down {
left: 0px;
top: 0px;
width: 100%;
height: 25px;
background: #000; // Remove image, etc
position:relative; // Add this so that pseudo element can be centered
}
/* Display a pseudo element for icon */
.simply-scroll-btn-down:after {
//[UPDATE] This is required
content:'';
position:absolute;
display:block;
// This translates the pseduo element for centering
left: 50%;
top: 50%;
// This adjusts the pseduo element for centering based on pseduo elements dimensions
margin-left:-20px;
margin-top:-20px;
width: 40px;
height: 40px;
// Adjust these rules to suit the icon coordinates in your sprite/atlas
background-image: url('YOUR_SPRITE_URL'); // Customise as needed
background-repeat: no-repeat; // Customise as needed
background-position: 10px 10px; // Customise as needed
}
| {
"pile_set_name": "StackExchange"
} |
Q:
WooCommerce Customer Order xml export suite plugin
I using the woocommerce-customer-order-xml-export-suite plugin and trying to customize the output xml. I have if 90% figured out, it the last part that is giving me issues. Basically the output xml has to look like this:
Order.xml
<ItemOut quantity="1" lineNumber="1">
<ItemID>
<SupplierPartID>GPS-2215RB</SupplierPartID>
</ItemID>
<ItemDetail>
<UnitPrice>
<Money currency="USD">105.99</Money>
</UnitPrice>
</ItemDetail>
</ItemOut>
</OrderRequest>
</Request>
</cXML>
This is what I am getting now:
MyOrder.xml
<ItemOut Quantity="">
<ItemID>
<SupplierPartID>S1072-35</SupplierPartID>
<Quantity>1</Quantity>
</ItemID>
<ItemDetail>
<UnitPrice>
<SupplierPartID>S1072-35</SupplierPartID>
<Quantity>1</Quantity>
</UnitPrice>
</ItemDetail>
</ItemOut>
</OrderRequest>
</Request>
</cXML>
Here is my current PHP code:
'ItemOut' => array(
'@attributes' => array('Quantity' => $item_data['qty'] ),
'ItemID' => wc_sample_xml_get_line_items( $order ),
'ItemDetail' => array(
'UnitPrice' => wc_sample_xml_get_line_items( $order ),
),
),
), // End OrderRequest Array
), //End Main Request Array
), // End Request
);
}
add_filter( 'wc_customer_order_xml_export_suite_order_export_order_list_format', 'wc_sample_xml_order_list_format', 10, 2 );
/**
* Adjust the individual line item format
*
* @since 1.0
* @param object $order \WC_Order instance
* @return array
*/
function wc_sample_xml_get_line_items( $order ) {
foreach( $order->get_items() as $item_id => $item_data ) {
$product = $order->get_product_from_item( $item_data );
$ItemID[] = array(
'SupplierPartID' => $product->get_sku(),
'Quantity' => $item_data['qty'],
);
$ItemDetail[] = array(
'Money' => $product->get_price(),
);
}
return $ItemID;
}
Here is the last part of the php code that I'm having issues with. Any help would be appreciated.
A:
Okay, so both your ItemID and ItemDetail/UnitPrice are showing the same thing because they are calling the same function, wc_sample_xml_get_line_items. The returned value of that function is saved in your array:
'ItemOut' => array(
'@attributes' => array('Quantity' => $item_data['qty'] ),
'ItemID' => wc_sample_xml_get_line_items( $order ),
'ItemDetail' => array(
'UnitPrice' => wc_sample_xml_get_line_items( $order ),
),
The result of that function is the return value,
function wc_sample_xml_get_line_items( $order ) {
<...snipped irrelevant stuff...>
$ItemID[] = array(
'SupplierPartID' => $product->get_sku(),
'Quantity' => $item_data['qty'],
);
$ItemDetail[] = array(
'Money' => $product->get_price(),
);
}
return $ItemID; # This is what's returned
}
I suspect that you want $ItemDetail to also be returned to be set in UnitPrice, but what is actually happening is that you've created $ItemDetail, however, once the function finishes, that variable is gone because it is not passed as a return value...and your function already has a return value for something else.
What you need is a new function that is similar to the first, but returns the money detail instead of the ItemID details:
function wc_sample_xml_get_line_item_unit_prices( $order ) {
foreach( $order->get_items() as $item_id => $item_data ) {
$product = $order->get_product_from_item( $item_data );
$ItemDetail[] = array(
'Money' => $product->get_price(),
);
}
return $ItemDetail;
}
And then you can use that for when creating your array:
'ItemOut' => array(
'@attributes' => array('Quantity' => $item_data['qty'] ),
'ItemID' => wc_sample_xml_get_line_items( $order ),
'ItemDetail' => array(
'UnitPrice' => wc_sample_xml_get_line_item_unit_prices( $order ),
),
EDIT:
Getting ItemOut Output
To get ItemOut to generate the XML you need, it is probably best to scrap wc_sample_xml_get_line_item_unit_prices and create one function that will generate the entirety of ItemOut, instead of doing it in bits in pieces. Here is what the resulting ItemOut assignment would look like:
'ItemOut' => wc_sample_xml_get_item_out( $order ),
Notice all the ItemId, ItemDetails, and all that are gone. We want to create that in wc_sample_xml_get_item_out. So, here is that:
function wc_sample_xml_get_line_items( $order ) {
$itemOut = array ();
// Keep track of the line Item number
$lineNumber = 1;
// Build a list of itemOut's from the line items in the order
foreach($order->get_items() as $item_id => $item_data ) {
$product = $order->get_product_from_item( $item_data );
// The idea here is that we'll generate each XML child node individually, then combine them into one ItemOut node afterwards.
// So these will go in <itemout>'s attributes
$newAttributes = array(
'quantity' => $item_data['qty'],
'lineNumber' => $lineNumber
);
// This is ItemId
$newItemId = array(
'SupplierPartID' => $product->get_sku()
);
// and ItemDetail
$newItemDetail = array (
'UnitPrice' => array (
'Money' => $product->get_price()
)
);
// Now we combine these into the ItemOut
$newItemOut = array(
'@attributes' => $newAttributes,
'ItemId' => $newItemId,
'itemDetail' => $newItemDetail
);
// Now we tack this new item out onto the array
$itemOut[] = $newItemOut;
// Set the next line number, and then loop until we've done each line item
$lineNumber++;
}
return $itemOut;
}
I am pretty sure that will get you there or very close. Since I don't have access to your $order and $item_data and even OrderRequest, I'm not sure that it will be structured correctly when you have multiple line items in an order. If this works, definitely test an order with multiple line items and tweak as necessary.
| {
"pile_set_name": "StackExchange"
} |
Q:
C#: How do i access data from a deserialized xml-file
I've set up a xml-serialization / deserialization for saving data in my application. I can deserialize non-array elements, but when i deserialize an array it is empty. I have a hunch that the problem is in the set portion of the property im trying to serialize/deserialize.
First the class i'm trying to serialize:
namespace kineticMold
{
[Serializable()]
public class Config
{
public Config() { }
public string ComPort
{
get
{
return comPort;
}
set
{
comPort = value;
}
}
[XmlArrayItem("recentFile")]
public string[] LastOpen
{
get
{
return lastOpen;
}
set
{
ArrayList holderList = new ArrayList();
holderList.Add(value);
for (int i = 0; i < 4; i++)
{
holderList.Add(lastOpen[i]);
}
lastOpen = (string[])lastOpen.ToArray<string>();
}
}
private string comPort;
private string[] lastOpen = new string[5];
}
}
The result of the serialization:
<?xml version="1.0" encoding="utf-8" ?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ComPort>COM12</ComPort>
<LastOpen>
<recentFile>test.xml</recentFile>
<recentFile xsi:nil="true" />
<recentFile xsi:nil="true" />
<recentFile xsi:nil="true" />
<recentFile xsi:nil="true" />
</LastOpen>
</Config>
The code for deserialization:
_cf = new Config();
XmlSerializer ser = new XmlSerializer(typeof(Config));
if (File.Exists(settings_filepath))
{
FileStream fs = new FileStream(@settings_filepath, FileMode.Open);
_cf = (Config)ser.Deserialize(fs);
fs.Close();
}
The code for reading the deserialized data:
for (int i = 0; i < _cf.LastOpen.Length; i++)
{
if (_cf.LastOpen[i] != null)
{
toolStripMenuItem1.DropDownItems.Add(_cf.LastOpen[i]);
recentState = true;
}
}
A:
You have:
lastOpen = (string[])lastOpen.ToArray<string>();
Do you mean holderList here (on the right hand side)?
It isn't entirely clear which data you want, but you don't currently keep any of the items from value beyond the setter. Also, ArrayList is largely redundant here; it could be a List<string> perhaps?
Of course, even simpler:
private readonly List<string> lastOpen = new List<string>();
[XmlArrayItem("recentFile")]
public List<string> LastOpen {get {return lastOpen;}}
(and let the calling code worry about how many items to keep in there)
| {
"pile_set_name": "StackExchange"
} |
Q:
Putting 7 bits to a byte using loop
I'm trying to put 7 bits to a byte (bit by bit) by using a loop:
unsigned char bytetosend;
unsigned char y[] = { 0x7f };
int x = 0;
int i;
int main()
{
for (i = 0; i < 8; i++)
{
bytetosend = (y[x] & 0x01);
bytetosend >>= 1;
y[x] >>= 1;
}
printf("the out is %x", bytetosend);
}
but why is the output 0?
A:
That's because you are "copying" the LSB of y[x] to the LSB of bytetosend and then you remove it by shifting bytetosend right by one.
I don't know why you need to copy bit by bit if you just can copy the whole byte at once by bytetosend = y[x]; but let's assume that you really want it.
Then you can do it by:
bytetosend = 0;
for (i=0; i < 8; ++i)
{
bytetosend |= y[x] & ((unsigned char)1 << i);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
extend UIView or UITableView
I'm trying to extend my UITableView or UIView 's height by clicking a button to show more details in it as same as the option in the App Store when you want to see more updates of the app. Is it any tutorial for that ?
A:
ok I'm gonna answer my own question. probably there is a easier way for this but if someone has the same question u can use this :
1. Add a UIButton on the view
2. In the .h file make a NSInteger i and in the viewDidLoad give i=0.
3. When user click the invisible button on the UIView :
-(IBAction) clickMyView (id) sender {
if (i==0){
i=1;
[self changeView];
}
else{
i=0;
[self changeView];
}
4.Set chageView:
-(void) changeView{
if (i==0){
[UIView beginAnimations : nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationBeginsFromCurrentState:TRUE];
// Change the view back to it's normal size here
[UIView commitAnimations];
}
else{
[UIView beginAnimations : nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationBeginsFromCurrentState:TRUE];
// Change the view to the new size here
[UIView commitAnimations];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Can you be awarded the 100th capture XP bonus multiple times?
When you catch the 100th pokemon of a species, you get 100 xp points bonus.
Is this for the first 100 or each 100 pokemon captured?
A:
If you take a look at this answer:
This bonus is conferred on every 100th catch of a specific type of Pokemon. This bonus may be repeated.
Yes you can earn this bonus multiple times.
For further proof, other people are reporting that on their 300th capture they receive the bonus as well.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use environment variables in Java with Eclipse? (MAC OS X)
In .bash_profile I have listed many env variables as follows:
export JAVA_HOME=...
export PYTHON=...
...
System.getenv() returns a list of env variables (e.g., SHELL, TMP_DIR) but not those listed in .bash_profile. Where these are coming from and how to get the ones in .bash_profile?
Thanks!
A:
Eclipse takes them from the run configuration. menu Run->Run Configurations...
Select your app, switch to the arguments tab, and put your env variables down there, eg:
-Dname=value
A:
You probably want them in .bashrc instead of .bash_profile. See the INVOCATION section of the bash man page for details of how and when certain init files are loaded.
| {
"pile_set_name": "StackExchange"
} |
Q:
sed used to replace text between some chars with new text
I have a question with I can't figure out.
I have in xml file something like this:
<tag desc="some desc can be different" dep="dep" >value</tag>
I wanna change this like using sed to:
<tag desc="NEW DESC" dep="dep" >value</tag>
My question is: can I use sed to replace text between "<tag ... >" with new one?
Thank you for help :)
A:
Since you are not trying to really parse the xml sed can help you:
sed -i 's/\(<tag[^>]*[ ]*desc[ ]*\)=[ ]*"[^"]*"/\1="NEW DESC"/g' input.xml
But if you want to have a robust solution, use xmlstarlet:
xmlstarlet edit -L -u "//tag/@desc" -v "NEW DESC" input.xml
| {
"pile_set_name": "StackExchange"
} |
Q:
Personal practice regarding stream entry
Have experience when notting the thoughts as impermanence disappears the body and thoughts together .But still there's somebody looking at and it goes into a cloudy space. What is this experience?Is it stream winner?
A:
No one can tell if you are, or not a stream enter-er but yourself. Buddha even gave tools if you wish to proclaim yourself one. Buddha gave about 60 or so definitions for stream enterer. From my observation of sutta, stream enterer can be achieved thru one of 5 majors groups;
views + conducts
views + advancement of mind (wisdom or meditation)
views + letting go of 3 fetters
views + advancement of mind + coducts
Views only
(IMO) Almost like one can clime corperate ladder to be come a CEO thu different depts such as from Engineering, Finance, accounting etc.. But one your are in high level, rout options get narrower (none returners are pretty much about views + letting go of fetters)
Some interesting facts about stream enter:
Unshakeable confidence in 3 gems (Buddha, Dhamma, and Sangha) + keeping 5 precepts are the most spoken quality of stream enterer.
Aññā-Kondañña was the only stream-enterer who had only confidence in 2 out of 3 gems + views. He became a stream enterer (anna means eyes, seeing, sights etc. another name for stream enter-er) after Buddha finished his first sermon and there was no Sangha right at that time. Sangha came right after that when Buddha ordained 5 ascetics. (Aññā-Kondañña became an arahat a few days later at the end of second sermon.)
Those who let go of first 3 fetters are also called stream-enterers. Interestingly, confidence in Buddha and Dhamma is indirectly put into number 2 instead of first and foremost quality when you use fetters to proclaim stream enterer. A direct view would be, letting go of doubt in Buddha and Dhamma.
For men (women) in carpenter village, Buddha explained stream-enterer as those with confidence in 3 gems + generosity (without greed which defiles heart, letting of gifts, open handed, taking pleasure in giving etc.. No 5 precepts was mentioned to them.
Practicing in 8 folds path. Another interesting one. When Buddha asked ven Sarriputta about which of those who sat in front of them were stream enterers, he said those who practice 8 folds path. Tho faith or confidence in 3 gems were not mentioned by ven Sariputta, but in another sutta, those who "sit near and listen" is a characteristic of those who have faith. so stream enterers have confidence in 3 gems + walk the 8 folds paths.
Confidence in 3 gems + understanding of dependent origination (or 5 skandhas, or 6 sense gates) or understand the raise and fall.
confidence in 3 gems + understanding of 5 sensual pleasures (causal, inability to sustain, deliciousness of it, drawbacks, and nisarana-method to get away from it.)
Views only. those who only believes that 5 skandhas or 6 sense gates are not permanents, thorn, boils, nest of diseases etc., have stepped out of ordinary person and into a noble one. in mid-flight of entering a stream enter if you will. Buddha guaranteed he would not die until realize stream entry.
There is correlation between 5 precepts and confidence in 3 gems. As if someone whom you believe told you the well is poisoned, you automatically stop drinking for it without being told.
maybe more definition which I have missed. Please let me know.
Bottom line, (IMO) i think stream enterer has spectrum which Buddha tried to explained it in different lights but as I study further of other stages of enlightment such as once or none-returner, seems like the only option is lettering of fetter to make an advancement.
| {
"pile_set_name": "StackExchange"
} |
Q:
Filter data from an XML document
I have the following XML file.
<JamStatus>
<IPAddress Value="10.210.104.32 " FacId="2">
<Type>Letter</Type>
<JobId>1</JobId>
<fi>50-30C-KMC-360A</fi>
<TimestampPrinting>1309464601:144592</TimestampPrinting>
</IPAddress>
<IPAddress Value="10.210.104.32 " FacId="2">
<Type>Letter</Type>
<JobId>2</JobId>
<fi>50-30C-KMC-360A</fi>
<TimestampPrinting>1309465072:547772</TimestampPrinting>
</IPAddress>
<IPAddress Value="10.210.104.32 " FacId="2">
<Type>Letter</Type>
<JobId>2</JobId>
<fi>50-30C-KMC-360A</fi>
<TimestampPrinting>1309465072:547772</TimestampPrinting>
</IPAddress>
</JamStatus>
There may be any number of IPaddress elememt in the document. jobid and timestamp can be same for a perticular IPAddress. I want to get the count of ipAddress whose Value, jobid and timestampprinting are same. In this case it is 2. which is the best way to get this information?
Is there any simple method without using LINQ?
Thanks,
syd
A:
You can use XElement and LINQ:
var s = @"
<JamStatus>
<IPAddress Value=""10.210.104.32 "" FacId=""2"">
<Type>Letter</Type>
<JobId>1</JobId>
<fi>50-30C-KMC-360A</fi>
<TimestampPrinting>1309464601:144592</TimestampPrinting>
</IPAddress>
<IPAddress Value=""10.210.104.32 "" FacId=""2"">
<Type>Letter</Type>
<JobId>2</JobId>
<fi>50-30C-KMC-360A</fi>
<TimestampPrinting>1309465072:547772</TimestampPrinting>
</IPAddress>
<IPAddress Value=""10.210.104.32 "" FacId=""2"">
<Type>Letter</Type>
<JobId>2</JobId>
<fi>50-30C-KMC-360A</fi>
<TimestampPrinting>1309465072:547772</TimestampPrinting>
</IPAddress>
</JamStatus>";
XElement xel = XElement.Parse(s);
Console.WriteLine(xel.XPathSelectElements("//IPAddress")
.GroupBy(el => new Tuple<string, string>(el.Element((XName)"JobId").Value, el.Element((XName)"TimestampPrinting").Value))
.Max(g => g.Count())
);
| {
"pile_set_name": "StackExchange"
} |
Q:
pandas dataframe create new columns and fill with calculated values from same df
Here is a simplified example of my df:
ds = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
ds
A B C D
1 1.099679 0.042043 0.083903 0.410128
2 0.268205 0.718933 1.459374 0.758887
3 0.680566 0.538655 0.038236 1.169403
I would like to sum the data in the columns row wise:
ds['sum']=ds.sum(axis=1)
ds
A B C D sum
1 0.095389 0.556978 1.646888 1.959295 4.258550
2 1.076190 2.668270 0.825116 1.477040 6.046616
3 0.245034 1.066285 0.967124 0.791606 3.070049
Now, here comes my question! I would like to create 4 new columns and calculate the percentage value from the total (sum) in every row. So first value in the first new column should be (0.095389/4.258550), first value in the second new column (0.556978/4.258550)...and so on...
Help please
A:
You can do this easily manually for each column like this:
df['A_perc'] = df['A']/df['sum']
If you want to do this in one step for all columns, you can use the div method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):
ds.div(ds['sum'], axis=0)
And if you want this in one step added to the same dataframe:
>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
A B C D sum A_perc B_perc \
1 0.151722 0.935917 1.033526 0.941962 3.063127 0.049532 0.305543
2 0.033761 1.087302 1.110695 1.401260 3.633017 0.009293 0.299283
3 0.761368 0.484268 0.026837 1.276130 2.548603 0.298739 0.190013
C_perc D_perc sum_perc
1 0.337409 0.307517 1
2 0.305722 0.385701 1
3 0.010530 0.500718 1
A:
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
| {
"pile_set_name": "StackExchange"
} |
Q:
How to save images on other platforms to save space on system to optimize website?
I am creating a website that allows users to post news, photos, videos...
My database is roughly like this:
PostNews_M table has a column named ImgID, this column is foreign key to the table Image_M (ImgID, Link).
I think if the site has fewer users with little post, every post has little images, so the images stored on the server does not problem matter.
But if one day the website has more users, the storage of such image will have problems, it will cause the server to store more images, the website will be heavy and slow.
I think that when the user posts the post, the image will be saved in another place, then column Link will save the url of the image, so when i load the website, system will call the image url has been saved in the Link.
I am looking forward to have someone suggest, advice me how to handle or how to give me keyword to me to learn it.
A:
As far as I know, you could use Azure Blob Storage to do it.
Azure Blob Storage can be used to store several kinds of files, including news, photos, videos. If you store the files you need to blob, each of them will have a URL. Then you could save the url to column Link.You can find them in the portal or Azure Storage Explorer.
In the portal
In the Azure Storage Explorer
For more details, please refer to this article.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can Hellfire missiles be used effectively as air-to-air weapons?
Consider the following hypothetical scenario:
An MQ-1 Predator pilot sees an Su-27 closing in from straight ahead for a kill. The pilot prepares to write up his 10th loss of the week when he has an idea: He targets the Su-27 with the laser designator and fires two AGM-114 Hellfire missiles.
Would this work? Can Hellfire missiles be used effectively as air-to-air weapons?
A:
While I can't say that I know the too much about Hellfires, the aiming capability appears extremely limited for any air-to-air combat.
The range is bad: ~8km (compared to ~35km for a 'proper' Sidewinder). Covering this does not take many seconds for jets travelling in opposite directions. I'd imagine you might be able to get a helicopter if you're lucky.
I'm incredibly doubtful that a sensible lock on any aircraft could be achieved from a Predator. Bear in mind that you only have a camera on the bottom, so you've got huge blind spots.
You got a fair bit of satellite/communication lag, in the range of 0.5 seconds either way to get any response. More likely that your opponent has already got you by the time you understand what's going on.
The majority of the Hellfire missiles appear to require a constant lock to seek its target; some can continue on autopilot with limitations if it were to lose it. Again, sustaining a lock with that setup does not have a good outlook.
Remember that the Su-27 has countermeasures (such as flares) to protect itself.
A:
Actually, hellfire missiles have been used as air-to-air missiles, albeit only once.
On 24 May 2001, an IDAF AH-64 Apache used two hellfire missiles to shoot down a Lebanese Cessna 152. This is the only known use of hellfire missile so far as an air-to-air missile.
However, it is doubtful if the missile could be employed against a extremely maneuverable target like the Su-27. The AGM 114 is basically a anti-tank missile and not suited for use against aerial targets. The Cessna 152 was piloted by a student pilot and in any case had little maneuverability.
Another issue is that the laser designator has to continuously point at the aircraft through out the guidance phase, which is very difficult in the case of a predator against any fighter aircraft.
Also, the range is poor. All in all, unless the pilot is extremely lucky, a predator is not going to get a Su-27. Maybe a helicopter from its blind spot though.
| {
"pile_set_name": "StackExchange"
} |
Q:
What comes next in this poetic sequence?
This is an ode to me
I am just too good
When compared to thee.
For I am indeed so hot
My fire cannot be contained
Near me, sit you shall not.
Sever your self-worth
And behold my might
So we may dine on earth.
This is not your average sequence. What comes next? why?
A:
A suggestion for the next line
I am better than all men.
It seems as though
Every line contains a word which is one letter different (either by replacement or subtraction) from the corresponding number of the line. This is an ode (one) to me I am just too (two) good When compared to thee (three) For (Four) I am indeed so hot My fire (five) cannot be contained Near me, sit (six) you shall not. Sever (Seven) your self-worth And behold my might (eight) So we may dine (nine) on earth.
| {
"pile_set_name": "StackExchange"
} |
Q:
Proper way to combine wavelet coefficients from multiple rounds of analysis
I am doing signal analysis for a time series and the assumption of signal is
S = F + e
Where S is the original signal, F is the frequency component and e is white noise (auto-regressive time series with moving average = 0). I have a large number of samples, say, N samples; and I can do wavelet decomposition for all them to obtain N number of coefficients arrays.
Now my question is what's the proper way to combine all those coefficients to achieve an "average" of the coefficients, so that e would have smallest standard deviation? I tried to do arithmetic average or average norm times average coefficients vector by cross product; but I couldn't prove either of them is a proper way.
Thanks in advance for your help.
A:
It sounds like this is a numerical problem without analytic solution. So I would suggest to use a numerical optimizer to minimize the standard deviation, e.g. MATLABs FMINCON() function can minimize virtually any expression that can be calculated.
So for your problem, I recommend to calculate:
$$\text{Fmincon}(\sigma(x))$$
where $x$ being your coefficient vector.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error using nth-child
I have this:
a {
display:table;
}
a:hover {
text-decoration:none;
}
a:first-child {
color:#00FF00; /* green */
}
a:nth-child(3) {
color:#FF0000; /* red */
}
<a href="www.google.com">Google<a>
<a href="www.google.com">Google<a>
<a href="www.google.com">Google<a>
Question:
Why is the second "Google" red and not the third? Whats happening here?
A:
close the achor tag
HTML
<a href="www.google.com">Google</a>
<a href="www.google.com">Google</a>
<a href="www.google.com">Google</a>
http://jsfiddle.net/vasanthanvas/z569bm6w/
| {
"pile_set_name": "StackExchange"
} |
Q:
Counting number of words that have each alphabet letter
From the Think Julia book, I wrote the following code to count the number of words that have each alphabet letter:
abc = "abcdef"
letter_count = 0
fin = open("words.txt")
for letter in abc
for line in eachline(fin)
if letter in line
global letter_count += 1
end
end
println("$letter has $letter_count")
global letter_count = 0
end
However, the code only counts the number of occurrences of the letter 'a'.
I could not figure why this code fails.
It returns:
56613 have a
0 have b
0 have c
0 have d
0 have e
0 have f
A:
You have a wrong order of loops (i.e. the outer loop should iterate letters). You can fix it like this (I have also simplified the code a bit):
for letter in "abcdef"
letter_count = count(x -> letter in x, eachline("words.txt"))
println("$letter has $letter_count")
end
However iterating the words.txt file once like this will be faster:
let counts = zeros(Int, 6)
for line in eachline("words.txt")
for (i, letter) in enumerate("abcdef")
counts[i] += letter in line
end
end
counts
end
You could also achieve the desired result using broadcasting like this (I report it as I found it an interesting solution):
julia> letters = "abcdef"
"abcdef"
julia> sum(in.(hcat(letters...), eachline("words.txt")), dims=1)
1×6 Array{Int64,2}:
56613 16305 30466 30648 76168 11277
EDIT:
the difference between eachline(fin) and eachline("words.txt") is the following:
eachline("words.txt") opens (and closes when done) a new stream every time it is called;
eachline(fin) uses the same stream, which means that after the first loop of the iteration is finished we are at the end of the stream and nothing is left to be read in it.
You can retain the eachline(fin) approach if you move to the start of the stream after each iteration like this:
abc = "abcdef"
letter_count = 0
fin = open("words.txt")
for letter in abc
for line in eachline(fin)
if letter in line
global letter_count += 1
end
end
println("$letter has $letter_count")
global letter_count = 0
seekstart(fin)
end
close(fin)
Note that I have added one significant line to your code (and also added close(fin) as you should always close opened streams). But, at least for me, it is not a very clean approach so I did not want to recommend it in the first place.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python re not matching when there is a dot in the string?
It appears that python regex is not matching when the target string has a dot. Is this a feature? Am I missing something? Thanks!
>>> import re
>>> re.compile('txt').match('txt')
<_sre.SRE_Match object at 0x7f2c424cd648>
>>> re.compile('txt').match('.txt')
>>>
A:
The docs are quite explicit about the difference between search and match:
Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).
You should therefore replace match with search:
In [9]: re.compile('txt').search('.txt')
Out[9]: <_sre.SRE_Match at 0x7f888afc9cc8>
I don't know the history behind this quirk (which, let's face it, must trip a lot of people up), but I'd be interested to see (in the comments) why re offers a specific function for matching at the start of a string.
In general, I'm broadly against anything whose name is broad enough that you have to go to the docs to work out what it does.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to rebase an interface default method with ByteBuddy?
I'm trying to annotate a default method at runtime using ByteBuddyAgent. In order to keep the default implementation, I'm using a rebasing strategy, but I can't figure out how to intercept the new method with a call to the original one.
I tried using MethodCall.invokeSuper() and MethodCall.invokeSelf().onDefault(), but with both give me an IllegalStateException.
new ByteBuddy()
.subclass(MyInterface.class)
.method(isDeclaredBy(typeDescription).and(isDefaultMethod()))
.intercept(MethodCall.invokeSelf().onDefault())
.annotateMethod(AnnotationDescription.Builder
.ofType(MyAnnotation.class).build())
.make()
...
A:
You need to use SuperMethodCall.INSTANCE. This way, Byte Buddy gets a chance to locate the actual super method which is the rebased method.
In your case, you would only invoke the same method recursively. Also, the onDefault configuration would attempt to invoke a default method on an interface implemented by MyInterface.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is a real logarithm of a special orthogonal matrix necessarily skew-symmetric?
The exponential map from the Lie algebra of skew-symmetric matrices $\mathfrak{so}(n)$ to the Lie group $\operatorname{SO}(n)$ is surjective and so I know that given any special orthogonal matrix there exists a skew-symmetric real logarithm.
However, must all real logarithms of a special orthogonal matrix be skew-symmetric?
A:
No. Let's say that $A$ is real a logarithm of $-I_2 \in \operatorname{SO}(2)$. Then for any invertible $P$ we have
$$ e^{PAP^{-1}} = P e^A P^{-1} = P (-I_2) P^{-1} = -I_2 $$
so $PAP^{-1}$ is also a real logarithm of $-I_2$. If you start with a skew-symmetric logarithm of $-I_2$ and conjugate it by a general invertible matrix, there is no reason that you'll get a skew-symmetric matrix. For example, if
$$ A = \begin{pmatrix} 0 & \pi \\ -\pi & 0 \end{pmatrix}, P = \begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix} $$
then
$$ PAP^{-1} = \begin{pmatrix} -\pi & 2\pi \\ -\pi & \pi \end{pmatrix} $$
is a real non-skew-symmetric logarithm of $-I_2$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there formula to quickly autofill only the first number in a range?
Below is an example of the list of numbers I need to create exactly as they appear.
401-409
501-509
601-609
701-709
I need to do this all the way up to 3901-3909 but can't get excel to only replace the first digits and leave the rest.
A:
In the first cell:
=(ROW(1:1)-1)*100+401 & "-" & (ROW(1:1)-1)*100+409
and copy down
| {
"pile_set_name": "StackExchange"
} |
Q:
How can i enable true ToolStripMenuItem in form1 when backgroundworker completed his operation in a new class?
In form1 constructor i did:
viewResponsesToolStripMenuItem.Enabled = false;
In a new class i have a backgroundworker:
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < allLinksToParse.Count; i++)
{
GetResponsersFN(allLinksToParse[i]);
}
}
And completed:
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
I need when the backgroundworker completed so in form1 to make:
viewResponsesToolStripMenuItem.Enabled = false;
But how do i know in form1 when the backgroundworker completed in the new class ?
A:
You need to give reference to your form1 instance. You can do that in your new classes' constructor. Add a new private variable for the form1 in your new class:
private Form form1;
Then set the reference in your classes constructor:
newClass(Form form1Reference)
{
this.form1 = form1Reference;
}
Then you can use this in your BackgroundWorker's Completed-event:
this.form1.viewResponsesToolStripMenuItem.Enabled = false;
Make sure that you've set the viewResponsesToolStripMenuItem's Modifiers to Public.
| {
"pile_set_name": "StackExchange"
} |
Q:
is it possible that my server doesnt like api v3?
Im not sure how but thats the only conclusion I can come to.
Ive been playing around with placing a marker at a distance along a route, I found Mike Willamsons epoly.js and some example files and started to play around with them but for some reason the exact same code doesnt work on my server.
eg
http://www.geocodezip.com/v3_GoogleEx_directions-waypoints_kmmarkersC.html
is a simple example that drops two markers at 2 different distances along the route.
I simply viewed source, copied the entire code and pasted it into an hmtl file on my server, taking care to create the scripts directory and drop v3_epoly.js into it.
As you can see below, my page however does everything except output those 2 important markers.
http://peg-web.me.uk/map/
Am I missing something fundamental?
I know, this forum isnt for the epoly.js add in but Im trying to establish if my problem is more fundamental ie related to javascript itself.
A:
Those marker icons are referenced with relative URLs, copy the icons onto your server, put them in the same relative location to the HTML page and they will appear.
Or change this line in the createMarker function:
icon: getMarkerImage(color),
To (comment the property out):
// icon: getMarkerImage(color),
(that will make them use the default marker icon)
| {
"pile_set_name": "StackExchange"
} |
Q:
create .xls file using php
This is what I have:
$sep = "\t"; //tabbed character
$fp = fopen('registrars.xls', "w");
$schema_insert_rows = "";
//printing column names
$schema_insert_rows.="#" . $sep;
$schema_insert_rows.="Registrar" . $sep;
$schema_insert_rows.="Country" . $sep;
$schema_insert_rows.="Website" . $sep;
//$schema_insert_rows.="Postal Address" . $sep;
//$schema_insert_rows.="Contact Number" . $sep;
$schema_insert_rows.="Email Address" . $sep;
$schema_insert_rows.="\n";
fwrite($fp, $schema_insert_rows);
// printing data:
$row = 0; $i = 0; $schema_insert_rows = "";
$schema_insert_rows .= (++$row) . "" . $sep;
$schema_insert_rows .= $registrarArr[$i] . "" . $sep;
$schema_insert_rows .= $registrarArr[$i+1] . "" . $sep;
$schema_insert_rows .= $linkArr[$i] . "" . $sep;
$schema_insert_rows .= (string)(strip_tags($address)) . "" . $sep;
$schema_insert_rows .= (string)(strip_tags($phone)). "" . $sep;
$schema_insert_rows .= "email test";
$schema_insert_rows .= "\n";
fwrite($fp, $schema_insert_rows);
fclose($fp);
The other column works fine but the ones i commented out are not working [for postal address and email address].. I i get rid of the comments, the data will go to the next row though it should be on the same row as the others.. I checked via var_dump to see if there's < br> but there's none.. What's wrong here?
A:
I've used PHPExcel on a client project with good results. It can generate Microsoft Excel, Open Excel and PDF documents.
You might find the file format CSV limiting.
The newer, but not yet stable project is PhpSpreadsheet.
It also supports more formats.
| {
"pile_set_name": "StackExchange"
} |
Q:
#error directive whats wrong with error macro
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#define CHECK(x,y,n) ((x) > 0 && (x) < (n) && (y) > 0 && (y) < (n) ? 1 : 0)
#error(index) fprintf(stderr, "Range error: index = %d\n",index)
int main(void)
{
/*char s[5];
int i;
strcpy(s,"abcd");
i = 0;
putchar(s[++i]);*/
int i = CHECK(10,50,45);
printf("%d",i);
return 0;
}
I tries to do error input that takes an argument because macro can do that but when i try to build and compile i get this error message
#error (index) fprintf(stderr, "Range error: index = %d\n",index)
can i have an argument in the error directive or fprintf
or whats is wrong?
A:
I try to do error input that takes an argument because macro can do that
First, #error isn't a macro. It's a directive. So it gets processed by the preprocessor. Meaning, it only works at compile time. In other words, it can't be used at runtime, say, after an if statement. This also explains that you, at least logically, can't demand an argument because the preprocessor wouldn't know what to do with it.
Second, as it seems you're starting to learn the preprocessor, I'll tell you that all it does is simple substitution. In fact, you can see the final form of the source file as the compiler sees it with the -E option to gcc. For example:
#define BIGGER(x,y) (x > y ? x : y)
int main(void) {
int num = BIGGER(3, 7); // 7
}
Now, all the compiler sees is this:
int main(void) {
int num = (3 > 7 ? 3 : 7);
}
I hope that clarifies your confusion.
| {
"pile_set_name": "StackExchange"
} |
Q:
why rxjs keeps not being the right version?
I'm trying to install a node/angular2 solution on cloud9. Here is my package.json
{
"name": "example",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"postinstall": "typings install",
"typings": "typings",
"vendor": "gulp vendor",
"gulp": "gulp clean && gulp",
"build:production": "gulp clean && gulp build && node systemjs.builder.js"
},
"dependencies": {
"@angular/common": "2.0.0-rc.5",
"@angular/compiler": "2.0.0-rc.5",
"@angular/core": "2.0.0-rc.5",
"@angular/forms": "0.3.0",
"@angular/http": "2.0.0-rc.5",
"@angular/platform-browser": "2.0.0-rc.5",
"@angular/platform-browser-dynamic": "2.0.0-rc.5",
"@angular/router": "3.0.0-rc.1",
"@angular/upgrade": "2.0.0-rc.5",
"body-parser": "~1.15.2",
"cookie-parser": "~1.4.3",
"core-js": "^2.4.1",
"debug": "~2.2.0",
"express": "~4.14.0",
"hbs": "~3.1.0",
"mongoose": "^4.5.8",
"mongoose-unique-validator": "^1.0.2",
"morgan": "~1.6.1",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.11",
"serve-favicon": "~2.3.0",
"systemjs": "0.19.36",
"zone.js": "^0.6.12"
},
"devDependencies": {
"del": "^2.2.1",
"gulp": "^3.9.0",
"gulp-sourcemaps": "^1.6.0",
"gulp-typescript": "^2.10.0",
"systemjs-builder": "^0.15.26",
"typings": "^1.3.2"
}
}
In spite of how this is written, I keep getting this error during npm install:
npm WARN @angular/[email protected] requires a peer of [email protected] but none was installed.
npm WARN @angular/[email protected] requires a peer of [email protected] but none was installed.
npm WARN @angular/[email protected] requires a peer of [email protected] but none was installed.
when I try to run the solution I keep getting this error:
UNMET PEER DEPENDENCY [email protected]
I tried changing the package.json to beta.6, and it still fails.
does anyone have any wisdom on this?
Thanks.
A:
Update package.json to use "rxjs": "5.0.0-beta.6",
Delete node_modules directory in project folder.
Run npm install
That should fix it. I use your package.json with rxjs 5 beta6, the installation was successful without any issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Algebra question leading to a 3rd order equation solving.Any other answers?
if :
$x+y+z=2$ , $ x^2+y^2+z^2=3$ , $xyz=4$
Then evaluate:
$\frac {1} {xy+z-1} + \frac {1} {yz+x-1} + \frac {1} {zx+y-1}$
My try:
$(x+y+z)^2=x^2+y^2+z^2+2(xy+yz+xz)=4 \rightarrow 3+2(xy+yz+xz)=4 \rightarrow xy+yz+xz=\frac {1}{2} \rightarrow xy=\frac {1}{2}-yz-xz$
$\rightarrow xy+z-1=\frac {1}{2}-yz-xz+z-1=-\frac{1} {2} +z(1-y-x)$ $\mathbb{I}$
$x+y+z=2 \rightarrow z-1=1-y-x$ $\mathbb{II}$
$\mathbb{I,II} \rightarrow -\frac {1}{2}+z(z-1)=z^2-z-\frac {1}{2}$ $\mathbb{III}$
$xyz=4 \rightarrow xy=\frac {4}{z} \rightarrow xy+z-1=\frac {4}{z} +z -1=\frac {4+z^2-z}{z}$ $\mathbb{IV}$
$\mathbb{III,IV} \rightarrow z^2-z-\frac{1}{2}=\frac {4+z^2-z}{z} \rightarrow \text{after simplifying} \rightarrow z^3-2z^2+\frac{1}{2} z -4=0$
From that I can find the value of $z$ and doing the same calculations again, values of $y,x$ can be found.
I can't seem to be able to proceed from here and a really strong hunch tells me that I've done a terrible mistake somewhere here.Besides I don't really know how the equation above is solved without using a computer.
So please don't post the complete answer here what I'm asking for is:
1-A hint or anything that can lead me to the solution
2-Finding the error in my solution (if there's any)
3-Please don't laugh at me if I've made a really really stupid mistake back there because I've spent a nice 3 hours on this and it really hurts. :D
P.S:I myself couldn't identify the error in my calculation I have checked them more that a few times.Also please feel free to edit the title and the tags , but I'm pretty sure the question itself has been written correctly.(According to the book here I mean)
Thank you all for your time and help in advance.
A:
$\bf{My\; Solution::}$ Given $$x+y+z = 2\;\;, x^2+y^2+z^2=3\;\;,xyz = 4$$
Now $$xy+z-1 = xy+2-x-y-1 = (1-x)\cdot (1-y)......................(1)\color{\red}\checkmark$$
Above we put $z=2-x-y$ in $xy+z-1$
Similarly $$yz+x-1=yz+2-y-z-1 = (y-1)\cdot (z-1).........................(2)\color{\red}\checkmark$$
Similarly $$zx+y-1=zx+2-x-z-1 = (z-1)\cdot (x-1).........................(3)\color{\red}\checkmark$$
So $$\displaystyle \frac{1}{xy+z-1}+\frac{1}{yz+x-1}+\frac{1}{zx+y-1} = \frac{1}{(1-x)\cdot (1-y)}+\frac{1}{(y-1)\cdot (z-1)}+\frac{1}{(z-1)\cdot (x-1)}$$
So Expression $$\displaystyle = \frac{3-(x+y+z)}{(1-x)\cdot (1-y)\cdot (1-z)} = \frac{3-(x+y+z)}{1-(x+y+z)+(xy+yz+zx)-xyz}$$
Now Using $$\displaystyle (x+y+z)^2=(x^2+y^2+z^2)+2(xy+yz+zx)\Rightarrow xy+yz+zx = \frac{1}{2}.$$
Put These value in above equation , We Get $$\displaystyle = \frac{3-2}{1-2+\frac{1}{2}-4} = -\frac{2}{9}$$
So $$\displaystyle \frac{1}{xy+z-1}+\frac{1}{yz+x-1}+\frac{1}{zx+y-1} = -\frac{2}{9}$$
| {
"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.