text:
Q: I can't setText to navigation view menu item after user is logged it. Error : NullPointerException I'm trying to setText and setDrawable in the NavigationView menuItem after the user is signed in. But after user is signing in i'm getting NullPointerException for the TextView and CircleImageView. Here is the java code and XML for the menu and NavigationView
    @Override
        protected void onStart() {
            super.onStart();
            userAuth.addAuthStateListener(authStateListener);
        }
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        userAuth = FirebaseAuth.getInstance();

        sideMenu = findViewById(R.id.navMenu);

        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() != null)
                    updateActivity(true);
                else
                    updateActivity(false);
            }
        };

    private void updateActivity(Boolean isActive) {
            CircleImageView circleImageView = (CircleImageView) sideMenu.getMenu().findItem(R.id.profile_image);
            if(isActive)
            {
                Glide.with(Home.this)
                        .load(Objects.requireNonNull(userAuth.getCurrentUser()).getPhotoUrl())
                        .centerCrop()
                        .into(circleImageView);
                ((TextView)findViewById(R.id.navName)).setText(userAuth.getCurrentUser().getDisplayName());
                sideMenu.getMenu().findItem(R.id.logout).setVisible(true);
                sideMenu.getMenu().findItem(R.id.login).setVisible(false);
            }else
            {
                Glide.with(Home.this)
                        .load(R.drawable.splash_logo)
                        .centerCrop()
                        .into(circleImageView);
                ((TextView)findViewById(R.id.navName)).setText(R.string.app_name);
                sideMenu.getMenu().findItem(R.id.logout).setVisible(false);
                sideMenu.getMenu().findItem(R.id.login).setVisible(true);
            }

        }

This is the menu (home.xml)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group
        android:id="@+id/main"
        android:checkableBehavior="single">
        <item
            android:id="@+id/login"
            android:title="Login" />
    </group>

    <group
        android:id="@+id/second"
        android:checkableBehavior="single">
        <item
            android:id="@+id/share"
            android:title="Share" />
        <item
            android:id="@+id/report"
            android:title="Report" />
    </group>

    <group
        android:id="@+id/third"
        android:checkableBehavior="single">
        <item
            android:id="@+id/license"
            android:title="Licenses"/>
        <item
            android:id="@+id/developer"
            android:title="Developer" />
        <item
            android:id="@+id/contact"
            android:title="Contact us" />

        <item
            android:id="@+id/logout"
            android:title="Logout"
            android:visible="false" />
    </group>

</menu>

This is NavigationView in activity.xml
<com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/navigation_header"
        app:menu="@menu/home"
        android:id="@+id/navMenu"/>

navigation_header.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimaryDark"
    android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/profile_image"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        app:civ_border_color="#ffffff"
        app:civ_border_width="2dp"
        android:src="@color/colorPrimary"/>

    <TextView
        android:id="@+id/navName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/profile_image"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp"
        android:layout_marginBottom="10dp"
        android:fontFamily="@font/montserrat_bold"
        android:text="User Name"
        android:textAlignment="center"
        android:textColor="@android:color/white"
        android:textSize="25sp" />

</RelativeLayout>

A: First try to get headerView from NavigationView and then get your CircleImageView and TextView like below:
View headerView = sideMenu.getHeaderView(0);
CircleImageView circleImageView = (CircleImageView) headerView.findViewById(R.id.profile_image);
TextView navName = (TextView) headerView.findViewById(R.id.navName);

Complete solution:
private void updateActivity(Boolean isActive) {

    View headerView = sideMenu.getHeaderView(0);

    CircleImageView circleImageView = headerView.findViewById(R.id.profile_image);
    TextView navName = headerView.findViewById(R.id.navName);

    if(isActive) {
        Glide.with(Home.this)
            .load(Objects.requireNonNull(userAuth.getCurrentUser()).getPhotoUrl())
            .centerCrop()
            .into(circleImageView);

        navName.setText(userAuth.getCurrentUser().getDisplayName());
        sideMenu.getMenu().findItem(R.id.logout).setVisible(true);
        sideMenu.getMenu().findItem(R.id.login).setVisible(false);
    } else {
        Glide.with(Home.this)
            .load(R.drawable.splash_logo)
            .centerCrop()
            .into(circleImageView);
        navName.setText(R.string.app_name);
        sideMenu.getMenu().findItem(R.id.logout).setVisible(false);
        sideMenu.getMenu().findItem(R.id.login).setVisible(true);
    }
}


text:
Q: Finding exact match of letters from a link occuring only once I created some code to add some text depending on the language found in the link but I have a problem with matching exactly the language because the pattern is too simple. I need to find exactly what comes after .com and nothing else. I tried this /.*\/\/.*?\/(\S{2})/gm expression but, it isn't exactly what I'm looking for.

//find the url of the page
// const findUrl = window.location.href;
const findUrl = "https://www.example.com/fr/Pages/examplefr.html";
console.log(findUrl);

const langs = [{
    pattern: /en/, //find strictly only the EN
    text: "A very long text in English to replace existing text"
  },
  {
    pattern: /fr/, //find strictly only the FR
    text: "Je ne parle pas français"
  },
  {
    pattern: /es/, //find strictly only the ES
    text: "No hablo español."
  }
];

let found = false;
for (let i = 0; i < langs.length; i++) {
  if (findUrl.match(langs[i].pattern)) {
    console.log("The match has been found!");
    let findP = document.getElementById("texts").querySelectorAll("p");
    findP[0].innerText = langs[i].text;
    found = true;
    break;
  }
}
if (!found) {
  console.log("The match was not found");
}

Some text here

A: You could use a regex like /\.com\/(\w{2})\// to get the language and compare it as a text. This would be easier if your langs object was of the format {[lang: string]: string}.

const findUrl = "https://www.example.com/fr/Pages/examplefr.html";
console.log(findUrl);

const langs = {
  "en": "A very long text in English to replace existing text",
  "fr": "Je ne parle pas français",
  "es": "ANo hablo español.",
};

if (!findLanguage()) console.log("The match was not found");

function findLanguage() {
  var result = /\.com\/(\w{2})\//.exec(findUrl);
  if (result && result[1] in langs) {
    console.log("The match has been found!");
    document.querySelector("#texts p").textContent = langs[result[1]];
    return true;
  }
}

Some text here

A: You can extract the 'lang pattern' from the original URL and find the object in your array that matches this pattern:

//find the url of the page
// const findUrl = window.location.href;
const findUrl = "http://enmicasa.com/es/Pages/examplefr.com/fr";
console.log(findUrl);

const langs = [{
    pattern: "en", //find strictly only the EN
    text: "A very long text in English to replace existing text"
  },
  {
    pattern: "fr", //find strictly only the FR
    text: "Je ne parle pas français"
  },
  {
    pattern: "es", //find strictly only the ES
    text: "No hablo español."
  }
];
const myLang = langs.find(obj => findUrl.replace(/.*\.com\/(.+?)\/.*/,"$1") === obj.pattern);
if (myLang){
    console.log("The match has been found!");
    let findP = document.getElementById("texts").querySelectorAll("p");
    findP[0].innerText = myLang.text;
}else {
  console.log("The match was not found");
}

Some text here

Note: I changed the URL to test one with some complication on it

A: Hi check this snippet!

How it works

*

*We are iterating trought all values of the langs object using .map langs.map(e => ...)

*We are checking if the langs pattern + Regex matches the URI using findUrl.match(new RegExp(..com${e.pattern}., "g")

*We extract the matching value from the array using .filter(e => !!e).pop()

const findUrl = "https://www.example.com/fr/Pages/examplefr.html";

const langs = [{
    pattern: /en/, //find strictly only the EN
    text: "A very long text in English to replace existing text"
  },
  {
    pattern: /fr/, //find strictly only the FR
    text: "Je ne parle pas français"
  },
  {
    pattern: /es/, //find strictly only the ES
    text: "No hablo español."
  }
];

const result = (
  langs.map(e => !!findUrl.match(new RegExp(`.*\.com${e.pattern}.*`, "g")) ? e.text : null).filter(e => !!e).pop()
);
texts.innerText = result;
console.log(result);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shadow mapping does not work correctly using GLSL and OpenGL I have a scene composed with 2 meshes (plane, cube), a light and a camera. I want to display shadows on my scene using shadow mapping technique with GLSL shaders and OpenGL.
Here's the result I have (for a sake of simplicity, my cube and my plane are both in blue color and the color) :

Here's the FBO and depth texture initialization :
GLfloat border[] = {1.0f, 1.0f, 1.0f, 1.0f};

    glGenTextures(1, &this->m_TextId);
    glBindTexture(GL_TEXTURE_2D, this->m_TextId);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
    glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);

    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24,
        this->m_Width, this->m_Height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);

    glBindTexture(GL_TEXTURE_2D, 0);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, this->m_TextId, 0);

    glDrawBuffer(GL_NONE);
    glReadBuffer(GL_NONE);

    GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if( result == GL_FRAMEBUFFER_COMPLETE) {
        printf("Framebuffer is complete.\n");
    } else {
        printf("Framebuffer is not complete.\n");
    }

Here's the content of my vertex shader :
#version 400
layout (location = 0) in vec3 VertexPosition;
layout (location = 1) in vec3 VertexNormal;
layout (location = 2) in vec2 VertexTexture;

uniform mat4 MVP;
uniform mat4 ShadowMatrix;

out vec4 ShadowCoords;

void main(void)
{
    ShadowCoords = ShadowMatrix * vec4(VertexPosition, 1.0f);
    gl_Position = MVP * vec4(VertexPosition, 1.0f);
}

And the one of my fragment shader :
#version 400

in vec3 Position;
in vec3 Normal;
in vec2 TexCoords;
in vec4 ShadowCoords;

layout (location = 0) out vec4 FragColor;

uniform sampler2DShadow ShadowMap;

void main(void)
{
    vec4 ModelColor = vec4(0.0f, 0.0f, 1.0f, 1.0f);

    float shadow = textureProj(ShadowMap, ShadowCoords);

    FragColor = ModelColor * shadow;
}

As you can see there are some artifacts on the models and I don't know how to withdraw them. But the shadow seems to be correct so the variables in input in my shaders should be correct too (I think so).
I tried an other technique in the fragment shader like the following one :
#version 400

in vec3 Position;
in vec3 Normal;
in vec2 TexCoords;
in vec4 ShadowCoords;

layout (location = 0) out vec4 FragColor;

uniform sampler2D ShadowMap;

void main(void)
{
    vec4 ModelColor = vec4(0.0f, 0.0f, 1.0f, 1.0f);

    vec4 shadowCoordinateWdivide = ShadowCoords / ShadowCoords.w;

    shadowCoordinateWdivide.z += 0.0005;

    float distanceFromLight = texture2D(ShadowMap,shadowCoordinateWdivide.st).z;

    float shadow = 1.0;
    if (ShadowCoords.w > 0.0)
        shadow = (distanceFromLight < shadowCoordinateWdivide.z) ? 0.5 : 1.0 ;

    FragColor = shadow * ModelColor;
}

You can notice that I don't use a sampler2DShadow but now a sampler2D. But as you can see there's none shadow displayed :

Does anyone can help me?

A: Your first image can be explained by floating point problems. When you transform your vertex by your shadow matrix, you obtain a point whose distance from the light is almost equal to the depth in the light's depth buffer (since the point lies on the geometry). For some of those points, the transformation will give a light-space depth a little in front of the geometry and for others the depth will be a little to the back of the geometry. Hence half of them end up being occluded according to some weird pattern.
What you want to do is to perturb your ShadowCoords' Z coordinate a tiny bit towards the light to avoid this problem.


text:
Q: Modernizr detection of IndexedDB in iOS-Simulator Inside my app I use Modernizr to detect various features. To detect if IndexedDB is available I use "Modernizr.indexeddb". In the iOS Simulator (v8.1) it returns false! (It should return true, because IndexedDB is available since iOS 8.0 - nevertheless it's buggy behavior).
(The app uses AngularJS, MobileAngularUI and jQuery, but this not-related to the issue I think.)
I checked the same app in the Desktop-Safari and Chrome: Modernizr.indexeddb returns true.
I re-checked if indexedDB is supported on this device with this website:
https://www.browserleaks.com/modernizr  -  It shows that IndexedDB is supported inside the simulator's Safari Browser.
To be sure that I'm running the latest version of Modernizr I re-downloaded Modernizr from this URL:
http://modernizr.com/downloads/modernizr-latest.js
Edit: This Pluker contains a button where you can check the output of Modernizr.indexeddb.
I tested this on my iOS8.1 device, and on the 8.1 iOS Simulator. On both devices the return value was true!
The button triggers that function:
function checkIndexedDB() {
  alert('Modernizr.indexeddb = ' + Modernizr.indexeddb);
};

Why does my app (that runs in the cordova-container) has no indexeddb available?

A: I found the answer - IndexedDB is not available inside Cordova-Applications. (state today: 31. October '14)
In iOS8 a new component WKWebView has been introduced. Cordova still uses the old UIWebView component. They want to switch to the new WKWebView, but there are some bugs apple has to solve:

Unfortunately there is a serious bug in WKWebView where it can't load file:// urls, so it has hampered our efforts. This functionality was working in iOS 8 betas 1 to 3 on the device (it always works in the iOS 8 Simulator), but broken after that. I'm not sure what the ETA for the bug fix is, but it is in Apple's radar (literally!).

See this for more infos:
Does iOS 8 support IndexedDB with UIWebView?


text:
Q: How can I prevent docker compile a library every time I deploy to bitbucket? Is there any bitbucket pipeline cache? We have our Flask API in a docker image, we push this docker to a bitbucket repository, then a bitbucket pipeline start deploying.
Everything works as expected, but the compilation of OpenCV is taking in average 15 min.
I would like to know if is there any way to avoid this compilation every time we push to bitbucket. Something like caching.
I have read about cache on bitbucket pipelines but it did not work as I expected.
This is part of my Dockerfile I would like to improve:
RUN mkdir /opt && cd /opt && \
  wget -q https://github.com/opencv/opencv/archive/${OPENCV_VERSION}.zip && \
  unzip ${OPENCV_VERSION}.zip && \
  rm -rf ${OPENCV_VERSION}.zip && \
  mkdir -p /opt/opencv-${OPENCV_VERSION}/build && \
  cd /opt/opencv-${OPENCV_VERSION}/build && \
  CXX=/usr/bin/clang++ CC=/usr/bin/clang cmake \
  -D CMAKE_BUILD_TYPE=RELEASE \
  -D CMAKE_INSTALL_PREFIX=/usr/local \
  -D WITH_FFMPEG=NO \
  -D WITH_IPP=NO \
  -D WITH_OPENEXR=NO \
  -D WITH_TBB=YES \
  -D BUILD_EXAMPLES=NO \
  -D BUILD_ANDROID_EXAMPLES=NO \
  -D INSTALL_PYTHON_EXAMPLES=NO \
  -D BUILD_DOCS=NO \
  -D BUILD_opencv_python2=NO \
  -D BUILD_opencv_python3=ON \
  -D ENABLE_PYTHON3=ON \
  -D PYTHON3_EXECUTABLE=/usr/bin/python3 \
  .. && \
  make VERBOSE=1 -j8 && \
  make && \
  make install && \
  rm -rf /opt/opencv-${OPENCV_VERSION}

I expect some solution like just pointing a pre-compiled version of the OpenCV Api.

A: I have recently faced this problem and agree that cache doesn't seem to work as expected. However without looking at your entire Dockerfile, it's hard to say. ADD's and COPY's will invalidate the cache so i'd suggest you move this section up to the top if you can before adding any files.
A better solution (if there is no pre-compiled version), is to use the concept of a base image which is what I have done to cut my build time down in half. Basically you build a base image flask-api-base which will install all your packages and compile OpenCV and then your actual final image will pull FROM flask-api-base:latest and build your application specific code. Just remember if the base image changes, you may need to wipe your Bitbucket cache.

A: I'm unfamiliar with OpenCV but assume that, if there is a binary that you can use, that would be the ideal option.
I'm curious as to why this layer (RUN ...) isn't being cached between builds. It appears that you're cleanly separating the make of OpenCV from other statements in your Dockerfile and so, this RUN should generate a distinct layer that's stable and thus reused across builds.
Does this statement occur after earlier e.g. RUN statements that do change? If so, you may want to reorder this statement and place it earlier in the Dockerfile so that this layer becomes constant. See best practices for the Dockerfile statements that generate layers.
Alternatively, you could make a separate image containing OpenCV and then FROM this image in your code builds. You may do this either using distinct Dockerfiles or multi-stage builds. This way, this image containing the OpenCV build would only be built on (your) demand and reused across subsequent builds.

A: The solution I used was to create my own image, upload it to Docker hub, and create a new one based on that.
So the first docker image should contain all the basic libraries my system uses.
The second has the environmental variables and the api itself.


text:
Q: Is there sofware that can emulate how Oracle works with disks? Don't now if its a right place to ask, so if not please give me a hint.
I need some software that do can emulate how Oracle works with disks (Notice: Not the Oracle workload tool).
I've already took a look at solutions kinda Benchmark Factory (Quest Software), SwingBench, etc., but they do not emulate.

A: Why not just grab Oracle Express Edition ?

Oracle Database 10g Express Edition (Oracle Database XE) is an entry-level, small-footprint database based on the Oracle Database 10g Release 2 code base that's free to develop, deploy, and distribute

A: Oracle ORION is the tool your looking for. It generates Oracle like IO. The are several parameters you can set to generate a specific type of load (random io, sequential io) etc.
orion


text:
Q: Publish Input and Output Json to cloudwatch from Step Function States Is it possible to publish the input and output json to each state in the State diagram of the step function to cloudwatch or something else directly? i.e. without using any lambda or anything?

A: No CloudWatch can only provide state machine metrics. Input and output data traverse from start to end cannot be logged in to CloudWatch. It's only available in state machine execution history. AWS X-Ray might collect that data but I'm not sure about that.


text:
Q: Firestore security rules, allowing access from nodejs API I'm using Firestore as an MVP DB for an API we've got hosted on Heroku. The API doesn't use any authentication outside the OAuth provided by platforms like Slack and Google, and we're also not using any of Firebase's authentication
I'd like to change our security rules away from the insecure
allow read, write: if true; but I'm unsure how to write these rules in my context given most of the docs show security rules using Firebase auth or collection visibility
So, a couple questions:

*

*Is it secure "enough" that I'm using the Firebase admin SDK on the Heroku server to access Firestore, but that my security rules basically allow access to anyone?

*If not, How can I write rules that allow access only to a specific Heroku API endpoint?

*Alternatively, are there better practices I should use to secure the data?

Thanks so much

A: The Admin SDK to access the database with special administrative privileges, and bypasses the security rules. So if you only access the database through the Admin SDK, you can lock the database for access by regular users with:
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

A: For an MVP, I think allow read: if True is not really a problem, depending the data you make available. However, on write, you can easily implement a rule with the incoming data, like that for example :
allow write: if request.resource.data.securityKey === 'custom key shared between firebase and heroku'
A better option would be to use the auth module firebase.auth().signInWithEmailAndPassword(email, password), store an email and password in the env variable of your heroku app and auth from there.


text:
Q: Join two tables with one table has multiple rows matching Trying to figure out if it is possible to create a query where you join tables, table one is smaller than table two, table two has multiple references matching table one entries, the query would output a joining where table one length is preserved but you just add more columns. Not sure if that makes sense so here is a example of what I am after
Table One                                  Table two
+-----------------------------+           +-----------------------------+
| id | english  |  definition |           | id | word_id  |  sentence   |
+-----------------------------+           +-----------------------------+
|1   |    A1    |    blah     |           |1   |    1    |   blahblah1  |
|2   |    B4    |    blah2    |           |2   |    1    |   blahblah2  |
+-----------------------------+           |3   |    1    |   blahblah3  |
                                          |4   |    2    |   blahblah4  |
                                          |5   |    2    |   blahblah5  |
                                          +-----------------------------+

********* Query should return something like *****************
+----------------------------------------------------------------+
| id | english  |  definition | sentence | sentence2 | sentence3 |
+----------------------------------------------------------------+
|1   |    A1    |    blah     | blahblah1|  blahblah2| blahblah3 |
|2   |    B4    |    blah2    | blahblah4|  blahblah5|           |
+----------------------------------------------------------------+

My Current query looks like this and results in:
$query = "SELECT * FROM T1 INNER JOIN T2 ON T1.id = T2.word_id";

Resulting in:
+----------------------------------------+
| id | english  |  definition | sentence |
+----------------------------------------+
|1   |    A1    |    blah     | blahblah1|
|1   |    A1    |    blah     | blahblah2|
|1   |    A1    |    blah     | blahblah3|
|2   |    B4    |    blah2    | blahblah4|
|2   |    B4    |    blah2    | blahblah5|
+----------------------------------------+

I am working with PHP and MySql.
UPDATE!!
Staying with my original query and manipulating the results with PHP getting good performance too. Let me know if you need me to post my code.

A: You might be looking for GROUP_CONCAT()
SELECT T1.id, T1.english,T1.definition,
GROUP_CONCAT(T2.sentence ORDER BY T2.ID SEPARATOR '|')
FROM Table1 T1 INNER JOIN Table2 T2 ON T1.id = T2.word_id
Group by word_id

Sample fiddle

A: The answer is NO. Simply because there's unknown number of columns (say, if you add one more sentence to the top word you could be adding one more column to the result set) and each column is not well defined ( Why blahblah4  should be in column sentence instead of sentence2 ?)
IMO, SQL is used to tell what you want to get, but in this case, SQL is unable to tell exactly what you want.
Even if  this can be done ( I would love to learn ), I believe the complexity offsets any benefit and handling this in PHP is a better option.


text:
Q: Create class with multiple indexed properties I'm trying to create a class with multiple properties that are indexed by the same number I pass into the property. I've tried several configurations of code, my latest failure being this:
'dataTypeClass class module
Private ap() As String
Private dt() As String

Public Property Get apos(index As Long) As Variant
Set apos = ap(index)
End Property

Public Property Get dataType(index As Long) As Variant
Set dataType = dt(index)
End Property

Public Property Let apos(index As Long, apVal As String)
ap(index) = apVal
End Property

Public Property Let dataType(index As Long, dtVal As String)
dt(index) = dtVal
End Property

I get this error code mostly:

Expecting to use below to get "INT" and "" for item 1 in sub below.
Sub classTest()

Dim d As New dataTypeClass
d(1).dataType = "INT"
d(1).apos = ""
Debug.Print d(1).dataType & d(1).apos
End Sub

What several things am I doing wrong?
EDIT:
Taking suggestions below (such as editing my question rather than commenting), I'm setting the variants to strings, and using let instead of set. Since I did indeed get a subscript out of range, I need to initialize the class, but do I need to redim index? How might I do that if the index will have a different maximum each time I run the script?

A: The apos property1 gets a Variant at the specified index; the implementation suggests that the encapsulated ap(index) is an Object, so the return type should probably be Object instead of Variant:
Public Property Get apos(index As Long) As Variant
Set apos = ap(index)
End Property

The setter uses Let assignment, which is hackish, but allowed given the value is Variant - oh wait no, it's a String!
Public Property Let apos(index As Long, apVal As String)
ap(index) = apVal
End Property

You're getting this error because, as the error states, the property definition is inconsistent. If ap(index) is a String, then the getter should look like this:
Public Property Get apos(index As Long) As String
apos = ap(index)
End Property

If ap(index) is an Object, then the setter should look like this:
Public Property Set apos(index As Long, apVal As Object)
Set ap(index) = apVal
End Property

...and the getter like this:
Public Property Get apos(index As Long) As Object
Set apos = ap(index)
End Property

Or like this:
Public Property Get apos(index As Long) As Variant
Set apos = ap(index)
End Property

Public Property Set apos(index As Long, apVal As Variant)
Set ap(index) = apVal
End Property

In other words:

*

*The RHS/value parameter of Property Let/Property Set needs to be the same type as the return type of the same-name Property Get member.

*If the type is an object type, use Property Set for assignments.

*If the type is a value type, use Property Let for assignments.

*Avoid Variant if possible.

*Do not use Set to assign anything other than an object reference.

1All of this is also true for the dataType property.

A: You have a variant for the return type of your Get but your Let additional param is using a string. Perhaps you need  dtVal As Variant? As mentioned in comments and other answer there are additional things to consider; some will be implementation specific.
Quote:

The parameters for Property Get, Property Let, and Property
  Setprocedures for the sameproperty must match exactly, except that the
  Property Let has one extra parameter, whose type must match the return
  type of the corresponding Property Get, and the Property Set has one
  more parameter than the corresponding Property Get, whose type is
  either Variant, Object, a class name, or an object library type
  specified in an object library. This error has the following causes
  and solutions:
The number of parameters for the Property Get procedure isn't one less
  than the number of parameters for the matching Property Let or
  Property Set procedure. Add a parameter to Property Let or Property
  Set or remove a parameter from Property Get, as appropriate.
The parameter types of Property Get must exactly match the
  corresponding parameters of Property Let or Property Set, except for
  the extra Property Set parameter. Modify the parameter declarations in
  the corresponding procedure definitions so they are appropriately
  matched.
The parameter type of the extra parameter of the Property Let must
  match the return type of the corresponding Property Get procedure.
  Modify either the extra parameter declaration in the Property Let or
  the return type of the corresponding Property Get so they are
  appropriately matched.
The parameter type of the extra parameter of the Property Set can
  differ from the return type of the corresponding Property Get, but it
  must be either a Variant, Object, class name, or a validobject library
  type.
Make sure the extra parameter of the Property Set procedure is either
  a Variant, Object, class name, or object library type.
You defined a Property procedure with an Optional or a ParamArray
  parameter. ParamArray and Optional parameters aren't permitted in
  Property procedures. Redefine the procedures without using
  thesekeywords.


text:
Q: What is the expectation of a normally-distributed random variable raised to a (positive, non-integer) power? Let $x$ be a normally-distributed random variable, $x \sim N(\mu,\sigma^2)$. Denote its PDF $\phi(x)$.
Let $g(x)$ be the function $g(x) = x^{\lambda}$, where $\lambda > 1$ is a non-integer positive constant.
What is the value of the expectation $E[g(x)] = \int{g(x)\phi(x)dx} $?
Every resource I search through provides solutions for positive integer values of $\lambda$ by evaluating the MGF of $x$; I have yet to find a clear solution for non-integer values.
Thank you!


text:
Q: How to install urwfonts-8.71.tar.bz2 in Linux? I have downloaded this free set of 80 standard fonts, but I'm not sure how to install it in my Linux box (CentOS 5.4). Any suggestion would be greatly appreciated!
Thanks!!

A: Here's CentOS's font guide.
Basically, you unzip the fonts into /usr/share/fonts/local (creating the folder if necessary), then call fc-cache /usr/share/fonts/local.


text:
Q: Python - Create string from list of list of characters I got stuck in returning a string from a list of list of characters.
[['h', 'i', 'i', 'u', 'i', 'h'],
 ['r', 'm'], ['h', 'g', 'i', 'z', 'g', 'v', 't', 'b'],
 ['x', 'z', 'm', 'm', 'l', 'g'], ['y', 'v'],
 ['x', 'l', 'i', 'i', 'v', 'x', 'g'],
 ['g', 's', 'i', 'l', 'f', 't', 's'],
 ['g', 'z', 'x', 'g', 'r', 'x', 'z', 'o'],
 ['n', 'z', 'm', 'v', 'f', 'e', 'v', 'i', 'h']]

My expected output is:
'hiiuih rm hgizgvtb xzmmlg yv xliivxg gsilfts gzxgrxzo nzmvfevih'

A: Use a list comprehension in combination with join method.
result = ' '.join([''.join(item) for item in my_list])

Output
'hiiuih rm hgizgvtb xzmmlg yv xliivxg gsilfts gzxgrxzo nzmvfevih'

A: Assuming level one is words, level two is letters:
foo = [['h', ...], ...]
" ".join("".join(w) for w in foo)

Gives
'hiiuih rm hgizgvtb xzmmlg yv xliivxg gsilfts gzxgrxzo nzmvfevih'


text:
Q: Battery status always at 100% and a second status in settings with correct level I've just switched from Windows 11 to Ubuntu 22.04.1 LTS and I love it.
I'm learning a lot about Linux and fixed some problems, but there's one I can't find the issue.
I have a Lenovo Ideapad 330-15IKB.
The battery level on the upper status bar is always 100%, but when I look at the power settings, the battery section shows me a first line with fully charged battery and a second line with the real battery level marked "Extra".

I have only one battery on this laptop.
I've discovered that the main battery showed is in fact my UPS battery backup who is plugged via USB for it's management software I had in Windows. If I unplugged it, my laptop battery level shows up correctly.
My question is... how to show the actual laptop battery first and the UPS as an extra?


text:
Q: Mysql Php Email Every Year I have been scratching my head on this one for awhile. I need to send out an email on certain days after someone registers with my site.
Day of registration (Set up)
1 month
3 months
6 months
1 year and every year after
Right now an automatic email goes out the day of registration. That works fine but now I need one after 1 month and so on. The months I think I understand. It is just comparing the date to the registered on date, and then the yearly message I have no idea. I am still learning how to do this so any help would be great thanks!
//get status of email queue
$q_lock = getLockStatus($conexao, 5);

//if email queue is locked, exit the script
if($q_lock)
{
exit();
}
//if email queue is not locked, lock it now and continue
else
{
setLockStatus($conexao, 5, 1);
}

$aryQueue = getMemberemails($conexao);
$date = date("Y-m-d");
$current_year = date("Y");
//echo '<pre>', print_r($aryQueue, true), '</pre>';

foreach($aryQueue as $e)
{
$email_id = $e["id"];
$full_name = $e["full_name"];
$to_name = $e["first_name"];
$email= $e["email"];
$member_id = $e["member_id"];
$registered_on = $e["registered_on"];
$yearly_message = date('Y-m-d', strtotime("$registered_on + 1 year"));
$oneYearOn = date('Y-m-d',strtotime(date("Y-m-d", mktime()) . " + 365
day"));

if( $date == $yearly_message){


text:
Q: How can I apply cuda to custom model in pytorch? The type of inputs is dictionary of tensors. So while training I convert device to cuda to use gpu. And my custom model is like above. Also I assigned cuda to the model.
class EmbeddingLayer(nn.Module):
  def __init__(self):
    super(EmbeddingLayer, self).__init__()

    # other features
    self.other_features_embedding = []
    for feature_name in OTHER_FEATURES:
      vocabulary = CATEGORICAL_FEATURES_WITH_VOCABULARY[feature_name]
      embedding_dims = int(math.sqrt(len(vocabulary)))
      embedding = nn.Embedding(len(vocabulary)+1, embedding_dims)
      self.other_features_embedding.append(embedding)

    # transformer features
    item_vocabulary = CATEGORICAL_FEATURES_WITH_VOCABULARY['item']
    self.item_embedding_dims = int(math.sqrt(len(item_vocabulary)))
    self.item_embedding = nn.Embedding(len(item_vocabulary)+1, self.item_embedding_dims)

  def forward(self, inputs):

    # other features
    encoded_other_features = []
    for i, feature_name in enumerate(OTHER_FEATURES):
      embedding = self.other_features_embedding[i](inputs[feature_name])
      encoded_other_features.append(embedding)

    encoded_other_features = torch.cat(encoded_other_features, -1)

    # transformer features
    encoded_sequence_item = self.item_embedding(inputs['sequence_item'])
    encoded_target_item = self.item_embedding(inputs['target_item'])

    positions = inputs['target_timestamp'].repeat(sequence_length-1, 1).transpose(0, 1) - inputs['sequence_timestamp']
    encoded_positions = positions.repeat(1, self.item_embedding_dims).reshape(-1, self.item_embedding_dims, sequence_length-1).transpose(1,2)

    encoded_sequence_item_with_position = encoded_sequence_item + encoded_positions
    encoded_transformer_features = torch.cat((encoded_sequence_item_with_position, encoded_target_item.reshape(-1, 1, self.item_embedding_dims)), 1)

    return encoded_other_features, encoded_transformer_features

class BST(nn.Module):
  def __init__(self, hidden_units, dropout, num_heads):
    super(BST, self).__init__()

    ...

    self.embedding_layer = EmbeddingLayer()

    ...

  def forward(self, inputs):
    other_features, transformer_features = self.embedding_layer(inputs)

    ...

    return self.output(features)

model = BST([256, 128], 0.3, 1)
model.to(device)

def train(model, optimizer, dataloader):
  model.train()
  for inputs in tqdm(dataloader, total=len(dataloader)):

    for k, v in inputs.items():
      inputs[k] = v.to(device)

    model.zero_grad()
    pred = model(inputs)

    ...

But following error occurs:
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument index in method wrapper__index_select)

I think the error occurs at embedding in EmbeddingLayer. How can I fix this error to use gpu while training?

A: Your list of nn.Module is not registering the embedding layers as sub modules of your layer. In order to properly register a list of modules you should use nn.ModuleList. Therefore, you should add the following right after the loop in your __init__ function:
embeddings = []
for feature_name in OTHER_FEATURES:
    vocabulary = CATEGORICAL_FEATURES_WITH_VOCABULARY[feature_name]
    embedding_dims = int(math.sqrt(len(vocabulary)))
    embedding = nn.Embedding(len(vocabulary)+1, embedding_dims)
    embeddings.append(embedding)

self.other_features_embedding = nn.ModuleList(embeddings)


text:
Q: Vue Component with Webpack I think I may be suffering from brain-fog here. I want to just render a simple Vue Compnent using Webpack. The result from the code and config below just renders a <hello></hello> when compiled.
The error seems to stem from the

Resultant HTML
<!DOCTYPE html>

            <hello></hello>

A: Solution for me was to extract the css using mini-css-extract-plugin. Updated webpack config is:
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    mode: 'development',
    entry: {
        main: './src/index.js'
    },
    output: {
        filename: 'assets/[name].js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/'
    },
    devServer: {
        port:9000,
        index: 'index.htm',
        host: 'hello.local'
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                use: [
                    'vue-loader'
                ]
            },
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            },
            {
                test: /\.pug$/,
                use: [
                    'pug-loader'
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin(),
        new VueLoaderPlugin(),
        new HtmlWebpackPlugin({
            template: './src/index.pug',
            filename: 'index.htm',
            inject: true
        })
    ]
}

Plan was to extract CSS later so unsure why this didn't work with the original config. If anyone can guide me to the reason, that would be great!


text:
Q: EF Core running query's I did not call I have the following two models within my Blazor Server project:
Vergadering:
public class Vergadering
{
    [Key]
    public int Id { get; set; }
    public string Naam { get; set; }
    public DateTime DatumTijd { get; set; }
    public ICollection<Bestuurslid> Aanwezigen { get; set; }
    public string? Notulen { get; set; }
    public ICollection<Vergadering>? HoofdVergadering { get; set; }
    public ICollection<Vergadering>? GekoppeldeVergaderingen { get; set; }
    public ICollection<Bestand>? Bestanden { get; set; }
    public string? UserLastEditId { get; set; }
    public IdentityUser? UserLastEdit { get; set; }
    public DateTime? LastEdit { get; set; }
    public ICollection<VergaderingAgendaItem>? vergaderingAgendaItems { get; set; }
}

VergaderingAgendaItem:
public class VergaderingAgendaItem
{
    public int Id { get; set; }
    public string Omschrijving { get; set; }
    public bool Afgerond { get; set; }
    public int? ParentId { get; set; }
    public VergaderingAgendaItem? Parent { get; set; }
    public int VergaderingId { get; set; }
    public Vergadering Vergadering { get; set; }
    public string? UserAangedragenId { get; set; }
    public IdentityUser? UserAangedragen { get; set; }

}

This results in three tables:
Vergaderingen
VergaderingAgendaItems
VergaderingVergadering

In my repository I have the following update method:
public async Task ChangeAfgerondStatusAsync(VergaderingAgendaItem item)
{
    using (var _db = _factory.CreateDbContext())
    {
        _db.VergaderingAgendaItems.Update(item);
        await _db.SaveChangesAsync();
    }
}

Whenever the Vergadering does not have a GekoppeldeVergadering this update method does not create any problem.
But whenever the Vergadering does have a GekoppeldeVergadering and I update a VergaderingAgendaItem of that Vergadering I get this error:

An error occurred while saving the entity changes. See the inner exception for details.

Looking at the command prompt that opens up while running the project I saw the following query and error.
Queries:

Error:

An exception occurred in the database while saving changes for context type 'AVA_ZICHT.Data.ApplicationDbContext'.
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
Microsoft.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK_VergaderingVergadering'. Cannot insert duplicate key in object 'dbo.VergaderingVergadering'. The duplicate key value is (4, 3).

How is it that EF Core tries to update the GekoppeldeVergadering in VergaderingVergadering table. My method states VergaderingAgendaItem.Update()?

A: When handed a detached entity and told to Update it, EF will consider any associated entities as well. Since those references aren't tracked by the DbContext, the context will see those entities as new items to be inserted. This can result in duplicate key exceptions (as you are seeing) or inserting duplicate data with new PKs if those keys are set up as Identity columns.
One way to get around this issue is to use Automapper configured to just update the columns you expect to change:
public async Task ChangeAfgerondStatusAsync(VergaderingAgendaItem item)
{
    using (var _db = _factory.CreateDbContext())
    {
        var existingItem = _db.VergaderingAgendaItems.Single(x => x.Id == item.Id);
        Mapper.Map(item, existingItem);
        await _db.SaveChangesAsync();
    }
}

Alternatively this can be done manually by copying values from item to existingItem. existingItem is tracked entity so once it's updated, just call SaveChanges. The advantage of this over Update is that the resulting UPDATE SQL statement will only be for any columns that have actually changed, and it won't execute an UPDATE if nothing has actually changed.
This assumes we only want to copy fields from that entity, and none of the child/related entities. If you want to alter the collections/associations then you will need to eager load them and handle these separately. For instance changing the UserLastEdit reference, this is likely something you would want to eager-load so that it can be updated with the current User record.
My general advice is to avoid working with detached entities for concerns like this and instead use POCO view models. The trouble with using detached entities is that these are often incomplete representations of entity state, at worst, something deserialized from view state and cast into an Entity object. View Models can also be scaled down to just the data your client needs and what data is allowed to change. When it gets back to the server there is no confusion about what it is vs. what it pretends to be. Another consideration of applying updates which is important in multi-user systems is detecting stale data. Writing updates like this applies a "last in wins" approach where you should ideally check that the current DB data state concurrency token matches the token/version at the time that this user's original version was read. The attraction of using detached entities is the thought of avoiding a round-trip to the DB when performing an update, but in all honesty you should justify a round trip to ensure that the record is actually valid, the user actually can update that record, and the record hasn't been updated by someone else in the time this user was editing it.
Edit: Automapper Example:
var config = new MapperConfiguration( cfg =>
{
    cfg.CreateMap<VergaderingAgendaItem,VergaderingAgendaItem>()
        .ForMember(x => x.Id, opt => opt.Ignore());
});
var mapper = config.CreateMapper();

mapper.Map(item, existingItem);

Now normally you would either have a centralized MapperConfiguration set up at the start of the application and register the mapper with the IoC container to be injected into the controllers/services that need it, or you can create Mapper Factory classes/functions to construct and provide mappers on demand. The above example code also sets up a mapper that will copy across all data except the Id column. It is a good idea to exclude any properties you never expect to be changed. This can help guard against unexpected updates when using Automapper vs. manually copying values across.


text:
Q: laravel do not return call stack on error For example in my REST Json API: When I call a route with route model binding and pass an invalid id I get:
{
    "message": "No query results for model [App\\Models\\User].",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
    "file": "D:\\allianz\\backend\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Exceptions\\Handler.php",
    "line": 199,
    "trace": [
        { ...

However I would prefer not to show this to the API consumer. (Or just the message).

A: You can always catch the exception in the App\Exceptions\Handler.php
Import the exception into the class using the following:
use \Illuminate\Database\Eloquent\ModelNotFoundException;

and in the render method, add
if ($e instanceof ModelNotFoundException) {
    return response()->json([
        'message' => 'Record not found', //or modify it to display whatever message you want here
    ], 404);
}

A: What is you APP_ENV variable set at?  I believe the call stack won't be returned when it's in production.

A: Although this question was asked in the last century, I like to leave an answer for Laravel 9.7.0.
This answer shows how to globally set how unhandled exceptions should be rendered in http-responses.
I changed the code a bit to return the exception-info without a stack-trace:
<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    $this->renderable(function (Throwable $e, $request) {
        $env = config("app.env");

        $msg = $e->getMessage() . " in file '" . $e->getFile() . "' on line '" . $e->getLine() . "'";

        if ($request->is('api/*')) {
            if (strcmp($env, "debug") == 0) {
                return response()->make($msg.$e->getTraceAsString(), 500);
            } else {
                return response()->json([
                    'message' => $msg
                ], 500);
            }
        }
    });
}

So if I set APP_ENV=debug in the .env-file the stacktrace will be added to the repsonse text-message. It's text because I did not test how the stacktrace would mess with the consumers json interpreter. If APP_ENV != debug, the response is a json object with a message-value containing the message, file and linenumber.


text:
Q: How to checkout latest release tag I'm aware of how to checkout a specific commit or branch using Checkout(&git.checkoutOptions) with plumbing.ReferenceName("<branchName>") or plumbing.Hash("<commit hash>"), but I want to be able to clone a specific release version. Any ideas on how to do this?

A: You will need to set ReferenceName in CloneOptions.
Example cloning v4.1 of git-go:
r, err := git.PlainClone("/tmp/foo", false, &git.CloneOptions{
        URL:      "https://github.com/go-git/go-git",
        ReferenceName: plumbing.ReferenceName("refs/tags/v4.1.0"),
        Progress: os.Stdout,
})


text:
Q: Android reading sqlite database from assets and populating it to listview I've been trying to read my sqlite database from assets and populating it on a listview and every time i get "no such table found",
here is my Database Adapter
DatabaseHelper.Java
public class DatabaseHelper extends SQLiteOpenHelper {

private static String DB_Path="/data/data/com.example.pc.myapp/databases/";
private static String DB_Name= "myDatabase.sqlite";
private final Context mycontext;
private SQLiteDatabase myDatabse;

public DatabaseHelper(Context context) {
    super(context, DB_Name,null,1);
    this.mycontext=context;
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

private boolean chechDatabase(){
    SQLiteDatabase checkDB=null;

    try {
        String myPath=DB_Path+DB_Name;
        checkDB=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READONLY);
    } catch (SQLException e){

    }
    if (checkDB !=null) checkDB.close();
    return checkDB != null ? true : false;
}
private void copyDatabase () throws IOException {
    InputStream myInput=mycontext.getAssets().open(DB_Name);
    String outFileName=DB_Path+DB_Name;
    OutputStream myOutput = new FileOutputStream(outFileName);
    byte[] buffer=new byte[1024];
    int length;

    while ((length=myInput.read(buffer))>0);{
        myOutput.write(buffer,0,length);
    }
    myOutput.flush();
    myInput.close();
    myOutput.close();
}
public void openDatabse() throws SQLException{
    String myPath=DB_Path+DB_Name;
    myDatabse=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READONLY);
}
public void ExeSQLData(String sql) throws SQLException{
    myDatabse.execSQL(sql);
}
public Cursor queryData(String query) throws SQLException{
    return myDatabse.rawQuery(query,null);
}

@Override
public synchronized void close() {
    if (myDatabse != null)
        myDatabse.close();
    super.close();
}
public void checkAndCopyDatabase(){
    boolean dbExist=chechDatabase();
    if (dbExist){
        Log.d("TAG","DataBase Already Exists");
    }else {
        this.getReadableDatabase();
        try {
            copyDatabase();
        }catch (IOException e){
            Log.d("Tag","Error Copying Database");
        }
    }
}

and this is my main Activity
Mainactivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
public String TABLE_NAME="dic";
private DatabaseHelper dbHelper;
ArrayList<Word> arrayList=new ArrayList<Word>();
CustomAdapter customAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Load Database
    dbHelper=new DatabaseHelper(this);
    try {
        dbHelper.checkAndCopyDatabase();
        dbHelper.openDatabse();
    } catch (SQLException e){
    }
    try {
        Cursor cursor = dbHelper.queryData("Select * from "+TABLE_NAME);
        if (cursor !=null){
            if (cursor.moveToFirst()){
                do {
                    Word word = new Word();
                    word.setmWord(cursor.getString(1));
                    word.setmDescription(cursor.getString(2));
                    arrayList.add(word);

                }while (cursor.moveToNext());
            }
        }
    }catch (SQLException e){ }
    customAdapter = new CustomAdapter(this,R.layout.custom_list_view,arrayList);
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(customAdapter);
    customAdapter.notifyDataSetChanged();
    }
}

the logcat
LOGcat
08-17 22:27:20.757 19145-19145/com.example.pc.myapp E/SQLiteLog: (28) failed to open "/data/data/com.example.pc.myapp/databases/myDatabase.sqlite" with flag (131072) and mode_t (0) due to error (2)
08-17 22:27:20.757 19145-19145/com.example.pc.myapp E/SQLiteLog: (14) cannot open file at line 32546 of [9491ba7d73]
08-17 22:27:20.757 19145-19145/com.example.pc.myapp E/SQLiteLog: (14) os_unix.c:32546: (2) open(/data/data/com.example.pc.myapp/databases/myDatabase.sqlite) -
08-17 22:27:20.787 19145-19145/com.example.pc.myapp E/SQLiteDatabase: Failed to open database '/data/data/com.example.pc.myapp/databases/myDatabase.sqlite'.
                                                                      android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 1294): Could not open database
                                                                      #################################################################
                                                                      Error Code : 1294 (SQLITE_CANTOPEN_ENOENT)
                                                                      Caused By : Specified directory or database file does not exist.
                                                                        (unknown error (code 1294): Could not open database)
                                                                      #################################################################
                                                                          at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
                                                                          at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:318)
                                                                          at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:228)
                                                                          at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:512)
                                                                          at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:206)
                                                                          at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:178)
                                                                          at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:908)
                                                                          at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:878)
                                                                          at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:699)
                                                                          at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:674)
                                                                          at com.example.pc.myapp.DatabaseHelper.chechDatabase(DatabaseHelper.java:45)
                                                                          at com.example.pc.myapp.DatabaseHelper.checkAndCopyDatabase(DatabaseHelper.java:84)
                                                                          at com.example.pc.myapp.MainActivity.onCreate(MainActivity.java:25)
                                                                          at android.app.Activity.performCreate(Activity.java:6178)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2648)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769)
                                                                          at android.app.ActivityThread.access$900(ActivityThread.java:177)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:135)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5910)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
08-17 22:27:21.158 19145-19145/com.example.pc.myapp D/Tag: Error Copying Database
08-17 22:27:21.158 19145-19145/com.example.pc.myapp E/SQLiteLog: (1) no such table: dic
08-17 22:27:21.258 19145-19563/com.example.pc.myapp D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: false
08-17 22:27:21.268 19145-19145/com.example.pc.myapp D/PhoneWindow: *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
08-17 22:27:21.268 19145-19145/com.example.pc.myapp D/PhoneWindow: *FMB* isFloatingMenuEnabled return false
08-17 22:27:21.488 19145-19563/com.example.pc.myapp I/OpenGLRenderer: Initialized EGL, version 1.4
08-17 22:27:21.498 19145-19563/com.example.pc.myapp D/OpenGLRenderer: Enabling debug mode 0
08-17 22:27:21.808 19145-19145/com.example.pc.myapp I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3f408cb9 time:154747142
08-17 22:27:29.086 19145-19145/com.example.pc.myapp I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3f408cb9 time:154754420
08-17 22:28:58.363 19145-19145/com.example.pc.myapp D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN

A: The method you access to database is not suitable I use following code
private void importDatabaseFromAssets() {
        try {
            InputStream myInput = getAssets().open(DatabaseManager.DATABASE_NAME);
            String DB_PATH = "/data/data/" + getPackageName() + "/databases/";
            String outFileName = DB_PATH + DatabaseManager.DATABASE_NAME;
            OutputStream myOutput = new FileOutputStream(outFileName);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            // Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

You can check that database exist or not with:
private boolean isDataBaseExist() {
    String DB_PATH = "/data/data/" + getPackageName() + "/databases/";
    File dbFile = new File(DB_PATH + DatabaseManager.DATABASE_NAME);
    return dbFile.exists();
}


text:
Q: Did I misunderstand "not constructive"? Before I post this question I've read

*

*How is this not constructive? It is duplicate, but very constructive!

*Why was this question closed as not constructive?
I want to get an answer of the truth with my question
Why doesn't Array class expose its indexer directly? [closed]
for design my class in the correct way, but the question get closed by the reason of not constructive.
By the declaration of not constructive:
As it currently stands, this question is not a good fit for our Q&A format.

*

*According to Bart's answer before:
We need a good single question related to a practical problem you face ... I want you to ask me a single, self-contained question.
Thus, should I change the question to
What should my ToArray method return?
Would that be better?

We expect answers to be supported by
facts - Does it closed because of there are no answer supported by facts with my question?
references - I can't figure out the references myself, but not implying nobody does. If I can always done it myself, then I would not ask.
or specific expertise - Does it closed because of the question can be answered without specific expertise?
but this question will likely solicit
debate - I'm not expecting that.
arguments - What for?
polling - Opinion poll? No, I expect the truth for the why.
or extended discussion - Then don't extended it, just tell me why.

A: Yes, to a small extent you have misunderstood. I saw this appear in the re-open queue and spent quite a while working out why it was closed before voting for it to remain that way.
The reason for the closure is explained pretty well in Alexei Levenkov's upvoted comment (my emphasis):

KenKin I vote to close and removing my guess answer why it was done
  that way. Unless Eric Lippert decides that your question is insanely
  interesting you have more or less no chance to dig inner reasons of
  "why". My guess is "no explicit demand for feature and works", but it
  is just that - guess.

I don't know that I can say it better than that. Unless the designer of the language passes by and decides to answer your question any answer will be a guess, and therefore not very useful for the future. He might, he's a Stack Overflow user but it doesn't seem likely. If he'd like to answer it he can always flag your question for moderator attention to get it reopened.
To go over the points in the close reason; as the question is not answerable by the wider community they cannot supply facts, references or specific expertise. They will instead have to rely on guesswork and discussion.

A: No, you didn't misunderstand "not constructive". Your problem is that a large part of the Stack Overflow community does not understand the topic of your question. This is fairly common with language design questions.
Programming language design is a science, albeit a poorly-understood one. There are reasons to make this or that choice, which can have to do with nice theoretical properties, ease of implementation, performance, etc. To complicate matters, language design is also a historical process, so sometimes the reason is "we didn't understand the implications at the time" or "the author of the spec made a typo". Both kinds of answers call on facts and specific expertise. The former kind is considerably more interesting than the latter, but usually if the asker had known he wouldn't have needed to ask.
Programming language design is on-topic on Stack Overflow because it has a direct impact on programming. It is also on-topic on Computer Science since programming language design is a branch of CS. Unlike the SO community, the CS.SE community understands CS, so I think your question would get a warm reception. However, the CS.SE community is vastly smaller than the SO community. In practical terms, you are far more likely to reach someone who knows the answer on SO than on CS.SE.
(As an advocate and moderator of CS.SE, I hope this will change. Hey, y'all programming language designers, come and join us on Computer Science!)


text:
Q: TAP::Harness::JUnit does not flush output to STDOUT I am running a test script using the
prove utility
and
TAP::Harness::JUnit.
The output is getting buffered and not flushed immediately as compared to running with perl.
prove -v --timer --harness=TAP::Harness::JUnit <script name>

The same works fine when run locally on the machine itself. Is there any option available in prove or TAP::Harness::JUnit to flush the output on STDOUT as well as capture in an XML file


text:
Q: Good resources for building web-app in Tapestry I'm currently researching into Tapestry for my company and trying to decide if I think we can port our pre-existing proprietary web applications to something better. Currently we are running Tomcat and using JSP for our front end backed by our own framework that eventually uses JDBC to connect to an Oracle database.
I've gone through the Tapestry tutorial, which was really neat and got me interested, but now I'm faced with what seems to be a common issue of documentation. There are a lot of things I'd need to be sure that I could accomplish with Tapestry before I'd be ready to commit fully to it. Does anyone have any good resources, be it a book or web article or anything else, that go into more detail beyond what the Tapestry tutorial explains?
I am also considering integrating with Hibernate, and have read a little bit about Spring too. I'm still having a hard time understanding how Spring would be more useful than cumbersome in tandem with Tapestry,as they seem to have a lot of overlapping features. An example I read seemed to use Spring to interface with Hibernate, and then Tapestry to Spring, but I was under the impression Tapestry integrates to the same degree with Hibernate. The resource I'm speaking of is
http://wiki.apache.org/tapestry/Tapstry5First_project_with_Tapestry5,_Spring_and_Hibernate . I was interested because I hadn't found information anywhere else on how to maintain user levels and sessions through a Tapestry application before, but wasn't exactly impressed by the need to use Spring in the example.

A: The sources I use are:

*

*the documentation itself particularly the component reference

*Howard's blog

*the wiki, particularly the howtos

*the mailing list archives (the convention is to put 'T5' in the subject for Tapestry 5 issues)

*the Jumpstart project pages

*the Chenille Kit demo for additional components

Personally, I've found that Tapestry 5 does everything a basic web app needs without Spring. There might be some specific Spring utilities you would want to pull in, but the Tapestry/Hibernate integration is very solid and easy to use. Still, the wiki has some examples of integrating the two.
I'm not sure of what you're referring to regarding sessions. It's extremely simple with T5.  See this.

A: Don't forget to check the new, improved documentation at http://tapestry.apache.org.


text:
Q: Powershell for users password date I want to write a basic script for checking for accounts with a password about to expire.
Here is my script:
$maxPasswordAges = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days

$Today = Get-Date

Get-AdUser -Searchbase "MyOU" -filter * - Properties PasswordExpired, AccountExpirationDate, PasswordLastset | Sort-Object  PasswordlastSet
 Select-Object Name, PasswordExpired, AccountExpirationDate, PasswordlastSet

Everything seems fine in the above code, it reads many account types in my OU.
How can I add an additional column to list the "Expiry date" (in how many days that the password will expire)?
For now, I need to do an additional job and run this additional code:
where-object {$_.PasswordlastSet} | foreach {($_.Passwordlastset.AddDays($maxpasswordage) - $Today).Days}

If I combine the two scripts together, it only show me only "How many days to Expire".

A: You have check the property "msDS-UserPasswordExpiryTimeComputed".
You can calculate that like this:
(((Get-ADUser –Identity 'TestUser' -Properties "msDS-UserPasswordExpiryTimeComputed")."msDS-UserPasswordExpiryTimeComputed")-(Get-Date).Days)

Note: Difference of present date and computed date will give you what you are looking for.

A: You can combine your two scripts by using a calculated property in the Select-Object statement:
$maxPasswordAges = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days
$Today = Get-Date

Get-AdUser -Searchbase "MyOU" -filter * - Properties PasswordExpired, AccountExpirationDate, PasswordLastset |
    Sort-Object  PasswordlastSet |
    Select-Object Name, PasswordExpired, AccountExpirationDate, PasswordlastSet, @{Name="DaysToExpire";Expression={($_.Passwordlastset.AddDays($maxpasswordage) - $Today).Days}}


text:
Q: tikz: A mixture of line segments and wavy lines I would like to be able to draw, using TikZ, a picture as the one below, which consists of:

*

*two vertical line segments

*a wavy line going from the top point of the line segment on the left to the top point of the line segment on the right;

*a wavy line going from the bottom point of the line segment on the left to the bottom point of the line segment on the right.

Furthermore, I want to be able to fill this region with some color.

I did it using this code:
\begin{tikzpicture}
  \filldraw[fill=cyan,domain=0:2,samples=100]
  plot(\x,{(\x)^3-3*(\x)^2+2*\x})
  --plot({2-\x},{(2-\x)/(1+(2-\x)^2)-2})--cycle;
\end{tikzpicture}

What bothers me was the need of finding two concrete curves in order to obtain the wavy lines. I think that I should be able to get them using something similar to the rounded corners option of the draw command. Is it possible?

A: Do it with Bezier curves:

\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
    \begin{tikzpicture}
        \clip (0,.5) rectangle (2,-2);
        \draw[fill=cyan] (0,0) .. controls ++(1,1.5) and ++(-1,-1.5).. (2,0) -- (2,-1.5) .. controls ++(-1,.2) and ++(.5,.75) .. (0,-2) --cycle;
    \end{tikzpicture}
\end{document}

EDIT: a bit of explanation
While you can look for what Bezier curves are (there are an incredible amount of example on TeX-SE and elsewhere, and of course, you can find them in the manual), here are some explanations:
Pierre Bézier was a French engineer who worked for Renault cars and created these parametrical curves.
In TikZ, you can draw cubic Bezier curves, which allow you to use a start point, an end point, and two other points that conduct the curve. There's some magical maths in here ;) but let's see what it gives graphically:

\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
    \begin{tikzpicture}[lin/.style={red,line width=0.1pt},dot/.style={circle,inner sep=0.5pt,fill=red}]
        \draw[fill=cyan!50]
            (0,0) .. controls ++(1,1.5)
            and ++(-1,-1.5).. (2,0) --

            (2,-1.5) .. controls ++(-1,.2)
            and ++(.5,.75) .. (0,-2)

            --cycle;

        \draw[lin] (0,0) --++ (1,1.5) node[dot]{};
        \draw[lin] (2,0) --++ (-1,-1.5) node[dot]{};
        \draw[lin] (2,-1.5) --++ (-1,.2) node[dot]{};
        \draw[lin] (0,-2) --++ (.5,.75) node[dot]{};

    \end{tikzpicture}
\end{document}

Here in the code, I added what you need to understand (a bit) how it works. This is the same that you do when using softwares like Illustrator (SVG files).

A: I find it easier to do a smooth plot with a couple of coordinates instead of finding control points. -also no need to clip or adjust bounding box.
\documentclass[tikz, border=1mm]{standalone}
\begin{document}
\begin{tikzpicture}
 \draw[fill=cyan] plot [smooth, tension=1] coordinates {(0,0) (0.6,0.4) (1.4,-0.4) (2,0)} -- plot [smooth, tension=1] coordinates {(2,-1.5) (0.8,-1.4) (0,-2)} -- cycle;
\end{tikzpicture}
\end{document}


text:
Q: Replot matlab contour plots using gnuplot He guys!
I am (slowly) moving away from matlab towards the OS realm and I have recently discovered gnuplot which creates really nice plots so far.
Now I want to replot some graphs I made with matlab earlier this year (contour plots), but I am a bit struggling with the data format for gnuplot.
gnuplot expects the data to be in
x0 y0 f(x0, y0)

format, whereas for my purpose I created all data files with
f(x0,y0), f(x0,y1), f(x0, y2)....
f(x1, y0), ....
..
.

format (x and y vectors are always the same so I didnt lose any information). Can I avoid reformatting all my datafiles (which are quite large and many) and still use gnuplot to use the existing files in a 'matlab-like' manner, i.e. contour(z) where z is the data mentioned above?
Thanks for all the support here!
Cheers,
Chris

A: Sounds like you are looking for splot '' matrix, from help splot matrix:
Example commands for plotting uniform matrix data:
     splot 'file' matrix using 1:2:3          # ascii input
     splot 'file' binary general using 1:2:3  # binary input

In a uniform grid matrix the z-values are read in a row at a time, i. e.,
    z11 z12 z13 z14 ...
    z21 z22 z23 z24 ...
    z31 z32 z33 z34 ...
and so forth.


text:
Q: PHP payment gateway integration using CCAvenue I want to pass the value for select payment mode and card type.
My code is :
<form method="post" action="http://www.ccavenue.com/shopzone/cc_details.jsp" name="frmTransaction">
     <input type="hidden" name="Merchant_Id" value="<?php echo $Merchant_Id;?>">
     <input type="hidden" name="Amount" value="<?php echo $Amount;?>">
     <input type="hidden" name="Order_Id" value="<?php echo  $Order_Id;?>">
      <input type="hidden" name="Redirect_Url" value="<?php echo $Redirect_Url;?>">
       <input type="hidden" name="Checksum" value="<?php echo $Checksum; ?>">

<input type="hidden" name="Merchant_Param" value="<?php echo $Order_Id; ?>">
        <input type="hidden" name="pay_type" value="Debit Card" /> //credit card, netbanking
        <input type="hidden" name="nb_bid" value="<?php echo $bank_name;?>" /> //VISA, mastercard

Here, How to pass pay_type and bank type and preselect the value in CCAvenue gateway. I cannot get any resource for this. Thanks in advace.

A: You want to use cURL. Also, it seems that CC Avenue provides its members with sample PHP code to interact with their web services. I found a manual here that shows where to get sample code from their website on page 12. Using cURL you'll be able to handle the payment before sending it out (adding database records, etc.) and you can obfuscate sensitive data such as your merchant ID.
You'll also probably need to write a second script to handle the response if you're redirecting the user outside of your own site to make the payment (which you might be since you're passing Redirect_Url). All this second script will do is check incoming GET/POST fields that they send you (such as an error code or a confirmation number for the user) and use that to add more info to your database.

A: I followed the below steps to integrate ccavenue in PHP

*

*Login to ccavenue dashboard.

*On the top menu bar navigate to Settings > Api keys. There you can find
merchant_id ,access_code,Working key

*Navigate to Resources > Web Integration Kit

*Under this screen there is an option to select Testing and Production Environment where you can find the testing and production URL.

*

*Testing URL is not enabled by default you need to ask the support to enable it.

*On the same screen there is Download Integration Kits . Click on this and find the Download PHP kit and download the code.

*Use the downloaded kit according to your requirments.Also you can find the required parameters on Integration Methods menu as i used the iframe method.
Hope this will help in integrating the payment gateway


text:
Q: Confirm the file type (.jpg, .png) I have to make sure a given file (.jpg, etc.) is in fact an image
besides just checking for extension, what would be some ways to actually confirm that it is in fact an image? or rather is this possible to do so?
does image file have certain characteristics that are identifiable from the rest of the file types?


text:
Q: Unexpected Token JSON.parse I am trying to parse this text coming from server
var s = "{\"server\":DSL01,\"item\":101,\"data\":[[1357849366000,null],[1357849485000,null]}";
JSON.parse(s);

In the console I get following error,
Unexpected token D
I need to convert this into a json object.

A: Because DSL01 should be a string, and therefore wrapped in ""
"{\"server\":\"DSL01\",\"

Also, you lack a ] on the last part, for closing data array.
I suggest you programmatically create your JSON rather than hand-crafting it. That way, you don't make such errors.


text:
Q: Parsing Xml with A tag that contains multiple attributes [Java,DOM] I use DOM parser to mine the data.Problem is that i cannot manage to get the "url=" "length" and "type" tag that is  inside the "enclosure" tag
<item>
      <title>blah blah</title>
      <description>blah blah</description>
      <enclosure url="THEURL" length="LENGTH" type="TYPE" />
</item>

Here's the code that i use : Can anyone point me to the right direction?
for (int t = 0; t < nList.getLength(); t++) {
                Node nNode = nList.item(t);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;

                    System.out.println("title : "
                            + getTagValue("title", eElement));
                    System.out.println("description : "
                            + getTagValue("description", eElement));

                    for (int t2 = 0; t2 < nList2.getLength(); t2++) {
                    Node nNode2 = nList2.item(t2);
                    Element eElement2 = (Element) nNode2;
                    System.out.println("url: "
                            + getTagValue("url", eElement2));
                    }
                }
        }

private static String getTagValue(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
            .getChildNodes();
    Node nValue = (Node) nlList.item(0);

    return nValue.getNodeValue();
}

A: Look up the Element.getAttributes() method to retrieve all the attributes as an array. The Element.getAttributeNode(String name) will give you a specific attribute.


text:
Q: How to show large amount of data in page wise using html? How to show large amount of data in page wise using HTML and how to restrict the page data.
ex:suppose if we save the page using browser the data should not be saved by the users.

A: 1) To show parts of HTML data divided over a few pages, you'll probably want to have the data in a database and then retrieve, format it and the deliver to your user.
2) You can't restrict the users from saving the data on your page when using HTML. The rationale is that what the user sees must definitely be downloaded from your site. That being said, when he saves the page, he'll definitely be able to save all the text and HTML. If your data is really that important and needs to be protected, consider using other technologies, such as Adobe Flash or even Java Applets.
Hope it helps. Cheers!

A: Not sure I understood the question, but if you want to show something on the page that user cannot easily download or copy you can use Flash. There is no way to do it with HTML.

A: You can use hyperlinks to divide the page data in multiple pages or needs to use some server side scripting like PHP/ASP.
  You cannot restrict user to save the html output however you can use java applets or flash to do that.


text:
Q: Can I Join 3 table using Natural Join? The image down below shows a small database,

I got a question

Give a relational algebra expression to find the name of the judge who
  presides over the trial for defendant known as "Mike" starting on
  1.12.2012.

And the answer given is

But I think it should Join JUDGE table as well something like this :
Please leave some comment if I' wrong about this

A: Nope, you don't need to join the JUDGE table to get the judge's name.
Notice how Jname is the primary key of JUDGEs, that is to say, a judge is uniquely identified by her name; and the TRIAL table will actually contain Jname denoting which judge presided over a given trial:
Judge | Defendant | Number | Sdate
Dredd |  1        |   1    | 1.12.2012
Dredd |  2        |   2    | 2.12.2012
Rico  |  1        |   3    | 1.12.2012

You can see how selecting tuples yields us the judge's name without joining anything in. (In case you're wondering, this is a very bad design that you should never employ in the real world.)
In contrast, we do have to join DEFENDANT with TRIAL: a DEFENDANT's primary key is his ID, so only that ID appears in the TRIAL table, so if we need to select a defendant by name, we have to employ a join.
As for your question title: yes, you can of course join more than three tables. If you find it hard to imagine, recall that R ⨝ S ⨝ T = (R ⨝ S) ⨝ T. Note that natural join is nicely commutative and associative as well.


text:
Q: Finding a generator of an ideal in an algebraic function field I have an algebraic function field $\mathbb{Q}(x,y)$, where $y$ satisfies
$$ (y^2-1)^2 = x^2(1+x^2), $$
and I need to find a rational function that has a first order root at $x=0,y=1$ a first order pole at $x=0,y=-1$, and no other roots or poles.
Is this possible? How do I go about finding such a function or proving that it cannot exist? Is it an issue that $y+1$ has a branch point of order $\frac12$ at $z=\pm i$? I need to automate this process, so is there any standard algorithm for this that I need to look at?
This might be easy (I don't know), but I asked a related question on MSE and got no responses at all, so I want to ask here this time.


text:
Q: Use OpenCV library in CodeBlocks I am using Codeblocks 16.01 with OpenCV 3.2.0-vc14 which is installed to C:\opencv
The compile and link search directory is set in CodeBlocks already.
I wrote an openCV example, and there's a conflict as following:
-------------- Build: Debug in try_opencv (compiler: openCL)---------------

mingw32-g++.exe -L"C:\Program Files (x86)\Intel\OpenCL_SDK\6.3\lib\x86" -LC:\opencv\build\x64\vc14\lib -LC:\opencv\build\x64\vc14\bin -o bin\Debug\try_opencv.exe obj\Debug\main.o  -lOpenCL  C:\opencv\build\x64\vc14\lib\opencv_world320.lib C:\opencv\build\x64\vc14\lib\opencv_world320d.lib
obj\Debug\main.o: In function `main':
D:/TheOpenCLProgrammingBook/image_process_test/try_opencv/main.cpp:9: undefined reference to `cv::imread(cv::String const&, int)'
D:/TheOpenCLProgrammingBook/image_process_test/try_opencv/main.cpp:10: undefined reference to `cv::namedWindow(cv::String const&, int)'
D:/TheOpenCLProgrammingBook/image_process_test/try_opencv/main.cpp:11: undefined reference to `cv::imshow(cv::String const&, cv::_InputArray const&)'
D:/TheOpenCLProgrammingBook/image_process_test/try_opencv/main.cpp:12: undefined reference to `cv::waitKey(int)'
obj\Debug\main.o: In function `ZN2cv6StringC1EPKc':
C:/opencv/build/include/opencv2/core/cvstd.hpp:622: undefined reference to `cv::String::allocate(unsigned int)'
obj\Debug\main.o: In function `ZN2cv6StringD1Ev':
C:/opencv/build/include/opencv2/core/cvstd.hpp:664: undefined reference to `cv::String::deallocate()'
obj\Debug\main.o: In function `ZN2cv3MatD1Ev':
C:/opencv/build/include/opencv2/core/mat.inl.hpp:592: undefined reference to `cv::fastFree(void*)'
obj\Debug\main.o: In function `ZN2cv3MataSERKS0_':
C:/opencv/build/include/opencv2/core/mat.inl.hpp:613: undefined reference to `cv::Mat::copySize(cv::Mat const&)'
obj\Debug\main.o: In function `ZN2cv3Mat7releaseEv':
C:/opencv/build/include/opencv2/core/mat.inl.hpp:704: undefined reference to `cv::Mat::deallocate()'
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
10 error(s), 0 warning(s) (0 minute(s), 0 second(s))

It's so confused. Could someone help me out?

A: You are attempting to link libraries, e.g.
C:\opencv\build\x64\vc14\lib\opencv_world320.lib

that have been built with the MS Visual Studio 2014 C++ compiler in a program
that you are building with a different C++ compiler, namely mingw32-g++.
That won't work. Libraries built by one C++ compiler are in general
binary incompatible with programs or libraries built with a different
one and in particular, code built with an MS C++ compiler is binary
incompatible with code built by a GCC compiler (which you are using).
In addition, it seems that you are building a 32-bit program
with mingw32-g++ - since the 32-bit TDM GCC compiler is the bundled
default compiler in Code::Blocks 16.01 - and are attempting to link
64-bit libraries with it. Even if the libraries were not made by
an incompatible compiler, you cannot link 64-bit code with 32-bit
code.
All the libraries that you link in your 32[64]-bit program must
have been built with the same compiler or at least a binary ABI compatible
compiler, and they must also be 32[64]-bit.
Start again and build OpenCV from source, for targeting mingw, 32-bit,
using your mingw32 compiler. Get the windows source in the zip archive Source code
from the GitHub OpenCV repo.
It seems as if you may already have built from source. If so, then you
built the libraries for 64-bit VC++14, not mingw32, and those libraries
are useless.
To build the libraries again and configure an OpenCV project in Code::Blocks,
follow this tutorial,
carefully.


text:
Q: Multi-columns Tables how can I remove the light gray color in the first column below t. Tq.
\begin{table}[h!]
{\textbf{\caption {Numerical results for $y_{1}(t)$, $y_{2}(t)$ (light gray color) in Example \ref{example 1.2}}}}
 \begin{center}
\label{table61} \addtocontents{lot}{\protect\addvspace{.5cm}}
\begin{footnotesize}
\vspace{0.5cm} \scriptsize
\begin{tabular}{cccccc}
&      & \multicolumn{4}{c}{CWFD} \\
\cline{3-6} \\
t&ChC\;\cite{} &$M=10, k=1$&$M=7, k=2$&$M=10, k=2$&$M=12, k=2$\\\hline
0.2 &0.389$\times10^{-9}$&3.766$\times10^{-10}$&2.366$\times10^{-9}$&2.030$\times10^{-12}$&3.228$\times10^{-15}$\\
\rowcolor{lightgray}    &0.623$\times10^{-6}$&1.005$\times10^{-8}$&1.293$\times10^{-8}$&4.668$\times10^{-11}$&3.822$\times10^{-14}$\\\hline
0.4 &0.535$\times10^{-9}$&2.948$\times10^{-9}$&2.787$\times10^{-9}$&9.351$\times10^{-14}$&4.062$\times10^{-15}$\\
\rowcolor{lightgray}& 0.408$\times10^{-6}$&5.823$\times10^{-8}$&1.425$\times10^{-9}$&4.220$\times10^{-12}$&2.814$\times10^{-14}$\\\hline
0.6 &0.143$\times10^{-7}$&1.801$\times10^{-9}$&4.003$\times10^{-9}$&7.782$\times10^{-12}$&2.632$\times10^{-14}$\\
\rowcolor{lightgray}     & 0.362$\times10^{-6}$&3.758$\times10^{-8}$&6.360$\times10^{-8}$&5.791$\times10^{-11}$&7.850$\times10^{-13}$\\\hline
0.8 &0.501$\times10^{-7}$&1.198$\times10^{-11}$&1.296$\times10^{-8}$&1.868$\times10^{-11}$&4.453$\times10^{-14}$\\
\rowcolor{lightgray}     & 0.475$\times10^{-5}$&6.207$\times10^{-10}$&1.462$\times10^{-7}$&1.226$\times10^{-10}$&1.649$\times10^{-12}$\\\hline
1.0 &0.332$\times10^{-6}$&1.152$\times10^{-10}$&1.730$\times10^{-8}$&2.728$\times10^{-11}$&2.181$\times10^{-14}$\\
 \rowcolor{lightgray}    &0.982$\times10^{-5}$&9.882$\times10^{-10}$&1.985$\times10^{-7}$&1.696$\times10^{-10}$&2.261$\times10^{-12}$
\end{tabular}
\end{footnotesize}
\end{center}
\end{table}

A: See, if you like to have something similar to the following:

In resetting of your table I exploit some packages which make it easy and gives better (more beautiful) results:

*

*for caption: caption package with option font=\bf

*for columns type I use S from package siunitx, which simplify typing of cel content from &0.389$\times10^{-9}$ to 0.389e-9
Beside this the mismatch with table font size I replace with simple \footnotesize (this is easy change to desired size), replace \begin{center} ... \end{center} with \centering, which not add spurious vertical space. Also is considered suggestion in above comments how to remove gray colors in the first column with \cellcolor{white}.
According to my taste I also remove horizontal lines in table, but if you like to have, you can return it :-). With all thee the MWE with your table is:
\documentclass{article}
\usepackage[font=bf]{caption}
\usepackage[table]{xcolor}
\usepackage{siunitx}

\begin{document}
\begin{table}[h!]
\caption {Numerical results for $y_{1}(t)$, $y_{2}(t)$ (light gray color) in Example \ref{example 1.2}}
    \centering
\label{table61}
%\addtocontents{lot}{\protect\addvspac.5cm}}
%\begin{footnotesize}
%\vspac0.5cm}
%    \scriptsize
    \footnotesize
\renewcommand\arraystretch{1.2}
\begin{tabular}{     S[table-format=1.1]
                *{5}{S[table-number-alignment = center,
                       table-format = 1.3,
                       table-figures-exponent = 2]}
                }%ccccc}
 &      & \multicolumn{4}{c}{CWFD} \\
    \cline{3-6}
t   &   ChC \cite{}
                & {$M=10, k=1$}
                           & {$M=7, k=2$}
                                      & {$M=10, k=2$}
                                                  & {$M=12, k=2$}   \\
    \hline
0.2 & 0.389e-9 & 3.766e-10 & 2.366e-9 & 2.030e-12 & 3.228e-15       \\
    \rowcolor{lightgray}
\cellcolor{white}
    & 0.623e-6 & 1.005e-8  & 1.293e-8 & 4.668e-11 & 3.822e-14       \\
0.4 & 0.535e-9 & 2.948e-9  & 2.787e-9 & 9.351e-14 & 4.062e-15       \\
    \rowcolor{lightgray}
\cellcolor{white}
    & 0.408e-6 & 5.823e-8  & 1.425e-9 & 4.220e-12 & 2.814e-14       \\
0.6 &0.143e-7 & 1.801e-9   & 4.003e-9 & 7.782e-12 & 2.632e-14       \\
    \rowcolor{lightgray}
\cellcolor{white}
    & 0.362e-6 & 3.758e-8  & 6.360e-8 & 5.791e-11 & 7.850e-13       \\
0.8 & 0.501e-7 & 1.198e-11 & 1.296e-8 & 1.868e-11 & 4.453e-14       \\
    \rowcolor{lightgray}
\cellcolor{white}
    & 0.475e-5 & 6.207e-10 & 1.462e-7 & 1.226e-10 & 1.649e-12   \\
\cellcolor{white}
1.0 & 0.332e-6 & 1.152e-10 & 1.730e-8 & 2.728e-11 & 2.181e-14   \\
    \rowcolor{lightgray}
\cellcolor{white}
    & 0.982e-5 & 9.882e-10 & 1.985e-7 & 1.696e-10 & 2.261e-12   \\
    \hline
\end{tabular}
%\end{footnotesize}
%\end{center}
\end{table}
    \end{document}

A: I would recommend that you not highlight alternating rows in gray. Instead, simply insert a bit of whitespace after every second row, and provide a short legend to inform readers what the first and second row of each pair of rows shows. Incidentally, you needn't use \footnotesize or even \scriptsize -- the tabular material fits if you use the normal font size. Just use a tabular* environment to assure that the table fits inside the text block.
As @Zarko does in his answer, I would also recommend that you use some of the tools of the siunitx package to simplify and structure the inputs of the tabular material.

\documentclass{article}
\usepackage{booktabs,siunitx,caption}
\captionsetup{font=bf,skip=0.75\baselineskip}
\begin{document}
\begin{table}[h!]
\caption{Numerical results for $y_{1}(t)$ and $y_{2}(t)$ in Example XYZ}
\label{table61}
\setlength\tabcolsep{0pt}
%%\small

Results for $y_{1}(t)$ ($y_{2}(t)$) are shown in upper (lower) row of each pair of rows.

\bigskip
\sisetup{tight-spacing = true, table-format = 1.3, table-figures-exponent = 2}
\begin{tabular*}{\textwidth}{ c @{\extracolsep{\fill}} *{5}{S} }
$t$ & {ChC} & \multicolumn{4}{c}{CWFD} \\
\cmidrule{3-6}
&& {$M=10$, $k=1$} & {$M=7$, $k=2$} & {$M=10$, $k=2$} & {$M=12$, $k=2$}\\
\midrule
0.2 &0.389E-9&3.766E-10&2.366E-9&2.030E-12&3.228E-15\\
    &0.623E-6&1.005E-8&1.293E-8&4.668E-11&3.822E-14\\
\addlinespace
0.4 &0.535E-9&2.948E-9&2.787E-9&9.351E-14&4.062E-15\\
    &0.408E-6&5.823E-8&1.425E-9&4.220E-12&2.814E-14\\
\addlinespace
0.6 &0.143E-7&1.801E-9&4.003E-9&7.782E-12&2.632E-14\\
    &0.362E-6&3.758E-8&6.360E-8&5.791E-11&7.850E-13\\
\addlinespace
0.8 &0.501E-7&1.198E-11&1.296E-8&1.868E-11&4.453E-14\\
    &0.475E-5&6.207E-10&1.462E-7&1.226E-10&1.649E-12\\
\addlinespace
1.0 &0.332E-6&1.152E-10&1.730E-8&2.728E-11&2.181E-14\\
    &0.982E-5&9.882E-10&1.985E-7&1.696E-10&2.261E-12\\
\bottomrule
\end{tabular*}
\end{table}
\end{document}


text:
Q: Changing color of text on click HTML I'm currently learning HTML. I have to do an exercice where a text must change back and forth from red to green.
The code I have is below but doesn't seem to work. Any help would be appreciated.
.red { color : #FF0000 }
.green {color : #00FF00; }

This is  special  text.

Click to change the colour of text

A: Don't set any value. Check directly txt class.
function f(){
  var txt = document.getElementById("txt");

  if (txt.className == 'green') {
   txt.className = "red";
  }
  else {
    txt.className = "green";
  }
}

https://jsfiddle.net/fNPvf/33526/

A: It's because your value is always re-set to 1.
I suggest using data attribute to set current state of your element.

function f() {
  var el = document.getElementById('txt');

  if (el.dataset.val == 1) {
    el.className = "green";
    el.dataset.val = 0;
  } else if (el.dataset.val == 0) {
    el.className = "red"
    el.dataset.val = 1;
  }
}
.red {
  color: #FF0000
}
.green {
  color: #00FF00;
}

This is  special   text.

Click to change the colour of text

jQuery

function f() {
  $('#txt').toggleClass('red green');
}
.red {
  color: #ff0000;
}
.green {
  color: #00ff00;
}

This is  special   text.

Click to change the colour of text

A: CHANGES

*

*Used addEventListener() instead of attribute event handler. Now presentation is completely separated from code.

*Hinged the color states upon the method classList() since everything is centered around classes. More styles can extend the function's functionality easily.

*Used event delegation by adding the event handling on the parent element (#content) and then singling out the origin of the event trigger (e.target is the element clicked) Event delegation will save us tons of time, work, and memory, instead of writing an event handler on each element, you write only one.

var content = document.getElementById('content');

content.addEventListener('click', f);

function f(e) {
  var tgt = e.target;
  if (tgt.classList.contains('red')) {
    tgt.classList.remove('red');
    tgt.classList.add('green');
  } else {
    tgt.classList.add('red');
    tgt.classList.remove('green');
  }
}
p {
  cursor: pointer;
}
.red {
  color: #FF0000
}
.green {
  color: #00FF00;
}

This is  special  text.

Click to change the colour of text

A: the problem with your code is that you run your code in the wrong order, your basic algorithm is this:
onclick -> f() start ->  set value to 1 -> check if value is 1 (true){set color to green}    (false) {set color to red}
then if the user clicks again, that same algorithm will run again.
this is what you should do:

    var value = true;
    function f() {
        var txt = document.getElementById("txt");
        if(value) {
            document.getElementById("txt").className = "green";
            value = false;
        } else {
            document.getElementById("txt").className = "red";
          value = true;
        }
    }
.red { color : #FF0000 }
.green {color : #00FF00; }

This is  special  text.

Click to change the colour of text

this way, you set value as true (1 is basically true, and 0 false), then wait for the user to click, set the text to green, changing the value to false, then if the user clicks again, you won't reset value, instead, it will still be false and the text will be set to red and set value back to true.


text:
Q: Apache Beam : is it possible to comsume messages of RabbitMQ with exchange and routing key I defined a pipeline in Apache Beam to consume messages of a given queue in RabbitMQ message broker.
I defined an exchange and routing key in RabbitMQ.
I used AmqpIO.read() in Beam (version 2.9.0) but I did not found any API to set the echange and the routing key.
(Following this doc : https://beam.apache.org/releases/javadoc/2.4.0/org/apache/beam/sdk/io/amqp/AmqpIO.html)
Is there any possibility to do that ? Even with any other plugin.
Regards,
Ali

A: There is a new (experimental) IO connector for RabbitMQ shipped with the latest v2.9.0 Apache Beam release.  The AMQP connector will not work for RabbitMQ.
If you are using Maven add the following dependency in your POM
<!-- Beam MongoDB I/O -->
<dependency>
    <groupId>org.apache.beam</groupId>
    <artifactId>beam-sdks-java-io-mongodb</artifactId>
    <version>2.9.0</version>
</dependency>

and you can use it in a pipeline like
public class RabbitMQPipeline {

final static Logger log = LoggerFactory.getLogger(RabbitMQPipeline.class);

/**
 * Mongo Pipeline options.
 */
public interface RabbitMQPipelineOptions extends PipelineOptions {

    @Description("Path of the file to read from")
    @Default.String("amqp://localhost")
    @Required
    String getUri();

    void setUri(String uri);

}

/**
 * @param args
 */
public static void main(String[] args) {

    RabbitMQPipelineOptions options = PipelineOptionsFactory.fromArgs(args).withValidation()
            .as(RabbitMQPipelineOptions.class);

    Pipeline pipeline = Pipeline.create(options);

    PCollection<RabbitMqMessage> messages = pipeline
            .apply(RabbitMqIO2.read().withUri(options.getUri()).withQueue("test"));

    messages.apply(ParDo.of(new DoFn<RabbitMqMessage, String>() {
        @ProcessElement
        public void process(@Element RabbitMqMessage msg) {
            System.out.println(msg.toString());
        }
    }));

    pipeline.run().waitUntilFinish();
}

}
The RabbitMqIO Javadoc has examples of how to use the reader and writer.
A word of caution
There is a known bug that has been fixed but scheduled for release in v2.11.0 that blocks the connector from working even in the simplest scenarios. The fix is really simple (see JIRA issue) but you will need to rebuild a new version of the class.  In case you want to give it a try make sure you add the following Maven dependency
<dependency>
    <groupId>com.google.auto.value</groupId>
    <artifactId>auto-value</artifactId>
    <version>1.5.2</version>
    <scope>provided</scope>
</dependency>

and add the following configuration in Maven Compiler plugin
<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.1</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <annotationProcessors>
        <annotationProcessor>com.google.auto.value.processor.AutoValueProcessor</annotationProcessor>
            </annotationProcessors>
        </configuration>
    </plugin>

If you are using Eclipse make sure you install the m2-apt Maven plugin.  Good luck!