text:
Q: Child attribute from parent - access Given a function with parameter x of a parent class A and class B the child class which inherits from A, how is the proper way to access the attribute of x when it is a B object? The previous description is exampled below.
-- Edit --
class A {
}

class B : public A {
    public:
      int foo;
}

void bar(A foo_){
    cout << foo_.foo << endl;
}

int main(){
    // Previous code:
    // A a{};
    // bar(a);

    // Current code:
    B b{};  // @O'Neil: B b(); will lead to the most vexing parse problem
    bar(b);
}

-- Edit --
I thank sincerely for the help.

A: If you pass b into bar() without changing anything else, bar() can only access the A within its parameter, a problem known as Object Slicing.
The solution is to pass b into bar() either by reference or via a pointer, even though the parameter is of type A you can use a dynamic_cast<> to try and get back to the derived object.
Pass it in as follows:
bar(&b);

and rewrite bar like this:
void bar(A *foo_)
{
    B *foo_as_B = dynamic_cast<B *>(foo_);
    if (foo_as_B != nullptr)
    {
        cout << foo_as_B->foo << endl;
    }
}

Then it'll work.
dynamic_cast<> is capable of casting a pointer/reference to a superclass into a pointer/reference to a subclass, provided the superclass object actually was originally instantiated as the subclass.  It's actually a bit more complex than this, but just for getting started that will be sufficient.
In the pointer case, if the cast is OK, you get a valid pointer.  If the cast can't be done, the pointer version returns nullptr.  Hence the reason for checking it before using it.
Good defensive coding says you should always check pointers from unknown sources.  Even though you may believe that the cast will succeed and you may be right at the time you write bar(), in production code, it's entirely possible that some other programmer will come along two or three years later and add the following:
class C : public A
{
    ....
}

C c{};
bar(&c);

At which point your check for nullptr will save you from the demon of undefined behavior.
You can also do it with references, but the failure case here is different: it throws an exception, which you'd probably want to catch.
This question shows the details of this.
-- Edit --
In response to the notes about getting error C2683: 'dynamic_cast': 'A' is not a polymorphic type, this SO Question explains why.  The standard states that there must be at least one virtual function for dynamic_cast<> to work, that's what being polymorphic means.
I have never bumped into this because it's a reflex action now for me to make all destructors virtual in production code.  The issue of why you want to make destructors virtual is a whole separate topic which I am not going to dig into here.  Suffice it to say that it does have its advantages to do so.
All that said, the fix is to change class A as follows:
class A
{
public:
    virtual ~A() {}
};

A: According to this link, it should have been worked from a base to a derived pointer of polymorphic class and it does belongs to RTTI, but still stumbling on errors.

A: The final solution for the thread may be found here. Thanks for all the participants.


text:
Q: PIC18F various output voltage level How can I control voltage level on a specific pin in PIC18F? Let's say then I want to send about 0.6V to transistor base. But I cannot use a voltage divider. I need to control output voltage by my PIC18F (PIC18F2525).

A: You don't actually want to send 0.6V to the transistor base.  $V_{BE}$ will vary a good deal between various transistors, so you won't get a well defined current through the transistor if you set it to 0.6V.
The standard way to bias a transistor is by sending a small amount of current through it.  Let's assume you're working with a MMBT3904, and want to send 30mA through it.  Get the datasheet, and find the graph which relates $h_{FE}$* and $I_C$ (Line 2 is at $25^{\circ}{\rm C}$):

$h_{FE}$ is about 140, so you need to send $214\mbox{ }{\mu}A$ through the base:
$$\frac{I_C}{h_{FE}}=\frac{30\mbox{ mA}}{140}=214\mbox{ }{\mu}A$$
Note that this parameter isn't precisely defined (that's why they used a graph), is temperature dependent (that's why there are three lines in this figure), and varies with $V_{CE} (as indicated by Figure 3).  However, it varies a lot less than $V_{BE}$.
There are many circuits to perform the task of sending a small current through the base.  Basically, every way you can connect resistors to $V_{CC}$, GND, and $V_{EE} (if a negative supply is used) has a name.  Wikipedia has a good article, but my college course spent a good two weeks talking about these different modes, so don't be discouraged if you don't get it in the first pass. I'll explain the simplest circuit (fixed bias) here.
The schematic looks like this:

$R_L$ is your load; if you need to connect your load to ground, use a PNP and invert everything.
When you drive pin 5 into a low or high-impedance state, only a leakage current will flow through the collector.  According to the datasheet, this value is $I_{CBO}=50\mbox{ }nA$ with $V_{CB} = 30\mbox{ }V$.  When you drive it high (say, $3.3\rm V$), there is a voltage established across $R_B$ and the base-emitter junction of the transistor.  This is an N-P silicon junction, very similar to a diode.  It has a similar voltage characteristic - According to Figure 4 of the datasheet, it will be about $790\rm mV$, but that will vary as we've said before.  But $800\mbox{ }mV$ is close enough for our purposes.  We need to find the value of $R_B$ that gives a current of $30\mbox{ }mA$:
$$ I_C = h_{FE} * I_B = 140 * \frac{ 3.3\mbox{ }V - 0.8\mbox{ }V }{R_B} $$
$$ R_B = \frac{140 * ( 3.3\mbox{ }V - 0.8\mbox{ }V ) }{I_C} $$
$$ R_B = \frac{350}{I_C} \rightarrow 11.66\mbox{ }k\Omega $$
An $11\mbox{ }k\Omega$ 5%, 2%, or 1% resistor should do nicely!
* - $h_{FE}$ is roughly synonymous with $\beta$, so you may see both values in datasheets.  $h_{FE}$ usually refers to the quiescent/DC state of the transistor, while $\beta$ is used when working with small-signal/AC currents.  They both denote the ratio of base current to collector current.

A: Some PICs have built in low resolution DACs that you can use. Check the datasheet!

A: If you need to supply a digital signal to a transistor base of 0v or 0.6v, use a resistor.
If you want to provide an analogue output, you need to use an external DAC (Digital to Analogue Converter) (some PICs may provide these internally). You can make a simple DAC with a resistor ladder and several digital output pins. The more pins you use, the more bits of resolution you'll get.
If you want to control the brightness of an LED you can rapidly toggle a digital signal and modulate the width of your pulses. This is called PWM, Pulse Width Modulation. Because we humans cannot see the rapid pulses, we perceive them as a continuous analogue output.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove the screen dimming when is presented dialog? I want to be able to press the other buttons on my screen when open dialog.
Dialog menuDialog = new Dialog("Dialog Demo");
menuDialog.setTimeout(1000);
menuDialog.show(90, 90, 10, 10, true);

A: Whilst 'pheromix' is correct in associating an action to the pointerReleased region. You would also need to make setDisposeWhenPointerOutOfBounds(false) in the derived Dialog class.
You can also refer the detailed explanation here http://www.java.net/forum/topic/mobile-embedded/lwuit/how-remove-screen-dimming-when-presented-dialog-2

A: Don't use directly a Dialog but create a class which derives Dialog. Implement the pointerReleased method , assuming that the device is tactile , and test if the x and y params are contained inside the area delimited by the Buttons's coordinates :
if ( ( x >= btn.getAbsoluteX() && x <= btn.getAbsoluteX() + btn.getPreferredW() ) && ( y >= btn.getAbsoluteY() && y <= btn.getAbsoluteY() + btn.getPreferredH() ) )
   // execute the Buttons's action method
else
   super.pointerReleased(x,y);


text:
Q: C# Create user control without creating new project How do i create new user control with only create new files on current project (i mean we do not have to create new class library project)?

A: Right click on the current project and select "Add->New Item". Select "Visual C# Items" and then "User Control".


text:
Q: Email Field Validation I am using an email validation script for my form. I am trying to add a function that returns TRUE if the email field contains certain spammy domains, like "mail.ru" and others... Here's what I have, that's not working. Any help would be appreciated!
Also, any way to expand this to add multiple values to search the email input?
"Email" is the field name in my form.
Thanks, Nick
function DoCustomValidation() {
    var frm = document.forms["contactus"];
    if (frm.Email.value.includes("mail.ru")) {
        sfm_show_error_msg('Sorry, no spam allowed!');
        return false;
    } else {
        return true;
    }
}

A: It should be something like this
function DoCustomValidation() {
  var frm = document.forms["contactus"];
  var spams = ['mail.ru', 'something.ru']; //Keep spam sites in this array
  var i, token = frm.Email.value, hasSpam = false;

  for (i = 0; i < spams.length; i++) {
    if (token.includes(spams[i])) {
      hasSpam = true;
      break;
    }
  }

  if (hasSpam) {
    sfm_show_error_msg('Sorry, no spam allowed!');
  }

  return hasSpam;
}


text:
Q: Browserify change the order the dependencies are loaded The issue is Browserify loads bootstrap's javascript before loading jquery.
I have this in my package.json
"scripts": {
    "build": "browserify app/scripts/main.js -o app/scripts/bundle.js"
},

and I require  dependencies in my main.js file like this:
var $ = require('jquery');
var bootstrap = require('bootstrap-sass');
var value = require('./test.js');

after I run npm run build I get my bundle.js file in which bootstrap script is first and jquery is second. That leads to a $ is undefined error, and of course to bootstrap scripts not working as they depend on jquery.
So, why is Browserify loading the files in this manner and how can I change it?

A: Browserify will load your modules in order, but you have to pay attention to browser scripts which rely on the global scope to resolve their dependencies.
Bootstrap just references $ and expects it to resolve to jQuery, so try this jazz by leaking jQuery into the global scope:
var jquery = require('jquery');
global.$ = global.jQuery = jquery;

require('bootstrap-sass');


text:
Q: Create shapefile with images as attributes using JavaScript I want to make a feature in a react.js web application where I can export/download shapefiles from the dashboard. I have implemented shp-write which takes a GeoJSON input. It is working fine with textual data. I would like to add 3 attributes which should contain an image in the shapefile. I have saved the required Image in my local storage. There is no JavaScript NPM module to do so
My implementation
var shpwrite = require('shp-write');
var options = {
    folder: 'myshapes',
    types: {
        point: 'mypoints',
        polygon: 'mypolygons',
        line: 'mylines'
    }
}
// a GeoJSON input for features
shpwrite.download({
    type: 'FeatureCollection',
    features: [
        {
            type: 'Feature',
            geometry: {
                type: 'Point',
                coordinates: [0, 0]
            },
            properties: {
                name: 'Foo',
                image: 'C:\Users\DELL1\Downloads\Survey.png'
            }
        },
        {
            type: 'Feature',
            geometry: {
                type: 'Point',
                coordinates: [0, 10]
            },
            properties: {
                name: 'Bar',
                image: 'C:\Users\DELL1\Downloads\Survey.png'

            }
        }
    ]
}, options);

The Current output has image path as a text type field. It doesn't contain image.
My Expected output should contain the image itself.
What approach can I use in JavaScript to achieve this result.


text:
Q: Kotlin tries to cast a Double to an Int for no reason? Good day,
I am trying to make this code work:
fun <T: Comparable<T>> getExtreme(data: JSONArray, searchKeyword: String, compareValue: T, define: CompareOp): T {
    val tmpFun: (T, T) -> Boolean = when (define) {
        CompareOp.LESSER -> { a: T, b: T -> a < b }
        CompareOp.GREATER -> { a: T, b: T -> a > b }
    }

    var extremeAmount: T = compareValue

    for (hourlyIndex in 0 until data.length()) {
        val dataSet: JSONObject = data.getJSONObject(hourlyIndex)
        val hourlyUvi: T = dataSet.get(searchKeyword) as T
        Log.d("MATH FUNC", "$hourlyUvi")
        if (tmpFun(hourlyUvi, extremeAmount)) extremeAmount = hourlyUvi
    }
    return extremeAmount
}

But for some reason it always throws this exception:

I think what the error is, is that each time it reads a whole number it automatically converts it to an Int instead of staying with my specified T. This code works fine and pretty much flawlessly without this line:
if (tmpFun(hourlyUvi, extremeAmount)) extremeAmount = hourlyUvi
If that is the error, how do I enforce my T instead of its own definition, and why is it doing it, or does the error lie anywhere else?

A: There are several built-in type converters like jsonObj.getDouble(key) or jsonObj.getInt(key) which will appropriately handle conversions when the JSON input string is a numeric type like an integer and you want a different numeric type as an output (e.g. double).
However, using this with a generic output type T is not as straightforward. If you really need to use the generic, you can write a generic JSONObject to T converter. If the JSBONObject is not a numeric type or a string that can be parsed to a numeric type, the getX methods will throw.
Make sure the converter covers all the possible numeric types you want to use, or it will fall to the last case and return the test value. You have to pass in an object of type T for the type checking, even if it is unused.
fun <T> jsonObjToType(o: JSONObject, arg: String, test: T): T {
    return when(test) {
        is Double -> o.getDouble(arg) as T
        is Int -> o.getInt(arg) as T
        is Float -> o.getDouble(arg).toFloat() as T
        is Long -> o.getLong(arg) as T
        else -> test // will never hit this as long
                     // as all possible T types are covered above
    }
}

and use it in your function
val hourlyUvi: T = jsonObjToNumericType(dataSet, searchKeyword, extremeAmount)
if (tmpFun(hourlyUvi, extremeAmount)) extremeAmount = hourlyUvi

Note: when you use Int or Long types, if there are floating point values in the array they will be truncated to an integer value. In almost all cases it is probably better to just write this function for doubles rather than as a generic of T to appropriately handle all cases.


text:
Q: Ocultar "" PopUp usando Cookie Tenho um web site o qual exibe um vídeo de boas vindas, quero ocultar uma div o qual é um PopUp que criei o qual exibe o vídeo, quero ocultar esta div usando cookie para que ele não apareça novamente e não atrapalhe sempre que o usuário entrar. preciso ajuda com a logica e se possível algum exemplo de código que talvez funcione.
<div id="popup_this" class="popup">
<!-- O video vai aqui -->
</div>

Este é o código da div a qual não quero mostrar, toda a logica por trás do PopUp funciona mas exibir ele toda vez que o usuário entrar será chato.


text:
Q: Aligning bootstrap carousel controls middle vertical I am using a Bootstrap carousel and I would like to vertically center the chevron arrows I am using to slide back and forward in the carousel. Currently they are horizontally centered, but aligned to the top.
Code:

Header

Content

A: You can use this CSS to center them vertically and align 20px from left and right of your carousel.
.carousel .left > i,
.carousel .right > i {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
}
.carousel .right > i {
  left: auto;
  right: 20px;
}


text:
Q: Can I set a hashChange listener to an iFrame src? I'm wondering if I have a page, that contains multiple iFrames and if I'm communicating through modification of the iFrame src attribute, would it be possible to set a hashChange listener on the src attribute.
Of course this would have to be inside the iFrame code, but trying this:
  $(document).ready(function () {
    console.log(window);
    $(window).on('hashchange', function() {
      console.log("IFRAME HASH CHANGED");
    });
   });

Does not trigger anything.
Question:
Any idea if this is possible? If not, how else could it be done?
Thanks for inputs!

A: The code above is fine. You should have no issues setting a hashchange event listener on the iframe's window. The problem is that you are viewing the console for the parent window. For example, if you change your console.log to an alert, you will see that it is in fact working.
If you're using google chrome's developer tools, you can click on this drop-down to switch between which window context you are in:


text:
Q: increasing record time in android? I have  a frequency indicator sound recorder which record sound successfully but it record for only 4 seconds.I need more than 4 seconds to record the code is given below:
public class vr1 extends Activity
{

private static final int SAMPLE_RATE_IN_HZ = 8000;
private static final int RECORDER_BPP      = 16;
private static final int CHANNEL_CONFIG    = AudioFormat.CHANNEL_IN_MONO;
private static final int AUDIO_FORMAT      = AudioFormat.ENCODING_PCM_16BIT;
private static final int AUDIO_SOURCE      = MediaRecorder.AudioSource.MIC;
private static final String TAG            = "VoiceDetection";
private static final int MAX_VOL           = 600;
//private static final int MAX_VOL           = 15000;
private static final int MIN_VAL           = 0;
private static final int START_RECORD_FROM = 350;
private static final int CHECK_BLOCK_COUNT = 3;

private Thread onCreateThread     = null;
private AudioRecord audioRecorder = null;
private int minBufferSizeInBytes  = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.porec);

    TextView textView = (TextView)findViewById(R.id.textView3);
    Button button     = (Button)findViewById(R.id.button1);

    button.setVisibility( android.view.View.INVISIBLE );
    textView.setVisibility( android.view.View.VISIBLE );

    Start();
}

public void Start( )
{
    // Create Handler
    final Handler handler = new Handler() {

         @Override
         public void handleMessage(Message msg)
         {
             int value         = msg.what;
             ImageView picture = (ImageView) findViewById(R.id.imageView);

             int resID[] = {
                             R.drawable.image0001, R.drawable.image20, R.drawable.image40,
                             R.drawable.image60,   R.drawable.image80, R.drawable.image100
                           };

             for( int i=MIN_VAL, step = (MAX_VOL - MIN_VAL)/resID.length; i<resID.length; i++ ) {
                 if( value >= i*step && value <= i*step + step )
                     picture.setImageResource( resID[i] );
             }

             // Set image for maximum value.
             if( value >= MAX_VOL )
                 picture.setImageResource( R.drawable.image100 );
         }
    };

    // Text change handler
    final Handler changeTexthandler = new Handler() {

        @Override
        public void handleMessage(Message msg)
        {
            TextView textView = (TextView)findViewById(R.id.textView3);
            Button button     = (Button)findViewById(R.id.button1);

            switch( msg.what )
            {
                case 0:
                    textView.setText("Waiting");
                    button.setVisibility( android.view.View.INVISIBLE );
                    textView.setVisibility( android.view.View.VISIBLE );
                    break;
                case 1:
                    textView.setText("Recording");
                    button.setVisibility( android.view.View.INVISIBLE );
                    textView.setVisibility( android.view.View.VISIBLE );
                    break;
                default:
                    button.setVisibility( android.view.View.VISIBLE );
                    textView.setVisibility( android.view.View.INVISIBLE );
                    break;

            }

        }

    };

    // Initialize minimum buffer size in bytes.
    minBufferSizeInBytes = AudioRecord.getMinBufferSize( SAMPLE_RATE_IN_HZ,
                                                         CHANNEL_CONFIG,
                                                         AUDIO_FORMAT
                                                        );

    if( minBufferSizeInBytes == AudioRecord.ERROR_BAD_VALUE )
        Log.e( TAG, "Bad Value for \"minBufferSize\", recording parameters are not supported by the hardware" );

    if( minBufferSizeInBytes == AudioRecord.ERROR )
        Log.e( TAG, "Bad Value for \"minBufferSize\", implementation was unable to query the hardware for its output properties" );

    // Initialize Audio Recorder.
    try {
        audioRecorder = new AudioRecord( AUDIO_SOURCE,
                                         SAMPLE_RATE_IN_HZ,
                                         CHANNEL_CONFIG,
                                         AUDIO_FORMAT,
                                         minBufferSizeInBytes
                                        );
    }
    catch(IllegalArgumentException ex) {
        Log.e( TAG, "Illegal Arguments: " + ex.getMessage() );
    }

    // Launch Thread.
    onCreateThread = new Thread( new Runnable() {

        @Override
        public void run()
        {
            // Starts recording from the AudioRecord instance.
            audioRecorder.startRecording();

            int numberOfBytesRead  = 0;
            byte audioBuffer[]     = new byte[minBufferSizeInBytes];
            float tempBuffer[]     = new float[CHECK_BLOCK_COUNT];
            int tempIndex          = 0;
            boolean isRecording    = false;
            int totalReadBytes     = 0;
            byte totalByteBuffer[] = new byte[60 * 44100 * 2];

            // While data coming from microphone.
            while( true )
            {
                float totalAbsValue = 0.0f;
                short sample        = 0;
                numberOfBytesRead   = audioRecorder.read( audioBuffer, 0, minBufferSizeInBytes );

                // Analyze income sound.
                for( int i=0; i<minBufferSizeInBytes; i+=2 ) {
                    sample = (short)( (audioBuffer[i]) | audioBuffer[i + 1] << 8 );
                    totalAbsValue += Math.abs( sample ) / (numberOfBytesRead/2);
                }

                // Set Animation of microphone.
                handler.sendEmptyMessage((int)totalAbsValue);

                // Analyze tempBuffer.
                tempBuffer[tempIndex%CHECK_BLOCK_COUNT] = totalAbsValue;
                float tempBufferTotalCount              = 0.0f;
                for( int i=0; i<CHECK_BLOCK_COUNT; ++i )
                    tempBufferTotalCount += tempBuffer[i];

                // Finalize value.
                tempBufferTotalCount = tempBufferTotalCount/CHECK_BLOCK_COUNT;

                // Waiting for load speak to start recording.
                if( (tempBufferTotalCount >=0 && tempBufferTotalCount <= START_RECORD_FROM) && !isRecording )
                {
                    Log.i("TAG", "Waiting for voice to start record.");
                    tempIndex++;
                    changeTexthandler.sendEmptyMessage(0);
                    continue;
                }

                if( tempBufferTotalCount > START_RECORD_FROM && !isRecording )
                {
                    Log.i("TAG", "Recording");
                    changeTexthandler.sendEmptyMessage(1);
                    isRecording = true;
                }

                // Stop Recording and save data to file.
                if( (tempBufferTotalCount >= 0 && tempBufferTotalCount <= START_RECORD_FROM) && isRecording )
                {
                    Log.i("TAG", "Stop Recording and Save data to file");
                    changeTexthandler.sendEmptyMessage(2);

                    audioRecorder.stop();
                    audioRecorder.release();
                    audioRecorder = null;

                    SaveDataToFile( totalReadBytes, totalByteBuffer );
                    totalReadBytes = 0;

                    tempIndex++;
                    break;
                }

                // Record Sound.
                for( int i=0; i<numberOfBytesRead; i++ )
                    totalByteBuffer[totalReadBytes + i] = audioBuffer[i];

                totalReadBytes += numberOfBytesRead;
                tempIndex++;
            }

        }

    }, "Voice Detection Thread" );

    // Run the Thread.
    onCreateThread.start();
    //*/
}

public void SaveDataToFile( int totalReadBytes, byte[] totalByteBuffer )
{
    // Save audio to file.
    String filepath = Environment.getExternalStorageDirectory().getPath();
    File file = new File( filepath, "VioceDetectionDemo" );
    if( !file.exists( ) )
        file.mkdirs();

    // String fileName = file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".wav";
    // File always saved by same name.
    String fileName = file.getAbsolutePath() + "/" + "VoiceDetectionDemo" + ".wav";

    long totalAudioLen  = 0;
    long totalDataLen   = totalAudioLen + 36;
    long longSampleRate = SAMPLE_RATE_IN_HZ;
    int channels        = 1;
    long byteRate       = RECORDER_BPP * SAMPLE_RATE_IN_HZ * channels/8;
    totalAudioLen       = totalReadBytes;
    totalDataLen        = totalAudioLen + 36;
    byte finalBuffer[]  = new byte[totalReadBytes + 44];

    finalBuffer[0]  = 'R';  // RIFF/WAVE header
    finalBuffer[1]  = 'I';
    finalBuffer[2]  = 'F';
    finalBuffer[3]  = 'F';
    finalBuffer[4]  = (byte) (totalDataLen & 0xff);
    finalBuffer[5]  = (byte) ((totalDataLen >> 8) & 0xff);
    finalBuffer[6]  = (byte) ((totalDataLen >> 16) & 0xff);
    finalBuffer[7]  = (byte) ((totalDataLen >> 24) & 0xff);
    finalBuffer[8]  = 'W';
    finalBuffer[9]  = 'A';
    finalBuffer[10] = 'V';
    finalBuffer[11] = 'E';
    finalBuffer[12] = 'f';  // 'fmt ' chunk
    finalBuffer[13] = 'm';
    finalBuffer[14] = 't';
    finalBuffer[15] = ' ';
    finalBuffer[16] = 16;  // 4 bytes: size of 'fmt ' chunk
    finalBuffer[17] = 0;
    finalBuffer[18] = 0;
    finalBuffer[19] = 0;
    finalBuffer[20] = 1;  // format = 1
    finalBuffer[21] = 0;
    finalBuffer[22] = (byte) channels;
    finalBuffer[23] = 0;
    finalBuffer[24] = (byte) (longSampleRate & 0xff);
    finalBuffer[25] = (byte) ((longSampleRate >> 8) & 0xff);
    finalBuffer[26] = (byte) ((longSampleRate >> 16) & 0xff);
    finalBuffer[27] = (byte) ((longSampleRate >> 24) & 0xff);
    finalBuffer[28] = (byte) (byteRate & 0xff);
    finalBuffer[29] = (byte) ((byteRate >> 8) & 0xff);
    finalBuffer[30] = (byte) ((byteRate >> 16) & 0xff);
    finalBuffer[31] = (byte) ((byteRate >> 24) & 0xff);
    finalBuffer[32] = (byte) (2 * 16 / 8);  // block align
    finalBuffer[33] = 0;
    finalBuffer[34] = RECORDER_BPP;  // bits per sample
    finalBuffer[35] = 0;
    finalBuffer[36] = 'd';
    finalBuffer[37] = 'a';
    finalBuffer[38] = 't';
    finalBuffer[39] = 'a';
    finalBuffer[40] = (byte) (totalAudioLen & 0xff);
    finalBuffer[41] = (byte) ((totalAudioLen >> 8) & 0xff);
    finalBuffer[42] = (byte) ((totalAudioLen >> 16) & 0xff);
    finalBuffer[43] = (byte) ((totalAudioLen >> 24) & 0xff);

    for( int i=0; i<totalReadBytes; ++i )
        finalBuffer[44+i] = totalByteBuffer[i];

    FileOutputStream out;
    try {
        out = new FileOutputStream(fileName);
         try {
                out.write(finalBuffer);
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

public void OnClickButtonTryAgain(View view)
{
    Start();
}
}


text:
Q: __syncthreads not working in CUDA I wrote simple kernel to test functionality of CUDA __syncthreads. In kernel I've managed to print from each thread if updated value is not visible to other threads. Ideally  no thread should print Not visible to me error message but some threads end up printing this message.
Here is the kernel.
__device__ int a=0;
__global__ void kernel()
{

    isItOK=false;
    if(threadIdx.x==0 && blockIdx.x==0)
    {
        atomicAdd(&a,1);
        __threadfence();
    }
    __syncthreads();
    if(atomicAdd(&a,0)==0)
    {
        cuPrintf("Not Visible to me\n");
    }

}
int main()
{
    int *a;
    cudaPrintfInit();
    kernel<<<16,16>>>();
    cudaPrintfDisplay(stdout,true);
    cudaPrintfEnd();
}

Please help me with this, very simple test program but still not working. Do we need some compiler flags to set ?

A: __syncthreads() is a synchronization barrier primitive that only synchronizes threads in the same block.
CUDA has no mechanism for safely synchronizing across thread blocks.
Communication and synchronization between thread blocks is not recommended because it breaks scalability of execution across GPUs with varying numbers of multiprocessors, which is the reason for having thread blocks in the first place.


text:
Q: Finding Linear transformation, that transforms original point in addition to consecutive images . Original Question
I have inferred from the question that a linear transformation T, originally transforming point (1,3), also transforms its image(-2,-3) in adittion to the image following that(2,4). However when attempting to find the matrix trasnforming (1,3) to (-2,-3), i found it was inconsistant with that which transformed (-2,-3) to (2,4). So i am led to conclude thati have not understood the question correctly.
Attempted Working: T(X) = X' .  T=$\begin{bmatrix}a & b\\c & d\end{bmatrix}$
$\begin{bmatrix}a & b\\c & d\end{bmatrix}$·$\begin{bmatrix}1\\3\end{bmatrix}$ = $\begin{bmatrix}a +3b\\c+3d\end{bmatrix}$ $=>$ $a+3b = -2$ & $c+3d=-3$
$\begin{bmatrix}a & b\\c & d\end{bmatrix}$·$\begin{bmatrix}-2\\-3\end{bmatrix}$ = $\begin{bmatrix}-2a -3b\\-2c-3d\end{bmatrix}$ $=>$ $-2a-3b = 2$ & $-2c-3d=4$
$\begin{bmatrix}a & b\\c & d\end{bmatrix}$·$\begin{bmatrix}2\\4\end{bmatrix}$ = $\begin{bmatrix}2a +4b\\2c+4d\end{bmatrix}$ $=>$ $2a+4b = -3$ & $2c+4d=-11$
There shouldn't be any x or y values that satisfy all 3 or else an equation is redundant according to https://www.physicsforums.com/threads/three-equations-two-unknowns.426629/
, so i'm just wondering how i'm interpreting it wrong. The answer is  1/2$\begin{bmatrix}-1 & -1\\-21 & 5\end{bmatrix}$ according to my textbook.

A: It seems there is a typo in the text, it should be
$$\begin{bmatrix}a & b\\c & d\end{bmatrix} \begin{bmatrix}1\\3\end{bmatrix}=\begin{bmatrix}-2\\-3\end{bmatrix}$$
$$\begin{bmatrix}a & b\\c & d\end{bmatrix} \begin{bmatrix}2\\4\end{bmatrix}=\begin{bmatrix}-3\\-11\end{bmatrix}$$
which can be solved to obtain the answer.

A: You're right. There is no such linear transformation: $(2,4)^T = \frac23(1,3)^T-\frac23(-2,-3)^T$, but $(-3,-11)^T \ne \frac23(-2,-3)-\frac23(2,4)$. The textbook answer doesn't match the problem as stated, either, since it doesn't map $(-2,-3)^T$ to $(2,4)^T$.
Looks like there's a typo in the problem itself. If you change it to "... and the point $(2,4)$..." the given solution works and is easily computed as $$\begin{bmatrix}-2&-3\\-3&-11\end{bmatrix} \begin{bmatrix}1&2\\3&4\end{bmatrix}^{-1}.$$


text:
Q: ansible file to deploy a particular version of elastic search I am trying to convert my docker-compose.yml which deploy elastic search to  an ansible.yml file to deploy a elastic search server.
docker-compose.yml
# Run both the app and Elasticsearch inside Docker containers.
version: '3'

services:

  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.2.0
    container_name: es01
    environment:
      - node.name=es01
      - cluster.initial_master_nodes=es01
      - cluster.name=docker-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - esdata01:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
    networks:
      - esnet

volumes:
  esdata01:
    driver: local

networks:
  esnet:

I converted the above docker-comps file as below but it did not throw any error but never deploy an elastic search.
ansible.yml
---
- hosts: localhost
  tasks:
    - name: "Elasticsearch"
      docker_container:
        name: "es01"
        image: docker.elastic.co/elasticsearch/elasticsearch:7.2.0
        ports:
          - "9200:9200"
        volumes:
          - "sdata01:/usr/share/elasticsearch/data"
        env:
          node.name: es01
          cluster.initial_master_nodes: es01
          cluster.name: docker-cluster
          bootstrap.memory_lock: "true"

I checked the  official elastic search ansible page (https://github.com/elastic/ansible-elasticsearch/blob/master/README.md) and I am having a difficulty to understand it.
Could someone please  advice why my ansible.yml is not able to deploy elastic search

A: I couldn't replicate your error even though I found some things in your playbook that could create problems:

*

*You are using localhost as your host value, but you are not setting your connection method to local. As the docs says:

This connection plugin allows ansible to execute tasks on the Ansible 'controller' instead of on a remote host.

*You are not escaping the dots . of the env dictionary keys.

Nonetheless, the playbook either runs or not, which is not your behavior.
Here is my playbook:
- name: Elasticsearch
  hosts: local
  connection: local
  gather_facts: no
  vars:
    project_name: es
    es_version: '7.2.0'
  tasks:
    - name: Docker Network
      docker_network:
        state: 'present'
        name: '{{ project_name }}_network'

    - name: ES 01 Docker Volume
      docker_volume:
        state: 'present'
        name: '{{ project_name }}_volume_01'

    - name: "Elasticsearch Docker Container"
      docker_container:
        name: "{{ project_name }}_01"
        state: started
        image: 'docker.elastic.co/elasticsearch/elasticsearch:{{ es_version }}'
        ports:
          - "9200:9200"
        ulimits:
          - 'memlock:-1:-1'
        volumes:
          - "{{ project_name }}_volume_01:/usr/share/elasticsearch/data"
        env:
          node.name: es01
          cluster.initial_master_nodes: es01
          cluster.name: docker-cluster
          bootstrap.memory_lock: 'true'
          'ES_JAVA_OPTS': '-Xms512m -Xmx512m'

And here is my hosts.yml file:
all:
  children:
    local:
      hosts:
        localhost:

I have also added a variable called es_version which you can override to install the Elastisearch version you like.
I hope it helps.


text:
Q: Why IE 9 not supporting JavaScript function? I'm trying to make a function for checking file size and extension on run time, I have done it  and working properly on all browser except ie 9. Can anyone let me know where the problem?
Javascript
<script type='text/javascript'>
function showFileSize() {
    var input, file;

    // (Can't use `typeof FileReader === "function"` because apparently
    // it comes back as "object" on some browsers. So just see if it's there
    // at all.)
    if (!window.FileReader) {
        bodyAppend("p", "The file API isn't supported on this browser yet.");
        return;
    }

    input = document.getElementById('fileinput');

   if (!input.files[0]) {
        bodyAppend("p", "Please select a file before clicking 'Load'");
    }
    else {
        file = input.files[0];
        var sFileName = file.name;
        var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();

        bodyAppend("p", "File Type " + sFileExtension + " is " + file.size + " bytes in size");
    }
}

function bodyAppend(tagName, innerHTML) {
    var elm;

    elm = document.createElement(tagName);
    elm.innerHTML = innerHTML;
    document.body.appendChild(elm);
}
</script>

HTML
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Save' onclick='showFileSize();'>
</form>

A: IE9 does not support HTML5 File API, including FileReader() ..
A possible workaround would be to polyfill, the solution below uses Flash to provide access to the filesystem on browsers that don't support the File APIs (IE and Safari), but it does not support drag-n-drop.

*

*Link here

*Reference on why FileReader does not work for IE9

A: Instead, clone the input, place the clone where the original is, and move the original into a hidden form. You might have to use an iframe for this.
This would certainly work but involves some coding.


text:
Q: Response Time (exclude lunch-break, weekends, holidays) I have two date fields with times. I want to calculate the response time of mins between Start and Finish excluding lunch breaks, weekends, and holidays.
I found the formula to exclude weekends, and holidays but how to exclude lunch also
Working hour start 9:00
End: 17:30
Response time (SLA) =
VAR _M =
    CALCULATE (
        COUNTROWS ( 'Date' ),
        DATESBETWEEN ( 'Date'[Date], 'Table'[StartDate] + 1, 'Table'[ClosedDate] - 1 ),
        'Date'[Weekday1] <> 6
            && 'Date'[Weekday1] <> 7,
        ALL ( 'Table' )
    ) * 7.5 * 60
VAR _S =
    IF (
        WEEKDAY ( 'Table'[StartDate], 2 ) IN { 6, 7 },
        0,
        IF (
            HOUR ( 'Table'[StartDate] ) < 9,
            7.5 * 60,
            DATEDIFF (
                'Table'[StartDate],
                DATE ( YEAR ( 'Table'[StartDate] ), MONTH ( 'Table'[StartDate] ), DAY ( 'Table'[StartDate] ) )
                    + TIME ( 17, 00, 00 ),
                MINUTE
            )
        )
    )
VAR _C =
    IF (
        WEEKDAY ( 'Table'[ClosedDate], 2 ) IN { 6, 7 },
        0,
        IF (
            HOUR ( 'Table'[ClosedDate] ) >= 17,
            7.5,
            DATEDIFF (
                DATE ( YEAR ( 'Table'[ClosedDate] ), MONTH ( 'Table'[ClosedDate] ), DAY ( 'Table'[ClosedDate] ) )
                    + TIME ( 9, 00, 00 ),
                'Table'[ClosedDate],
                MINUTE
            )
        )
    )
VAR _Minute =
    IF (
        ISBLANK ( 'Table'[ClosedDate] ),
        BLANK (),
        _M
            + IF (
                EDATE ( 'Table'[StartDate], 0 ) = EDATE ( 'Table'[ClosedDate], 0 )
                    && NOT ( WEEKDAY ( 'Table'[StartDate], 2 ) IN { 6, 7 } ),
                DATEDIFF ( 'Table'[StartDate], 'Table'[ClosedDate], MINUTE ),
                _S + _C
            )
    )
RETURN
    IF ( _Minute = BLANK (), BLANK (), _Minute )

Lunch Hour 13:00 to 14:00
25-10-22 10:02  31-10-22 16:58
31-10-22 14:40  31-10-22 16:48
31-10-22 12:17  31-10-22 16:50
31-10-22 15:03  31-10-22 17:00
31-10-22 15:45  31-10-22 16:44
31-10-22 14:19  31-10-22 16:44


text:
Q: Kubernetes on AWS with kube-up.sh no logs I'm setting up a cluster using kube-up.sh (v1.3.4) with AWS as provider. Everything is good, my only issue is that I don't see my logs (in Kibana and Elsaticsearch). If I docker attach inside the fluentd-elasticsearch container here is what I have:
in /var/logs/containers I see a symlink to a log file for every pods running on my node, for example:
elasticsearch-logging-v1-9lwly_kube-system_POD-3bb54515d4e0e479c39cb7c35aa6675fdfe2970233e095420e2116c2f633ab50.log
is a symlink to
/mnt/ephemeral/docker/containers/3bb54515d4e0e479c39cb7c35aa6675fdfe2970233e095420e2116c2f633ab50/3bb54515d4e0e479c39cb7c35aa6675fdfe2970233e095420e2116c2f633ab50-json.log
However, /mnt is empty in my fluentd-elasticsearch container. So all symlinks are wrong.
I guess it's just that /mnt/ephemeral is not bind mounted in the fluentd-elasticsearch container. I'm not advanced enough in kubernetes to know where to fix that, and might be a bug since I used the standard procedure to setup my cluster.
If I run kubectl describe on the pod I get:
Name:       fluentd-elasticsearch-ip-172-20-0-168.eu-west-1.compute.internal
Namespace:  kube-system
Node:       ip-172-20-0-168.eu-west-1.compute.internal/172.20.0.168
Start Time: Fri, 02 Sep 2016 17:15:03 +0200
Labels:     k8s-app=fluentd-logging
Status:     Running
IP:     10.244.3.2
Controllers:    <none>
Containers:
  fluentd-elasticsearch:
    Container ID:   docker://d376a900ef770e65dfbf75bf5bc1c711c650868bb4e4ea74002818852a81aa04
    Image:      gcr.io/google_containers/fluentd-elasticsearch:1.17
    Image ID:       docker://sha256:e74f564e4c316e0f6baebf838015f516e26d7501c96ead5f115523ff80c614fd
    Port:
    Limits:
      memory:   200Mi
    Requests:
      cpu:          100m
      memory:           200Mi
    State:          Running
      Started:          Fri, 02 Sep 2016 17:15:36 +0200
    Ready:          True
    Restart Count:      0
    Environment Variables:  <none>
Conditions:
  Type      Status
  Initialized   True
  Ready     True
  PodScheduled  True
Volumes:
  varlog:
    Type:   HostPath (bare host directory volume)
    Path:   /var/log
  varlibdockercontainers:
    Type:   HostPath (bare host directory volume)
    Path:   /var/lib/docker/containers
QoS Tier:   Burstable
No events.

So obviously volumes are wrong (/var/lib/docker/containers instead of /mnt/ephemeral/docker/containers.
Where / how can I fix this ? Should this be reported as a bug in k8s repos ?

A: I am using the cluster addon for a rackspace setup, not a aws one. But basiaclly you need to look for the kubernetes deployment file. In the rackspace case you need a daemon set, not a replication controller, I bet the AWS stuff is constructed the same way.
You need to add to the deployment yaml file:
containers:
        ...
        volumeMounts:
        - name: mntephemeraldockercontainers
          mountPath: /mnt/ephemeral/docker/containers
          readOnly: true
        ...
        volumes:
        - name: mntephemeraldockercontainers
          hostPath:
              path: /mnt/ephemeral/docker/containers

Why? Fluentd inside the pod read the path /var/log/containers/* which is a symlink that points to a "deak end" inside the container, because /mnt/ephemeral/docker/containers is not mounted there. It only exists on the host. So, mounting it in will make fluentd able to read the file.
NB: You need probably want to make the kubernetes metadata plugin work correctly, too.
rgds,
j


text:
Q: Can a boundary between bounded and unbounded solutions of a differential equation have a shape of a fractal? Iterative maps (like $z_{n+1}=z_n^2+c$, where $z\in  \mathbb{C}$, $z_0=c$) sometimes have a fractal-like boundary between bounded and unbounded sequences (Mandelbrot set). Are there differential equations that have a similar property of the fractal boundary between bounded and unbounded solutions?
I have tried to build the analogue of the Mandelbrot fractal with a differential equation,
$$z+z'+\frac{1}{2!} z''+\frac{1}{3!} z'''+ \frac{1}{4!}z''''=z^2+c$$ with initial conditions $z(0)=c$, $z'(0)=z^2+c-z$, $z''(0)=z'''(0)=0$. The result looks the following (color of each pixel corresponds to the time $t$ when $|z(t)|=100$ for the first time; Calculations were performed for $t<300$):

Even though the plot may seem to resemble Mandelbrot fractal, with a closer look the boundary appears fairly smooth:

Do all boundaries between bounded and unbounded solutions for differential equation look this simple (meaning, they are not fractals)?


text:
Q: Pandas loop through sheets without sheet name I have a couple of excel files with different sheet names
Was wondering if its possible to iterate through all of the sheet names without giving a variable "sheetname"
Right now it is through input selection.. I have tried to search before posting but haven't found or figured out how to work this out, help is appreciated.
import pandas as pd
# Look for sheet names
    file = file_name
    df = pd.ExcelFile(file).sheet_names

    # Filter sheets
    counter = 0
    sheets = [""]
    for sheet in df:
        if sheet[0] == "Δ" or sheet == "Log Data":
            pass
        else:
            counter += 1
            sheets.append(sheet)
            print(f"{sheets[counter]} - {counter}")

    # Sheet selection
    try:
        x = int(input("Select Sheet Number: "))
        assert x in range(1, counter + 1), "Select a value from list"
    except ValueError as err:
        logger.error(err)
        raise
    else:
        df = pd.read_excel(f"{file}", f"{sheets[x]}")
    finally:
        print(f"{sheets[x]} Selected")


text:
Q: Preventing process context switching on Android Now this may seem a bit extreme. I am curious if there would be a way to prevent an application's process from being pre-empted by the Android OS. I have time critical testing in C++ which can varying in results depending if the OS gives the context to another process, which in this case are native processes outside my control.
Is there a way to guarantee process control for at least a given period of time? (such as specifically defining the processes time slice) I've stumbled upon some  documentation  which hints at control over the dynamic priority of background process but I'm not sure if this is a guaranteed and/or safe way of doing this since I'd be overriding defines within threads.h
Any ideas? Creative solutions are welcomed.


text:
Q: RVest too slow, trying to optimize for pulling stock indicators In my first post, I would like to share my pet project. I am in the process of making a machine learning algorithm that can assign buy/sell/hold positions to securities. The first step of this project is to build the dataframe that contains the securities' basic information as well as relevant predictive indicators. I am using rvest to webscrape data from two different websites that give stock information. Below is my code:
#load all variables of interest
 for(i in 1:nrow(stockdata)){
  #price
  url <- paste0('https://www.nasdaq.com/symbol/',tolower(stockdata[,1][i]),
 sep="")
  html <- read_html(url)
  #Select the text I want
  Price <- html_nodes(html,'#qwidget_lastsale')
  stockdata$Price[i] <-  html_text(Price)

  #price change percentage
   url <- paste0('https://finviz.com/quote.ashx?t=',stockdata[,1][i], sep="")
   html <- read_html(url)
   #Select the text I want
   change <- html_nodes(html,'.table-dark-row:nth-child(12) .snapshot-td2:nth-
 child(12) b')
   stockdata$PriceChange[i] <-  html_text(change)

}

I have truncated the code, but the above works in pulling data. Unfortunately, the process is horrifically slow. I have many more variables to pull, and each one slows it down more and more. My knowledge of vectorization is decent for speeding up the process, but not sure how to apply it. Any tips on making this process faster in its execution or some knowledge on general speedier iteration tips would be greatly appreciated.


text:
Q: Resize image depending on window height As per the title, I want to be able to reduce image size when window height becomes smaller.
It's working for reducing part but I want it to get the original height back when window height is greater than specified.
I know this part $('.model').height(); is wrong.
$(window).on('load resize', function() {
  var h = $(window).height();

  if (h < 850) {
     $('.model').height(600);
  } else {
     $('.model').height();
  }
});

A: You can try to store the height of .model in a variable and restore it like this:
var originalHeight = $('.model').height();

$(window).on('load resize', function() {
   var h = $(window).height();

  if (h < 850) {
     $('.model').height(600);
  } else {
     $('.model').height(originalHeight);
  }
});

A: try putting height back into (the default) "auto" when you want the original size back?
     $(window).on('load resize', function() {
     var h = $(window).height();
if (h < 850) {
   $('.model').height(600);
} else {
   $('.model').css("height","auto");
}
});


text:
Q: Is there any way to use API with headers and API KEY using Volley to develop Android App? I found some good APIs on RapidApi i wanted to use for developing Android and iOS apps but those Apis require Headers and API KEY for GET requests and i cant find any tutorial or solution as to how to use such APIs where headers are necessary for using in Volley.
Can anyone provide a sample solution of using an Api which requires Headers, by getting JSON data from such API?
Is there any solution to this? And also is there any Better Alternate to Volley for such purpose?
RapidApi provide format for only UniRest and OKHttp and what is the way to translate such format to Volley for further usage?

A: For using any API from RapidAPI Hub you have to pass custom headers in the HTTP requests, x-rapidapi-host and x-rapidapi-key. You can head over to this link to learn more about how to add custom header in the Volley request.


text:
Q: How wide-spread is this GNU extension on ternary operation? This is a GNU extension on ternary operation according to the Wikipedia.
iMyVal = --iVal ?: iDft;

While I'm fully aware that this is a GNU extension, but sometimes things may come in very handy with this special syntax.
So, does anybody know if this syntax is only available in gcc?  Or are they any other compilers which support it?
to anyone who's interested, PHP started supporting this syntax from 5.3
Thanks in advance.

A: Some answers:

*

*GCC - yes

*MSVC - no (based on vanetto's answer)

*CLANG - no yes - the LLVM online compiler compiles it successfully.

*Intel C compiler - yes

Bottom line - not wide-spread. Only Intel's compiler, which is almost 100% gcc-compatible, supports this.?

A: C++11 workaround:
template<typename Fcond, typename Flast>
auto ternary2support(Fcond fcond, Flast flast) -> decltype(fcond())
{
  auto    cond_result= fcond();
  return  cond_result? cond_result : flast();
}

#define ternary2(c,case0) ternary2support(  [&](){ return (c);}, [&](){ return (case0);} )

void test_tern2()
{
  int i= 3;

  int res1= ternary2(--i,1000);
  int res2= ternary2(--i,1000);
  int res3= ternary2(--i,1000);

  std::cout<<" res1="<< res1<<" res2="<< res2<<" res3="<< res3;
  // output: res1=2 res2=1 res3=1000

}

int main(){test_tern2(); return 0;}

Lambda lasyness prevents the condition recalculation and unnecassary case0 expression evaluation (as the original ternary operator extension works)


text:
Q: Google Map Loading issue in cordova ios When I open Google Maps using google map URL for the first time(if google map is not running in background) direction will not show. If google map is running in background then direction will show properly. I am working on Cordova, in android, this issue is not there but in iOS, I am getting this issue.
My code is:
I used all these URL but it's not working in iOS if Google Maps is not running in the background.
var mapLocationUrl = "https://maps.google.com/maps?saddr=current location&daddr=" + lat + "," long;
var mapLocationUrl = "https://www.google.com/maps/dir/?api=1&destination=" + lat + "," + long + "&travelmode=driving";
var mapLocationUrl = "maps://maps.google.com/maps?daddr=" + lat + "," + long + "&ll=";
var mapLocationUrl = "comgooglemaps://?saddr=&daddr=" + lat + "," + long;
var mapLocationUrl = "https://maps.google.com/maps?origin=My Location" + "&daddr=" + lat + "," + long;
var mapLocationUrl = "https://maps.google.com/maps?daddr=" + lat + "," + lng;

window.open(encodeURI(mapLocationUrl), '_self', 'location=yes');
window`.open(encodeURI(mapLocationUrl), '_system', 'location=yes');

A: It looks like this may be related to issue 142856429 in Google's Issue Tracker. I recommend you star the issue to get updates on its progress.
Edit: The issue is now fixed as per the recent comment on the tracker.


text:
Q: How to compile a Qt application through the command line with MinGW? I have downloaded the latest Qt version for MinGW, and I have the correct MinGW version which is compatible with Qt. When I try to make the project, g++ is unable to find my source file even if it's in the same folder as the project file.
Those are the steps I followed (all project and source files are in T:\QtTest ):
T:\QtTest> qmake -project
T:\QtTest> qmake
T:\QtTest> make

And the output is this:
T:\QtTest> make
mingw32-make -f Makefile.Debug
mingw32-make1: Entering directory `T:/QtTest'
g++ -c -g -frtti -fexceptions -mthreads -Wall -DUNICODE -DQT_LARGEFILE_SUPPORT -DQT_DLL -DQT_GUI_LIB -DQT_CORE_LIB -DQT_HAVE_MMX -DQT_HAVE_3DNOW -DQT_HAVE_SSE -DQT_HAVE_MMXEXT -DQT_HAVE_SSE2 -DQT_THREAD_SUPPORT -DQT_NEEDS_QMAIN -I"c:\Qt\4.8.0\include\QtCore" -I"c:\Qt\4.8.0\include\QtGui" -I"c:\Qt\4.8.0\include" -I"." -I"c:\Qt\4.8.0\include\ActiveQt" -I"debug" -I"c:\Qt\4.8.0\mkspecs\default" -o debug\main.o main.cpp
g++: main.cpp: no such file or directory
g++: no input files
mingw32-make1: *** [debug/main.o] Error 1
mingw32-make1: Leaving directory `T:/QtTest'
mingw32-make: *** [debug] Error 2

I have no idea why it can't find "main.cpp" file when it's in the same directory as the
project files. Even if I replace "main.cpp" with the full path ("T:\QtTest\main.cpp") it still won't find it. What am I doing wrong?
The following is my project structure:
(main.cpp is the only file that I wrote, all the others were generated by qmake)
T:\QtTest\main.cpp
T:\QtTest\Makefile
T:\QtTest\Makefile.debug
T:\QtTest\Makefile.release
T:\QtTest\QtTest.pro
T:\QtTest\debug\
T:\QtTest\release\

My g++ version is 4.4.0, which is the version suggested by the Qt installer and available for download in the same page as the Qt for MinGW installer.

A: Problem solved.
It had nothing to do with MinGW or Qt or the makefiles generated by qmake. I found it was caused solely by a custom entry in the Windows registry. I'm posting this solution for anyone who encounters the same problem:
Sometime ago I had created an entry in the Windows registry under HKEY_CURRENT_USER \ Software \ Microsoft \ Command Processor called Autorun, which makes CMD.exe start in a custom working directory, which was something I wanted to do (so I followed the steps detailed in this page about "How to change the default startup directory for Command Prompt": http://windowsxp.mvps.org/autoruncmd.htm).
Well, I completely neglected the CAUTION part in that page, which states that "Changing the current directory using Autorun value as mentioned in this article, might affect the functionality of batch scripts". Yes, shame on me.
So, if you have the same problem of being unable to make your Qt projects using qmake, and everything else looks OK in your project structure and makefiles, verify that you don't have something in the Windows registry which might change the startup directory for the command prompt.

A: Do you have MSYS installed? If sh.exe from MSYS is on the system path, it may conflict with the interpretation of windows style paths. Check the documentation here.
If that isn't the problem, then delete everything in your project folder except the source files and start over again with qmake -project. After that step, open the .pro file and verify that things look correct. For a very basic project, I get something like this:
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
HEADERS += widget.h
FORMS += widget.ui
SOURCES += main.cpp widget.cpp

The next two steps, running qmake and then make should work correctly. If not, there is nothing wrong with the steps you followed and there is something wrong with your system/environment.


text:
Q: Configure Asp.net Telerik editor Dialog when EnableEmbededScript is OFF I have used asp.net Telerik RadEditor control in web-site and to host this website in Shared hosting server, I have to disable Telerik.EnableEmbeddedScripts flag and add required scripts in page but Dialog of RadEditor is not working.
My site is hosted in FastHost shared hosting server. Other controls of Telerik is worked perfect. Version of Telerik is 2011.3.1115.35
Can anyone suggest how to enable dialogs for editor control on any shared hosting server?

A: My suggestion is to test with enabled CDN scripts or configure your own custom CDN provider which will automatically import the dialog scripts
If you disable the scripts, you will need to create a handler file EditorDialogScripts.zip - this file is old and created for Q1 SP2 2009) containing the dialog scripts of RadEditor and import it via the DialogsScriptFile property of RadEditor (DialogsScriptFile="~/Scripts/EditorDialogScripts.ashx"), which is a time consuming and not straightforward process.
You can see which files are loaded in the dialogs using Firebug or Fiddler.


text:
Q: How can I retrieve titles of various articles from one website using python web scraping? I am looking to get topic of all the articles available in this webpage "  " using python web crawler. I am very new to html. This is the code I have so far which I got as a reference from different examples. Would somebody please help me undersand this and get the correct code?
The code below is what I tried changing h2 tag to h1, h3,h4 and so on.
from urllib2 import urlopen

from urllib2 import HTTPError

from urllib2 import URLError

from bs4 import BeautifulSoup

try:

     html = urlopen("https://query.nytimes.com/search/sitesearch/#/*/365days/")
except HTTPError as e:

    print(e)

except URLError:

    print("Server down or incorrect domain")

else:

    res = BeautifulSoup(html.read(),'html.parser')

    tags = res.findAll("h2", {"class": "widget-title"})

    for tag in tags:

        print(tag.getText())

My expected outcome is titles of various new articles in this webpage. For eg:
Judge Harshly Criticizes Kobach During Contempt Hearing
How a Self-Driving Uber Killed a Pedestrian in Arizona

A: Every time you go to the page
https://query.nytimes.com/search/sitesearch/#/*/365days/

there is javascript that is executed on pageload which requests the resource living at
https://query.nytimes.com/svc/add/v1/sitesearch.json?begin_date=365daysago&facet=true

This responds with a very large JSON document containing the results of your search, which you can parse to get back the article headlines. The code would look something like:
import json
from urllib2 import urlopen, HTTPError, URLError

resp = urlopen("https://query.nytimes.com/svc/add/v1/sitesearch.json?q=quack&begin_date=365daysago&facet=true")
content = resp.read()
j = json.loads(content)

articles = j['response']['docs']

headlines = [ article['headline']['main'] for article in articles ]
print headlines


text:
Q: SQL Server 2008 Full-Text Search installation I have full version of SQL Server 2008 R2 on my machine. Only problem is when my computer was created (by the IT Tech's at my work) they did not add the Full-Text Search feature to the installation. I would like to know if there is anywhere that you can download this feature from online. And if there is how do i install it?
Thanks.

A: Full-Text Search is a feature on the installation media. You will need the installation media or binaries and go through setup and add the feature to an existing installation of SQL Server. You cannot download Full-Text search as a standalone installation.


text:
Q: Concern about the data style manipulation on the view So, I want to display some rules concatenated with AND or OR, and I want to add color to AND or OR like red, green etc.
Fruit = Apple AND Market = SuperMarket1

So how should I do this? I have following thoughts:

*

*To control the css by adding the css properties in repository or service class which handles the data access, which works but violates MVC design pattern.

*To manipulate the data in the View using something like the Helper class, but the problem is the helper class has to parse the string to find the AND and it is possible that if AND is part of the rule. Even it is in rare case but it is still possible that if any rule contains the keyword and displays it incorrectly.

Any idea? Thanks in advance!

A: Just conditionally set a span with appropriately styled class on the element you want to color in the View.  You can set helpers to do this and that, but often times people get so out of hand with helpers that they needlessly complicate the app....which is the opposite of the aim of MVC.  Yes, it might violate the "strict" rules that MVC is supposed to follow.  But step back and think about it.....is your environment REALLY big enough that you have to 100% strictly separate a minute amount of code and the presentation layer?  Really?  I've worked for Fortune 500's who don't stress that much.
The thing about MVC is that you can analyze it to death.  It's great help to those of us who are building complex apps.  But, there's an exception to EVERTHING.  If you stress about these exceptions, you're not going to get anything done.  Loosen the tie, man.


text:
Q: killing process group with SIGINT and SIGTERM shows different result (I changed the point of question into about more basic symptom.)
I created child and grand child in bash script.(in Ubuntu 14.04)
#! /bin/bash

{
    sleep 21 &
    sleep 22
}&

sleep 23

But 2 kind of command to kill process group shows different result.
( I've run the kill command in another terminal at this test.)
kill -INT -<pgid>     # -> grand child(sleep 21) survives.
kill -TERM -<pgid>    # -> kills all correctly.

Could you explain what it is going on internally?


text:
Q: How to go to webpage and check a html checkbox At the coffee place I use to go, the captive portal grants wifi access after you check a checkbox in their landing page (accepting the TOS). That wouldn't be an issue if I didn't spend hours there and they didn't asked every 15 min or 100 MB again and again.
Could I automatize the process of connecting with Bash, Perl, Python or any other resource commonly found on Ubuntu?
Html snipped of it:
<form action="http://1.1.1.1/reg.php" method="post" name="form2">
<input name="url" value="2EB8F3587D88E953591ABBE4833943D6C1241D2842D3D2FC83D98ED1D0613DC1BFFB8380" type="hidden">

          <input name="checkbox" id="checkbox" value="checkbox" type="hidden">
          <input checked="checked" name="checkbox2" value="checkbox" onchange="evalue(this);" type="checkbox">
          I accept the Terms and Conditions

          <input name="Submit" value="Enter" id="button1" type="submit">

</form>

A: I am assuming the url value here is some sort of session key unlike what the field name implies. You could try to get it using e.g. sed:
wget -qO- http://… | sed -n 's/<input name="url" value="\([^"]\+\)" type="hidden">/\1/p'

Then using this you could build a request on your own using curl. It might help to get inside Chrome developer tools where you can right-click on the request to get a copy of it as a curl command line.
Alternatively, you could use Selenium. Using Selenium for Python the code would then look like:
driver.find_element_by_name('checkbox2').click()
driver.find_element_by_id('button1').click()


text:
Q: Login Design Logic This is a pretty generic question, but any advice is appreciated.
I am writing an Ionic2 app that uses Firebase Authentication.
A user can sign up to the app. A verification email is sent to the user's email address. If the user verifies their email, they can access the app.
However, if a user does not verify their email, for example if they signed in with the incorrect email address, then the email will never be verified. In such a case, the incorrectly registered email address sits on the Firebase database redundantly, or if the valid user tries to signup with that email, they get a message that that email address belongs to the original provider (Facebook, Google or plain email), and cannot sign up as a different provider.
As you can see, the above situation can potentially block a user from registering their email address.
I have tried to delete the Firebase account when the user comes to sign in so they start afresh as I do have the matching uid. However, I don't think the AngularFire2 api allows a Firebase account to be deleted by uid. See here.
Can either suggest:

*

*How to delete the account by uid, or

*Another design I can use to resolve this issue.

Thanks you
UPDATE
Thank you for the advise below.  I have a Java server which I would like to do the Firebase Admin management of users.
I have found Java documentation on how to initialize Firebase Admin. e.g.
public void initialize() {
    String keyPath = "/appname-123456-firebase-adminsdk-eknji-3071d579f5.json";

    InputStream serviceAccount;
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    serviceAccount = loader.getResourceAsStream(keyPath);
    // serviceAccount = new FileInputStream(keyPath);
    FirebaseOptions options = new FirebaseOptions.Builder()
            .setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
            .setDatabaseUrl("https://appname-123456.firebaseio.com").build();
    FirebaseApp app = FirebaseApp.initializeApp(options);
    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseDatabase database = FirebaseDatabase.getInstance();
}

I can find Node.js documentation on how to manage users. But how do you do this in Java?  i.e. How do I delete a user by uid?
UPDATE
Looks like you need to create a custom token with the uid. See here.
How do you do the following in Java?
admin.auth().deleteUser(uid)
  .then(function() {
    console.log("Successfully deleted user");
  })
  .catch(function(error) {
    console.log("Error deleting user:", error);
  });

UPDATE
I don't think it is possible to manage accounts in Java. I think the custom token needs to be passed back to the client, and then used to sign in for that user. see here.

A: There are three ways to delete a Firebase Authentication account:

*

*from the Firebase Authentication console.

*by calling delete() on the signed in user from the app.

*by calling deleteUser() from the Admin SDK.

It sounds like you're looking for option 3. This requires that you run a trusted process that deletes the extraneous users. Don't try to run this code in your actual app, since that would open up a security that allows all your app's users to delete each other's account.


text:
Q: Setting up an API in Power BI to pull data from website I'm relatively new to python and API's. Basically, I have a form in Wufoo that I am currently manually exporting the data from into an excel document so that builds a Power BI report. I have been trying to set up a web connection directly to Wufoo so I no longer have to do the manual data pull.
I have tried using the get data from Web in Power BI and entering the URL: http://{subdomain}.wufoo.com/api/v3/forms/{identifier}/fields.{format})  updating the subdomain and using the form's hash as the identifier, and setting the format to json
But get an error:
"(400): Your request has been rejected.  Please make this request via HTTPS."
I built some code in Python (I'm using version 3.9.5) below, and while I am able to get it to pull the data and print it out in my code editor (Komodo Edit), but no data comes up in the navigator. What am I doing wrong here?
#!/usr/bin/python3

import urllib.request
import json

base_url = 'https://ewolford.wufoo.com/api/v3/'
username = 'API KEY'
password = 'password'

password_manager = urllib.request.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, base_url, username, password)
handler = urllib.request.HTTPBasicAuthHandler(password_manager)
opener = urllib.request.build_opener(handler)

urllib.request.install_opener(opener)

response = urllib.request.urlopen(base_url+'forms/hash/entries.json?sort=EntryId&sortDirection=DESC')

data = json.load(response)

print(json.dumps(data, indent=4, sort_keys=True))

A: Add a last line to print a pandas.dataframe instead. From Microsoft doc. (emphasis mine):

The Power BI Python integration requires the installation of two Python packages:

Pandas. A software library for data manipulation and analysis. It offers data structures and operations for manipulating numerical tables and time series. Your imported data must be in a pandas data frame. A data frame is a two-dimensional data structure. For example, data is aligned in a tabular fashion in rows and columns.

import pandas as pd

{your code here}

data=json.load(response)

table=pd.DataFrame(data)

print(table)


text:
Q: How do I remove a folder from Powershell? I'm trying to delete an empty folder via Powershell. I can delete the folder manually w/o any issues but when I try to run the following PS command I get the error:

the PS command is Remove-Item "C:\Program Files\P...Ware" -Force;

update
I followed @Captain's advise and still got the same error:

A: This solution may work for you:
$allProcesses = Get-Process
#$lockedFile is the file path
foreach ($process in $allProcesses) {
$process.Modules | where {$_.FileName -eq $lockedFile} | Stop-Process
-Force -ErrorAction SilentlyContinue
    }
Remove-Item $lockedFile

from
https://stackoverflow.com/a/45714289/10958914

A: You have to provide the -path parameter as well
Remove-Item -path "yourfolder path" -force

Your command will be like this
Remove-Item -path "C:\Program Files\P...Ware" -Force;


text:
Q: Anti-Aliasing filter with ffmpeg or other tools to old video I have many old computer generated videos in mp4 at very low resolution 640x480.
Here an example:

I have tried to upscale it with IA but still a lot of aliasing.
I ask if there is a way to apply a anti-aliasing filter with ffmpeg or other tools to my videos.
Thanks !

A: give a try to hqx filter or xbr filter


text:
Q: Sharing memory in NodeJS and Express application I'm trying to understand Node/Express a little better and was wondering if it was possible for one request to overwrite the memory of another. Here's a contrived example:
// UserController.js
const userService = require('./UserService');

class UserController {
  async show(req, res)  {
    userService.userId = req.params.userId;
    const userDetails = await userService.getDetails();
  }
}
module.exports = UserController;

// UserService.js
const request = require('request-promise');

class UserService {
  set userId(userId) {
    this._userId = userId;
  }

  async getDetails() {
    // Make HTTP request to some service
    let options = {
      method: 'GET',
      url: 'https://url-to-user-service/' + this._userId, // Notice use of userId
      json: true,
      headers:{}
    };

    return request(options);
  }

}
const userService = new UserService(); // pseudo-singleton
module.exports = userService;

Is it possible to have 2 concurrent requests do something like this:
Request1: execute line "userService.userId = req.params.userId" // userId 1
Request2: execute line "userService.userId = req.params.userId" // userId 2
Request1: execute line "const userDetails = await userService.getDetails();" which would have a userId of 2? Or will the entire show() function be executed for request 1 before request 2 would execute it?
Thanks!

A: As it is, your code is buggy and it will bite you when you have several requests coming fast.
Here:
  async show(req, res)  {
    userService.userId = req.params.userId;
    const userDetails = await userService.getDetails();
  }

While node waits for the results of userService.getDetails(), yes you can have another parallel execution, total or partial, of the show function.
This feature lets your program be more efficient, especially when userService.getDetails appends to be slow. Of course if you access some shared data from the function then you need to think about the possible inconsistencies which may occur.
I can't redesign your program without knowing more but a simple solution could be to have an instance of UserService or an object having the same role kept in the scope of show.


text:
Q: Proving the convergence of the sequence $\sum \limits _{n=1}^{\infty}\frac{\sin (n)}{n}$ with comparison test I need proving that the sequence $\sum \limits _{n=1}^{\infty}\frac{\sin (n)}{n}$ converges with comparison test.

I have seen a lot of questions that are really like this question, but I haven't found an answer using only a comparison test. I need to do that in the most elementary way, without Dirichlet's test, Abel, Fourier, complex trigonometric identities, but just with comparison test. Is it possible? if so I will be glad to hear from you how. Thanks a lot!


text:
Q: Finding bounding rectangle after rotation
I have two rectangles  inner rectangle(green) and the outer one (red).
OuterRectangle will be calculated by adding some offset to inner rectangle as shown below.
OuterLeft = innerLeft - 100;
OuterTop = innerTop - 100;
OuterRight = innerRight + 100;
OuterBottom = innerBottom + 100;
But this will not work once the inner rectangle is rotated .
Please let me know how can i calculate outer rectangle based on inner rectangle after rotation by some angle.
Thanks in advance

A: If you knew the rotation angle, you could simply apply the same rotation to the outer rectangle. So I assume that you only have to corner points of the (rotated) inner rectangle.
Let $p_0, p_1, p_2, p_3$ be the points of the inner rectangle, ordered counterclockwise (starting at the upper left corner, in this case). Then you can compute the vectors describing the edges

*

*$e_0 = p_1 - p_0$

*$e_1 = p_2 - p_1$

*$e_2 = p_3 - p_2$

*$e_3 = p_0 - p_3$

and the corresponding directions, by normalizing these vectors
$d_i = e_i / |e_i|$ for $i = 0...3$
The corners of the outer rectangle can then be computed based on the original points and these direction vectors. Let $s_t, s_l, s_b, s_r$ denote the offset of the outer rectangle at the top, left, bottom and right side, respectively (in your case, they are all 100).

*

*$q_0 = p_0 - s_t d_0 + s_l d_3$

*$q_1 = p_1 - s_l d_1 + s_b d_0$

*$q_2 = p_2 - s_b d_2 + s_r d_1$

*$q_3 = p_3 - s_r d_3 + s_t d_2$

(This is not really related to trigonometry, by the way)


text:
Q: Why is the time in my Python programm not updating? I want to display time in a python programm. When I start the programm it gets the time but than it dont changes.
Here is my code:
import time
import pytz
from datetime import datetime

current_time = datetime.now(pytz.timezone('Europe/Madrid')).strftime("%H:%M:%S")

while True:
    print(current_time)
    time.sleep(5)

I always get the same time and i have no idea why

A: You are not updating the time in your programm.
datetime.now result is stored only once in a variable current_time.
If you want to get the current time at each loop iteration :
import time
import pytz
from datetime import datetime

while True:
  #update the time here
  current_time = datetime.now(pytz.timezone('Europe/Madrid')).strftime("%H:%M:%S")
  print(current_time)
  time.sleep(5)

A: You are assigning the current_time variable only once outside of the loop - you're displaying current_time every 5 seconds but you need to update the time every 5 seconds too.
To fix this, move the variable assignment inside the loop.
import time
import pytz
from datetime import datetime

while True:
    current_time = datetime.now(pytz.timezone('Europe/Madrid')).strftime("%H:%M:%S")
    print(current_time)
    time.sleep(5)


text:
Q: Logarithmic Inequality and quadratic function Prove that if $m$ satisfy inequality: $$\left (1+ \frac{1}{2m}\right) \log_k 3 - \log_k (27 + 3^\frac{1}{2m}) \le 2$$
where $k=\frac{1}{2}$, then $x^2 + mx + 1  > 0$ for every real number.
I solved one $m_1=0$, but the other doesn't satisfy the second condition.

A: HINT.-You have $$\left (1+ \frac{1}{2m}\right) \log_k x - \log_k (27 + 3^\frac{1}{2m}) \le 2\iff\log_k\frac{x^{1+\frac{1}{2m}}}{27+ 3^{\frac{1}{2m}}}\le2=\log_k\frac14$$
and because the log is injective and increasing we get
$$\frac{x^{1+\frac{1}{2m}}}{27+ 3^{\frac{1}{2m}}}\lt\frac14$$ Now you can work in an easier way.Try it and if you can't finish I shall give you the final part.


text:
Q: How can I reverse and modify my string in assembly? I have a project where I want to enter a number and say I enter 3, it gives you an output of,
ZYX**XYZ

ZY****YZ

Z******Z

And a 5 will give you
ZYXWV**VWXYZ

ZYXW****WXYZ

ZYX******XYZ

ZY********YZ

Z**********Z

In my project I don't think my instructor will allow me to use an array, or at least not yet but here is my idea.
I was thinking of making a string for the number so say I get a 3. I would produce ZYX* and simply reverse it to get the other half of the triangle. Only thing is, I don't know how to change the letters one at a time to the stars. I'm thinking of using loops to do it but not sure how to do it. I just know that the next string would be ZY** and then simply reverse it.
Don't get me wrong, I'm not asking you all to do it for me but maybe give me some pointers or tips on how to approach it. thank you.
So far, thanks to you all, I have been able to come up with this.
TITLE MASM Template                     (main.asm)

; Description:
;
; Revision date:

INCLUDE Irvine32.inc

.data
x       DWORD   ?
msg     BYTE    "Please input a number: " ,0dh,0ah,0

.code
;crlf
main PROC
    call    Clrscr

    MOV     edx, OFFSET msg         ; Moves message to input number into register
    call    WriteString         ; Displays message on screen to prompt user to input number
    call    readInt             ; Take the number that the user inputs
    MOV     x,eax                   ; Store it into x
    MOV     ecx, eax                ; For the loop counter
    MOV     al, 'Z'                 ; Move Z to the register

L2:
    MOV     al, 'Z'             ; Resets al to z for loop

L1:                         ; Start of the loop with label L1
    call    WriteChar           ; To write the letters
    ;call crlf              ; To put in 'enter'
    SUB     al, 1               ; To Move the next char going downward
    LOOP    L1

    MOV     al, ' '
    call    WriteChar
    MOV     ecx, x                  ; Resets ecx for outside loop
    SUB     x, 1                    ; Decrements x for counter

    call    crlf                    ; To be tidy
    LOOP    L2

    exit
main ENDP
END main

Now I just need the other side.

A: Welcome to the blackest of the black computer arts - Assembler!
Let's look at this problem from an Assembler programmer's point of view.
You have a number, let's say BL ('cause that's a good Assemblerish name) and what you want to do is produce BL lines of output. Let's say BL=5
Now, CX is really good as a counter register, so if we copy BL to CL and clear CH by XORing it with itself, we have CX=#lines too.
The number of characters we have to print before reversing is conveniently one more than this, so we could increment CX - and that's an important number, so save it in say, BP
Each line consists of the letters 'Z' down to ('Z' - BH + 1) and one asterisk, then the same in reverse, and a new line. And every new line, you reduce the number of letters printed by one and add one to the number of asterisks.
To produce one line, we'd

*

*Load a register - say, DL, with 'Z' (DL because it's convenient as
the output for a 'printme' routine)

*Copy that to another register, say BH (a register-to-register move is
faster and smaller than a load-immediate)

*Subtract BL from BH, yielding a magic value, 'Z' - 5 = 'U' - is there
a bell ringing yet?

We want to print a count of letters, so if we copy BP into CX, that should be useful.
Here's something we want to do CX times:

*

*Write out the character in DL - with a twist.

*Change the character in DL by DECREMENTING it

Then we need to output another BP bytes, so sopy BP to CX again
Here's something we want to do CX times:

*

*Write out the character in DL - with a twist.

*Change the character in DL by INCREMENTING it

Then send CR and LF
So - what's the twist?
Well, if the character in DL is LESS THAN or EQUAL TO the character in BH, we want to substitute an asterisk, so

*

*save DX on the stack

*load DL with ASTERISK if DL<=BH

*output DL

*pop DX back from the stack, restoring its value before we substituted
the asterisk.

Done that line - decrement the count of lines in BL; if the result is non-zero, produce another line

*

*If it is zero, we're all done.

Note here that by decrementing the count of lines in BL, the number subtracted from DL at the start of the produce-a-line routine decrements, so the 'change to aster' value becomes 'V', 'W'...
Now let's get downright kinky.
You'll note that the only difference between the two write-CX-characters routines is that one DECREMENTS and the other INCREMENTS DL...
Let's set SI to 0FFFFH and DI to 1 before we start, just for laughs.
Now - DH is sitting on the bench for this entire game.
Suppose we write the routine to print CX characters such that it ADDs SI to DX. That will give us the decrement we need in the loop the first time.

*

*When the loop ends, suppose we EXCHANGE DI and SI.

*The next time the loop runs, it will INCREMENT DX, then exchange SI
and DI again.

Useful, huh?
Oh, and while we're twisting, we can get DH involved by using it to store DL rather than pushing DX and popping it back. Move DL to DH, test for substituting the aster, write out and restore DL from DH.
So - the point with this routine is that it doesn't rely on a string in storage...

A: I wrote a tutorial on how to create a pyramid of characters.  It uses NASM and the Windows API instead of Irvine, but the tutorial should get you going and help you a bit on the logistics.


text:
Q: Python Bar Chart X axis re-naming matplotlib my question is simply how would I change the X-axisOUTCOME OF CODE FOR BAR CHART
from the numbers (Ex. 17, 1, 2, 4) to the PET names (Ex. Horse, Dog, etc). Code Below
I'm new to stack overflow but here is an image of the code. I'll eventually figure out how to use it.
Here is my code.
CSV DOWN BELOW
Height,Ice Cream,Pet,#of letters,Favorite TA,Minutes to Hometown
67,Chocolate,Dog,16,Ryan,55
63,Cookie Dough,None,15,Mimi,180
75,Vanilla,Dog,20,Peter,150
66,Moose Tracks,Dog,16,Erik,300
72,Vanilla,Dog,17,Ryan,60
66,Moose Tracks,Dog,14,Emily,85
72,Chocolate,None,21,Josh,70
72,Mint Chip,Cat,9,Abe,70
71,Vanilla,Dog,20,Brian,90
75,Vanilla,Dog,5,None,105
68,Strawberry,Horse,19,Emily,120
59,Chocolate,Dog,13,Cezanne,45
73,Vanilla,Dog,14,Monica,155
64,Chocolate,None,16,Sarah,120
67,Mint Chip,Dog,21,Kelly,180
67,Mint Chip,Dog,20,Ryan,90
68,Cookies & Cream,Dog,13,Toner,180
65,Chocolate,Dog,20,None,60
75,Chocolate,Dog,9,Chris,120
67,Cookie Dough,None,10,Katie,75
67,Vanilla,Dog,24,Carlos,120
75,Mint Chip,Dog,17,Tim,180
64,Vanilla,Dog,15,Xavier,135
74,Cookies & Cream,Horse,18,Jeff,180

Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

h2 = pd.read_csv("hw_2_data.csv")

## create grouped dataframe
h2Grouped = h2.groupby('Pet').count()
##h2Grouped

##recreate serverity variable
h2Grouped['Pet'] = h2Grouped.index
## rename the variables
h2Grouped.columns = ['Count', 'Pet', 'Ice Cream', '#of letters', 'Favorite TA', 'Minutes to Hometown']

#matplot
%matplotlib inline

##bar
bar1 = h2Grouped.plot.bar(x = 'Pet', y = 'Count', title = 'Pet Bar Chart')
bar1.set_xlabel('Pet')

##get rid of text output
t = bar1.set_ylabel('Count')


text:
Q: How do you filter the user with hasRole() in Laravel 5 within relational query? I want to filter my query and return only if the user hasRole "Premium" and limit the result to 10.
Along with this query is a count of records which Conversion has and sort it in DESC order by total column.
Right now I have a working query that returns the count of Conversion and with a User but without user filter Role.
// Model Conversion belongs to User
// $from & $end uses Carbon::createDate()
// Current code
$query = Conversion::select('user_id',DB::raw('COUNT(*) as total'))
                ->whereBetween('created_at', [$from,$end])
                ->where('type','code')
                ->where('action','generate')
                ->whereNotNull('parent_id')
                ->with('user')
                ->groupBy('user_id')
                ->orderBy('total', 'DESC')
                ->take(10)
                ->get();

// current result
foreach ($query as $q) {
    $q->user->name; // To access user's name
    $q->total; // To access total count
}

// I tried this but no luck
$query = Conversion::select('user_id',DB::raw('COUNT(*) as total'))
                ->whereBetween('created_at', [$from,$end])
                ->where('type','code')
                ->where('action','generate')
                ->whereNotNull('parent_id')
                ->with('user', function($q) {
                    $q->hasRole('Premium');
                })
                ->groupBy('user_id')
                ->orderBy('total', 'DESC')
                ->take(10)
                ->get();

A: Use the whereHas() instead of with(). Also, you can't use hasRole() if it's not a local scope:
->whereHas('user.roles', function($q) {
    $q->where('name', 'Premium');
})

A: You need to use whereHas instead of with, like this:
 ->whereHas('user', function ($query) {
       $query->where('role','Premium');
 })


text:
Q: How to choose a prime p s.t. n-th cyclotomic polynomial splits into as much as possible irreducible polynomials while p is almost constant size? The reason I ask this question is that cyclotomic polynomial is critical to the construction of lattice-based cryptography. In most of the existing lattice-based cryptographic schemes, $n$ is usually chosen to be the power of 2, and according to Corollary 1.2 of ``Short, Invertible Elements in Partially Splitting Cyclotomic Rings and Applications to Lattice-Based Zero-Knowledge Proofs'' (https://eprint.iacr.org/2017/523.pdf), $p$ is equal to $2k+1 \mod 4k$, where $k$ is the number of irreducible polynomials $X^n+1$ can split into in $\mathbb{Z}_p[X]$. In other words, the size of $p$ seems to depend on the size of $k$ in this case.
I wonder what would happen in the general case of cyclotomic polynomial where $n$ is not necessarily the power of 2. According to Wikipedia (https://en.wikipedia.org/wiki/Cyclotomic_polynomial#Cyclotomic_polynomials_over_a_finite_field_and_over_p-adic_integers, sorry this is the best source I can find regarding this topic), the cyclotomic polynomial ${\displaystyle \Phi _{n}} $ factorizes into ${\displaystyle {\frac {\varphi (n)}{d}}} $ irreducible polynomials of degree $d$, where ${\displaystyle \varphi (n)}$ is Euler's totient function and $d$ is the multiplicative order of $p \mod n$. I wonder if I choose $d$ to be, say $\sqrt{\varphi (n)}$, which means the number of resulting split polynomials would be around $\sqrt{\varphi (n)}$ while $p$ should satisfy $p^{\sqrt{\varphi (n)}}=1\bmod n$. Can I say with high probability there exists a $p$ of size $O(|\log_{\sqrt{\varphi (n)}}(n)|)$ such that $p^{\sqrt{\varphi (n)}}=1\bmod n$ holds? As a result, I can claim the conclusion mentioned in the title holds. For practical purpose, $d$ doesn't have to be $\sqrt{\varphi (n)}$, it could well be $\varphi (n)^{\frac{1}{k}}$, where $k$ is an integer that is $\geq 2$. In which case, $p^{\varphi (n)^{\frac{1}{k}}}=1 \bmod n$ still needs to hold. Can I argue in this general case, there still exists a parameter choice such that the size of $p$ is $O(|\log_{\varphi (n)^{\frac{1}{k}}}(n)|)$ for the above condition to hold?
This seems to hold when $n$ is a certain prime. For instance, one could see when $n=5$ and $d=4$, $p$ can be either 2 or 3. But still, I don't know how I could generalize from this special case to specify the condition under which the above conclusion holds? Thank you so much in advance.


text:
Q: Insert record if all values do not exist in a row I have three columns: a, b, c.
I want to INSERT a new row if a, b, c do not already exist into a row.
Using Python to do this.
INSERT INTO mytable(column_a, column_b, column_c)
VALUES(value_a, value_b, value_c)
WHERE value_a, value_b, value_c are all unique in existing rows.

A: One way to approach this is to create a unique index on the three columns. The database will reject the insert if you attempt to insert a duplicate row. No special query is required. This should work on any relational database, not just MySQL.
Create the unique index with this:
CREATE UNIQUE INDEX a_b_c ON mytable (column_a, column_b, column_c)

Insert like this:
INSERT INTO mytable(column_a, column_b, column_c) VALUES (value_a, value_b, value_c)

If there already exists a row with the same values for columns column_a, column_b, and column_c the database will reject the insert and you will see an exception in Python.

A: If you are fine with implementing a general mechanism to avoid duplicates on columns column_a/b/c, you can simply add a composite unique constraint on both columns, like
ALTER TABLE mytable
ADD CONSTRAINT constr_ID UNIQUE (column_a, column_b, column_c);

If anything operation happens on the table that would generate duplicates, MySQL will raise a constraint violation error. You can ignore the error with the ON DUPLICATE KEY UPDATE option :
INSERT INTO mytable(column_a, column_b, column_c)
VALUES(value_a, value_b, value_c)
ON DUPLICATE KEY UPDATE column_a = column_a;

In this demo on DB Fiddle, we are inserting 3 records with 2 duplicates, and we end up with 2 records in the table, as expected.

On the other hand, if you want to restrict the check on duplicate to just one query, and/or if you want to avoid wasting autoincrement sequences on duplicate keys, then you can turn to an INSERT ... SELECT statement, with a WHERE NOT EXISTS condition that does the duplicate check :
INSERT INTO mytable(column_a, column_b, column_c)
SELECT src.*
FROM (SELECT value_a column_a, value_b column_b, value_c column_c) src
WHERE NOT EXISTS (
    SELECT 1
    FROM mytable
    WHERE
        column_a = src.column_a
        AND column_b = src.column_b
        AND column_c = src.column_c
);

If you attempt to insert a duplicate, the query will do nothing (and will not generate an error or warning).
Demo on DB Fiddle.


text:
Q: How to use flawfinder with a git patch I want to use flawfinder for my merge requests, thus analyzing only the code that change. I saw that flawfinder supports patches, so I thought it would be really easy.
Thing is : I'm unable to make it work with git patch. Flawfinder does recognize it's a git patch, it does scan only the needed files, but there are no hits. If I run flawfinder without the patch argument and check the hits on the changed file, I do see some hits, in the new lines added.
I tried with a diff from svn : works like a charm. With no diff at all : same. With a diff from git : no way to make it works.
If someone has an idea, I'll gladly take it. Or an example.
Quick commands to reproduce :
git diff --patch --output PATCH
flawfinder --patch PATCH <dir>

I got on the output :
Examining <dir>/<file.c>

FINAL RESULTS:

ANALYSIS SUMMARY:

No hits found.

A: For those interested : it is indeed an issue due to the git diff format being slightly different form the unified diff / svn diff format.
diff --git a/file.c b/file.c
index 19651c89a3..c119389931 100644
--- a/file.c
+++ b/file.c
@@ -5017,6 +5017,15 @@ static void foo()

The svn / unified diff don't have the function name after the last @@.
Here is the regex used in flawfinder.py :
 diff_hunk = re.compile(r'^@@ -\d+(,\d+)?\s+\+(?P<linenumber>\d+)[, ].*@@$')

Just removing the $ in the regex is enough to make it work for git.


text:
Q: Using Cocos2d to create a CCMenuSprite shows image incorrectly I am developing a game with Cocos2d for the iPad.  I have created an Image that I would like to use for my menu, as the regular ItemLabel is flat and ugly.  The following shows the same image, but the one on the top is the MenuItem using this code:
CCMenuItemImage *itemEasyLevelImage = [CCMenuItemImage itemWithNormalImage:@"Old_Slow_Menu.png" selectedImage:@"Old_Slow_Menu.png" block:^(id sender){...

The bottom image is the same using this code:
CCSprite *oldSlow = [CCSprite spriteWithFile:@"Old_Slow_Menu.png"];
oldSlow.position = ccp(size.width /2, size.height /2);
[self addChild:oldSlow z: 10];

Any ideas why the image shows up all messed up, as shown in this image:

A: My guess is that something not shown in your code here is changing the color property of the menu item to ccc3( 255, 0, 0 ).


text:
Q: How to make constants in CodeIgniter for images? I want to use the constants.php file to store common image locations.  I have a menu and each item has an image of it's own, and currently for each image in the view, I have:
<?php echo $this->config->item('base_url'); ?>/images/database.png">

Or whatever the filename is.  What I want to do is store a constant "DB_IMG" in this instance, and simply be able to say in my view:
<?php echo DB_IMG; ?>

I know that I can't put:
$this->config->item('base_url')

in the constants file (I tried it, it errored out) and I tried:
$config('base_url')

which said it wasn't defined.  Here's what I'd like to put in my constants file (even though I know this doesn't work) so if you could help me, I'd appreciate it:
define('DB_IMG',$this->config->item('base_url').'/images/database.png');

Thanks.

A: try this
in constants.php
require APPPATH . 'config/config' . EXT;

define(BASE_URL, $config['base_url']);
define(DB_IMG, $config['base_url'] . '/images/database.png');

unset($config);

A: Because constants.php is in the config directory it doesn't have access to config items because config.php hasn't been loaded yet.  I think you'll need to put the full URL in there or else use native PHP functions to get the base URL.


text:
Q: Delphi code fails at 64 bits access violation This Delphi code works when compiled for 32 bits, but gives an access violation when compiled for 64 bits. Is there a problem with the code, or is there a compiler bug?
{$APPTYPE CONSOLE}

uses
  SysUtils;

const
  MaxSize = 2; // nothing special about this value, could equally be 1

type
  TArraySize = 1..MaxSize;

procedure Main;
var
  size: TArraySize;
  arr: array [-MaxSize..MaxSize] of Integer;
begin
  FillChar(arr, SizeOf(arr), 0); // zero initialize
  size := MaxSize;
  Writeln(arr[-size]);
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

A: This is a compiler bug. The compiler does not handle
arr[-size]

correctly, presumably because size is a subrange type.
You can workaround the bug by forcing the compiler to perform the arithmetic in an Integer context.
arr[-Integer(size)]

You should submit a bug report to Embarcadero's Quality Portal.
Update
I tested this in XE7. According to a comment, the defect appears to have been fixed at least in Seattle.

A: A compiler which gives a Access Violation-error is always having a bug. A compiler should never do that but handle every occurring error gracefully.


text:
Q: Potentiometer position with op-amp I would like to measure a 10k ohms linear potentiometer (position) with A/D converter using an op-amp like this :

In my case V+ will be 3,3 volts and Vout need to have maximum of 2,5 volts (which is my A/D converter reference). Can somebody could tell me which value are required for all resistors around the op-amp ?

A: If your ADC can handle source impedance of 2.5K ohms (maximum) you can directly use the pot.
The op-amp can be used as a buffer to minimize variations due to the (typically large) tolerance of the pot element.

simulate this circuit – Schematic created using CircuitLab
If it cannot handle 2.5K then you can add an op-amp voltage follower. In both cases the op-amp needs to be able to operate from 3.3V and in the second case the output needs to be able to swing near ground and the input common mode range include ground (single-supply or rail-to-rail input and output).

A: A series resistor is all that is needed to reduce the potentiometer maximum output voltage.

simulate this circuit – Schematic created using CircuitLab
Figure 1. A resistor will reduce the output value by the ratio \$ \frac {R_2}{R_1+R_2} \$.
$$ \frac {2.5}{3.3} = \frac {R_2}{R_1+R_2} $$
$$ 0.76 = \frac {10k}{R_1+10k} $$
$$ 0.76 R_1 + 7.6k = 10k $$
$$ R_1 = \frac {10k - 7.6k}{0.76} = 3.15\ \text k \Omega $$
There is no need for the op-amp.

A:

simulate this circuit – Schematic created using CircuitLab
I would use elements of the other two answers in the following way. In the schematic R2 is the potentiometer. R1 reduces the 3.3V to 2.49V. The opamp buffer produces a low source impedance to the ADC. Use a rail-rail opamp.


text:
Q: import mod from another package How do I import mod1 from ccc.py?
I have the following dir and files:
proj/
|- aaa/
  |- bbb/
    |- ccc.py
|- ddd/
  |- __init__.py
  |- eee/
    |- __init__.py
    |- mod1.py
    |- fff.py
  |- ggg/
    |- __init__.py
    |- mod2.py

A: You can use it like this:
from proj.aaa.bbb.ccc import mod1

A: assuming your tree files;
you should write in your ccc.py file:
from proj.ddd.eee import mod1

or if you want to import everything:
from proj.ddd.eee.mod1 import *


text:
Q: Return generic of generic I want translate this code in Haskell:
fmap :: (a -> b) -> f a -> f b

to C#. I've tried:
public static T3<T2> Fmap<T1, T2, T3>(Func<T1, T2> f, T3<T1> x)
{
    throw new NotImplementedException();
}

Error: The type parameter 'T3' cannot be used with type arguments

I've tried too:
public static T3<T2> Fmap<T1, out T2, out T3>(Func<T1, T2> f, T3<T1> x)

Error: Invalid variance modifier. Only interface and delegate type
  parameters can be specified as variant.