text:
Q: SearchView return empty listview I have main Activity with SearchView and custom ListView, when I click on SearchView it doesn't filter the elements on ListView but show only one element when I finished writing, and when clearing SearchView it doesn't back to main ListView.
Please help,
Thanks
public class MainActivity extends AppCompatActivity {
    private ListView listView;
    List<WordTranslation> quotes;
    Context context;
    Adapter adapter;
    Button searchBtn;
    ArrayList <WordTranslation> arrayList = new ArrayList<>();
    WordTranslation wordTranslation;
    DatabaseAccess databaseAccess;
    SearchView sv;
    EditText editText;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    public  ArrayList<WordTranslation> getwordtranslation(String SearchItem){
       arrayList.clear();

        Log.e("get word" , "open" );
        wordTranslation = null;
        Cursor cursor = retrieve(SearchItem);
        System.out.println(SearchItem);

        while (cursor.moveToNext()){
            String word = cursor.getString(0);
            String translation = cursor.getString(1);
            WordTranslation wordTranslation1 = new        WordTranslation(word,translation);
            arrayList.add(wordTranslation1);
        }

        ArrayAdapter<WordTranslation> adapter = new Adapter(this, R.layout.activity_list_view_item,arrayList );
        listView.setAdapter(adapter);
        Log.e("get word" , arrayList.toString() );

        return arrayList;
    }

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.ListView);
        listView.setTextFilterEnabled(true);
        sv = (SearchView) findViewById(R.id.search_view);
        DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
        databaseAccess.open();
        databaseAccess.getQuotes();
        quotes = databaseAccess.ShowDictionaryDetails();
        databaseAccess.close();
        ArrayAdapter<String> adapter = new Adapter(this,    R.layout.activity_list_view_item, quotes);
        listView.setAdapter(adapter);

        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(MainActivity.this, "search loading .....", Toast.LENGTH_LONG).show();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
               getwordtranslation(newText);

                listView.clearTextFilter();

                return false;
            }
        });
    }

    public Cursor retrieve(String name){
        DatabaseOpenHelper databaseOpenHelper = new DatabaseOpenHelper(this);
        SQLiteDatabase data =databaseOpenHelper.getReadableDatabase();
        String table = "quotes";
        String where = "word = ? ";
        String [] whereargs = {name};
        Log.e("retrieve", whereargs.toString());
        return data.query(table , null ,where , whereargs ,null, null, null );
    }
}

Log activity
E/get word: open I/SQLiteAssetHelper: successfully opened database quotes.db      E/retrieve: [Ljava.lang.String;@408fb608 E/get word: [] E/get word: open I/SQLiteAssetHelper: successfully opened database quotes.db E/retrieve: [Ljava.lang.String;@40a6f900 E/get word: [] E/get word: open I/SQLiteAssetHelper: successfully opened database quotes.db E/retrieve: [Ljava.lang.String;@40a748b0 E/get word: []

A: This is because you filter even empty string. If the SearchView becomes empty, your retrieve() receives empty string as an argument, and your database query looks like this:
SELECT * FROM quotes WHERE word = ''

And it looks like there is no record with word equals to empty string.
To fix it, in your retrieve() you need to check if name is empty, then select all data without WHERE


text:
Q: Почему приложение не меняется после изменения кода В приложение есть кнопка перехода на новое окно (activity), я изменил обработчик нажатия, но после запуска всё равно остался переход на новое окно
обработка нажатия
private Button passTestButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    addListenerOnButton();
}

public void addListenerOnButton() {
    passTestButton = (Button)findViewById(R.id.passTestButton);
    passTestButton.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    passTestButton.setText("q1");
                    /*Intent intent = new Intent(".PassTestActivity");
                    startActivity(intent);*/

                }
            }
    );
}

A: Вот как у вас:
public class MainActivity extends AppCompatActivity {
    private Button passTestButton = (Button)findViewById(R.id.passTestButton);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        passTestButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        passTestButton.setText("q1");
                        /*Intent intent = new Intent(".PassTestActivity");
                        startActivity(intent);*/

                    }
                }
        );
    }
}

вот как нужно:
public class MainActivity extends AppCompatActivity {
    private Button passTestButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        passTestButton = (Button)findViewById(R.id.passTestButton);
        passTestButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        passTestButton.setText("q1");
                        /*Intent intent = new Intent(".PassTestActivity");
                        startActivity(intent);*/

                    }
                }
        );
    }
}

по логике должно работать нормально и правильно, проверьте должно все быть ок. Если будут вопросы - не стесняйтесь и пишите. Удачи :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Direct3D: Recording to AVI files In follow up to my previous question, I am able to save the backbuffer of a Direct3DDevice to a surface.
I already found the D3DXSaveSurfaceToFile in the DirectX SDK and it works fine! However, I want to record the obtained surfaces to an AVI file.
I also found the AVIFile reference but they are obviously not straight up compatible with DirectX surfaces.
What would be the best way of approaching this problem? I've seen a number of GDI+/MVC based solutions of grabbing HDCs but those are out of the question. I'm also not sure what kind of data AVIFile expects and how to extract it from the D3DSurface.
Please advise! :)
edit:
Post-processing is also an option. I can capture the surface data in a number of formats, specified here, into memory with D3DXSaveSurfaceToFileInMemory. Afterwards, I could compress this data and then store to disk.
How should I be compressing my data? How should I be storing it? Do I store a timestamp along with it? After recording, how should I turn the generated data into an AVI file?

A: The source code at this link will show you how to do it:
http://gpalem.web.officelive.com/SimulationRecording.html
Edit: Well you don't have to do things exactly like that linked code.  You have a D3DSurface so you can just lock it grab the bits and pass them into CAviFile::AppendFrameUsual ... If you want to change its format then use D3DXLoadSurfaceFromSurface. I didn't say the link was a perfect solution but it DOES show you how to write the frames into an AVi file.
Edit2:  As I didn't answer your edit I should do.  Firstly don't bother with compression until you have got uncompressed working.  Compression is a significantly more complicated thing to get right and you won't be able to get proper compression by simply using the various D3DXSurface copying functions.  They don't support the kinds of compression you are after.  D3DX is for 3D rendering and NOT for video compression.
For video compression you are best off using DirectShow as you can, simply, add any compressors you wish.  This will however mean you'll need to write a "source filter" that you can build your graph off.  DirectShow is not an easy thing to use but its very powerful.  As far as writing the "source filter" goes you can check out the "Push Source" example in the windows SDK.  You will need to adapt it to take the data you are retrieving however.
As an aside, going further on my original edit you could use that code as is by intercepting more D3D9 calls.  If you hook the SetRenderTarget calls then you can insert whatever render target you like in there and use the, previously, linked code directly ...


text:
Q: Why does the TIdMailBox.UnseenMsgs property return 0 value? I'm trying to get the number of unread messages of my IMAP mailbox by using TIdIMAP4 from Indy 10.6.0.4975.
The problem is that the UnseenMsgs property returns 0 even when there are some unread messages in the accessed mailbox. This is the code I use:
procedure TForm1.FormClick(Sender: TObject);
var
  TotalMsgs: Integer;
  UnseenMsgs: Integer;
begin
  IdIMAP41.Connect(True);
  IdIMAP41.SelectMailBox('Inbox');

  TotalMsgs := IdIMAP41.MailBox.TotalMsgs; // returns correct value
  UnseenMsgs := IdIMAP41.MailBox.UnseenMsgs; // <- returns always 0

  IdIMAP41.Disconnect(False);
end;

Why does the TIdMailBox.UnseenMsgs property return 0 instead of proper number?

A: Call the StatusMailBox method before you access that property. It is mentioned in the UnseenMsgs property documentation as:

UnseenMsgs is updated when the results from the TIdIMAP4.StatusMailBox
  method are parsed.

So do it like:
IdIMAP41.Connect(True);
IdIMAP41.SelectMailBox('Inbox');
IdIMAP41.StatusMailBox('Inbox', IdIMAP41.MailBox);

UnseenMsgs := IdIMAP41.MailBox.UnseenMsgs;


text:
Q: ¿Cómo hago para mostrar la respuesta AJAX? Durante el proceso de inicio de sesión de la aplicación web, utilizo un sistema de autenticación por token.
Partiendo de una ventana de inicio de sesión, envío una petición al servidor y este me devuelve un token que será necesario para el acceso a rutas protegidas, que irá en las peticiones http siguientes del cliente, en una cabecera x-access-token.
Una vez que tengo el token de sesión, lo que quiero es cargar directamente la página del panel de administración.
Es decir, el cliente inicia sesión, le dan un token, y se va a una ruta protegida pasando ese token.
Actualmente, había pensado en una petición AJAX y luego otra petición más básica, algo como esto:
function autenticarse(){
  $("#credenciales").bind("submit",function() {
    $.ajax({
      url: $('#credenciales').attr('action'),
      data: $('#credenciales').serialize(),
      type: $('#credenciales').attr("method"),
      cache: false,
      success: function (json) {
        if (json.success) {
          var xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              myFunction(this);
            }
          };
          sessionStorage.setItem("tokenGS", json.token);
          xhr.open("GET", "http://localhost:8080/admin/panel", true);
          xhr.setRequestHeader("Content-Type", "application/html");
          xhr.setRequestHeader("x-access-token", sessionStorage.getItem("tokenGS"));
          xhr.send();

          function myFunction(xml) {
            //var xmlDoc = xml.responseXML;
            //parser = new DOMParser();
            //xmlDoc = parser.parseFromString(xhr.responseText,"application/xml");
            //alert(xml.responseText);
            //window.createRequest();
          }

        } else {
          document.location.href="http://localhost:8080/loginErroneo";
        }
      },
      error: function (xhr, status) {
        document.location.href="http://localhost:8080/404";
      }
    });
    return false;
  });
}

Esto se realiza todo correctamente, pero no se me carga la segunda petición, la puedo ver en Firebug en el navegador pero no se me carga.

El servidor, es NodeJS, y devuelve una plantilla EJS con la siguiente instrucción:
res.render('1panel');

¿Cómo hago para que al usuario se le cargue en el navegador la segunda petición que realizo en el código?

A: Por lo que veo el problema está en que tratas de acceder a una propiedad no definida en la función onreadystatechange del objeto xhr. Recuerda que en javascript el ambito de una función define un nuevo contexto para this, en este caso this se refiere a la función callback no al objeto xhr.
Puedes resolverlo cambiando this por xhr y cambiando myFunction(this) por xhr.responseText o xhr.responseXML en estas líneas:
if (this.readyState == 4 && this.status == 200) {
    myFunction(this);
}

para que queden de la siguiente forma:
if (xhr.readyState == 4 && xhr.status == 200) {
    myFunction(xhr.responseText);
}

A: Prueba a depurar paso a paso a ver si en algún momento, alguna variable no tiene el dato que requieres. Por ejemplo en la línea
$('#credenciales').attr('action')

Que realmente tenga una URL correcta
json.success

Que exista y sea true
Y si puedes, ya que estás utilizando jQuery, en lugar de utilizar en la 2a petición XMLHTTPRequest, utiliza de nuevo $.ajax o $.get.

A: espero ayudarte en el tema yo uso con mucha frecnuencia esta porción de código:
  $(document).ready(function () {

   var config = {
    url: '../../aplicacion/crud/index.php',
    variables: 'tabla'
   };
  var fuentedata = sendData(config);
  function  sendData(config)
  {//json captura
   var json = null;
   $.ajax({
    'type': "POST",
    'data': config,
    'async': false,
    'global': false,
    'url': '' + config.url,
    'dataType': "json"
    , 'beforeSend': function (data)
    {
       // console.log('... cargando...');
    }
    , 'error': function (data) {
        //si hay un error mostramos un mensaje
        console.log('Tenemos problemas Houston ' + data);
    },
    'success': function (data) {
        json = data;
    }
    });
    return json;
   }

 });


text:
Q: Different pipe size between Ubuntu and Debian I was testing file transfer with OpenBSD netcat and noticed that it takes a bit more time to transfer the same file on Ubuntu rather than Debian. Using strace, I found that data is transferred in 64k blocks on Ubuntu.
mgamal@ubuntu:~$ strace cat test | nc -vvvv 10.10.172.11 8888
...

read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 65536) = 65536

write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 65536) = 65536

read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 65536) = 65536

write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 65536) = 65536

read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 65536) = 65536

write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 65536) = 65536

On Debian on the other hand:
mgamal@ubuntu:~$ strace cat test | nc -vvvv 10.10.172.11 8888
....
write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072
read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072
write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072
read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072
write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072

I wrote the following piece of code on Debian to check the pipe size:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
    int pipefd[2];
    int size;
    int i;

    pipefd[0] = STDIN_FILENO;
    pipefd[1] = STDOUT_FILENO;

    pipe(pipefd);

    size = fcntl(pipefd[0], F_GETPIPE_SZ);

    printf("%d\n", size);

    size = fcntl(pipefd[1], F_GETPIPE_SZ);

    printf("%d\n", size);

    return 0;
 }

Running it, it still reports 64k
mgamal@debian:~$ ./test
65536
65536

I also tried using something other than netcat to check. And I still see the pipe size being 128k
root@debian:~# strace cat foo | less
...
read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072
write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072
read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072
write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072
read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072
write(1, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072
read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 131072) = 131072

I've tried to check the source packages for netcat, the kernel, glibc to see if the pipe size is set to 128k, or if there are any calls to fcntl() that change the pipe size, but could find no trace.
Why is the pipe size reported as 64k, while actual size is 128k?

A: GNU cat is in the coreutils package. GNU cat does a stat or fstat on its input and output and looks at st_blksize, the optimal blocksize for filesystem I/O.  It then takes the max of that number and a hardwired number and uses that as the buffer size for input and output. This is done in io_blksize.
Ubuntu 14 comes with coreutils 8.21. The minimum blocksize in that version is 64KiB.
Debian 8 comes with coreutils 8.23. The minimum blocksize in that version is 128KiB.


text:
Q: are there easy to customize/extend forum web apps? let's say I want to make a forum that has pretty much all the functionality of a typical high end forum, like phpBB2, but I also want to add a few more features here and there. Maybe I want to add user reputation (kind of like what we have here on StackOverflow) and a button to sort threads or posts based on that in some pages.
Needless to say, I also want to do this without reinventing bicycles or rebuilding pyramids from scratch...
What is the professional approach to this? What would you do if you wanted basically a slightly tweaked, advanced web forum?

A: I would suggest that you take a look at Vanilla Forums:
http://vanillaforums.org/

A: I'm biased but I'd recommend looking at Drupal - you seem to want to build a customized system out of existing components and Drupal's module architecture lets you do this quite easily. There are lots of resources on the web for learning how to build community sites with Drupal that a quick Google search will bring up.
You can then use modules like the User Karma module to create a reputation system

A: Pligg, open source, seems pretty useful for features such as voting up and down posts http://www.pligg.com/about.php .
BBpress http://bbpress.org/ , integrates with Wordpress and allows for plug ins.
Also, https://stackexchange.com/ looks interesting!


text:
Q: mongo db which is runing on ec2 instance , during connection with node app it is saying you can not use ipv4 when my node app trying to connect mongo db url which is runing on ec2 instance , it is saying you can not use ipv4 , i use dns name of mongo , again same issue coming
UNHANDLED REJECTION!  Shutting down...
Error querySrv ENOTFOUND _mongodb._tcp.ec2-52-66-138-70.ap-south-1.compute.amazonaws.com


text: Q: Compiling docs into main project directory folder instead of /target compiled? In order to keep track of all docs by performing a compile and pushing the yaml spec into the repository I was wondering, is it possible to relocate the output OpenAPI spec to, for example, a /openapi folder within the root directory which can be versioned rather than /target?


text:
Q: Couchbase geospatial bounding box query As far as I know, couchbase has support for geospatial data, but I am not sure how to use this.
Does anybody know, if it is possible to query for elements which are inside a bounding box via N1QL SELECT statement in couchbase?
If yes, how would a SELECT statement look like, to query with a bounding box for the elements in the following json?
{
  "type": "Feature",
  "properties": {
    "name": "Bermuda Triangle",
    "area": 1150180
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [-64.73, 32.31],
        [-80.19, 25.76],
        [-66.09, 18.43],
        [-64.73, 32.31]
      ]
    ]
  }
}

{
  "type": "Feature",
  "properties": {
    "name": "Flemish Diamond",
    "area": 2947
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [3.55, 51.08],
        [4.36, 50.73],
        [4.84, 50.85],
        [4.45, 51.30],
        [3.55, 51.08]
      ]
    ]
  }
}

{
  "type": "Feature",
  "properties": {
    "name": "Research Triangle",
    "area": 252
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [-78.93, 36.00],
        [-78.67, 35.78],
        [-79.04, 35.90],
        [-78.93, 36.00]
      ]
    ]
  }
}

A: Couchbase Geospatial queries are only supported through Geospatial Views, not N1QL queries.
You would need to create Geospatial View for your coordinates and query it via the Views API.
You can see more information on Geospatial Views in the Couchbase Server documentation: https://developer.couchbase.com/documentation/server/current/indexes/querying-using-spatial-views.html
It is technically possible to emulate a geospatial query using N1QL, however it would not be backed by a spatial index and would incur a significant performance penalty - especially for polygon data like you've supplied. You can see an article on how to do this with point data here: https://dzone.com/articles/speed-up-spatial-search-in-couchbase-n1ql


text:
Q: How to work with TF Lite library in a c++ project I've been struggling in the last 1-2 days with how to build TensorFlow Lite so I can use it as headers or library in my own C\C++ project.
For example, I have a C++ project with main.cpp with the following code:
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"

int main()
{
    std::unique_ptr<tflite::FlatBufferModel> model;
    model = tflite::FlatBufferModel::BuildFromBuffer(h5_converted_tflite, h5_converted_tflite_len);

    tflite::ops::builtin::BuiltinOpResolver resolver;
    std::unique_ptr<tflite::Interpreter> interpreter;
    tflite::InterpreterBuilder(*model, resolver)(&interpreter);

    // Resize input tensors, if desired.
    interpreter->AllocateTensors();

    float* input = interpreter->typed_input_tensor<float>(0);
    // Fill `input`.

    interpreter->Invoke();

    float* output = interpreter->typed_output_tensor<float>(0);
}

What should I download\build, and from where, so I can successfully compile this code? Currently it says, obviously, that the h files cannot be found, and when I clone the TF repository and add it to the include folders, it doesn't find "flatbuffers.h" file, and when I add it manually, it gives me many linkage errors.
Any help will be appreciated here...
Thanks in advance

A: Try the following code, which has been tested with TensorFlow lite 1.14.0:
std::string str = "model.tflite";
ifstream file(str, std::ifstream::binary);
file.seekg(0, file.end);
int length = file.tellg();
file.seekg(0, file.beg);
char * model_data = new char [length];
file.read (model_data, length);
file.close();
std::unique_ptr<tflite::Interpreter> interpreter;
std::unique_ptr<tflite::FlatBufferModel> model;
tflite::ops::builtin::BuiltinOpResolver resolver;
model = tflite::FlatBufferModel::BuildFromBuffer(model_data, length);
tflite::InterpreterBuilder(*model, resolver)(&interpreter);
interpreter->AllocateTensors();

A: Recently, TFLite supports CMake and it seems that it resolves your dependency issue.
https://www.tensorflow.org/lite/guide/build_cmake#create_a_cmake_project_which_uses_tensorflow_lite


text:
Q: How to declare HTMLElement variable outside of a function in Angular component.ts? I want to declare HTMLElement variables visible to all functions in given class, however i am unable to do so for some reason. Method of declaring it before constructor and then assigning its value in constructor does not work, but when i declare and assign it in a function, for example employeesClick() it works.
I am trying to avoid using multiple instances of same code, as i need to change other buttons based on which one was clicked.
There are no errors, but nothing happens. How do i do this?
export class HeaderComponent implements OnInit {

  projects:HTMLElement;
  constructor() {
    this.projects=document.getElementById('projects');
  }

  ngOnInit() {
  }

  projectsClick(){
    this.projects.style.color="#DEA731";
  }
  employeesClick(){
    var employees : HTMLElement = document.getElementById('employees');
    employees.style.color="#DEA731";
  }
}

A: You can use the @ViewChild directive. Just create a reference for a button and get an element in your .ts file.
For example, html looks like:
<button #btn> ... </button>

In your .ts:
export class HeaderComponent implements OnInit {

@ViewChild('btn') buttonRef: ElementRef;

...
someMethod(){
  //do something like change a text color of your button
  this.buttonRef.nativeElement.style.color = "#aaa";
}

The buttonRef is a global variable in the class and you can use it where you need.
Don't forget to import ViewChild and ElementRef from @angular/core;


text:
Q: Ubuntu 13.04 Multi Monitor Dell precision m4600 nvidia optimus I've been fighting for two days now trying to get mulitmonitor support for the my dell precision m6400 with a nvidia quadro 1000m.
I recently saw that Nvidia's 319 drivers supported optimus, so naively I went in bright eyed and bushy tailed down the rabbit hole...
I am currently in a docking station using 2 external monitors (over DVI) connected to the dock and I'd like to use the laptop screen as my 3rd monitor.
I've tried using bumblebee and not, I've tried using the xorg.config I found on nvidia's website, I've tried using the ubuntu software center's additional drivers section. My machine is in such a bad state, I'm not sure where to go from here.
There was a time when I was able to get just get the two external monitors with a blank laptop screen and even getting back to that would be a huge.
Any advice would be really appreciated. Please let me knwo what further information is required to help solve this problem.
Thanks

A: what package of nvidia did you try ?
there is acutally a newer package of nvidia-driver
for optimus Cuda cards : NVIDIA_CUDA_SDK_1.1_Beta_Linux.run

A: I'd suggest you turn off optimus (BIOS settings) and reinstall from scratch. I have the same machine and it's a nightmare. The downside is the impact it has to battery life. In my case, I value stability more than power efficiency


text:
Q: $\overline\pi$ vs. $\check\pi$ Let $\pi$ be the automorphic representation of ${\rm GL}_2$ or $B^\times$ ($B$ an indefinite quaternion algebra over $\Bbb Q$) of central character $\varepsilon$ attached to some holomorphic newform $f$ of nebentypus $\varepsilon$.
Given $\pi$ we can consider

*

*the contragredient (or "dual") representation $\check\pi$ which is isomorphic to $\pi\otimes\varepsilon^{-1}$;

*the "complex conjugate" representation $\overline\pi$ (thinking of $\pi$ as an irreducible component of $L^2(G_{\Bbb Q}\backslash G_{\Bbb A},\varepsilon)$ we can define $\overline\pi=\{\overline F\mid F\in\pi\}$).
Both $\check\pi$ and $\overline\pi$ have central character $\varepsilon^{-1}$ (because $\varepsilon$ is unitary) and both definitions are involutory. Is there a chance that $\check\pi\simeq\overline\pi$?
This could be checked at the level of local components. Given $\pi=\bigotimes_{p\leq\infty}\pi_p$, it is clear that $\check\pi=\bigotimes_{p\leq\infty}(\pi_p\otimes\varepsilon_p^{-1})$ but it is not obvious to me the effect of $\pi\mapsto\overline\pi$ on local components.
Clearly, by multiplicity one, an identity of local components could be checked just for unramified primes.


text:
Q: npm install error: 'ENOENT: no such file or directory' I donwload a project form somewhere , and I run 'npm install' , I got this:
npm ERR! path /Users/<username>/package.json
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall open
npm ERR! enoent ENOENT: no such file or directory, open '/Users/<username>/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

but I have checked the project , there were a package.json file there:
/Users/username/Desktop/Directory/Projects/ProjectName/package.json
do I need to use npm init to create another one?

A: cd to the directory where package.json is (/Users/username/Desktop/Directory/Projects/ProjectName/ in your case) and run npm install again.

A: Simplest solution:
Simply run npm init and it will walk you through the process of creating package.json file


text:
Q: Find the intersection coordinate of a line and a 3D surface defined by a contour plot I have two points, for instance {1, 1, 1} and {10, 11, 15} that connected to form a line. I also have an enclosed surface region got by a contour plot. How can I find the coordinate of the intersection of the line and the surface?
I tried the function RegionIntersection but it doesn't work I guess because the two regions have different embedded dimensions. And even if it works I don't know how to extract the coordinate.
Could somebody help me with this?

The code to get the region is like:
    Iso = ListContourPlot3D[DataTable, Contours ->
          {0.5}, ContourStyle -> {Yellow, Opacity[0.7]}, DataRange ->
          {{x0,x1}, {y0,y1}, {z0,z1}}, Mesh -> None, BoxRatios -> {x1-
          x0, y1-y0, z1-z0}];

    RegionSurface = RegionBoundary[BoundaryDiscretizeGraphics[Iso]];

    RegionIntersection[RegionSurface, Region[Line[{{0, 0, 0}, {10, 11,
    19}}]]]

where the DataTable is a 3D table containing volumetric data read in from a file. One example of the RegionSurface is given by the following picture:


text:
Q: Transfer domain and DNS from Azure to Cloudflare I want to transfer a domain (.uk) from Azure to Cloudflare. Both the domain and DNS hosting is on Azure.

*

*Cloudflare require the DNS resolution to be moved to them prior to the domain transfer.

*Cloudflare need the existing Azure DNS servers removed from the DNS record and replaced with Cloudflare ones.

Editing the DNS record in Azure doesn't allow the Azure DNS servers to be removed, only the Cloudflare ones to be added at the end. This isn't sufficient for Cloudflare to allow the transfer.
This question and this question both state to select the "Advanced Management Portal" under "Domain Management". But I don't have that option, only "Domain Renewal".
Where is the new management screen to do what I need?

A: *

*The "Advanced Management Portal" no longer shows in the UI (for reasons unknown), but it can be accessed here: https://dcc.secureserver.net/domains

*My Azure login email wasn't recognised as a valid username. Use"Need to find your username" and follow the instructions, the result was a numeric ID customer #.

*Use "Need to find your password" to reset the password for that customer #.

*Login using the new details
Once logged in the portal allows you to:

*

*Fully manage the DNS server settings for the domain (removing the Azure entries)

*Removing domain locking (to allow transfer)

*Allow the setting of the IPS tag to allow the domain transfer to Cloudflare


text:
Q: Database enum fields I'm trying to simulate a Java Enum type in a Microsoft SQL Server table:
CREATE TABLE ResultType(
    result TINYINT PRIMARY KEY,
    description VARCHAR(30)
);

INSERT INTO ResultType
VALUES (0, 'Pass with distinction'),
       (1, 'Pass with credit'),
       (2, 'Pass'),
       (3, 'Fail first attempt),
       (4, 'Fail and debar');

CREATE TABLE CandidateResult(
    candidate_id INT PRIMARY KEY,
    candidate_name NVARCHAR(100),
    result TINYINT References ResultType(result)
)

Now, what is the best practice for ensuring that the ResultType table is consistent with a Java ResultType enum?
enum ResultType { DISTINCTION, CREDIT, PASS, FAIL, DEBAR };
...
ResultType result;
if (mark > 90) {
    result = ResultType.DISTINCTION;
} else if (mark > 70)
    result = ResultType.CREDIT;
}
etc...
preparedStatement.setInt(1, result.ordinal)

The above doesn't look robust enough to me: I have to manually and constantly ensure that the enum agrees with the values in the ResultType table. How should I ensure this correspondence always holds, but without creating a performance overhead?

A: I'd good way, based on dictionary table ResultType. And you can build SQL reports with human readable name of types. Also using of table ResultType can provides same additional information, 'outdated' type for example.
select cr.*, ct.description
from CandidateResult cr
join ResultType ct
on cr.result = ct.result
;


text:
Q: How can I filter nested lists in java I have list of Recipes and List of Alergens from user and I need to return List of Recipes in with products there is not any alergen from alergensOfUser list.
Each Recipe contains list of Products and each Product contains list of Alergens. How can I do it?
public class Recipe {

    ...

    private List<Product> products;

}

public class Product {

    ...

    private List<Alergen> alergens;

}

A: Use Java streams.
What we need to get is if recipe is made of products for which each of the product has no alergen in user's defined alergen.
List<Recipe> recipesList;
List<Alergen> userAllergens;

public List<Recipe> getRecipesForUser() {
    return recipesList.stream()
            .filter(recipe -> isNotMadeOfAlergen(recipe))
            .collect(Collectors.toList());
}

public boolean isNotMadeOfAlergen(Recipe recipe) {
    List<Product> productList = recipe.products;

    return productList.stream().noneMatch(product -> containsAlergen(product));
}

public boolean containsAlergen(Product product) {
    List<Alergen> alergenList = product.alergens;

    return alergenList.stream()
            .anyMatch(alergen -> userAllergens.contains(alergen));
}

A: If you want to avoid 3 levels of nested streams, you can do this
  List<Recipe> userEnteredRecipes; //populate it
  List<Alergen> userEnteredAlergens; //populate it
  List<Product> allProducts; //populate it

  // first get products which have these alergens
  List<Product> productsToAvoid =
      allProducts.stream()
          .filter(e -> e.getAlergens().stream().anyMatch(userEnteredAlergens::contains))
          .collect(Collectors.toList());

  // get the recipes which do not have these alergens
  List<Recipe> filteredRecipes =
      userEnteredRecipes.stream()
          .filter(e -> (e.getProducts().stream().noneMatch(productsToAvoid::contains)))
          .collect(Collectors.toList());


text:
Q: Dynamically set the size of buffered image I'm using this to set the size of my buffered image.
Dimension imgDim = new Dimension(700, 380);

BufferedImage gridImage = new BufferedImage(imgDim.width, imgDim.height,
    BufferedImage.TYPE_INT_RGB);

instead of this, I would like to set the size of the image using something like:
Dimension imgDim = d;

BufferedImage gridImage = new BufferedImage(d.width/8, d.height/8,
    BufferedImage.TYPE_INT_RGB);

but I'm getting negativeArraySizeException
d is the dimensions of my JFrame which I'm getting using getMaximumSize() method
when I print out the value of d.width/8 its something like 268435455 which I can't make sense of. Is there another way to do this please help
Thank you

A:
d is the dimensions of my JFrame which I'm getting using getMaximumSize() method

You would get d using the getSize() method after you call the pack() method or setSize() method.

A: You should use getSize() instead of getMaximumSize().
If you don't setPreferredSize for your JFrame, getMaximumSize() will return a very big number. See Component.getMaximumSize()
getSize() returns your JFrame's current size
See Component JavaDocs


text:
Q: ISP Config tells me to delete index.html from my web directory / And it doesn't exist I recently copied a wordpress directory from a subdomain to another different ,
From < name >.lalala.com  , to < second-name >.lalala.com ....
As well as I got a Wordpress installed and working.
Inside both subdomains, in < root >/web subfolder I got WP installed.
But, in the new/second subdomain where I pasted WP content, I get this message...

So I look for the index.html, and doesn't exists in web folder and any folder inside.
I check .htaccess and don't have fault about it.
So I don't know where to continue here... Why this?
Some help? What can be?

Here I post my web folder with files as any other Wordpress folder. What's wrong?
I Can access database, I got data copied too... As well as wp-options for url...


text:
Q: Inserting multiple rss feeds into MYSQL with simplexml Below is my code to parse multiple rss feeds into a mysql db.
I do something wrong in the foreach part I think, since there is no output.
The db however, gets filled. When using 1 feed, the script works fine.
Anybody sees what I do wrong? Many thanks in advance :)
$feeds = ('https://www.ictu.nl/rss.xml', 'http://www.vng.nl/smartsite.dws?id=97817');
$xml = simplexml_load_file($feeds);

foreach($xml->channel->item as $item)
{
$date_format = "j-n-Y"; // 7-7-2008
echo date($date_format,strtotime($item->pubDate));
         echo 'link.'" target="_blank">'.$item->title.'';
         echo '
' . $item->description . '
';

mysql_query("INSERT INTO rss_feeds (id, title, description, link, pubdate)
VALUES (
    '',
    '".mysql_real_escape_string($item->title)."',
    '".mysql_real_escape_string($item->description=htmlspecialchars(trim($item->description)))."',
    '".mysql_real_escape_string($item->link)."',
    '".mysql_real_escape_string($item->pubdate)."')");
}

A: Try this:
<?php
$feeds = array('https://www.ictu.nl/rss.xml', 'http://www.vng.nl/smartsite.dws?id=97817');
foreach( $feeds as $feed ) {
    $xml = simplexml_load_file($feed);

    foreach($xml->channel->item as $item)
    {
    $date_format = "j-n-Y"; // 7-7-2008
    echo date($date_format,strtotime($item->pubDate));
             echo 'link.'" target="_blank">'.$item->title.'';
             echo '
' . $item->description . '
';

    mysql_query("INSERT INTO rss_feeds (id, title, description, link, pubdate)
    VALUES (
        '',
        '".mysql_real_escape_string($item->title)."',
        '".mysql_real_escape_string($item->description=htmlspecialchars(trim($item->description)))."',
        '".mysql_real_escape_string($item->link)."',
        '".mysql_real_escape_string($item->pubdate)."')");
    }
}
?>

Hope it helps.


text:
Q: How do I convert from a semi-annual interest rate to montly? On a practice exam I am given a $.06$ compounded semi-annually and need it converted to monthly. I assumed it would be $.005$ because it has annual percentage of $.06/12$ but my answer is slightly off so I wanted to have this verified

A: The equation for semi-annually is $A=P(1+\frac{r}{2})^{2t} $ while for monthly it is $A=P(1+\frac{R}{12})^{12t}$ . Making these equations equal with r = 0.06 yields
$$P(1+\frac{0.06}{2})^{2t}=P(1+\frac{R}{12})^{12t}$$
If we solve the above equation we get R = 0.05926…

A: If we have interest rate $i$ compounded in $n$ periods per year; the effective per annum interest is given by
$$(1+\frac{i}{n})^n$$
If we want to calculate some $i'$ associated with an $n'$ for the same per annum rate we must set the two to be equal:
$$(1+\frac{i}{n})^n=(1+\frac{i'}{n'})^{n'}$$
Given that in your case you know $n'$ that leaves 1 equation, 1 variable; easy to solve.


text:
Q: how to limit data inside foreach value if there is condition applied? In my blade template, I have applied foreach loop . And the data from foreach loop is from relation that I want to show. In that single loop I have to show three different type of data by applying IF condition. From my backend i have passed whole collection without limiting or pagination to front. And i want to limit data in my blade template.
blade view

@foreach($ft->menus as $menu)
    @if($menu->foodtype_id == $ft->id)
            //want to limti data here
            // for every food type i want to show 6 data
    @endif
@endforeach

controller page
$data['food_type'] = FoodType::with('menus')->get();

A: if i understood you correctly, you want to show 6 relationship rows for each food type. you have to check for current key in the loop then.
@foreach ($data['food_type'] as $ft)
    @foreach ($ft->menus as $key => $menu)
        @if ($key < 6)
            {{ $menu->attribute }}
        @else
            @break
        @endif
    @endforeach
@endforeach

this will show you the first six rows from the relationship. and when it reaches the limit, it will break the foreach loop.
you can query the relationship too.
@foreach ($ft->menus()->limit(6)->get() as $menu)
    {{ $menu->attribute }}
@endforeach


text:
Q: Geometric pattern quality and filling On the image above there is some geometrical pattern. Model a distance is known. Points are not in model distance strictly.

I want to:

*

*calculate each point quality (real distance between points is not a) the better point fits to pattern better quality coeficient it should have (I've tried to take distance and 45deg angle)

*eliminate wrong points (I've marked it with red) - it's connected with pattern quality computing

What I've tried so far:

*

*Take each point with each other

*Calculate distance and angle between them

*Take only points neighbour to current point (which distance is between a - delta and a + delta

*Quality is realDistance/modelDistance * realAngle/modelAngle

Why it failed:

*

*Good points quality was strongly decreased with bad points in neighbourhood

*If bad point has only one neighbour and the distance and angle was ok its quality was ok.

So the question is: what is the best algorithm to calculate points quality in this case, and fill pattern. Pattern should be filled by averaging position of element taking in account neighbours positions. The best answer will be pseudocode or code or reference to some known algorithm which can be helpful in this case.
Question is a little bit related with my previous question Filling rectangle with points pattern but the filling could not be done with wrong quality points.

A: If the error/distortion of the points does not get bigger when you go from left to right or top to bottom (i.e. the average distance a between neighbouring good points is known exactly enough), you can try the following:

*

*bring each point Pi into the square [0,a[ x [0,a[ by taking the remainder of x and y coordinates when dividing through a (generating Qi). Thus the good points will more or less be mapped onto one point.

*Among these generated points Qi choose one point R with the closest neighbours (e.g. sum up 1/distance for all distances to other points Qj, j≠ i, and choose the one with maximal sum).

*Now you can distinguish between good and bad points Pi by looing at the distances Qi to R. (Points Pi whose corresponding Qi is close to R will be good points.)

If the point R (with the closest neighbours) has a coordinate close to 0 or a (i.e. R is close to the border of the square [0,a[ x [0,a[), you better start from the beginning and add a/2 to the corresponding coordinate (of each Pi) before computing the remainder, in order to bring the point R more to the center of the square. (Or you manage to compute the minimal distance of the different possibilities of leaving the square [0,a[ x [0,a[ on one side and come back into it on the opposite side.)

A: The good points seem to be aligned along a grid. The grid lines can be found using a line fitting algorithm using RANSAC. RANSAC line fitting is a probabilistic algorithm. You will have to repeat it until you find a line that is almost horizontal or vertical. Take the points on/near this line out and go for the next grid line. Depending on your problem characteristics you will stop looking for new grid lines if too few points are left or too few points are on/near one line. The remaining points are the bad ones. When you take the intersections of the found grid lines and there is no point (from all the original ones) near the intersection, then you can fill in a point here.


text:
Q: Преобразование money к numeric PostgreSQL Есть таблица:
\d money
                              Таблица "public.money"
Столбец  |           Тип            |                    Модификаторы

----------+--------------------------+----------------------------------------------------
id       | integer                  | NOT NULL DEFAULT nextval('money_id_seq'::regclass)
type     | smallint                 |
count    | money                    |
comment  | text                     |
time     | timestamp with time zone | NOT NULL DEFAULT now()
username | integer                  | NOT NULL

Индексы:
    "money_pkey" PRIMARY KEY, btree (id)
Ограничения-проверки:
    "money_count_check" CHECK (count > 0::money)
Ограничения внешнего ключа:
    "money_type_fkey" FOREIGN KEY (type) REFERENCES types(id) ON DELETE RESTRICT
    "money_username_fkey" FOREIGN KEY (username) REFERENCES users(id)

Хочу сделать в колонке count поменять тип данных с money на numeric.
Делаю запрос:
ALTER TABLE money ALTER COLUMN count SET DATA TYPE NUMERIC(2) USING count::money::numeric;

И получаю ошибку:
ОШИБКА:  оператор не существует: numeric > money
ПОДСКАЗКА:  Оператор с данными именем и типами аргументов не найден. Возможно, вам следует добавить явные приведения типов.

Как правильно преобразовать тип колонки?

A: Посмотрите внимательнее на текст ошибки:

ОШИБКА:  оператор не существует: numeric > money

Почему ищется оператор сравнения?

"money_count_check" CHECK (count > 0::money)

А вот почему, у вас добавлено ограничение на данные.
Вам необходимо удалить это ограничение и добавить новое после смены типа данных
begin;
alter table money drop constraint money_count_check;
alter table money alter column count set data type numeric;
alter table money add constraint money_count_check check (count > 0::numeric);
commit;

Обратите внимание, такие действия на большой таблице могут выполняться долго и заблокируют все пишущие операции.
И что более важно - вы действительно хотели изменить тип данных на numeric(2)? Т.е. хранить значения в диапазоне от -99 до 99 без дробной части? (плюс check отрезающий отрицательные значения) Для такого диапазона используйте smallint - это простой тип данных в отличии от numeric и занимает меньше места. (2 байта вместо, если не ошибаюсь, 16 для numeric(2))


text:
Q: How to find ideal number of parallel processes to run with python multiprocessing? Trying to find out the correct number of parallel processes to run with python multiprocessing.
Scripts below are run on an 8-core, 32 GB (Ubuntu 18.04) machine. (There were only system processes and basic user processes running while the below was tested.)
Tested multiprocessing.Pool and apply_async with the following:
from multiprocessing import current_process, Pool, cpu_count
from datetime import datetime
import time

num_processes = 1 # vary this

print(f"Starting at {datetime.now()}")
start = time.perf_counter()

print(f"# CPUs = {cpu_count()}") # 8
num_procs = 5 * cpu_count() # 40

def cpu_heavy_fn():
    s = time.perf_counter()
    print(f"{datetime.now()}: {current_process().name}")
    x = 1
    for i in range(1, int(1e7)):
        x = x * i
        x = x / i
    t_taken = round(time.perf_counter() - s, 2)
    return t_taken, current_process().name

pool = Pool(processes=num_processes)

multiple_results = [pool.apply_async(cpu_heavy_fn, ()) for i in range(num_procs)]
results = [res.get() for res in multiple_results]
for r in results:
    print(r[0], r[1])

print(f"Done at {datetime.now()}")
print(f"Time taken = {time.perf_counter() - start}s")

Here are the results:
num_processes total_time_taken
1 28.25
2 14.28
3 10.2
4 7.35
5 7.89
6 8.03
7 8.41
8 8.72
9 8.75
16 8.7
40 9.53

The following make sense to me:

*

*Running one process at a time takes about 0.7 seconds for each process, so running 40 should take about 28s, which agrees with what we observe above.

*Running 2 processes at a time should halve the time and this is observed above (~14s).

*Running 4 processes at a time should further halve the time and this is observed above (~7s).

*Increasing parallelism to more than the number of cores (8) should degrade performance (due to CPU contention) and this is observed (sort of).

What doesn't make sense is:

*

*Why does running 8 in parallel not twice as fast as running 4 in parallel i.e. why is it not ~3.5s?

*Why is running 5 to 8 in parallel at a time worse than running 4 at a time? There are 8 cores, but still why is the overall run time worse? (When running 8 in parallel, htop showed all CPUs at near 100% utilization. When running 4 in parallel, only 4 of them were at 100% which makes sense.)

A:
Q : "Why is running 5 to 8 in parallel at a time worse than running 4 at a time?"

Well, there are several reasons and we will start from a static, easiest observable one :
Since the silicon design ( for which they used a few hardware tricks ) does not scale beyond the 4.
So the last Amdahl's Law explained & promoted speedup from just +1 upscaled count of processors is 4 and any next +1 will not upscale the performance in that same way observed in the { 2, 3, 4 }-case :
This lstopo CPU-topology map helps to start to decode WHY ( here for 4-cores, but the logic is the same as for your 8-core silicon - run lstopo on your device to see more details in vivo ) :
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Machine (31876MB)                                                                                │
│                                                                                │
│ ┌────────────────────────────────────────────────────────────┐                      ┌───────────────────────────┐ │
│ │ Package P#0                                                │  ├┤╶─┬─────┼┤╶───────┤ PCI 10ae:1F44             │ │
│ │                                                            │      │               │                           │ │
│ │ ┌────────────────────────────────────────────────────────┐ │      │               │ ┌────────────┐  ┌───────┐ │ │
│ │ │ L3 (8192KB)                                            │ │      │               │ │ renderD128 │  │ card0 │ │ │
│ │ └────────────────────────────────────────────────────────┘ │      │               │ └────────────┘  └───────┘ │ │
│ │                                                            │      │               │                           │ │
│ │ ┌──────────────────────────┐  ┌──────────────────────────┐ │      │               │ ┌────────────┐            │ │
│ │ │ L2 (2048KB)              │  │ L2 (2048KB)              │ │      │               │ │ controlD64 │            │ │
│ │ └──────────────────────────┘  └──────────────────────────┘ │      │               │ └────────────┘            │ │
│ │                                                            │      │               └───────────────────────────┘ │
│ │ ┌──────────────────────────┐  ┌──────────────────────────┐ │      │                                             │
│ │ │ L1i (64KB)               │  │ L1i (64KB)               │ │      │               ┌───────────────┐             │
│ │ └──────────────────────────┘  └──────────────────────────┘ │      ├─────┼┤╶───────┤ PCI 10bc:8268 │             │
│ │                                                            │      │               │               │             │
│ │ ┌────────────┐┌────────────┐  ┌────────────┐┌────────────┐ │      │               │ ┌────────┐    │             │
│ │ │ L1d (16KB) ││ L1d (16KB) │  │ L1d (16KB) ││ L1d (16KB) │ │      │               │ │ enp2s0 │    │             │
│ │ └────────────┘└────────────┘  └────────────┘└────────────┘ │      │               │ └────────┘    │             │
│ │                                                            │      │               └───────────────┘             │
│ │ ┌────────────┐┌────────────┐  ┌────────────┐┌────────────┐ │      │                                             │
│ │ │ Core P#0   ││ Core P#1   │  │ Core P#2   ││ Core P#3   │ │      │     ┌──────────────────┐                    │
│ │ │            ││            │  │            ││            │ │      ├─────┤ PCI 1002:4790    │                    │
│ │ │ ┌────────┐ ││ ┌────────┐ │  │ ┌────────┐ ││ ┌────────┐ │ │      │     │                  │                    │
│ │ │ │ PU P#0 │ ││ │ PU P#1 │ │  │ │ PU P#2 │ ││ │ PU P#3 │ │ │      │     │ ┌─────┐  ┌─────┐ │                    │
│ │ │ └────────┘ ││ └────────┘ │  │ └────────┘ ││ └────────┘ │ │      │     │ │ sr0 │  │ sda │ │                    │
│ │ └────────────┘└────────────┘  └────────────┘└────────────┘ │      │     │ └─────┘  └─────┘ │                    │
│ └────────────────────────────────────────────────────────────┘      │     └──────────────────┘                    │
│                                                                     │                                             │
│                                                                     │     ┌───────────────┐                       │
│                                                                     └─────┤ PCI 1002:479c │                       │
│                                                                           └───────────────┘                       │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

A closer look, like the one from a call to hwloc-tool: lstopo-no-graphics -.ascii, shows where mutual processing independence ends - here at a level of shared L1-instruction-cache ( the L3 one is shared either, yet at the top of the hierarchy and at such a size that bothers for large problems solvers only, not our case )

Next comes a worse observable reason WHY even worse on 8-processes :

Q : "Why does running 8 in parallel not twice as fast as running 4 in parallel i.e. why is it not ~3.5s?"

Because of thermal management.

The more work is loaded onto CPU-cores, the more heat is produced from driving electrons on ~3.5+ GHz through the silicon maze. Thermal constraints are those, that prevent any further performance boost in CPU computing powers, simply because of the Laws of physics, as we know them, do not permit to grow beyond some material-defined limits.
So what comes next?
The CPU-design has circumvented not the physics ( that is impossible ), but us, the users - by promising us a CPU chip having ~3.5+ GHz ( but in fact, the CPU can use this clock-rate only for small amounts of time - until the dissipated heat does not get the silicon close to the thermal-limits - and then, the CPU will decide to either reduce its own clock-rate as an overheating defensive step ( this reduces the performance, doesn't it? ) or some CPU-micro-architectures may hop ( move a flow of processing ) onto another, free, thus cooler, CPU-core ( which keeps a promise of higher clock-rate there ( at least for some small amount of time ) yet also reduces the performance, as the hop does not occur in zero-time and does not happen at zero-costs ( cache-losses, re-fetches etc )
This picture shows a snapshot of the case of core-hopping - cores 0-19 got too hot and are under the Thermal Throttling cap, while cores 20-39 can ( at least for now ) run at full speed:

The Result?
Both the thermal-constraints ( diving CPU into a pool of liquid nitrogen was demonstrated for a "popular" magazine show, yet is not a reasonable option for any sustainable computing, as the mechanical stress from going from deep frozen state into a 6+ GHz clock-rate steam-forming super-heater cracks the body of the CPU and will result in CPU-death from cracks and mechanical fatigue in but a few workload episodes - so a no-go zone, due to negative ROI for any serious project ).
Good cooling and right-sizing of the pool-of-workers, based on in-vivo pre-testing is the only sure bet here.
Other architecture :

A: Most likely cause is that you are running the program on a CPU that uses simultaneous multithreading (SMT), better known as  hyper-threading on Intel units. To cite after wiki, for each processor core that is physically present, the operating system addresses two virtual (logical) cores and shares the workload between them when possible. That's what's happening here.
Your OS says 8 cores, but in truth it's 4 cores with SMT. The task is clearly CPU-bound, so any increase beyond physical number of cores does not bring any benefit, only overhead cost of multiprocessing. That's why you see almost linear increase in performance until you reach (physical!) max. number of cores (4) and then decrease when the cores needs be shared for this very CPU-intensive task.


text:
Q: When hovered, navigation bar elements changing position. Why? So, my goal is to create a simple navigation bar with centered links/elements. I kinda succeeded... Kinda because when i set the floating option it changes spaces between elements and twitches the text out of position (run the snippet to see the efect).
Wanna have some space between the words, but to stay fixed when floated over or activated/selected.
I tried to make it work with styling only ul and li tags but it didnt work, so i tried placing the li tags into separate divisions. Still no success.
Looked through every possible solution i could think of - adding margins, padding, setting them to auto, looked through similar questions here and around web and i got nothing.
Obviously i'm missing something and i would appreciate your help very much so i can continue working on my website.
Here is the code:

* {
  box-sizing: border-box;
}

body {
 margin: 0;
 padding: 0;
 background: #ccc;
}

.nav ul {
 list-style: none;
 margin: 0;
 position: fixed;
 height: 85px;
 width: 100%;
 text-align: center;
 background-color: #002345;
}

.about {
 font-family: 'Baloo';
 font-size: 24px;
 color: #fff;
 display: inline-block;
 line-height: 85px;
 height: 85px;
 margin-left: 10px;
 margin-right: 10px;
}

.portfol {
 font-family: 'Baloo';
 font-size: 24px;
 color: #fff;
 display: inline-block;
 line-height: 85px;
 height: 85px;
 margin-left: 10px;
 margin-right: 10px;
}

.cont {
 font-family: 'Baloo';
 font-size: 24px;
 color: #fff;
 display: inline-block;
 line-height: 85px;
 height: 85px;
 margin-left: 10px;
 margin-right: 10px;
}

.active {
 display: block;
 padding-left: 15px;
 padding-right: 15px;
 background-color: #fff;
 color: #002345;
}

a:hover {
 display: block;
 padding-left: 15px;
 padding-right: 15px;
 background-color: #777;
 color: #002345;
}

 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>PortfolioPage</title>

ABOUT ME

PORTFOLIO

CONTACT

A: it happens because you have added padding on the :hover state but it is not present in the normale state rule...
a {
    padding-left: 15px;
    padding-right: 15px;
}
a:hover {
    display: block;
    /*padding-left: 15px;
    padding-right: 15px;*/
    background-color: #777;
    color: #002345;
}

A: It is because in your hover class you are adding padding to the a tag, add them by default like the example

* {
  box-sizing: border-box;
}

body {
 margin: 0;
 padding: 0;
 background: #ccc;
}

.nav ul {
 list-style: none;
 margin: 0;
 position: fixed;
 height: 85px;
 width: 100%;
 text-align: center;
 background-color: #002345;
}

.about {
 font-family: 'Baloo';
 font-size: 24px;
 color: #fff;
 display: inline-block;
 line-height: 85px;
 height: 85px;
 margin-left: 10px;
 margin-right: 10px;
}

.portfol {
 font-family: 'Baloo';
 font-size: 24px;
 color: #fff;
 display: inline-block;
 line-height: 85px;
 height: 85px;
 margin-left: 10px;
 margin-right: 10px;
}

.cont {
 font-family: 'Baloo';
 font-size: 24px;
 color: #fff;
 display: inline-block;
 line-height: 85px;
 height: 85px;
 margin-left: 10px;
 margin-right: 10px;
}

.active {
 display: block;
 padding-left: 15px;
 padding-right: 15px;
 background-color: #fff;
 color: #002345;
}
a{
     padding-left: 15px;
     padding-right: 15px;
}
a:hover {
 display: block;
 background-color: #777;
 color: #002345;
}

 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>PortfolioPage</title>

ABOUT ME

PORTFOLIO

CONTACT

A: just remove
padding-left: 15px;
padding-right: 15px;

from
a: hover


text:
Q: Javascript Regex: find & REPLACE letters that repeat LESS THAN a certain number of times This question is a derivative from another one here:
Say, for the string "lllrrrrrrrruuddddr", how to replace those letters that repeat less than 4 times with "-", thus resulting in "---rrrrrrrr--dddd-".

A: The easiest way is the simplest way.

*

*[a-zA-Z] matches a single ASCII letter

*([a-zA-Z]) is a capturing group

*\1 is a backreference that tells us to match again exactly what was matched by capturing group #1 again

*\1* tells us to match that backreference zero or more times

Then you just need this:
function replaceRunsWithLengthLessThan( s, n, r ) {
    const replaced = typeof(s) !== "string"
      ? s
      : s.replace( rxSingleLetterRun, m => m.length < n ? r : m )
      ;
    return replaced;
  }
  const rxSingleLetterRun = /([a-zA-Z])\1*/ig;

which can be invoked as
const orig = 'aaaa bbb cc d eeeeee'
const repl = replaceRunsWithLengthLessThan( orig, 4, '-');

and which produces the expected value: aaaa - - - eeeeee.
Edited to note: If you want to replace the short runs with as many dashes as the length of the run, you just need to change
s.replace( rxSingleLetterRun, m => m.length < n ? r : m )

with
s.replace( rxSingleLetterRun, m => m.length < n ? r.repeat(m.length) : m )


text:
Q: Java RegEx removing "/*....*/" and "{.....}" I get the error: "Invalid ecape sequence on this regex:
(\/\*[^/*]*(?:(?!\/\*|\*\/)[/*][^/*]*)*\*\/)|(\{.*?\})

Are there any other regexes that are more suitable or what can I do to fix this regex?

A: You need to escape the backslashes one more time.  This is a "feature" of Java's strings.  Java "consumes" the backslashes that you have written because it recognizes special characters like '\t'.  When it sees, for example '\/' at the beginning of your regex, it thinks you're asking for a special character, and it complains because this sequence is not valid for that purpose.  To get the backslash considered in the regex, you need '\\'.
That being said, this entire approach to handling comments and braces is not going to work generally because it's going to have trouble with a variety of cases like nested blocks in braces. (Just to name one of many.)

A: (\/\*[^\/*]*(?:(?!\/\*|\*\/)[\/*][^\/*]*)*\*\/)|(\{.*?\})

This is the correct regex, you missed escaping the forward slashes which represent the start and end of a regex sequence.
Here is a simplified version (\/\*.*\*\/|\{.*\})


text:
Q: ImportError: No module named 'spiders' On the command line I'm executing the following simple attempt to invoke scrapy:
scrapy version

I get the following error:
$ scrapy version
Traceback (most recent call last):
  File "/Users/nathanielford/virtualenvironments/crawler/bin/scrapy", line 11, in <module>
    sys.exit(execute())
  File "/Users/nathanielford/virtualenvironments/crawler/lib/python3.5/site-packages/scrapy/cmdline.py", line 141, in execute
    cmd.crawler_process = CrawlerProcess(settings)
  File "/Users/nathanielford/virtualenvironments/crawler/lib/python3.5/site-packages/scrapy/crawler.py", line 238, in __init__
    super(CrawlerProcess, self).__init__(settings)
  File "/Users/nathanielford/virtualenvironments/crawler/lib/python3.5/site-packages/scrapy/crawler.py", line 129, in __init__
    self.spider_loader = _get_spider_loader(settings)
  File "/Users/nathanielford/virtualenvironments/crawler/lib/python3.5/site-packages/scrapy/crawler.py", line 325, in _get_spider_loader
    return loader_cls.from_settings(settings.frozencopy())
  File "/Users/nathanielford/virtualenvironments/crawler/lib/python3.5/site-packages/scrapy/spiderloader.py", line 33, in from_settings
    return cls(settings)
  File "/Users/nathanielford/virtualenvironments/crawler/lib/python3.5/site-packages/scrapy/spiderloader.py", line 20, in __init__
    self._load_all_spiders()
  File "/Users/nathanielford/virtualenvironments/crawler/lib/python3.5/site-packages/scrapy/spiderloader.py", line 28, in _load_all_spiders
    for module in walk_modules(name):
  File "/Users/nathanielford/virtualenvironments/crawler/lib/python3.5/site-packages/scrapy/utils/misc.py", line 63, in walk_modules
    mod = import_module(path)
  File "/Users/nathanielford/virtualenvironments/crawler/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'spiders'

If I leave my project directory, the error no longer occurs:
$ scrapy version
Scrapy 1.2.2

What is causing the ImportError: No module named 'spiders'?

A: This error was caused by my settings.py file, where the I had the following:
SPIDER_MODULES = ['spiders']

While it is in the default project provided by scrapy, I had moved that module. Values in that list need to be fully qualified module names: even trivial executions of scrapy will load the settings file, and thus try to import modules from your project. If it can find a settings file, it will need to be correct.


text:
Q: Issue with bucket sort for strings C# I am writing a program that takes in data for student info with a student ID # field, student first name field and student last name field. The user will input the data for each student (up to 20 students) or until the user enters '999' for the student ID field. Next I would like to sort the student info into two separate buckets based on the last name field.
I am having an issue with the buckets separating correctly. I will use the CompareTo method to compare the last name strings for the student last name array but when I print the buckets they are mixed up. For example, the last names starting with A-K should go into a 'low values' bucket and last names starting with J-Z should go into a 'high values' bucket.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace _123_Assignment2
    {
    using System;
    using static System.Console;
    class Program
    {
    struct student
    {
        public int studentId;
        public string firstName;
        public string lastName;
    };

    static void Main(string[] args)
    {
        student[] studentInfo = new student[20];
        string[] bucketLow = new string[20];
        string[] bucketHigh = new string [20];
        int x = 0;
        int y = 0;
        int z = 1;

        WriteLine("Enter student ID number:");
        studentInfo[x].studentId = Convert.ToInt32(ReadLine());

        while (studentInfo[x].studentId != 999)
        {
            WriteLine("Enter first name:");
            studentInfo[x].firstName = ReadLine();
            WriteLine("Enter last name:");
            studentInfo[x].lastName = ReadLine();
            x++;
            WriteLine("Enter student ID number:");
            studentInfo[x].studentId = Convert.ToInt32(ReadLine());
        }

        for (int j = 0; j < x; j++)
        {

      if(studentInfo[j].lastName.CompareTo(studentInfo[z].lastName)<= 0)

                bucketLow[y] = studentInfo[j].lastName;
            else
                bucketHigh[y] = studentInfo[j].lastName;

                y++;
                z++;
        }

        WriteLine("Unsorted Table:");
        for (int j = 0; j < studentInfo.Length; j++)
        {

       WriteLine("{0}{1}{2}",studentInfo[j].studentId,studentInfo[j].firstName,
       studentInfo[j].lastName);
        }
        WriteLine("Bucket 1:");
        for (int j = 0; j < x; j++)
        {
            WriteLine(bucketLow[j]);
        }
        WriteLine("Bucket 2:");
       for (int j = 0; j < x; j++)
        {
            WriteLine(bucketHigh[j]);
       }
    }
}

}
I believe I am not writing the CompareTo method correctly, I tried sorting from both the beginning and end of the array respectively and keep getting the same results?

A: As this appears to be homework, I'll refrain from actually writing the correct code for you. But here are at least some of your problems:

*

*Directly addressing your concern, the code you have to sort the array elements is using the wrong comparison. If you have two buckets, and you want one to represent last names starting with A through K and the other to represent last names starting with L through Z, then you need to compare to K or L to determine the right bucket. Comparing to other names is just going to randomize the data. Something like string.Compare(studentInfo[j].lastName, "L", StringComparison.CurrentCultureIgnoreCase) < 0 should work.

*You need to maintain two indexes, one for each bucket, and only increment an index for that bucket if you've actually copied a student record to that bucket.

*Your current code will crash with an IndexOutOfRangeException if you actually try to entry data for 20 students, because you increment x and store the ID value into the array without checking to see if you've entered 20 student's worth of data yet. After 20 students have been entered, then even if the user enters 999, the while condition won't check that until it's too late and the code has already tried to stored the value into the array.

There may be other problems; those are the ones that I noticed at first glance.
For future reference, you should make sure when asking questions here on Stack Overflow that you provide a good Minimal, Complete, and Verifiable code example. You came close; at least the code was complete. But don't make other SO users enter your test data. Write a separate program that includes all the data built-in, doesn't have user prompts, and doesn't do anything that isn't strictly required to reproduce the issue you're having.

A: I do not think that you sorting works (the j and z comparisons):
studentInfo[j].lastName.CompareTo(studentInfo[z].lastName)<= 0

Try to simplify your bucket sort - if you know that your buckets are A-K and J-Z maybe you should replace the part of:
for (int j = 0; j < x; j++)
{
  if(studentInfo[j].lastName.CompareTo(studentInfo[z].lastName)<= 0)
      bucketLow[y] = studentInfo[j].lastName;
   else
      bucketHigh[y] = studentInfo[j].lastName;
      y++;
      z++;
   }
}

Try something like:
for (var i = 0; i < studentInfo.Length; i++)
{
   if (studentInfo[i].lastName[0] <= 'K')
      bucketLow[y] = studentInfo[i].lastName;
   else
      bucketHigh[y] = studentInfo[i].lastName;

   y++;
}

(And of course add some check that you have a valid input of at least 1 character and so on...)

A: If you must use a struct and arrays then you may consider the code below for separating the names into the appropriate buckets. As I commented you need to two indexes, one for each bucket. Because you are fixing the array sizes to 20, there will be empty rows when outputting the results if there are less than 20.
x = studentInfo.Length;
int lowIndex = 0;
int highIndex = 0;

for (int j = 0; j < x; j++) {
  if (String.CompareOrdinal(studentInfo[j].lastName, "L") < 0) {
    bucketLow[lowIndex] = studentInfo[j].lastName;
    lowIndex++;
  } else {
    bucketHigh[highIndex] = studentInfo[j].lastName;
    highIndex++;
  }
}


text: Q: Creating multiple components using ReactJS in Sharepoint online as I'm new to developing Sharepoint online using ReactJS, I have been trying to look ways to use react components in Sharepoint online as the same as normal ReactJS websites. I mean, If I want to create another component that makes it easy to maintain instead of writing the whole logics, codes... inside just one file. So If there's anyone experienced in Sharepoint online with React please give me an example ^^ Thank you!


text:
Q: How do I align  elements so that they are centered with one another and resemble a target in css? I am trying to create a target out of div elements but I cannot seem to figure out how to align them so that they are all centered and the smallest of the div elements is visible on top.  In the html file all I have are div elements since I am doing all of the modifications in the CSS file. It should look something like this but with different colours.Target

/* box_model.css */
div {
    height: 50px;
    width: 50px;
    background-color: red;
    border-radius: 50px;
    display: inline-block;
    position:absolute;
}
div:nth-of-type(2) {
    height: 100px;
    width: 100px;
    background-color: orange;
    border-radius: 50px;
    display: inline-block;
    position: relative;
}
div:nth-of-type(3) {
    height: 150px;
    width: 150px;
    background-color: yellow;
    border-radius: 80px;
    display:inline-block;
    position: relative;
}

div:nth-of-type(4) {
    height: 250px;
    width: 250px;
    background-color: green;
    border-radius: 150px;
    display: inline-block;
    position: relative;
}

A: First, I gave the parent container (in your case, body), a flex display. Next, I made all children absolutely positioning, so that they can stack on top of one another using z-index. Finally, the vertical transform was added to account for their own height, so that the elements would be truly positioned in the center of the screen.
Note: I condensed all the border-radius lines into a single line, to hopefully make your life a bit easier.

body {
  display: flex;
  align-items: center;
  justify-content: center;
}

body>div {
  position: absolute;
  transform: translateY(-50%);
  top: 50%;
  border-radius: 50%;
}

div {
  height: 50px;
  width: 50px;
  background-color: red;
  display: inline-block;
}

div:nth-of-type(1) {
  z-index: 4;
}

div:nth-of-type(2) {
  height: 100px;
  width: 100px;
  background-color: orange;
  z-index: 3;
}

div:nth-of-type(3) {
  height: 150px;
  width: 150px;
  background-color: yellow;
  z-index: 2;
}

div:nth-of-type(4) {
  height: 200px;
  width: 200px;
  background-color: green;
  z-index: 1;
}

Result:

jsFiddle

A: I guess this is what you want to accomplish. This is your CSS code:
div.red {
   height: 50px;
   width: 50px;
   background-color: red;
   border-radius: 50px;
   display:flex;
   align-items: center;
   position:absolute;
   z-index: 3;
}
div.orange {
  height: 100px;
  width: 100px;
  background-color: orange;
  border-radius: 50px;
  display:flex;
  align-items: center;
  position:absolute;
  z-index: 2;
}
div.yellow {
  height: 150px;
  width: 150px;
  background-color: yellow;
  border-radius: 80px;
  display:flex;
  align-items: center;
  position: absolute;
  z-index: 1;
}

div.green {
  height: 250px;
  width: 250px;
  background-color: green;
  border-radius: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 0;
}

And this is you HTML code:

A:

#a1{
    display:flex;
    height: 250px;
    width: 250px;
    background-color: green;
    border-radius: 125px;
    z-index:5;
   justify-content:center;
   align-items:center;
}
#a2{
    display:flex;
    height: 200px;
    width: 200px;
    background-color: yellow;
    border-radius: 100px;
    z-index:10;
   justify-content:center;
   align-items:center;
}

#a3{
    display:flex;
    height: 150px;
    width: 150px;
    background-color: orange;
    border-radius: 75px;
    z-index:15;
   justify-content:center;
   align-items:center;
}

#a4{
    display:flex;
    height: 100px;
    width: 100px;
    background-color: red;
    border-radius: 50px;
    z-index:20;
   justify-content:center;
   align-items:center;
}

use flexbox with z-index

A: There's a few techniques you might want to to use here.
Firstly, absolute positioning lets you position an object relative to its parents layout.
Remember that absolute positioned elements are positioned based on the next parent that has absolute or relative positioning. That is, if the immediate parent has position: static that parent will be ignored for the purpose of absolute positioning. This is why, in my example, I've given the container div position: relative - just to make the absolute positioning apply.
Secondly, the calc() function lets you make derived calculations - in this case to perfectly center things, we calc the left and right properties as 50% of the parent's width, minus 1/2 * however wide we want this thing to be.
Thirdly, the z-index property lets us control how which element displays on top.
I've quickly modified what you've done, and here's what I've got.

/* box_model.css */

.container {
    position: relative;
    height: 250px;
    width: 250px;
}

.container>.target {
    position:absolute;
}
.target:nth-of-type(1) {
    height: 50px;
    width: 50px;
    background-color: red;
    border-radius: 50px;
    z-index: 4;
    left: calc(50% - 25px);
    top: calc(50% - 25px);
}

.target:nth-of-type(2) {
    height: 100px;
    width: 100px;
    background-color: orange;
    border-radius: 50px;
    z-index: 3;
    left: calc(50% - 50px);
    top: calc(50% - 50px);

}
.target:nth-of-type(3) {
    height: 150px;
    width: 150px;
    background-color: yellow;
    border-radius: 80px;
    z-index:2;
    left: calc(50% - 75px);
    top: calc(50% - 75px);
}

.target:nth-of-type(4) {
    height: 250px;
    width: 250px;
    background-color: green;
    border-radius: 150px;
    z-index:1;
    left: calc(50% - 125px);
    top: calc(50% - 125px);

}

I would note though - that generally manually setting z-index values should be avoided, because as your application grows you might find other things over lapping when you don't want them to.
Instead, you can control how the elements stack just by their document position - in this case - make the largest circle the first element, rather than the last.

A: I hope This help

.wrapper {
  width: 500px;
  height: 500px;
  border: 1px solid;
  position: relative;
  margin: 20px;
}

.wrapper div:nth-child(1) {
  height: 300px;
  width: 300px;
  background-color: red;
  border-radius: 150px;
  position: absolute;
  top:calc(50% - 150px);
  left: calc(50% - 150px);
}
.wrapper div:nth-child(2) {
  height: 200px;
  width: 200px;
  background-color: white;
  border-radius: 100px;
  position: absolute;
  top:calc(50% - 100px);
  left: calc(50% - 100px);
}
.wrapper div:nth-child(3) {
  height: 100px;
  width: 100px;
  background-color: red;
  border-radius: 100px;
  position: absolute;
  top:calc(50% - 50px);
  left: calc(50% - 50px);
}


text:
Q: php script randomly hangs up I install php 5 (more precisely 5.3.1) as apache module.
After this one of my application becomes randomly hang up on mysql_connect - sometimes works, sometimes no, sometimes reload of page helps.
How can this be fixed?
I use Windows Vista, Apache/2.2.14 (Win32) PHP/5.3.1 with php module, MySql 5.0.67-community-nt.
After a minute I obtain the error message:
Fatal error: Maximum execution time of 60 seconds exceeded in path\to\mysqlcon.php on line 9
I run MySql locally and heavy load could not be a reason:
SHOW PROCESSLIST shows about 3 process
SHOW VARIABLES LIKE 'MAX_CONNECTIONS' is 100.
UPDATE:
At first I thought that this is connected with mysql_connect.
But now I can't say for certain.
More difficult thing is when I insert the line to debug:
$fh = fopen("E://_debugLog", 'a'); fwrite($fh, __FILE__ . " : " . __LINE__ . "\n"); fclose($fh);
script start working near that location as a rule.
Restart of apache resolve the issue.

A: You may be hitting the MySQL connection limit, and the script attempting to connect will spin its wheels until a connection is made available, but runs into the max execution time limit before that happens. When you hit one of these long pauses, hop into the mysql monitor and do SHOW PROCESSLIST, which will list all connections to the server. You can retrieve the connection limit with SHOW VARIABLES LIKE 'MAX_CONNECTIONS'. If the number of active processes is close to or at the max_connections value, that's your problem.

A: Try to isolate the problem:

*

*Shut everything down (apache mysql).

*Bump the logging levels of apache and mysql to a detailed level (so that you're logging almost everything).

*Pull the single function/piece of code that calls mysql_connect out of your existing script and create a new script that does nothing else but query mysql and return the results. (You can also comment everything out of your existing script).

*Start everything back up and look in the logs for anything out of the ordinary.

*Execute your script and examine the logs. Was it slow? Anything weird in the logs? If it wasn't slow, start adding in/uncommenting things from your original script. Does it slow down? What is showing up in the logs?

A: It is connected with the issue described at Did I find a bug in PHP's `crypt()`?


text:
Q: Integration of $1/x$ becomes $\ln(x) + \ln(C)$? Why is
$$
\int\dfrac{1}{x} + \dfrac{1}{3-x}  dx= \ln(x) - \ln(3-x) + \ln(C) \;?
$$
Isn't it
$$
\ln(x) - \ln(3-x) + C \;?
$$

A: Both are correct since both $\ln(C)$ and $C$ are arbitrary constants.

A: The sets
$$\left\{x\mapsto \frac{1}{3}(\ln x - \ln(3-x) + C)| C\in\mathbb R\right\}$$
and
$$\left\{x\mapsto \frac{1}{3}(\ln x - \ln(3-x)) + C| C\in\mathbb R\right\}$$
are equal. That is, these are just two different ways of describing the same set of functions.

A: If fact, the correct result for the primitive would be
$$
\int \frac 1x dx = \ln |x| + K, \quad K \in \mathbb{R}.
$$
The absolute value is fundamental so that the domain of the primitive is the same as the domain of $\frac 1x$. Since $\log C$ can take any real value, you can choose to say that $K = \log C$.

A: In fact, the complete antiderivative is
$$
\begin{cases}
\ln(-x) - \ln(3-x) + C_1 \textrm{ if $x<0$}\\
\ln(x) - \ln(3-x) + C_2 \textrm{ if $0<x<3$}\\
\ln(x) - \ln(x-3) + C_3 \textrm{ if $3<x$}
\end{cases}
$$
Where $C_1, C_2, C_3$ are three (potentially) different constants.


text:
Q: Building a Javascript Regex from string I'm trying to return the number of times a letter appears in a word.
I'm passing the letter to a function like so
function getCount(letter)
{
    var pattern = '/' + letter + '/g';
    var matches = word.match(pattern);
    return matches.length;
}

Unfortunately matches is null so I'm unable to call length on it, I know the letter appears in the word as I've already checked that
word.indexOf(letter) > -1

I suspect the problem is with the way I'm building or evaluating pattern

A: Here's how you build a non literal regular expression :
var pattern = new RegExp(letter, 'g');

See the MDN on building a regular expression.
And here's a simpler solution to count the occurrences of the letter :
return word.split(letter).length-1;

A: You can do this:
function hasClass(letter) {
    var pattern = new RegExp(letter,'g'); // Create a regular expression from the string
    var matches = word.match(pattern);
    return matches;

Ref: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp
This was also answered here: javascript new regexp from string


text:
Q: The UVa 3n + 1 in C++ with Dynamic Programming So, there are ways to do this, and/or optimize this. Stupid that I am, I immediately wants to implement a recursive function, which later caused a segmentation fault, and then I tried to adopt dynamic programming, and it seemed to work, but somehow I got Wrong answer.
Problem Here
So here's my code, and I think it's pretty self-explanatory.
#include <iostream>

using namespace std;

int cycleLength(long long int);

int cycleLengthResult[1000000];

int main(int argc, char *argv[])
{
    int i = 0, j = 0, cur = 0, max = 0;
    while ( cin >> i >> j )
    {
        if ( i > j ) //swap to ensure i <= j
        {
            int s = i;
            i = j;
            j = s;
        }
        for ( int k = i ; k <= j ; ++ k )
        {
            cur = cycleLength(k);
            if (cur > max) max = cur;
        }
        cout << i << " " << j << " " << max << endl;
        max = 0;
    }
}

int cycleLength(long long int arg)
{
    if ( arg > 1000000 ) //if out of array bound, then don't memorize, just calculate
    {
        if (arg % 2 == 0)
        {
            return 1 + cycleLength(arg/2);
        }
        else
        {
            return 1 + cycleLength(arg*3+1);
        }
    }
    if (!cycleLengthResult[arg-1]) //if result for arg doesn't exist then....
    {
        int valueForArg = 0;
        if (arg == 1)
        {
            valueForArg = 1;
        }
        else if (arg % 2 == 0)
        {
            valueForArg = 1 + cycleLength(arg/2);
        }
        else
        {
            valueForArg = 1 + cycleLength(arg*3+1);
        }
        cycleLengthResult[arg-1] = valueForArg;
    }
    return cycleLengthResult[arg-1];
}

I passed all the sample inputs, and also (1, 1000000) for speed test. But it seemed that it's not the problem.
I want to fix my code, and not change the methodology used, of course, I can just not use recursive, and use a loop instead in main, which wouldn't overflow. But it's fun.

A: Read the statement carefully:
The integers i and j must appear in the output in the same order in which they appeared in the input
So save them after reading and print the saved values.


text:
Q: Can I write HTML code into a Rmarkdown file and have it output as an HTML file? I've been using Rmarkdown for a while and I have used HTML commands like  of  before but for some reason I cannot get this code to generate in Rmarkdown.
Here is some HTML code I have written and it works fine in the editor of my Rstudio console.
This is my HTML Code

              Dashboard Example 1

              Dashboard Example 2

And here is how it outputs

Now when I try to copy this code into a Rmarkdown file I get this
RMD Code
---
title: "Test Example"
date: "9/8/2021"
output: html_document
---

              Dashboard Example 1

              Dashboard Example 2

The code doesn't generate and it actually breaks it up into chunks for some reason

Am I missing something?

A: Markdown doesn't seem to like indentation of embedded html code since it's the same syntax as the code blocks. You can remove the indentation to make it look right or save the html to a different file and call it from a chunk with htmltools::includeHTML


text:
Q: Showing limit of an expression containing trigonometric functions Given $ f,g:\mathbb{R}\rightarrow\mathbb{R}$ $f(x) =x + \sin x\cos x$ and $g(x) =f(x) e^{\sin x}$ I have to show that $\lim_{x\to \infty}\frac{f'(x)}{g'(x)}$ exists.
I have reached $\lim_{x\to \infty}\frac{1+\cos2x}{e^{\sin x}(1+\cos2x+x\cos x+\sin x \cos^2x)}$ and then I got stuck. Perhaps there is a more intuitive way of doing this or a trick, as I have a feeling it shouldn't look this convoluted.
Anyone have any tips?


text:
Q: How to get a table from an html page using JAVA I am working on a project where I am trying to fetch financial statements from the internet and use them in a JAVA application to automatically create ratios, and charts.
The site I am using uses a login and password to get to the tables.
The Tag is TBODY, but there are 2 other TBODY's in the html.
How can I use java to print my table to a txt file where I can then use in my application?
What would the best way to go about this, and what should I read up on?

A: If this were my project, I'd look into using an HTML parser, something like jsoup (although others are available). The jsoup site has a tutorial, and after playing with it a while, you'll likely find it pretty easy to use.
For example, for an HTML table like so:

jsoup could parse it like so:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class TableEg {
   public static void main(String[] args) {
      String html = "http://publib.boulder.ibm.com/infocenter/iadthelp/v7r1/topic/" +
            "com.ibm.etools.iseries.toolbox.doc/htmtblex.htm";
      try {
         Document doc = Jsoup.connect(html).get();
         Elements tableElements = doc.select("table");

         Elements tableHeaderEles = tableElements.select("thead tr th");
         System.out.println("headers");
         for (int i = 0; i < tableHeaderEles.size(); i++) {
            System.out.println(tableHeaderEles.get(i).text());
         }
         System.out.println();

         Elements tableRowElements = tableElements.select(":not(thead) tr");

         for (int i = 0; i < tableRowElements.size(); i++) {
            Element row = tableRowElements.get(i);
            System.out.println("row");
            Elements rowItems = row.select("td");
            for (int j = 0; j < rowItems.size(); j++) {
               System.out.println(rowItems.get(j).text());
            }
            System.out.println();
         }

      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Resulting in the following output:
headers
ACCOUNT
NAME
BALANCE

row
0000001
Customer1
100.00

row
0000002
Customer2
200.00

row
0000003
Customer3
550.00


text:
Q: How to use ` ` in c# I want to add ASCII art to a c# console application this doesn't work.
in javascript, I can do this
console.log(` hey `)
but I can't do the same in c#
console.WriteLine(` hey `)
what should I do?
edit:
I want to be able to do this
Console.WriteLine(`
hello :))
:]

`)

A: chose what you want
Console.WriteLine(" hey ")
//will print:  hey

Console.WriteLine("` hey `")
//will print: ` hey `


text:
Q: How to add stripe noise to an image? (Matlab, Python, C++) I want to put artificial noise in the image, what should I do?
You want to put stripes at regular pixel intervals, as shown in the figure below.

I wrote the code below to put black stripes on one line for every three lines
for i = 1:512
    counter = counter + 1;
    if counter > 3
        counter = 0;
    end
    for j = 1:512
        if counter < 3
            img{i,j} = 255;
        elseif counter == 3
            img{i,j} = 0;
        end
    end
end

fr = imread("image.bmp")

sum = fr + img;

I thought I could simply add the stripe arrangement and image made like this.
However, the pixel that should be zero value was not created because the pixel value of the original image was included.
The result was added only white stripes with a value of 0.
Please let me know if there is a function or code to put stripe noise in the mat wrap.

A: What you can do is simply create stripes -PIL and then Alpha composting.
so the way of approch here is

*

*first create stripes

*Then overlay images

I think I seen functions to remove stripe noises in images...But, Never any functionality approch to add stripe noise.
Python
opencv - 4.5.5

Like so.
#create stripes
from PIL import Image, ImageDraw

img = Image.new('RGB', (100, 100), (255, 255, 255))
draw = ImageDraw.Draw(img)
for y in range(10, 91, 20):
    draw.line((100, y, 0, y), (0, 0, 0), 10)

img.save('stripes.png')

####Overlay

import cv2

background = cv2.imread(r"bird.png", cv2.IMREAD_UNCHANGED)
foreground = cv2.imread(r"stripes.png", cv2.IMREAD_UNCHANGED)

height, width, channels = background.shape
foreground = cv2.resize(foreground, (width, height))

# normalize alpha channels from 0-255 to 0-1
alpha_background = background[:,:,2] / 255.0
alpha_foreground = foreground[:,:,2] / 255.0

# set adjusted colors
for color in range(0, 3):
    background[:,:,color] = alpha_foreground * foreground[:,:,color] + \
        alpha_background * background[:,:,color] * (1 - alpha_foreground)

# set adjusted alpha and denormalize back to 0-255
background[:,:,2] = (1 - (1 - alpha_foreground) * (1 - alpha_background)) * 255

# display the image
cv2.imshow("Composited image", background)
cv2.waitKey(0)

some sample insights.
Background image

After noise


text:
Q: how to press Ctrl + ] in Selenium web driver I have the ff.code which opens a chrome browser and press "F12" to open chrome dev tools, I've been searching in google on how to press Ctrl+] but unfortunately did not find any article/info about it. Has anyone here made this stuff? thanks!
    IWebDriver wdriver = new ChromeDriver();

        wdriver.Navigate().GoToUrl("www.samplewebapp.com");
        wdriver.Manage().Window.Maximize();

        Actions action = new Actions(wdriver);
        action.SendKeys(OpenQA.Selenium.Keys.F12).Perform();

A: Use either
Actions action=new Actions(driver);
action.SendKeys(OpenQA.Selenium.Keys.Control + "]").Build().Perform();

or
yourWebElement.SendKeys(Keys.Control + "]");


text:
Q: Best syntax for a = (x == null) ? null : x.func() Basic question here - I have many lines of code that look something like:
var a = (long_expression == null) ? null : long_expression.Method();

Similar lines repeat a lot in this function. long_expression is different every time. I am trying to find a way to avoid repeating long_expression, but keeping this compact. Something like the opposite of operator ??. For the moment I'm considering just giving in and putting it on multiple lines like:
var temp = long_expression;
var a = (temp == null) ? null : temp.Method();

But I was curious if there is some clever syntax I don't know about that would make this more concise.

A: Well, you could use an extension method like this:
public static TResult NullOr<TSource, TResult>(this TSource source,
    Func<TSource, TResult> func) where TSource : class where TResult : class
{
    return source == null ? null : func(source);
}

Then:
var a = some_long_expression.NullOr(x => x.Method());

Or (depending on your version of C#)
var a = some_long_expression.NullOr(Foo.Method);

where Foo is the type of some_long_expression.
I don't think I would do this though. I'd just use the two line version. It's simpler and less clever - and while "clever" is fun for Stack Overflow, it's not usually a good idea for real code.

A: var x = "";

/* try null instead */
string long_expression = "foo";

var a = ((x = long_expression) == null) ? null : x.ToUpper();

/* writes "FOO" (or nothing) followed by newline */
Console.WriteLine(a);

The type of the initialization value of x must be compatible to the type of long_expression (here: string). Works with the Mono C# compiler, version 2.10.8.1 (from Debian package mono-gmcs=2.10.8.1-4).

A: I think the C# language could really use a new operator for this sort of logic - it's quite common, and an operator would simplify countless lines of code out there.
We need something along the lines of the "??" or "if null then" operator, but that works as special '.' dot operator with a "if not null" condition.  For "??", the first '?' is like the 'if' part of the "?:" if-then, and the second '?' represents 'null' like for nullable types.  I think we need a ".?" operator which works just like '.', except it simply evaluates to null if the left expression is null instead of throwing an exception.  I guess it would be a "dot not null" operator (OK, so maybe ".!?" would be more logical, but let's not go there).
So, your oh-so-common example could lose the redundant symbol name like this:
var a = long_expression.?Method();

There is a ton of C# code out there with nested null checks that would benefit greatly.  Just think how nice it would if this:
if (localObject != null)
{
    if (localObject.ChildObject != null)
    {
        if (localObject.ChildObject.ChildObject != null)
            localObject.ChildObject.ChildObject.DoSomething();
    }
}

could become just:
localObject.?ChildObject.?ChildObject.?DoSomething();

There is also a ton of code where null checks that should be there are missing, resulting in occasional runtime errors.  So, actually using the new '.?' operator by default would eliminate such problems... It's perhaps unfortunate that we couldn't reverse the behavior of '.' and '.?' at this point, so only the new '.?' throws an exception if the left side is null - it would be the cleaner and more logical way to go, but breaking changes are very bad.  Although, one could argue that this particular change would be likely to fix a lot of hidden problems, and unlikely to break anything (only code that expects a null ref exception to be thrown).  Oh, well... one can always dream...
The only downside to checking for the null is really the slight performance hit, which is most assuredly why '.' doesn't check for null.  But, I really think the ability to just use '.?' when you care about performance (and know the left side will never be null) would have been the better way to go.
On a similar note, having 'foreach' check for and ignore a null collection would have also been so much nicer.  No more need to wrap most 'foreach' statements with "if (collection != null)", or worse, develop the common habit of always using empty collections instead of null ... which is fine in some cases, but an even worse performance issue than the null check when this is done in complex object trees where the majority of the collections are empty (which I've seen a lot).  I think the good intention of not having 'foreach' check for null to provide better performance has backfired in the majority of cases.
Anders, it's never too late to make such changes, and add a compiler switch to enable them!

A: I found this answer insightful.
By doing this assignment, you are propagating the null deeper into the system.  You'll have to write your null handling condition again (and again and again) to handle these propagations.
Instead of allowing execution to continue with nulls, replace the null with a better representation (quoted from link)

*

*If the null represents an empty collection, use an empty collection.

*If the null represents an exceptional case, throw an Exception.

*If the null represents an accidentally uninitialized value, explicitly initialize it.

*If the null represents a legitimate value, test for it - or even better use a NullObject that performs a null op.

In particular, replacing a null collection reference with an empty collection has saved me many null tests.

A: You can write an extension method for whatever type long_expression evaluates to:
public static object DoMethod(this MyType pLongExpression)
{
   return pLongExpression == null ? null : pLongExpression.Method();
}

This will be callable on any MyType reference, even if that reference is null.

A: You could put long_expression == null into a function with a short name and just call that function each time.

A: if (!String.IsNullOrEmpty(x))
    x.func()