input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Add border to ImageView Android for cropping <p>I want to add a rectangular border on my <code>ImageView</code> which allow users to change it's size from 8 directions to provide them a preview for cropping purpose.</p>
<p>Which way I can implement to achieve my purpose best, defining a custom <code>ImageView</code> and add code to draw rectangle or add <code>ImageView</code> to a <code>SurfaceView</code>?</p>
<p>Here is my code which I can use to draw a rectangle around my image:</p>
<pre><code>import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
public class CustomCropImageView extends ImageView implements View.OnTouchListener{
// Bitmap to draw.
Bitmap myBitmap;
// Fundamental attributes.
int xPos, yPos;
int originWidth, originHeight;
int widthImg, heightImg;
int xCrop, yCrop;
int cropWidth, cropHeight;
GestureDetector myGesture;
public CustomCropImageView(Context context){
super(context);
xPos = yPos = xCrop = yCrop = 0;
// setOnTouchListener(this);
}
public CustomCropImageView(Context context, AttributeSet attSet){
super(context, attSet);
xPos = yPos = xCrop = yCrop = 0;
// setOnTouchListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if(drawable == null)
return;
if(originWidth == 0 && originHeight == 0){
Bitmap tmp = ((BitmapDrawable)drawable).getBitmap();
myBitmap = tmp.copy(Bitmap.Config.ARGB_8888, true);
originWidth = myBitmap.getWidth();
originHeight = myBitmap.getHeight();
Integer[] myDWAndH = getScreenWidthAndHeight();
widthImg = cropWidth = myDWAndH[0];
heightImg = cropHeight = (int)((float)myDWAndH[0]*((float)originHeight / (float)originWidth));
yPos = yCrop = (myDWAndH[1] - heightImg) / 2;
myBitmap = Bitmap.createScaledBitmap(myBitmap, widthImg, heightImg, false);
}
Paint myPaint = new Paint();
canvas.drawBitmap(myBitmap, xPos, yPos, myPaint);
drawAnchorRectangle(canvas);
}
void drawAnchorRectangle(Canvas canvas){
// Anchor rectangle.
Paint myPaint = new Paint();
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setColor(getContext().getResources().getColor(R.color.ImgVBorder));
myPaint.setStrokeWidth(5);
Rect myRect = new Rect(xCrop, yCrop, cropWidth, yCrop + cropHeight);
canvas.drawRect(myRect, myPaint);
// Anchor point.
myPaint.setStyle(Paint.Style.FILL);
myPaint.setColor(getContext().getResources().getColor(R.color.ImgVAnchorPoint));
myPaint.setStrokeWidth(3);
int anchorPointW = 10;
int halfAnchorPointW = anchorPointW / 2;
/*
// Top left.
Rect anchorPoint = new Rect(xCrop + cropWidth - halfAnchorPointW, yCrop - halfAnchorPointW,
anchorPointW, yCrop + halfAnchorPointW);
canvas.drawRect(anchorPoint, myPaint);
// Top right.
anchorPoint.set(xCrop + cropWidth - halfAnchorPointW, yCrop - halfAnchorPointW,
anchorPointW, yCrop + halfAnchorPointW);
canvas.drawRect(anchorPoint, myPaint);
*/
}
Integer[] getScreenWidthAndHeight(){
DisplayMetrics dMetrics = new DisplayMetrics();
((MainActivity)getContext()).getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
Integer[] myResult = new Integer[2];
myResult[0] = dMetrics.widthPixels - 40;
myResult[1] = dMetrics.heightPixels;
return myResult;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
final String TAG = "!!!123";
switch (action) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "Action was DOWN");
return true;
case MotionEvent.ACTION_MOVE:
Log.d(TAG, "Action was MOVE");
break;
case MotionEvent.ACTION_UP:
Log.d(TAG, "Action was UP");
break;
case MotionEvent.ACTION_CANCEL:
Log.d(TAG, "Action was CANCEL");
break;
case MotionEvent.ACTION_OUTSIDE:
Log.d(TAG, "Movement occurred outside bounds of current screen element");
break;
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return super.onTouchEvent(event);
}
}
</code></pre>
| <p>Here's how i solved, by defining a custom image view and make some change in OnDraw method, i also added code to reduce brightness of image so it looks nice with a background image behind the real when you resize the rectangle:</p>
<pre><code>import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class CustomCropImageView extends ImageView implements View.OnTouchListener{
// Bitmap to draw.
Bitmap myBitmap;
// Fundamental attributes.
int xPos, yPos;
int originWidth, originHeight;
int widthImg, heightImg;
int xCrop, yCrop;
int cropWidth, cropHeight;
int offsetLeft = 0, offsetRight = 0, offsetTop = 0, offsetBottom = 0;
// List of anchor point rectangle.
List<Rect> anchorPoints;
int anchorPointW = 30;
int halfAnchorPointW = anchorPointW / 2;
// Background bitmap for cropping.
Bitmap darkBitmap;
public CustomCropImageView(Context context){
super(context);
xPos = yPos = xCrop = yCrop = 0;
// setOnTouchListener(this);
}
public CustomCropImageView(Context context, AttributeSet attSet){
super(context, attSet);
xPos = yPos = xCrop = yCrop = 0;
// setOnTouchListener(this);
}
Integer[] myDWAndH;
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if(drawable == null)
return;
if(originWidth == 0 && originHeight == 0){
Bitmap tmp = ((BitmapDrawable)drawable).getBitmap();
myBitmap = tmp.copy(Bitmap.Config.ARGB_8888, true);
originWidth = myBitmap.getWidth();
originHeight = myBitmap.getHeight();
myDWAndH = getScreenWidthAndHeight();
widthImg = cropWidth = myDWAndH[0] - anchorPointW;
heightImg = cropHeight = (int)((float)myDWAndH[0]*((float)originHeight / (float)originWidth)) - anchorPointW;
yPos = yCrop = (myDWAndH[1] - heightImg) / 2;
myBitmap = Bitmap.createScaledBitmap(myBitmap, widthImg, heightImg, false);
createDarkBitmap(myBitmap);
initAnchorPoint();
}
Paint myPaint = new Paint();
canvas.drawBitmap(darkBitmap, xPos + halfAnchorPointW, yPos + halfAnchorPointW, myPaint);
drawAnchorRectangle(canvas);
}
void drawAnchorRectangle(Canvas canvas){
// Anchor rectangle.
Paint myPaint = new Paint();
canvas.drawBitmap(myBitmap, new Rect(offsetLeft, offsetTop, cropWidth + offsetRight, cropHeight + offsetBottom),
new Rect(xCrop + halfAnchorPointW + offsetLeft, yCrop + halfAnchorPointW + offsetTop,
xCrop + halfAnchorPointW + cropWidth + offsetRight, yCrop + halfAnchorPointW + cropHeight + offsetBottom), myPaint);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setColor(getContext().getResources().getColor(R.color.ImgVBorder));
myPaint.setStrokeWidth(5);
Rect myRect = new Rect(xCrop + halfAnchorPointW + offsetLeft, yCrop + halfAnchorPointW + offsetTop,
xCrop + halfAnchorPointW + cropWidth + offsetRight, yCrop + halfAnchorPointW + cropHeight + offsetBottom);
canvas.drawRect(myRect, myPaint);
// Anchor point.
myPaint.setStyle(Paint.Style.FILL);
myPaint.setColor(getContext().getResources().getColor(R.color.ImgVAnchorPoint));
// Top left.
canvas.drawRect(anchorPoints.get(0), myPaint);
// Top right.
canvas.drawRect(anchorPoints.get(1), myPaint);
// Bottom left.
canvas.drawRect(anchorPoints.get(2), myPaint);
// Bottom right.
canvas.drawRect(anchorPoints.get(3), myPaint);
}
void initAnchorPoint(){
if(anchorPoints != null)
anchorPoints.clear();
else
anchorPoints = new ArrayList<>();
// Top left.
anchorPoints.add(new Rect(xCrop + offsetLeft, yCrop + offsetTop,
xCrop + anchorPointW + offsetLeft, yCrop + anchorPointW + offsetTop));
// Top right.
anchorPoints.add(new Rect(xCrop + cropWidth + offsetRight, yCrop + offsetTop,
xCrop + cropWidth + anchorPointW + offsetRight, yCrop + anchorPointW + offsetTop));
// Bottom left.
anchorPoints.add(new Rect(xCrop + offsetLeft, yCrop + cropHeight + offsetBottom,
xCrop + anchorPointW + offsetLeft, yCrop + cropHeight + anchorPointW + offsetBottom));
// Bottom right.
anchorPoints.add(new Rect(xCrop + cropWidth + offsetRight, yCrop + cropHeight + offsetBottom,
xCrop + cropWidth + anchorPointW + offsetRight, yCrop + cropHeight + anchorPointW + offsetBottom));
}
Integer[] getScreenWidthAndHeight(){
DisplayMetrics dMetrics = new DisplayMetrics();
((MainActivity)getContext()).getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
Integer[] myResult = new Integer[2];
myResult[0] = dMetrics.widthPixels - 40;
myResult[1] = dMetrics.heightPixels;
return myResult;
}
int anchorChoice = -1;
void setAnchorAction(MotionEvent event){
int x = (int)event.getRawX();
int y = (int)event.getRawY();
int offset = 50 + anchorPointW;
anchorChoice = -1;
if(y > (anchorPoints.get(0).top - offset) && y < (anchorPoints.get(0).bottom + offset)){
if(x < (anchorPoints.get(0).right + offset) && x > (anchorPoints.get(0).left - offset)){
anchorChoice = 0;
}
else if(x < (anchorPoints.get(1).right + offset) && x > (anchorPoints.get(1).left - offset))
anchorChoice = 1;
}
else if(y > (anchorPoints.get(2).top - offset) && y < (anchorPoints.get(2).bottom + offset)){
if(x < (anchorPoints.get(2).right + offset) && x > (anchorPoints.get(2).left - offset)){
anchorChoice = 2;
}
else if(x < (anchorPoints.get(3).right + offset) && x > (anchorPoints.get(3).left - offset))
anchorChoice = 3;
}
}
void resizeRectangle(MotionEvent event){
if(anchorChoice == -1)
return;
int x = (int)event.getRawX();
int y = (int)event.getRawY();
int dif = 0;
initAnchorPoint();
invalidate();
// xCrop + halfAnchorPointW + offsetLeft, yCrop + halfAnchorPointW + offsetTop,
// xCrop + halfAnchorPointW + cropWidth + offsetRight, yCrop + halfAnchorPointW + cropHeight + offsetBottom
int prevOLeft = offsetLeft;
int prevORight = offsetRight;
int prevOTop = offsetTop;
int prevOBottom = offsetBottom;
if(anchorChoice == 0){
offsetLeft = (x - xCrop - halfAnchorPointW);
offsetTop = (y - yCrop - halfAnchorPointW);
}
else if(anchorChoice == 1){
offsetRight = (x - xCrop - halfAnchorPointW - cropWidth);
offsetTop = (y - yCrop - halfAnchorPointW);
}
else if(anchorChoice == 2){
offsetLeft = (x - xCrop - halfAnchorPointW);
offsetBottom = (y - yCrop - halfAnchorPointW - cropHeight);
}
else if(anchorChoice == 3){
offsetRight = (x - xCrop - halfAnchorPointW - cropWidth);
offsetBottom = (y - yCrop - halfAnchorPointW - cropHeight);
}
// Boundaries.
// Left boundary.
if(xCrop + offsetLeft < xCrop)
offsetLeft = 0;
if(xCrop + halfAnchorPointW + cropWidth + offsetRight < xCrop + anchorPointW + offsetLeft)
offsetRight = prevORight;
// Top boundary.
if(yCrop + offsetTop < yCrop)
offsetTop = 0;
if(yCrop + halfAnchorPointW + cropHeight + offsetBottom < yCrop + anchorPointW + offsetTop)
offsetBottom = prevOBottom;
// Right boundary.
if(xCrop + halfAnchorPointW + cropWidth + offsetRight > xCrop + halfAnchorPointW + cropWidth)
offsetRight = 0;
if(xCrop + anchorPointW + offsetLeft > xCrop + halfAnchorPointW + cropWidth + offsetRight)
offsetLeft = prevOLeft;
// Bottom boundary.
if(yCrop + halfAnchorPointW + cropHeight + offsetBottom > yCrop + halfAnchorPointW + cropHeight)
offsetBottom = 0;
if(yCrop + anchorPointW + offsetTop > yCrop + halfAnchorPointW + cropHeight + offsetBottom)
offsetTop = prevOTop;
// End boundaries.
return;
}
void createDarkBitmap(Bitmap processedBitmap){
darkBitmap = Bitmap.createBitmap(processedBitmap.getWidth(), processedBitmap.getHeight(), Bitmap.Config.ARGB_8888);
int substractValue = 220;
for(int i = 0; i < processedBitmap.getWidth(); i++){
for(int j = 0; j < processedBitmap.getHeight(); j++){
int pixelToProcess = processedBitmap.getPixel(i, j);
// Get component infos.
int r = Color.red(pixelToProcess);
int g = Color.green(pixelToProcess);
int b = Color.blue(pixelToProcess);
int alpha = Color.alpha(pixelToProcess);
// Process component info.
alpha -= substractValue;
// alpha = alpha - substractValue;
darkBitmap.setPixel(i, j, Color.argb(alpha, r, g, b));
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
final String TAG = "!!!123";
switch (action) {
case MotionEvent.ACTION_DOWN:
setAnchorAction(event);
Log.d(TAG, "" + anchorChoice);
return true;
case MotionEvent.ACTION_MOVE:
resizeRectangle(event);
break;
case MotionEvent.ACTION_UP:
Log.d(TAG, "Action was UP");
break;
case MotionEvent.ACTION_CANCEL:
Log.d(TAG, "Action was CANCEL");
break;
case MotionEvent.ACTION_OUTSIDE:
Log.d(TAG, "Movement occurred outside bounds of current screen element");
break;
}
return super.onTouchEvent(event);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return super.onTouchEvent(event);
}
}
</code></pre>
|
One process writing while the other one reads the shared memory <p>I have 2 programs (processes). One process writes to shared memory while the other reads it. So, my approach was like this:
Initially, value of shared memory is 0. So, process 1 writes only when value is 0. Now process 1 has written some other value to shm and "waits" till value becomes 0. Process 2 reads the shm and writes 0 to it. By wait, I mean in while(1) loop.</p>
<p>My question is if this approach fine or can I do better with some other approach in terms of CPU usage and memory usage?</p>
| <p>Mentioned problem known as Process Synchronization problem and given logic is nothing but Busy Waiting approach of the problem which is very primary solution.</p>
<p>Read <a href="https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem" rel="nofollow">Producer-Consumer Problem</a> which is similiar to given problem.</p>
<p>There are some better solutions to this than Busy Waiting like:</p>
<p>Spinlock, Semaphore etc.</p>
<p>You can get basic knowledge of all of this from <a href="https://en.wikipedia.org/wiki/Synchronization_(computer_science)" rel="nofollow">here</a></p>
<p>Hope it will help!!</p>
|
Score variable won't update, and must be final? <p>The issue I'm having is that my score counter variable 'score' cannot go higher than 1 in my program. If the user inputs a value equal to the random number displayed (LoadG1), they are awarded a point. This is then outputted at the end, as shown in the longer timer. In the shorter timer, the point is added. The int variable is declared at the beginning. All is shown below. Now I'm aware that it's final, and that this is most likely the cause of my issue, but the IDE requires it to be final otherwise I can only call the variable 'score' in one method (CountDown Timer in my case). This is causing me problems. I intend to have a point added each time the 4 second timer repeats if the user has the correct input each time, though it can't go more than 1 at the moment. I would like the final score to be outputted at the end, as shown below.</p>
<p>The code:</p>
<pre><code>final int[] score = {0};
final Random generateG1 = new Random();
final int loadG1 = generateG1.nextInt(1000000)+10000;
final TextView number = (TextView) findViewById(R.id.number);
number.setText(" "+loadG1);
final CountDownTimer loop = new CountDownTimer(4000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
number.setVisibility(View.GONE);
final TextView prompt = (TextView) findViewById(R.id.prompt);
prompt.setVisibility(View.VISIBLE);
prompt.setText(" Enter the number");
final EditText input = (EditText) findViewById(R.id.enterAnswer);
input.setVisibility(View.VISIBLE);
input.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
Editable answer = input.getText();
int finalAnswer = Integer.parseInt(String.valueOf(answer));
int finalLoadG1 = Integer.parseInt(String.valueOf(loadG1));
input.setVisibility(View.GONE);
prompt.setVisibility(View.GONE);
if (finalAnswer == finalLoadG1) {
score[0]++;
}
number.setVisibility(View.VISIBLE);
final int loadG1 = generateG1.nextInt(1000000) + 10000;
number.setText(" " + loadG1);
input.getText().clear();
start();
return true;
default:
}
}
return false;
}
});
}
}.start();
new CountDownTimer(24000, 1000) {
@Override
public void onTick (long millisUntilFinished) {
}
@Override
public void onFinish() {
TextView result = (TextView) findViewById(R.id.outcome);
result.setText("Score: "+ score[0]);
TextView prompt = (TextView) findViewById(R.id.prompt);
prompt.setVisibility(View.GONE);
final EditText input = (EditText) findViewById(R.id.enterAnswer);
input.setVisibility(View.GONE);
loop.cancel();
}
}.start();
</code></pre>
<p>I'd greatly appreciate it if someone can provide me with a fix to my issue, thanks in advance.</p>
| <p>Because you are not reading the random value that you have generated, just the first one. So the first time the answer is correct, but next time you answer different, but the <code>if</code> compares to the firstly generated random number, so it is not counting as valid answer (if you enter same first number all times it will count). You need to read the number from the TextEdit number every time since there is the current number.</p>
<p>So it could be:</p>
<pre><code>final int[] score = {0};
final Random generateG1 = new Random();
final int loadG1 = generateG1.nextInt(1000000)+10000;
final TextView number = (TextView) findViewById(R.id.number);
number.setText(" "+loadG1);
final CountDownTimer loop = new CountDownTimer(4000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
number.setVisibility(View.GONE);
final TextView prompt = (TextView) findViewById(R.id.prompt);
prompt.setVisibility(View.VISIBLE);
prompt.setText(" Enter the number");
final EditText input = (EditText) findViewById(R.id.enterAnswer);
input.setVisibility(View.VISIBLE);
input.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
Editable answer = input.getText();
int finalAnswer = Integer.parseInt(String.valueOf(answer));
// here we get from text field the current correct value
int finalLoadG1 = Integer.parseInt(String.valueOf(number.getText()));
input.setVisibility(View.GONE);
prompt.setVisibility(View.GONE);
if (finalAnswer == finalLoadG1) {
score[0]++;
}
number.setVisibility(View.VISIBLE);
final int loadG1 = generateG1.nextInt(1000000) + 10000;
number.setText(" " + loadG1);
input.getText().clear();
start();
return true;
default:
}
}
return false;
}
});
}
}.start();
new CountDownTimer(24000, 1000) {
@Override
public void onTick (long millisUntilFinished) {
}
@Override
public void onFinish() {
TextView result = (TextView) findViewById(R.id.outcome);
result.setText("Score: "+ score[0]);
TextView prompt = (TextView) findViewById(R.id.prompt);
prompt.setVisibility(View.GONE);
final EditText input = (EditText) findViewById(R.id.enterAnswer);
input.setVisibility(View.GONE);
loop.cancel();
}
}.start();
</code></pre>
<p>Also, you could (and should) use AtomicInteger instead of <code>int[]</code>, the methods you'll be interested are:</p>
<pre><code>int AtomicInteger#get();
int AtomicInteger#incrementAndGet()
</code></pre>
<p>So declare the score as AtomicInteger like:</p>
<pre><code>final AtomicInteger score = new AtomicInteger();
</code></pre>
<p>then instead of <code>score[0]++;</code> do <code>score.incrementAndGet();</code></p>
<p>then when you read the results do: <code>score.get();</code></p>
|
Iterating through tables in Excel mac using office js is not working <p>I am trying to iterate through tables in Excel using office js</p>
<p>Here is the code sample(same as one in the docs here <a href="https://github.com/OfficeDev/office-js-docs/blob/master/reference/excel/tablecollection.md" rel="nofollow">https://github.com/OfficeDev/office-js-docs/blob/master/reference/excel/tablecollection.md</a>):</p>
<pre><code>Excel.run(function (ctx) {
var tables = ctx.workbook.tables;
tables.load('items');
return ctx.sync().then(function() {
console.log("tables Count: " + tables.count);
for (var i = 0; i < tables.items.length; i++)
{
console.log(tables.items[i].name);
}
});
}).catch(function(error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
</code></pre>
<p>Get the number of tables.</p>
<pre><code>Excel.run(function (ctx) {
var tables = ctx.workbook.tables;
tables.load('count');
return ctx.sync().then(function() {
console.log(tables.count);
});
}).catch(function(error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
});
</code></pre>
<p>The code works correctly on windows Excel 2016 but on Mac Excel 2016 both code samples throw an error of type: <strong>"General Exception"</strong>, and error location: <strong>"TableCollection.count"</strong></p>
| <p>We tried to repro the issue, but are not getting the "General Exception". We are getting an error in the first example of "PropertyNotLoaded", though that's understandable in the sense that the sample is slightly incorrect, the load statement should be <code>tables.load('name, count')</code> instead of <code>tables.load('items')</code>. But that still doesn't explain the error. And the second samples should work just fine.</p>
<p>Are you running this on an existing document? Is there something special about that document? If you ran this code against a completely new document with a couple of tables in it, would it work then? Also, what version number is your version of Office for Mac?</p>
|
Redirect visitor to his/her SO profile from my profile <p>I want to add a link in my profile which will redirect the visitor to his/her profile when it will be <code>clicked</code>.</p>
<p>I came across a profile few week ago(tried to find account but no luck ) which has the same implementation like as written below</p>
<p><code>i always upvote (this user) ... etc</code> where <code>this user</code> is a hyperlink which redirected me to my profile (seems cool to me).</p>
<p>Attempts Info</p>
<p>As we know , we can use <code>html</code> so it was easy to put a static link there like </p>
<pre><code><a href="http://stackoverflow.com/users"> Testing</a>
</code></pre>
<p>but the implementation required the dynamic code which should appends the user id at the end of the link so i thought of <code>Javascript</code> but it can't be used directly , result in the same <code>JS</code> code to displayed on my profile along with script tags.</p>
<p>but then i wrote the whole HTML template as and no <code>script</code> tag shown in my profile</p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<script>
window.localStorage.getItem('username'); // appear as it is
</script>
</head>
<body>
<a href="http://stackoverflow.com/users"> Testing</a>
</body>
</html>
</code></pre>
<p>but still , whatever i write inside script , displayed as it is on my profile screen, even i thought to get the <code>username</code> from <code>cookies</code> or browser but no luck </p>
<p>1.) How can get the visitor profile link and use it as <code>href</code> link ?</p>
<p>right now it looks like this and clicking on <code>testing</code> link, redirect visitor to users tab on SO site which is not desirable </p>
<p><a href="https://i.stack.imgur.com/7xoaH.png" rel="nofollow"><img src="https://i.stack.imgur.com/7xoaH.png" alt="enter image description here"></a></p>
<p>i would really appreciate any help or direction . Thanks you</p>
<p>Note : you can try this in your profile too , just copy paste the code in your profile section , i am not really asking to visit my profile for views</p>
| <p>I been trying since from two days and finally i just managed to do this by just making a small amendment to my code , no <code>javascript</code> required. Hurrraah!</p>
<p>All i needed to do was, add <strong><code>/current</code></strong> at the end of my URL's <strong><code>href</code></strong> link which will take the visitor to his/her profile when clicked.</p>
<p>so it should be like this</p>
<pre><code><a href="http://stackoverflow.com/users/current">
</code></pre>
<p>instead of this</p>
<pre><code><a href="http://stackoverflow.com/users">
</code></pre>
<p>small things do help !</p>
|
Swift - Predicate to filter an array by a property of member array <p>I need to filter out an array of MyClass3 Objects. An array of MyClass2 Objects is a member of MyClass3 object(Please refer to code below). MyClass2 object has an id. I have an idArray at hand. I need to filter out those MyClass3 objects in which all ids in idArray are present in its [MyClass2] member.</p>
<pre><code>class MyClass2 : NSObject {
var uid: Int = 0
init(uid : Int) {
self.uid = uid
}
}
class MyClass3 : NSObject {
var arr: [MyClass2]
init(units: [MyClass2]) {
arr = units
}
}
var units1 = [MyClass2(uid: 1),MyClass2(uid: 2), MyClass2(uid: 3), MyClass2(uid: 4), MyClass2(uid: 5)]
var units2 = [MyClass2(uid: 4),MyClass2(uid: 5), MyClass2(uid: 6)]
var units3 = [MyClass2(uid: 3),MyClass2(uid: 5), MyClass2(uid: 7), MyClass2(uid: 1)]
var ids = [1,5]
var available3: [MyClass3] = [MyClass3(units: units1), MyClass3(units: units2), MyClass3(units: units3)]
var filtered3: [MyClass3] = []
let searchPredicate: NSPredicate = NSPredicate(format: " ANY arr.uid IN \(ids)") // needed predicate
print(searchPredicate.predicateFormat)
filtered3 = (available3 as NSArray).filteredArrayUsingPredicate(searchPredicate) as! [MyClass3]
</code></pre>
<p>The required answer is that we need MyClass3(units: units1) and MyClass3(units: units3) in the filtered Array.</p>
<p>This is not working out. Can someone suggest a predicate format for this purpose</p>
| <p>You can do using perform intersection operation instead of NSPredicate:</p>
<p>Refer below link for this </p>
<p><a href="http://stackoverflow.com/questions/24589181/set-operations-union-intersection-on-swift-array?answertab=votes#tab-top">Set operations (union, intersection) on Swift array?</a></p>
|
Issues while trying to collect nested lists in Drools <p>I am facing some difficulties while trying to write a rule with Drools (6.4.Final).
Either my rule is not completely correct, or I am ending up writing several rules for the same goal but without conviction. I'd like to get your opinions based on your experiences and/or references to help me.</p>
<p>I have a fact (type C) that contains a list of E. </p>
<p>Each E :</p>
<ul>
<li>has an int attribute which is a year</li>
<li>may have a list of R</li>
</ul>
<p>Each R :</p>
<ul>
<li>has a type</li>
<li>has an amount</li>
</ul>
<p>I want to check, for one/each year, if the sum of the amounts of R of a certain type exceeds a value.
If it exceeds, I want to insert a fact (X) with all the E that are behind.</p>
<p><strong>My first try was</strong> :</p>
<pre><code>rule "Sum of R exceed for one year"
when
C( $listOfE : listOfE )
// Pick one E
E( $year : year ) from $listOfE
// All Es of the same year
// "collectLists" is a custom accumulate function that simply adds all the elements of a list
accumulate ( E(year == $year, $listofR : listofR ) from $listOfE;
$allR : collectLists($listofR))
// Check the sum
// "sumbd" is a custom accumulate function that simply adds BigDecimal (sum is broken for that in 6.4)
accumulate ( R( type == « X », $amount : amount ) from $allR;
$sum : sumbd($amount);
$cumulAnnee > 20000)
then
insert( new X($year, $elements));
end
</code></pre>
<p>It is working but there is an issue with elements in X that may not have any R or have R that do not match the expecting type...</p>
<p><strong>My second try is</strong>:</p>
<p>Several but simpler rules declaring a type to help accumulate data and working with single E.</p>
<pre><code>declare YearAccumulation
year : int
allE : java.util.List
sum : BigDecimal
end
rule "Sum of R exceed for one year (1)"
when
C( $listOfE : listOfE )
$e : E( $year : year ) from $listOfE
// No accumulation for this year yet
not(YearAccumulation( year == $year ))
accumulate ( R( type == « X », $amount : amount ) from $e.listOfR;
$amounts : collectList($amount),
$sum : sumbd($amount);
$amounts.size > 0)
then
YearAccumulation ya = new YearAccumulation();
ya.setYear($year);
List allE = new ArrayList();
allE.add($element);
ya.setAllE(allE);
ya.setSum($sum);
insert(ya);
end
rule "Sum of R exceed for one year (2)"
when
C( $listOfE : listOfE )
$e : E( $year : year ) from $listOfE
accumulate ( R( type == « X », $amount : amount ) from $e.listOfR;
$amounts : collectList($amount),
$sum : sumbd($amount);
$amounts.size > 0)
// Do not process already processed E
$ya : YearAccumulation ( year == $year, $e not memberOf allE)
then
$ya.getAllE().add($e);
$ya.setSum($ya.getSum().add($sum));
update($ya);
end
rule "Sum of R exceed for one year (3)"
when
YearAccumulation ($year:year, $elements:allE, sum > 20000)
then
insert( new X($year, $elements));
end
</code></pre>
<p>But I don't feel confident with this solution and it looks (quite) complicated to get the result.
Eventually I'd like to have a simple rule(s) that will be easy to understand and maintain.</p>
<p>Thanks</p>
| <p>A simple approach would be to collect all sums per year in one pass over all E and R and return a <code>Map<YearType,BigDecimal></code> where <code>YearType</code> combines a year and a type, and you can extract the Entry objects to inspect the BigDecimal etc. etc.</p>
<p>I'm not sure whether you can write a custom accumulate function returning a Map, but it can be done using the "traditional" accumulate syntax where you have init, action and result clauses to program anything you need.</p>
<p>This is a short version of the accumulate you might use: </p>
<pre><code>Map() from accumulate( E( $lr: listOfR != null, $y: year )
init( Map m = new HashMap(); )
action( for( int i = 0; i < $lr.size(); ++i ){
//... add to m.get($y) observing R's type
} )
result( m ) )
</code></pre>
|
Unable to save merged articles <p>So I'm trying to create a feature for Typo (blogging app) that merges two articles in one. For some reason, I can't manage to save the merged article. I have followed several threads here, read over and over Rails and Ruby docs... And Can't figure out why it doesn't work</p>
<p>Besides finding what's wrong with my code, I'd like to know best solutions to see what's going on 'under the hood', to debug the code. Eg: See when methods are called, what parameters are passed... </p>
<p>Here is my code: </p>
<p>View: </p>
<pre><code><% if @article.id && @user_is_admin %>
<h4>Merge Articles</h4>
<%=form_tag :action => 'merge_with', :id => @article.id do %>
<%= label_tag 'merge_with', 'Article ID' %>
<%= text_field_tag 'merge_with' %>
<%= submit_tag 'Merge' %>
<% end %>
<% end %>
</code></pre>
<p>Controller</p>
<pre><code>def merge_with
unless Profile.find(current_user.profile_id).label == "admin"
flash[:error] = _("You are not allowed to perform a merge action")
redirect_to :action => index
end
article = Article.find_by_id(params[:id])
debugger
if article.merge_with(params[:merge_with])
flash[:notice] = _("Articles successfully merged!")
redirect_to :action => :index
else
flash[:notice] = _("Articles couldn't be merged")
redirect_to :action => :edit, :id => params[:id]
end
end
</code></pre>
<p>Model: </p>
<pre><code>def merge_with(other_article_id)
other_article = Article.find_by_id(other_article_id)
if not self.id or not other_article.id
return false
end
self.body = self.body + other_article.body
self.comments << other_article.comments
self.save!
other_article = Article.find_by_id(other_article_id)
other_article.destroy
end
</code></pre>
<p>Thanks in advance, and sorry if this is a rookie question :)</p>
| <p>You did not mentioned what problem you are facing while saving, you just said you could not manage to save so I can't help you with that unless you provide some stack trace.
I will mention a few things though:</p>
<p>first is in your controller method you have multiple redirection code like <code>redirect_to :action => index</code> without any <code>return</code> from method so I think you will get <code>multiple redirect or render</code> error at some point like when <code>unless</code> executes and redirects but code continues the execution and throws error so try to reduce these redirects or mention it like <code>redirect_to :action => index and return</code>.</p>
<p>Then in model <code>merge_with</code> you are assigning <code>other_article</code> twice, you don't need the second one.</p>
<p>about debugging, you can create some <code>puts</code> line inside code and check it in rails server console to verify that the condition is executed like in controller method after <code>if article.merge_with</code> you can put:</p>
<pre><code>puts "merge sucess"
</code></pre>
<p>and check console when merge action is called, if you see <code>"merge sucess"</code> then <code>if</code> block executed.</p>
<p>OR
use <code>byebug</code> like you used <code>debugger</code>. It will stop the execution where it will find the <code>byebug</code> word and will give access to a live session in rails console.
if you put it where you have <code>debugger</code> you can access the console and do the operations manually like run:</p>
<pre><code>article.merge_with(params[:merge_with])
</code></pre>
<p>then see what happens. or put before <code>self.save!</code> in model and save it manually in console and check errors like <code>self.errors.messages</code>.</p>
<p>Stack trace is also helpful to see line by line code execution and identify the error.</p>
<p>I will update this if you post any info about what error you are facing</p>
|
Validation error An invalid form control with name='' is not focusable <p>I had a html form with set of input fields for each of which I am giving <code>required="true"</code> for validation. But when I click on submit after entering the mandatory fields it is give an error:</p>
<blockquote>
<p>An invalid form control with name='' is not focusable</p>
</blockquote>
<p>I know if we use <code>novalidate</code> to the form I wont get that error, but my validation wont work. How can I make my validation work without error?</p>
<pre><code> <form name="customerForm" class="form-horizontal" id="custForm">
<fieldset>
<div class="form-group">
<label for="customerName" class="col-lg-4 col-lg-offset-1 control-label">Name</label>
<div class="col-lg-4">
<input class="form-control" ng-model="$root.customerDetails.customerName" placeholder="Enter customer name" type="text" required="true" value = "{{customerName}}">
</div>
</div>
<div class="form-group">
<label for="postCode" class="col-lg-4 col-lg-offset-1 control-label">Post code</label>
<div class="col-lg-4">
<input class="form-control" ng-model="$root.customerDetails.address.postcode" placeholder="Enter post code" type="text" value = "{{postCode}}">
</div>
<div class="col-lg-2">
<button type="next" class="btn btn-primary" ng-click="$ctrl.findAddress()">Find address</button>
</div>
</div>
<div class="form-group">
<label for="selectAddress" class="col-lg-4 col-lg-offset-1 control-label">Select address</label>
<div class="col-lg-4">
<select class="form-control" id="selectAddress" ng-model="$ctrl.quote.newClient.customerAddress" ng-change="$ctrl.populateAddressFields()">
<option ng-repeat="address in addresses"
value="{{address}}" >{{address}}</option>
</select>
</div>
</div>
<div class="form-group ng-hide">
<label for="textArea" class="col-lg-4 col-lg-offset-1 control-label">Address</label>
<div class="col-lg-4">
<textarea ng-model="$ctrl.quote.newClient.customerAddress" class="form-control" rows="3" required="true"></textarea>
</div>
</div>
<div class="form-group">
<label for="address1" class="col-lg-4 col-lg-offset-1 control-label">Address 1</label>
<div class="col-lg-4">
<input class="form-control" ng-model="$root.customerDetails.address.addressLine1" placeholder="Enter Address 1" type="text" required="true" value = "{{addressLine1}}">
</div>
</div>
<div class="form-group">
<label for="address2" class="col-lg-4 col-lg-offset-1 control-label">Address 2</label>
<div class="col-lg-4">
<input class="form-control" ng-model="$root.customerDetails.address.addressLine2" placeholder="Enter Address 2" type="text" required="true" value = "{{addressLine2}}">
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-lg-4 col-lg-offset-1 control-label">Email address</label>
<div class="col-lg-4">
<input class="form-control" ng-model="$root.customerDetails.eMail" placeholder="Enter customer email" type="email" required="true" value = "{{emailId}}">
</div>
</div>
<div class="form-group">
<label for="customerMobile" class="col-lg-4 col-lg-offset-1 control-label">Mobile number</label>
<div class="col-lg-4">
<input class="form-control" ng-model="$root.customerDetails.customerMobile" placeholder="Enter customer mobile number" type="text" required="true">
</div>
</div>
<div class="form-group" ng-show="$root.customerDetails.tradeType.description == 'Limited Company'">
<label for="inputCompanyRegistrationNumber" class="col-lg-4 col-lg-offset-1 control-label">Company registration number</label>
<div class="col-lg-4">
<input class="form-control" ng-model="$root.customerDetails.companyRegNo" placeholder="Enter company registration number" type="text" required="true">
</div>
</div>
</fieldset>
</form>
</code></pre>
<p>And Iam using <code>$valid</code> to validate the form</p>
<pre><code><div class="col-lg-1">
<button form="custForm" type="submit" class="btn btn-primary right-button" ng-click="customerForm.$valid && $ctrl.proceedToPaymentDetails()">Next</button>
</div>
</code></pre>
| <p>The answer is very simple name and ID has to match for the angular, or it won't be able to find it</p>
<pre><code><form name="customerForm" id="customerForm"
</code></pre>
<p>here is the plunker which is just copy paste of your code but with the fields adjusted <a href="https://plnkr.co/edit/z8WaJF6QetQZxMR5pwap?p=preview" rel="nofollow">https://plnkr.co/edit/z8WaJF6QetQZxMR5pwap?p=preview</a></p>
|
avoid daemon running in dedicated cpu cores <p>I have grub set isolcpus=2 in my linux 3.10.0-327.el7.x86_64 , what I want is
avoid the kernel scheduler not to schedule task to cpu core 2 , then I have the</p>
<pre><code>perf record -e sched:sched_switch -C 2
</code></pre>
<p>to see what is going on in core 2 and then run my ap(which CPU_SET(2) ,
and following command :</p>
<pre><code>perf report --show-total-period -i perf.data
</code></pre>
<p>get result :</p>
<pre><code> 48.85% 85 swapper [kernel.kallsyms] [k] __schedule
18.97% 33 kworker/u384:0 [kernel.kallsyms] [k] __schedule
11.49% 20 :4594 [kernel.kallsyms] [k] __schedule
11.49% 20 smartd [kernel.kallsyms] [k] __schedule
4.60% 8 watchdog/2 [kernel.kallsyms] [k] __schedule
3.45% 6 sshd [kernel.kallsyms] [k] __schedule
1.15% 2 kworker/2:2 [kernel.kallsyms] [k] __schedule
</code></pre>
<p>I know kworker/2 , watchdog/2 are housekeeping tasks , thread id 4594 is what I run my app with CPU_SET(2) , But I really do want to avoid sshd , smartd daemons running in core 2 , Is there any config file or methods I can do to tell kernel that avoid daemons running in core 2 ?!</p>
<p>Edit :</p>
<p>after edit grub , there should be update-grub command and then reboot ,
I will try to figure out how to update-grub , I think grub config isolcpus=2 but it is not enabled yet , I will update the result after I make isolcpus=2 work . </p>
| <p>The program 'schedtool' maybe helpful, it can limit the process to run on specified cpu(s).
according to the help of that utility.
To set a process' affinity to only the first CPU (CPU0):
#> schedtool -a 0x1
replace the parameters 0x1 and PID according your exactly requirement.</p>
|
Update button text through inputfield <p>Is there a way to update button text dynamically while some value is being entered in an input field.</p>
<pre><code><input class="paymentinput w-input" type="tel" placeholder="0" id="amount-field">
<button id="rzp-button1" class="paynowbutton w-button">Pay Now</button>
</code></pre>
<p>I would like to update the button text "Pay Now" with the value which is entered in the input field with id="amount-field"</p>
<p>I know I am supposed to use onKeyUp for this, but I am slighly clueless about how to write this code. Any help is highly appreciated.</p>
| <p>is this something you want done ?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('.myName').keyup(function(){
if ($(this).val()==""){
$('button').text("Pay Now")
}else{
$('button').text($(this).val());
}
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="myName">
<button>sample</button></code></pre>
</div>
</div>
</p>
|
How does the framework know that `ModelState.IsValid` must be true in HTTPGET but false in HTTPPOST when the form fields are invalid? <p>Consider a simple data model <code>Student.cs</code> as follows,</p>
<pre><code>class Student
{
[Required(ErrorMessage="Please enter your name.")]
public string Name {get;set;}
// other properties go here
}
</code></pre>
<p>A form view <code>registration.cshtml</code> as follows,</p>
<pre><code><form asp-action="Registration" method="Post">
<p>ModelState.IsVali is @ViewBag.Message</p>
<p>Data: <input asp-for="Name"></p>
<button type="submit">Submit</button>
</form>
</code></pre>
<p>And action method as follow,</p>
<pre><code>[HttpGet]
ViewResult Registration()
{
ViewBag.Message=ModelState.IsValid;
return View();
}
[HttpPost]
ViewResult Registration(Student s)
{
if(!ModelState.IsValid){
ViewBag.Message=false;
return View();
}
}
</code></pre>
<ul>
<li><p>How does the framework know that <code>ModelState.IsValid</code> must be true in HTTPGET but false in HTTPPOST when the form fields are invalid? For me, the blank view form delivered to the user (by the HttpGet version of the action method) should make the <code>ModelState.IsValid</code> false.</p></li>
<li><p>Extra question: Why don't we need to do <code>return View(s);</code> instead of <code>return View();</code> when returning invalid form and preserving the entered data field? For me, <code>return View();</code> seems to return a blank form. </p></li>
</ul>
| <p>When you make a request (either GET or POST), the <code>DefaultModelBinder</code> reads values from the request (query string parameter, route values, form values etc), initializes any parameters in your method, and attempts to set their values.</p>
<p>In the case of your GET method, you do not have a model as a parameter, so there is nothing to initialize, and nothing to set, so nothing is ever added to <code>ModelState</code> and <code>ModelState.IsValid</code> returns <code>true</code> (it only returns false if there is a validation error as a result of setting the value of a model property).</p>
<p>In the case of the POST method, you have a parameter <code>Student s</code> which so a new instance of the model is initialized. If your textbox was left empty, a <code>ModelState</code> error would be added because of the <code>[Required]</code> attribute (by default, an empty string means <code>null</code>) and <code>ModelState.IsValid</code> would return <code>false</code>.</p>
<hr>
<p>Using <code>return View();</code> will return the current view without passing the model to the view. Any form controls generated with the <code>HtmlHelper</code> methods use values from <code>ModelState</code> if they exist (if not, the value is read from the <code>ViewDataDictionary</code> and then from the actual model) so if you initially posted <code>"xyz"</code>, a key/value pair of <code>Name: "xyz"</code> will be added to <code>ModelState</code>. Your <code>@Html.TextBoxFor(m => m.Name)</code> method finds a match in <code>ModelState</code> and the value of the textbox is set to "xyz". As proof, if in the POST method, you were to use</p>
<pre><code>s.Name = "Another Value";
return View(s);
</code></pre>
<p>you will see that the textbox retains the original value you posted, not "Another Value"</p>
<p>If however you were also to include <code><div>@Model.Name</div></code>, a <code>NullReferenceException</code> would be thrown (because you cannot access the <code>Name</code> property of <code>null</code>) so you should always return a model to the view.</p>
|
ruby on rails marketplace and stripe <p>I am building a two side marketplace with RoR,
and i want to use stripe to handle the payment.</p>
<p>I want the user to do a request and pay, (but using capture false, to charge later), and charge (or cancel) when the user providing the service accept or deny the request.</p>
<p>So what i've done so far:</p>
<p>.Submiting the request
.creating a new request in the DB (with a boolean statut)
.User can valid or not</p>
<p>But now i don't know how to record the outcome and update the statut of this request and so that point make a new api call to update the payment.</p>
<p>Anyone already done that ?</p>
| <p>First, you'd <a href="https://stripe.com/docs/api#create_charge" rel="nofollow">create the charge</a> with <code>capture</code> set to <code>false</code>:</p>
<pre><code>charge = Stripe::Charge.create({
amount: 1000,
currency: 'usd',
destination: 'acct_...',
application_fee: 200,
capture: false,
})
</code></pre>
<p>If the charge succeeds, you'd save the charge's ID (<code>charge.id</code>) in your database.</p>
<p>Then, if the transaction is confirmed, you'd <a href="https://stripe.com/docs/api#capture_charge" rel="nofollow">capture the charge</a> like this:</p>
<pre><code># Retrieve charge_id from your database
charge = Stripe::Charge.retrieve(charge_id)
charge.capture
</code></pre>
<p>If the transaction is canceled, you'd release the authorization by <a href="https://stripe.com/docs/api#create_refund" rel="nofollow">refunding the charge</a>:</p>
<pre><code># Retrieve charge_id from your database
refund = Stripe::Refund.create({
charge: charge_id,
})
</code></pre>
<p>Note that uncaptured charges are <a href="https://support.stripe.com/questions/does-stripe-support-authorize-and-capture" rel="nofollow">automatically released after 7 days</a>.</p>
<p>In the above, I assumed you were creating charges <a href="https://support.stripe.com/questions/does-stripe-support-authorize-and-capture" rel="nofollow">through the platform</a>, i.e. with the <code>destination</code> parameter. If you are instead charging <a href="https://stripe.com/docs/connect/payments-fees#charging-directly" rel="nofollow">directly on connected accounts</a>, you'd need to modify the requests to use the <a href="https://stripe.com/docs/connect/authentication#authentication-via-the-stripe-account-header" rel="nofollow"><code>Stripe-Account</code></a> header:</p>
<pre><code># Create the charge directly on the connected account
charge = Stripe::Charge.create({
amount: 1000,
currency: 'usd',
application_fee: 200,
capture: false,
}, {stripe_account: 'acct_...'})
# Save charge.id in your database
# Capture the charge
charge = Stripe::Charge.retrieve(charge_id, {stripe_account: 'acct_...'})
charge.capture
# Release the uncaptured charge
refund = Stripe::Refund.create({
charge: charge_id,
}, {stripe_account: 'acct_...'})
</code></pre>
|
O(1) Constant time solution example? <p>I have a task which requires calculating a frog jumping from position X to a position greater than or equal to Y, given a fixed distance each jump (D).</p>
<p>E.g
X = 10; Y = 85; D = 30; Answer = ((Y-X)/D) = 3;</p>
<p>The solutions complexity must be <strong>O(1)</strong>.</p>
<p>The obvious solution didn't work:</p>
<pre><code>int diff=Y-X;
int jumps=diff/D;
</code></pre>
<p>Because if jumps returns a double which rounds down, this will not be equal to or greater.</p>
<p>I can use a while loop:</p>
<pre><code>int diff=Y-X;
int jumps=0;
int jumps_counter=0;
while(jumps<diff)
{
jumps+=D;
jumps_counter++;
}
</code></pre>
<p>However clearly this isn't going to be O(1), instead O(x-y)...</p>
<p>Whats the best way to solve this?</p>
| <p>Obvious solution would be to round it up.</p>
<pre><code>int diff = Y-X;
int jumps = std::ceil((double)diff/D);
</code></pre>
<p>This is an O(1) operation and avoids looping to find the required number of steps.</p>
|
Inherited constructors, default constructor and visibility <p>As stated by <a href="http://eel.is/c++draft/namespace.udecl#18" rel="nofollow">[namespace.udecl]/18</a>:</p>
<blockquote>
<p>[...] A using-declaration that names a constructor does not create a synonym; instead, the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class, and the accessibility of the using-declaration is ignored. [...]</p>
</blockquote>
<p>Because of that, the following code does not compile:</p>
<pre><code>class B { protected: B(int) { } };
class D: B { using B::B; };
int main () { D d{0}; }
</code></pre>
<p>It returns an error that is more or less the same with all the major compilers:</p>
<blockquote>
<p>declared protected here</p>
</blockquote>
<p>On the other side, the following code compiles:</p>
<pre><code>class B { protected: B() { } };
class D: B { using B::B; };
int main () { D d{}; }
</code></pre>
<p>Shouldn't it fail to compile instead for the same reasons that lead to an error in the previous example?<br>
What does it allow it to compile?</p>
| <pre><code>class B { protected: B() { } };
class D: B { using B::B; };
int main () { D d{}; }
</code></pre>
<p><code>D</code> has no user-defined constructor in this case, so the compiler generates one (public) for you that calls <code>B::B</code> (but not because of the <code>using</code>, that has no effect in this case), that compiler-generated constructor is then called by main.</p>
<pre><code>class B { protected: B(int) { } };
class D: B { using B::B; };
int main () { D d{0}; }
</code></pre>
<p>Even though <code>D</code> has no user-defined constructor here, the compiler-generated one is implicitly deleted because <code>B</code> only has a constructor that takes an <code>int</code>. <code>D</code> does also have a constructor that takes an <code>int</code> (<code>using</code> did that) but this constructor is marked <code>protected</code> and thus inaccessible by <code>main</code>.</p>
|
Saving image in python <p>I'm new to python. What I want to do is to read in an image, convert it to gray value and save it.</p>
<p>This is what I have so far:</p>
<pre><code># construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())
#Greyvalue image
im = Image.open(args["image"])
im_grey = im.convert('LA') # convert to grayscale
</code></pre>
<p>Now my problem is how to save it. As far as I unterstood there are a lot of different modules (Using python 2.7) Could someone give my an example?</p>
<p>Thanks</p>
| <p><strong>Method 1: save method</strong></p>
<pre><code>im_grey.save('greyscale.png')
</code></pre>
<p>Use Image_object.save() method</p>
<p><strong>Method 2: imsave method</strong></p>
<pre><code>import matplotlib.image as mpimg
mpimg.imsave("greyscale.png", im_grey)
</code></pre>
|
MySQL Function IF() do not return the value that i declare <blockquote>
<p>i want my function to return "INC" when put "INC" inside the function parameters</p>
</blockquote>
<pre><code>SELECT getEquivalentGrade('INC');
</code></pre>
<blockquote>
<p>Output: INC</p>
</blockquote>
<pre><code>DELIMITER $$
USE `nmsc_scholarship_db`$$
DROP FUNCTION IF EXISTS `getEquivalentGrade`$$
CREATE DEFINER =`root`@`localhost` FUNCTION `getEquivalentGrade`(grade CHAR(5))
RETURNS CHAR(5)
CHARSET latin1
BEGIN
DECLARE equivalent_grade CHAR(5);
IF (grade > 100)
THEN
SET equivalent_grade = '1';
ELSEIF (grade < 69)
THEN
SET equivalent_grade = '5';
ELSEIF (grade = 'INC')
THEN
SET equivalent_grade = grade;
ELSE
SET equivalent_grade = (SELECT equivalent_grade.`equivgrade`
FROM equivalent_grade
WHERE equivalent_grade.`fromgrade` <= grade AND equivalent_grade.`tograde` >= grade);
END IF;
RETURN equivalent_grade;
END$$
DELIMITER ;
</code></pre>
<blockquote>
<p><strong>now, if i will execute this function, this is what i get.</strong></p>
</blockquote>
<pre><code>SELECT getEquivalentGrade('INC');
</code></pre>
<blockquote>
<p><strong>Output: 5</strong></p>
</blockquote>
| <p>You should move the INC to the TOP </p>
<pre><code>IF (grade='INC') THEN
SET equivalent_grade = grade;
ELSEIF (grade > 100) THEN
SET equivalent_grade = '1';
ELSEIF (grade < 69) THEN
SET equivalent_grade = '5';
ELSE
SET equivalent_grade = (SELECT equivalent_grade.`equivgrade` FROM equivalent_grade WHERE equivalent_grade.`fromgrade`<= grade AND equivalent_grade.`tograde`>= grade);
</code></pre>
<p>And you should research how IFELSE work.
Condition was working like it will stop/goto ENDIF.. IF** the condition <strong>true</strong> was meet, or they will keep finding till the latest <strong>IF</strong></p>
|
Execute a Program with arguments <p>I want to build a PowerShell script for invoking Python3. Now in shell this would be pretty simple but I cannot seem to get the following converted to PS:</p>
<pre><code>../py/python3 myscript.py $@
</code></pre>
<p>I am lost somewhere in the maze of <code>Start-Process</code>, <code>get-item</code>, path building, ...
Is there any EASY way of doing that in PowerShell?</p>
| <p>PowerShell is a shell, so for the most part, running programs is what it does well. I'm guessing you're converting a Unix shell script which is where <code>$@</code> comes from. The equivalent in PowerShell for that would probably be <code>$args</code> or <code>@args</code>:</p>
<pre><code>../py/python3 myscript.py $args
</code></pre>
<p>Within a script, <code>$args</code> contains the arguments to that script. However, within a script block or function it will contain the arguments to that script block or function, so careful when abstracting things in your script.</p>
|
State design pattern in compliance with Liskov <p>I am designing an order system and the state design pattern seems appropriate because the order can change its state and thereby the allowed functionalities for the order. Below is my basic class diagram:</p>
<p><img src="https://i.stack.imgur.com/QRbP5.jpg" alt=""></p>
<p>I do not like this approach because clients cannot see if a method is supported and violates Liskov principle. I created an alternative below: </p>
<p><img src="https://i.stack.imgur.com/nvXWc.jpg" alt=""></p>
<p>I like this better but still the client has to check if a method is supported. But they can still call the unsupported method and get an exception. Does this still violates the Liskov principle?</p>
<p>Is there a better design that is in compliance with Liskov and keeps the user from calling invalid methods for a specific state?</p>
| <p>What you are showing is not State pattern. State pattern alters object behavior when its internal state changes. For example, a light switch can turn on or turn off the light when you toggle it, depending on its state (different behavior on the same method).</p>
<p>With this Order interface (4 diff methods) I don't see any benefits of introducing State pattern. It will only complicate things for no reason. But I don't know all the details so it is up to you what to do next.</p>
<p>Check this link to see examples of State patten implementation <a href="https://sourcemaking.com/design_patterns/state" rel="nofollow">https://sourcemaking.com/design_patterns/state</a></p>
|
Invalid syntax error at end <p>I am getting invalid syntax error for end in below line </p>
<pre><code>print("\t" **end** = " ")
</code></pre>
<p>Below is the code -</p>
<pre><code>def print_lol(the_list,level):
for each_item in the_list:
if isinstance (each_item,list):
print_lol(each_item,level+1)
else:
for tab_stop in range(level):
print("\t" end = " ")
print(each_item)
</code></pre>
<p>Please help</p>
| <p>it should be like these:</p>
<pre><code>print("\t", end = " ")
</code></pre>
<p>also please note that for good practice make the indentation of your <code>else</code> statement the same with the <code>if</code> statement indentation.</p>
|
Where is define codeigniters rewrite rules for recognizing controller,method,id in segment? <p>how codignitetr recognzes controllername,methodname,id from url like:</p>
<p><a href="http://stackoverflow.com/controllername/methodname/id">http://stackoverflow.com/controllername/methodname/id</a></p>
| <p>The most used method for this is <code>CI_URI->segments();</code> </p>
<p>Read more here: <a href="https://www.codeigniter.com/userguide3/libraries/uri.html#CI_URI::segment" rel="nofollow">https://www.codeigniter.com/userguide3/libraries/uri.html#CI_URI::segment</a></p>
<blockquote>
<p>So, each / after your host be different segment.</p>
</blockquote>
<p>For example:</p>
<pre><code>//http://stackoverflow.com/controllername/methodname/id
echo $this->uri->segment(1); // controllername
echo $this->uri->segment(2); // methodname
echo $this->uri->segment(3); // id
</code></pre>
|
How to change entity name in flash message <p>After editing an object I got this flash message</p>
<blockquote>
<p>L'élément "P\BOBundle\Entity\Distributeur:0000000037396bc6000000006e8ad34e" a été mis à jour avec succès.</p>
</blockquote>
<p>So I need to change the entity name in this message: <code>P\BOBundle\Entity\Distributeur:0000000037396bc6000000006e8ad34e</code> to <code>Distributeur</code>.</p>
| <p>the best solution is to override </p>
<blockquote>
<p>__toString</p>
</blockquote>
<p>methode in the entity class and make it return the name of object. </p>
|
Read HBase table with where clause using Spark <p>I am trying to read a HBase table using Spark Scala API.</p>
<p><strong>Sample Code:</strong></p>
<pre><code>conf.set("hbase.master", "localhost:60000")
conf.set("hbase.zookeeper.quorum", "localhost")
conf.set(TableInputFormat.INPUT_TABLE, tableName)
val hBaseRDD = sc.newAPIHadoopRDD(conf, classOf[TableInputFormat], classOf[ImmutableBytesWritable], classOf[Result])
println("Number of Records found : " + hBaseRDD.count())
</code></pre>
<p>How to add <code>where</code> clause if i use <code>newAPIHadoopRDD</code> ?</p>
<p>Or we need to use any <code>Spark Hbase Connector</code> to achieve this?</p>
<p>I saw the below Spark Hbase connector, but i don't see any example code with where clause.</p>
<p><a href="https://github.com/nerdammer/spark-hbase-connector" rel="nofollow">https://github.com/nerdammer/spark-hbase-connector</a></p>
| <blockquote>
<p><strong>Q : How to add where clause if i use <code>newAPIHadoopRDD</code> ? Or we need to use any Spark Hbase Connector to achieve this?</strong></p>
</blockquote>
<p>Answer</p>
<ul>
<li><p>SparkOnHBase project in Cloudera provide support for spark hbase integration on RDD level.</p></li>
<li><p>If you are expecting DataFrame kind of then you can have a look at
<a href="http://hortonworks.com/blog/spark-hbase-dataframe-based-hbase-connector" rel="nofollow">Horton Works - spark-hbase-dataframe-based-hbase-connector</a>
where you can use dataframe and filter/where</p></li>
</ul>
<blockquote>
<p><a href="http://hortonworks.com/blog/spark-hbase-dataframe-based-hbase-connector" rel="nofollow">SCAN AND BULKGET These two operators are exposed to users by
specifying <strong>WHERE CLAUSE</strong>, <strong><em>e.g., WHERE column > x and column < y for</em></strong>
<strong><em>scan and WHERE column = x for get</em></strong>. The operations are performed in the
executors, and the driver only constructs these operations. Internally
they are converted to scan and/or get, and Iterator[Row] is returned
to catalyst engine for upper layer processing.</a></p>
</blockquote>
<h3>Example with where condition working.. <a href="https://github.com/hortonworks-spark/shc/tree/master/src/main/scala/org/apache/spark/sql/execution/datasources/hbase/examples" rel="nofollow">from</a></h3>
<pre><code>package org.apache.spark.sql.execution.datasources.hbase.examples
import org.apache.spark.sql.{SQLContext, _}
import org.apache.spark.sql.execution.datasources.hbase._
import org.apache.spark.{SparkConf, SparkContext}
case class HBaseRecord(
col0: String,
col1: Boolean,
col2: Double,
col3: Float,
col4: Int,
col5: Long,
col6: Short,
col7: String,
col8: Byte)
object HBaseRecord {
def apply(i: Int): HBaseRecord = {
val s = s"""row${"%03d".format(i)}"""
HBaseRecord(s,
i % 2 == 0,
i.toDouble,
i.toFloat,
i,
i.toLong,
i.toShort,
s"String$i extra",
i.toByte)
}
}
object HBaseSource {
val cat = s"""{
|"table":{"namespace":"default", "name":"shcExampleTable"},
|"rowkey":"key",
|"columns":{
|"col0":{"cf":"rowkey", "col":"key", "type":"string"},
|"col1":{"cf":"cf1", "col":"col1", "type":"boolean"},
|"col2":{"cf":"cf2", "col":"col2", "type":"double"},
|"col3":{"cf":"cf3", "col":"col3", "type":"float"},
|"col4":{"cf":"cf4", "col":"col4", "type":"int"},
|"col5":{"cf":"cf5", "col":"col5", "type":"bigint"},
|"col6":{"cf":"cf6", "col":"col6", "type":"smallint"},
|"col7":{"cf":"cf7", "col":"col7", "type":"string"},
|"col8":{"cf":"cf8", "col":"col8", "type":"tinyint"}
|}
|}""".stripMargin
val cat1 = s"""{
|"table":{"namespace":"default", "name":"shcExampleTable1"},
|"rowkey":"key",
|"columns":{
|"col0":{"cf":"rowkey", "col":"key", "type":"string"},
|"col1":{"cf":"cf1", "col":"col1", "type":"boolean"},
|"col2":{"cf":"cf2", "col":"col2", "type":"double"},
|"col3":{"cf":"cf3", "col":"col3", "type":"float"},
|"col4":{"cf":"cf4", "col":"col4", "type":"int"},
|"col5":{"cf":"cf5", "col":"col5", "type":"bigint"},
|"col6":{"cf":"cf6", "col":"col6", "type":"smallint"},
|"col7":{"cf":"cf7", "col":"col7", "type":"string"},
|"col8":{"cf":"cf8", "col":"col8", "type":"tinyint"}
|}
|}""".stripMargin
def main(args: Array[String]) {
val sparkConf = new SparkConf().setAppName("HBaseTest")
val sc = new SparkContext(sparkConf)
val sqlContext = new SQLContext(sc)
import sqlContext.implicits._
def withCatalog(cat: String): DataFrame = {
sqlContext
.read
.options(Map(HBaseTableCatalog.tableCatalog->cat))
.format("org.apache.spark.sql.execution.datasources.hbase")
.load()
}
// for testing connection sharing only
def withCatalog1(cat: String): DataFrame = {
sqlContext
.read
.options(Map(HBaseTableCatalog.tableCatalog->cat1))
.format("org.apache.spark.sql.execution.datasources.hbase")
.load()
}
val data = (0 to 255).map { i =>
HBaseRecord(i)
}
sc.parallelize(data).toDF.write.options(
Map(HBaseTableCatalog.tableCatalog -> cat, HBaseTableCatalog.newTable -> "5"))
.format("org.apache.spark.sql.execution.datasources.hbase")
.save()
// for testing connection sharing only
sc.parallelize(data).toDF.write.options(
Map(HBaseTableCatalog.tableCatalog -> cat1, HBaseTableCatalog.newTable -> "5"))
.format("org.apache.spark.sql.execution.datasources.hbase")
.save()
val df = withCatalog(cat)
df.show
df.filter($"col0" <= "row005")
.select($"col0", $"col1").show
df.filter($"col0" === "row005" || $"col0" <= "row005")
.select($"col0", $"col1").show
df.filter($"col0" > "row250")
.select($"col0", $"col1").show
df.registerTempTable("table1")
val c = sqlContext.sql("select count(col1) from table1 where col0 < 'row050'")
c.show()
// for testing connection sharing only
val df1 = withCatalog(cat1)
df1.show
df1.filter($"col0" <= "row005")
.select($"col0", $"col1").show
df1.filter($"col0" === "row005" || $"col0" <= "row005")
.select($"col0", $"col1").show
df1.filter($"col0" > "row250")
.select($"col0", $"col1").show
df1.registerTempTable("table1")
val c1 = sqlContext.sql("select count(col1) from table1 where col0 < 'row050'")
c1.show()
}
}
</code></pre>
<ul>
<li><p>If you are expecting to use what was given in API <a href="https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/SparkContext.html" rel="nofollow">see doc</a>.</p>
<p><a href="https://i.stack.imgur.com/OF5SS.png" rel="nofollow"><img src="https://i.stack.imgur.com/OF5SS.png" alt="enter image description here"></a> </p></li>
</ul>
<blockquote>
<p>Get an RDD for a given Hadoop file with an arbitrary new API
InputFormat and extra configuration options to pass to the input
format.</p>
</blockquote>
<p>So Standard <code>RDD</code> operations like map etc.. will apply.</p>
<p>Also see <a href="http://stackoverflow.com/a/27514526/647053">@javadba's answer</a>.</p>
<p>Another example </p>
<pre><code>import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.rdd._
import org.apache.hadoop.hbase.client.HBaseAdmin
import org.apache.hadoop.hbase.{HBaseConfiguration, HTableDescriptor}
import org.apache.hadoop.hbase.mapreduce.TableInputFormat
object ScoresAnalyzer {
def main(args: Array[String]) {
val scconf = new SparkConf().setAppName("Scores Analyzer").setMaster("local")
val sc = new SparkContext(scconf)
val conf = HBaseConfiguration.create()
conf.set("hbase.zookeeper.quorum", "quickstart.cloudera")
conf.set(TableInputFormat.INPUT_TABLE, "tweets")
val hBaseRDD = sc.newAPIHadoopRDD(conf, classOf[TableInputFormat],
classOf[org.apache.hadoop.hbase.io.ImmutableBytesWritable],
classOf[org.apache.hadoop.hbase.client.Result])
val categories = hBaseRDD.map(tuple => tuple._2).map(result => (result.getRow, result.getColumn("metrics".getBytes(), "categories".getBytes())))
val keywords = hBaseRDD.map(tuple => tuple._2).map(result => (result.getRow, result.getColumn("metrics".getBytes(), "keywords".getBytes())))
val sentiments = hBaseRDD.map(tuple => tuple._2).map(result => (result.getRow, result.getColumn("metrics".getBytes(), "sentimental_score".getBytes())))
println(hBaseRDD.count())
sc.stop()
}
}
</code></pre>
|
Uploading blob to Azure with Unity <p>I am trying to upload data to a blob service on Azure portal. </p>
<p>I have been trying to use this page: <a href="https://msdn.microsoft.com/library/azure/dd179451.aspx" rel="nofollow">https://msdn.microsoft.com/library/azure/dd179451.aspx</a></p>
<p>The code I have is the following:</p>
<pre><code>IEnumerator SetItem ()
{
DataJson data = new DataJson("Amy", "201289");
string json = JsonUtility.ToJson(data);
UnityWebRequest newWWW = UnityWebRequest.Put(
"https://compstorage.blob.core.windows.net/folderName/item", json);
yield return newWWW.Send();
if (newWWW.isError == false)
{
Debug.Log("Form upload complete!");
}
UnityWebRequest www = UnityWebRequest.Get("compstorage.blob.core.windows.net/folderName/item.json");
yield return www.Send();
string text = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);
DataJson newData = JsonUtility.FromJson<DataJson>(text);
Debug.Log(newData.ToString());
}
</code></pre>
<p>The blob is set as Blob meaning read, write permission. I tried all kind of variations like adding/removing file extension, also adding the SaS key but it never updates the server content despite the Put request claiming to be successful. The Get request does work fine but prints old version of data, not the updated one.</p>
<p>Does anyone know the way to use the Put request in Unity</p>
| <p>Can't tell why this is happening but you can use <a href="https://github.com/dgkanatsios/AzureServicesForUnity" rel="nofollow">this</a> plugin to communicate with your Azure service. It will solve your problem.</p>
<p><strong>EDIT</strong>:</p>
<p>After reading the MS link you posted, the problem is that you are missing several headers:</p>
<ul>
<li>Authorization</li>
<li>Date or x-ms-date</li>
<li>x-ms-version</li>
<li>Content-Length</li>
<li>x-ms-blob-type</li>
</ul>
<p>Please understand that there types of blob. You did not mention the type of blob request you are making. Please see that <a href="https://msdn.microsoft.com/library/azure/dd179451.aspx" rel="nofollow">link</a> again to see which extra headers are needed for each blob. If it says "Required" in the description then you must include it in the request. You don't need it if it says "Optional".</p>
<p>How do you include headers with <code>UnityWebRequest</code> ?</p>
<pre><code>UnityWebRequest newWWW = UnityWebRequest.Put("https://compstorage.blob.core.windows.net/folderName/item", json);
newWWW.SetRequestHeader("Authorization","your Authorization");
newWWW.SetRequestHeader("x-ms-version","v1");
newWWW.SetRequestHeader("x-ms-blob-type","BlockBlob");
newWWW.SetRequestHeader("x-ms-date","Your Datte");
</code></pre>
<p>Don't worry about the <code>Content-Length</code> and <code>Date</code> headers as Unity will automatically generate them for you. You are not allowed to set them manually with <code>UnityWebRequest</code> anyways. Look <a href="https://social.msdn.microsoft.com/Forums/silverlight/en-US/f1d0538f-e4ae-44cd-9ca0-db58eb6b1338/notification-hub-authentication-errors?forum=notificationhubs" rel="nofollow">here</a> for what to put for the authorization header.</p>
|
Some server garbled when use UrlConnection? <p>I use below code to post some data,but i find In some server the response string is garbled(not all servers).</p>
<pre><code> URL url = new URL("http://url");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod(method);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Accept-Charset", String_UTF_8);
connection.setRequestProperty("contentType", String_UTF_8);
connection.connect();
PrintWriter out = new PrintWriter(newOutputStreamWriter(connection.getOutputStream(),String_UTF_8));
out.println(json);
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), String_UTF_8));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes());
sb.append(lines);
}
reader.close();
connection.disconnect();
</code></pre>
<p>I tried a lot of ways,but all have no effect.</p>
| <p>Don't use <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#getBytes--" rel="nofollow"><code>String#getBytes()</code></a> it will decode your <code>String</code> using the <strong>platform's default charset</strong> which means that it is <strong>platform dependent</strong>. Moreover as you have already decoded your stream content as <code>String</code> using <code>UTF-8</code> as charset, it is even <strong>useless</strong>.</p>
<p><strong>Try this instead:</strong></p>
<pre><code>try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), String_UTF_8))
) {
String lines;
while ((lines = reader.readLine()) != null) {
sb.append(lines);
}
}
</code></pre>
|
How to implement an infix calculator with precedence and associativity <p>I'm testing the example of writing an infix calculator using bison flex. I found that everything is right except for the brackets "()". I find that when I input a calculation with brackets, the calculation result is incorrect. Here is the code for file "infix-calc.y"</p>
<pre><code>/* bison grammar file for infix notation calculator */
%{
#define YYSTYPE double
#include <math.h>
#include <stdio.h>
int yyerror(const char *s);
int yylex(void);
%}
%token NUM
%left '-' '+'
%left '*' '/'
%left NEG
%right '^'
%% /* Grammer rules and actions follow */
input: /* empty */
| input line
;
line: '\n'
| exp '\n' { printf("\t%.10g\n", $1); }
;
exp: NUM { $$ = $1; }
| exp '+' exp { $$ = $1 + $3; }
| exp '-' exp { $$ = $1 - $3; }
| exp '*' exp { $$ = $1 * $3; }
| exp '/' exp { $$ = $1 / $3; }
| '-' exp %prec NEG { $$ = -$2; }
| exp '^' exp { $$ = pow($1, $3); }
| '(' exp ')' { $$ = $2; }
;
%%
/* Additional C code */
int main() { return yyparse(); }
int yyerror(const char* s)
{
printf("%s\n", s);
return 0;
}
</code></pre>
<p>And here is the code for file "infix-calc.lex"</p>
<pre><code>/* lex file for infix notation calculator */
%option noyywrap
%{
#define YYSTYPE double /* type for bison's var: yylval */
#include <stdlib.h> /* for atof(const char*) */
#include "infix-calc.tab.h"
%}
digits [0-9]
rn (0|[1-9]+{digits}*)\.?{digits}*
op [+*^/\-]
ws [ \t]+
%%
{rn} yylval = atof(yytext); return NUM;
{op} |
\n return *yytext;
{ws} /* eats up white spaces */
%%
</code></pre>
<p>The problem is that when I input, say "2 * (3 + 4)", I'm supposed to receive the output "14". But the input is "() 10". It seems the brackets don't work in this case. What's wrong with the codes?
Thank you all very much for helping me!!!!</p>
| <p>It looks like you have to declare <code>(</code> and <code>)</code> as tokens for this to work.</p>
<p>Add the following two lines before the final <code>%%</code> in your lex file:</p>
<pre><code>"(" return LEFT;
")" return RIGHT;
</code></pre>
<p>Then add</p>
<pre><code>%token LEFT RIGHT
</code></pre>
<p>to the top of infix-calc.y, and replace</p>
<pre><code> | '(' exp ')' { $$ = $2; }
</code></pre>
<p>with</p>
<pre><code> | LEFT exp RIGHT { $$ = $2; }
</code></pre>
|
Dynamic Textarea/Input Character Counter <p>I have a basic HTML form with multiple dynamic textareas and input field in them. Some of these fields already have information stored being pulled out from a database.</p>
<p>What I need is a character counter that can detect the amount of characters <strong>remaining</strong> when the page loads in any given field but then to also change when adding/removing characters.</p>
<p>Any ideas on how I'd do this?</p>
| <p>just like @MayankPandeyz code some editing</p>
<p>var text_length,text_remaining;</p>
<pre><code>$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
function whenLoad (){
text_length = $('#textarea').val().length;
text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
}
whenLoad();
$('#textarea').keyup(function() {
text_length = $('#textarea').val().length;
text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
</code></pre>
|
Jenkins cannot find the external Jars added for the selenium project through Eclipse <p>I have a Maven project in Eclipse. My project is for Automation Testing. So in my pom.xml I've all dependencies added.</p>
<p>For example: Testng, Cucumber, Selenium-java etc..</p>
<p>I have installed Jenkins and configured my automation project with Jenkins, so that when executed with Jenkins this project will be executed.</p>
<p>I have all dependencies added to my pom.xml so no issues was there. But now when I added the jar files externally in Eclipse, it is not recognized by Jenkins and therefore, script is not executed.</p>
<p>Here is my test case:</p>
<pre><code>package com.giveback360.tests.sampletest;
import org.openqa.selenium.WebDriver;
import com.giveback360.utils.OpenBrowserHelp;
import cucumber.api.java.en.When;
import org.openqa.selenium.firefox.FirefoxDriver;
import atu.testrecorder.ATUTestRecorder;
import atu.testrecorder.exceptions.ATUTestRecorderException;
public class SampleTest {
/**
* Initialize the webdriver.
*/
private WebDriver driver = new FirefoxDriver();
/**
* Initialize recorder.
*/
ATUTestRecorder recorder;
/**
* Open browser.
* @throws InterruptedException the InterruptedException.
*/
@When("Open browser maximize")
public void browserOpen() throws InterruptedException, ATUTestRecorderException {
recorder = new ATUTestRecorder("/home/username/workspace/project/scriptVideos","TestVideo",false);
recorder.start();
driver.get("http://www.google.com");
Thread.sleep(4000);
driver.quit();
recorder.stop();
}
}
</code></pre>
<p>My Console output in Jenkins is:</p>
<pre><code>java.lang.NoClassDefFoundError: atu/testrecorder/exceptions/ATUTestRecorderException
Caused by: java.lang.ClassNotFoundException: atu.testrecorder.exceptions.ATUTestRecorderException
Results :
Failed tests:
SampleTest>AbstractTestNGCucumberTests.setUpClass:16 » NoClassDefFound atu/tes...
Tests run: 3, Failures: 1, Errors: 0, Skipped: 2
[ERROR] There are test failures.
</code></pre>
<p>The issue is because of ATUTestRecorder jar files I've added in Eclipse for this project.</p>
<p>Problem is how to instruct Jenkins to find those JAR files? Should I configure it in Jenkins or How should I do it?</p>
<p>Any help is greatly appreciated. Thanks in advance.</p>
| <p>You have set up a jar only with the eclipse build path so it only accessible for eclipse</p>
<p>while with the Jenkins you only setup a maven project so Jenkins is trying to find it's required dependency from POM.xml. it is not able to find the jar that is from eclipse build path.</p>
<p>You have to find maven declaration of that particular jar and have to put in POM.XML </p>
<p>or you can add 3rd party jar in maven using the following command</p>
<pre><code>mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>
</code></pre>
<p><a href="https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html" rel="nofollow">Find more information about adding 3rd party jar from here</a></p>
|
Wants copyright information of OSS components <p>I want ot take copyright information of all open source components which are used for embedded system.Is there any short way to get the copyright information of OSS components?</p>
| <p>That <strong>very</strong> much depends on your concrete setup; which of course you completely fail to describe here. How should we know which OSS components you are using in your embedded system?!</p>
<p>But the general answer is: there is <strong>no</strong> detour. When your product is using OSS components, and you want to "track" that; then you have to do the tracking work. </p>
<p>That means: </p>
<ol>
<li>You have to create a catalog of <strong>all</strong> OSS components that are included in your product (and the version in use). Ideally, that would be no-op, because your build / library setup already makes such a distinction.</li>
<li>Then you use that catalog as input, to determine the <strong>licence</strong> for each and any of these components.</li>
<li>Finally, depending on the specific licence, you determine the effects of using OSS component X for your product.</li>
</ol>
|
Orientation change in cordova mobile app <p>Please can suggest the below questions</p>
<ol>
<li>How can i maintain the server data(JSON) while mobile has changed the orientation like portrait to landscape and landscape to portrait using cordova in android, iOS and WP.</li>
</ol>
<p>I don't want reload again the if the orientation change.</p>
<ol start="2">
<li>How to display 2000 of records in mobile. </li>
</ol>
| <p>To display many records in mobile phone or web, I recommend using a table called DataTables (<a href="http://www.datatables.net" rel="nofollow">www.datatables.net</a>). It is developed in JavaScript and has MIT license. It is very simple to use and it can be customized.</p>
<p>Best regards!</p>
|
DataTrigger RelativeSource WPF XAML <p>The thing I want to make When mouseover in grid Border <em>Visibilty</em> property value must change.</p>
<p>I have a grid with a 3 ColumnDefinition.</p>
<p><a href="https://i.stack.imgur.com/nqQId.png" rel="nofollow"><img src="https://i.stack.imgur.com/nqQId.png" alt="enter image description here"></a></p>
<p>The code is</p>
<pre><code><Grid x:Name="grid1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="27*"/>
<ColumnDefinition Width="93*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Background="Blue" Visibility="Hidden">
<Border.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsMouseOver , RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" Value="True">
<Setter Property="Border.Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
<Image Grid.Column="1" />
<TextBlock Grid.Column="2" />
</Grid>
</code></pre>
<p>When mouseover the grid nothing is happen.so This codes not working</p>
| <p>one thing is that you should not use <code>IsReadOnly</code> property in DataTrigger when MouseOver is required.</p>
<p>another one is that local value <code>Visibility="Hidden"</code> has higher priority than DataTrigger setter <code><Setter Property="Border.Visibility" Value="Visible" /></code> and will not be changed even if condition is true</p>
<p>a fix for both (initial value of <code>Visibility</code> is defined in a setter)</p>
<pre><code><Border Grid.Column="0" Background="Blue">
<Border.Style>
<Style>
<Setter Property="Border.Visibility" Value="Hidden" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" Value="False">
<Setter Property="Border.Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
</code></pre>
<p>you should also set Grid Background to non-null value (e.g. <code><Grid x:Name="grid1" Background="Transparent"></code>) for mouse movements to be registered in grid (<a href="http://stackoverflow.com/questions/5344699/xnull-vs-transparent">{x:Null} vs. Transparent?</a>)</p>
|
ng-if in select option selected tag <p>I am developing Angular JS application and I want to make a select option like below.</p>
<pre><code><select class="form-control" ng-model="rc.status" ng-init="rc.status=1">
<option value="1" selected="selected">Active</option>
<option value="0" selected="">Inactive</option>
</select>
</code></pre>
<p>I want to make active when the ng-model rc.status becomes 1 and inactive when 0.</p>
<p>How can I do that without doing ng-repeat.</p>
<p>Because I generating this view from laravel and binding the html with Angular js</p>
| <p>Here is example that select dropdown value as per <code>rc.status</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="">
<select class="form-control" ng-model="rc.status" ng-init="rc.status=1">
<option value="--Select--">--Select--</option>
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
<br><br>
<div>Status : {{rc.status}}</div>
</div></code></pre>
</div>
</div>
</p>
|
Angular2 need to know things to learn and create demo with database connectivity <p>I need to know the process and fundamental flow of angular2 and what things I should to know before start angular2, I want to create two demo one is simple demo without database connectivity and another is with database connectivity
Please help me or guide me to start work on the same.</p>
| <p>I started Angulra by using the angular tutorial itself: </p>
<p><a href="https://angular.io/docs/ts/latest/tutorial/" rel="nofollow">https://angular.io/docs/ts/latest/tutorial/</a></p>
<p>"Database connectivity" depends on the kind of webservice you implement to get your data. I used asp.webservices and now moved to owin:</p>
<p><a href="https://dotnetcodr.com/2015/07/02/building-a-web-api-2-project-from-scratch-using-owinkatana-net-part-1/" rel="nofollow">https://dotnetcodr.com/2015/07/02/building-a-web-api-2-project-from-scratch-using-owinkatana-net-part-1/</a></p>
|
OnCurrent event firing when moving from first record to the last but not from last to the first <p>I have the code below which is supposed to enable and disable the amount field on the main form and the purchases and sales subforms based on the value in the transaction type field. Now it works perfectly on the forward run. I.e. as soon as the form is loaded and i am scrolling from the first record to the last. But as soon as i hit the last record and i am scrolling through the records from back to front, the amount field remains disabled (i.e. the code no longer runs) and I have to reload the form. Is there a way I can solve this? I would like the user to have a realtime response with respect to the enabling and disabling. </p>
<p>Please find a picture of the form just in case it helps visualize the scenario.</p>
<p><a href="https://i.stack.imgur.com/BJFpw.png" rel="nofollow"><img src="https://i.stack.imgur.com/BJFpw.png" alt="enter image description here"></a></p>
<pre><code>Private Sub Form_Current()
Select Case Me.transactionType.Value
Case 1
Me.PurchaseOrderDetails_subform.Enabled = False
Me.SalesOrderDetails_subform.Enabled = False
Case 4
Me.Amount.Enabled = False
Me.PurchaseOrderDetails_subform.Enabled = False
Me.SalesOrderDetails_subform.Enabled = True
Case 2
Me.Amount.Enabled = False
Me.PurchaseOrderDetails_subform.Enabled = True
Me.SalesOrderDetails_subform.Enabled = False
Case 3
Me.Amount.Enabled = False
Me.PurchaseOrderDetails_subform.Enabled = False
Me.SalesOrderDetails_subform.Enabled = True
End Select
End Sub
</code></pre>
<p>I will truly appreciate your help.</p>
| <p>You never enable that field, so you may need this modification:</p>
<pre><code>Select Case Me.transactionType.Value
Case 1
Me.Amount.Enabled = True
Me.PurchaseOrderDetails_subform.Enabled = False
Me.SalesOrderDetails_subform.Enabled = False
</code></pre>
|
How to use ajax in codeigniter? <p>I am trying to make a very simple php chat for my website with CodeIgniter and Ajax. The messages are saved in a html file, not in a database table. Whenever I click the send button, the page refreshes, even though it's not supossed to and I don't know what's wrong.
Here is my code:
My controller code:</p>
<pre><code>class Chat_con extends CI_Controller{
function construct(){
parent::_construct();
}
public function index(){
$this->load->model('login_model');
$d['info']=$this->login_model->display_user_data();//this info is sent to view to display the username of the person who is using the chat
$d['message']=$this->read_conv();
$this->load->view('chat_view',$d);
}
function write_conv() {
$this->load->helper('directory');
$this->load->helper('url');
$this->load->helper('file');
$this->path = "application" . DIRECTORY_SEPARATOR . "files"
. DIRECTORY_SEPARATOR;
$this->file = $this->path . "log.html";
$m=$this->input->post('usermsg');
$u=$this->session->userdata('username');
write_file($this->file,"<div class='msgln'>(".date("g:i A").") <b>".$u."</b>: ".stripslashes(htmlspecialchars($m))."<br></div>",'a');
$this->index();
}
function read_conv(){
$this->load->helper('directory');
$this->load->helper('url');
$this->load->helper('file');
$this->path = "application" . DIRECTORY_SEPARATOR . "files"
. DIRECTORY_SEPARATOR;
$this->file = $this->path . "log.html";
$string = read_file($this->file);
return $string;
}
}
</code></pre>
<p>Part of my view:</p>
<pre><code> <div id="chatbox">//this is the div where the messages are displayed
<?php echo $message; ?></div>
//this is the form
<form name="message" id="message"action="<?php echo base_url();?
>chat_con/write_conv" method='post'>
<input name="usermsg" type="text" id="usermsg" size="63" /> <input
name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
</code></pre>
<p>//The script</p>
<pre><code><script type="text/javascript">
$(document).ready(function() {
$("#message").submit(function(e) {
e.preventDefault();
var postData = $(#message).serializeArray();
var formActionURL = $(this).attr("action");
$.ajax({
url: formActionURL,
type: "POST",
data: postData,
}).done(function(data) {
alert("success");
}).fail(function() {
alert("error");
}).always(function() {
$("#submitmsg").val('submit');
});
});
}
</script>
</code></pre>
| <ol>
<li><code>var postData = $(#message).serializeArray();</code> should be:<br>
<code>var postData = $("#message").serializeArray();</code></li>
<li>If issue still not get resolved then try to debug by putting <code>alert()</code> or <code>console.log()</code> before <code>e.preventDefault()</code> and then debug your js code.<br>
For example <code>alert('dummy text for debug');</code></li>
</ol>
|
Recording locations in time domain with AVFoundation <p>I followed a lot of tutorials and every tutorials about recording in AVFoundation covers only recording Video or Audio or both of this things.</p>
<p>I would like to record some location in the same time domain like Video/Audio on separate track. This location waypoints is described with 5 properties only - latitude, longitude, altitude, startTime, duration and it'll be changing no often that 5 seconds of the recording. This recording is for presentation purposes and I need functionality such as streaming, play forward, skipping, pause.</p>
<p>Anybody have some idea how to do it with AVFoundation framework?</p>
| <p>Sure, this is possible.</p>
<p>AVFoundation is a collection of higher and lower level libraries with lots of options to tap into the processing pipeline at various stages. Assuming you want to capture from the Camera, then you're going to be using some combination of AVCaptureSession, its delegate <a href="https://developer.apple.com/reference/avfoundation/avcapturevideodataoutputsamplebufferdelegate" rel="nofollow">https://developer.apple.com/reference/avfoundation/avcapturevideodataoutputsamplebufferdelegate</a> and an AVAssetWriter.</p>
<p>The AVCaptureVideoDataOutputSampleBufferDelegate is capturing vended CMSampleBuffers (which combine a frame of video data with timing information), at the point you receive it, you typically just "write out" the CMSampleBuffer to record the video, but you can also further process it to filter it in realtime or, as you want to do, record additional information with timing data (e.g. at this point in the video, I had these coordinates).</p>
<p>Research how to write video from the camera on iOS to get started and using the Delegate, you'll soon see where to hook into the code to achieve what you're after.</p>
|
HTTP ERROR: 404 solr not running <p>Yesterday if was opening <a href="http://my-ip:3000/solr" rel="nofollow">http://my-ip:3000/solr</a> then the home page is opening of Solr.
But today I restarted VM after that is showing me like that.</p>
<pre><code>HTTP ERROR: 404
Problem accessing /solr. Reason:
Not Found
Powered by Jetty://
</code></pre>
<p>If I run this URL <a href="http://my-ip:3000" rel="nofollow">http://my-ip:3000</a> then it shows me</p>
<pre><code>Error 404 - Not Found.
No context on this server matched or handled this request.
Contexts known to this server are:
Powered by Jetty:// Java Web Server
</code></pre>
<p>I checked Jetty and it is running fine.</p>
<p>Now I'm confused whats not running. I'm new to Solr. Please help me?</p>
| <p>You may need going to the Solr directory: <code>cd solr-6.2.0/</code> and launching it: <code>bin/solr start</code> The Solr admin UI will run on the port 8983 by default: <code>http://localhost:8983/solr/</code>. However, the support for deploying Solr 5.0 and newer on Jetty is <a href="https://cwiki.apache.org/confluence/display/solr/Running+Solr+on+Jetty" rel="nofollow">unsuported</a>, so you might consider another solution, without Jetty.</p>
|
Javascript: add function as parameter to predefined callback function <p>I have this code that uses a cordov/phonegap plugin:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var app = {
init: function (){
sensors.getState(app.callback);
},
callback: function(state){
//parameter of this callback function is define by cordova plugin
if (state[0] == 0) {
//execute another function passed as argument because I wwant to change it in other parts of my code
}
},
firstFunction(){
//execute action 1
},
secondFunction(){
//execute action 2
}
}</code></pre>
</div>
</div>
</p>
<p>Now sensors.getState has one argument and is predefined by plugin . I would like to execute a function passed as added argument like:
sensor.getState(app.callback(firstFunction)) or when i need sensor.getState(app.callback(secondFunction))</p>
<p>Thanks.
IngD</p>
| <p>Try this</p>
<pre><code> var app = {
init: function() {
sensors.getState(app.callback);
},
test: function() {},
setCallback: function(callback) {
app.test = callback;
},
callback: function(state) {
app.test();
},
firstFunction() {
alert("firstFunction");
},
secondFunction() {
alert("secondFunction");
}
};
app.setCallback(app.firstFunction);
app.callback();
app.setCallback(function () { alert("thirdFunction"); });
app.callback();
</code></pre>
|
Count doesn't give back 0 <p>I have a table where I must recover for each month the count of Groups that will be taking lessons, this check has to be done every three months, the final output should be this:</p>
<pre><code>Gruppi A nel mese di Luglio 20
Gruppi A nel mese di Agosto 18
Gruppi A nel mese di Settembre 5
Gruppi B nel mese di Luglio 8
Gruppi B nel mese di Agosto 0
Gruppi B nel mese di Setembre 12
</code></pre>
<p>This is my query:</p>
<pre><code>WITH T AS (
SELECT GROUPS.GROUP_NAME || ' nel mese di ' || TO_CHAR(REVIEW.REVIEW_DATE, 'Month') AS FORMAT_MONTH,
COUNT(*) AS COUNT_GROUPS
FROM REVIEW
INNER JOIN GROUPS ON REVIEW.ID = GROUPS.ID
WHERE GROUP_TYPE = 1
AND GROUP_MASTER = 50
AND TO_CHAR(REVIEW.REVIEW_DATE, 'YYYYMM')
IN ((SELECT TO_CHAR(ADD_MONTHS(TO_DATE('20160701', 'YYYYMMDD'), 0), 'YYYYMM') FROM DUAL),
(SELECT TO_CHAR(ADD_MONTHS(TO_DATE('20160701', 'YYYYMMDD'), 1), 'YYYYMM') FROM DUAL), (SELECT TO_CHAR(ADD_MONTHS(TO_DATE('20160701', 'YYYYMMDD'), 2), 'YYYYMM') FROM DUAL))
GROUP BY GROUPS.GROUP_NAME || ' nel mese di ' || TO_CHAR(REVIEW.REVIEW_DATE, 'Month')
UNION ALL
SELECT GROUPS.GROUP_NAME || ' nel mese di ' || TO_CHAR(REVIEW.REVIEW_DATE, 'Month') AS FORMAT_MONTH,
COUNT(*) AS COUNT_GROUPS
FROM REVIEW
INNER JOIN GROUPS ON REVIEW.ID = GROUPS.ID
WHERE GROUP_TYPE = 1
AND GROUP_MASTER = 50
AND TO_CHAR(REVIEW.REVIEW_DATE, 'YYYYMM') IN ((SELECT TO_CHAR(ADD_MONTHS(TO_DATE('20160701', 'YYYYMMDD'), 0), 'YYYYMM') FROM DUAL),
(SELECT TO_CHAR(ADD_MONTHS(TO_DATE('20160701', 'YYYYMMDD'), 1), 'YYYYMM') FROM DUAL),
(SELECT TO_CHAR(ADD_MONTHS(TO_DATE('20160701', 'YYYYMMDD'), 2), 'YYYYMM') FROM DUAL))
GROUP BY GROUPS.GROUP_NAME || ' nel mese di ' || TO_CHAR(REVIEW.REVIEW_DATE, 'Month')
)
SELECT *
FROM T
UNION ALL
SELECT 'Gruppi nel periodo', SUM(COUNT_GROUPS)
FROM T;
</code></pre>
| <p>I think you may rewrite your query like that. </p>
<ol>
<li>If you want see groups without REVIEW you should yse left join. </li>
<li>Why you get data twice with the equal param (I delete it from my query)</li>
<li>For total you may use group by rollup()</li>
<li>IMHO/ You may use trunc(date.'mm') for comparing date by months</li>
<li><strong>EDIT:</strong> Move check review dates to join condition.</li>
</ol>
<p>I assume <strong>GROUP_TYPE</strong> and <strong>GROUP_MASTER</strong> are belong to groups My code look like:</p>
<pre><code>WITH T AS (
SELECT
GROUPS.GROUP_NAME || ' nel mese di ' || TO_CHAR(d.REVIEW_DATE, 'Month') AS FORMAT_MONTH,
COUNT(REVIEW.ID) AS COUNT_GROUPS
FROM GROUPS
JOIN (SELECT add_months(TO_DATE('20160701', 'YYYYMMDD'),0) as REVIEW_DATE from DUAL UNION ALL
SELECT add_months(TO_DATE('20160701', 'YYYYMMDD'),1) from DUAL UNION ALL
SELECT add_months(TO_DATE('20160701', 'YYYYMMDD'),2) from DUAL ) d ON 1=1
LEFT JOIN REVIEW ON REVIEW.ID = GROUPS.ID AND trunc(REVIEW.REVIEW_DATE, 'MM') = d.REVIEW_DATE
WHERE GROUP_TYPE = 1
AND GROUP_MASTER = 50
GROUP BY rollup(GROUPS.GROUP_NAME || ' nel mese di ' || TO_CHAR(d.REVIEW_DATE, 'Month'))
)
SELECT nvl(FORMAT_MONTH,'Gruppi nel periodo') as FORMAT_MONTH
,COUNT_GROUPS
FROM T ;
</code></pre>
|
VBA Word : Error 5174 when Documents.Open with filename including pound sign # <p>In Microsoft Word 2010 VBA</p>
<p>I am getting a runtime error 5174, when trying to open a document which file name includes a pound sign "#", with a relative file path.</p>
<pre><code>Sub openPoundedFilename()
Dim doc As Object
' Both files "C:\Temp\foo_bar.docx" and "C:\Temp\foo#bar.docx" exist
' With absolute file paths
Set doc = Documents.Open(fileName:="C:\Temp\foo_bar.docx") ' Works
doc.Close
Set doc = Documents.Open(fileName:="C:\Temp\foo#bar.docx") ' Works
doc.Close
' With relative file paths
ChDir "C:\Temp"
Set doc = Documents.Open(fileName:="foo_bar.docx") ' Works
doc.Close
Set doc = Documents.Open(fileName:="foo#bar.docx") ' Does not work !!!!
'Gives runtime error 5174 file not found (C:\Temp\foo)
doc.Close
End Sub
</code></pre>
<p>I did not find any explanation for why the last <code>Documents.Open</code> fails.
<br>It probably has to do with some mismatch regarding the "#" sign used for URL.
<br>(see <a href="https://support.microsoft.com/en-us/kb/202261" rel="nofollow"><a href="https://support.microsoft.com/en-us/kb/202261" rel="nofollow">https://support.microsoft.com/en-us/kb/202261</a></a>)</p>
<p>Thanks in advance for answers</p>
<hr>
<p><em>Edit 17/10/2016 13:37:17</em>
<br>The macro recording generates the following:</p>
<pre><code>Sub Macro1()
'
' Macro1 Macro
'
'
ChangeFileOpenDirectory "C:\Temp\"
Documents.Open fileName:="foo#bar.docx", ConfirmConversions:=False, _
ReadOnly:=False, AddToRecentFiles:=False, PasswordDocument:="", _
PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", _
WritePasswordTemplate:="", Format:=wdOpenFormatAuto, XMLTransform:=""
End Sub
</code></pre>
<p>This macro doesn't work (gives the same error 5174).</p>
| <p>To open the file using a relative path you need to URLEncode the filename. There is no built-in support in VBA for doing so (besides in <a href="http://stackoverflow.com/a/24301379/40347">newer Excel versions</a>), but you can use @Tomalak's <strong><a href="http://stackoverflow.com/a/218199/40347"><code>URLEncode</code></a></strong> function, which should encode <code>foo#bar.docx</code> as <code>foo%23bar.docx</code>:</p>
<pre><code>ChangeFileOpenDirectory "C:\Temp\"
Dim urlEncodedFilename as String
urlEncodedFilename = URLEncode("foo#bar.docx")
Set doc = Documents.Open(fileName:=urlEncodedFilename)
</code></pre>
|
Unit tests are failing when run from dotCover <p>I have a TFS 2015 build which builds one of our applications (it's an ASP.NET Web API application). As part of the build process it runs our unit tests.</p>
<p>I have a <em>Visual Studio Tes</em>t build step which runs these unit tests and they all pass okay.</p>
<p>I then run <strong>dotCover</strong> from this same build to determine code coverage (no we don't use the built-in code coverage as we don't have enterprise licences). However, when run from <strong>dotCover</strong> all the same unit tests fail. </p>
<p>I use a script step to run a batch file which invokes <strong>dotCover</strong> as follows.</p>
<p><strong>E:\JetBrains\Installations\dotCover05\dotCover.exe analyse coverage.xml /LogFile=dotcover.log</strong></p>
<p>The <strong>dotCover</strong> log file doesn't seem to give any indications as to why the unit tests have failed.</p>
<p>Any ideas why the unit tests pass when run from the <em>Visual Studio Test</em> build step and then fail when run from <strong>dotCover</strong>? </p>
| <p>Make sure your build service account have enough permission to run the dotcove.exe. According to your <code>E:\JetBrains\Installations\dotCover05\dotCover.exe</code> Seems you didn't install for <strong><em>all users</em></strong> on the build agent. Which should installed under <code>%ProgramFiles(x86)%</code> not %LOCALAPPDATA%\JetBrains\Installations.</p>
<p><a href="https://i.stack.imgur.com/wwGho.png" rel="nofollow"><img src="https://i.stack.imgur.com/wwGho.png" alt="enter image description here"></a></p>
<p>Try to use <code>CoreInstructionSet</code> parameter in your dotCover as a workaround for your situation. Details see below picture.
<a href="https://i.stack.imgur.com/41pGv.png" rel="nofollow"><img src="https://i.stack.imgur.com/41pGv.png" alt="enter image description here"></a></p>
<p>After doing this try to run the build again.</p>
<p><a href="https://i.stack.imgur.com/M1Sxm.png" rel="nofollow"><img src="https://i.stack.imgur.com/M1Sxm.png" alt="enter image description here"></a></p>
|
Remove rows of a csv file which are in another csv file <p>I have two Excel files, I want to remove rows from the first file excel1 who are not in the second file excel2 with an R insctruction.</p>
<p>Here is my escounted result. What should I do ?</p>
<p><a href="https://i.stack.imgur.com/R55pq.png" rel="nofollow"><img src="https://i.stack.imgur.com/R55pq.png" alt="enter image description here"></a></p>
| <p>You can read the csv files first</p>
<pre><code> excel1<-read.csv("excel1.csv", header=T)
excel2<-read.csv("excel2.csv", header=T)
excel1.excel2<-setdiff(excel1, excel2)
</code></pre>
<p>You can also refer to this post to help you prepare reproducible examples: <a href="http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example">How to make a great R reproducible example?</a></p>
|
Count consecutive values in groups with condition with dplyr and rle <p>My question is very similar to the one posed below, however I want to add an additional command to return only cases when a sequence has more than 2 consecutive values. </p>
<p>How do I count the number of consecutive "success" (i.e. 1 in $consec) when a given sequence run has more than 2 consecutive numbers, within a given Era and a given Year?</p>
<p>Similar question to: <a href="http://stackoverflow.com/questions/32164093/summarize-consecutive-failures-with-dplyr-and-rle">Summarize consecutive failures with dplyr and rle</a>
. For comparison, I've modified the example used in that question:</p>
<pre><code>library(dplyr)
df <- data.frame(Era=c(1,1,1,1,1,1,1,1,1,1),Year = c(1,2,2,3,3,3,3,3,3,3), consec = c(0,0,1,0,1,1,0,1,1,1))
df %>%
group_by(Era,Year) %>%
do({tmp <- with(rle(.$consec==1), lengths[values])
data.frame(Year= .$Year, Count=(length(tmp)))}) %>%
slice(1L)
> Source: local data frame [3 x 3]
> Groups: Era, Year
> Era Year Count
> 1 1 1 0
> 2 1 2 1
> 3 1 3 2
>
</code></pre>
<p>All I need now is to add a condition to include only cases of consecutive numbers in a sequence of >2. Desired result:</p>
<pre><code>> Source: local data frame [3 x 3]
> Groups: Era, Year
> Era Year Count
> 1 1 1 0
> 2 1 2 0
> 3 1 3 1
</code></pre>
<p>Any advice would be greatly appreciated.</p>
| <p>We need to create a logical index with <code>lengths</code> and get the <code>sum</code> of it</p>
<pre><code>df %>%
group_by(Era, Year) %>%
do({ tmp <- with(rle(.$consec), sum(lengths > 2))
data.frame(Count = tmp)})
# Era Year Count
# <dbl> <dbl> <int>
#1 1 1 0
#2 1 2 0
#3 1 3 1
</code></pre>
|
Selecting different columns from databases <p>Hello I have two databases and each has the same tables. For example I have table called <code>world</code> and it has 4 columns: <code>pkey1</code>, <code>pkey2</code>,<code>companyid</code>, <code>company_name</code></p>
<p>I made a query which searches for rows which have the same pkey1 and pkey2 but one or many of their other property is different in the 2 tables. My question is how can I see only the different properties? </p>
<p>Here is my query it selects the rows which have the same pkey1 and pkey2 how can I upgrade it to see the columns where there is difference in both databases and of course if there is no difference the result of the query should return NULL in the column here is an example what I want to achieve: </p>
<p>in first database (1,1,345,'Ron'), second database (1,1,377,'Ron') the result should be (1,1,345,null)</p>
| <p>If your databases are linked, you can join both tables and with "case" statement check if the value has changed:</p>
<pre><code>select a.pkey1, a.pkey2,
case when a.companyid <> b.companyid then a.companyid else null end as companyid,
case when a.company_name <> b.company_name then a.company_name else null end as company_name
from db1.dbo.world a
inner join db2.dbo.world b on a.pkey1 = b.pkey1 and a.pkey2 = b.pkey2
</code></pre>
<p>If you want to omit rows with no difference you can use "except":</p>
<pre><code>select a.pkey1, a.pkey2,
case when a.companyid <> b.companyid then a.companyid else null end as companyid,
case when a.company_name <> b.company_name then a.company_name else null end as company_name
from (
select pkey1, pkey2, companyid, company_name
from db1.dbo.world
except
select pkey1, pkey2, companyid, company_name
from db2.dbo.world) a
inner join db2.dbo.world b on a.pkey1 = b.pkey1 and a.pkey2 = b.pkey2
</code></pre>
|
Django 1.10.2 error "NoReverseMatch at " ,"Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found." <p>I am new to python & Django. I am getting one error and have absolutely no idea how to solve it.
Any help will be appreciated.
<a href="https://i.stack.imgur.com/4Cw94.png" rel="nofollow"><img src="https://i.stack.imgur.com/4Cw94.png" alt="enter image description here"></a></p>
<pre><code>from django.shortcuts import render
# Create your views here.
#log/views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.
# this login required decorator is to not allow to any
# view without authenticating
@login_required(login_url="login/")
def home(request):
return render(request,"home.html")
</code></pre>
<p>The code in urls.py is,</p>
<pre><code>from django.conf.urls import include,url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from log.forms import LoginForm
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('log.urls')),
url(r'^login/$', auth_views.login ,{'template_name': 'login.html','authentication_form': LoginForm}),
url(r'^logout/$', auth_views.logout, {'next_page': '/login'}),
]
</code></pre>
<p>The code in login.html is,</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{% extends 'base.html' %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
{% if next %}
{% if user.is_authenticated %}
<p>Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>
{% else %}
<p>Please login to see this page.</p>
{% endif %}
{% endif %}
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Please Sign In</h3>
</div>
<div class="panel-body">
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<p class="bs-component">
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
</p>
<p class="bs-component">
<center>
<input class="btn btn-success btn-sm" type="submit" value="login" />
</center>
</p>
<input type="hidden" name="next" value="{{ next }}" />
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
<script>
{% if not user.is_authenticated %}
$("ul.nav.navbar-nav.navbar-right").css("display","none");
{% endif %}
</script>
{% endblock %}</code></pre>
</div>
</div>
</p>
<p>Hope this much info will do....</p>
| <p>Add a <code>name</code> to the login <em>url pattern</em>:</p>
<pre><code>kwargs = {'template_name': 'login.html','authentication_form': LoginForm}
...
url(r'^login/$', auth_views.login, kwargs=kwargs, name='login'),
# ^^^^
</code></pre>
<p>and then use that <code>name</code> in your template:</p>
<pre><code><form method="post" action="{% url 'login' %}">
</code></pre>
|
R - Convert Date Time as character into Seconds (numeric) <p>I am reading data time value from csv file stored as below</p>
<pre><code>"2013-08-01 00:10:46"
"2013-08-01 00:10:51"
"2013-08-01 00:10:53"
"2013-08-01 00:11:04"
"2013-08-01 00:11:06"
</code></pre>
<p>While reading it is read as character and i want to convert it into seconds from 1970-01-01. I am able to achieve it using the below line of code but it takes ages to convert. Is there a better and faster way to achieve this</p>
<pre><code>rstarttime <- as.numeric(as.POSIXct(rdata$starttime,origin = "1970-01-01"))
</code></pre>
| <p>You can use <code>lubridate</code>.</p>
<p>According to the following test, it can be around 12 times faster:</p>
<pre><code>library(lubridate)
ttt <- c(
"2013-08-01 00:10:46",
"2013-08-01 00:10:51",
"2013-08-01 00:10:53",
"2013-08-01 00:11:04",
"2013-08-01 00:11:06"
)
t <- Sys.time()
q <- as.numeric(as.POSIXct(rep(ttt,50000),origin = "1970-01-01"))
t1 <- Sys.time() - t
t <- Sys.time()
q <- time_length(interval(ymd("1970-01-01"), rep(ttt, 50000)), "second")
t2 <- Sys.time() - t
</code></pre>
<p>The values I obtained for <em>t1</em> and <em>t2</em> are 6 seconds and 0.5 seconds respectively. So <code>lubridate</code> performs around 12 times faster.</p>
|
Connecting Apache Spark with couchbase <p>I am trying to connect spark application with Couchbase. For this i am applying the following code.</p>
<pre><code>double[] val=new double[3];
SparkContext sc = new SparkContext(new SparkConf().setAppName("sql").setMaster("local").set("com.couchbase.nodes", "url").set("com.couchbase.client.bucket","password"));
SQLContext sql = new SQLContext(sc);
JsonObject content = JsonObject.create().put("mean", val[0]).put("median", val[1]).put("standardDeviation",
val[2]);
JsonDocument doc=JsonDocument.create("docId", content);
bucket.upsert(doc);
</code></pre>
<p>But i am getting the following exception</p>
<pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: com/couchbase/client/java/document/json/JsonObject
at com.cloudera.sparkwordcount.JavaWordCount.main(JavaWordCount.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:731)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:181)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:206)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:121)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: com.couchbase.client.java.document.json.JsonObject
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 10 more
</code></pre>
<p>My maven dependencies are as follows:-</p>
<pre><code> <dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.10</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>com.databricks</groupId>
<artifactId>spark-csv_2.10</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>spark-connector_2.10</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>java-client</artifactId>
<version>2.3.4</version>
</dependency>
</code></pre>
<p>Please tell me where i am missing.</p>
| <p>Below are the minimum dependencies you need to connect to Couchbase using Spark 1.6</p>
<pre><code><dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.10</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.couchbase.client</groupId>
<artifactId>spark-connector_2.10</artifactId>
<version>1.2.1</version>
</dependency>
</code></pre>
<p>And here is the sample program to save and retrieve JsonDocument to Couchbase. Hope this helps.</p>
<pre><code>import java.util.Arrays;
import java.util.List;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.spark.japi.CouchbaseDocumentRDD;
import com.couchbase.spark.japi.CouchbaseSparkContext;
public class CouchBaseDemo {
public static void main(String[] args) {
//JavaSparkContext
SparkConf conf = new SparkConf().setAppName("CouchBaseDemo").setMaster("local").set("com.couchbase.bucket.travel-sample", "");
JavaSparkContext jsc = new JavaSparkContext(conf);
CouchbaseSparkContext csc = CouchbaseSparkContext.couchbaseContext(jsc);
//Create and save JsonDocument
JsonDocument docOne = JsonDocument.create("docOne", JsonObject.create().put("new", "doc-content"));
JavaRDD<JsonDocument> jRDD = jsc.parallelize(Arrays.asList(docOne));
CouchbaseDocumentRDD<JsonDocument> cbRDD = CouchbaseDocumentRDD.couchbaseDocumentRDD(jRDD);
cbRDD.saveToCouchbase();
//fetch JsonDocument
List<JsonDocument> doc = csc.couchbaseGet(Arrays.asList("docOne")).collect();
System.out.println(doc);
}
}
</code></pre>
|
Insert multiple rows into mysql database (items separated by comma) <p>need help...!!!
i have 2000 number of values like (3458,1356,....n)
i want to post them from html input field as $_POST['roll']; along with few other columns which has similar values like board (dhaka,dhaka,dhaka) .. i want to insert them into database with php at once not one by one..</p>
<p>NOTE: i know there is a way to insert multiple rows but it will be time consuming to create that query for 2000 values.. so i want to use 2000 values at once with comma..</p>
<p>result should be like this</p>
<pre><code> +---------+-------------+
| board | roll |
+---------+-------------+
| dhaka | 3456 |
| dhaka | 4574 |
| dhaka | 6357 |
| dhaka | 2467 |
+---------+-------------+
</code></pre>
<p>i am using this query to post single row at a time</p>
<pre><code> $board = $_POST['board'];
$roll = $_POST['roll'];
$query = "INSERT INTO `host`.`result` (`board`, `roll`) VALUES ('$board','$roll') "
</code></pre>
| <p>At first,
you can use php <code>explode()</code> function to make an php array. Then you INSERT your data using loop depending on Array size.</p>
<p>Code Example :</p>
<pre><code>$roll = array();
$board = array();
$roll = (explode(",",$_POST['roll']));
$board = (explode(",",$_POST['board']));
$arraySize = sizeof($roll);
for($i=0; $i<$arraySize ; $i++){
$query = "INSERT INTO `host`.`result` (`board`, `roll`) VALUES ($board[$i],$roll[$i]) "
}
</code></pre>
|
How can i use environment variable in systemd timer unit? <p>A have a systemd service to execute some shell.
I want to start this systemd service with a systemd timer.
I need to make the value for OnCalendar configurable for devops.</p>
<p>My first attempt was to provide a config file with key TIMER_ONCALENDAR,
load it as EnvironmentFile within timer unit and set default within timer unit in case the config file doesn't provide this key.</p>
<pre><code>[Timer]
Environment="TIMER_ONCALENDAR=*-*-* *:00,15,30,45:00"
EnvironmentFile=/etc/sysconfig/my-config-file
OnBootSec=2min
OnCalendar=${TIMER_ONCALENDAR}
Unit=myservice.service
[Install]
WantedBy=multi-user.target
</code></pre>
<p>My problem is, that the service is only run once and not every 15 min.
Is it even possible to use environment variable within timer unit and how?</p>
| <p>If you aren't sure about a directive, like <code>Environment=</code>, you can use <code>man systemd.directives</code> to find which man page the directive is documented. </p>
<p>In this case, it's documented in <code>man systemd.exec</code>, which explains that <code>Environment=</code> works in 4 types of unit files, but "timer" files are not one of them. </p>
<p>From reading 'man systemd.timer', you can find there's no mention of environment variables for systemd timers. </p>
<p>But you mentioned your end goal was to help with DevOps automation. That's possible.</p>
<p>Read about "drop-in" files in <code>man systemd.unit. You can create a file which contains *only* the</code>OnCalendar` directive, which will override or add to another base configuration file. </p>
<p>DevOps folks can easily automate adding or replacing the file that contains the <code>OnSchedule=</code> directive. </p>
|
Nodejs persist a sqlite in-memory database <p>I'm using the nodejs sqlite library (<a href="https://github.com/mapbox/node-sqlite3" rel="nofollow">https://github.com/mapbox/node-sqlite3</a>). How can i persist an in-memory database to disk? Since in the c/c++ implementation there are the backup api how can i persist in nodejs with this library? (or with another library/mechanism)</p>
| <p><a href="http://stackoverflow.com/q/1437327/11654">Using the backup API</a> is the only way.
And Node.js does not implement this API.</p>
<p>Just use a normal, on-disk database.
You can make it as unsafe as an in-memory database with <a href="http://www.sqlite.org/pragma.html#pragma_synchronous" rel="nofollow">PRAGMA synchronous = OFF</a>.</p>
|
Minimum time to shift given weight boxes from one position to other when capacity of machines are given <p>Given n boxes of different weights and m machines of different weight carrying capacity. Find the minimum time required to move all boxes. </p>
<p>Machines Capacities : C[0] , C[1] , C[2],........C[m-1].</p>
<p>Box Weights : W[0] , W[1] , W[2] .... W[n].</p>
<p>Each machine takes 1 minute to carry one time.
What can be the optimal approach recursive approach will be to try assigning current box to given machine and not assign and recur for rest of thee boxes.</p>
<p>Note: A single machine can carry boxes multiple times , Each round trip takes exactly 1 unit time.</p>
| <p>Sort the machines in descending order of weight carrying capacities.</p>
<p>Sort the boxes in increasing order of weights.</p>
<p>Now, add boxes one by one to each machine until the weight carrying capacity of the machine exceeds.</p>
<p>When it exceeds then move to the next machine.</p>
<p><strong>Pseudocode:</strong></p>
<pre><code>W[] //sorted in increasing order
C[] //sorted in decreasing order
i = 0 //pointer for box
j = 0 //pointer for machine
curr_weight = 0
time_taken = 0
while i<n:
curr_weight = curr_weight + W[i]
if curr_weight > C[j]:
curr_weight = 0
j = j + 1
time_taken = time_taken + 1
else
i = i + 1
end while
print time_taken + 1
</code></pre>
<p><em>Check for boundary cases. For example if <code>j</code> exceeds <code>m-1</code></em></p>
<p><strong>Edit:</strong> In case the same machine can carry multiple times</p>
<p>Maintain a sorted <em>STACK</em> for machines [sorted in descending order]. As soon as a machine gets full and leaves for transportation, pop the machine from <em>STACK</em> and enqueue it in a <em>QUEUE</em>. As soon as a machine is ready to carry again(after it has returned from the transportation job), dequeue it from the <em>QUEUE</em> and push it back on the <em>STACK</em>.</p>
<p><strong>Assumption:</strong> time to move from source to destination for a machine is 1 minute. time to move back from destination to source for a machine is 1 minute.</p>
|
Receive POST information from callback, Android WebView <p>My scenario is this: we point the user to a form where they fill in the data (3DSecure) and then POST, the website then POSTS the response to a callback URL - this response is what I want to capture. <code>WebView.shouldInterceptRequest()</code> can get the headers but not the content (Why, Google?). I tried <a href="http://stackoverflow.com/questions/3613798/is-it-possible-to-access-html-form-data-posted-through-a-webview">this link</a> and it can get the POST data that the user sends. Is there any way to use Javascript to catch the POST data being received to a callback of my choosing?</p>
<p>I saw <a href="http://stackoverflow.com/questions/4958596/receive-post-data-from-a-3rd-party-within-a-webview">this post from 5 years ago</a> and the man resorted to POSTing the response back to a server and then getting the contents from the phone. This is far from ideal. Surely there's a newer solution?</p>
<p><code>shouldInterceptRequest()</code> mentions that a response contains the "<a href="https://developer.android.com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest" rel="nofollow">response information or null if the WebView should load the resource itself</a>", how do I get it so that the WebView shouldn't load the resource itself? The source code seems to return null always.</p>
| <p>I used this gentleman's library: <a href="https://github.com/LivotovLabs/3DSView" rel="nofollow">https://github.com/LivotovLabs/3DSView</a></p>
<p>If one was looking to do this with something other than 3DSecure they could use it as a template.</p>
|
How to insert into type text <p>I wish to insert into an SQL table in a field whose data type is text. However I am informed of an error saying ' check datatype' my Name field is of type nvarchar and my job field is of type text.</p>
<pre><code>INSERT INTO Table1 (Name, Job) VALUES ('John', 'Clerk')
</code></pre>
| <p>In MS SQL Server, you wont be able to insert string values(with more than 1 characters) in table if the column of type nvarchar. You can only insert only one character using nvarchar. </p>
<p>If you wish to insert some text, please specify the some size with nvarchar.</p>
<p>For example in your case: </p>
<pre><code>Create table Table1(Name nvarchar(5), Job Text)
Insert into Table1(Name, Job) values ('John','Clerk')
</code></pre>
<p>This will work.</p>
<p>Hope it will help you out.</p>
|
Programatically tell the difference between data <p>Im converting mass files to XML and each file is either XML, JSON, CSV or PSV. To do the conversion I need to know what data type the file is without looking at the file extension (Some are coming from API's). Someone suggested that I try parse each file by each of the types until you get a success but that is pretty inefficient and CSV cant be easily parsed as it is essentially just a text file (Same as PSV). </p>
<p>Does anyone have any ideas on what I can do? Thanks.</p>
| <p>You can have some kind of "pre-parsing":</p>
<ul>
<li>Either it starts with an XML declaration, or directly with the root node, first character of an <a href="https://en.wikipedia.org/wiki/XML" rel="nofollow">XML file</a> should be <code><</code>.</li>
<li>First character of a <a href="http://json.org/" rel="nofollow">JSON file</a> can only be <code>{</code> if the JSON is built on an object, or <code>[</code> if the JSON is built on an array.</li>
<li>For CSV and PSV (I guess PSV stands for Point-Separated Values?), each line of the file represent a specific record.</li>
</ul>
<p>So by checking first character, you may find XML and/or JSON parsing is pointless.</p>
<p>Parsing the first line of the file should be enough to decide if the file format is CSV or PSV.</p>
|
How to calculate hours worked in month <p>I made a program in C# windows forms application,
that you input the day, and hour and minutes you start work, and hour and minutes you finish work on this day.
(for example: day 15, hour1: 8, min1: 0. hour2: 17, min2: 40).
and it calculate the hours you worked in the current day (09:40:00).
The month and year taken from the PC date.</p>
<p>Now, I know how much time I worked in some day.
But I need also to calculate the hours I worked the month.</p>
<p>I added more variable that will calculate the sum of the hours every day, but I don't know how to code it.</p>
<p>*I'm calculating all in the end of the month and not every day.</p>
<p>Code:</p>
<pre><code>DateTime date1 = new DateTime(year01, month01, day01, hour01, min01, 00);
DateTime date2 = new DateTime(year01, month01, day02, hour02, min02, 00);
TimeSpan work = date2 - date1;
</code></pre>
<p>workTotal...</p>
<p>*Here I need add to workTotal the value of work</p>
<hr>
<p>It's ok, I have done that.
thx to IInspectable.</p>
| <p>The <a href="https://msdn.microsoft.com/en-us/library/system.timespan.aspx" rel="nofollow">TimeSpan</a> type provides the <a href="https://msdn.microsoft.com/en-us/library/system.timespan.op_addition.aspx" rel="nofollow">TimeSpan.Addition Operator</a>:</p>
<blockquote>
<p>The Addition method defines the addition operator for TimeSpan values. It enables code such as the following:</p>
<pre><code>TimeSpan time1 = new TimeSpan(1, 0, 0, 0); // TimeSpan equivalent to 1 day.
TimeSpan time2 = new TimeSpan(12, 0, 0); // TimeSpan equivalent to 1/2 day.
TimeSpan time3 = time1 + time2; // Add the two time spans.
Console.WriteLine(" {0,12}\n + {1,10}\n {3}\n {2,10}",
time1, time2, time3, new String('_', 10));
// The example displays the following output:
// 1.00:00:00
// + 12:00:00
// __________
// 1.12:00:00
</code></pre>
</blockquote>
|
Horizontal and Vertical navigation inside div using arrows along and down the text <p>I have a HTML <strong>div</strong> with multi line(more than one line) of text. I need to enable horizontal and vertical navigation using keyboard arrows(<strong>up, down, left , right</strong>) as in html input fields(text-area, text) along the text or down the next lines.</p>
<pre><code><div id='enabled_arrow_navigation'>
Horizontal and Vertical navigation inside, div using arrows along and down the text,
Horizontal and Vertical navigation inside div using arrows along and down the text
Horizontal and Vertical navigation inside div using arrows along and down the text
</div>
</code></pre>
<p>I tried bellow code but its not working</p>
<pre><code>$("#enabled_arrow_navigation").keyup(function(e)
{
if (e.keyCode == 40)
{
Navigate(1);
}
if(e.keyCode==38)
{
Navigate(-1);
}
});
</code></pre>
| <p>You can make a div editable by adding contenteditable attribute to true</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='enabled_arrow_navigation' contenteditable='true'>
Horizontal and Vertical navigation inside, div using arrows along and down the text,
Horizontal and Vertical navigation inside div using arrows along and down the text
Horizontal and Vertical navigation inside div using arrows along and down the text
</div></code></pre>
</div>
</div>
</p>
|
Adding items to a dictionary using a function <p>I'm trying to add items to a dictionary using a function, I'm not getting any error message but when I want to display the dictionary items nothing is shown, I'm always getting "Empty".</p>
<pre><code>Function Store_Params()
Dim aDictionary
Set aDictionary = CreateObject("Scripting.Dictionary")
Dim comment
comment = "FALSE"
Set objExcel1 = CreateObject("Excel.Application")
Set objWorkbook1= objExcel1.Workbooks.Open(Environment("STPFilePath"))
For Each objsheet1 In objworkbook1.Sheets
If objsheet1.Name = Environment("TestScriptName") Then
'LastRow = objsheet1.UsedRange.Rows.Count + objsheet1.UsedRange.Row
For irow = 1 To 10
If InStr(1, objExcel1.Cells(irow, 1).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 2).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 3).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 4).Value, "#") = 0 Then
comment = "TRUE"
End If
If comment = "TRUE" Then
For j = 5 To 10
aDictionary.RemoveAll
aDictionary.Add objExcel1.Cells(irow, j).Value, objExcel1.Cells(irow + 1, j).Value
irow = irow + 2
Next
End If
Next
End If
Next
Set Store_Params = aDictionary
If aDictionary.Exists("name1") Then
MsgBox aDictionary.Item("name1")
Else
MsgBox("Empty")
End If
objExcel1.Quit
Set objSheet1 = Nothing
Set objWorkbook1 = Nothing
Set objExcel1 = Nothing
Set aDictionary = Nothing
End Function
Call Store_Params()
</code></pre>
<p>This is my script screenshot:</p>
<p><a href="https://i.stack.imgur.com/vb8rk.png" rel="nofollow"><img src="https://i.stack.imgur.com/vb8rk.png" alt="enter image description here"></a></p>
<p>Any help please, where I'm wrong?</p>
| <p>This section of your code doesn't make any sense.</p>
<blockquote>
<pre><code>For irow = 1 To 10
If InStr(1, objExcel1.Cells(irow, 1).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 2).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 3).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 4).Value, "#") = 0 Then
comment = "TRUE"
End If
If comment = "TRUE" Then
For j = 5 To 10
aDictionary.RemoveAll
aDictionary.Add objExcel1.Cells(irow, j).Value, objExcel1.Cells(irow + 1, j).Value
irow = irow + 2
Next
End If
Next
</code></pre>
</blockquote>
<p>You're checking if there is no <code>#</code> in any of the first 4 cells of a row. If no <code>#</code> is found, you loop <code>j</code> from 5 to 10, and with each iteration remove all entries from the dictionary <strong>and</strong> increment the <strong>row index</strong> (<code>irow</code>) by 2. Meaning your statement <code>aDictionary.Add</code> will add a keys and values from the following ranges:</p>
<pre>E1:E2
F3:F4
G5:G6
H7:H8
I9:I10
J11:J12</pre>
<p>But since you remove all entries with every iteration of the inner loop only the key and value from the last range remain (<code>J11:J12</code>). Since those cells are empty, you end up with a dictionary that has just one entry where both key and value are empty strings. In JSON notation it would look like this:</p>
<pre class="lang-json prettyprint-override"><code>{
"": ""
}
</code></pre>
<p>That you always get a message "Empty" from this is only natural, because the dictionary doesn't contain an entry "name1".</p>
<p>Now, assuming that what you actually want is fill the dictionary with all keys and values from the data rows and skip over those rows that contain a <code>#</code> in any of the first 4 cells, you'd do something like this:</p>
<pre><code>For irow = 1 To 10
If InStr(1, objExcel1.Cells(irow, 1).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 2).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 3).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 4).Value, "#") = 0 Then
For j = 5 To 10
aDictionary(objExcel1.Cells(irow, j).Value) = objExcel1.Cells(irow + 1, j).Value
Next
irow = irow + 1 'skip over value row
End If
Next
</code></pre>
<p>Or, if you want to clear the dictionary every time you encounter a row containing <code>#</code>:</p>
<pre><code>For irow = 1 To 10
If InStr(1, objExcel1.Cells(irow, 1).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 2).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 3).Value, "#") = 0 And InStr(1, objExcel1.Cells(irow, 4).Value, "#") = 0 Then
For j = 5 To 10
aDictionary(objExcel1.Cells(irow, j).Value) = objExcel1.Cells(irow + 1, j).Value
Next
irow = irow + 1 'skip over value row
Else
aDictionary.RemoveAll
End If
Next
</code></pre>
<p>The latter would still produce a message box "Empty", though, since there is no "name1" in the rows 8 and 9.</p>
|
Enable autocomplete when loaded by AJAX <p>trying to get my head around this problem:</p>
<p>I often load fragments of page via .load() function such as:</p>
<pre><code><div class="fragment_load">
<form>
<input id="typeaway" type="text" class="autocomplete"/>
<label>Test Type</label>
</form>
<script type="text/javascript">
$("#typeaway").autocomplete({
serviceUrl: "/restaway",
minChars: 3,
paramName: "query",
});
</script>
</div>
</code></pre>
<p>Now as you can imagine autocomplete is not working due to this.</p>
<p>I am unsure how to make it work going forwards for these small fragments that i load via AJAX.</p>
<p>Any assistance is appreciated.</p>
| <p>In this case you could put the <code>autocomplete</code> initialisation code within the callback of the <code>load()</code> method, something like this:</p>
<pre><code>$('#foo').load('bar.html', function() {
$("#typeaway").autocomplete({
serviceUrl: "/restaway",
minChars: 3,
paramName: "query",
});
});
</code></pre>
|
Bonus points system <p>Here is my circle touch code:</p>
<pre><code>scoreLabel.run(SKAction.sequence([SKAction.wait(forDuration: 1.0), SKAction.fadeIn(withDuration: 1.0)]))
let positionOfTouch = touch.location(in: self)
let tappedNode = atPoint(positionOfTouch)
var nameOfTappedNode = tappedNode.name
if nameOfTappedNode == "circleObject" {
tappedNode.name = ""
tappedNode.removeAllActions()
</code></pre>
<p>So i want to make a point system.
My app consists of clicking circles as they appear and disappear when clicked.</p>
<ol>
<li><p>I have a score at the top which counts how many circles i've clicked. </p></li>
<li><p>Sometimes the circles spawn on top of each other and stack so it is hard to click all the circles. </p></li>
<li><p>I want to make it so when the circles are stacked, you can tap them once and make them all disappear getting a +1 point for doing so, which can be counted at the top next to my score:
<img src="https://i.stack.imgur.com/CqeFOm.png" alt="Example of the Score UI"></p></li>
<li><p>Here is an example of the circles stacking and getting a +1 point when tapped.
<a href="https://i.stack.imgur.com/t1pYMm.png" rel="nofollow"><img src="https://i.stack.imgur.com/t1pYMm.png" alt="enter image description here"></a></p></li>
</ol>
<p>Thanks =]</p>
| <p>You have to get the touch position and check how many 'circle views' are in that point.</p>
<p>you can get the touch location using </p>
<pre><code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
var touch = event.allTouches()!.first!
var location = touch.location(inView: touch.view)
}
</code></pre>
|
tornado.locks.Lock release <p>The tornado example gives the following example for locks:</p>
<pre><code>>>> from tornado import gen, locks
>>> lock = locks.Lock()
>>>
>>> @gen.coroutine
... def f():
... with (yield lock.acquire()):
... # Do something holding the lock.
... pass
...
... # Now the lock is released.
</code></pre>
<p>Do you need to release the lock manually after the with or is that the purpose of using the with statement in that block? If this is the case why is there a separate release() and does this function need to be yielded?</p>
| <p>Right, the <code>with</code> statement ensures the Lock is released, no need to call <code>release</code> yourself.</p>
<p><code>release</code> is naturally non-blocking -- your coroutine can complete a call to <code>release</code> without waiting for any other coroutines -- therefore <code>release</code> does not require a <code>yield</code> statement. You can determine that for yourself by noticing the return value of <code>release</code> is <code>None</code>, whereas the return value of <code>acquire</code> is a Future.</p>
|
What is the best for develop front end of java EE application (JSF or angular js)? <p>I want to develop application using java spring,strut and hibernate.So I want to make front for this application.Now I have two options to make front.They are angular 2 or JSF.Therefore i want to clarify what is best for my application.Please compare angular 2 and JSF?
I want to know what is reference site that guys follows </p>
| <p>*AngularJS is client side HTML and Javascript, JSF is server side Java and XML
*JSF and RichFaces is ok for simple solutions like forms, tables, simple pages. But when requirements are more complex like dynamic rerender part of the page or some fancy features then things get more cumbersome if you try to do not standard things (especially when you want some complex validation where few fields depends on each other or you want to write own component). </p>
|
Why INTO Clause is expected in select statement? <p>I didn't declare a variable to assign value from query, then why code below throws error for INTO clause? </p>
<pre><code>create or replace PROCEDURE Disp_of_IPC_Crime_Case(
startDate DATE,
endDate DATE)
IS
BEGIN
SELECT *
FROM (
SELECT COUNT(*)
FROM t_crime_major_minor_heads cdmh
INNER JOIN t_fir_registration fr
ON fr.FIR_REG_NUM= cdmh.FIR_REG_NUM
INNER JOIN t_final_report fnr
ON fnr.FIR_REG_NUM = cdmh.FIR_REG_NUM
WHERE MAJOR_HEAD_CD = 8
AND fr.RECORD_CREATED_ON > (StartDate - INTERVAL '5' YEAR)
AND NVL(fnr.FR_TYPE_CD,0) =11
AND NVL(fnr.CHARGSHEET_OR_NOT,'')='N'
) Below5COUNTERFEITING;
END;
</code></pre>
| <p>If the aim of the procedure is to provide a report, you can do this by <a href="https://oracle-base.com/articles/misc/using-ref-cursors-to-return-recordsets" rel="nofollow">passing back a ref cursor</a>, or if you have Oracle 12.1 or later you can use the new <a href="https://oracle-base.com/articles/12c/implicit-statement-results-12cr1" rel="nofollow">implicit statement result</a> feature.</p>
|
How to check if Play Service is installed with Firebase? <p>I know how to check it with GoogleApiAvailability (by GCM). But this function is not supported be FireBase core library.</p>
<p>my dependencies are:</p>
<pre><code>compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile 'com.android.support:recyclerview-v7:24.2.1'
compile 'com.google.firebase:firebase-core:9.6.1'
compile 'com.google.firebase:firebase-messaging:9.6.1'
compile 'com.android.support:support-v4:24.2.1'
</code></pre>
| <p>I believe what you're looking for is this:</p>
<pre><code>compile 'com.google.android.gms:play-services-auth:9.6.1'
</code></pre>
|
PHP SimpleXML select elements <p>I'm trying to extract information from an ncx file via SimpleXML.
The file looks like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
<head>
<meta name="dtb:uid" content="http://www.hxa7241.org/articles/content/epup-guide_hxa7241_2007_1.epub"/>
</head>
<docTitle>
<text>Der Weg der Könige</text>
</docTitle>
<navMap>
<navPoint id="toc1" playOrder="1">
<navLabel>
<text>Widmung</text>
</navLabel>
<content src="e9783641059446_ded01.html"/>
</navPoint>
<navPoint id="toc2" playOrder="2">
<navLabel>
<text>Inhaltsverzeichnis</text>
</navLabel>
<content src="e9783641059446_toc01.html"/>
</navPoint>
<navPoint id="toc3" playOrder="3">
<navLabel>
<text>PRÃLUDIUM</text>
</navLabel>
<content src="e9783641059446_fm02.html"/>
</navPoint>
<navPoint id="toc4" playOrder="4">
<navLabel>
<text>4500 JAHRE SPÃTER</text>
</navLabel>
<content src="e9783641059446_fm03.html"/>
</navPoint>
<navPoint id="toc5" playOrder="5">
<navLabel>
<text>PROLOG - TÃTEN</text>
</navLabel>
<content src="e9783641059446_fm04.html"/>
</navPoint>
<navPoint id="toc6" playOrder="6">
<navLabel>
<text>ERSTER TEIL - Ãber dem Schweigen</text>
</navLabel>
<content src="e9783641059446_p01.html"/>
<navPoint id="toc7" playOrder="7">
<navLabel>
<text>1 - STURMGESEGNET</text>
</navLabel>
<content src="e9783641059446_c01.html"/>
</navPoint>
<navPoint id="toc8" playOrder="8">
<navLabel>
<text>2 - DIE EHRE IST TOT</text>
</navLabel>
<content src="e9783641059446_c02.html"/>
</navPoint>
<navPoint id="toc9" playOrder="9">
<navLabel>
<text>3 - DIE STADT DER GLOCKEN</text>
</navLabel>
<content src="e9783641059446_c03.html"/>
</navPoint>
<navPoint id="toc10" playOrder="10">
<navLabel>
<text>4 - DIE ZERBROCHENE. EBENE</text>
</navLabel>
<content src="e9783641059446_c04.html"/>
</navPoint>
<navPoint id="toc11" playOrder="11">
<navLabel>
<text>5 - HÃRETISCH</text>
</navLabel>
<content src="e9783641059446_c05.html"/>
</navPoint>
<navPoint id="toc12" playOrder="12">
<navLabel>
<text>6 - BRÃCKE VIER</text>
</navLabel>
<content src="e9783641059446_c06.html"/>
</navPoint>
<navPoint id="toc13" playOrder="13">
<navLabel>
<text>7 - ALLES, WAS VERNÃNFTIG IST</text>
</navLabel>
<content src="e9783641059446_c07.html"/>
</navPoint>
<navPoint id="toc14" playOrder="14">
<navLabel>
<text>8 - NÃHER ZUR FLAMME</text>
</navLabel>
<content src="e9783641059446_c08.html"/>
</navPoint>
<navPoint id="toc15" playOrder="15">
<navLabel>
<text>9 - VERDAMMNIS</text>
</navLabel>
<content src="e9783641059446_c09.html"/>
</navPoint>
<navPoint id="toc16" playOrder="16">
<navLabel>
<text>10 - GESCHICHTEN ÃBER CHIRURGEN</text>
</navLabel>
<content src="e9783641059446_c10.html"/>
</navPoint>
<navPoint id="toc17" playOrder="17">
<navLabel>
<text>11 - TROPFEN</text>
</navLabel>
<content src="e9783641059446_c11.html"/>
</navPoint>
</navPoint>
<navPoint id="toc18" playOrder="18">
<navLabel>
<text>ZWISCHENSPIELE</text>
</navLabel>
<content src="e9783641059446_p02.html"/>
<navPoint id="toc19" playOrder="19">
<navLabel>
<text>Z-1 - ISCHIKK</text>
</navLabel>
<content src="e9783641059446_c12.html"/>
</navPoint>
<navPoint id="toc20" playOrder="20">
<navLabel>
<text>Z-2 - NAN BALAT</text>
</navLabel>
<content src="e9783641059446_c13.html"/>
</navPoint>
<navPoint id="toc21" playOrder="21">
<navLabel>
<text>Z-3 - DER SEGEN DER UNWISSENHEIT</text>
</navLabel>
<content src="e9783641059446_c14.html"/>
</navPoint>
</navPoint>
<navPoint id="toc22" playOrder="22">
<navLabel>
<text>ZWEITER TEIL - Die leuchtenden Stürme</text>
</navLabel>
<content src="e9783641059446_p03.html"/>
<navPoint id="toc23" playOrder="23">
<navLabel>
<text>12 - EINHEIT</text>
</navLabel>
<content src="e9783641059446_c15.html"/>
</navPoint>
<navPoint id="toc24" playOrder="24">
<navLabel>
<text>13 - ZEHN HERZSCHLÃGE</text>
</navLabel>
<content src="e9783641059446_c16.html"/>
</navPoint>
<navPoint id="toc25" playOrder="25">
<navLabel>
<text>14 - ZAHLTAG</text>
</navLabel>
<content src="e9783641059446_c17.html"/>
</navPoint>
<navPoint id="toc26" playOrder="26">
<navLabel>
<text>15 - DER KÃDER</text>
</navLabel>
<content src="e9783641059446_c18.html"/>
</navPoint>
<navPoint id="toc27" playOrder="27">
<navLabel>
<text>16 - KOKONS</text>
</navLabel>
<content src="e9783641059446_c19.html"/>
</navPoint>
<navPoint id="toc28" playOrder="28">
<navLabel>
<text>17 - EIN BLUTROTER SONNENUNTERGANG</text>
</navLabel>
<content src="e9783641059446_c20.html"/>
</navPoint>
<navPoint id="toc29" playOrder="29">
<navLabel>
<text>18 - DER GROSSPRINZ DES KRIEGES</text>
</navLabel>
<content src="e9783641059446_c21.html"/>
</navPoint>
<navPoint id="toc30" playOrder="30">
<navLabel>
<text>19 - DER STURZ DER STERNE</text>
</navLabel>
<content src="e9783641059446_c22.html"/>
</navPoint>
<navPoint id="toc31" playOrder="31">
<navLabel>
<text>20 - SCHARLACHROT</text>
</navLabel>
<content src="e9783641059446_c23.html"/>
</navPoint>
<navPoint id="toc32" playOrder="32">
<navLabel>
<text>21 - WARUM MENSCHEN LÃGEN</text>
</navLabel>
<content src="e9783641059446_c24.html"/>
</navPoint>
<navPoint id="toc33" playOrder="33">
<navLabel>
<text>22 - AUGEN, HÃNDE ODER KUGELN?</text>
</navLabel>
<content src="e9783641059446_c25.html"/>
</navPoint>
<navPoint id="toc34" playOrder="34">
<navLabel>
<text>23 - VIELSEITIG</text>
</navLabel>
<content src="e9783641059446_c26.html"/>
</navPoint>
<navPoint id="toc35" playOrder="35">
<navLabel>
<text>24 - DIE GALERIE DER LANDKARTEN</text>
</navLabel>
<content src="e9783641059446_c27.html"/>
</navPoint>
<navPoint id="toc36" playOrder="36">
<navLabel>
<text>25 - DER SCHLÃCHTER</text>
</navLabel>
<content src="e9783641059446_c28.html"/>
</navPoint>
<navPoint id="toc37" playOrder="37">
<navLabel>
<text>26 - STILLE</text>
</navLabel>
<content src="e9783641059446_c29.html"/>
</navPoint>
<navPoint id="toc38" playOrder="38">
<navLabel>
<text>27 - KLUFTDIENST</text>
</navLabel>
<content src="e9783641059446_c30.html"/>
</navPoint>
<navPoint id="toc39" playOrder="39">
<navLabel>
<text>28 - ENTSCHEIDUNG</text>
</navLabel>
<content src="e9783641059446_c31.html"/>
</navPoint>
</navPoint>
<navPoint id="toc40" playOrder="40">
<navLabel>
<text>ZWISCHENSPIELE</text>
</navLabel>
<content src="e9783641059446_p04.html"/>
<navPoint id="toc41" playOrder="41">
<navLabel>
<text>Z-4 - RYSN</text>
</navLabel>
<content src="e9783641059446_c32.html"/>
</navPoint>
<navPoint id="toc42" playOrder="42">
<navLabel>
<text>Z-5 - DER SAMMLER AXIES</text>
</navLabel>
<content src="e9783641059446_c33.html"/>
</navPoint>
<navPoint id="toc43" playOrder="43">
<navLabel>
<text>Z-6 - EIN KUNSTWERK</text>
</navLabel>
<content src="e9783641059446_c34.html"/>
</navPoint>
</navPoint>
<navPoint id="toc44" playOrder="44">
<navLabel>
<text>DRITTER TEIL - Sterben</text>
</navLabel>
<content src="e9783641059446_p05.html"/>
<navPoint id="toc45" playOrder="45">
<navLabel>
<text>29 - IRRMASSUNG</text>
</navLabel>
<content src="e9783641059446_c35.html"/>
</navPoint>
<navPoint id="toc46" playOrder="46">
<navLabel>
<text>30 - UNSICHTBARE FINSTERNIS</text>
</navLabel>
<content src="e9783641059446_c36.html"/>
</navPoint>
<navPoint id="toc47" playOrder="47">
<navLabel>
<text>31 - UNTER DER HAUT</text>
</navLabel>
<content src="e9783641059446_c37.html"/>
</navPoint>
<navPoint id="toc48" playOrder="48">
<navLabel>
<text>32 - SEITENTRAGEN</text>
</navLabel>
<content src="e9783641059446_c38.html"/>
</navPoint>
<navPoint id="toc49" playOrder="49">
<navLabel>
<text>33 - CYMATIK</text>
</navLabel>
<content src="e9783641059446_c39.html"/>
</navPoint>
<navPoint id="toc50" playOrder="50">
<navLabel>
<text>34 - STURMWAND</text>
</navLabel>
<content src="e9783641059446_c40.html"/>
</navPoint>
<navPoint id="toc51" playOrder="51">
<navLabel>
<text>35 - EIN LICHT ZU SEHEN</text>
</navLabel>
<content src="e9783641059446_c41.html"/>
</navPoint>
<navPoint id="toc52" playOrder="52">
<navLabel>
<text>36 - DIE LEKTION</text>
</navLabel>
<content src="e9783641059446_c42.html"/>
</navPoint>
</navPoint>
<navPoint id="toc53" playOrder="53">
<navLabel>
<text>SCHLUSSBEMERKUNG</text>
</navLabel>
<content src="e9783641059446_bm01.html"/>
</navPoint>
<navPoint id="toc54" playOrder="54">
<navLabel>
<text>ARS ARCANUM</text>
</navLabel>
<content src="e9783641059446_bm02.html"/>
</navPoint>
<navPoint id="toc55" playOrder="55">
<navLabel>
<text>DANKSAGUNG</text>
</navLabel>
<content src="e9783641059446_ack01.html"/>
</navPoint>
<navPoint id="toc56" playOrder="56">
<navLabel>
<text>Die Sturmlicht-Chroniken werden fortgesetzt in:</text>
</navLabel>
<content src="e9783641059446_tea01.html"/>
</navPoint>
<navPoint id="toc57" playOrder="57">
<navLabel>
<text>Copyright</text>
</navLabel>
<content src="e9783641059446_cop01.html"/>
</navPoint>
</navMap>
</ncx>
</code></pre>
<p>And I want to grab all the html files, which are located in this element:</p>
<pre><code><content src="e9783641059446_cop01.html"/>
</code></pre>
<p>Currently I'm trying it this way:</p>
<pre><code>$ncx = simplexml_load_file($file);
$items = $ncx->navMap->children();
foreach ($items as $it) {
echo $it->content['src'];
}
</code></pre>
<p>Problem is that the content nodes are not in the same depth level as you might have noticed. Does anyone know how to fix it?</p>
| <p>The XML has a namespace. Try with</p>
<pre><code>$ncx = simplexml_load_file('test.xml');
$ncx->registerXPathNamespace('x', 'http://www.daisy.org/z3986/2005/ncx/');
foreach ($ncx->xpath('//x:content/@src') as $src) {
echo $src, PHP_EOL;
}
</code></pre>
<p>Without XPath:</p>
<pre><code>$ncx = simplexml_load_file('test.xml', "SimpleXmlElement", 0, 'http://www.daisy.org/z3986/2005/ncx/', false);
foreach ($ncx->navMap->navPoint as $np) {
echo $np->content->attributes()->src, PHP_EOL;
}
</code></pre>
|
How to remove function pointer from std::deque by val? <p>I am using <code>std::deque</code> to keep callback functions.</p>
<p>Everything works perfectly except removing a specific callback.</p>
<pre><code>typedef std::function<void(void)> cb_Action;
std::deque<cb_Action> actionCallbacks;
</code></pre>
<p>I can Add items one by one or clear all of them without any problems.</p>
<p>But I cannot remove a specific callback from the <code>deque</code> variable.</p>
<pre><code>actionCallbacks.erase ( std::remove(actionCallbacks.begin(), actionCallbacks.end(), callbackToRemove), actionCallbacks.end());
</code></pre>
<p>It gives compile time error:</p>
<pre><code>binary '==': no operator found which takes a left-hand operand of type:'std::function<void(void)>' (or there is no acceptable conversion)
</code></pre>
<p>So, how can I remove a specific <code>cb_Action</code>?</p>
| <p>If you deal with usual functions you can do something like this based on <a href="http://en.cppreference.com/w/cpp/utility/functional/function/target" rel="nofollow">std::function::target</a>:</p>
<pre><code>void callback_1(void) {}
void callback_2(void) {}
actionCallbacks = {
std::function<void(void)>(callback_1),
std::function<void(void)>(callback_2),
std::function<void(void)>(callback_1)
};
actionCallbacks.erase(
std::remove_if(actionCallbacks.begin(), actionCallbacks.end(), [](cb_Action action) {
return (*action.target<void(*)(void)>() == callback_1);
}),
actionCallbacks.end()
);
</code></pre>
<p>Here all items with <code>callback_1</code> inside are removed.</p>
|
Invalid child context `store` of type `function` supplied to `Provider`, expected `object` <p>I am trying to connect the state in the reducers to the components in my react components.
Here is the code of the reducer is in <code>reducer_books.js</code>:</p>
<pre><code>export default function(){
return [
{title:'A'},
{title:'E'}
];
}
</code></pre>
<p>Then, i added it to the combine reducer in <code>index.js</code>:</p>
<pre><code>import {combineReducers} from 'redux';
import BookReducer from './reducer_books';
const rootReducer= combineReducers({
books:BookReducer
});
export default rootReducer;
</code></pre>
<p>At the end i tried to add it in the parent component:</p>
<pre><code>import State from './reducer/index';
import { Provider } from 'react-redux';
ReactDOM.render(
<Provider store={State}>
<App />
</Provider>, document.getElementById('root'));
</code></pre>
<p>And in the target component i have:</p>
<pre><code>import React,{Component} from 'react';
import {connect} from 'react-redux';
class BookList extends Component{
renderList(){
return this.props.books.map((book)=>{
<li key={book.title}>{book.title}</li>
});
}
render(){
return(
<div>
<ul>
{this.renderList()}
</ul>
</div>);
}
}
function mapStateToProps(state){
return{
books:state.books
};
}
export default connect(mapStateToProps)(BookList);
</code></pre>
<p>Unfortunately, it complains with:</p>
<pre><code>Warning: Failed prop type: Invalid prop `store` of type `function` supplied to `Provider`, expected `object`.
in Provider (at index.js:11)
Warning: Failed childContext type: Invalid child context `store` of type `function` supplied to `Provider`, expected `object`.
in Provider (at index.js:11)
Warning: Failed context type: Invalid context `store` of type `function` supplied to `Connect(BookList)`, expected `object`.
in Connect(BookList) (at App.js:35)
in div (at App.js:33)
in div (at App.js:32)
in App (at index.js:12)
in Provider (at index.js:11)
Uncaught TypeError: _this.store.getState is not a function
Error: Attempted to update component `Connect(BookList)` that has already been unmounted (or failed to mount)
</code></pre>
| <p>In your example I don't see where you <a href="https://github.com/reactjs/redux#the-gist" rel="nofollow"><strong>configure <code>Store</code></strong></a>, I suppose that you missed this step </p>
<pre><code>import reducers from './reducer/index';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
const Store = createStore(reducers);
ReactDOM.render(
<Provider store={ Store }>
<App />
</Provider>, document.getElementById('root')
);
</code></pre>
|
Excel Copy certain values of Column to another sheet <p>I'm trying to copy certain values of column to another sheet, but it's not working.</p>
<p>The code I am using is:</p>
<pre><code>Worksheets("Report").Range(".Cells(x, 1)", ".Cells(x, 2)", ".Cells(x, 4)", ".Cells(x, 6)", ".Cells(x, 9):.Cells(x, 13)").Copy
</code></pre>
| <p>You are using <code>Range</code> wrong in two ways:</p>
<p>1) <code>Range</code> has only one or two arguments. The usage is either</p>
<pre><code>Range(someAddress)
</code></pre>
<p>where <code>someAddress</code> is a String like <code>"A1"</code>, <code>"A1:B2</code> or even unions like <code>"A1:B2,C3"</code> or</p>
<pre><code>Range(startCell, endCell)
</code></pre>
<p>where <code>startCell</code> and <code>endCell</code> are the first and last cells of the range. They can be supplied either by address (<code>"A1"</code>) or by range object (<code>Cells(1,1)</code>).</p>
<p>Note that you can also pass ranges with multiple cells but I am not completely sure how it acts then.</p>
<p>2) You are putting your arguments in quotes, making them strings. That means that you don't pass a cell reference to <code>Range</code> but the string <code>".Cells(x, 1)"</code> (not even x is replaced).</p>
<hr>
<p>Now to create a range from multiple cells you can use <code>Union</code></p>
<pre><code>Union(.Cells(x, 1), .Cells(x, 2), ... )
</code></pre>
<p>or create an address string using the cells addresses</p>
<pre><code>.Range(.Cells(x, 1).Address & "," & .Cells(x, 2).Address & "," & ...)
</code></pre>
|
How to add attributes in input element with Beautifulsoup <p>I use BeautifulSoup to find a specific element on my html page.
I want to add an attribute "value" to this element and save it to the original html.
How can I do this with Beautifulsoup? Right now I do this to get the whole html and find the specific element:</p>
<pre><code>static_map = opener.open('my_url')
bs = BeautifulSoup(static_map.read())
title = bs.find("input", {"name":"title"})
</code></pre>
<p>The title looks like:</p>
<pre><code><input class="has-popover form-control" data-container="body" id="id_title" maxlength="255" name="title" type="text"/>
</code></pre>
<p>I want to add in this input element the attribute: value
and then save it to the initial html.</p>
<p>Then I will have to send this as a post request.</p>
| <p>Try this instead:</p>
<pre><code>bs.find('input')['value'] = ''#Whatever you want the value to be.
</code></pre>
<p>Because <code>bs.find</code> returns a dictionary, so to set an item in a dicionary use subscript notation.</p>
|
Combining firebase observables with angular2 <p>I'm working on an angular2 - firebase app, and was wondering on some best rxjs practices, that I find difficult to google. </p>
<p>Say I have a class "Project" with properties like "name", "$key", etc. And then also arrays of "Note[]" and "Task[]"</p>
<p>"Note" and "Task" are then their own classes.</p>
<p>Initially I structured data in firebase like this:</p>
<ul>
<li>Project
<ul>
<li>Name</li>
<li>Tags</li>
<li>Other meta stuff</li>
<li>Tasks
<ul>
<li>Task1</li>
<li>Task2, etc</li>
</ul></li>
<li>Notes
<ul>
<li>Note1</li>
<li>Note2, etc</li>
</ul></li>
</ul></li>
</ul>
<p>I would get one data stream and use map to get the data to look exactly how I want it.</p>
<p>But then I realised that this is bad practice and the project trees should be as flat as possible so that I wouldn't be forced to load everything when I just need the project metadata for example.</p>
<p>So I restructured it to be like this:</p>
<ul>
<li>Projects
<ul>
<li>Project1
<ul>
<li>Name</li>
<li>Tags</li>
<li>etc</li>
</ul></li>
<li>Project2
<ul>
<li>Name</li>
<li>Tags</li>
<li>etc</li>
</ul></li>
</ul></li>
<li>Tasks
<ul>
<li>Project1
<ul>
<li>Task1
<ul>
<li>Name</li>
<li>Body</li>
</ul></li>
<li>Task2
<ul>
<li>Name</li>
<li>Body</li>
</ul></li>
</ul></li>
<li>Project2
<ul>
<li>Task1
<ul>
<li>Name</li>
<li>Body</li>
</ul></li>
<li>Task2
<ul>
<li>Name</li>
<li>Body</li>
</ul></li>
</ul></li>
</ul></li>
<li>Notes
<ul>
<li>Project1
<ul>
<li>Note1
<ul>
<li>Name</li>
<li>Body</li>
</ul></li>
<li>Note2
<ul>
<li>Name</li>
<li>Body</li>
</ul></li>
</ul></li>
</ul></li>
</ul>
<p>So this way I get three data streams of "Projects" "Notes" and "Tasks".
It seems to make sense to combine this into a single stream of "Projects" with "Notes" and "Tasks" inside it.</p>
<p>Although I'm unsure of what's the best way to do that?
I wrote a long function that concatMaps everything into and array of "Project[]", but now I'm left with an array instead of a stream, which definitely seams wrong.</p>
<p>Or maybe it's a wrong approach altogether? </p>
<p>Looking forward to your thoughts.
Thanks!
H</p>
| <p>I don't understand your structure exactly but if you have "Projects" "Notes" and "Tasks" as three separate streams (I guess this means you have three Observables). You can use <a href="http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-merge" rel="nofollow"><code>merge()</code></a> or <a href="http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-concat" rel="nofollow"><code>concat()</code></a> to consume whichever values comes first from any of them or consume one Observable at the time respectively:</p>
<pre><code>let obs1 = Observable.from([1, 2, 3]).map(v => Observable.of(v).delay(1000)).concatAll();
let obs2 = Observable.from(['a', 'b', 'c']).map(v => Observable.of(v).delay(1000)).concatAll();
obs1.concat(obs2)
.subscribe(v => console.log(v));
obs1.merge(obs2)
.subscribe(v => console.log(v));
</code></pre>
<p>See live demo: <a href="http://plnkr.co/edit/TLxg1jOuhAN6U8xoQJIo?p=preview" rel="nofollow">http://plnkr.co/edit/TLxg1jOuhAN6U8xoQJIo?p=preview</a></p>
<p>The first example with <code>concat()</code> prints:</p>
<pre><code>1
2
3
a
b
c
</code></pre>
<p>The second example with <code>merge()</code> gives:</p>
<pre><code>1
a
2
b
3
c
</code></pre>
<p>I think you should understand the difference.</p>
<p>Don't mind the complicated operator chaing for <code>obs1</code> and <code>obs2</code>. It's just to emit each value with delay to simulate asynchronous streams.</p>
|
Convert Java objects to JSON with specific fields <p>I want to create two different JSON documents and each contains 5 fields. I have a POJO class with 10 attributes. I want to form json1 with 5 attributes and json2 with 5 attributes using that POJO class. Is there any way to construct these objects?</p>
| <p>Consider writing two separate wrapper classes which each expose the fields you want for the two cases, and pass the pojo as a constructor arg.</p>
<p>So, one of them exposes one set of properties and might look like this:</p>
<pre><code>public class JsonObject1 {
private MyPojo myPojo;
public JsonObject1(MyPojo myPojo) {
this.myPojo = myPojo;
}
public void getProperty1() {
return myPojo.getProperty1();
}
......
}
</code></pre>
<p>and the other is similar, but exposes the other subset of properties.</p>
<p>Alternatively, you could add two methods (possibly to your POJO, or possibly to a service class that is exposing the POJO) that each returns a <code>Map</code> (eg a <code>HashMap</code>) where you've copied across the specific properties you want for each view, and then convert those Maps to JSON. This is less "model-driven", but might be less work overall. Thanks to @fvu for this observation!</p>
<pre><code>public Map<String, Object> getPojoAsMap1() {
Map<String, Object> m = new HashMap<>();
m.put("property1", pojo.getProperty1());
....
return m;
}
</code></pre>
<p>It's also possible that the two different JSON representations are trying to tell you that your POJO should be split up into two POJOs - sometimes things like this are hints about how your code could be improved. But it depends on the circumstances, and it might not apply in this case.</p>
|
Can any one explain scope of c-macro's defined local to function and global? <p>I don't know why this output appears and behavior of pre-processor.</p>
<p>Output:</p>
<pre><code>the value in main 10
the value in fun 20
the value in 2 main 10
</code></pre>
<p>Source</p>
<pre><code>#include<stdio.h>
#define MAX 10
int fun(int a);
int main()
{
int a;
a=MAX;
printf("the value in main =%d\n",a);
fun(a);
int b;
b=MAX;
printf("the value in 2 main =%d\n",b); /*<----doubt at this line*/
}
</code></pre>
<p>What's happening when we assign new value to the macro inside local function why it is not updating outside of function?</p>
<p>Please do needful.</p>
<pre><code>int fun(int a)
{
#undef MAX
#define MAX 20
a=MAX;
printf("the value in 2 main =%d\n",a);
}
</code></pre>
| <p>A macro is not checked at runtime. It is checked during before compilation, in a stage called pre-processing. </p>
<p>So, the compiler processes the <code>main</code> function first and replaces <code>MAX</code> with 10 in all lines. Then when it reaches the <code>fun</code> function, it undefines <code>MAX</code> and redefines it with 20, and replaces the lines in <code>fun</code> with 20.</p>
|
Meteor.js icons are missing after update <p>I have updated my meteor and now no icons are displayed - before the update all worked fine.</p>
<p>folder structure:</p>
<p>-public</p>
<p>--fonts</p>
<p>---tablet</p>
<p>---monitor</p>
<p>and I access the tablet icons with following code:</p>
<pre><code> @font-face {
font-family: "Flaticon";
src: url("fonts/tablet/Flaticon.eot");
src: url("fonts/tablet/Flaticon.eot?#iefix") format("embedded-opentype"),
url("fonts/tablet/Flaticon.woff") format("woff"),
url("fonts/tablet/Flaticon.ttf") format("truetype"),
url("fonts/tablet/Flaticon.svg#Flaticon") format("svg");
font-weight: normal;
font-style: normal;
}
@media screen and (-webkit-min-device-pixel-ratio:0) {
@font-face {
font-family: "Flaticon";
src: url("fonts/tablet/Flaticon.svg#Flaticon") format("svg");
}
}
[class^="flaticon-"]:before, [class*=" flaticon-"]:before,
[class^="flaticon-"]:after, [class*=" flaticon-"]:after {
font-family: Flaticon;
font-size: 20px;
font-style: normal;
/*margin-left: 20px;*/
}
.flaticon-clock:before { content: "\f100";font-size: 60px; }
.flaticon-clock-circular-outline:before { content: "\f101"; }
.flaticon-cooking-stove-with-heat:before { content: "\f103"; font-size: 60px; color:white;}
.flaticon-one-finger-click-black-hand-symbol:before { content: "\f104"; font-size: 60px; color:white;}
/*Pfanne blau*/
.flaticon-closed-pan-blue-white:before { content: "\f102"; color:blue; font-size: 140px;padding:0px; padding-left:10px; padding-right:10px;border:1px solid #e0e0e0;}
.flaticon-closed-pan-white-blue:before { content: "\f102"; color:white; background-color:blue; font-size: 140px;padding:0px; padding-left:10px; padding-right:10px;border:1px solid #e0e0e0;}
/*Topf gelb*/
.flaticon-saucepan-yellow-white:before { content: "\f105"; color:yellow; font-size: 120px; padding:10px; border:1px solid #e0e0e0;}
.flaticon-saucepan-white-yellow:before { content: "\f105"; color:white; font-size: 120px; padding:10px; background-color:yellow; }
/*Topf grün*/
.flaticon-saucepan-green-white:before { content: "\f105"; color:green; font-size: 120px;padding:10px; border:1px solid #e0e0e0;}
.flaticon-saucepan-white-green:before { content: "\f105"; color:white; background-color:green; font-size: 120px;padding:10px; border:1px solid #e0e0e0;}
/*.flaticon-saucepan-red:before { content: "\f105"; color:red; font-size: 120px;padding:10px; border:1px solid #e0e0e0;}*/
</code></pre>
<p>The strange thing is, that this code worked fine before the update but now no icons and images are displayed in my app.</p>
<p>Does anybody know the problem? Thank you very much.</p>
| <p>You may need to add a leading slash ('/') to all of your icon paths.</p>
<p><code>src: url("fonts/tablet/Flaticon.eot");</code></p>
<p>maybe should be:</p>
<p><code>src: url("/fonts/tablet/Flaticon.eot");</code></p>
|
Is this a C++ Semaphore? <p>I have a thread-save-resource (a OpenCl-Command Queue to a device),but i want restrict the number of threads that have access to this ressource at the same time(i want to calculate on my cpu if the gpu command-queue is 'to full'). Unfortunately i'm relatively new to c++11 atomic operations. So i want to know if the following source code works as intended. </p>
<pre><code>class SpinSemaphore{
public:
SpinSemaphore(int max_count):
_cnt(0),
_max_cnt(max_count){}
bool try_lock(){
bool run = true;
while(run){
int cnt = _cnt.load();
if(++cnt > _max_cnt) return false;
run = !std::atomic_compare_exchange_weak(&_cnt, &cnt,
std::memory_order_acquire);
}
return true;
}
void unlock(){
--_cnt;
}
private:
std::atomic<int> _cnt;
int _max_cnt;
};
//
SpinSemaphore m(4);
void foo(){ //..
if(m.try_lock()){//..
my_queue.enqueueNDRangeKernel(/**/);
}
else
//fallback
}
</code></pre>
| <p>No, that won't behave as expected - consider the situation where 2 threads get to
<code>int cnt = _cnt.load();</code> at the same time. They will both read the same value, and both set the counter to the same value, even though it might be that only 1 of them should've got though.</p>
<p>That might be considered an acceptably rare occurrence for you to ignore, apart from when you unlock, your count will become negative. </p>
|
How to get Angular 2 element through class name in Jasmine <p>I can get element with using the </p>
<pre><code>fixture.debugElement.query(By.css('h1'));
</code></pre>
<p>But what I should to do when I want get element through class name. Something like this </p>
<pre><code>fixture.debugElement.query(By.css('class="name"'))
</code></pre>
| <p>You use <code>By.css</code> to pass a css selector. So any selector you can use with css, you can use with <code>By.css</code>. And a selector for a class is simply <code>.classname</code> (with period).</p>
<pre><code>By.css('.classname') // get by class name
By.css('input[type=radio]') // get input by type radio
By.css('.parent .child') // get child who has a parent
</code></pre>
<p>These are just some example. If you know css, then you should know how to use selectors. </p>
|
Printing the CONTENT of a nested hash map is mixing characters on the same line <p>I'm trying to print a hashtable content, that hashtable contains a map inside it, the table is declared just like this:</p>
<pre><code> Map<String, Map<String,Integer>> mapSD = new HashMap<String, Map<String, Integer>>();
</code></pre>
<p>I'm using the next line to print its content, that works for normal (not nested) hashmap, and it's doing something weird with this nested hashmap:</p>
<pre><code> System.out.println("\n"+mapSD.toString());
</code></pre>
<p><strong>EDIT:</strong> Just in case it isn't clear enough, I need to print the content in the "{A{BE=2,XD=5}}" way , the toString method do this in not nested maps or hashtables, it works in normal tables, but is overwritting the console output with this nested table.</p>
<p><strong>EDIT 2:</strong> The printing should print something like {A{RT=5,CS=3}}, that is, a table of tables. It prints it, but then prints another line over the same line, creating an unreadable mix of characters. I'm using Eclipse Mars.2 IDE, maybe there's something to do with the problem.</p>
<p>Any idea of how to fix this?
Thanks in advance.</p>
| <p>Solved, the problem was the buffer size of the console, that's why it mixed the characters at the same line, the bufer was being overwritted. Thanks for your answers!</p>
|
RavenDB: Search with whitespace, behaving like String.Contains <p><strong>TL;DR</strong> how to run exact equivalent of <code>.Where(x => x.Name.Contains(value))</code> query in RavenDB, even when <code>value</code> string contains spaces (whitecharacters)?</p>
<hr>
<p>We're querying RavenDB with LINQ. We want to query with <code>String.Contains</code>-like constraint. As the RavenDb prevents <code>.Where(x => x.Name.Contains(value))</code> queries, we're using <code>LinqExtensions.Search</code> extension method, following the examples in the documentation:
<code>
query = query.Search(t => t.Name, $"*{value}*",
escapeQueryOptions: EscapeQueryOptions.AllowAllWildcards,
options: SearchOptions.And);
</code></p>
<p>Unfortunately this doesn't work as expected when the search term contains the space character, most likely because of this: <a href="https://github.com/ravendb/ravendb/blob/f3b5f3a186d07776bf38bf9effab4d7d75d5c647/Raven.Client.Lightweight/Document/AbstractDocumentQuery.cs#L1759" rel="nofollow">https://github.com/ravendb/ravendb/blob/f3b5f3a186d07776bf38bf9effab4d7d75d5c647/Raven.Client.Lightweight/Document/AbstractDocumentQuery.cs#L1759</a></p>
<p>We've been trying manual space escaping, with no success so far:</p>
<p><code>
var value = RavenQuery.Escape(filter.NameContains).Replace(" ", @"\ ");<br>
query = query.Search(t => t.Name, $"*{value}*",
escapeQueryOptions: EscapeQueryOptions.AllowAllWildcards,
options: SearchOptions.And);
</code></p>
| <p>You need to set the <code>Index</code> option of the field to <code>Analyzed</code></p>
<pre><code>public class YourObject_ByName : AbstractIndexCreationTask<YourObject>
{
public YourObject_ByName()
{
Map = objs => objs .Select(x => new { x.Name });
Indexes.Add(x => x.Name, FieldIndexing.Analyzed);
}
}
</code></pre>
<p>And then you can query using <code>DocumentQuery</code>:</p>
<pre><code>session.Advanced.DocumentQuery<YourObject, YourObject_ByName>()
.Where("(Name: *term*)")
.ToList();
</code></pre>
|
Can not search mail on Exchange IMAP server by javamail api? <p>I can not search mail on Exchange(2013) IMAP server by Javamail API.
I have done a tcpdump found that javamailAPI send the command:
<code>"A5 SEARCH TO xxx@eyou.net all "</code>,exchange server return nothing.</p>
<p>I sent a command:
<code>"A5 SEARCH HEADER TO xxx@eyou.net all"</code>. then exchange server return all the matching messageã
What can I do ï¼
thanks verymuch</p>
| <p>Ya, Exchange is broken. You can use <a href="https://javamail.java.net/nonav/docs/api/javax/mail/search/HeaderTerm.html" rel="nofollow">HeaderTerm</a> instead.</p>
|
How to know if touch position is in a specific area - Android <p>I want to call a method if a specific area of screen (my <code>RelativeLayout</code>) has been tapped. I'm devveloping a <strong>tic-toc-toe</strong> game, I want to make the <code>alpha</code> value of every circle or cross in each tapped square.<br>
here is my <code>xml</code> file, every <code>ImageView</code> will become a circle or cross if became tapped: </p>
<pre><code><RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:background="#e4f7a6"
android:layout_above="@+id/buttonRed"
android:id="@+id/relativeLayout">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/board"
android:src="@drawable/board"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/Center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="@drawable/red"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/leftCenter"
android:src="@drawable/red"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:translationX="20dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/rightCenter"
android:src="@drawable/red"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:translationX="-20dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/upCenter"
android:src="@drawable/red"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:translationY="40dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/upLeft"
android:src="@drawable/red"
android:layout_alignParentLeft="true"
android:translationX="20dp"
android:translationY="40dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/upRight"
android:src="@drawable/red"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:translationY="40dp"
android:translationX="-20dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/downLeft"
android:src="@drawable/red"
android:translationY="-40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:translationX="20dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/downRight"
android:src="@drawable/red"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:translationY="-40dp"
android:translationX="-20dp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/downCenter"
android:src="@drawable/red"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:translationY="-40dp"
/>
</RelativeLayout>
</code></pre>
<p>I know how to get tapped point position with: </p>
<pre><code>Display display = getWindowManager().getDefaultDisplay();
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
return true;
}
</code></pre>
<p>So how should I get area of each square in <strong>tic toc toe</strong> board?</p>
| <p>apply on focus change listner to the imageview and do your code where the image view will get the focus like:- </p>
<pre><code>if(hasFocus){
// do your code
}else{
}
</code></pre>
|
Align text to the bottom of a div with inline-block <p>I'm having trouble aligning some text to the bottom of a div which as a display of inline-block.</p>
<p><a href="https://i.stack.imgur.com/Z19ga.png" rel="nofollow"><img src="https://i.stack.imgur.com/Z19ga.png" alt="Right Now it looks like this"></a></p>
<p>but i can't place the text "BackOffice" in the bottom right corner of the div...</p>
<p><a href="https://i.stack.imgur.com/de3sm.png" rel="nofollow"><img src="https://i.stack.imgur.com/de3sm.png" alt="The yellow square marks the spot"></a></p>
<p>I've tried to use vertical-align. i've used divs, inside of divs, inside of divs, ect., i've tried the table-cell too nothing really works.</p>
<p>Any ideias? (Yes i've read almost every single thread in this website and other forums, nothing really works.</p>
<p>Here's my code.
Thanks!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#firstBox, #secondBox, #thirdBox, #fourthBox, #fifthBox {
width: 20%;
height: 200px;
margin-left: auto;
margin-right: auto;
display: inline-block;
color: white;
}
#firstBox {
background: url(/images/black.jpg);
}
#secondBox {
background: url(/images/blue.png);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
<!-- Todos os elementos(divs) têm que estar preenchidos para não perder o formato de linha. -->
<div id="firstBox"><!--
--><div id="firstBox-content>"><a href="backoffice.php">Backoffice</a></div>
</div><!--
--><div id="secondBox"><a href="">Backoffice</a>
</div><!--
--><div id="thirdBox"><a href="">Backoffice</a>
</div><!--
--><div id="fourthBox"><a href="">Backoffice</a>
</div><!--
--><div id="fifthBox"><a href="">Backoffice</a>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>(The rest of the boxs are the same just except the background change)</p>
| <p><strong>Flexbox</strong> can do that:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.header {
display: flex;
}
#firstBox,
#secondBox,
#thirdBox,
#fourthBox,
#fifthBox {
width: 20%;
height: 200px;
display: flex;
align-items: flex-end;
justify-content: flex-end;
color: white;
border: 1px solid green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
<div id="firstBox">
<div id="firstBox-content>"><a href="backoffice.php">Backoffice</a>
</div>
</div>
<div id="secondBox"><a href="">Backoffice</a>
</div>
<div id="thirdBox"><a href="">Backoffice</a>
</div>
<div id="fourthBox"><a href="">Backoffice</a>
</div>
<div id="fifthBox"><a href="">Backoffice</a>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Or use <strong>CSS Tables</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.header {
display: table;
table-layout: fixed;
width: 100%;
}
#firstBox,
#secondBox,
#thirdBox,
#fourthBox,
#fifthBox {
width: 20%;
height: 200px;
display: table-cell;
color: white;
border: 1px solid green;
vertical-align: bottom;
text-align: right;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
<div id="firstBox">
<!--
-->
<div id="firstBox-content>"><a href="backoffice.php">Backoffice</a>
</div>
</div>
<!--
-->
<div id="secondBox"><a href="">Backoffice</a>
</div>
<!--
-->
<div id="thirdBox"><a href="">Backoffice</a>
</div>
<!--
-->
<div id="fourthBox"><a href="">Backoffice</a>
</div>
<!--
-->
<div id="fifthBox"><a href="">Backoffice</a>
</div>
</div></code></pre>
</div>
</div>
</p>
|
Word document to python-docx <p><strong>Objective:</strong>
I use a word template to which I want to pass paragraph values from python. </p>
<p><strong>Pipeline:</strong>
The pipeline involves using python-docx and sending output paragraph to python docx;thus, creating a docx file.</p>
<pre><code>from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
r = """sample paragraph"""
p = document.add_paragraph(r)
document.add_page_break()
document.save('Test.docx')
</code></pre>
<p><strong>Question:</strong></p>
<p>I already got a sample template that I want to use, is it possible to create a blue print of the template using python-docx and continue with the content blocking. By blue print, I mean the section header,footer,margin ,spacing to name a few,must be preserved or coded in pyton-docx format automatically. So that I can send sample paragraphs to the relevant section.</p>
<p>If I need to create a template using another one as base; I believe,I need to hard code the section,margin and style again in python-docx. Is there a way to circumnavigate this work path?</p>
| <p>I think the approach you'll find most useful is to define <strong>paragraph styles</strong> in your template document that embody the paragraph and character formatting for the different types of paragraphs you want (heading, body paragraph, etc.), and then apply the correct style to each paragraph as you add it.</p>
<blockquote>
<p><a href="http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html" rel="nofollow">http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html</a><br>
<a href="http://python-docx.readthedocs.io/en/latest/user/styles-using.html" rel="nofollow">http://python-docx.readthedocs.io/en/latest/user/styles-using.html</a></p>
</blockquote>
<p>You'll still need to write the document from "top" to "bottom". If the items don't arrive in sequence you'll probably want to keep them organized in a memory data structure until you have them all and then write the document from that data structure.</p>
<p>There are ways around this, but there's no notion of a "cursor" in python-docx (yet) where you can insert a paragraph at an arbitrary location.</p>
|
Delete line from grid in axapta <p>I'm quite new in Axapta and I didn't get how I can to delete selected line from grid, actually my problem is that I cant get selected line, so how should I do this?</p>
| <p>In your form you have a <code>Data source</code> node, here you have your <code>Data source</code> to use to display data in <strong>form</strong> in methods you have <code>Delete()</code> method. This method is called when you delete record. Also you can override this method.</p>
<p>If you press <strong>ALT + F9</strong> in one line you can delete this line. The method <code>Delete()</code> of <code>Data source</code> is called.</p>
<p>You can create a <code>CommandButton</code> to delete records in grid, in <code>Command property</code> set <code>Delete Register</code>. Also you can create a button and call the method <code>Delete()</code> of your <code>Data Source</code>.</p>
<p>In all cases the record of the selected line is deleted.</p>
|
Getting Junk Characters while reading AppName programmatically on Android <p>My Sample code to get the AppName.</p>
<pre><code>public static String getApplicationName(Context mContext) {
String applicationName = mContext.getResources().getString(R.string.app_name);
if (applicationName != null) {
return applicationName;
} else {
return applicationName;
}
}
</code></pre>
<p>values folder under res</p>
<pre><code><string name="app_name">Test App Name</string>
</code></pre>
<p>Note: some times, I am receiving Junk characters for AppName<br /></p>
<blockquote>
<p>Ex: à ¤¬à ¤¾à ¤°à ¤•à ¥‹Ã ¤¡ à ¤¸à ¥&#14</p>
</blockquote>
<p>Please help to come out from this problem.<br />
Thanks in advance.</p>
| <p>Why don't you tried the below code?</p>
<pre><code>int stringId = this.getApplicationInfo().labelRes;
String appName = this.getString(stringId);
Log.e(TAG, appName);
</code></pre>
|
Wrong time since.. from timestamp <p>I added timestamp to Firebase database formatted like: <code>1476700050.83933</code>. </p>
<p>So I wanted to calculate the time since this timestamp was created however as an output I get something like this: <code>1969-12-31 23:32:04 +0000</code>. </p>
<p>It sees somehow correct but how I am able to convert it now to like 5 minutes ago, etc.</p>
<p>I am doing my calculations like this:</p>
<pre><code>let timestamp = postsArray[indexPath.row].timestamp//query timestamp from Firebase
let date = NSDate(timeIntervalSince1970: timestamp! )//Readable date
let timeSincePost = (NSDate().timeIntervalSinceNow-NSDate().timeIntervalSince(date as Date))//Calculate time since
print("TimeSince", NSDate(timeIntervalSince1970: timeSincePost))
</code></pre>
<p>I went trough many similar questions in many languages but they are all so different. Am I doing it very wrong?</p>
| <p><code>NSDate().timeIntervalSinceNow</code> return value close to <code>0</code>.</p>
<p><code>NSDate()</code> â creates date with current timestamp, you can call it <code>now</code>.
<code>timeIntervalSinceNow</code> here will be difference between time of creating data and method call, miniscule value.</p>
<p>So this:</p>
<pre><code>NSDate().timeIntervalSinceNow-NSDate().timeIntervalSince(date as Date)
</code></pre>
<p>Can be seen like this:</p>
<pre><code>0 - now.timeIntervalSince(date as Date)
</code></pre>
<p>For all dates in past <code>now.timeIntervalSince(date as Date)</code> is positive, and <code>0 - positive = negative</code></p>
<p>And in the end you're subtracting time interval from January 1st, 1970 and get your date of 1969. Btw, why are you doing this?</p>
<p>Also, stop using <code>NSDate</code> in Swift 3, just use <code>Date</code>. </p>
<p>And use <a href="https://developer.apple.com/reference/foundation/nsdate/1410206-timeintervalsince" rel="nofollow"><code>this method</code></a> for <code>timeSincePost</code> calculation.</p>
<blockquote>
<p>how I am able to convert it now to like 5 minutes ago etc...</p>
</blockquote>
<p>Just use <code>DateFormatter</code> with <a href="https://developer.apple.com/reference/foundation/dateformatter/1415848-doesrelativedateformatting" rel="nofollow"><code>doesRelativeDateFormatting</code></a> set to true and get <code>stringFromDate</code> with original date you got with Firebird timestamp.</p>
|
Clearing chrome's cache on server side <p>I have big problem with chrome's cache.
I'm building system for my clients. All are build on angular so at the begining there is always one index.html file.
With new version I'm changing js scripts tag to ex. <code>scripts.2.1.1.js</code> in index.html file.
I have also:</p>
<pre><code><FilesMatch "\.(html)$">
Header set Cache-Control "max-age=1, public"
</FilesMatch>
</code></pre>
<p>in my htaccess file.</p>
<p>But chrome seems to ignore it.
Every time when I type in url address I have old version, but in source code I have tags to new scripts. When I press F5 it loads new version, but when I close browser's tab and type in url once again I have old version once again?</p>
<p>What's wrong? How to get rid of cache? I don't want a browser solution (clearing cache). I can't force my clients to do that. I want server-side solution. Is there any?</p>
<p><strong>Solution:</strong></p>
<pre><code><FilesMatch "\.(html|js|css)$">
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</FilesMatch>
</code></pre>
| <p>You could try to set "no-store" in the header:
<a href="http://stackoverflow.com/questions/866822/why-both-no-cache-and-no-store-should-be-used-in-http-response">Why both no-cache and no-store should be used in HTTP response?</a></p>
<p>But Implementing ETag headers is a more robust way to do so:</p>
<p><a href="https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching?hl=en" rel="nofollow">https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching?hl=en</a></p>
|
Java Bulk Import <p>Will java bulk import sub packages inside one package?</p>
<p>For example I have this directory:</p>
<pre><code>- PackageA
- PackageB
- anotherClass.java
- PackageC
- myClass.java
- app.java
- someClass.java
</code></pre>
<p>If I use this following java code will my classes "anotherClass" and "myClass" be available on my code?</p>
<pre><code>import PackageA.*
</code></pre>
<p>or do I have to use this code?</p>
<pre><code>import PackageA.*
import PackageA.PackageB.*
import PackageA.PackageC.*
</code></pre>
| <p>Two things here:</p>
<p>A) no, these imports are not "recursive"; you only import the classes from the specific package, not of its sub-packages</p>
<p>B) bulk imports are considered "bad style" by most coding style conventions and tools</p>
<p>(eclipse for example will automatically turn them into specific imports if you use <kbd>ctrl-shift-o</kbd> "organize imports")</p>
|
MySQL returns always Error <p>I have a check for max letters. If the check is not true the first time, its working. But if i have a insert with 200 characters or more it always returns <code>Message cant have more than 200 characters.</code> Even with 10 characters after the test return error. Can't see what I'm doing wrong. </p>
<pre><code><?php
$stripped = mysql_real_escape_string($_GET['id']);
$id = mysql_real_escape_string($_GET['id']);
$message = mysql_real_escape_string($_POST['message']);
$aktiv = mysql_real_escape_string($_POST['aktiv']);
if (isset($_POST['sendmsg'])) {
if ($_POST['message'] < 200) {
echo "Message can't be more than 200 characters";
} else {
$result = mysql_query("UPDATE cms_prosjekt SET message = '$message', active_msg = '$aktiv' WHERE id = $stripped;");
header('Location: Location: /index.php?url=projectedit&id='.$stripped.'&code='.$id.'');
exit;
}
}
?>
</code></pre>
| <p>This is not mysql error but your php validation error</p>
<p>1) More than 200 is <code>>200</code> not <code><200</code></p>
<p>2) You need to check length of text not text</p>
<pre><code>if (strlen($_POST['message']) > 200)
{
echo "Message can't be more than 200 characters";
}
</code></pre>
|
Split string by brackets <p>I am trying to split a string by brackets but my array has some extra empty values.</p>
<p>I tried using the code of a similar question that was answered and it splits the string but also adds empty values.</p>
<pre><code>// faq data
$faq = "SELECT * FROM `web_content` WHERE catid = 13 AND `alias` = '".$conn->real_escape_string($_GET['alias'])."' AND state = 1 ORDER BY ordering";
$faqcon = $conn->query($faq);
$faqcr = array();
while ($faqcr[] = $faqcon->fetch_array());
$faqtext = $faqcr[0]['introtext'];
$arr = preg_split('/\h*[][]/', $faqtext, -1, PREG_SPLIT_NO_EMPTY);
echo '<pre>';
print_r($arr);
echo '</pre>';
</code></pre>
<p>The output of the array is this:</p>
<pre><code>Array
(
[0] =>
[1] => Vraag1? || Antwoord1
[2] =>
[3] => Vraag2? || Antwoord2
[4] =>
[5] => Vraag3? || Antwoord3
[6] =>
)
</code></pre>
<p>My string looks like this:</p>
<pre><code><p>[Vraag1? || Antwoord1]</p>
<p>[Vraag2? || Antwoord2]</p>
<p>[Vraag3? || Antwoord3]</p>
</code></pre>
<p>The <code><p></code> tags are irrelevant, im not splitting on those and I can just use strip tags afterwards.</p>
<p>Output of answer:</p>
<pre><code> Array
(
[0] => Array
(
[0] => [Vraag1? || Antwoord1]
[1] => [Vraag2? || Antwoord2]
[2] => [Vraag3? || Antwoord3]
)
[1] => Array
(
[0] => Vraag1? || Antwoord1
[1] => Vraag2? || Antwoord2
[2] => Vraag3? || Antwoord3
)
)
</code></pre>
| <pre><code>$line = '[This] is a [test] string, I think [this] answers [your] question.';
preg_match_all("/\[([^\]]*)\]/", $line, $matches);
var_dump($matches[1]);
</code></pre>
|
does not want grouping symbol in google chart numbers <p>I am google chart to draw tables. I have a column of numbers but numbers are printed as "1,222,322" but i don't want grouping symbol(comma) between digits.
i tried</p>
<pre><code>var formatter = new google.visualization.NumberFormat({ groupingSymbol: ' '});
formatter.format(data, 1);
</code></pre>
<p>but it is not working</p>
| <p>seems to work fine here </p>
<p>make sure to format the column before drawing the chart </p>
<p>see following working snippet... </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>google.charts.load('current', {
callback: drawChart,
packages:['controls', 'table']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['date', 'count'],
[new Date('2016-09-29 06:47:47'), 1000001],
[new Date('2016-09-29 14:48:42'), 1222322],
[new Date('2016-10-29 06:47:47'), 3250805],
[new Date('2016-11-29 06:48:42'), 1110588],
]);
var formatter = new google.visualization.NumberFormat({
groupingSymbol: ' '
});
formatter.format(data, 1);
var table = new google.visualization.ChartWrapper({
chartType: 'Table',
containerId: 'table_div',
dataTable: data
});
table.draw();
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div"></div></code></pre>
</div>
</div>
</p>
|
How to get difference between current date and given date from cell in VBA? <p>I am new in VBA. I want to get the difference between current date and given date from user. How can I solve this? <a href="https://i.stack.imgur.com/kdV95.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/kdV95.jpg" alt="enter image description here"></a>When I click the Calculate point Button it showed #NAME? </p>
<p>Here is my code:</p>
<pre><code>Private Sub Sum_Click()
Dim LastRow As Long
LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Range("F6:F" & LastRow).Formula = "=DateDiff(""y"", Now, c6)"
End Sub
</code></pre>
| <p><code>Range("F6:F" & LastRow).Formula = "=Text(Now()-C6, "y")"</code> should do it. </p>
<p>Refer to the <a href="https://support.office.com/en-gb/article/TEXT-function-20d5ac4d-7b94-49fd-bb38-93d29371225c" rel="nofollow">text function</a> for other formatting options.</p>
<p>In particular:</p>
<p><a href="https://i.stack.imgur.com/b4ews.png" rel="nofollow"><img src="https://i.stack.imgur.com/b4ews.png" alt="Image from the supplied link to support.office.com"></a></p>
|
How to smooth lines in a figure in python? <p>So with the code below I can plot a figure with 3 lines, but they are angular. Is it possible to smooth the lines? </p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
# Dataframe consist of 3 columns
df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]
fig,ax = plt.subplots()
# plot figure to see how the weight develops through the years
for name in ['A','B','C']:
ax.plot(df[df.name==name].year,df[df.name==name].weight,label=name)
ax.set_xlabel("year")
ax.set_ylabel("weight")
ax.legend(loc='best')
</code></pre>
| <p>You should apply interpolation on your data and it shouldn't be "linear". Here I applied the "cubic" interpolation using scipy's <code>interp1d</code>. Also, note that for using cubic interpolation your data should have at least 4 points. So I added another year 2031 and another value too all weights (I got the new weight value by subtracting 1 from the last value of weights): </p>
<p>Here's the code: </p>
<pre><code>import matplotlib.pyplot as plt
import pandas as pd
from scipy.interpolate import interp1d
import numpy as np
# df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
# df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
# df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]
df1 = pd.DataFrame()
df1['Weight_A'] = [80, 65, 60 ,59]
df1['Weight_B'] = [65, 60, 55 ,54]
df1['Weight_C'] = [88, 70, 65 ,64]
df1.index = [2005,2015,2030,2031]
ax = df1.plot.line()
ax.set_title('Before interpolation')
ax.set_xlabel("year")
ax.set_ylabel("weight")
f1 = interp1d(df1.index, df1['Weight_A'],kind='cubic')
f2 = interp1d(df1.index, df1['Weight_B'],kind='cubic')
f3 = interp1d(df1.index, df1['Weight_C'],kind='cubic')
df2 = pd.DataFrame()
new_index = np.arange(2005,2031)
df2['Weight_A'] = f1(new_index)
df2['Weight_B'] = f2(new_index)
df2['Weight_C'] = f3(new_index)
df2.index = new_index
ax2 = df2.plot.line()
ax2.set_title('After interpolation')
ax2.set_xlabel("year")
ax2.set_ylabel("weight")
plt.show()
</code></pre>
<p>And the results: </p>
<p><a href="https://i.stack.imgur.com/QnDvl.png" rel="nofollow"><img src="https://i.stack.imgur.com/QnDvl.png" alt="Before interpolation"></a>
<a href="https://i.stack.imgur.com/aUJGs.png" rel="nofollow"><img src="https://i.stack.imgur.com/aUJGs.png" alt="After interpolation"></a></p>
|
Find pd.DataFrame cell that has the value of None <p>I have a <code>pd.DataFrame</code> that looks like this:</p>
<pre><code>index A B
0 apple bear
0 axis None
0 ant None
0 avocado None
</code></pre>
<p>and my goal is to simple drop those row if they have <code>None</code> in the B column.</p>
<p>I tried <code>df[df['B'] != None]</code> but pandas returns me the exact same DataFrame without deleting the rows. And <code>df[df['B'] == None]</code> gives only an empty DataFrame.</p>
<p>Is this the correct way of trying to match the None value? I am not sure what is going on but <code>test = None</code> and then <code>test == None</code> works fine (returns True). Any thoughts are appreciated!</p>
| <p>You could try this:</p>
<pre><code>df.dropna(subset=["B"])
</code></pre>
|
Tomcat server unavailable from JEE7 <p>I have created a gradle webapp project in IntelliJ.</p>
<p>I have set Tomcat 8.5.6 to execute the project.</p>
<p>In file <code>webapp/WEB_INF/web.xml</code> i have defined a servlet</p>
<pre><code><servlet-mapping>
<servlet>
<servlet-name>RestServlet</servlet-name>
<servlet-class>com.anatoli.customer.service.Home</servlet-class>
</servlet>
</servlet-mapping>
@ApplicationPath("rest")
public class Home extends Application {
}
</code></pre>
<p>And I have a simple java class to show something</p>
<pre><code>@Stateless
@Named
@Path("test")
public class Customer {
@GET @Path("text")
@Produces("text/plain")
public String getText() {
return "Hello World";
}
}
</code></pre>
<p>When I run the project, and try to call <a href="http://localhost:8080/rest/test/text" rel="nofollow">http://localhost:8080/rest/test/text</a> -> I receive 404</p>
<p>But if I run <a href="http://localhost:8080" rel="nofollow">http://localhost:8080</a>, then I can see the index.jsp that is in webapp-folder -> tomcat is running</p>
<p>I need to use Annotations in my JEE7 Project</p>
| <p>Tomcat is web container and not an application server. </p>
<p>So your:</p>
<ul>
<li><code>@Stateless</code> does nothing </li>
<li><code>@Named</code> does nothing as well </li>
<li><code>@ApplicationPath("rest")</code>/<code>@Path</code> does nothing unless you've provided a JAX-RS implementation either as apart of your app or in <code>catalina-home/lib</code> (but given your problem - you didn't)</li>
</ul>
<p>Have you considered trying out Apache TomEE ? It's Tomcat + JavaEE spec impl., so it should suit you better</p>
|
What is the most readable way to replace multiple strings with replacements in a string in postgresql. <p>My usecase is something like this :</p>
<pre><code>String = "INDIA CANADA ITALY",
String Post Repacement = "IN CA IT"
</code></pre>
<p>I'm looking for something like this : </p>
<pre><code>replaceMultiple(String, "INDIA", "IN", "CANADA", "CA", "ITALY", "IT")
</code></pre>
<p>I'm currently doing this by using nested replace, but it's not readable much, and if I want to add more replacements, I'll have nest it further more.</p>
<p>Can this be achieved by functions, like creating a temporary table in runtime with key-value pairs, and replace every key in string with value.
Or some other method? </p>
| <p>There are many ways to do it.</p>
<p>You could use temporary tables and <code>regexp_replace</code>, or you could use a JSON dictionary like this:</p>
<pre><code>SELECT string_agg(
COALESCE(
'{ "INDIA": "IN", "CANADA": "CA", "ITALY": "IT" }'::jsonb->>s,
s
),
' '
)
FROM regexp_split_to_table('INDIA CANADA ITALY', '\s') s;
</code></pre>
|
PHP regex pattern to extract string like [3,4,aAn] <p>With the following peace of code I want to extract values like <code>[3,6,AN]</code> from a given string:</p>
<pre><code>$custom='[4,100,A]@erric.com';
$regexIpAddress = '/\[\d{1,3}\,\d{1,3}\,[a|A|Aa|aA|aN|Na|AN|NA|ANa||AaN|NAa|NaA|aAN|aNA]\]/';
preg_match($regexIpAddress, $custom, $match);
var_dump($match);
</code></pre>
<p>I want to extract with the predefined regex pattern the value like <code>[2,4,A], [2,4,Aa], [20,5,AaN]</code>.
The regex pattern I used extracts only <code>[2,4,A] or [2,4,a]</code>.</p>
<p>Is there any solution to extract all possible values?</p>
| <p>Use the following regex pattern with <code>i</code>(case-insensitive modifier):</p>
<pre><code>$re = "/\[\d{1,3},\d{1,3},[an]{1,3}\]/i";
$matched = preg_match($re, "[20,5,AaN]");
print_r($matched); // 1
$matched = preg_match($re, "[2,5,1]");
print_r($matched); // 0
</code></pre>
|
No applicable action for totalSizeCap in logback spring boot logging <p>I am trying to limit maximum number of log files using "totalSizeCap" element from logback. I am using sprong boot application, so included logback as follows,</p>
<p>logback.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<include resource="log4j/logback-${spring.profiles.active}.xml"/>
</configuration>
</code></pre>
<p>log4j/logback-DEV.xml</p>
<pre><code>included>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
</Pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/tmp//log/log.out</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>/tmp/log/log_%d{yyyy-MM-dd}.%i.out</fileNamePattern>
<maxFileSize>10MB</maxFileSize>
<maxHistory>1</maxHistory>
<totalSizeCap>2MB</totalSizeCap>
</rollingPolicy>
<encoder>
<charset>UTF-8</charset>
<pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
<logger name="com.company" level="INFO" />
<logger name="org.springframework" level="ERROR" />
</included>
</code></pre>
<p><em>ERROR</em></p>
<pre><code>ERROR in ch.qos.logback.core.joran.spi.Interpreter@17:27 - no applicable action for [totalSizeCap], current ElementPath is [[configuration][appender][rollingPolicy][totalSizeCap]]
</code></pre>
<p>How I limit the log files?</p>
| <p>My guess is that the <code>logback.xml</code> isn't the right place to specify what you want. Instead you should be using the <code>logback-spring.xml</code> file. This is due to the fact that the Logback framework is loaded before the ApplicationContext (so that the context can log some initial things) then the context loads the <code>logback-spring.xml</code> to change the logback settings for the rest of the time the application is running. As such my guess is that the <code>${spring.profiles.active}</code> is not replaced with the active profile.</p>
<p>From the <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html" rel="nofollow">reference</a></p>
<blockquote>
<p>When possible we recommend that you use the <code>-spring</code> variants for your
logging configuration (for example <code>logback-spring.xml</code> rather than
<code>logback.xml</code>). If you use standard configuration locations, Spring
cannot completely control log initialization.</p>
</blockquote>
<p>Reading a bit further while answering this question there is a section specifically around <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html#boot-features-logback-extensions" rel="nofollow">Logback extensions</a>. It looks like you need to use <code><springProperty></code> element in the configuration to expose the property.</p>
<pre><code><springProperty scope="context" name="activeProfile" source="spring.profiles.active" defaultValue="DEV"/>
<include resource="log4j/logback-${activeProfile}.xml"/>
</code></pre>
|
Multiply the rows in ten columns, by the values in one column <p>I have the following data:</p>
<pre><code>ID <- c("CB1", "CB2","CB3")
size <- c(10, 40, 4)
Year.1 <- c(10, 6, 15)
Year.2 <- c(12, 7, 20)
Year.3 <- c(14, 8, 25)
data <- data.frame(ID, size, Year.1, Year.2, Year.3)
</code></pre>
<p>I want to multiply the values for all years, by the values in the 'size' column (I have ten years in my actual data frame). The data should end up looking like this. </p>
<pre><code>ID <- c("CB1", "CB2","CB3")
size <- c(10, 40, 4)
Year.1 <- c(100, 240, 60)
Year.2 <- c(120, 280, 80)
Year.3 <- c(140, 320, 100)
data <- data.frame(ID, size, Year.1, Year.2, Year.3)
</code></pre>
<p>Ideally, the new values will replace the existing values for each year, as I don't really want to add another ten columns to my data frame. </p>
| <p>Why not this simple in base R:</p>
<pre><code>yr <- grep("Year", names(data)) # finds year columns
data[,yr] <- data$size*data[,yr]
# ID size Year.1 Year.2 Year.3
#1 CB1 10 100 120 140
#2 CB2 40 240 280 320
#3 CB3 4 60 80 100
</code></pre>
|
How to get the selected row value in aspxgridview <p>I have a aspxgridview and use the popup edit form. In the gridview there is a column "Unitname". In the popup edit forms header I would like to show this Unit name of the currently edited row.</p>
<p>i am using StartRowEditing event is used to show this.</p>
<p>also I want to get the Unitname and it should stored into string.</p>
<p>How can I achieve this?</p>
| <p>The selected row values can be accessed both in the server-side code and in the browser.</p>
<p>To access selected values on the server side, use the <a href="https://documentation.devexpress.com/#AspNet/DevExpressWebASPxGridBase_GetSelectedFieldValuestopic" rel="nofollow">GetSelectedFieldValues</a> method of the ASPxGridView. It returns the list of values corresponding to field names passed as method parameters.</p>
<p>On the client side, the ASPxGridView is presented by the ASPxClientGridView component. It provides a similar method to obtain selected values: <a href="https://documentation.devexpress.com/#AspNet/DevExpressWebScriptsASPxClientGridView_GetSelectedFieldValuestopic" rel="nofollow">GetSelectedFieldValues</a>.</p>
|
How to Convert a String into a user defined object reference <pre><code>public class Country {
public static void main(String[] args) {
String country_name;
String capital;
String iso_numeric;
String iso2;
String iso3;
String[] name = new String[] {"united_state", "united_kingdom", "france", "germany", "canada"};
for(int i = 0; i < name.length; i++) {
Country name[i] = new Country();
}
}
}
</code></pre>
<p>Hi, I have the above code:</p>
<p>What I want to do is to automate the creation of the object references of Country class, so by the end I should have something looks like:</p>
<pre><code>Country united_state = new Country();
Country united_kingdom = new Country();
Country france = new Country();
Country germany = new Country();
Country canada = new Country();
</code></pre>
<p>However, I'm getting error at:
Country name[i] = new Country();</p>
<p>Thanks in advance for your time and help.</p>
| <p>You appear to want this: </p>
<pre><code>public class Country {
private final String name;
// Add these later
// private final String capital;
// private final String iso_numeric;
// private final String iso2;
// private final String iso3;
public Country(String name) {
this.name = name;
}
public String getName() { return this.name; }
}
</code></pre>
<p>Once you have this, you can do this:</p>
<pre><code> String[] name = new String[] {"united_state", "united_kingdom", "france", "germany", "canada"};
List<Country> countries = new ArrayList<Country>();
for(int i = 0; i < name.length; i++) {
countries.add(new Country(name[i]));
}
</code></pre>
|
Centre ImageView horizontally inside a TableViewCell <p>I am having a bit of a problem putting my image view in the middle of the cell.</p>
<p><strong>I have a tableView cell with:</strong>
a label which is left aligned
a UIImageView (which is to be in the middle of the screen but not overlap the AccessoryView or Accessory)
an optional AccessoryView or Accessory. </p>
<p><strong>I then have a header cell:</strong>
a label which is left aligned
a UIImageView (which is to be in the middle of the screen)</p>
<p>The problem is that i want all the images to be aligned Horizontally (including the header) but the AccessoryView/Accessory throws off my calculation. The image view is a ScaleAspectFit. Currently i have set the width to be the full width of the contentView. </p>
<p>Does anyone know roughly how I would accomplish this? I have read people say to put in an empty view into the cells that won't have an AccessoryView or Accessory but this doesnt help with the Header? others have hardcoded values?</p>
<p>Many Thanks </p>
| <p>Change imageView frame x origin after your cell layout subviews. Just add this to your cell definition. </p>
<pre><code>override func layoutSubviews() {
let screenWidth = UIScreen.main.bounds.width
let imageViewWidth = self.imageView?.frame.width
let imageViewOriginX = (screenWidth - imageViewWidth!) / 2
self.customImageView.frame.origin.x = imageViewOriginX
}
</code></pre>
|
Why z3c.RML ignores the pageSize Attribute of <template> <p>I am trying to get an A4-Landscape output file. The Document i am modifying is A4-Portrait, so i thought simple switch: <strong><em>pageSize="(21cm, 29.7cm)"</em></strong> to <strong><em>pageSize="(29.7cm, 21cm)"</em></strong>, but nothing happend.</p>
<p>I then fount an Attribute: <strong><em>rotation="90"</em></strong>. The Page on the Screen ist still A4-Portrait, but the content ist turned 90 degres around. On paper it woulde be fine, but on screen i have to turn my head by 90 degress, not very comfortable.</p>
<p>After this i tryed: <strong><em>pageSize="(10cm, 10cm)"</em></strong>, thought this should look terrible, but nothing changed.</p>
<p>Could it be possible, that the Size of the generated PDF-File is set in thePython-Code and not set by the RML-File?</p>
<p>This is the Python Code:</p>
<pre><code>#!venv/bin/python
# -*- coding: utf-8 -*-
from z3c.rml import pagetemplate
rmlPageTemplate = pagetemplate.RMLPageTemplateFile("test.rml")
open('test.pdf', 'wb').write(rmlPageTemplate())
</code></pre>
<p>My RML-File locks like:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE document SYSTEM "rml_1_0.dtd">
<document test.pdf">
<docinit>
...
</docinit>
<template pageSize="(10cm, 10cm)"
rotation="90"
leftMargin="2.5cm"
rightMargin="2.5cm"
topMargin="2.5cm"
bottomMargin="2.5cm"
showBoundary="1"
>
<pageTemplate id="main">
<frame id="first" x1="2.5cm" y1="2.5cm" width="24.7cm" height="16cm" showBoundary="1"/>
</pageTemplate>
</template>
<stylesheet>
...
</stylesheet>
<story>
...
</story>
</document>
</code></pre>
<p>Thank you very much.</p>
| <p><a href="https://github.com/zopefoundation/z3c.rml/blob/master/RML-DIFFERENCES.rst" rel="nofollow">https://github.com/zopefoundation/z3c.rml/blob/master/RML-DIFFERENCES.rst</a></p>
<p><strong>RML2PDF and z3c.rml Implementation Differences</strong></p>
<p>This document outlines the differences between ReportLab Inc.'s RML2PDF library and z3c.rml.</p>
<p><strong>Incompatibilies</strong></p>
<p>
<em>page<strong>S</strong>ize</em>: This is called page<strong>s</strong>ize in this implementation to match the API.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.