text:
Q: Live Video Encoding Using Intel Quick Sync and Opencv Is Slow I want to develop one software that takes frames from 4K camera and encodes it simultaneously.
And right-now I can get the frames and compress it to a .h264 file. However, The problem is, I want to get 10 FPS from my video.(I mean the video eventually becomes 10FPS, but while encoding process, it doesn't get all the frames.(I am getting in between 3-5 FPS).When I dig the code I have realized that, the encoding function is okay but the function that converts BGR->YUV is pretty slow. Also, in my case, there is one dedicated computer and camera for this software. That computer only has intel integrated GPU.(so, Using FFMPEG with NVIDIA GPU is not possible.)
How could I make this faster?
This is the code I am using:
` int main()
{
Mat frame;
VideoCapture vcap(0);
vcap.set(3, 3840);
vcap.set(4, 2160);

if (!vcap.isOpened()) {
    std::cout << "Error opening video stream or file" << std::endl;
    return -1;
}

int frame_width = vcap.get(3);
int frame_height = vcap.get(4);
VideoWriter video;
std::cout << video.open("out.h264", CAP_INTEL_MFX, VideoWriter::fourcc('H', '2', '6', '4'), 10, Size(frame_width, frame_height), true);
for (;;) {

    vcap >> frame;
    video.write(frame);
}

return  -1;

}`
The conversion function BGR->YUV takes about 0.20 seconds(~5 FPS).
The encoding function takes about 0.045(~20FPS) seconds.
I was thinking the encoding would take time, but apparently conversion part takes a lot more, which is odd. There must be a solution for this.
GPU: Intel(R) UDH Graphics 620
CPU: Intel Core i5-8350U 1.70GHZ(8 Core)
Okay, so this is the write_one() function from OpenCV, it converts the frame to YUV and encodes it.This function is callled in every frame. The function named cvtBGRtoTwoPlaneYUV() does the conversion from BGR->YUV.(TAKES 200 MS )
    bool VideoWriter_IntelMFX::write_one(cv::InputArray bgr)
{

 mfxStatus res;
    mfxFrameSurface1 *workSurface = 0;
    mfxSyncPoint sync;
    clock_t start1 = clock();
    if (!bgr.empty() && (bgr.dims() != 2 || bgr.type() != CV_8UC3 || bgr.size() != frameSize))
    {
        MSG(cerr << "MFX: invalid frame passed to encoder: "
            << "dims/depth/cn=" << bgr.dims() << "/" << bgr.depth() << "/" << bgr.channels()
            << ", size=" << bgr.size() << endl);
        return false;

    }

    if (!bgr.empty())
    {
        workSurface = pool->getFreeSurface();
        if (!workSurface)
        {
            // not enough surfaces
            MSG(cerr << "MFX: Failed to get free surface" << endl);
            return false;
        }
        Mat src = bgr.getMat();
        hal::cvtBGRtoTwoPlaneYUV(src.data, src.step,
                                 workSurface->Data.Y, workSurface->Data.UV, workSurface->Data.Pitch,
                                 workSurface->Info.CropW, workSurface->Info.CropH,
                                 3, false, 1);
    }
    clock_t end1 = clock();

    clock_t start = clock();
    while (true)
    {

        outSurface = 0;
        DBG(cout << "Calling with surface: " << workSurface << endl);
        res = encoder->EncodeFrameAsync(NULL, workSurface, &bs->stream, &sync);
        if (res == MFX_ERR_NONE)
        {
            res = session->SyncOperation(sync, getWriterTimeoutMS()); // TODO: provide interface to modify timeout
            if (res == MFX_ERR_NONE)
            {
                // ready to write
                if (!bs->write())
                {
                    MSG(cerr << "MFX: Failed to write bitstream" << endl);
                    return false;
                }
                else
                {
                    DBG(cout << "Write bitstream" << endl);
                    /*RSI*/
                    clock_t end = clock();
                    frame_info[0] += (double(end - start) / CLOCKS_PER_SEC);
                    frame_info[2] += (double(end1 - start1) / CLOCKS_PER_SEC);
                    frame_info[1]++;
                    /*RSI*/
                    return true;
                }
            }
            else
            {
                MSG(cerr << "MFX: Sync error: " << res << endl);
                return false;
            }
        }
        else if (res == MFX_ERR_MORE_DATA)
        {
            DBG(cout << "ERR_MORE_DATA" << endl);
            return false;
        }
        else if (res == MFX_WRN_DEVICE_BUSY)
        {
            DBG(cout << "Waiting for device" << endl);
            sleep_ms(1000);
            continue;
        }
        else
        {
            MSG(cerr << "MFX: Bad status: " << res << endl);
            return false;
        }

    }

}

A: For anyone who is facing with the same issue. After deeper search I have found that intel also has a function does BGR->YUV conversion using hardware acceleration. It is fast comparing the above cvtBGRtoTwoPlaneYUV() function(~4x times faster). However, it was still slow for my use case. I had to get 30FPS using Intel(R) UDH Graphics 620, apparently the only solution for now is getting a better GPU.
The samples for use case:
https://github.com/sivabudh/intel-media-sdk-tutorials/tree/master/simple_6_encode_vmem_vpp_preproc
I just have added OpenCV X86 lib and I have written my own function that reads from CV::MAT  rather than a file.


text:
Q: How to retrieve data from nested array of maps in Firestore (Kotlin) for RecyclerView I would like to ask for help on how to retrieve data from Firestore for nested Array of Maps called "cities" into MutableList , which I then want to insert into recycler view, where the data from the "regions" are for the header and data "cities" for the regular list items.
Data for regions: MutableList , when I follow the procedure https://medium.com/firebase-tips-tricks/how-to-map-an-array-of-objects-from-cloud-firestore-to-a-list -of-objects-122e579eae10 by Alex Mamo, got fine, but data for: cities: MutableList , according same approach, is null (unable to retrive).
Can you please advise how to get data for "cities"?
P.s. somewhere I read the recommendation to iterate over "cities", but I have no idea how, please go straight for an example (ideally in Kontlin).
Code:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

 …..

regionsRef.get().addOnCompleteListener { document ->
    if (document.isSuccessful()) {
        val documentSnapshot = document.result

        // Retrieve array of maps for "regions"
        val regions = documentSnapshot.toObject(RegionDocument::class.java)?.regions

        // Retrieve array of maps for "cities"
        val cities = documentSnapshot.toObject(CityDocument::class.java)?.cities

       …
    }
}

Data classes for object City:
data class City(
   val cityNumber: Long? = null,
   val cityName: String? = "" )

data class CityDocument(
    var cities: MutableList<City>? = null)

Firestore structure:

A: To be able to get the data that corresponds to your document structure, you need three classes:
class Document {
    var regions: MutableList<Region>? = null
}

class Region {
    var cities: MutableList<City>? = null
    var regionName: String? = null
    var regionNumber: Long? = null
}

class City {
    var cityName: String? = null
    var cityNumber: Long? = null
}

And below you can find a solution for reading all cities:
val db = FirebaseFirestore.getInstance()
val docIdRef = db.collection("collName").document("docId")
docIdRef.get().addOnCompleteListener { task ->
    if (task.isSuccessful) {
        val document = task.result
        if (document != null) {
            val doc = document.toObject(Document::class.java)
            if (doc != null) {
                val regions = doc.regions
                if (regions != null) {
                    for (region in regions) {
                        val cities = region.cities
                        //Do what you need to to do with your List<City>.
                    }
                }
            }
        }
    } else {
        Log.d("TAG", task.exception!!.message!!) //Never ignore potential errors!
    }
}

Now, simply replace collName and docId with the one you have in your database.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como mostrar exceções levantadas no Datasnap REST Server, no client? Muito boa tarde, pessoal.
Então, estou com o seguinte problema. Criei uma Aplicação multicamadas, utilizando o Datasnap REST Server.
Implementei o server com todos os servermethods e também o cliente, até aí tudo bem...
Estou utilizando o Reflection do Firedac para trazer os dados e o FDMemTable para Listá-los. Só que quando ha algum erro de banco, somente o Server mostrar a mensagem de
erro e no client não mostra, dificultando assim a manutenção e muito ruim pra identificar erros, porque se eu tiver 2 máquinas, uma com o server e outra com o client, somente é mostrado o erro no Server, eu tenho que ir la pra saber o que está acontecendo.
Alguém ja conseguiu fazer mostrar o erro no client? Sem usar OnReconcileError, pois o crud é feito por métodos passando o objeto por parâmetro.

A: Poderia fazer da seguinte forma, passar como parâmetro na função do server o tipo out, pois ele te retorna o valor depois que o cliente faz a requisição. Por exemplo:
Servidor:
function grava(out psVariavel: String): Boolean;

no cliente quando você chamar essa função você passa como parâmetro, uma variável ou um FDMemTable, assim ele vai te retornar o que acontecer no servidor.
Espero te sido claro. Abraços!


text:
Q: MongoDB FindAndModify Sorting I am using FindAndModify in MongoDB in several concurrent processes. The collection size is about 3 million entries and everything works like a blast as long as I don't pass a sorting option (by an indexed field). Once I try to do so, the following warning is spawned to the logs:
warning: ClientCursor::yield can't unlock b/c of recursive lock ns: test_db.wengine_queue top:
{
opid: 424210,
active: true,
lockType: "write",
waitingForLock: false,
secs_running: 0,
op: "query",
ns: "test_db",
query: {
    findAndModify: "wengine_queue",
    query: {
            locked: { $ne: 1 },
            rule_completed: { $in: [ "", "0", null ] },
            execute_at: { $lt: 1324381363 },
            company_id: 23,
            debug: 0,
            system_id: "AK/AK1201"
        },
    update: {
            $set: { locked: 1 }
        },
    sort: {
            execute_at: -1
        }
},
client: "127.0.0.1:60873",
desc: "conn",
threadId: "0x1541bb000",
connectionId: 1147,
numYields: 0
}

I do have all the keys from the query indexed, here they are:
PRIMARY> db.wengine_queue.getIndexes()
[
{
    "v" : 1,
    "key" : {
        "_id" : 1
    },
    "ns" : "test_db.wengine_queue",
    "name" : "_id_"
},
{
    "v" : 1,
    "key" : {
        "system_id" : 1,
        "company_id" : 1,
        "locked" : 1,
        "rule_completed" : 1,
        "execute_at" : -1,
        "debug" : 1
    },
    "ns" : "test_db.wengine_queue",
    "name" : "system_id_1_company_id_1_locked_1_rule_completed_1_execute_at_-1_debug_1"
},
{
    "v" : 1,
    "key" : {
        "debug" : 1
    },
    "ns" : "test_db.wengine_queue",
    "name" : "debug_1"
},
{
    "v" : 1,
    "key" : {
        "system_id" : 1
    },
    "ns" : "test_db.wengine_queue",
    "name" : "system_id_1"
},
{
    "v" : 1,
    "key" : {
        "company_id" : 1
    },
    "ns" : "test_db.wengine_queue",
    "name" : "company_id_1"
},
{
    "v" : 1,
    "key" : {
        "locked" : 1
    },
    "ns" : "test_db.wengine_queue",
    "name" : "locked_1"
},
{
    "v" : 1,
    "key" : {
        "rule_completed" : 1
    },
    "ns" : "test_db.wengine_queue",
    "name" : "rule_completed_1"
},
{
    "v" : 1,
    "key" : {
        "execute_at" : -1
    },
    "ns" : "test_db.wengine_queue",
    "name" : "execute_at_-1"
},
{
    "v" : 1,
    "key" : {
        "thread_id" : 1
    },
    "ns" : "test_db.wengine_queue",
    "name" : "thread_id_1"
},
{
    "v" : 1,
    "key" : {
        "rule_id" : 1
    },
    "ns" : "test_db.wengine_queue",
    "name" : "rule_id_1"
}
]

Is there any way around this?

A: For those interested -- I had to create a separate index ending with the key that the set is to be sorted by.

A: That warning is thrown when an operation that wants to yield (such as long updates, removes, etc.) cannot do so because it cannot release the lock it's holding for whatever reason.
Do you have the field you're sorting on indexed? If not adding an index for that will probably remove the warnings.


text:
Q: Customers did not transfer during migration. How best to proceed? Migration from Magento 1.9.4 --> Magento 2.4.2-p1

As far as I can tell my running of the Magento Migration tool transferred everything except the orders which we didn't want but I just noticed we are missing Customers also. What would be the best way to proceed? Shall I re-run the Magento Migration Tool or use the
System --> Import/Export --> Export/Dataflow - Profiles

option? If Import/Export - would it be better to use the 'Export' option or 'Dataflow - Profiles'?

RESOLVED: I ran the reindex via SSH as suggested by Pawan and it worked!

A: I am putting my comment as an answer here:
As you are using default migration tool, it should migrate all customer by default.
You can first check database of Magento 2 for customer record and If you found record, You just need to run re-indexing.


text:
Q: How to excute python script when pushing a button on excel I have several python scripts, test1,py, test2,py, test3.py and so on.
I would like to have three buttons (using VBA) on the Excel screen.
How do I associate a button to a specific python filename so that I can execute the file and capture the python response into a text box within excel (message response).

A: You could try embedding Python in Excel with this http://code.google.com/p/pyinex/
Or just have some VBA code that runs a Python shell script and captures the output into a file, then reads the file and fills the textbox.
Or try writing a Python COM server in 20 lines https://web.archive.org/web/20111113152839/http://showmedo.com/videotutorials/series?name=ktn7wmxvn
Or add Python as an Excel scripting language https://web.archive.org/web/20110718231808/http://blog.gobansaor.com/category/microetl/
Once you decide how to connect Excel and Python, the rest is straightforward.


text:
Q: Apache Apex - kryo ArrayList Exception I've implemented an operator to deserialize from avro byte[] to Object. After that I sent the object to ConsoleOutputOperator.
public final transient DefaultInputPort<byte[]> input = new DefaultInputPort<byte[]>() {
    @Override
    public void process(byte[] tuple) {
        SpecificDatumReader reader = new SpecificDatumReader<T>(User.getClassSchema());
        BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(tuple, null);
        try {
            binaryDecoder.readInt();
            obj = (T) reader.read(null, binaryDecoder);
        } catch (IOException e) {
            errorCount++;
            LOG.error("Avro decoder error.");
        }

        if (obj != null) {
            output.emit(""+obj);
            recordCount++;
        }else if (errorPort.isConnected()) {
            errorPort.emit(obj);
            errorCount++;
        }
    }
};

But, I got this error.
2016-05-09 10:53:21,481 ERROR com.datatorrent.stram.engine.StreamingContainer: deploy request failed
com.esotericsoftware.kryo.KryoException: Class cannot be created (missing no-arg constructor): org.apache.avro.generic.GenericData$Array
Serialization trace:
user (com.log.avro.User)
obj (com.log.avro.AvroOperator)
at  com.esotericsoftware.kryo.Kryo$DefaultInstantiatorStrategy.newInstantiatorOf(Kryo.java:1228)
at com.esotericsoftware.kryo.Kryo.newInstantiator(Kryo.java:1049)
at com.esotericsoftware.kryo.Kryo.newInstance(Kryo.java:1058)
at com.esotericsoftware.kryo.serializers.CollectionSerializer.create(CollectionSerializer.java:89)
at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:93)
at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:22)
at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:679)
at com.esotericsoftware.kryo.serializers.ObjectField.read(ObjectField.java:106)
at com.esotericsoftware.kryo.serializers.FieldSerializer.read(FieldSerializer.java:528)
at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:679)
at com.esotericsoftware.kryo.serializers.ObjectField.read(ObjectField.java:106)
at com.esotericsoftware.kryo.serializers.FieldSerializer.read(FieldSerializer.java:528)
at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:761)
at com.datatorrent.common.util.FSStorageAgent.retrieve(FSStorageAgent.java:193)
at com.datatorrent.common.util.FSStorageAgent.load(FSStorageAgent.java:137)
at com.datatorrent.stram.engine.StreamingContainer.deployNodes(StreamingContainer.java:894)
at com.datatorrent.stram.engine.StreamingContainer.deploy(StreamingContainer.java:843)
at com.datatorrent.stram.engine.StreamingContainer.processHeartbeatResponse(StreamingContainer.java:801)
at com.datatorrent.stram.engine.StreamingContainer.heartbeatLoop(StreamingContainer.java:694)
at com.datatorrent.stram.engine.StreamingContainer.main(StreamingContainer.java:312)

I think that it doesn't not support "ArrayList".
kryo.readObject(input, ArrayList.class);

How to fix this error?

A: Take a look at: http://avro.apache.org/docs/1.8.0/api/java/org/apache/avro/generic/GenericData.html
You'll notice that GenericData.Array does not have a default constructor (i.e. a constructor with no arguments) which Kryo requires in order to serialize/deserialize.
You can use the annotation: @DefaultSerializer(JavaSerializer.class)
if the class is Java serializable as is done in:
library/src/main/java/com/datatorrent/lib/codec/KryoJdkContainer.java
in Apex Malhar.
Please look at: http://docs.datatorrent.com/troubleshooting/#application-throwing-following-kryo-exception
for additional options.


text:
Q: How c++ new statement work? Why the last "cout" line always output "16" ??
On my machine, sizeof(int) is 4.
#include <iostream>

using namespace std;

int main() {
  int *pint1 = new int;
  int *pint2 = new int;
  cout<<pint1 <<endl;
  cout<<pint2 <<endl;

  cout<<(int)pint2 - (int)pint1 <<endl;
}

A: You cannot really make any assumptions about the location of pint1 and pint2 on the stack (the pointers are stack allocated but the things they point to are allocated on the heap) as it's not specified by the C++ standard. They certainly do not have to be in contiguous memory.
For example, using pointer arithmetic pint1 + 1 does not, in general, land you on pint2.
Pointer arithmetic could be used if you'd written int* pint = new int[2];. Then, pint + 1 points to the second element.
To keep things standard, using
 cout << (std::ptrdiff_t)(pint2 - pint1) << endl;

would be preferred, where I'm using (std::ptrdiff_t) explicitly. The way you've currently written it could give you undefined behaviour if you have a 32 bit int on a 64 bit architecture (e.g. Win64, MSVC).
(And don't forget to delete the allocated memory).

A: Because malloc addresses are 16-byte aligned by default on your platform. And new just uses malloc.
The result can highly depends on the used platform and the malloc implementation on your system. But most systems will print 16.

A: Because of INTERNAL compiler behaviour. It MAY allocate next memory block just after previous one.
But this is completely realisation option. Compiler MAY stop doing so EVERY MOMENT.
By the way, my compiler (gcc on ubuntu) prints 32
0x12b2010
0x12b2030
32

A: possibly due to alignment, but also the fact that every memory-chunk allocated with new or malloc have to remember its own size, and thus is larger than what you requested. the 'extra' info is usually right before the pointer returned


text:
Q: ASP - Removing Double quotes from a string I have a ASP Page and it has so many date variables.
myvariable = FormatParameter("EndDate")

EndDate is "10/01/2001"
How can I remove the double quotes from the date variable? so that it can be 10/01/2001.
I can do this in .NET but couldn't find a way to do it in ASP.
Any help is greatly appreciated.

A: myvariable = Replace(FormatParameter("EndDate"), """", "")


text:
Q: How to filter list of URLs in a jsonpath expression containing a substring in Python I've to filter the list of URLs in a jsonpath expression containing a substring in Python, I've tried the following but not able to get the desired results.
I referred to http://goessner.net/articles/JsonPath/ and http://mikelev.in/2012/08/implementing-jsonpath-in-python-with-examples/
Here are the details of all what I have tried:
My json response:
{
  "127.0.0.1": {
    "URLs": [
      "http://www.test.ca/",
      "http://b.scorecardresearch.com/p?ns__t=1387392184071&ns__c=ISO-8859-1&c1=3&c3=_es_7948950&c4=56568219&c5=105139691&c6=&c10=1&c11=1016510&c13=728x90&c16=dfa&c2=14397547&ax_iframe=2&ns_ce_mod=vce_st&ns__p=1387391507295&ax_cid=14397547&ax_bl=0&ax_blt=1228&ns_ad_event=show&ns_ad_id=DCF277937840&ns_ad_sz=728x90",
      "http://cdn.media.ca/a/mediative/sites/test_en.js",
      "http://pt200233.unica.com/ntpage.gif?js=1&ts=1387392184554.791&lc=http%3A%2F%2Fwww.test.ca%2F%3Fni_title%3D%2Fhome%2Fhomepage&rf=http%3A%2F%2Fwww.test.ca%2F&rs=1680x1050&cd=32&ln=en&tz=GMT%20-05%3A00&jv=1&ck=UnicaID%3DwQVZatfvXZ5-YZ0yaPj&m.pn=homepage&m.mlc=%2Fhome&m.cv_c13=ctest-new&m.cv_c14=en&m.utv=ut.ctest.2.2.131022.74&m.host=www.test.ca&m.page=%2Fhome%2Fhomepage&m.mlc0=home&ets=1387392184559.194&site=test",
    ]
  }
}

Above Json response is parsed as:
parsed_input = json.loads(urllib.urlopen('<URL for the above JSON response>').read())

To get the list of all URLs from the JSON response, I tried the following, which works great:
'\n'.join(jsonpath.jsonpath(parsed_input, '$..URLs[*]'))
Output:
http://www.test.ca/
http://b.scorecardresearch.com/p?ns__t=1387392184071&ns__c=ISO-8859-1&c1=3&c3=_es_7948950&c4=56568219&c5=105139691&c6=&c10=1&c11=1016510&c13=728x90&c16=dfa&c2=14397547&ax_iframe=2&ns_ce_mod=vce_st&ns__p=1387391507295&ax_cid=14397547&ax_bl=0&ax_blt=1228&ns_ad_event=show&ns_ad_id=DCF277937840&ns_ad_sz=728x90"
http://cdn.media.ca/a/mediative/sites/test_en.js"
http://pt200233.unica.com/ntpage.gif?js=1&ts=1387392184554.791&lc=http%3A%2F%2Fwww.test.ca%2F%3Fni_title%3D%2Fhome%2Fhomepage&rf=http%3A%2F%2Fwww.test.ca%2F&rs=1680x1050&cd=32&ln=en&tz=GMT%20-05%3A00&jv=1&ck=UnicaID%3DwQVZatfvXZ5-YZ0yaPj&m.pn=homepage&m.mlc=%2Fhome&m.cv_c13=ctest-new&m.cv_c14=en&m.host=www.test.ca&m.page=%2Fhome%2Fhomepage&m.mlc0=home&ets=1387392184559.194&site=test

Next I've to retrieve only those URLs that contain the word "unica".
I've tried everything below, but receive the TypeError,
what am I missing?:
'\n'.join(jsonpath.jsonpath(parsed_input, '$..URLs[?(/unica/)]'))
'\n'.join(jsonpath.jsonpath(parsed_input, '$..URLs[?(@(unica))]'))
'\n'.join(jsonpath.jsonpath(parsed_input, '$..URLs[?(@.(*.unica.*))]'))
'\n'.join(jsonpath.jsonpath(parsed_input, '$.*.URLs[?(unica)]'))
'\n'.join(jsonpath.jsonpath(parsed_input, '$.*.URLs[?:unica]'))

thanks,
Sam

A: The ? operator introduces a script element which runs in Python so needs to use Python syntax.
In this case you could use:
print '\n'.join(jsonpath.jsonpath(parsed_input, "$..URLs[?('unica' in @)]"))

A useful option for these cases is to use the debug option via:
jsonpath.jsonpath(parsed_input, '$..URLs[?(/unica/)]',debug=True)

This prints out various output including:
evalx /unica/
eval /unica/
invalid syntax (<string>, line 1)

The line "eval /unica/" shows you what is being run in Python so you can see what is failing.

A: Following Peter's explanation, you can actually use a regular expression in jsonpath filter expression if need be, using the dunder import built-in.
jsonpath.jsonpath(parsed_input, "$..URLs[?(__import__('re').match('.*unic', @))]")

Upon further look, jsonpath is a collection of hacks, specifically there's this line:
# Get caller globals so eval can pick up user functions!!!
caller_globals = sys._getframe(1).f_globals

Hence, if re is imported in the module from where you call jsonpath.jsonpath this would as well:
jsonpath.jsonpath(parsed_input, "$..URLs[?(re.match('.*unic', @))]")


text:
Q: Sci-fi novel in the 90's or early 2000 - Girl revived in violet room, tried to escape In the early 2000s I read a Science fiction book in school. The details I remember are vague. Just little glimpses of the beginning.
I believe in the beginning of the book a girl, the protagonist, wakes up in a kind of Laboratory out of a deep sleep. She doesn't know why she is there or what she is wearing. The room is glowing a type of violet. She realizes something is wrong and tries to escape. The room should be filled with other people like herself too I think.
I think she ends up being on a space ship.
Can't remember the middle or ending though.
It has had a little place in my mind for so long. want to read it again.


text:
Q: Identical Phpass code returning different results with CheckPassword I am using Phpass to hash the passwords of my users. The creation and hashing of the password - fine. The checking of the password when logging in - fine.
The checking of the old password when changing it to a new one though - always returns false!
It is basically the same code but it never returns true, even when the password is correct. I have tried just checking the password outright by typing a password and pasting its hash into the function instead of calling it from the database and the input form but that still returns false.
Here is the login code which works:
$user = $query->fetch(PDO::FETCH_ASSOC);

$t_hasher = new PasswordHash(8, FALSE);
$check = $t_hasher->CheckPassword($password, $user['password']);

if (!$check) { die("failed"); }
else { ... log them in etc.

And here is the change password check, which doesn't work:
$user = $query->fetch(PDO::FETCH_ASSOC);

$t_hasher = new PasswordHash(8, FALSE);
$check = $t_hasher->CheckPassword($oldpass, $user['password']);

if (!$check) { showMessage("Incorrect Password","Your password was not changed.","icon-lock", "warning"); }
else { ... change the password etc.

I am at a loss, as far as I can see there is no conceivable reason why this isn't working.

A: It turns out I am a massive idiot and forgot to execute the database query for the change password.


text:
Q: Using Exceptions to notify if the username is available or not let us say i'm having a table(login) that has usernames(unique key) and passwords, used for login purposes.
Now, in the registration module(that creates a new account by adding a new row in login table),is it okay if i just execute the insert and check if the username is already in the table when the SQLException() raises???. is it a good practice???
Here's an example of registration module:
enter code here
String uname = request.getParameter("username");
String passwd = request.getParameter("password");
try
{
  statement.executeUpdate("insert into login(username,password) values (" + uname + "," + passwd + ")");
}
catch(SQLException e)
{
   if((e.getErrorCode())==1) //error code when primary key violated
   {
      // username already exists....
   }
   //some other code
 }

 //username is available....rest of the code goes here

in the firs place i thought of a select query to check if the username (user has entered while registering) is already in the table....but it seemed redundant to me
because i thought, even doing so wouldnt prevent the DBMS to check the uniqueness violation, right????
Thanks in advance.

A: What I would recommend is do a validation before insert, in case you change underlying database which change the error code in SQLException.getErrorCode(). This also enable you do validation before user submit the form. You can create a custom exception the notify your service caller that username is already in use.

Retrieves the vendor-specific exception code for this SQLException
  object.

SELECT COUNT(*) FROM LOGIN WHERE USERNAME = :username

via a service method, for example:
public class UserService {

    public boolean isValidUsername(String username) {
        //validate
    }
    public void registerUser(User user) throws UsernameInUseException {
        if(!isValidUsername(user.getUsername()) {
            throw new UsernameInUseException("Usernaame " + user.getUsername() + " is already in use.");
        }
        // continue
    }

}

A: It will be cool if you could tell the user before form submission that username already exists using AJAX calls.


text:
Q: www.example.com redirects to https://www.www.example.com I want to redirect all traffic to https://www.example.com. I have .htaccess rules set as below:
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.*)$  [NC]
RewriteRule (.*) https://www.%1/$1 [R=301,L]
</IfModule>

Both DNS A records (www and non-www) are pointing to the same IP. That results with www.example.com redirecting to https://www.www.example.com What am I doing wrong?

A: This is happening because of this line in your .htaccess:
RewriteRule (.*) https://www.%1/$1 [R=301,L]

Change it to:
RewriteRule ^(.*)$ https://www.example.com%{REQUEST_URI} [R=301,L]

Should fix that issue. Make sure you clear your cache before testing this.

A: I've changed it to
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

and it works fine. Thanks for help Joe.


text:
Q: Rename variables at different levels of nested JSON dataset I am looking to rename a variable with a different name depending on its level within a nested JSON dataset.
An example JSON file is the following:
[
  {
    key: "John Doe School",
    values: [
      {
        key: "Mr. Brown",
        values: [
          {
            key: "Joe",
            TestScore: 95
          },
          {
            key: "Sarah",
            TestScore: 99
          }
        ]
      }
    ]
  }
]

In this example, I would like to change the first-level "key" to "School", the second-level "key" to "Teacher", and the third-level "key" to "Student".
The JSON dataset would look like this following the changes:
[
  {
    School: "John Doe School",
    values: [
      {
        Teacher: "Mr. Brown",
        values: [
          {
            Student: "Joe",
            TestScore: 95
          },
          {
            Student: "Sarah",
            TestScore: 99
          }
        ]
      }
    ]
  }
]

A: Well, given your example, you could just do this...
var json = [
  {
    key: "John Doe School",
    values: [
      {
        key: "Mr. Brown",
        values: [
          {
            key: "Joe",
            TestScore: 95
          },
          {
            key: "Sarah",
            TestScore: 99
          }
        ]
      }
    ]
  }
];

json[0].key = "School";
json[0].values[0].key = "Teacher";
json[0].values[0].values[0].key = "Student";
json[0].values[0].values[1].key = "Student";

UPDATE FOLLOWING COMMENT
json[0]['School'] = json[0].key; // Add new key:value
delete json[0].key; // Delete previous one

json[0].values[0]['Teacher'] = json[0].values[0].key; // Add new key:value
delete json[0].values[0].key; // Delete previous one

json[0].values[0].values[0]['Student'] = json[0].values[0].values[0].key; // Add new key:value
delete json[0].values[0].values[0].key; // Delete previous one

json[0].values[0].values[1]['Student'] = json[0].values[0].values[1].key; // Add new key:value
delete json[0].values[0].values[1].key; // Delete previous one

I assume you will be looping through a number of different JSON objects however, so you would of course also need to implement that but the above structure should point you in the right direction ;)


text:
Q: Ag-grid angular-material-theme I've included the new material theme (ag-theme-material) and encounterd a problem, which is, that the "$ag-mat-accent" variable is ignored completely. Is there a way to fix this?

A: Solved using $primary-color and $accent-color instead of $ag-mat-primary and $ag-mat-accent.


text:
Q: stacking multiple Access fields into a label & a data field I have a table that looks like this:
oldTab
I'd like to create a table that looks like this:
newTab
I can run only the first line of this query: -
INSERT INTO newTab (PairID, Code) SELECT PairID, MaleCode FROM oldTab
INSERT INTO newTab (PairID, Code) SELECT PairID, FemaleCode FROM oldTab
With the addition of the second giving "Syntax error in FROM clause."
I suspect I'm missing some assumed, basic SQL syntax, as am very much a beginner. Can anyone suggest what I'm doing wrong or missing out?
Many thanks :-)

A: With Access SQL, you need two queries.
First execute:
INSERT INTO newTab (PairID, Code) SELECT PairID, MaleCode FROM oldTab

Next, execute:
INSERT INTO newTab (PairID, Code) SELECT PairID, FemaleCode FROM oldTab


text:
Q: Ansible oc module inline definition I am trying to deploy into openshift with inline file definition, But getting error as
ERROR:
"msg": "parameters are mutually exclusive: ['name', 'definition']"
  oc:
    host: "{{openshift_uri}}"
    validate_certs: false
    name: "{{namespace}}"
    state: present
    definition: "{{ lookup('file', 'prometheus/dc.yaml') | from_yaml}}"
    token: "{{ openshift_devops_token }}"
  tags: deploy,deploy-prometheus```

A: This is happening because the definition argument is also an alias for 'def' or 'inline'.
In the documentation (https://docs.ansible.com/ansible/2.4/oc_module.html), it states this about the inline argument:

The inline definition of the resource. This is mutually exclusive
  with name, namespace and kind.

So its one or the other, not both. However, this module is also going to be deprecated in 2.9, so you might want to switch over to the openshift_raw module instead, which is the updated version that might give you more options with what you are trying to do.
https://docs.ansible.com/ansible/2.5/modules/openshift_raw_module.html


text:
Q: Get array from model to view In my model I have one int object and a boolean array:
public class mymodel
{
  public int Round { get; set; }
  public Boolean[] lstLabs { get; set; }
}

In my view I write this :
<script type="text/javascript">
var objModel = {
    Round:"@Model.Round",
    lstLabs: "@Model.lstLabs"
      };
</script>

I get only the value of Round (the int object) , but I can't get the array , I just get this : lstLabs : System.Boolean[] , I tried : lstLabs: @Model.lstLabs.slice() but it didn't work , I got the same thing...
Can anyone help me ?
Thanks in advance.

A: If you want all properties of the view model:
<script type="text/javascript">
    var objModel = @Html.Raw(Json.Encode(Model));
    alert(objModel.Round + ' ' + objModel.lstLabs.length);
</script>

or if you want only a subset:
<script type="text/javascript">
    var objModel = @Html.Raw(Json.Encode(new {
        Labs = Model.lstLabs
    }));
    alert(objModel.Labs.length);
</script>


text:
Q: Example of a group of order $15$ satisfying some conditions Suppose that a group  $G$ of order $15$ has only one subgroup of order $3$ and only one subgroup of order $5$, then I need to prove that $G$ is cyclic.
If I can show that $\exists a\in G$ such that $|a|=15$, then the result is proved.
By Lagrange's theorem, every subgroup of order $3$ and $5$ is cyclic. Hence, let $H=\{e,a,a^2\}$ and $K=\{e,b,b^2,b^3,b^4\}$ be the only subgroups of $G$ of orders $3$ and $5$ respectively, such that $|a|=3, |b|=5$ and that $b\notin \langle a \rangle$
Clearly, $H\cup K=\{e,a,a^2,b,b^2,b^3,b^4\}\subset G$. Suppose that $x\in G$ but $x\notin H\cup K$, then by Lagrange's theorem, $|x|=1,3,5,15$. Clearly, $|x|\ne 1$. If $|x|=3$, then $x\in H$ and similarly if $|x|=5$ then $x\in K$. So $|x|=15$. Hence proved.
I can't believe it so I am looking for an example of such a group. How will this group look like? I just can't get past the following thought:
$G=\{e,a,a^2, b,b^2,b^3,b^4, ab, ab^2,ab^3,ab^4,a^2b,a^2b^2,a^2b^3,a^2b^4\}\tag{1}$
Will the group $G$ look like as in $(1)$? If yes, then
$(A)$ how can it  be cyclic.
$(B)$ How to ensure closure i.e., whether for example $(ab)^2\in G$ or not?
Thanks for your time.

A: Well, yes, you can certainly form the group $C_3 \times C_5$ which has the elements that you write above. The point is that... this group is cyclic! And it is generated by the product of the generators.
The reason is that $3$ and $5$ are coprime, and that is actually a necessary condition for this to happen (this = "the direct product of two cyclic groups being cyclic"): in fact, take $C_a = \langle x \rangle$ and $C_b = \langle y \rangle$, where $a$ and $b$ are coprime. Since the generators commute in $G=C_a \times C_b$, the order of $xy$ divides the least common multiple of the orders of $a$ and $b$ (since if $x^a=1$ then $x^{ak}=1$), so if $q$ is a multiple of both $a$ and $b$ then $x^q=y^q=1$ and hence $(xy)^q = 1$ (because, again, they commute).
But if the orders are coprime... the least common multiple is $ab$, the product of the orders! Since $G$ has order $ab$, then it follows that all elements of $G$ are powers of $ab$. In other words, $G$ is cyclic.


text:
Q: MIPS - Create binary word of an order I have the following code in MIPS language:
lw $s5, -20($s6)

sub $t1, $s5, $t2

addi $t1, $t2, 50

I need to convert each order to its code:
a. in decimal
b. in hex
c. in binary 32 bits
for the first order (lw $s5, -20($s6)) I did:
a. 35 | 22 | 21 | -20
b. 23 | 16 | 15 | C
3 questions:
1) am I right ?
2) what will be the code for 32 bits binary ?
3) What are the other codes of the other 2 more orders ?
Thanks !

A: According to the operands and the type of the instruction, there are several encoding scheme, but all of them are composed by 32 bits and the first six specify the instruction opcode (add, lw etc).

*

*Register encoding: these instructions operates only on registers. First six bits are 0, next there are three fields of five bits which specify respectively first and second source register and the destination register. Finally there are other six bits which specify the function (add, sub etc)

*Immediate encoding: these instruction have an operand which is a memory location. After six bits of opcode there are two fields of five bits for the first and second register, and a field of sixteen bits for the memory location.

*Jump Encoding: they're composed by six bits of opcode and twenty-six bits of jump destination
This article explains these instructions encoding and has a list of all opcodes / function encoding in binary. Once you have determined the binary form simply convert it to decimal and hexadecimal.
EXAMPLE:
Suppose we want the encoding of lw $s5, -20($s6). This falls into immediate encoding category, whose encoding is ooooooss sssttttt iiiiiiii iiiiiiii, with o being the opcode, s the first register, t the second register and i the constant. Looking on the table we find the opcode for lw is 100011. Specifying the register's number is enough, so s is 00101 and t is 00110. The constant (-20) is represented by 2s complement. With 20 being 10100, its 2s complement on 16 bit is 1111111111101100. lw has a loadstore syntax, which template is o $t, i ($s), so the registers are swapped in the encoding. Therefore the instruction encoding for lw $s5, -20($s6) is
ooooooss sssttttt iiiiiiii iiiiiiii
10001100 11000101 11111111 11101100

or 8C C5 FF EC (hex) and 140 197 255 236 (dec)


text:
Q: Convert SQL Server .mdf file format I installed VS 11 beta and SQL Server 2012 on my development machine and at one point, I was asked to upgrade my database from version 661 (SQL Server 2008 R2) to SQL Server 2012.
I clicked yes, continued building, and now I've just realized that the file won't deploy in SQL Server 2008 R2, which is the version installed on the staging server (I don't control that machine).
I've thought of exporting the database to another format (access for instance) and reimporting it in SQL Server 2008 R2. Is that the best way to solve my problem? Is there another better way?
Thanks for your suggestions.

A: You have at least four options:

*

*Restore your last pre-upgrade backup

*Re-create the database from scripts in source control

*Use SMO to generate scripts for all objects and re-create the database

*Use SSIS or a third-party tool to copy all database objects from one DB to another

If you opt to re-create the database from scripts, you can then use SSIS or bcp to copy the data over. But restoring a backup is by far the easiest solution and if you don't take regular backups of your development environment then this might be a good time to start.
And as someone else advised, do not develop using tools and versions that don't match your production environment.

A: Look at this 10-minute solution to learn how to recreate your upgraded database using "Generate SQL Server Scripts" wizard.


text:
Q: Qt: Multiple windows showing on button press connect(ui->button,SIGNAL(pressed()),this,SLOT(showWindow2()));

// Slot
void Window1::showWindow2()
{
    Window2*cal = new Window2();
    cal->show();
}

There are 2 Window2 instances showing on top of Window1. I believe it is sensing a double tap on the capacitive touch screen and is triggering the pressed signal twice. I am having trouble finding a proper solution to this. I tried a delay after it was pressed once, and just return from the slot if the delay has not expired yet. But i do not believe this is a good solution. Does anyone know how to go about this?

A: Try using another QPushButton signal (i.e. clicked):
connect(ui->button,SIGNAL(clicked(bool)),this,SLOT(showWindow2()));

A: As you mentioned "I believe it is sensing a double tap on the capacitive touch screen" is an indication of how your code might leak!
The major problem is that you are creating a loose Window2 object that is only visible inside your SLOT (this is how your code appears), meaning: how you are going to manage this window2 object (cal) in your rest of code .. how you will close it? this is not possible - at least with the code you shared.
Solution:
Create a class member Window2 *cal in your window1 class header.
Then, modify your slot as:
void Window1::showWindow2()
{
    if (cal != nullptr)
     delete cal;
    cal = new Window2();
    cal->show();
}

A: As I see it you can approach this in two ways.
There are two signals in the QPushButton class, pressed() and clicked(). pressed() refers to an event when you actually push the button and it is triggered as soon as you touch the QPushButton. When you touch the QPushButton, pressed() is emitted continuously, till you release it. This is the reason for the multiple windows in your app. There is a good possibility that your touchscreen is detecting a double tap.
The second signal, clicked() is emitted when you remove your finger from the button (when it goes from ON back to OFF state). This will most likely be triggered only once in a single human touch. So, you could use clicked() instead:
connect(ui->button,SIGNAL(clicked()),this,SLOT(showWindow2()));

The other way is if you still want it to use pressed(). You can disconnect the signal and slot as soon as the slot is called:
// Slot
void Window1::showWindow2()
{
    disconnect(ui->button, SIGNAL(pressed()), this, SLOT(showWindow2()));
    Window2*cal = new Window2();
    cal->show();
}

If you follow the second approach, don't forget to connect the pressed() signal to showWindow2() slot after destroying the Window2 object.
I'd do the disconnect regardless of whether I am using either of these two methods (pressed() or clicked()) to make sure that the slot is not called twice.
As Mohammad mentioned, it is a good idea to move *cal to the class scope. Since you are dynamically allocating, you will want to make sure to destroy it later. Of course, this is subject to change in your design.


text:
Q: PHP: Performance difference between string concat and buffering contents I do lots of string concatenation in code and then I display output. I was wondering if there is any difference between following two codes:
string concat
$str = '';
for($x =0; $x <= 10000; $x++):
    $str .= 'I am string '. $x . "\n";
endforeach;

Output buffering
 ob_start();
 for($x =0; $x <= 10000; $x++):
    echo 'I am string ', $x , "\n";
 endforeach;
 $str = ob_get_contents();
 ob_end_flush();

A: Here's a benchmark for you:
<?php

$test_1_start = microtime();

$str = '';
for ( $x = 0; $x <= 10000; $x++ ) {
    $str .= 'I am string ' . $x . "\n";
}

$test_1_end = microtime();
unset($str);
echo 'String concatenation: ' . ( $test_1_end - $test_1_start ) . ' seconds';

$test_2_start = microtime();

ob_start();
for ( $x = 0; $x <= 10000; $x++ ) {
    echo 'I am string ', $x, "\n";
}
$str = ob_get_contents();
ob_end_clean();

$test_2_end = microtime();

echo "\nOutput buffering: " . ( $test_2_end - $test_2_start ) . ' seconds';

?>

My results:
$ php -v
PHP 5.3.4 (cli) (built: Dec 15 2010 12:15:07)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
$ php test.php
String concatenation: 0.003932 seconds
Output buffering: 0.002841 seconds%
$ php test.php
String concatenation: 0.004179 seconds
Output buffering: 0.002796 seconds%
$ php test.php
String concatenation: 0.006768 seconds
Output buffering: 0.002849 seconds%
$ php test.php
String concatenation: 0.004925 seconds
Output buffering: 0.002764 seconds%
$ php test.php
String concatenation: 0.004066 seconds
Output buffering: 0.002792 seconds%
$ php test.php
String concatenation: 0.004049 seconds
Output buffering: 0.002837 seconds%

Looks like output buffering + echo is consistently faster, at least in the CLI / on my machine.
Brendan Long made a good point in his comment, however — there is such a minor performance difference here that a choice of one or the other is not much of an issue.

A: I've made a benchmark, using OB is faster.
String: 0.003571 seconds
Output Buffer: 0.003053 seconds
StringBuilder (custom class Java/C#-Like): 0.050148 seconds
Array and Implode: 0.006248 seconds

A: at the first codes you write, you assign a string which will be kept until you unset the variable. It will stay in memory.
at the second one; op_start is to buffer the output. Until you end it, it will be stored in a buffer. ob end will send the ouput from the script and buffer will be cleaned.
instead of using variables or another thing; if you dont need to do anything with the output later, just use echo and free the memory. Don't use unnecessary variables.
another advantage of ob_start is that you can use it with a callback.
See here  http://php.net/manual/en/function.ob-start.php


text:
Q: django : calculate with function each line of your db I would like to calculate 'total' for each line, with the following code, it shows only last line total, not each line total.
class Invoice(models.Model):
    date = models.DateField(default=timezone.now)
    client = models.ForeignKey(Client,on_delete=models.CASCADE)

    def total(self):
        items = self.invoiceitem_set.all()
        for item in items:
            amount_due = (item.price * item.quantity)
        return round(amount_due, 2)

class InvoiceItem(models.Model):
    invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=20, decimal_places=2)
    quantity = models.DecimalField(max_digits=20, decimal_places=2)

{% for product in object.invoiceitem_set.all %}

    {{product.product}}
    {{product.price}}
    {{product.quantity}}
    {{object.total}}

{% endfor %}

A: You can try something like this:
class Invoice(models.Model):
    date = models.DateField(default=timezone.now)
    client = models.ForeignKey(Client,on_delete=models.CASCADE)
    # Total field for each invoice
    total = models.DecimalField(max_digits=20, decimal_places=2, default=0)

class InvoiceItem(models.Model):
    invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=20, decimal_places=2)
    quantity = models.DecimalField(max_digits=20, decimal_places=2)

    # Overriding the save method to update invoice total for each new item
    def save(self, *args, **kwargs):
        self.invoice.total += round(self.price * self.quantity, 2)
        self.invoice.save()
        super().save(*args, **kwargs)

{% for product in object.invoiceitem_set.all %}

    {{product.product}}
    {{product.price}}
    {{product.quantity}}
    {{product.invoice.total}}

{% endfor %}


text:
Q: How JSON format for calling Checking out REST Api of Broadleaf commerce looks like I have followed setting up Broadleaf to make it running by following its documentation (http://docs.broadleafcommerce.org/current/REST-Tutorials.html). I wanted to do checking out the cart using REST Api; that's, /cart/checkout. Therefore, I looked inside the code in order to understand how the JSON format being sent will look alike. By looking through the code, I found that it is required to pass the JSON data as shown following:
{
   "paymentInfo": {
      "id": ,
      "orderId": ,
      "type": ,
      "address": {
         "id":
         "firstname":
         "lastname":
         "addressLine1":
         "addressLine2":
         "city":
         "state":
         "country":
         "postalCode":

      },
      "phone": "",
      "additionalFields": "",
      "amount": "",
      "amountItems": "",
      "customerIpAddress": "",
      "referenceNumber": ""
   },
   "referenced": {
      "id": "",
      "referenceNumber": "",
      "type": "",
      "pan": "",
      "cvvCode:" "",
      "expirationMonth": "",
      "expirationYear": "",
      "accountNumber": "",
      "routingNumber": "",
      "pin": ""
   }
}

However, I have no idea such the JSON data looks like. Therefore, if anyone who has ever used the api, please help me by showing an example of data in order to make the request. Looking forward to the answers.
Thanks in advance.

A: All of our REST APIs are exposed through a 'wrapper' concept. For instance, there is a CustomerWrapper, OrderWrapper, etc. These wrappers define which properties are serialized back and forth with the REST APIs.
For your specific case, you should look at PaymentReferenceMapWrapper.

A: {
    "id": 1751,
    "status": "IN_PROCESS",
    "totalTax": {
        "amount": "0.00",
        "currency": "INR"
    },
    "totalShipping": {
        "amount": "0.00",
        "currency": "INR"
    },
    "subTotal": {
        "amount": "860.00",
        "currency": "INR"
    },
    "total": {
        "amount": "860.00",
        "currency": "INR"
    },
    "customer": {
        "id": 2600
    },
    "orderItems": [
        {
            "id": 1752,
            "name": "abc",
            "quantity": 2,
            "retailPrice": {
                "amount": "430.00",
                "currency": "INR"
            },
            "salePrice": {
                "amount": "430.00",
                "currency": "INR"
            },
            "orderId": 1751,
            "categoryId": 10300,
            "skuId": 10212,
            "productId": 10212,
            "isBundle": false,
            "orderItemPriceDetails": [
                {
                    "id": 1752,
                    "totalAdjustmentValue": {
                        "amount": "0.00",
                        "currency": "INR"
                    },
                    "totalAdjustedPrice": {
                        "amount": "860.00",
                        "currency": "INR"
                    },
                    "quantity": 2,
                    "adjustments": []
                }
            ],
            "isDiscountingAllowed": true
        }
    ],
    "fulfillmentGroups": [
        {
            "id": 1502,
            "orderId": 1751,
            "total": {
                "amount": "860.00",
                "currency": "INR"
            },
            "fulfillmentGroupItems": [
                {
                    "id": 1752,
                    "fulfillmentGroupId": 1502,
                    "orderItemId": 1752,
                    "totalTax": {
                        "amount": "0.00",
                        "currency": "INR"
                    },
                    "quantity": 2,
                    "totalItemAmount": {
                        "amount": "860.00",
                        "currency": "INR"
                    }
                }
            ]
        }
    ],
    "payments": [
        {
            "id": 601,
            "orderId": 1751,
            "type": "COD",
            "amount": "860.00",
            "currency": "INR",
            "gatewayType": "Passthrough",
            "transactions": [
                {
                    "id": 601,
                    "orderPaymentId": 601,
                    "type": "AUTHORIZE_AND_CAPTURE",
                    "success": true,
                    "amount": "860.00",
                    "currency": "INR"
                }
            ]
        }
    ]
}

This is the same json you will get from /cart?customerId="" with method GET after successfully executing /cart/checkout/payment


text:
Q: RabbitMQ Windows - Start Server automatically We are working with RabbitMQ on a Windows Environment.
At the moment I have installed RabbitMQ and it runs as a Service. It starts automatically as shown here:

But if I send a Message or if I query the server here: http://localhost:15672/#/queues the server returns 404
Now, if I open the Shell and hit this command:
rabbitmq-server

The server startup and I can send and receive messages and browse the administration page.
Questions:

*

*What is the difference then between RabbitMQ Windows Service and RabbitMQ Server?

*How can I have the RabbitMQ Server run as a daemon when the PC boot? Is there a command or configuration for that?

A: After further investigations I found out that all RabbitMQ have been installed before configuring the plugin rabbitmq_management and amqp_client so actually the Windows Service was running without doing anything.

*

*I fixed the problem on all my server by doing these steps:

*Remove RabbitMQ using rabbitmq-service stop, rabbitmq-service remove
Remember that the CMD must run under Administrator credentials on
Windows 10 and Windows Server 2012

*Install the plugin using
rabbitmq-plugins enable rabbitmq_management

*Re-install and start the serice rabbitmq-service install, rabbitmq-service start

*Also, I restarted Windows and verified that after the reboot the RabbitMQ was up and running.


text:
Q: How to connect python shell of aws glue to oracle database I am working on AWS Glue Python Shell. I want to connect the python shell with Oracle database.
I have successfully installed the library but when I tried to connect Oracle using cx_Oracle I am facing the following error
DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: "libclntsh.so: cannot open shared object file: No such file or directory.
I have downloaded oracle instant client put it s3 bucket and used its path as library path but still facing the same issue.
import cx_Oracle
conn_str = u'{username}/{password}@{host}:{port}/{sid}'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute(u'select * from hr.countries')
for row in c:
   print(row[0], "-", row[1])
conn.close()
print('hello I am here');


text:
Q: Does the body of the MOSFET consume current? Does the body of the MOSFET consume power and pass current if it weren't grounded? Like if I had a body bias and the value of Vsb wasn't zero, so in this case the diode inside the MOSFET must pass some current? Does it or not? And if it does, where does this current go and doesn't it make the MOSFET heat up?

A: Let's look at an NMOS sideview:

Realize that an PN-junction is a diode. So there is a diode between Source (anode) and Body (cathode) and a second diode between Drain (anode) and Body (cathode).
For normal operation we want these diodes not to be in forward mode which means \$V_{sb}\$ and \$V_{db}\$ should not be negative (drain and/or source having a lower voltage than Body).
So your question is, what happens if we do violate that rule ?
Well then these diodes can operate in forward mode! What really happens as a consequence of that depends on the actual situation (circuit, voltages etc.). Fact is that while normally all current flowing through the NMOS will enter at the Drain and leave at the Source.
This will no longer be the case when one of the body diodes operates in forward mode. Part of the current will then "escape" via the body (substrate). That current will then follow a different current loop, the current is not lost nor is it "consumed". How much current that will be depends on many factors like, (forward) voltage across the diode, drain current, substrate doping level (that influences the resistance of the substrate).
The current through the substrate will cause a voltage drop and just like with every other diode, power will be dissipated. So yes, the body/substrate will heat up. By how much depends on the amount of power that is dissipated and what the thermal resistance to the outside world is.
You should realize that Drain-Body and Source-Body diodes behave just like any other diode so current will flow when in forward and power will be dissipated. These diodes do not have a "magic" property which makes them different from other diodes. Think about this: would it make sense for a diode not to conduct current when in forward mode or would it make sense that it does not dissipate power when clearly it is consuming power because there is a forward voltage and a current.

A: I've seen transient effects, with drain slew_rates of 1 volt per nanosecond, where the induced I = C * dV/dT causes enough voltage drop in the substrate to trigger the parasitic bipolar.
[notice in the diagram provided by Blimpelrekkie there is a lateral NPN, with the base being bulk/well/substrate/tub.]
If the current is not limited (tickling the dragon, I call it), then the FET/bipolar becomes a fuzed mass of silicon.
Cure was to update the layout rules, and capture more of that transient current into substrate/well ties.
Failure voltages improved by 50%.
The travails of undocumented inherited highly-profitable semiconductor processes and products.
Would being "grounded" help with this? No. There is no way to get under the FET, within a few microns of where the transient currents were injected, and grab ahold of the silicon, without massive and expensive changes to the process.


text:
Q: Need help with a regular expression In my .NET app, I am required to parse text, which can have inline conditions, like this:

Here is some text. {{if: condition }} Here is some conditional text. {{endif}} Here is more text.

And so I have written the following regular expression to find these conditions:
\{\{if\:(?<condition>[^\}]+)\}\}(?<value>.+)\{\{endif\}\}

This has worked fine for me, and achieved what I want, until I have had to deal with an input with two conditions:

{{if: condition }} content {{endif}} some other content {{if: condition2 }} content2 {{endif}}

In this case, my regular expression picks up the entire string, starting with the {{if}} of the first condition, and ending with the {{endif}} of the second condition, making my applciation not work correctly.
How can I rewrite my regular expression to make this work? Or do I have to achieve it without regular expressions?
EDIT: I should have said the content within the conditions can also have double curly brackets to represent other constructs, and so it's not as simple is just ignoring those!
NOTE: There is also the potential issue of nested conditions, but I don't think I'll have to worry about those!

A: Your problem is the greedy quantifier for the value group. Use this:
\{\{if\:(?<condition>[^\}]+)\}\}(?<value>.+?)\{\{endif\}\}


text:
Q: dynamic database driven menus in VB.Net I'm trying to construct a database driven VB.Net app that pulls a list of registered accounts from a database and displays the usernames of throes accounts in menu, so the user can select one and a new form open (where they work with it).
what I have so far is the constructor for the MDI parent window
Public Sub New()

    InitializeComponent()

    Dim tsmi As New ToolStripMenuItem("Users", Nothing, AddressOf users_mousedown)
    MenuStrip1.Items.Add(tsmi)

End Sub

The handler for the user menu (where SQLite_db is a class that looks after the database and user_class is a class with two items (username and password) as strings.
Sub users_mousedown()

    Dim submenu As New ContextMenuStrip
    Dim database As New SQLite_db

    Dim user_list As New List(Of user_class)
    user_list = database.List_Users

    For Each user As user_class In user_list
        submenu.Items.Add(user.username, Nothing, AddressOf Open_new_window(user))
    Next

    submenu.Items.Add("Add new user", Nothing, AddressOf AddNew)
    submenu.Show(Control.MousePosition)

End Sub

What I want to happen is when a user clicks on the context menu a new MDI child form is created and the data in user is passed, however because AddressOf doesn't like passing data this doesn't work...
I've looked at delegates and landa expressions but don't think either of them do what I need, the other option is to make my own subclass of the ContextMenuStrip class, which 1) handles the clicks the way I want to and 2) sounds like a nightmare.
Before I launch into what I think will be a hell of a lot of work, am I missing something? is their a simple way to do what I want to do? or if not will sub-classing ContextMenuStrip work and if not any ideas as to what will (and if it will, any ideas as to how to start learning how to do that)

A: A simple way to encapsulate user info is with a Helper Class, where you store the context info.

Public Class Question1739163
    Class HelperUserCall
        Public userId As String

        Sub New(ByVal id As String)
            userId = id
        End Sub

        Public Sub OnClick()
            MsgBox(Me.userId)
        End Sub
    End Class
    Private Sub Question1739163_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim t As New ToolStripMenuItem("Users", Nothing, AddressOf user_mousedown)
        MenuStrip1.Items.Add(t)
    End Sub

    Public Sub user_mousedown()
        Dim s As New ContextMenuStrip
        Dim a As HelperUserCall

        a = New HelperUserCall("u1")
        s.Items.Add(a.userId, Nothing, AddressOf a.OnClick)

        a = New HelperUserCall("u2")
        s.Items.Add(a.userId, Nothing, AddressOf a.OnClick)

        s.Items.Add("New User", Nothing, AddressOf add_new)
        s.Show(Control.MousePosition)
    End Sub

    Sub add_new()
        MsgBox("add new")
    End Sub
End Class

You could improve the helper class adding the reference to database in the constructor, and retrieving the user info when the user click into the option.


text:
Q: PySide6.QtTest.QTest.mouseClick() - not exposed - is it not meant to be used? I got the code below from this answer
In the docs, mouseClick is not listed but it's present in QtTest.py and usable.
Does that mean it's deprecated?
import sys

import unittest
import threading

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox, QApplication
from PyQt5.QtTest import QTest

class Fortest:
    def messagebox(self):
        app = QApplication(sys.argv)
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setText("message text")
        msg.setStandardButtons(QMessageBox.Close)
        msg.buttonClicked.connect(msg.close)
        msg.exec_()

class Test(unittest.TestCase):
    def testMessagebox(self):
        a = Fortest()
        threading.Timer(1, self.execute_click).start()
        a.messagebox()

    def execute_click(self):
        w = QApplication.activeWindow()
        if isinstance(w, QMessageBox):
            close_button = w.button(QMessageBox.Close)
            QTest.mouseClick(close_button, Qt.LeftButton)


text:
Q: if else shorthand in C Is the statement below a kind of shorthand? i need someone help me understand with it.
#define clean_errno()(errno == 0? "None": strerror(errno))

From the execution result, I guess it means once  I confront clean_errno(),if errno ==0, I replace clearn_errno() with None, if not, I replace clean__errno() with strerror(errno). but I don't know how to analyse this statement logically?

A: Preprocessor macros are replaced in their call-sites.
That means a statement like
printf("Error = %s\n", clean_errno());

will be replaced by
printf("Error = %s\n", (errno == 0? "None": strerror(errno)));

That will then at run-time print either "None" if errno == 0, otherwise print the result of strerror(errno).
As for the ?: expression itself, it is the conditional (a.k.a. the ternary) expression, and it works similar to a if-else.
However, using a macro like this is not something I would recommend, as the value of errno is usually undefined if a function doesn't fail. You need to make sure the previous function actually did fail before checking errno, in which case it will never be zero. There are very few places where errno will be reset to zero unless you specifically do it beforehand and know that the function you call will not modify it unless there's an error.

A: The code is evaluated during runtime and follows the shorthand:
condition ? if_true : if_false

This shorthand is very similar to a regular if else statement.
However, unlike normal if else in C, the shorthand can be used as an expression as well as a statement. i.e.:
char * str = 1 ? "true" : "false";

... which doesn't work so well with if else (char * str = if ... probably wouldn't work).
Try it with 0 ? "true" : "false" and test it out.
Good luck!


text: Q: How do we determine which steady state a given set of initial condition approaches in a system? If we have an ordinary differential equation system with multiple steady states, how do we determine which steady state a given set of initial condition approaches in a system?


text:
Q: What is the function of unit test in jira software enter image description here
While working on the team project, I saw that cumin software has an option called unit testing. I want to know how to work with this option.

A: I can give you a generic definition of unit tests, the meaning of which is common across the software engineering field.
Unit tests are used to verify individual pieces of code like functions. For example - testing that your sort function actually sorts an array properly by giving it some sample inputs and checking the outputs automatically.
This is in contrast to integration tests, which are used to test the entire application as a whole. For example, testing your UI to see if it handles user interactions correctly.


text:
Q: Как можно присвоит значение если имя свойства совпадает с ключом объекта JObject? У меня есть класс
public class ClientDossierModel
{
    public string Name{ get; set; }
    public string Adress{ get; set; }
    public string Param{ get; set; }
}

И JObject объект
{"Name": "Addasd", "Address":"USA}
Как можно присвоит значение если имя свойства класса совпадает с ключом объекта JObject


text:
Q: struggling to populate lookupEdit problem! I am using the devexpress lookupedit control, and I have set the EditValue property(SocklocationBindingSource - Location).  When you click on the black little arrow ON the control itself, the datasource, displaymember and valumember are set.  I run my app and see [editvalue is null] in the actual control?
What else must i set?
What on earth am i doing wrong?
I use VS 2009

A: Are you trying to populate the lookUpEdit by all locations in the datasource + make EditValue take the selected location?, if so you can do this:
lookUpEdit1.Properties.DataSource = SocklocationBindingSource;
lookUpEdit1.Properties.DisplayMember = "Location";
lookUpEdit1.Properties.ValueMember = "Location";
lookUpEdit1.Properties.PopulateColumns();

(via Code or Designer)

A: You are not doing anything wrong, the LookUpEdit control does not have an EditValue by default.  Consider data binding the EditValue property to an object.  If you have already done this then you could set a default edit value to get the editor to function.
Also, the 'EditValue is Null' flavor text can be changed in Properties.NullText.

A: Did you set the Properties->Columns values?

A: I had the same problem you described, but it depends on how you are using the data, what data structures you are using, the events you are using, etc...
Here's what worked for me:
http://www.devexpress.com/Support/Center/p/Q350641.aspx

A: You must bind the SocklocationBindingSource with a proper data source such as an IList or Datatable.
ex:
SocklocationBindingSource.DataSource = MyBiz.GetAllObjs();
[editvalue is null] is displayed when the DataSource is null. You can change this in properties.

A: Definition you should check the DisplayMember and ValueMember property. View an example here: http://itjungles.com/devexpress/how-to-easily-populate-devexpress-lookupedit-in-c


text:
Q: ASP.NET MVC Action calls another action but doesn't trigger OnActionExecuting for the second one I have a custom ActionFilterAttributes in my solution, and using OnActionExecuting to do some logs.
However, the problem occurs because I want to trace the entire path taken during an action, and if by chance an action makes a call to another for some reason OnActionExecuting only triggers on the first call.
This is my ActionFilterAttribute
public class LogFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Log(filterContext.ActionDescriptor.ActionName)
    }
}

This is an example of a action that calls another.
[LogFilterAttribute]
public class CarouselController
{

    public ActionResult GetCarousel()
    {
        return ShowDialog()
    }

    public ActionResult ShowDialog()
    {
        //some code
    }
}

In my understanding, after the GetCarousel action is called, the OnActionExecuting should be triggered twice, once with the value of GetCarousel and another with the value of showDialog. However this is not the resulting behavior because it is only triggered for the first action.
What will be the problem? how can i get the expected result?
Thanks in advance


text:
Q: JS UTF-8 Decoding Issues: "0"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the "0o" prefix instead I've been banging my head off a wall trying to get this work, any help appreciated.
I essentially have a string that might looks like this "jas\303\241nek" and I want to convert it to a string that looks like this "jasánek". I've used [this site]https://mothereff.in/utf-8 which successfully managed to decode the string to the desired output, and wanted to integrate it into my site. This site uses a npm package utf8 which I've been trying to get working. It appeared that writing code like this wasn't sufficient in making the translation:
const utf8 = require('utf8')
let string = "jas\303\241nek"
let translation = utf8.decode(string);
console.log(translation)

Upon seeing this only returned the original string I realised the functionality wasn't what I assumed so I dug into the code for the initial translation site and saw it uses this syntax:
utf8.decode(eval('\'' + encoded.value + '\''));

So I tried implementing some variation of this like this:
const utf8 = require('utf8')
let string = "jas\303\241nek"
let translation = utf8.decode(eval('\'' + string + '\'');
console.log(translation)

Which returns an error that I don't understand:
SyntaxError: "0"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the "0o" prefix instead

And now I'm stuck. Any suggestions for how I might be able to resolve this problem?

A: So the issue ended up being trying to do the utf8 translations on the frontend with the library. I discovered this when trying to console.log the sample string and getting the string back instead of the value of the symbols.
To fix this I did the utf8 translations on the express server that sent it to the frontend and this resolved the problem.
Thanks all for the suggestions.


text:
Q: Конструктор по умолчанию для типа T (шаблоны классов) Есть реализация vector, не из пространства std, но примерно похожего по функциональности.
Вот некоторые выдержки серверной части и клиентской.
Файл Vect.h
#pragma once
#include <iostream>
#include <string>
#include "VectError.h"

template<typename T>class Vect {
public:
    explicit Vect() :first(0), last(0) {}
    explicit Vect(size_t _n, const T& _v = T()) {//интересующая часть, как
                                         //работает конструктор T(), откуда он??
        Allocate(_n);
        for (size_t i = 0; i < _n; ++i)
            *(first + i) = _v;
    }
    Vect(const Vect&);
    Vect& operator=(const Vect&);
    ~Vect()
    {
#ifdef DEBUG
        cout << "Destructor of " << markName << endl;
#endif // DEBUG
        Destroy();
        first = 0, last = 0;
    }
    void mark(std::string& name) { markName = name; }
    std::string mark()const { return markName; }
    size_t size()const;
    T* begin()const { return first; }
    T* end()const { return last; }

    T& operator[](size_t i);
    void insert(T* _P, const T& _x);
    void push_back(const T& _x);
    void pop_back();
    void show()const;
protected:
    void Allocate(size_t _n) {
        first = new T[_n * sizeof(T)];
        last = first + _n;
    }
    void Destroy() {
        for (T* p = first; p != last; ++p)p->~T();
        delete[] first;
    }
    T* first;
    T* last;
    std::string markName;
};

Выдержки из main.cpp
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include "Vect.h"
#include <string>
...
int main()
{
  try
  {
    Vect<int> v1(10);// вызывается конструктор
                     //explicit Vect(size_t _n, const T& _v = T())...
    v1.mark(string ("v1"));
    size_t n = v1.size();
    for (int i = 0; i < n; ++i)v1[i] = i + 1;
    v1.show();
  ....
}

Не понятно почему в Vect<int> v1(10) _v в выраженииconst T& _v = T() по умолчанию приравнивается нулю, (откуда?) и почему можно игнорировать вообще полное заполнение, ведь по моему здесь нет соответствующей перегрузки конструктора. Заранее спасибо.

A: Данный конструктор
explicit Vect(size_t _n, const T& _v = T()) {//интересующая часть, как
                                     //работает конструктор T(), откуда он??
    Allocate(_n);
    for (size_t i = 0; i < _n; ++i)
        *(first + i) = _v;
}

имеет аргумент по умолчанию для второго параметра, который равен значению выражения T(). Поэтому вы можете вызывать этот конструктор, не указывая второй аргумент для конструктора, как в вашем примере
Vect<int> v1(10);

В качестве второго аргумента будет использоваться это значение по умолчанию, которое присутствует в объявлении конструктора.
Выражение T() имеет название инициализация значением. Для фундаментальных типов такая инициализация соответствует инициализации объекта нулем.
Из стандарта C++ (8.5 Initializers)

10 An object whose initializer is an empty set of parentheses, i.e.,
  (), shall be value-initialized

И далее

7 To value-initialize an object of type T means:
...
  — otherwise, the object is zero-initialized.

И, наконец,

5 To zero-initialize an object or reference of type T means:
— if T is a scalar type (3.9), the object is set to the value 0
  (zero), taken as an integral constant expression, converted to T;

Рассмотрите следующий простой пример.
#include <iostream>

void f(int x = 10, int y = int())
{
    std::cout << "x = " << x << ", y = " << y << std::endl;
}

int main()
{
    f();
    f(1);
    f(1, 2);
}

Вывод этой программы на консоль будет выглядеть так
x = 10, y = 0
x = 1, y = 0
x = 1, y = 2


text:
Q: После изменения имени программы диспетчер задач выводит старое Возникла необходимость поменять имя исполняемого файла одной проги. Сделал стандартно - просто переименовал. Теперь самое интересное: tasklist выводит имя процесса новое, а диспетчер задач старое. Компьютер был перезагружен для чистоты эксперимента. Как это возможно и что делать?

A: Диспетчер задач вывод описание файла (2), а tasklist - название файла (1). Чтобы изменить описание, можно воспользоваться программами наподобие ResEdit.


text:
Q: Angular 4 firebase// function not found in callback Hope you can help me. I am trying to get a callback from firebase. Here is my code
createAccount() {

        this.afAuth.auth.createUserWithEmailAndPassword(this.email, this.password)

            .then(function (message) {
                console.log(message);
                this.setUserProfile();
            })
            .catch(function (e) {
                console.log(e);
            });

}
setUserProfile() {
    // some stuff
}`

I try to call this.setUserProfile() in callback. The problem is when I set this.setUserProfile() in the callback they don't find this function anymore console.log works without any problems.

A: using arrow function to keep the context.
this.afAuth.auth.createUserWithEmailAndPassword(this.email, this.password)

        .then((message) => {      //  <---- use error function here
            console.log(message);
            this.setUserProfile();
        })
        .catch(function (e) {     //  <---- if you use "this" in error callback, change it to arrow function too
            console.log(e);
        });


text:
Q: D3 v5 center path line in a bar graph I am using d3.js v5 to plot a bar graph , Porblem is while creating a bar graph and and appending path along with bars , paths are not making to  the center of a bar instead of that it is placed on the start point , is there any way to center the point, Currently the graph showing is like this

But i want the small circles and points to be in the center
sorry for bad image i am just visualizing my concept brown lines are in center and will be connected by path

var margin = {
    top: 10,
    right: 30,
    bottom: 90,
    left: 40
  },
  width = 900 - margin.left - margin.right,
  height = 400 - margin.top - margin.bottom;
this.x_axis = Array(20).fill(0).map((x, i) => (i + 1) * 5);
this.y_axis = [1.1, 2.2, 3.5, 4.9, 5.3, 6.9, 7.3, 8.1, 9.2, 8.2, 1.3, 0.1, 0.1, 0.4, 0.1, 0.4, 0.2, 0.4, 0.1, 0.2];

let data = [];
for (let i = 0; i < this.x_axis.length; i++) {
  data.push({
    Country: this.x_axis[i],
    Value: this.y_axis[i]
  })
}
var svg = d3.select("#graph")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

// Parse the Data

// X axis
var x = d3.scaleBand()
  .range([0, width])
  .domain(data.map(function(d) {
    return d.Country;
  }))
  .padding(0.3);
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x))
  .selectAll("text")
  .attr("transform", "translate(-10,0)rotate(-45)")
  .style("text-anchor", "end");

// Add Y axis
var y = d3.scaleLinear()
  .domain([0, 20])
  .range([height, 0]);
svg.append("g")
  .call(d3.axisLeft(y));

var x2 = d3.scaleBand()
  .range([0, width]);

// Bars
svg.selectAll("mybar")
  .data(data)
  .enter()
  .append("rect")
  .attr("x", function(d) {
    return x(d.Country);
  })
  .attr("width", x.bandwidth())
  .attr("fill", "#69b3a2")
  // no bar at the beginning thus:
  .attr("height", function(d) {
    return height - y(0);
  }) // always equal to 0
  .attr("y", function(d) {
    return y(0);
  })

// Animation
svg.selectAll("rect")
  .transition()
  .duration(800)
  .attr("y", function(d) {
    return y(d.Value);
  })
  .attr("height", function(d) {
    return height - y(d.Value);
  })
  .delay(function(d, i) {
    console.log(i);
    return (i * 100)
  })

svg.append("path")
  .datum(data)
  .attr("fill", "none")
  .attr("stroke", "black")
  .attr("stroke-width", 1)
  .attr("d", d3.line()
    .x(function(d) {
      return x(d.Country)
    })
    .y(function(d) {
      return y(d.Value)
    }))

svg.selectAll("myCircles")
  .data(data)
  .enter()
  .append("circle")
  .attr("fill", "red")
  .attr("stroke", "none")
  .attr("cx", function(d) {
    return x(d.Country)
  })
  .attr("cy", function(d) {
    return y(d.Value)
  })
  .attr("r", 3)

A: Since you're using a scaleBand, the axis automatically returns not the center, but the top left of the rectangle, by offsetting by about x.bandwidth() / 2. One workaround for this would be to use return x(d.Country) + x.bandwidth() / 2 to find the center of the bars.

var margin = {
    top: 10,
    right: 30,
    bottom: 90,
    left: 40
  },
  width = 900 - margin.left - margin.right,
  height = 400 - margin.top - margin.bottom;
this.x_axis = Array(20).fill(0).map((x, i) => (i + 1) * 5);
this.y_axis = [1.1, 2.2, 3.5, 4.9, 5.3, 6.9, 7.3, 8.1, 9.2, 8.2, 1.3, 0.1, 0.1, 0.4, 0.1, 0.4, 0.2, 0.4, 0.1, 0.2];

let data = [];
for (let i = 0; i < this.x_axis.length; i++) {
  data.push({
    Country: this.x_axis[i],
    Value: this.y_axis[i]
  })
}
var svg = d3.select("#graph")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

// Parse the Data

// X axis
var x = d3.scaleBand()
  .range([0, width])
  .domain(data.map(function(d) {
    return d.Country;
  }))
  .padding(0.3);
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x))
  .selectAll("text")
  .attr("transform", "translate(-10,0)rotate(-45)")
  .style("text-anchor", "end");

// Add Y axis
var y = d3.scaleLinear()
  .domain([0, 20])
  .range([height, 0]);
svg.append("g")
  .call(d3.axisLeft(y));

var x2 = d3.scaleBand()
  .range([0, width]);

// Bars
svg.selectAll("mybar")
  .data(data)
  .enter()
  .append("rect")
  .attr("x", function(d) {
    return x(d.Country);
  })
  .attr("width", x.bandwidth())
  .attr("fill", "#69b3a2")
  // no bar at the beginning thus:
  .attr("height", function(d) {
    return height - y(0);
  }) // always equal to 0
  .attr("y", function(d) {
    return y(0);
  })

// Animation
svg.selectAll("rect")
  .transition()
  .duration(800)
  .attr("y", function(d) {
    return y(d.Value);
  })
  .attr("height", function(d) {
    return height - y(d.Value);
  })
  .delay(function(d, i) {
    console.log(i);
    return (i * 100)
  })

svg.append("path")
  .datum(data)
  .attr("fill", "none")
  .attr("stroke", "black")
  .attr("stroke-width", 1)
  .attr("d", d3.line()
    .x(function(d) {
      return x(d.Country) + x.bandwidth() / 2;
    })
    .y(function(d) {
      return y(d.Value)
    }))

svg.selectAll("myCircles")
  .data(data)
  .enter()
  .append("circle")
  .attr("fill", "red")
  .attr("stroke", "none")
  .attr("cx", function(d) {
    return x(d.Country) + x.bandwidth() / 2
  })
  .attr("cy", function(d) {
    return y(d.Value)
  })
  .attr("r", 3)


text:
Q: Facebook Tag photo with contacts synced in the phone contact list [iOS] I am building a photo editing editing app.
I want that user should be able to tag the photos using the fb contacts synced in the contact list of the phone, which he can share later.
Is that possible using facebook sdk.

A: Using Facebook Open Graph actions you can tag friends. Look here: developers.facebook.com/docs/opengraph/actions/#taggingpeople


text:
Q: wordpress not loading on localhost I have a localhost website bm.ourdomain.local on our Mac machine (running AMPPS).
It has an entry in /etc/hosts:
<local IP> bm.ourdomain.local

It has an entry in /Applications/AMPPS/Apache/conf/extra/vhosts.conf:
<VirtualHost *:80>
    ServerAdmin hello@ourdomain.local
    DocumentRoot "/Applications/AMPPS/www/bm.ourdomain.local"
    ServerName bm.ourdomain.local
    ServerAlias bm.ourdomain.local
    ErrorLog "/Applications/AMPPS/www/bm.ourdomain.local/error_log"
    CustomLog "/Applications/AMPPS/www/bm.ourdomain.local/access_log" common
</VirtualHost>

When I load bm.ourdomain.local in Chrome, nothing happens, the loading icon just spins.
If I turn on debug, debug.log doesn't get created.
If I rename plugins to plugins.temp, nothing changes, same with themes to themes.temp.
There is Wordfence installed, and I have confirmed .htaccess and .user.ini contain the correct path to wordfence-waf.php.
There is no error_log.
If I clear the browser cache of files and cookies, nothing changes.
Other websites on the local server run fine, on vhosts.
Help appreciated.

A: Restarting the AMPPS server resolved this issue.
Every day since the problem the website has loaded fine since, so it looks like the problem was isolated to one occurrence.


text:
Q: How to use GPUImageLookupFilter without GPUImageFilterGroup? I have a problem with understanding GPUImage.
Specifically, I can't figure out how to use GPUImageLookupFilter. I have several examples of usage in GPUImageAmatorkaFilter for example.
But LookupFilter used there within GPUImageFilterGroup which I didn't understood yet either.
I wonder whether I can use LookupFilter alone.
I've tried this:
GPUImageLookupFilter *lookup = [[GPUImageLookupFilter alloc] init];

UIImage *image = [UIImage imageNamed:@"amatorka.png"];
GPUImagePicture *lookupImageSource = [[GPUImagePicture alloc] initWithImage:image];
[lookupImageSource addTarget: lookup atTextureLocation: 1];
[lookupImageSource processImage];

GPUImagePicture *inputImg = [[GPUImagePicture alloc] initWithImage:inputImage];
[inputImg addTarget:lookup atTextureLocation: 1];
[inputImg processImage];

UIImage *quickFilteredImage = [lookup imageFromCurrentlyProcessedOutput];

But it doesn't work, it crashes like this:
Assertion failure in -[GPUImageLookupFilter createFilterFBOofSize:], PathToSource/GPUImageFilter.m:369
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Incomplete filter FBO: 36054'

I definitely need to initialize something else, but ... .
So, can anyone help me to make this small piece of code work?
Thanks in advance.

A: Thanks to Brad Larson for answering:

For one thing, you're adding both of your images to texture location 1, so one is overriding the other. You need to add your input image to texture location 0 and lookup pattern to location 1, I believe.

A: This is how I personally use it:
- (UIImage *)filterImage:(GPUImagePicture *)originalImageSource withLUTNamed:(NSString *)lutName
{
    GPUImagePicture *lookupImageSource = [[GPUImagePicture alloc] initWithImage:[UIImage imageNamed:lutName]];
    GPUImageLookupFilter *lookupFilter = [[GPUImageLookupFilter alloc] init];

    [originalImageSource addTarget:lookupFilter];
    [lookupImageSource addTarget:lookupFilter];

    [lookupFilter useNextFrameForImageCapture];
    [originalImageSource processImage];
    [lookupImageSource processImage];

    return [lookupFilter imageFromCurrentFramebufferWithOrientation:UIImageOrientationUp];
}


text:
Q: Smartfield annotation for showing names of the key variables does not work. Do you have any idea about it? I implement annotation as shown is SDK, but it doesn't affect my smartfield. Still, it shows only key value. But I want to show that like 'description(key)'. Do you have any idea?
My annotation code:
            <Annotations Target="xxx.xxSh/Posid">
                <Annotation Term="Common.Text" Path="Post1">
                    <Annotation Term="UI.TextArrangement" EnumMember="UI.TextArrangementType/TextLast"/>
                </Annotation>
            </Annotations>
            <Annotations Target="xxx.xxar/Parnr">
                <Annotation Term="UI.TextArrangement" EnumMember="UI.TextArrangementType/TextFirst"/>
                <Annotation Term="Common.ValueList">
                    <Record Type="Common.ValueListType">
                        <PropertyValue Property="CollectionPath" String="xxShSet"/>
                        <PropertyValue Property="SearchSupported" Bool="true"/>
                        <PropertyValue Property="Parameters">
                            <Collection>
                                <Record Type="Common.ValueListParameterDisplayOnly">
                                    <PropertyValue Property="ValueListProperty" String="Post1"/>
                                </Record>
                                <Record Type="Common.ValueListParameterInOut">
                                    <PropertyValue Property="LocalDataProperty" PropertyPath="Parnr"/>
                                    <PropertyValue Property="ValueListProperty" String="Posid"/>
                                </Record>
                            </Collection>
                        </PropertyValue>
                    </Record>
                </Annotation>
            </Annotations>

my xml code:
<smartField:SmartField value="{Parnr}" textInEditModeSource="ValueList" change="onParnrChange">
                                            <smartField:configuration>
                                                <smartField:Configuration preventInitialDataFetchInValueHelpDialog="false"/>
                                            </smartField:configuration>
                                        </smartField:SmartField>

A: Have you tried adding this to the xml? This will display description and Id.                       <smartField:configuration> <smartField:Configuration displayBehaviour="descriptionAndId"/> </smartField:configuration>


text:
Q: Restricting tableau filter options without changing underlying data or display I am looking for a way to restrict the filter options on a dashboard without changing the underlying data or display.
For example, with a dataset of
Company A: 10 units.
Company B: 5 units.
Company C: 2 units.
I would like the Total Units to display as 17 when no filter is applied, however I would only like to show 'Company A' as an option in the filter.

A: I can't see your data, so I'm approximating the column names and values. You'll have to adjust these on your end.
Create a parameter, like CompanyFilterParameter, with the values 'Company A' and 'All'.
Create a calculated field to use as your filter, CompanyFilter:
[CompanyFilterParameter] = [Company] OR [CompanyFilterParameter] = 'All'

Put [CompanyFilter] on the Filter card and set it to true. Finally, add your parameter control to the sheet (right click [CompanyFilterParameter] and select "Show Parameter Control").


text:
Q: How to safely "pop-front" from std::map without extra copy? I have a std::map object.
std::map<std::string, std::string> m;

m.insert({ "abcd", "foo" });
m.insert({ "1234", "bar" });

and I want to get and remove the first element, like:
auto iter = m.begin();
auto [key, value] = std::move(*iter);
m.erase(iter);
do_something_with(key, value);

Is this considered safe?
(Moving from the iterator should make the key an empty string, which makes the m an invalid map.)

A: You can use std::map::extract like this:
auto nh = m.extract(m.begin());

and then use the key and value like this:
do_something(nh.key(), nh.mapped());

This has the needed property that no extra copies are made.

A:
Is this considered safe?

On the condition that the map isn't empty, yes.
However, note that the key will be a deep copy; not moved one. This is because the the key of the map element is const.

How to safely "pop-front" from std::map without extra copy?

It is possible to move from the key too, if you use the extract member function:
auto handle = m.extract(m.begin());
// if you need separate objects:
auto key = std::move(handle.key());
auto mapped = std::move(handle.mapped());

A: Use std map extract.  Using the resulting node handle, move the key/value to your key/value variables.
Prior to std map extract, this isn't fully possible.  std map extract was added to let you do this, and similar operations like splicing maps.


text:
Q: Reading BSD500 groundTruth with scipy I am trying to load using scipy loadmat a ground truth file, it return numpy ndarray of type object (dtype='O').
From that object I arrive to access to each element that are also ndarrays but I am struggling from that point to access to either the segmentation or the boundaries image.
I would like a to transform this a list of list of ndarray of numerical types how can I do that ?
Thanks in advance for any help

A: I found a way to fix my issue.
I do not think it is optimal but it works.
def load_bsd_gt(filename):
    gt = loadmat(filename)

    gt = gt['groundTruth']

    cols = gt.shape[1]

    what = ['Segmentation','Boundaries']

    ret = list()

    for i in range(cols):
        j=0
        tmp = list()
        for w in what:
            tmp.append(gt[0][j][w][0][0][:])
            j+=1
        ret.append(tmp)

    return ret

If someone have a better way to do it please feel free to add a comment or an answer.