text:
Q: C++ macro integers and object definitions I lack of experience with C++ and I am trying to create a Settings file to put all my definitions and global variables there, so my project's classes can access those the values from there. The Settings.h file could look like this:
#ifndef SETTINGS_H_
#define SETTINGS_H_

#define COLOR_BLUE = Vec3b(255, 0, 0);
#define COLOR_GREEN = Vec3b(0, 255, 0);
#define NOT_SET = 0;
#define IN_PROCESS = 1;
#define SET = 2;
#define FGD_PX = 255;
#define BGD_PX = 127;

#include <cv.h>
using namespace cv;

class Settings {
};
#endif /* SETTINGS_H_ */

The idea is to access the variables without instantiate the class but just including it.
Is there any beautiful way to do this?
cheers,

A: #include <cv.h>
using namespace cv;

#ifndef SETTINGS_H_
#define SETTINGS_H_

#define COLOR_BLUE Vec3b(255, 0, 0)
#define COLOR_GREEN Vec3b(0, 255, 0)
#define NOT_SET 0
#define IN_PROCESS 1
#define SET 2
#define FGD_PX 255
#define BGD_PX 127

class Settings {
public:
   static int var1;
   static float var2;
   static short var3;
};

// initialization
int Settings::var1 = SET;
float Settings::var2 = 3.14;
short Settings::var3 = BGD_PX;

#endif /* SETTINGS_H_ */

Usage:
int tmp = Settings::var1;

A: Constants either go in enums, or as static consts.  Manifest constants generally are reserved for compiler type options:
#ifndef SETTINGS_H_
#define SETTINGS_H_

class Settings {
public:
   static const vec3b color_blue;
   static const vec3b color_green;
   enum statics {
         NOT_SET = 0,
         IN_PROCESS = 1,
         SET = 2,
         FGD_PX = 255,
         BGD_PX = 127
   };

};

vec3b Settings::color_blue(255, 0, 0);
vec3b Settings::color_green(0, 255, 0);

#include <cv.h>

#endif

A: You shouldn't have equals signs or semicolons with #defines.  What do you plan on putting in your Settings class?


text:
Q: Convert Keras model output into sparse matrix without forloop I have a pretrained keras model that has output with dimesion of [n, 4000] (It makes the classification on 4000 classes).
I need to make a prediction on the test data (300K observations).
But when I call method model.predict(X_train), I get an run-out memory error, because I don't have enough RAM to store matrix with shape (300K , 4000).
Therefore, it would be logical to convert the model output to a sparse matrix.
But wrapping the predict method into scipy function sparse.csr_matrix does not work (sparse.csr_matrix(model.predict(X_train))), because it first allocates space in the RAM for the prediction, and only then it converts into the sparse matrix.
I can also make a prediction on a specific batch of test data, and then convert it using forloop.
But it seems to me that this is not optimal and very resource-consuming way.
Please give me advice, can there be any other methods for converting the model output into a sparse matrix?

A: Isn't there a batch_size parameter in the predict()?
If I get it correct the n means number of sample right?
Assume that you system ram is enough to hold the entire data but the VRAM is not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: automate postgresql data migration, preferably a fabric task My web stack is django/python + postgresql + linux + apache. I use fabric to automate the deployment from local to the server. For the deployment automation, I wish I could include data migration from my local database to the corresponding database on the server. Is there a way to do that? I prefer to see the data migration becoming a fabric task, if possible.

A: I think you need to somehow export the data to a file / files, copy to the target server, and import them. The utilities to do this in Django (documentation) are dumpdata and loaddata.
So on the local database:
django-admin.py dumpdata > mydata.json

Then to the server:
fabric.api.put('mydata.json','/server/data/dir/')
fabric.api.run('django-admin.py loaddata mydata.json')

You should also have a look at South, which is a database migration tool for Django.


text:
Q: Vue package Version mismatch Am getting a Vue packages version mismatch:Vue packages version mismatch even after updating Vue and vue-template-compiler to the same version The console prints
Vue packages version mismatch:
- vue@2.6.10
- vue-template-compiler@2.5.16
I have confirmed from my package.json that both Vue and vue-template-compiler are of the same version .ie 2.6.10  .Please Help

A: Either run npm update, or remove your node_modules + package-lock.json then npm install.

A: since you confirming from your question that both versions of vue and vue-template-compiler have the same version numbers, then delete your node_modules folder and package-lock.json then run
npm install
will help reinstall packages with the right version specified in your package.json file
Running the following command helped me
npm install vue-template-compiler@2.5.16 --save-dev
NB. Replace the version number with the right version that you need. In my case, the version of vue was 2.5.16 and vue-template-compiler was 2.5.13 hence I updated the vue-template-compiler to the version of the vue.
Hope this helps someone
Vue packages version mismatch error fix


text:
Q: Calculating a limit with exponent and trig function I got this limit to calculate:
$$
\lim_{x\to\frac{\pi}{2}}(\tan x)^\frac{1}{x-\frac{\pi}{2}}
$$
I'm trying to solve it with De L'Hopitals rule and the first step should be this, I guess:
$$
\lim_{x\to\frac{\pi}{2}}e^\frac{\ln(\tan x)}{x-\frac{\pi}{2}}
$$
Then I'm trying to solve the limit of the exponent:
$$
\lim_{x\to\frac{\pi}{2}}\frac{\ln(\tan x)}{x - \frac{\pi}{2}}
$$
In the last step I inversed the function in the denominator of the exponent. Next I do:
$$
\lim_{x\to\frac{\pi}{2}}\frac{\frac{1}{\tan x}*\frac{1}{\cos^2x}}{1} = \lim_{x\to\frac{\pi}{2}}\frac{1}{\tan x\cos^2x}= \lim_{x\to\frac{\pi}{2}}=...
$$
Skipping a few calculations, in the end I get
$$
\lim_{x\to\frac{\pi}{2}}\frac{1}{2\cos x\sin^3x}
$$
Which would mean the limit of the exponent = infinity, but the answer sheet says it's 2. I have a strong feeling I did something wrong in one of the first steps, however I'm unable to find out what exactly...

A: Something's broken.  First, if $x$ is a bit bigger than $\pi/2$, then $\tan x$ is negative which makes the exponential really hard to deal with.  So the limit only makes sense "from the left."
In that case, there's something odd with the steps you skipped.  $\tan x \cos^2 x = \sin x \cos x =\frac{1}{2}\sin 2x.$

A: $$L=\lim_{x \to \pi/2} (\tan x)^{1/(x-\pi/2)}$$
Lrt $x-\pi/2=y$
Then $$L=\lim_{y\to 0} (-\cot y)^{1/y}=\lim_{y \to 0} (-1/y)^{1/y}$$
Left limit $$L=\lim_{y\to 0^-} (\infty)^{-\infty}=0$$
Right limit $$\lim_{y \to 0^+} (-1/y)^{1/y}\to (-\infty)^{ \infty} \to \infty.$$
So the linit does not exist.

A: Being,
$$\lim_{x \to \frac{\pi}{2}^-} \tan^{\frac{1}{x - \frac{\pi}{2}}}{\left(x \right)} = \lim_{x \to \frac{\pi}{2}^-} e^{\ln{\left(\tan^{\frac{1}{x - \frac{\pi}{2}}}{\left(x \right)} \right)}}=\lim_{x \to \frac{\pi}{2}^-} e^{\frac{\ln{\left(\tan{\left(x \right)} \right)}}{x - \frac{\pi}{2}}}=\lim_{x \to \frac{\pi}{2}^-} e^{\frac{\ln{\left(\tan{\left(x \right)} \right)}}{x - \frac{\pi}{2}}} = e^{\lim_{x \to \frac{\pi}{2}^-} \frac{\ln{\left(\tan{\left(x \right)} \right)}}{x - \frac{\pi}{2}}}$$
and after
$$\lim_{x \to \frac{\pi}{2}^-} \frac{\ln{\left(\tan{\left(x \right)} \right)}}{x - \frac{\pi}{2}} = -\infty$$
hence:
$$\lim_{x \to \frac{\pi}{2}^-} \tan^{\frac{1}{x - \frac{\pi}{2}}}{\left(x \right)} = 0$$
For $x\to\frac{\pi}{2}^+, \ln(\tan (x))\to \nexists$ because $\tan(x)<0$.
Therefore the limit not exist.


text:
Q: Find a pattern in a string I am trying to detect a string inside the following pattern: [url('example')] in order to replace the value.
I thought of using a regex to get the strings inside the squared brackets and then another to get the text inside the parenthesis but I am not sure if that's the best way to do it.
//detect all strings inside brackets
preg_match_all("/\[([^\]]*)\]/", $text, $matches);

//loop though results to get the string inside the parenthesis
preg_match('#\((.*?)\)#', $match, $matches);

A: To match the string between the parenthesis, you might use a single pattern to get a match only:
\[url\(\K[^()]+(?=\)])

The pattern matches:

*

*\[url\( Match [url(

*\K Clear the current match buffer

*[^()]+ Match 1+ chars other than ( and )

*(?=\)]) Positive lookahead, assert )] to the right

See a regex demo.
For example
$re = "/\[url\(\K[^()]+(?=\)])/";
$text = "[url('example')]";
if (preg_match($re, $text, $match)) {
    var_dump($match[0]);;
}

Output
string(9) "'example'"

Another option could be using a capture group. You can place the ' inside or outside the group to capture the value:
\[url\(([^()]+)\)]

See another regex demo.
For example
$re = "/\[url\(([^()]+)\)]/";
$text = "[url('example')]";
if (preg_match($re, $text, $match)) {
    var_dump($match[1]);;
}

Output
string(9) "'example'"


text:
Q: what is the right way to define typecast operator template in C++ this code here is my attempt to define a template to typecast or assignment operator. Problem is, this is not calling typecast function template at line 27 while typecasting the object.
#include <iostream>
#include <string>

using namespace std;
struct FFJSON{
    template <typename T>
    FFJSON& operator=(T const& t){
        cout << "Assigning the object" << endl;
        ts=(void*)&t;
        return *this;
    };
    FFJSON& operator=(const char* s){return *this;};
    FFJSON& operator=(const string& s){return *this;};
    FFJSON& operator=(const int& i){return *this;};
    FFJSON& operator=(const unsigned int& i){return *this;};
    template <typename T>
    operator T(){
        cout << "Returning the object." << endl;
        return *ts;
    }
    void* ts;
};
int main(int argh, char** argv) {
    FFJSON f;
    timespec tt = {3,2};
    f = tt;
    timespec& t=(timespec&)f;
    cout << "sec:"<<t.tv_sec<<endl;
    cout << "usec:"<<t.tv_nsec<<endl;
    return 0;
}

Actual output:
Assigning the object
sec:126885484802960
nsec:4197094

Expected output:
Assigning the object
Returning the object
sec:3
nsec:2

The similar scenario is giving typecast operator not defined compile time error in an another program.

A: template <typename T> operator T() is fine, but such T can only be deduced to a non-reference type so this operator will not be used to convert to the type timespec&. Instead, your cast is a reinterpret_cast, which never performs a user-defined conversion.
In order to write a conversion operator that can produce an lvalue, you would need to write template <typename T> operator T&().
BTW, you can't dereference a void pointer. If your operator template were ever instantiated, you would get a compilation error because of that.

A: timespec& t=(timespec&)f; cannot use the typecast operator because you are casting to timespec& and not to timespec.
You have to implement
 operator T&(){
        cout << "Returning the object." << endl;
        return *reinterpret_cast<T*>(ts);
    }

to make this work.
Please do not use C-style casts in C++ modules. Use static_cast<>, dynamic_cast<>, reinterpret_cast<> and - if you really have to - const_cast<> instead.
I am not sure what you are trying to achieve, but the following implementation of the assignment operator copies the source value and should work for temporary objects and the typecast operator checks if the conversion may be valid.
class FFJSON
{
public:
    template <typename T>
    inline FFJSON& operator=(T const& t){
        cout << "Assigning the object" << endl;
        assert(std::is_trivially_copyable<T>::value );
        data.resize(sizeof(t));
        *reinterpret_cast<T*>(data.data()) = t;
        return *this;
    };

    template <typename T>
    inline operator T(){
        cout << "Returning the object." << endl;
        assert(sizeof(T) <= data.size());
        return *reinterpret_cast<T*>(data.data());
    }

private:
    std::vector<char> data;
};


text:
Q: ora-03115 unsupported network datatype or representation forms 6i I am trying to open tables from wizard in forms 6i and database 19c , I can connect by using user name and password in forms 6i but when I select the table from wizard it shows this error ,
actually I need to upgrade my old system and build new system in oracle APEX but during this time I need to continue using old system .
How to fix this error when select the table it show this error
ora-03115 unsupported network datatype or representation

A: Basically, it means that combination of client software (Forms 6i) is too old to successfully work with a new database (19c).
Forms 6i was released along with database version 8, back in 1997. Oracle database 19c dates from 2019 which means that there's over two decades difference between them. A LOT has changed during that time. Michael Ferrante from Oracle says that

Forms/Reports 6 was never certified for use with ANY database newer than Oracle 8.1.6.

and can't stress enough how important it is to upgrade.
OK, you're switching to Apex, but you can't expect that really old Forms application to work correctly with a new database. Perhaps you should have kept your old database and use it with Forms application, while you'd develop an Apex application using new database version. Once you're done, you'd migrate data from old database to new.

Meanwhile: what is SYS_USERS table description? Does it, by any chance, contain a TIMESTAMP column? If so, that might be cause of your problem. If you don't really care about fractional seconds, see if you can modify that column's datatype to
DATE. Don't alter the original table yet - first create its "duplicate", just switch timestamp to date datatype and try to access such a table from Forms. If it works, consider altering sys_users.

A: There are numerous reasons why old Forms/Reports versions cannot use DB versions newer than 8.1.  The most significant one is that beginning in DB 9 (I believe), the ROWID format was changed/lengthened.  Before Forms internally uses ROWID and expected this ROWID to be of an expected format, the change to it made newer DBs incompatible with Forms.  Again, this is just one of several changes impacting the use of old Forms versions.
Move to Apex?  Seems a better and generally easier approach would be to simply upgrade to a supported Forms version.  Once upgraded, begin to take advantage of the many new features introduced since 6.0.8.  In the planned coming versions of Forms, there are many new features expected.
Because your Forms application code (within the modules) mostly cannot be repurposed in Apex (or any other technology), what seems to work best for many other users is to invest some effort into moving Forms to a current version and introduce new features where appropriate.  As new business requirements arise, carefully consider which technology is best suited for that requirements.  As needed integrate all the technologies together (e.g. Forms and Apex can be integrated/share information).
You cannot build a house with a single tool.  It often takes many tools to achieve all the requirements appropriately.


text:
Q: Simultaneous sessions of Rstudio Is it possible to somehow open several RStudios at the same time? I have Rstudio open, and when I try to open another one, nothing happens. What is the proper way to work on several projects simultaneously in RStudio?

A: If your work is contained in a separate RStudio project file, it should be as simple as selecting "Open Project in New Session", either from the File menu or from the project selector in the upper-right (at least on a Mac).

A: On a Windows machine you can "scroll click" on the icon and it will open a new session. You could probably also right click and choose something, not on a PC right now so cant tell for sure.


text:
Q: How to transcribe a call with AWS transcribe API? I got this error when I'm trying to transcribe a call:

Account isn't authorized to call this operation. Check your account perm

I think the bad property is DataAccessRoleArn, I tried to create new role on IAM console, but it does not work.
Here's the full PHP code:
<?php
require 'vendor/autoload.php';

use Aws\TranscribeService\TranscribeServiceClient;

$awsKey = "{awsKey}";
$awsSecretKey = "{awsSecretKey}";

$clientAWS = new TranscribeServiceClient([
    'region' => 'eu-west-3',
    'version' => 'latest',
    'credentials' => [
        'key' => $awsKey,
        'secret' => $awsSecretKey
    ],
]);

$result = $clientAWS->startCallAnalyticsJob([
    'CallAnalyticsJobName' => 'Transcript1', // REQUIRED
    'ChannelDefinitions' => [
        [
            'ChannelId' => 0,
            'ParticipantRole' => 'AGENT',
        ],
        [
            'ChannelId' => 1,
            'ParticipantRole' => 'CUSTOMER',
        ]
    ],
    'DataAccessRoleArn' => 'arn:aws:iam::{id}:role/AWSRole', // REQUIRED
    'Media' => [ // REQUIRED
        'MediaFileUri' => 's3://{bucketName}/2022/02/23/file.wav',
        'RedactedMediaFileUri' => 's3://{bucketName}/2022/02/23/',
    ],
    'Settings' => [
        'ContentRedaction' => [
            'RedactionOutput' => 'redacted', // REQUIRED
            'RedactionType' => 'PII', // REQUIRED
        ],
    ],
]);

print_r($result);

Do you know how to fix role issue?

A: For fixing this issue, you have to:

*

*Select a region compatible (in my case eu-central-1)

*Create a new role with AmazonS3FullAccess policy (just for testing, adjust for security) and this trust entity:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "transcribe.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}

*Attach AmazonTranscribeFullAccess and AmazonS3FullAccess policiy to your IAM user (just for testing, adjust for security)


text:
Q: Nginx 404 Report I'm looking for some means of reporting 404 errors to my client for a site we've inherited.
404s in the application (Django) are handled by Sentry, and that's working brilliantly, but this is for things which don't hit Django (eg, links to static PDFs).
I'm thinking I can write something to grep the Nginx log, showing me a list of 404 URLs, with frequency maybe.
I think something like AWStats is a bit overkill for this.
Can anyone point me at anything?
Thanks!

A: Maybe you could do something like:
(nginx conf)
error_page 404 = /report_404.html;

And then create a django view for report_404.html that logs an entry to sentry.


text:
Q: Capture java applet window so I can analyze pixels? I have a (web) Java Applet which has ever changing graphics. I need to capture this image so that I can analyze pixels - sort of like face recognition software except that's not what I'll be using it for. I know there's ways to capture the entire screens, but I just want to capture the java window.

A: You can use Screen Image to create an image of any component.


text:
Q: Converting from string to Image in C# I am trying to convert a Unicode string to an image in C#. Each time I run it I get an error on this line
Image image = Image.FromStream(ms, true, true);

that says: ArgumentException was unhandled by user code. Parameter is not valid. Any ideas why this is happening? Below is the rest of the function.
public Image stringToImage(string inputString)
    {
        byte[] imageBytes = Encoding.Unicode.GetBytes(inputString);
        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

        ms.Write(imageBytes, 0, imageBytes.Length);
        Image image = Image.FromStream(ms, true, true);

        return image;
    }

A: Unicode doesn't encode all possible byte sequences that you'll need to represent an image.
byte[] -> String -> byte[] is a transformation that just won't work for many given sequences of bytes.  You'll have to use a byte[] throughout.
For example, if you read the bytes, convert them to UTF-16 then it's possible that byte sequences will be discarded as invalid.  Here's an example of an invalid byte sequence from UTF-16.

Code points U+D800 to U+DFFF[edit] The Unicode standard permanently
  reserves these code point values for UTF-16 encoding of the lead and
  trail surrogates, and they will never be assigned a character, so
  there should be no reason to encode them. The official Unicode
  standard says that all UTF forms, including UTF-16, cannot encode
  these code points.

A: May this can help you:
public Bitmap stringToImage(string inputString)
{
   byte[] imageBytes = Encoding.Unicode.GetBytes(inputString);
   using (MemoryStream ms = new MemoryStream(imageBytes))
   {
       return new Bitmap(ms);
   }
}

A: Take out your call that writes to the MemoryStream. The constructor call that accepts a byte array automatically puts the contents of the byte array into the stream. Otherwise your stream contains 2 copies of the raw data. In addition, the call to Write will leave the stream's position at the end of stream, so there is no data that the FromStream call can read.
So it would be:
public Image stringToImage(string inputString)
{
    byte[] imageBytes = Encoding.Unicode.GetBytes(inputString);

    // Don't need to use the constructor that takes the starting offset and length
    // as we're using the whole byte array.
    MemoryStream ms = new MemoryStream(imageBytes);

    Image image = Image.FromStream(ms, true, true);

    return image;
}

A: You're getting an image as a string, out of ldap? I'm pretty sure if that was true, the string would actually be base64 encoded, and in that case contains bytes that represent actual characters, and not image data.
Could you post a snippit of the string you're getting?
If it's true, you need to take the string and turn it a byte[] by un-base64'ing it, and then use the byte array to make the image. Combined with @JonBenedicto's code:
public Image stringToImage(string inputString)
{
    byte[] imageBytes = Convert.FromBase64String(inputString);
    MemoryStream ms = new MemoryStream(imageBytes);

    Image image = Image.FromStream(ms, true, true);

    return image;
}

A: With string you might get loss of data,i will just post example on converting image to byte array and array to image again,and after image to byte array,to string and back,without loss of data.
            MemoryStream ms = new MemoryStream();
            Image.FromFile(@"C:\..\..\..\img.jpg").Save(ms,ImageFormat.Jpeg);
            byte[] bytes = ms.ToArray();
            MemoryStream ms1 = new MemoryStream(bytes);
            Image NewImage = Image.FromStream(ms1);
            NewImage.Save(@"C:\..\..\..\img1.jpg");

try this out and it might help you produce what you need.
trying to convert to string and back,better use base64.
            MemoryStream ms = new MemoryStream();
            Image.FromFile(@"C:\..\..\..\img.jpg").Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] bytes = ms.ToArray();
            string byteString = Convert.ToBase64String(bytes);
            byte[] NewBytes = Convert.FromBase64String(byteString);
            MemoryStream ms1 = new MemoryStream(NewBytes);
            Image NewImage = Image.FromStream(ms1);

This should give you the outcome you need.
 MemoryStream ms = new MemoryStream();
    Image.FromFile(@"C:\..\..\..\img.jpg").Save(ms,ImageFormat.Jpeg);
    byte[] bytes = ms.ToArray();
    string byteString = Convert.ToBase64String(bytes);

then when you pass this string into your method...
    public Image stringToImage(string inputString)
    {
         byte[] NewBytes = Convert.FromBase64String(inputString);
         MemoryStream ms1 = new MemoryStream(NewBytes);
         Image NewImage = Image.FromStream(ms1);

         return NewImage;
     }


text:
Q: How to assign variables in a recursion? Suppose you have a bunch of boxes inside other boxes, i.e.
inBox(a,b).
inBox(b,c).
inBox(c,d).

inBox(x,y) meansbox x is in box y. Now I want to write a method to determine if one box is inside of another box, e.g. insideBox(a,d) = true since a is inside b, which is inside c, which is inside d. So it appears to be a naturally recursive problem and my attempt at solving it fails to initialize my variable to "move one box up":
insideBox(X, Y) :- inBox(X, Y), inBox(X, Z), insideBox(Z,Y).

The logic is to first check the base case of whether or not box X is currently inside box Y, if not then call inBox(X, Z) to get a value for which box X is in and then recall the recursive method. I have tried looking at the trace but can't reason what is going on:
| ?- insideBox(a,d).
  1    1  Call: insideBox(a,d) ? c
  2    2  Call: inBox(a,d) ? c
  2    2  Fail: inBox(a,d) ? c
  1    1  Fail: insideBox(a,d) ? c

I've tried other stuff like Z is inBox(X, _) for setting the variable Z but this hasn't worked either and I have no clue how Z is ending up with the value of a.

A: Try this:
?- insideBox(a,d).

inBox(a,b).
inBox(b,c).
inBox(c,d).

insideBox(X,Z) :- inBox(X,Z).
insideBox(X,Z) :- inBox(X,Y), insideBox(Y,Z).

Just a side-note: be careful with the terms you use. You don't "assign" variables, instead you "unify" them. Also you're not writing "methods", you're writing "predicates".


text:
Q: Godot: Strange boolean values In this script:
func _process(delta):
    print(player_city.stats["has_battlemech"])
    if has_it:
        player_city.stats["has_battlemech"] = true
    if not has_it:
        player_city.stats["has_battlemech"] = false

I determine whether or not the player "has" the battlemech. This is in the script for the battlemech, by the way. has_it is set when someone clicks the "purchase" button in the store. It contacts a singleton called player_city which has a dictionary which stores all the stats variables in my game.
extends StaticBody

var stats = {
    "has_battlemech": false,
    "has_ranged_battlemech": false,
    "has_helicopter": false
}

City code
func _on_Purchase_pressed():
    if camera_in_first_spot:
        slot_1.has_it = true
    if camera_in_second_spot:
        slot_2.has_it = true
    if camera_in_third_spot:
        slot_3.has_it = true
    if camera_in_fourth_spot:
        slot_4.has_it = true

Market code
Now when I run this, the debug print section of the first code snippet is telling me that every frame the value of has_battlemech is
true
false
true
false
true
false
true
false
You get the idea. I have no idea why this is happening, but am probably missing something obvious. Help would be greatly appreciated.
Code for camera placement:
match camera_x:
        -30.0:
            camera_in_first_spot = true
            camera_in_second_spot = false
            camera_in_third_spot = false
            camera_in_fourth_spot = false
        0.0:
            camera_in_first_spot = false
            camera_in_second_spot = true
            camera_in_third_spot = false
            camera_in_fourth_spot = false
        30.0:
            camera_in_first_spot = false
            camera_in_second_spot = false
            camera_in_third_spot = true
            camera_in_fourth_spot = false
        60.0:
            camera_in_first_spot = false
            camera_in_second_spot = false
            camera_in_third_spot = false
            camera_in_fourth_spot = true

camera_x is the x value of the camera placement


text:
Q: Same Analyics Account ID on multiple website I am using Asynchronous google Analytics code in my website. Account key for Google Analytic which i am using for Live website in also in my local website environment.
but in my google analytics account the Url is of live website. suddenly i noticed that my Google Analytics is tracking the data from local environment as well and that is a huge huge problem. why its tracking from two different URLs.

A: Google Analytics will track any domain or URL onto which you have installed the Google Analytics Tracking Code (GATC).  For analytics/tracking purposes, it does not matter to Google which URL you written your GA account, either at Admin -> Profile Settings or at Account List -> Account Settings.
For example, let's say that your current GA account number is "UA-12345678-1".  You have installed your GATC with UA-12345678-1 onto "livewebsite.com" and onto "localenvironment.com".  As long as the GA JavaScript file called "ga.js" can load and can connect to the Internet, then a GA cookie can be created and stored on your browser and the tracking information can be sent back to GA.
Assuming that you want to keep GATC installed on your local environment webpages, some possible solutions that may fix your dilemma would either be to create a filter to exclude your own traffic or install an entirely new, unique account number into your local environment:
'1.  Exclude your own traffic from UA-12345678-1 by creating a new profile for UA-12345678-1.  In the new profile, create and apply one of the following "Custom/Advanced" filters:
'a.  "Include" traffic from "Hostname" of livewebsite.com
--or--
'b.  "Exclude" traffic from "Hostname" of localenvironment.com
--or--
'c.  "Exclude" traffic from "IP Address" of your local environment.  For example, if your local environment uses the IP address 65.99.208.1, you would write the IP address into the Exclude IP Address advanced filter as:  ^65.99.208.1$
More info here:
http://www.morevisibility.com/analyticsblog/clean-up-your-google-analytics-data-with-these-5-filters.html
'2.  Create a second GA account (they're free to create):
'd. Install the new GA account number into the code of localenvironment.com.  After installing the new GA account number (for example: UA-98765432-1) , you would continue using UA-12345678-1 on livewebsite.com without interference from your test environment, which would use UA-98765432-1 .


text:
Q: $D_X$ algebras, $D_X$ schemes, connections I have a basic question about the definition of $D_X$-algebras and schemes, which are defined in [BD2], Chiral algebras. I have some understanding of connections on a vector bundle, but I am not sure about connections in different contexts. Here $X$ is a scheme, of course.
Question 1: [BD2] defines a $D_X$ algebra as a commutative unital $O_X$ algebra equipped with an integrable connection along $X$. What precisely does an "integrable connection along X mean in this context?
Question 2: [BD2] defines a $D_X$ scheme as a X-scheme equipped with an integrable connection along $X$. Again, what does "integrable connection along X" mean in this context?

A: For question 1 it means that derivations of $O_X$ act on the algebra $A$ as derivations: $D(ab)=D(a)b+aD(b)$ while integrability means $[D_1,D_2]a=D_1(D_2 a)-D_2(D_1a)$, these conditions allow you to extend the action from derivations to a left action of the whole algebra $D_x$ of differential operators. This is the local case. For 2 I guess you patch these conditions to get a global version.
If you prefer a geometric picture: you have a fiber bundle $Y\to X$ where $Y$ is supplied with an involutive distribution whose planes project isomorphically to the tangent planes of $X$.

A: Keerthi Madapusi Sampath already answered the question in the comments, so I'll just add some remarks.
The definitions in question are given in section 2.3.1, on page 80 of Beilinson and Drinfeld's Chiral algebras.  The authors assume $X$ is smooth over the spectrum of a field $k$ of characteristic zero, but only bother to say so back on page 66 (and only mention $k$ on page 53).  Their use of integrable connections along $X$ is a reference to Grothendieck's crystalline interpretation of connections, and they wrote their own sketchy introduction to this subject in section 7.10 of their unfinished book Quantization of Hitchin's Integrable System and Hecke Eigensheaves.  The interpretation there is that schemes and commutative algebras of quasicoherent sheaves form fibered categories over the crystalline site $X_{cr}$, and the corresponding $D_X$-objects are Cartesian sections.  This is just another way to put the infinitesimal descent data into a nice-looking package.


text:
Q: Read Firebase Firestore document if it document's property matches a request property I'm sure this is a popular question but I can't find the question/answer!

*

*Aim: Read Firestore if the currently logged-in user's uid matches a document's uid.

*Current result: I get an error when trying to read.
Uncaught Error in snapshot listener: FirebaseError: Missing or insufficient permissions.
Here's my Firestore rule:
service cloud.firestore {
  match /databases/{database}/documents {

    match /cars/{document} {
        allow read: if request.auth.uid == document.uid;
    }

  }
}

Here's a sample data:

A: If you want to refer to document data in rules, the syntax is like this:
allow read: if request.auth.uid == resource.data.uid;

This will work when the client performs a get() of the individual document, and they are signed in with a UID that matches the uid field of the document.
I suggest reviewing the documentation on authentication and data validation.


text:
Q: HTML5 canvas painting rectangle on mouse click I have a canvas which loads in a selected image. The canvas should display 2 6x6 rectangles where the user clicks. On the first click, the rectangle should be red, the second click it should be blue on the third click, it resets (deletes both first rectangles) and so on..
This works fine (see example here: http://jsfiddle.net/8HSGG/)
My problem is when I reload an image, the rectangles start messing up (i.e. colors come in different order or don't show up at all).
I have two variables in the Javascript: topLeft and bottomRight which are both null whenever an image is loaded in, then a check based on those and paint accordingly.
Any idea what's going on?

A: You're adding click and mouseover event listeners to the canvas every time you're "handling" the image.  Thus, I would suspect you're getting code that gets invoked multiple times.


text:
Q: Connecting to guest vms on VMware ESXi I have an local server built in our office with  VMware ESXi 6.0.0 installed on it.  My local network is in the range 192.168.2.0/24 and the vmware host has the Ip address 192.168.2.254...
I have created a vm (centos)from vsphere client and set a private IP 192.168.2.240 to this VM and set the gatway to 192.168.2.1
I can access the vmware host node from my local computer (192.168.2.164) but cannot connect to the vm from any of our network. The vm ip 192.168.2.240 is pinging from the vmware host node..
I can access the console of the vm via vsphere and the ifconfig shows an additional network (virbro ) with another IP address 192.168.122.1
A lot knowledgebase says to enable bridge network from the vmware but I cannot see that option in my vmware...
Any Idea how can I get access to the vm and it can communicate to internet.

A: You'll need to create a portgroup on the ESXi host which can access your 192.168.2.0/24 subnet. Then, update your VM to have a network adapter using that portgroup via the VM Settings.
I would recommend to start by reading through this: Port Group Configuration for Virtual Machines


text:
Q: Linq To Entites error: The entity or complex type .... cannot be constructed in a LINQ to Entities query I have been pulling my hair out trying to do the MVC 3 Music Store tutorial found on the asp.net website.
In the below code I am trying to use a Linq to Entities query to return results to my Browse view from the storeController but I receive this error when I navigate to the browse page:
The entity or complex type 'MvcMusicStore.Models.Genre' cannot be constructed in a LINQ to Entities query.
The code below works when I use the Lambda expression that they use in tutorial but I am more comfortable using a Linq Query. Please can someone explain to me why this doesn't work using the following code?
Storecontoller.cs
MusicStoreEntities storeDB = new MusicStoreEntities();
    public ActionResult Browse(string genre)
    {

        //working code used in tutorial
        //var genreModel = storeDB.Genres.Include("Albums")
        //.Single(g => g.Name == genre);

        storeDB.Genres.Include("Albums");
        var genreModel = from p in storeDB.Genres
                         where p.Name == genre
                         select new Genre
                         {
                          GenreId = p.GenreId,
                          Name = p.Name,
                          Description = p.Description,
                          Albums = p.Albums
                         };

        return View(genreModel.Single());

    }

Genre.cs
using System.Collections.Generic;
namespace MvcMusicStore.Models
{
    public class Genre
    {
        public int GenreId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<Album> Albums { get; set; }
    }
}

MusicStoreEntities.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MvcMusicStore.Models
{
    public class MusicStoreEntities : DbContext
    {
        public DbSet<Album> Albums { get; set; }
        public DbSet<Genre> Genres { get; set; }
    }

}

browse.cshtml

Browsing Genre: @Model.Name

    @foreach (var album in Model.Albums)
    {

            @album.Title

    }

Many thanks
desperate dave

A: You must use this:
var genreModel = from p in storeDB.Genres.Include("Albums")
                 where p.Name == genre
                 select p;
return View(genreModel.Single());

Include must be part of query. Calling it in advance doesn't work. You can do this:
var query = storeDB.Genres.Include("Albums");
var genreModel = from p in query
                 where p.Name == genre
                 select p;

Also you can't create projection to entity class (new Genre). You must select it directly.


text:
Q: How to have nested conditions for PMD Xpath rules My rule requires me to apply them only to methods without 'get' as part of their name. In another words, my rules need to apply to only non-getter methods in the class. I know to get a hold of all the non-getter methods, I can use
//MethodDeclarator[not(contains(@Image,'get'))]

However, I don't know the syntax about where I insert my logic for the rules. Is it like
//MethodDeclarator[
not(contains(@Image,'get'))

 'Some Rule Statements'
]

I saw the use of . in the beginning of statement inside [] in some example code. what are they used for?
In my particular case, I need to combine following pieces together but so far I am unable to accomplish it yet.
Piece 1:
 //PrimaryExpression[not(PrimarySuffix/Arguments)]

Piece 2:
 //MethodDeclarator[not(contains(@Image,'get'))]

Piece 3:
 //PrimaryExpression[PrimaryPrefix/@Label='this']

A: You need to have at least some basic knowledge/understanding of XPath.

I saw the use of . in the beginning of statement inside [] in some
  example code. what are they used for?

[] is called predicate. It must contain a boolean expression. It must immediately follow a node-test. This specifies an additional condition for a node that satisfies the node-test to be selected.
For example:
/*/num

selects all elements named num that are children of the top element of the XML document.
However, if we want to select only such num elements, whose value is an odd integer, we add this additional condition inside a predicate:
/*/num[. mod 2 = 1]

Now this last expression selects all elements named num that are children of the top element of the XML document and whose string value represents an odd integer.
.  denotes the context node -- this is the node that has been selected so-far (or the starting node off which the complete XPath expression is evaluated).

In my particular case, I need to combine following pieces together ...

You forgot to say in what way / how the three expressions should be combined. In XPath some of the frequently used "combinators" are the operators and, or, and the function not().
For example, if you want to select elements that are selected by all three provided XPath expressions, you can use the and operator:
//PrimaryExpression
   [not(PrimarySuffix/Arguments)
  and
    PrimaryPrefix/@Label='this'
   ]


text:
Q: How does inetd know which process to send incoming data to? I'm trying to replace a inetd/xinetd service by a standalone one.
What is the simplest I can do this? Is there some standard code to get started?

A:
How does inetd know which process to send incoming data to

It spawns it (typically using fork() followed by exec*()), so it has the process-id.

Is there some standard code to get started?

What about xinetd's sources?


text:
Q: Different single page applications on same domain but different paths I have two single page applications video and messages and trying to publish them on same domain chat.example.com but on different paths. eg chat.example.com/video  to load video spa and chat.example.com/messages to load messages spa.
I have tried doing this with react router by checking the path then dynamically loading the bundled javaScript
What is the best solution for this?
Currently using render.com static site

A: If you have 2 different projects , you just go in your domains host in www folder create 2 separate folder and copy each of your apps in each folder, and you can call them in web with your folder names
For example

www.example.com/folder1
  Www.example.com/folder2

But if you have 2 page in one app you should use router, check documents from here react router dom
Then in one app, you can access different pages with different URL paths
Hope you get the idea
update: if your host doesn't have www folder it must have a similar folder that you copy your project files in it


text:
Q: Animation in Android and Multithreading In trying to add animation to ImageViews, I don't seem to get the multithreading right which is giving me incorrect results.
This is the part where I am calling the animation >>
startAnimation(gameController.getSecondImage()); // 1
...
startAnimation(gameController.getFirstImage()); // 2
...
startAnimation(gameController.getSecondImage()); // 3
...

The problem here is that when I was not creating a separate thread, for the startAnimation() function, all 3 calls happened simultaneously and everything got messed up. But still now it is not working perfectly and the 1st & 3rd calls are jumbled up.
public void startAnimation(final ImageView image1) {

    final ImageView image2 = cardViewMap.get(cardSwapMap.get(image1.getId()));
    Runnable animate = new Runnable() {

        @Override
        public void run() {

            animationController.animate(image1, image2);
        }
    };
    Thread animationThread = new Thread(animate);
    animationThread.start();
    try {                                         //
        animationThread.join();                   //
    } catch (InterruptedException e) {            // Added Later
        Log.d("ERROR", e.toString());             //
    }                                             //
}

I tried to experiment with join() but it didn't work out, it is giving more radical outcomes now. I thought that using join() will ensure excution of the previous calls to startAnimation() before starting a new.
EDIT: I have tracked the issue and the issue is that my startAnimation() function is being called when the main Looper is running. So it is being executed after all three calls to the function has been made. I need to ensure that startAnimation() runs at the time when I make the call, and is executed before the next call to the same function happens. Any ideas how to ensure this?

A: try to run this code it will help you understand a work around, once you run it it will be easier for you to understand,
make an layout name it animation_test_activity.xml code is below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ImageView
    android:id="@+id/imageView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/ic_launcher"
    android:visibility="invisible" />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView3"
    android:layout_alignParentTop="true"
    android:src="@drawable/ic_launcher"
    android:visibility="invisible" />

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView3"
    android:layout_alignParentTop="true"
    android:src="@drawable/ic_launcher"
    android:visibility="invisible" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView3"
    android:layout_alignParentBottom="true"
    android:text="click me" />

</RelativeLayout>

now in make an activity named AnimationTest.java the code is as mentioned below.
package com.some.servewrtest;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;

public class AnimationTest extends Activity implements OnClickListener {

private ImageView[] imageViews = new ImageView[3];
private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.animation_test_activity);

    initializeUI();
}

private void initializeUI() {
    // TODO Auto-generated method stub
    imageViews[0] = (ImageView) findViewById(R.id.imageView1);
    imageViews[1] = (ImageView) findViewById(R.id.imageView2);
    imageViews[2] = (ImageView) findViewById(R.id.imageView3);
    button = (Button)findViewById(R.id.button1);
    button.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    AnimationSet set = new AnimationSet(true);
    TranslateAnimation[] animations = new TranslateAnimation[3];
    int duration = 300;
    animations[0] = createCoins(0, duration*1, 0, 0, 0, 270);
    animations[1] = createCoins(1, duration*2, 0, -100, 0, 270);
    animations[2] = createCoins(2, duration*3, 0, 100, 0, 270);
    set.addAnimation(animations[0]);
    set.addAnimation(animations[1]);
    set.addAnimation(animations[2]);
    set.start();
}

private TranslateAnimation createCoins(int i, int duration, int fromXDelta, int toXDelta, int fromYDelta, int toYDelta) {
    // TODO Auto-generated method stub
    TranslateAnimation animation = new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta);
    animation.setDuration(duration+1900);
    animation.setFillAfter(false);
    imageViews[i].setVisibility(ImageView.VISIBLE);
    imageViews[i].setAnimation(animation);
    imageViews[i].setVisibility(ImageView.INVISIBLE);
    return animation;
}

}

This code is working you can test it as well that you may customize the way you want to use it.
Now we have a working example we will see how did we get there,
First if you try to animate same image over and over using AnimationSet or making different TranslateAnimation reference type to same image that doesn't work because a single image tries to be at two different places virtually at the same time. So what happens is only first animation is seen and others are ignored by android it is one of the result of repeat method doesn't work in android.
To solve this what we can do is have as many Views as we need to show different animation on each one a separate View this time. It works as each animation is related to single view and they can work concurrently.
I am in no position to tell not not to go for Multi-Threading but remember you are trying to do this on UI Thread so if you have many animations in your app it will bog your app with these threads that is quite possible.
if you want to listen to an event when a particular animation is over lets say animation then do this
animation..setAnimationListener(new AnimationListener() {

                @Override
                public void onAnimationStart(Animation animation) {
                    // TODO Auto-generated method stub
                    Log.d(TAG, "Animation has started");
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                    // TODO Auto-generated method stub
                    Log.d(TAG, "Animation is repeat");
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    // TODO Auto-generated method stub
                    Log.d(TAG, "Animation is over");

                }
            });

by doing this you can start a new animation when previous is over :)

A: I tried and failed using Android tools. I went back and fixed it with multithreading.
Though there is a lot of other code that I changed, this is one of the important one w.r.t. my issue-
package thakur.rahul.colourmemory.controller;

import thakur.rahul.colourmemory.view.Animation.DisplayNextView;
import thakur.rahul.colourmemory.view.Animation.Flip3dAnimation;
import android.app.Activity;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;

public class AnimationController implements Runnable {

    private Activity activity;
    private ImageView image1;
    private ImageView image2;
    private boolean isFirstImage = true;
    private volatile static int numThread = 1;
    private volatile static int threadAllowedToRun = 1;
    private int myThreadID;
    private volatile static Object myLock = new Object();
    private volatile static boolean hasNotSlept = true;
    public volatile static boolean fixForMatch = false;

    public AnimationController(Activity activity, ImageView image1, ImageView image2) {

        this.activity = activity;
        this.image1 = image1;
        this.image2 = image2;
        this.myThreadID = numThread++;
    }

    @Override
    public void run() {

        synchronized (myLock) {
            while (myThreadID != threadAllowedToRun)
                try {
                    myLock.wait();
                } catch (InterruptedException e) {
                } catch (Exception e) {
                }
            animate();
            if (myThreadID % 2 == 0)
                if (hasNotSlept || fixForMatch)
                    try {
                        Thread.sleep(1000);
                        hasNotSlept = !hasNotSlept;
                    } catch (InterruptedException e) {
                    }
                else
                    hasNotSlept = !hasNotSlept;
            myLock.notifyAll();
            threadAllowedToRun++;
        }
    }

    public void animate() {

        if (isFirstImage) {
            applyRotation(0, 90);
            isFirstImage = !isFirstImage;
        } else {
            applyRotation(0, -90);
            isFirstImage = !isFirstImage;
        }
    }

    private void applyRotation(float start, float end) {

        final float centerX = image1.getWidth() / 2.0f;
        final float centerY = image1.getHeight() / 2.0f;
        final Flip3dAnimation rotation = new Flip3dAnimation(start, end, centerX, centerY);
        rotation.setDuration(300);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(isFirstImage, image1, image2));
        if (isFirstImage)
            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    image1.startAnimation(rotation);
                }
            });
        else
            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    image2.startAnimation(rotation);
                }
            });
    }
}

This is being called from the main controller as-
public void startAnimation(ImageView image1) {

    ImageView image2 = cardViewMap.get(cardSwapMap.get(image1.getId()));
    animationController = new AnimationController(activity, image1, image2);
    animationThread = new Thread(animationController);
    animationThread.start();
}

Basically, every time I need to run the animation, I make and tag the thread so I can run it in order.
Please add your answer if you have a better solution.


text:
Q: Why am I getting this error for ProfileCommon? I have a global.asax file in an ASP.NET web application, and I want to add the event handler for migrating anonymous profiles.
Here is the code:
using System;
using BCC.Data;
using System.Web;
using System.Web.Profile;
using System.Web.Security;

namespace BCC {
    public class Global : System.Web.HttpApplication {
        protected void Session_Start ( object sender, EventArgs e ) {
            if ((string)Request.QueryString["rc"] != null)  {
                var code = (string)Request.QueryString["rc"];
                if ( ReferralMemberDB.ValidateCode ( code ) )
                    Session ["RCode"] = code;
                else
                    Session ["RCode"] = null;
            }
        }

        public void Profile_OnMigrateAnonymous ( object sender, ProfileMigrateEventArgs args ) {
            ProfileCommon anonymousProfile = Profile.GetProfile(args.AnonymousID);
            Profile.ZipCode = anonymousProfile.ZipCode;
            Profile.CityAndState = anonymousProfile.CityAndState;
            Profile.StockSymbols = anonymousProfile.StockSymbols;
            ProfileManager.DeleteProfile ( args.AnonymousID );
            AnonymousIdentificationModule.ClearAnonymousIdentifier ( );
            Membership.DeleteUser ( args.AnonymousID, true );

        }
    }
}

For whatever reason, I get the error that the type or namespace for ProfileCommon can't be found, even though I'm including references to System.Web.Security and and System.Web.Profile.  Any help with what's going on?


text:
Q: In MongoDB, how to obtain only a specific field of a collection? Lets suppose we have the following collection:
{
        "_id" : 10,
        "youtube_id" : "xxx",
        "title" : "yyy",
        "counters" : [
                {
                        "timestamp" : 202003181300,
                        "views" : 7433,
                        "likes" : 2477,
                        "dislikes" : 34,
                        "comments" : 105
                },
                {
                        "timestamp" : 202003200815,
                        "views" : 12494,
                        "likes" : 4877,
                        "dislikes" : 248,
                        "comments" : 322
                }
        ]
}
{
        "_id" : 11,
        "youtube_id" : "xxz",
        "title" : "yyz",
        "counters" : [
                {
                        "timestamp" : 202003181300,
                        "views" : 12,
                        "likes" : 2,
                        "dislikes" : 0,
                        "comments" : 0
                },
                {
                        "timestamp" : 202003200815,
                        "views" : 198,
                        "likes" : 50,
                        "dislikes" : 4,
                        "comments" : 36
                }
        ]
}

And I want to query for the number of comments given a certain timestamp and title, my guess would be to do as follows:
db.youtube.find({"title":"yyy","counters.timestamp":{$eq:202003181300}},{"_id":0,"title":1,"counters.timestamp":1,"counters.comments":1}).pretty()

And the result I am getting is the following:
{
        "title" : "yyy",
        "counters" : [
                {
                        "timestamp" : 202003181300,
                        "comments" : 105
                },
                {
                        "timestamp" : 202003200815,
                        "comments" : 322
                }
        ]
}

The problem is that I would only like to see the part that has the same timestamp I have done the query for, like this:
{
        "title" : "yyy",
        "counters" : [
                {
                        "timestamp" : 202003181300,
                        "comments" : 105
                }
        ]
}

Is there a way to do it, and in case I am missinterpreting what the query does could anyone give me a piece of advice? Thanks in advance
Ps. It is my first post, and I am learning the mongo basics so forgive me if I have said anything wrong.

A: The problem is that your "counters.timestamp":{$eq:202003181300} gets ignored, since counters is an array of subdocuments, not a subdocument itself. You can use $elemMatch query modifier like I did here:
    db.youtube.find(
      {
        "title":"yyy","counters":{
          $elemMatch: { "timestamp": { $eq: 202003181300 } }
        }
      },
      {"_id": 0, "title": 1, "counters.timestamp": 1, "counters.comments": 1 }
    ).pretty()

P.S. You can omit $eq: query modifier and simply do { "timestamp": 202003181300 }.
Let me know if it works.


text:
Q: problems in finding mathematical reviews journal (MR XXX) for example, this one:
http://www.ams.org/mathscinet-getitem?mr=0215729
the journal has the number like "MR215729 (35 #6564)"
I wanna know what does the 35 #6564 means...
because for some references, it just quote "MR 21 #852",
which i cannot find the MR number, which is "215729" like the previous one.
sounds weird enough to me :(


text:
Q: What is the best way to store large files created by my app in Android sdk 30? My app creates large files of my own format. We used to save those on device memory but from sdk level 30 we can't access them anymore (it is too slow and complicated to use DocumentFiles).
Is there a way to store files in scoped storage that are not media files, that doesn't increase app memory and bog it down?
And I am also worried about files being deleted when a user uninstalls the app.
What is the best way to do this?
Edit: We used to store it on a folder on the phone memory that is accessible by the user via file browser. On Android 11 we can't do that so the files would have to move to scoped storage i.e. Android/data//files
Is there another storage location that an app can access on Android 11 that won't be deleted after app uninstall?


text:
Q: In between parent and iframe: mouseover/out combined with click behavior I am very new in programming. Please give me a mercy.
According to the post mouseover/out combined with click behavior .
I would like to ask further question since I still cannot achieve the task.
Here below is my code:
Child.html

This div will be highlighted

Parent.html

Click to highlight the custom div in Child.html

What I want to do is:

*

*when the user hovers mouse on "custom_link", the "custom_div" is being highlighted.

*when the user moves mouse out off "custom_link", the highlight at "custom_div" is eliminated.

*when the user clicks at "custom_link", "custom_div" is being highlight. However, when the user moves mouse out, the 'highlightDiv' is still being added to "custom_div".

Could you please help me to dissolve this? I sought a lot of "accessing iframe element by Jquery" issue ,however, I still cannot understand. It would be very nice if you could provide Jsfiddle example as well.

A: If I have understand your requirement currently this should resolve this issue

A: this fiddle: http://jsfiddle.net/W4dUa/ should do what you are asking for, if I understood right, however:
First of all, classes and IDs are case sensitive - revise your code, as you have bits like this: $('#Custom_Link') with uppercase C that is different from id="custom_Link"
I believe that this is because you're unbinding mouseenter mouseleave on click:
   $(e.currentTarget).unbind('mouseenter mouseleave');

from http://api.jquery.com/hover/

The .hover() method binds handlers for both mouseenter and mouseleave events.

for that reason,
$('#custom_Link').hover(function () {
    $('#custom_div').toggleClass('highlight');
});

does not "work" anymore and the highlight class stays on your div


text:
Q: Snort - Trying to understand how this snort rule works I have an assignment that is requiring me to put the following rule into Snort.
drop tcp any any -> 192.168.1.0/24 any (msg:"TCP DoS"; flow: established, to_server; flags:A; threshold: type threshold, track by_src, count 10, seconds 10;)
The rule is supposed to stop HC from doing a DoS on on SVR.  I am under the impression that this rule will stop traffic heading to the ..1.0/24 sub-net stoping the 'SYN' replies that are heading to the ..1.0/24 sub-net and this will allow the server to continue opperating
The way that I see the rule, it would not work.  It would block the traffic heading to the wrong location.  The server is on the ..2.0/24 and ..3.0/24 nets and the traffic should be blocked from heading that direction.
My network is set up like the following:
System / LAN Segment / IP Addresses
Administrative Client (AC) / IT / 192.168.100.3/24
User Client (UC) / Corporate / 192.168.101.25/24
Hacker Client (HC) / Rogue / 192.168.13.37
pfSense Router/Firewall (3 NICS) / fwNet / 192.168.1.2
                           IT                     192.168.100.1
                           Corporate              192.168.101.1

Ubuntu Router (3 NICS) / fwNet / 192.168.1.1
                           idsNet                 192.168.2.1
                           Rogue                  192.168.13.1

Snort IDS/IPS (2 NICS) (IDS)            idsNet                 192.168.2.2
                           sNet                   192.168.3.1

Server (SRV) / sNet / 192.168.3.2
It looks ugly in the form above but I am unable to fix it now.  I have tried and there is no snipping tool on this system and this is the best I can do for now.
Basically, who is correct?
Thanks in advance for the help.  This is informational.  The assignment is turned in and is being graded.  I need to understand how this works.
Thanks again.

A: This rule is going to drop every tcp packet that is destined for any IP within the 192.168.1.0/24 range where the connection is established and the Ack flag is set and the host in the ..1.0/24 range is considered the server.
It is only going to generate an event if the rule triggers 10 times in 10 seconds, this doesn't mean that it won't drop the traffic, threshold only limits the amount of events you get, so it will drop all packets and only generate an event if it matches 10 times in 10 seconds.  If it's intended to prevent a DOS, you would want to use the rate_filter keyword instead, otherwise it just drops everything, preventing DOS, yes, but also preventing anyone from accessing the server at all.
In tcp all packets from client to server after the 3whs should have the Ack flag set so this is going to drop every single packet going to the server after the 3whs.  (I believe "flags:A" was used in snort before the flow: established functionality was added, so these are doing pretty much the exact same thing and it's an extra unnecessary check)
If your server is not in the ..1.0/24 range, then this rule will not do anything because it's a uni-directional rule. It would be impossible to have a packet going to 192.168.1.0/24 that is considered flow to server in that case. Since you said your servers are in the ..2.0/24 and ..3.0/24 range, this rule would not do anything at all.
Examples:
Client: 192.168.1.1
Server: 192.168.3.2

In this scenario, the rule will never match because the server does not fall within the 192.168.1.0/24 range.
Reversing the above example:
Client: 192.168.3.2
Server: 192.168.1.1

After the 3 way handshake, any packets in the session that are from 192.168.3.2 to 192.168.1.1 will be dropped. An event will be generated if 10 packets are sent within 10 seconds from client to server.


text:
Q: Ansible playbook to install and configure MySQL on Ubuntu I am trying to set up MySQL reasonably secured,
on Ubuntu 22.04, using Ansible. This is my playbook (from a post by Lorin Hochstein) See Ansible idempotent MySQL installation Playbook This is my playbook (converted for apt and Ubuntu)
- hosts: carme.hcs
  become: yes
  gather_facts: false
  vars:
    new_mysql_root_password: <redacted>
    mysqlsoftware:
      - python3-pymysql
      - mysql-client
      - mysql-server

  tasks:
    - name: Install MySQL
      action: apt install {{ item }}
      with_items: "{{ mysqlsoftware }}"

    - name: Start the MySQL service
      action: service name=mysql state=started

    # 'localhost' needs to be the last item for idempotency, see
    # http://ansible.cc/docs/modules.html#mysql-user
    - name: update mysql root password for all root accounts
      mysql_user:
        check_implicit_admin: true
        login_user: root
        name: root
        priv: '*.*:ALL,GRANT'
        host: "{{ item }}"
        password: "{{ new_mysql_root_password }}"
      with_items:
        - 127.0.0.1
        - ::1
        - localhost

    - name: copy .my.cnf file with root password credentials
      template: src=./shared/my.cnf.j2 dest=/root/.my.cnf owner=root mode=0600

    - name: delete anonymous MySQL server user for $server_hostname
      action: mysql_user user="" host="{{ server_hostname }}" state="absent"

    - name: delete anonymous MySQL server user for localhost
      action: mysql_user user="" state="absent"

    - name: remove the MySQL test database
      action: mysql_db db=test state=absent`

Steps 1 and 2 work just fine.
Step 3 always fails with
TASK [update mysql root password for all root accounts] ********************************************************************************************************* failed: [carme.hcs] (item=127.0.0.1) => {"ansible_loop_var": "item", "changed": false, "item": "127.0.0.1", "msg": "unable to connect to database, check login_user and login_password are correct or /root/.my.cnf has the credentials. Exception message: (1698, \"Access denied for user 'root'@'localhost'\")"} failed: [carme.hcs] (item=::1) => {"ansible_loop_var": "item", "changed": false, "item": "::1", "msg": "unable to connect to database, check login_user and login_password are correct or /root/.my.cnf has the credentials. Exception message: (1698, \"Access denied for user 'root'@'localhost'\")"} failed: [carme.hcs] (item=localhost) => {"ansible_loop_var": "item", "changed": false, "item": "localhost", "msg": "unable to connect to database, check login_user and login_password are correct or /root/.my.cnf has the credentials. Exception message: (1698, \"Access denied for user 'root'@'localhost'\")"}
I have checked on carme.hcs, and /root/.my.cnf does not exist.
I can log in to mysql with "sudo mysql" but not with
"mysql -u root" nor with "mysql -u root -p". Is this not
the default set up of a fresh MySQL install, that I wish to change?
I also ran 'select user, host, plugin, authentication_string from user where user = "root";' on carme, and the result is garbled beyond belief.
In short, plugin = "mysql_native_password" and authentication_string is blank for root@localhost.
I do not understand what is going wrong. Some enlightenment please!

A: There are so many things wrong with the playbook I'm embarrassed.

*

*I misunderstood about installing pip and what should be installed with apt and what with pip.

*apt will hang, and needs a -y param.

*It leaves /root/.my.cnf so root can still log in with no password.

*When that is fixed, when it is run twice it will fail the second time because it can't log in with no password.

*127.0.0.1 and ::1 do not exist in mysql.user table, so they do not need to have their root access removed.

OK, Lets post the updated playbook.
- hosts: carme.hcs
  become: yes
  gather_facts: false
  vars:
    new_mysql_root_password: redacted
    mysqlsoftware:
      - mysql-server
      - mysql-client
  tasks:
    - name: install python, pip etc
      shell: apt-get -y install "{{ item }}"
      with_items:
        - pip
        - python3-dev
        - default-libmysqlclient-dev
        - build-essential

    - name: Install MySQL server
      shell: apt-get -y install mysql-server

    - name: Install MySQL client
      shell: apt-get -y install mysql-client

    - name: pip install mysqlclient
      shell: pip install mysqlclient

    - name: Start the MySQL service
      action: service name=mysql state=started

    - name: copy .my.cnf file with root password credentials
      template: src=/home/ian/Ansible/playbooks/shared/my.cnf.j2 dest=/root/.my.cnf owner=root mode=0600

    - name: update mysql root password for all root accounts
      mysql_user:
        name: root
        host: localhost
        password: "{{ new_mysql_root_password }}"

    - name: delete anonymous MySQL server user for localhost
      action: mysql_user user="" state="absent"

    - name: remove the MySQL test database
      action: mysql_db db=test state=absent

    - name: Remove   /root/.my.cnf
      ansible.builtin.file:
        path: /root/.my.cnf
        state: absent


text:
Q: Keep getting errors on my Pointer code in c++ for no apparent reason So I am experimenting with pointers as I am quite new to C++ programming  the error p1 was not declared in this scope keeps coming up I have no clue what's wrong I have searched the deepest corners of the internet to no avail.
#include <iostream>
using namespace std;

int main()
{
    int num1 = 8;
    *p1 = &num1;

    cout << "VALUE:" <<  *p1 <<endl;
    cout << "adress" << &num1 <<endl;

    return 0;
}

A: You have not mentioned the type of *p1 = &num1; - it should be:
int num1 = 8;
int *p1 = &num1;


text:
Q: Ubuntu 16.04 AMDGPU-Pro Not Recognizing Second Graphics Card Running Ubuntu 16.04. Installed AMDGPU-Pro driver. I have an MSI Z270 motherboard, with two AMD Radeon RX 470 graphics cards connected.
When I run lspci | grep VGA only one of the two cards displays.
The exact output is:
cardinal@cardinal-MS-7850:~$ lspci | grep VGA
01:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Ellesmere [Radeon RX 470/480] (rev cf)

As you can see, only one card is visible. I tried uninstalling and reinstalling the driver software, then restarting.
Does anyone know what I should try next to see the second gpu?
The ultimate goal is to run a driver with OpenCl, as I am trying to run ethminer, using multiple GPU's. I am also not sure if it is maybe it is the OS, and would need to reinstall Ubuntu.


text:
Q: @OneToMany relationship using a single @JoinColumn? I have the following tables (most essential columns shown only, A & B are not the real names btw):
table A {
  ...
}

table B {
  ...
}

table METADATA {
  KEY
  VALUE
  REF_A
  REF_B
}

METADATA holds additional key/value meta data for both table A & B. The key/value is needed as we have to handle dynamic data for which we cannot up front create columns for in A and B.
The entities are setup as (JPA using hibernate as provider):
interface Entity {
  ...
  getId()
  ...
}

class A implements Entity {
  ...
  @OneToMany(cascade = {ALL}, mappedBy = "a", orphanRemoval = true, fetch = LAZY)
  private List<MetaData> metaData;
  ...
  @Override
  public List<MetaData> getMetaData() {
    return metaData;
  }
  ...
}

class B implements Entity {
  ...
  @OneToMany(cascade = {ALL}, mappedBy = "b", orphanRemoval = true, fetch = LAZY)
  private List<MetaData> metaData;
  ...
  @Override
  public List<MetaData> getMetaData() {
    return metaData;
  }
  ...
}

class MetaData implements Entity {
  ...
  @ManyToOne
  @JoinColumn(name = "REF_A", nullable = true)
  private A a;

  @ManyToOne
  @JoinColumn(name = "REF_B", nullable = true)
  private B b;
  ...
}

This setup works fine. However we have run into issues on some databases (for instance DB2) with a unique index we create (to ensure a meta key is only used once for a given row in A or B):
CREATE UNIQUE INDEX METADATA_UNIQUE_KEY ON METADATA (METAKEY, REF_A, REF_B)

as creating the index requires requires that all columns are non-null. This is not the case for use with the above design as the domain logic will either be that the meta data is set on A or B, hence one of these will always be null.
Possible solutions of course are to split the METADATA into two tables, one for A and one for B. However I would prefer to keep one table and instead just have one "REF" column which would either be an A or B as well as a TYPE column to say whether it's a meta data for an A or B. The TYPE would be needed as we have separate sequences for id for each table and a A and B could get the same technical id and hence get mixed up data otherwise.
My question is - is there any way to set this up with JPA?
For one-table based inheritance there is a @DiscriminatorValue which can be used to distinguish the specific stored sub-class, can this be used here as well? I am looking for something like:
table A {
  ...
}

table B {
  ...
}

table METADATA {
  KEY
  VALUE
  REF
  TYPE
}

@DiscriminatorValue("A")
class A implements Entity {
  ...
  @OneToMany(cascade = {ALL}, mappedBy = "entity", orphanRemoval = true, fetch = LAZY)
  private List<MetaData> metaData;
  ...
  @Override
  public List<MetaData> getMetaData() {
    return metaData;
  }
  ...
}

@DiscriminatorValue("B")
class B implements Entity {
  ...
  @OneToMany(cascade = {ALL}, mappedBy = "entity", orphanRemoval = true, fetch = LAZY)
  private List<MetaData> metaData;
  ...
  @Override
  public List<MetaData> getMetaData() {
    return metaData;
  }
  ...
}

class MetaData implements Entity {
  ...
  @ManyToOne
  @JoinColumn(name = "REF", nullable = true)
  private Entity entity;

  @DiscriminatorColumn(name="TYPE", discriminatorType=STRING, length=20)
  private String type;
  ...
}

so basically when a meta data is inserted for A this SQL would be used:
INSERT INTO METADATA (KEY, VALUE, REF, TYPE) VALUES ("metaKey", "metaValue", 1, "A")

Any suggestion are welcomed.
Rgs,
-Martin

A: I'm not sure why you need to create a key (metakey) in the metadata table, given thet the rows are already tied either to Table A or Table B.
However I think the problem is in considering the MetaData table an entity, given that its only purpose is to save some extra information of an existing entity, it means that you cannot have a row in MetaData without a row in TableA or TableB.
Instead of using relationship mapping one option is to use element collections to directly have the Map of key/value pairs in the corresponding entities:
@Entity
@Table(name="TableA")
public class TableA
{
    @Id
    @GeneratedValue(strategy= GenerationType.TABLE)
    private int id;

    @ElementCollection
    @CollectionTable(name="MetaData", joinColumns={@JoinColumn(name="TableA_id")})
    @MapKeyColumn(name="metaKey")
    @Column(name="metaValue")
    private Map<String, String> metadata;
}

@Entity
@Table(name="TableB")
public class TableB
{
    @Id
    @GeneratedValue(strategy= GenerationType.TABLE)
    private int id;

    @ElementCollection
    @CollectionTable(name="MetaData", joinColumns={@JoinColumn(name="TableB_id")})
    @MapKeyColumn(name="metaKey")
    @Column(name="metaValue")
    private Map<String, String> metadata;
}

Note that there is no java class for a "MetaData" table or entity, the table is automatically mapped from the @ElementCollection and @CollectionTable annotations.
The above mappings correspond to the following MetaData table:
+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| TableA_id | int(11)      | YES  | MUL | NULL    |       |
| metaValue | varchar(255) | YES  |     | NULL    |       |
| metaKey   | varchar(255) | YES  |     | NULL    |       |
| TableB_id | int(11)      | YES  | MUL | NULL    |       |
+-----------+--------------+------+-----+---------+-------+

If you prefer to keep a separate java class for MetaData to keep using a List instead of a Map, it can also be done with @ElementCollection, you just need to annotate the MetaData class with @Embeddable instead of @Entity. In that way it doesn't need an Id column like a regular entity.


text:
Q: how to delete the specific item in the document directory ios objective c I want remove specific item from DocumentDirectory i.e I have 50 objects in the DocumentDirectory and i want to remove the 5 different elements from it. I used following code to get the DocumentDirectory objects.
NSURL *vedioURL;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];

NSLog(@"files array %@", filePathsArray);

can any one Help me out to solve this problem

A: You can try the following approach
NSString *path = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [paths[0] stringByAppendingPathComponent:@"YOUR DIR"];
path = [path stringByAppendingPathComponent:@"YOUR FILE"];
NSError *error;
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
    if (![[NSFileManager defaultManager] removeItemAtPath:path error:&error])   //Delete it
    {
        NSLog(@"Delete file error: %@", error);
    }
}

A: You can try like this way
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (filePathsArray.count >= 6) {
    for (NSInteger i=filePathsArray.count-6; i < filePathsArray.count; i++) {
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:i]];
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])  {
           NSError *error;
            if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]) {
                NSLog(@"Delete error: %@", error);
            }
        }
    }
}


text:
Q: How to find repeating numbers in a column in SQL server . Eg 11111, 33333333, 5555555555,7777777 etc I need to identify repeated numbers( Eg: 1111, 33333333, 5555555555,777777777 etc.) in a column.
How can I do this in sql server without having to hard code every scenario. The max length is 10 of the column. Any help is appreciated.

A: This will check if the column has all the same value in it.
SELECT *
FROM tablename
WHERE columnname = REPLICATE(LEFT(columnname,1),LEN(columnname))

As Nicholas Cary notes, if the column is numbers you'd need to cast as varchar first:
SELECT *
FROM tablename
WHERE CAST(columnname AS VARCHAR(10)) = REPLICATE(LEFT(CAST(columnname AS VARCHAR(10)),1),LEN(CAST(columnname AS VARCHAR(10))))

A: Riffing on @Dave.Gugg's excellent answer, here's another way, using patindex() to look for a character different than the first.
select *
from some_table t
where 0 = patindex( '[^' + left(t.some_column,1) + ']' , t.some_column )

Again, this only works for string types (char,varchar, etc.). Numeric types such as int will need to be converted first.


text:
Q: Joining multiple tables together with eloquent and eager loading in laravel [implementing filter] What I have already and what I'm trying to do:
I have a website that lets users make posts advertising themselves to other users. Now, I'm trying to implement a filter for these posts but filter by values in the users table, posts table and three others. This is where I'm running into some trouble.
Code that works, as is, no filter:
$posts = Post::with('user','lookingfors','playstyles', 'postcomments')->orderBy('id', 'DESC')->paginate(10);

return View::make('posts/index', compact('posts'));

This is what I've tried:
$posts = User::leftjoin('posts', function($join)use($region){
            $join->on('users.id', '=', 'posts.user_id');
            $join->on('playstyle_post.post_id', '=', 'posts.id'); // join pivot, then join pivot to playstyles
            $join->on('playstyle_post.playstyle_id', '=', 'playstyles.id');
            //$join->on;
        })->where('users.region_id', 'like', $region)->get();

This one keeps bringing up this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'playstyle_post.post_id' in 'on clause' (SQL: select * from users
  left join posts on users.id = posts.user_id and
  playstyle_post.post_id = posts.id and
  playstyle_post.playstyle_id = playstyles.id where
  users.region_id like ?) (Bindings: array ( 0 => 6, ))

Also:
$posts = Post::with('lookingfors', 'playstyles', 'postcomments')
        ->leftjoin('users', 'posts.user_id', '=', 'users.id')
        //->join('playstyle_post', 'posts.id', '=', 'playstyle_post.post_id')
        ->paginate(10);

This one is odd ( well for me ), when 'leftjoin' is commented out obviously it works just as before, but when I have it as it is now it displays the view as it should and even pulls all the right values from the users table but does not display any of the information thats being requested through the 'with'.
I've tried a couple other things in the last two weeks, but I've already thrown them out when they didn't work. This has been kicking my ass for the better half of a month and I can't wrap my head around why I can't get it to work.
So really, my trouble right now is just trying to join the tables and returning it to the view in an eloquent fashion so I can keep treating it the same. The filter itself will be a problem of its own, but getting the joins to work has proved to be the hard part.

A: Instead of passing a bunch of relationship names to the with() function, try passing an array, setting keys as the names of the relationships and the values as callback functions and pass in the query for actual editing.  Also will have to use use ($region) where needed.  Hopefully you get the idea.
I put in some examples for adding filters on each relationship.  Because you are working locally with each one, you shouldn't have to worry about prefixing them with table names or aliases.
$posts = Post::with(array(
'user' => function($query) use ($region)
{
    // User constraints here
    $query->where('status', 'A');
    $query->where('deleted', '0');
},
'lookingfors' => function($query)
{
    // lookingfors constraints here
    $query->where('name', 'somelookingforname');
},
'playstyles' => function($query)
{
    // playstles constraints here
    $query->where('name', 'someplaystylesname');
},
'postcomments' => function($query)
{
    // Some postcomments constraints here
    $query->where('name', 'somepostcommentsname');
}))
->orderBy('id', 'DESC')
->paginate(10);

Looking at your attempt at left joins though, I don't know if these relationships are correct.  My example assumes all the relationships can relate directly back to the user table.  Otherwise, you will need to change the keys on the array to match how the relationships should be.
For example, if trying to relate to the playstyles table, but the relationship between playstyles and posts doesn't exist because you need to go through the users table first, you would just change 'playstyles' to 'users.playstyles'.
If you post your migrations, I could help you further.


text:
Q: How to get flutter app to span the width of joined displays on Linux I have started with Flutter recently and am developing some simple applications on Ubuntu Linux. I noticed that the main app screen by default will stretch to the size of the set resolution. I have two questions:
(1) Is there some way of creating an application with a width that is wider than the set resolution (3000-pixel width on a 1920X1080 display)? I tried creating an app with a container and setting the minimum width but the application always snaps back to the display resolution of 1920 on launch.
(2) Extending this question a little. If I have joined displays using two monitors is there a way I can get the application to open at the width of the joined display. So on a setup up with two 1920X1080 screens, my app opens with a width of 3840?


text:
Q: Extract text before first \sx\s with regex I have text like this:
#12222223334 x $32.97

I want to extract the last number of the number before the "x" for example in this case the number 4.
Another example: #8885555889 x $33.33. Here, the number I want is 9.
I tried ^(.+?) x, but its all the number before the x.

A: this also gets you the last digits before the space and x
https://regex101.com/r/zVevtY/1
(\d)\s?x

# (\d) : capture a digit
# \s? : before a possible white space
# x : followed by literal x

A: If your regex engine support lookaheads, you may use:
\d(?=\s*x\s+\$\d+(?:\.\d+)?$)

Demo
This pattern says to match:

*

*\d a single digit

*(?= assert that what follows (but do not match)

*

*\s*x\s+ x

*\$\d+(?:\.\d+)? followed by a currency amount

*$ end of the string

*) end lookahead


text:
Q: Redis Exceptions with ServiceStack I periodically I get these exceptions:
RedisResponseException
Unexpected reply: +OK, sPort: 60957, LastCommand:
It seems to happen when lots of activity occurs simultaneously. Using even the latest Amazon ElastiCache server, as well as local Mac & Ubuntu flavors.
Other errors occur to but this is the most common. Is there some gotcha with Redis in terms of config settings etc?

A: Are you using PooledRedisClientManager or BasicRedisClientManager?
I got a lot of Unexpected reply whith BasicRedisClientManager

A: I had the same error (Unexpected reply) on a multi-threaded Azure Worker Role.
Solution:
The ServiceStack.Redis.RedisClient is not Thread safe.
On multithreaded applications you need to create a new insance of the RedisClient for each thread!
var myRedisClient = new RedisClient(accessKey);

...or use the client manager as fvoncina said. But I didn´t use it so far.


text:
Q: Tkinker cursor that impacts a graph I am not good at all at informatics.
I don't find anything on the website that explains how to change a value on a cursor that will impact a specific variable in a model that is represented in a graph. With X depending on the time (that is a loop).
We have the following easy model : X= L + Z + H and the 3 variable that are cursors.
Here is our code for a first cursor with tkinter:
from tkinter import *
def sel():
   selection = "Value = " + str(var.get())
   label.config(text = selection)
   print(var.get())
root = Tk()
var = DoubleVar()
root = Tk()
var = DoubleVar()
scale = Scale( root, length = 150, from_=-3, to=5, variable = var)
scale.pack(anchor = CENTER)
button = Button(root, text = "Get Scale Value", command = sel)
button.pack(anchor = CENTER)
label = Label(root)
label.pack()
root.mainloop()

Thank you very much !


text:
Q: 503 Login WordPress Anyone have experience failed to login and got the 503 Service Unvailable?
My WP site hosted on GoDaddy Managed Hosting. They said cause of this is came from the WooCommerce. I tried to disable this but the error still occured.
Thanks

A: I've had 503 errors when using shared hosting services with Fasthosts / Rackspace etc.  Typically, they don't last long, but if yours are - then there is something going on with the server you are sharing.  You might want to check that the memory limit in the config is 96 MB but that shouldn't be causing the issue.


text:
Q: dereferencing a char* always gives segmentation fault I am trying to go over the memory addresses and see different accessibility of the contiguous memory areas, which are: read-only, read&write and no accessibility. I also have a signal handler that takes care of segmentation fault so the program can continue running.

char* currentAdd;
char readBuf;

for (unsigned int i = 0; i < 0xffffffff, i+=PAGE_SIZE){
    currentAdd = (char*)i;
    jmpVar = sigsetjmp(env,1); // don't worry about this, it's handled properly

    if(jmpVar == 0){
    currentMode = MEM_RO;
    readBuf = *currentAdd; // always a segmentation fault

    // it can never try writing!!
    currentMode = MEM_RW;
    *currentAdd = readBuf;
    }
    else{
    ...
    }

}

my program never goes past (readBuf = *currentAdd;), which is sometimes expected but not always. Did I do something wrong?
I tried to start from i=1, to prevent what some people suggested but still it keeps giving me the segmentation fault.

A: well you start your loop at i = 0, and then give currentAdd the address of a char at the address i, so currentAdd is basically (void*)0, aka NULL, so you are deferencing NULL, and no computer really like that.


text:
Q: CriteriaBuilder Predicate isMember using only entity ID Given the following entities, how can I construct a JPA Predicate to select only those Items that have a Category with a given ID in their categories set?
@Entity
public class Item
{
  @Id
  private String id;

  private String name;

  @JoinTable(name="category_items",
    joinColumns={@JoinColumn(name="item_id")},
    inverseJoinColumns={@JoinColumn(name="category_id")})
  private Set<Category> categories;

  /* etc */
}

@Entity
public class Category
{
  @Id
  private String id;

  private String name;

  /* etc */
}

I think I can do it if I have the Category object to hand:
Predicate buildPredicate( CriteriaBuilder cb, Root root, Category category )
{
  Expression<Collection<Category>> categories = root.get( "categories" );
  return cb.isMember( category, categories );
}

But my question is : Can I do it using only the Category.id string? In SQL it would be something like
SELECT item.id, item.name FROM item JOIN category_items ON item.id = category_items.item_id WHERE category_items.category_id=?

which doesn't go near the category table.
I ask because I want to avoid having to create or retrieve a new Category instance when all I need is its ID, which I already have.
Thanks for any help!

A: I eventually solved this using join and not isMember:
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Item> cq = cb.createQuery( Item.class );
Root from = cq.from( Item.class );
From join = from.join( "categories" );
Path<Item> p = join.get( "id" );
Predicate predicate = cb.equal( p, "my_category_id" );
cq.where( predicate );
cq.select( from );
TypedQuery<Item> typedQuery = em.createQuery( cq );
List<Item> resultList = typedQuery.getResultList();


text:
Q: Interceptor not intercepting http requests (Angular 6) I'm in the proces of adding an interceptor to my angular 6 project. To make calls to my API, I need to add a bearer token to all calls. Unfortunately the interceptor does not seem to be called. My code:
import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>,
              next: HttpHandler): Observable<HttpEvent<any>> {

        //Retrieve accesstoken from local storage
        const accessToken = localStorage.getItem("access_token");

        //Check if accesToken exists, else send request without bearer token
        if (accessToken) {
            const cloned = req.clone({
                headers: req.headers.set("Authorization",
                    "Bearer " + accessToken)
            });

            console.log('Token added to HTTP request');

            return next.handle(cloned);
        }
        else {
            //No token; proceed request without bearer token
            console.log('No token added to HTTP request');
            return next.handle(req);
        }
    }
}

Does anyone know what could be causing this issue?
Thanks in advance.

A: If you have a providers array for a module then you have to define the HTTP_INTERCEPTORS too for that module then only it will intercept the requests under that module.
e.g:
providers: [
// singleton services
PasswordVerifyService,
{ provide: HTTP_INTERCEPTORS, useClass: AppInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptorService, multi: true }
]

A: You use the right way to intercept.
For people who use interceptor, you need to do 2 modifications :
Interceptor in service
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse }
  from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {

    return next.handle(req).do(evt => {
      if (evt instanceof HttpResponse) {
        console.log('---> status:', evt.status);
        console.log('---> filter:', req.params.get('filter'));
      }
    });

  }
}

Provide HTTP_INTERCEPTOR
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
(...)
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
  ],

Read this article for more details. It's pretty good

A: In my case, I had to import both HTTP_INTERCEPTORS, HttpClientModule in same module.

A: In my case i had a post method like this:
this.http.post<any>(this.authUrl, JSON.stringify({username: username, password: password})).pipe(
      map((response: any) => {
            let token: any = response.token;
            if (token) {
                localStorage.setItem('currentUser', 'value' }));
                return response;
            } else {
                return null;
            }
        }),
        catchError((error:any) => {return observableThrowError(error.json().error || 'Server error')})
      );

Because the map method could return null the interceptor stopped intercepting the requests made with this post method call. Don't ask me why this is so, but as soon as i replace null with say response everything started working again.

A: In my case interceptor wasn't getting involved for service calls because I had imported HttpClientModule multiple times, for different modules.
Later I found that HttpClientModule must be imported only once. Doc ref

A: Check your module & sub-module files, If you have imported the interceptor in a sub-module, then move it to the root module and it should work.

A: In my case I accidentally had my service proivded providers  : [ ApplicationService ] in my component when it wasn't supposed to be as I had it defined using providedIn: 'root'

A: Please ensure that dependencies for the interceptor are also provided in the module. ProvidedIn:'root' for the interceptor dependency services did not work for me.

A: In my case, since I am working with modules, I had to import the child module (AuthModule) in app.module.ts. I was just missing that.
imports: [
HttpClientModule,
AppRoutingModule,
AuthModule
]

A: In my case the HttpClient was not used to do the requests.
Instead fetch has been used directly and that is not intercepted by angular.
Changed fetch(...) to http.get(...) and it worked


text:
Q: Execute a command with superuser permission in JNI method in Android In Java, I can have something like this:
Process p = Runtime.getRuntime().exec("su");
DataOutputStream pOut = new DataOutputStream(p.getOutputStream());
pOut.writeBytes("find / -perm -2000 -o -perm -4000\n");
pOut.writeBytes("ps\n");
pOut.writeBytes("ls\n");
pOut.writeBytes("exit\n");
pOut.flush();
p.waitFor();

I know that to execute the find command in JNI method, we can use system or popen function. But I don't know how to execute it with su privilege?
PS: Since the system function forks a new child process. I want to have a single child process spawning up to execute multiple commands like in Java.

A: I don't see what's the point for you to use system() to execute, system() doesn't return you stream to read the output.
I think you should try popen() instead

A: Assuming you have su installed on your Android device and it is in the path, you could try it like this:
system("su -c \"find / -perm -2000 -o -perm -4000\" root");

su accepts arguments: the -c argument specifies a command to run.
EDIT: you might be out of luck there. I'm not sure if you can pass multiple commands to the su command. You might get away with passing it a shell and then passing that shell commands, but no guarantees there.
system("su -c \"sh -c 'find / -perm -2000 -o -perm -4000; rm /tmp/1'\" root");

A: Femi answer is close, I have tested, the following works for me:
system("su -c \"find / -perm -2000 -o -perm -4000; ps; ls\"");


text:
Q: How to yield an Exception in a stream so that it can be caught in widget tree? I can't seem to find a way to intentionally yield or throw an error in a stream in such a way that can be used by an AsyncValue widget in the tree (using Riverpod for State Management).
class AsyncValueWidget<T> extends StatelessWidget {
   AsyncValueWidget(
      {Key? key,
      required this.value,
      required this.data
      : super(key: key);
  final AsyncValue<T> value;
  final Widget Function(T) data;

  @override
  Widget build(BuildContext context) {
    return value.when(
      data: data
      error: (e, st) => Center(child: ErrorMessageWidget(e.toString())),
      loading: () => const Center(child: CircularProgressIndicator()),
    );
  }
}

I want the stream in my fake repo to return a value in certain cases and Exception in other cases:
`
  Stream<T> function() async* {
    await Future.delayed(const Duration(milliseconds: 500));

    switch (condition) {
      case condition 1:
        yield value1;
        break;
      case condition 2:
        yield value2;
        break;
      case condition 3:
        // neither these work
        throw Exception('You should not be able to call this function under this condition');
        yield* Stream.error()...
      case condition 4:
        yield null;
        break;
    }
  }

`
Unfortunately, the Exception/Error does not seem to make it to the widget and I get a nasty red screen. I've also tried try/catch to no avail. Any ideas?

A: if you are working with a service, I recommend FutureBuilder. for more info you can check here https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

FutureBuilder(
              future: controller.mainFuture.value,
              builder: (context, snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.active:
                  case ConnectionState.waiting:
                    return Container(
                      color: Colors.white,
                      width: context.width,
                      height: context.height,
                      child: globalShimmer(height: 50, itemCount: 10),
                    );
                  case ConnectionState.done:
                    if (snapshot.hasError) {
                      return Container();
                    }
                    return Container();
                  default:
                    return Container();
                }
              });

A: To return a fake error to a stream using riverpod, just simply return Stream.error('Something went wrong'):

final fakeErrorStreamProvider = StreamProvider.autoDispose<List<T>>(
  (ref) {
    return Stream.error('something went wrong');
  },
);

or

  Stream<List<T>> watchWhatever() => Stream.error('Something went wrong.');

Your AsyncValueWidget will catch this error from the UI.