text:
Q: Why do my custom activities just sit on a greyed-out loading screen when I try to view them in Journey Builder? I have built two different custom activities and hosted them on two different hosting platforms and both of them view fine when I load them in the browser, but when I add them to a journey and click on them to make edits, I can see the interface faded out with a loading wheel in front. It does not seem to ever finish loading. Is there a setting I am missing? Obviously the app package is "seeing" the code as I can see my interface loaded in the background...
Where it has happened with two different apps and two different hosting servers (Heroku and Siteground), I have to assume I am missing something in SFMC itself... but the set up there is pretty straightforward and I haven't found anything online to identify anywhere I may have gone wrong...

A: I had the same issue. Make sure you configured a Data Source to the journey (i.e. data extension or something else).


text:
Q: How create a folder on SdCard and how to copy files from one to another In this Project i am trying to copy files from sdcard (for eg images in DICM) to Recycle Folder whenever user click delete button. But, i am facing problem. I am able to delete files but but unable to copy thing.
C.Java - Using for assigning directories.
package com.haha.recyclebin;

public class C
{

    public static String SDCARD = "/mnt/sdcard";
    public static String RECYCLE_BIN_ROOT = SDCARD+"/.Recycle";
}

U.Java - Using for copying file from one folder on Sdcard to Recycle Folder.
package com.haha.recyclebin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class U
{

    public static void copyFile(File sourceLocation, File targetLocation)
            throws FileNotFoundException, IOException
            {

        U.debug("copying from "+sourceLocation.getAbsolutePath()+" to "+targetLocation.getAbsolutePath());

        String destDirPath = targetLocation.getParent();
        File destDir = new File(destDirPath);
        if(!destDir.exists()){
            destDir.mkdirs();
        }

        InputStream in = new FileInputStream(sourceLocation);
        OutputStream out = new FileOutputStream(targetLocation);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024*512];
        int len;
        while ((len = in.read(buf)) > 0) {
            System.out.println("papa");
            out.write(buf, 0, len);
            System.out.println(">");
        }
        System.out.println(".");
        in.close();
        out.close();
    }

    public static void debug(Object msg){
        System.out.println(msg);
    }
}

RecycleActivity - using U.java and C.java in this code :-
package com.haha.recyclebin;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

public class RecycleActivity extends Activity {

    private OnClickListener exitListener = new OnClickListener()
    {

        @Override
        public void onClick(DialogInterface paramDialogInterface, int paramInt)
        {
            RecycleActivity.this.finish();
        }
    };

    /**
     * need a standalone class to hold data (file name)
     */
    private final class DeleteFileListener implements OnClickListener
    {

        String file = null;

        /**
         * @param file the file to set
         */
        public void setFile(String file)
        {
            this.file = file;
        }

        @Override
        public void onClick(DialogInterface paramDialogInterface, int paramInt)
        {

            RecycleActivity.this.prepareRecyclebin();

            File src = new File(file);
            String destPath = C.RECYCLE_BIN_ROOT+file;

            File dest = new File(destPath);

            try
            {
                U.copyFile(src, dest); /* using U.java here */
                src.delete();
                String msg = RecycleActivity.this.getResources().getString(R.string.deleted) + destPath;
                Toast.makeText(RecycleActivity.this, msg, Toast.LENGTH_SHORT).show();
            } catch (Exception e)
            {
                e.printStackTrace();
                Toast.makeText(RecycleActivity.this, R.string.delete_failed, Toast.LENGTH_SHORT).show();
            }

            RecycleActivity.this.finish();
        }
    }

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

        Intent intent = getIntent();
        debugIntent(intent);

        Bundle extras = intent.getExtras();

        /* For File Explorer */
        Object obj = extras.get(Intent.EXTRA_INTENT);
        if(null!=obj){
            Intent it2 = (Intent) obj;
            Bundle ex2 = it2.getExtras();
            Object obj2 = ex2.get(Intent.EXTRA_STREAM);
            if(null!=obj2){
                Uri uri = (Uri) obj2;
                String file = uri.getPath();
                System.out.println("file: "+file);
                toRecyclebin(file);
            }
        }

    }

    /**
     * @param file
     */
    private void toRecyclebin(String file)
    {

        if(!file.startsWith(C.SDCARD))
        {
            promptLimit();
            return;
        }

        String conf = this.getResources().getString(R.string.confirm_delete);
        conf+="\n\n"+file;

        DeleteFileListener listener = new DeleteFileListener();
        listener.setFile(file);

        new AlertDialog.Builder(this)
        .setMessage(conf)
        .setPositiveButton(R.string.yes, listener)
        .setNegativeButton(R.string.no, exitListener)
        .show();
    }

    /**
     *
     */
    private void promptLimit()
    {
        new AlertDialog.Builder(this)
        .setMessage(R.string.limit)
        .setPositiveButton(R.string.ok, exitListener)
        .show();
    }

    /**
     * @param intent
     */
    private void debugIntent(Intent intent)
    {
        System.out.println("intent: "+intent);
        Bundle extras = intent.getExtras();
        Set<String> keys = extras.keySet();
        for(String key:keys){
            Object value = extras.get(key);
            System.out.println("-["+key+"]:["+value+"]");
            if(value instanceof Intent){
                Intent intent2 = (Intent) value;
                Bundle ext2 = intent2.getExtras();
                Set<String> ks2 = ext2.keySet();
                for(String k:ks2){
                    Object v2 = ext2.get(k);
                    System.out.println("--["+k+"]:["+v2+"]");
                    if(v2 instanceof Intent){
                        Intent i3 = (Intent) v2;
                        Bundle e3 = i3.getExtras();
                        Set<String> ks3 = e3.keySet();
                        for(String kk:ks3){
                            Object v3 = e3.get(kk);
                            System.out.println("---["+kk+"]:["+v3+"]");
                        }
                    }
                }
            }
        }

        Uri data = intent.getData();

        System.out.println("data: "+data);

    }

    void prepareRecyclebin(){
        File root = new File(C.RECYCLE_BIN_ROOT);
        if(!root.exists()){
            root.mkdirs();
        }
    }
}

I have file explorer which is working fine, I can see images and music on sdcard and i am able to delete then also. But after deletion they should go to Recycle folder (as stated in C.java ). I have created Recycle Folder (/mnt/sdcard/Recycle) manually using file explorer in  eclipse.
But i don't see files in recycle folder.
Is there any problem with the Code ?
Any kind of Help will be appreciated.
Thanks !!

A: Have you Debug and make sure the copyfile has been executed?
And this is My CopyFile function, and they are quite the same:
public static boolean copyFile(String from, String to) {
    try {
        int bytesum = 0;
        int byteread = 0;
        File oldfile = new File(from);
        if (oldfile.exists()) {
            InputStream inStream = new FileInputStream(from);
            FileOutputStream fs = new FileOutputStream(to);
            byte[] buffer = new byte[1444];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            inStream.close();
            fs.close();
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}

A: Try following Code, it will Work.
public void Save_To_Phone(Bitmap bitmap){
    try {
      FileOutputStream os = new FileOutputStream(YourSDCardPath);
      bitmap.compress(CompressFormat.JPEG, 80, os);
      os.close();
    } catch (Exception e) {
      Log.w("ExternalStorage", "Error writing file", e);
    }
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Password reset form not displaying Update:
Looks like it was a browser issue, now resolved
When I use the password reset in development it works fine. However in production after the user opens the reset email the password reset form is not displayed however other forms on the site via crispy forms are working fine. Nothing has been changed from dev to production besides the url in the view. The server and dev are running the same version of crispy forms.
I did it based off this tutorial and it seems I have made all the required changes for production
When checking the urls of the email between production and dev i do not see an issue
http://127.0.0.1:8000/reset/MQ/***hm*-e00d**b30b635b358be1573e********/
https://domain.co/reset/MQ/***ht*-71ff80c**580c6cecc3ffd44********/

view that sends the email:
def password_reset_request(request):
    if request.method == "POST":
        password_reset_form = PasswordResetForm(request.POST)
        if password_reset_form.is_valid():
            data = password_reset_form.cleaned_data['email']
            associated_users = User.objects.filter(Q(email=data)|Q(username=data))
            if associated_users.exists():
                for user in associated_users:
                    subject = "Password Reset Requested"
                    plaintext = template.loader.get_template('users/password_reset_email.txt')
                    htmltemp = template.loader.get_template('users/password_reset_email.html')
                    c = {
                    "email":user.email,
                    'domain':'domain.com',
                    'site_name': 'Website',
                    "uid": urlsafe_base64_encode(force_bytes(user.pk)),
                    "user": user,
                    'token': default_token_generator.make_token(user),
                    'protocol': 'https',
                    }
                    text_content = plaintext.render(c)
                    html_content = htmltemp.render(c)
                    try:
                        msg = EmailMultiAlternatives(subject, text_content, 'myemail@email.com', [user.email], headers = {'Reply-To': 'myemail@email.com'})
                        msg.attach_alternative(html_content, "text/html")
                        msg.send()
                    except BadHeaderError:
                        return HttpResponse('Invalid header found.')
                    return redirect ("password_reset_done")
    password_reset_form = PasswordResetForm()
    return render(request=request, template_name="users/password_reset.html", context={"password_reset_form":password_reset_form})

template that the user resets password (auth_view):
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}

        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Reset Password</legend>
                {{ form|crispy }}
            </fieldset>

                <button class="login-register-btn" type="submit">Reset</button>

        </form>

{% endblock content %}

urls:
    from users import views as user_views
    path("reset_password/", user_views.password_reset_request, name="password_reset"),
    path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="users/password_reset_sent.html"), name="password_reset_done"),
    path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name="users/password_reset_form.html"), name="password_reset_confirm"),
    path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="users/password_reset_done.html"), name="password_reset_complete"),

Update:
If I try and render the form like {{ form }} it only renders None leading me to believe the context is not being passed and not a crispy issue
Update:
Although I am pretty sure it has nothing to do with it I double checked all my email settings and they look good. I also tried the template from the tutorial and it did the same thing
Update:
Took a look in the docs and found this for the password reset confirm view, It appears I am passing the correct form value of {{form}} However When I pass validlink to the template it returns false
Update:
I cleared my cache and waited a bit and then the resets were retuning true. I think it was reading false because I had one pending. Tried it on my phone and the form displayed, Unsure why its not displaying on my desktop.


text:
Q: Remove rows based on multiple conditions in pyspark I have this dataframe below:
+--------+----------+----------+--------+----------+
|SID     |StartDate |EndDate   |CID     |Date Added|
+--------+----------+----------+--------+----------+
|1001    |2021-04-05|2021-04-05|1002    |2021-03-26|
|1001    |2021-03-30|2021-03-31|1002    |2021-03-26|
|1001    |2021-04-07|2021-04-09|1002    |2021-03-26|
|1004    |2021-04-05|2021-04-05|1003    |2021-03-26|
|1005    |2021-04-06|2021-04-06|1006    |2021-03-26|
|1001    |null      |null      |null    |2021-03-29|
|1001    |2021-04-05|2021-04-05|1002    |2021-03-29|
|1001    |2021-03-30|2021-03-31|1002    |2021-03-29|
+--------+----------+----------+--------+----------+

What I'm trying to do is if there is a null value for the record SID in StartDate, EndDate and CID, it will drop the row with null value and other records for SID that is less than the Date Added. So the result would look like this.
+--------+----------+----------+--------+----------+
|SID     |StartDate |EndDate   |CID     |Date Added|
+--------+----------+----------+--------+----------+
|1004    |2021-04-05|2021-04-05|1003    |2021-03-26|
|1005    |2021-04-06|2021-04-06|1006    |2021-03-26|
|1001    |2021-04-05|2021-04-05|1002    |2021-03-29|
|1001    |2021-03-30|2021-03-31|1002    |2021-03-29|
+--------+----------+----------+--------+----------+

I know filter can probably help but I'm not really sure how to do it with the other conditions I mentioned. Can anyone help, please?

A: You can filter those specific rows that have null in StartDate, EndDate and CID then join with the original dataframe using left_anti join :
from pyspark.sql import functions as F

filter_cond = F.col("StartDate").isNull() & F.col("EndDate").isNull() & F.col("CID").isNull()

df1 = df.alias("df").filter(~filter_cond).join(
    df.filter(filter_cond).select("SID", "Date Added").alias("f"),
    (F.col("df.SID") == F.col("f.SID")) & (F.col("df.`Date Added`") < F.col("f.`Date Added`")),
    "left_anti"
)

df1.show()
#+----+----------+----------+----+----------+
#| SID| StartDate|   EndDate| CID|Date Added|
#+----+----------+----------+----+----------+
#|1005|2021-04-06|2021-04-06|1006|2021-03-26|
#|1001|2021-04-05|2021-04-05|1002|2021-03-29|
#|1001|2021-03-30|2021-03-31|1002|2021-03-29|
#|1004|2021-04-05|2021-04-05|1003|2021-03-26|
#+----+----------+----------+----+----------+

A: You can add a nulldate column of the date where the three columns are null, and filter to get the rows where that date does not exist, or DateAdded is greater than or equal to that date, and of course, the rows where the three columns are not null.
from pyspark.sql import functions as F, Window

cond = F.col('StartDate').isNull() & F.col('EndDate').isNull() & F.col('CID').isNull()

df2 = df.withColumn(
    'nulldate',
    F.max(
        F.when(
            cond,
            F.col('DateAdded')
        )
    ).over(Window.partitionBy('SID'))
).filter('(nulldate is null or DateAdded >= nulldate)').filter(~cond).drop('nulldate')

df2.show()
+----+----------+----------+----+----------+
| SID| StartDate|   EndDate| CID| DateAdded|
+----+----------+----------+----+----------+
|1005|2021-04-06|2021-04-06|1006|2021-03-26|
|1001|2021-04-05|2021-04-05|1002|2021-03-29|
|1001|2021-03-30|2021-03-31|1002|2021-03-29|
|1004|2021-04-05|2021-04-05|1003|2021-03-26|
+----+----------+----------+----+----------+


text:
Q: How to get the latest patch updates of antivirus client in Windows 7 in C# Is there any way to know the antivirus patch updates in Windows 7 since WMI doesnt povide them.
I found that Windows Xp do provide the version Number but is there any other method to know the version number for Windows 7
Windows XP
Namespace : SecurityCenter
AntiVirusProduct-Properties

companyName
displayName
enableOnAccessUIMd5Hash
enableOnAccessUIParameters
instanceGuid
onAccessScanningEnabled
pathToEnableOnAccessUI
pathToUpdateUI
productUptoDate
updateUIMd5Hash
updateUIParameters
versionNumber

Windows Vista and Windows 7

Namespace : SecurityCenter2

displayName
instanceGuid
pathToSignedProductExe
pathToSigned

I need to develop an application that will provide me the patch updates of the antivirus in C#

A: Two ways you could try:
string x = Environment.OSVersion.ToString();

or another round about way is to run cmd.exe to run "ver"
string[] MyArguments = { "ver", ">text.txt"};
Process.Start("cmd.exe", String.Join(" ", MyArguments));

then open the file text.txt to parse the version information.


text:
Q: Difference between number of runs and loops in timeit result I want to examine whether using a numeric lookup value in merging 2 dataframes is faster than using a string lookup value or not. for this purpose I used %timeit with below codes:
Merge on a string lookup value:
%timeit newframe = subframe.merge(frame, on = 'a string column', how = 'left')

result : 2.82 ms ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Merge on a numeric lookup value:
%timeit newframe2 = subframe.merge(frame, on = 'a numeric column', how = 'left')

result : 2.88 ms ± 28.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

My question is that within my code, there were not any loops. I am wondering what is the difference between the number of runs and the number of loops in the timeit result?
Does 7 runs means that the timeit module runs the merge 7 times and calculating the mean and std for those 7 runs? and if so, what does loops mean?

A: It runs your code 7 * 100 times: 7 runs of 100 loops each.


text:
Q: Skype for Business 2015 : Audio / Video not working in meetings I'm new to Skype for Business Technology, and I'm trying to deploy a server that I'm willing to use with Skype WebSDK and AppSDK.
At first I tried using the skype for business online, but the websdk doesn't support the anonymous join to a meeting. So I decided to deploy an on premise version of it.
I followed instructions on this video : https://www.youtube.com/watch?v=uNIm5YNIY6Q and also this Document : http://www.msic.ch/Portals/0/Images/Skype%20for%20Business%20Server%202015%20Step%20by%20Step%20for%20Anyone%20-%20Installing%20and%20Upgrading_REV_05.pdf
I have two servers :
- Active Directory +  Certificat Authority + DNS
- Skype for Business Standard
The active directory is configured with "contoso.com" and my external domain is also "contoso.com". On the internal DNS I used internal adresses, and on the external DNS I used the public ones. I have an A record for "admin, dialin, meet, sip, lyncdiscover ..."  and SRV record for "_sipinternaltls_tcp" as described on the tutorials.
The installation process was successfull without any error.
My problem is when I create a meeting, I have only the chat without any video or audio. At first the client tries to connect the audio and then hangs up without any errors.
Is there any way to troubleshoot this situation ?  Is there any extra step I should do to activate audio / video in meetings ?
Thank you for your help

A: This sounds like you don't have the CAL licenses to enable conferencing. The default (free) standard client license doesn't allow conferencing.


text:
Q: ldconfig can't find lib in standard location EDIT:
Cloudera says that CentOS is supported please check Cloudera manual install as they have instructions on how to do so, it relies on libpython2.6.so.1.0 and libsasl2.so.2.

When installing a package ( impala from cloudera repository ) I am told that libsasl2.so.2 and libpython2.6.so.1.0 are missing. After some searching people have said that soft linking the more up to date versions is fine.
I do this in the same folder that all other libs are which is /usr/lib64. However, when I run ldconfig -n -v /usr/lib64 I do not see the new libs in the list. I run the following commands:
ln -s /usr/lib64/libpython2.7.so.1.0 /usr/lib64/libpython2.6.so.1.0
ln -s /usr/lib64/libsasl2.so.3 /usr/lib64/libsasl2.so.2
ldconfig -n -v /usr/lib64

I have looked at other questions, but none of the answers solve the issue. What am I doing incorrectly?

A:

Cloudera says that CentOS is supported

The packages are for CentOS 6 , and your OS is CentOS 7 .....
.... ( CentOS 5 packages are also available.)


text:
Q: conversion from empty string to float using stringstream results in non-zero value I have tried to solve this with previously answered questions like Conversion from string to float changes the number but I have not  been successful.
In my code I take a string full of ' ' characters and convert it to float using stringstream. It worked fine (returned me a zero valued float) until I performed another conversion right after that. When a conversion is executed afterwards, the value stored in the float previously converted is not zero, but 4.57048e-41. I hope the following code explains my problem more clearly.
I started with:
std::stringstream ss;
float a;
float b;
for(int i=0; i<LIM; ++i){
    //some other conversions using same stringstream
    //clearing stringstream
    ss.str( std::string() );
    ss.clear();

    ss << str1;    //string full of empty spaces, length of 5
    ss >> a;
    std::cout << a;//prints zero
}

That worked just fine, but when I changed it to
std::stringstream ss;
float a;
float b;
for(int i=0; i<LIM; ++i){
    //some other conversions using same stringstream
    //clearing stringstream
    ss.str( std::string() );
    ss.clear();

    ss << str1;    //string full of empty spaces, length of 5
    ss >> a;
    std::cout << a;//prints 4.57048e-41

    ss.str ( std::string() );
    ss.clear();

    ss << str2;    //another string full of empty spaces, length of 5
    ss >> b;
    std::cout << b;//prints zero
}

I am using gcc 4.6.3 with the following flags:
 -o2 -Wall -Wextra -ansi -pedantic
Any kind of help will be greatly appreciated, but I am not willing to use doubles.
Many thanks!

A: If the conversion fails, then the target value isn't changed. In your case, it still has its original uninitialised value; so printing it gives garbage or other undefined behaviour.
You should check whether the conversion succeeded:
if (!(ss >> a)) {
    a = 0; // or handle the failure
}

or use conversion functions like std::stof in C++11, or boost::lexical_cast, which throw to indicate conversion failure. (Or, as mentioned in the comments, just set it to zero to start with if you don't otherwise need to detect failure).


text:
Q: How to make a button work like a html a tag with href I have the functional component below which I want to use
to download an excel file stored on the server to my computer.
When I use the html a tag with href, everthing works. Now I decided to change
this to a button.
How do I call my download function here to download my excel file?
Do I need to dispatch this?
        const MyfirstTest = () => {

          const download = () => {
            '/api/tester1/tester3'
          }

          return (
            <div>
              <Button
                  variant={'primary'}
                  type={'button'}
                  squared={false}
                  uppercase={true}
                  className={classes.btn}
                  onClick={download}
                >
                  <IconButton icon={'download'} />
                  Download File
                </Button>

              </div>
          )
        }

        export default MyfirstTest

A:       const download = () => {
      const link = document.createElement('a')
        link.href = '/api/tester1/tester3'
        link.setAttribute('download','fileName')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }

You can achieve by creating an Link element and click on it.


text:
Q: trying to give "right/path/to/endpoint" but 404 not found returns I put a backend files into /www folder, but can't return the endpoint it's giving 404. When I try to access the domain.com/api/schedule it returns You don't have permission to access /api/schedule/ on this server. but if I try to reach endpoint which is domain.com/api/schedule/read then it's giving the 404 not found
inside the read.php I include files from different folders. like below.
include_once "../../config/Database.php";
include_once "../../models/User.php";
include_once "../../models/Schedule.php";
include_once "../../models/Blank.php";

So i am not very sure, 404 not found error about the path "../.." or not
and here is the /www/ access of in apache .conf file.
<VirtualHost *:8005>
    DocumentRoot /var/www/rest_backend
    <Directory /var/www>
        AllowOverride All
    </Directory>
</VirtualHost>

what do I missing here?


text:
Q: mimic bdh function fill down When a query is entered into the Bloomberg BDH function in Excel it automatically populates the selected cell, and cells below with the requested data.
I am trying to create a function that does something similar (albeit with a different source of data). How does the BDH function circumvent the typical restriction within a user defined function of modifying other cells when it fills down the queried data?

A: You need to do it in a two-stage process:

*

*Your function calls another process to compute values and return only the 1st element of the array to be returned (could be "#NA #NA" or the date or price, etc.

*The called process can be running in a separate RTD server (check out Real Time Data server) or a separate process which links to your spreadsheet via DDE. (Bloomberg uses DDE for some functions, RTD for the others, I think)

*That way when you call a function, the first value is returned immediately (i.e. the answer, or "#NA Requesting Data..." and then when the RTD server fetches the required data the answer to this function changes to whatever the top-left array element is, and the rest of the cells are populated via DDE/RTD.
Simple examples of setting up a RTD server are found on Microsoft's knowledge base. Also, lots of examples using DDE (an older, but very popular technology for financial data exchange using Excel, even today) are available upon Googling.
A simple filler application can be built using C# or VB.net Interop (search again for examples).
Hope this helps.
Edit: You can also do this completely using VBA by using some clever combination of the OnTime functionality (see http://www.cpearson.com/excel/OnTime.aspx) and combining it with DDE driven from a separate spreadsheet (look up Tushar Mehta DDE clock, a very old example, but some things never change!)


text:
Q: C++'s pure virtual function implementation and header files I'm having some trouble implementing pure virtual functions inherited from some abstract class, when the classes in question are divided into *.h and *.cpp files. The compiler (g++) tells me that the derived class cannot be instantiated because of the existence of pure functions.
/** interface.h**/
namespace ns
{
    class Interface {
        public:
            virtual void method()=0;
    }
}

/** interface.cpp**/
namespace ns
{
    //Interface::method()() //not implemented here
}

/** derived.h **/
namespace ns
{
    class Derived : public Interface {
        //note - see below
    }
}

/** derived.cpp **/
namespace ns
{
    void Derived::Interface::method() { /*doSomething*/ }
}

/** main.cpp **/
using namespace ns;
int main()
{
    Interface* instance = new Derived; //compiler error
}

Does this mean that I have to declare the method() twice - in the Interface's *.h and in the derived.h too? Is there no other way around?

A: You have to declare your method in the subclass.
// interface.hpp
class Interface {
public:
    virtual void method()=0;
}

// derived.hpp
class Derived : public Interface {
public:
    void method() override;
}

// derived.cpp
void
Derived::method()
{
    // do something
}

A: You forgot to declare Derived::method().
You tried to define it at least, but wrote Derived::Interface::method() rather than Derived::method(), but you did not even attempt to declare it. Therefore it doesn't exist.
Therefore, Derived has no method(), therefore the pure virtual function method() from Interface was not overridden... and therefore, Derived is also pure virtual and cannot be instantiated.
Also, public void method()=0; is not valid C++; it looks more like Java. Pure virtual member functions have to actually be virtual, but you did not write virtual. And access specifiers are followed by a colon:
public:
    virtual void method() = 0;

A: You also did not call constructor properly - it's also a method;
 Interface* instance = new Derived;

Should be
 Interface* instance = new Derived();


text:
Q: Método save() do mongoose não salva Estou com o seguinte problema:
Quando chamando o método save do mongoose ele parece não estar fazendo nada.
O código do save é o seguinte:
var newProjects = new projectModel({
    "teste":"teste"
});
newProjects.save(function (err){
    if(err){
        console.log("Erro");
        return;
    }else {
        console.log("Funcionou");
        return;
    };
});
console.log("Passou")

O que acontece é que ele nunca loga as mensagens de "Erro" nem a "Funcionou", mas loga a mensagem "Passou", e também não cria a collection no MongoDB. Por ser a primeira vez que o save dessa model é executado, creio que a criação devia ser feita.
A variável ProjectModel é inicializada assim:var projectModel = mongoose.model('Projects');
E a modelagem da collection é a seguinte:
var mongoose = require("mongoose");

var projectsSchema = new mongoose.Schema({
    teste: {type: String, required: true}
});

mongoose.model('Projects', projectsSchema);

Alguma ideia do que pode estar causando o problema?

A: Você pode utilizar o metodo Model.create() onde ele cria um registro em seu banco de dados a partir de sua model:
try {
   const projectModel = await projectModel.create({teste:"teste"});
   return projectModel ;
}
catch(err) {
    return err
}


text:
Q: How do I install VLC extensions? VLC player allows installing extensions, plugins, skins. They have to be copied into a folder: for example, its .lua extensions should be in a folder with the same name. Where is that?

A: To install extensions (.lua) the needed folder is ~/.local/share/vlc/lua/extensions/ for the current user and /usr/lib/vlc/lua/extensions/ for all users. I found about it here and here.
Once installed, they are to be found under 'View'

(I put them here for illustration, I do not recommend all of them.)
Skins are installed by going to Tools/Preferences(Ctrl-P) - Interface: 'Use custom skin', and select the skin file.

UPDATE
At least for the moment, very few VLSub extensions are really working and are worth trying; and, among these, most are not actively developed, as you can see here: the best is VLSub, probably the best tool around at the present for downloading subtitles - to the point that recent versions of the player have integrated that addon by default (but in VLC 2.2.2 that is outdated and has stopped working: see below).
VLC 2.2. has the capability to search and install extensions within it's settings, under Tools-Plugins and extensions:

Only it doesn't always install the latest version which is needed for the extension to really work, in which case download the script from the developer (for VLSub, here) and install it as indicated in the first part of this answer.
If the addons that come with the player need to be replaced, look for them in /usr/lib/vlc/lua/extensions/.

A: I'm using the snap version of VLC on Xubuntu 20.10.
The extensions are located under:
/home/[username]/snap/vlc/1700/.local/share/vlc/lua/extensions/

A: For those that installed the Flatpak version of VLC the path to your extension folder is
/home/[username]/.var/app/org.videolan.VLC/data/vlc/lua/extensions

(at least on Ubuntu 21.10 using VLC 3.0.16)

A: Sorry,I don't have enough reputation to comment on the previous answers:

*

*1st answer by user47206 & edited by Jorge Castro descries two ways to add add-ons (plugins or extensions) to VLC manually by placing their lua files in a certain directory or automatically via tools menu>plugins and extensions which are still valid ways theoretically but directories mentioned in the answer and the comment by Antonio Petricca are now all not working/ obsolete.

*2nd Answer by user1137772 & edited by Nmath shows a new directory /home/[username]/snap/vlc/1700/.local/share/vlc/lua/extensions/ which needs a little tweak now "I'm using VLC version 3.0.12.1 on ubuntu 21.04 from ubuntu software store" to /home/[username]/snap/vlc/2103/.local/share/vlc/ "which contains folders skins2 for vlt file type skins and lua/ for different plugins and extensions of lua file types i.e extensions like VLsub which is preadded by default now, playlist like radiotime also preadded,later it may create other folders inside e.g sd for service discovery like TuneIn or intf for interface like syncplay which you can add the automatic way".

*location for luac files library extracted from " preadded VLsub = extension" more information from tools menu>plugins and extensions>active extensions is /snap/vlc/2103/usr/lib/vlc/lua/[folder] see evidence image and evidence image which contains luac files for other preadded add-ons like jamendo and icecast.

*By default tools>preferences>"advanced"interface>input / Codecs>disable all lua plugins is checked and unchecking it will disable those preadded "luac" add-ons (like VLsub, jamendo, and icecast) and the "lua" ones I added (like TuneIn Radio, Jump to time, Sampler_PG "which have only a lua file in /home/[username]/snap/vlc/2103/.local/share/vlc/lua/[folder] !").

*For me, I added some add-ons automatically and some manually, only extensions appeared in view menu under VLsub ,while service dicovery add-ons added the "automatic way" will appear in playlist left panel and other add-ons e.g. skins, playlist parsers, interface will appear installed only in tools>plugins and extensions :

*

*Skins worked only manually for me from native skin by going to tools>preferences>"simple"preferences>look and feel>check use custom skin and then browse to your vlt file "automatically downloaded skins will not appear here as .local is hidden directory so you'll have to put them into a visible one" click save and restart VLC. After loading a cusom skin an option will appear in right click menu>interface>select skin, From which you can choose a skin from /home/gandalf/snap/vlc/2103/.local/share/vlc/skins2.
Choosing skin2 from tools>preferencec>"advanced"preferences>interface>main interface>skinnable interface "check" caused the player to crash and not be opened anymore except by typing VLC in terminal.

*Extensions I added automatically "appeared to" work.

*All other add-ons that I added did not work.


text:
Q: integrate paypal in cakephp I want to integrate PayPal simple Payment (by redirecting to PayPal and returning to our website after completion) gateway with my CakePHP website, any idea about available components or helpers? thanks

A: this all works with a simple form. just use the form action as described (paypal website). i do not think that there is something that can be made simpler.


text:
Q: Convert Header file .h to C# I am having a lot of header files (written in C) that I want to convert into C# code.
The header files contains enums, structs, methods.
I can convert them by hand, but that would take forever, so i was wondering if there is a tool to convert header files into C#.
I have tried PInvoke Interop Assistant but that only works with /clr compiled .dlls.
I have tried SWIG and that works some of the way, it succesfully generates nice enums, but the structs and methods doesn't look very good.
Is there other ways I can convert header .h files?


text:
Q: How do i access a local state inside the mapstatetoprops method Thanks in advance.
Below is the snippet
const mapStateToProps = (state) => {
  const { itemReducer } = state;
  return {
    itemTree: getItemTree(itemReducer),
  };
};

getItemTree is a selector, and i would like to have another selector something like getFilteredItemTree.
This transition should based on a local state. How do i access a local state or variable in this function.
Or is there any other way to work on this.

A: You can access props passed to this component through 2nd param of mapStateToProps but you can't access local state of the component.
What you can do is pass the whole data in the component and then filter it in the component's lifecycle hook.


text:
Q: Cannot start debugging xamarin.android for a project in vs2019 I have a Xamarin.Android project that I haven't touched for a few months. Today when I open it, the Debug button is showing Start instead of the emulators that I installed. If I press Startbutton then I received Error: Cancelled in the output window.

From another branch I can see the button showing devices correctly and I can start the project in the emulator.

I cannot figure out why. Both soluitons compile correctly. It's just one of them cannot be debugged.
Edit: I compared everything in both branches. There's no difference. Then I tried plugging in a physical android device. After enabling USB debugging on the device, the Start button gets refreshed and is showing the device name of the newly plugged in device along with all the other emulators. But that only last until the next restart of Visual Studio, then it returns to a simple Start button without listing devices.
Another observation: In Android Manifest of the project property, it shows No AndroidManifest.xml found. Click to add one. Clicking it does not do anything. And I'm pretty sure AndroidManifest.xml is right where it should be.

Another observation: If I created a new Android project, sometimes everything will be normal. Android Manifest is showing correctly and debug button is showing devices but last only until next startup of VS2019. I tried reparing VS2019 then restart computer. Also it works until next startup.
Another observation:
One of the VS2019 suddenly loads Android Manifest and devices normally after leaving open for a while. I'll see if all instances will be normal if left open long enough.
I'm using Visual Studio 16.11.4

A: As suggested by YanFang Wang from https://developercommunity.visualstudio.com/t/cannot-start-debugging-xamarinandroid-for-a-projec/1572614#T-N1573976

Uninstall all those programs from control panel:

*

*Visual Studio 2019

*Microsoft Visual Studio Installer

*Microsoft Visual C++ xxxx-xxxx Redistributable (x64)- xxxx

*Microsoft Visual C++ xxxx-xxxx Redistributable (x86)- xxxx

*Microsoft Build of OpenJDK with Hotspot xxxxx

*Microsoft Edge WebView2 Runtime

*Microsoft SQL Server 2019 LocalDB

*Delete "Microsoft Visual Studio" folder from C:\Program Files and C:\Program Files (x86)

*Delete all content from C:\Users\v-yanfw\AppData\Local\Temp

*Delete regedit: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio

Then reinstall VS2019. Problem is fixed.
Previous found alternative:
Running VS2019 as administrator.

A: *

*Open Android Device Manager, select your emulator and run it.

*Find the simulator you just ran in the start drop-down menu and select it.

*Right-click your Android project and select Set as Startup Project.


text:
Q: WCF 'There was no endpoint listening at URL that could accept the message' I have a WCF SOAP app that I run under Azure Cloud Services.
For about 30% of all SOAP calls that I make to the app (or my users make) I get the following error:
There was no endpoint listening at URL that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details., Server stack trace:
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

I am a bit confused about this error because normally I'd expect this error to orrur always or never.
I have checked some of the users input and I don't see anything weird with it compared to other inputs.


text:
Q: Run php snippet in interval I'm currently making a hacky way for a chat application, just to play around really.
What happens is, you allow an user to login, or register, and they will be send to the index.php which is a chatbox.
Once you send a message, this message is stored inside the database. The html then loads in the messages with php using a foreach loop.
So now, once I send a message, I use AJAX to send this message to a php file, which processes it and sends it to the database. I'm now trying to figure out how I can allow the following code snippet to run in an interval, so that it will fill the contents of the chat from the database by 'x' seconds.

sendbutton.click(function(e){
        e.preventDefault();

        var message = sendinput.val();

        var data = {
            message: message
        };

        if(message != ''){
            $.ajax({
                type: 'POST',
                data: data,
                url: 'sendmessage.php',
                success: function(data){
                    if(data == "True"){
                        sendinput.val('');

                        // Could do an ajax get request here.
                    }
                },

            })
        }
    });
<?php
        $messages = Database::getInstance()->query('SELECT * FROM message ORDER BY createdAt ASC');

        foreach($messages->results() as $message){
        $owner = Database::getInstance()->get('user', array('ID', '=', $message->ID));

        $ownername = $owner->first()->username;

        $toDrop = <<<ETO

$ownername

$message->message

$message->createdAt

ETO;

            print $toDrop;
        }

?>

You can not run this snippet, but I do think this gives a general idea on what I'm achieving or trying to achieve.

A: Okay, I now have a solution, which doesn't even have to get an interval, but I'm just not sure if it is the right way to go.
I made a AJAX get request which fills a div with the response from that get request.
$.ajax({
            type: 'POST',
            data: data,
            url: 'sendmessage.php',
            success: function(data){
                if(data == "True"){
                    sendinput.val('');

                    $.ajax({
                        type: 'GET',
                        url: 'todrop.php',
                        success: function(data){
                            $('.messages').html(data);
                        }
                    })
                }
            },

        })

A: I understand it's for play and in the same time if you're gonna test it on a site with more people then it will start to kill server. 2 many connections created, so the pooling model (where you check for new msgs every x seconds or after each msg ppl sent) and db aren't that great for chat.
If you already want to do it that way I'd suggest you switch database to redis whichis much faster and you can set expiry on stored data, but in reality you'd use WebSockets or some other more real time solution.
See this https://github.com/Flynsarmy/PHPWebSocket-Chat or just search for php/js live chat with websockets.


text:
Q: :inverse_of not working through accepts_nested_attributes_for relationship I have something kind of like this:
class Project < ActiveRecord::Base
  has_many :foos, inverse_of: :project
  has_many :bars, inverse_of: :project
end

class Foo < ActiveRecord::Base
  belongs_to :project, inverse_of: :foos
  has_and_belongs_to_many :bars

  accepts_nested_attributes_for :bars
end

class Bar < ActiveRecord::Base
  belongs_to :project, inverse_of: :bars
  has_and_belongs_to_many :foos

  validates_presence_of :project
end

proj = Project.create
foo  = Foo.new(project: project, bars_attributes: {0 => [name: "first bar"]})
foo.save! #-> Bar is invalid

Foos and Bars both belong to a Project, and a habtm relationship joins them...
I want to be able to create new Foos for the Bar, and have them belong to the Bar's project... but the project validation is failing.
I'm doing this through ActiveAdmin, but I'm trying to solve it at the model/relationship level before getting hacky with InheritedResources overrides...


text:
Q: I'm wanting to create a separate file of every member who joins the server and then be able to chose them randomly for a 'winner' command sorta thing So I am using discord.js or Visual studio code or whatever. and I've made a random hug command. And I would like to be able to have it so that the one that gets hugged doesn't get @ and it's just their name. I've successfully made a command similar to it, but i don't want to have to keep adding in names manually and theres no promise that the member won't change their name so it's not very reliable.
So I guess what's in my mind is having a file that automatically updates with users leaving or joining or changing their names and then to be able to call on them randomly without @ing them.
So does anybody know how to do this and how i can call on them?
I've done it with the @, and now im at where I manually write in every member's name but I know that is going to end up tedious and their name might change and I don't want to have to worry about them changing their name.
case 'randhug':

        var user = message.guild.members.random();
        let dismember = ["Klemon", "Second sofira", "CloudBot"]
        let disresults = Math.floor((Math.random() * dismember.length));
        message.channel.send(`${message.author} SURPRISE huggies you, ${dismember[disresults]}!!!!!`);
        if (message.author.bot) return;
        break;

The code I have now works, but isn't reliable in the sense that things change.

A: It sounds like you might find the tag or username properties of a User very valuable in this situation.
User.tag would return Username#1234.
User.username would return Username.
const member = message.guild.members.random();

message.channel.send(`${message.author} surprise huggies you, **${member.user.username}**!`)
  .catch(console.error);


text:
Q: How to get several values from the same it.next() List<Drank> dranken = admin.getBestelling().getDranken();
Iterator<Drank> it = dranken.iterator();
while (it.hasNext()) {
     String name = it.next().getName();
     String description = it.next().getDescription();
     model.addRow(new Object[]{name,description});
}

This is our code. We want to loop through the array.
The problem is that if you use it.next() it always goes to the next value, and because we have getName() and getDescription() it always skips either the name or the description, making value's not match with each other,
any suggestions?

A: Use a variable to store the next element.
 Drank next = it.next();
 String name = next.getName();
 String description = next.getDescription();

A: Use it.next() only once, and get the result in a Drank variable, as @user1906108 shew you.
Alternatively, you can use the enhanced for loop, and totally get rid of the iterator's code:
ArrayList<Drank> dranken = admin.getBestelling().getDranken();

for (Drank d : dranken) {
     String name = d.getName();
     String description = d.getDescription();
     model.addRow(new Object[]{name,description});
}

Or even shorter, as you don't really need extra variables here:
ArrayList<Drank> dranken = admin.getBestelling().getDranken();

for (Drank d : dranken) {
     model.addRow(new Object[]{ d.getName(), d.getDescription()});
}

A: Change it to this
while (it.hasNext()) {
     Drank item = it.next();
     String name = item.getName();
     String description = item.getDescription();
     model.addRow(new Object[]{name,description});
}


text:
Q: Как найти и заменить выражение в файле? Мне нужно найти и заменить слово или выражение в файле, на свое, разумеется. Например, у меня есть файл file.xml:
<title name="Article">Article</title>
<title name="article_1">text Article text</title>

Мне нужно заменить слово Article только внутри скобок ><. Я пробовал работать с perl через cmd:
perl -p -i -e "s/article/myText/gi" file.xml

но при составлении выражения замены с регулярными выражениями получается так, что происходит замена не одного слова, а всего, что я указал. Мне нужно, чтобы производилась замена только одного слова - article.

A: perl -p -i -e 's/(\G|>)[^<>]*?\Karticle/myText/gi' file.xml

\G - обозначает точку входа в выражение после последней произведенной замены. Таким образом (\G|>) будет искать последующий текст сразу после конца тега и после произведенной замены продолжит искать тот же текст с точки где эта замена произошла. \K - обозначает точку, все выражение до которой считается предварительной проверкой в само совпадение для замены не входящее.
Пример на regex101.com

A: Например, так:
#!/usr/bin/env perl

use Modern::Perl;
use Data::Printer;
use XML::Simple;

my $xml = XMLin( 'data.xml' );
p $xml;
replace_content( $xml, 'article', 'myText' );
p $xml;
say XMLout( $xml );

sub replace_content
{
  my ($xml, $what, $to) = @_;
  # доп. проверки пропущены для наглядности
  if( ref $xml eq 'HASH' ) {
      $xml->{content} =~ s/$what/$to/igs if $xml->{content};
      replace_content( $xml->{$_}, $what, $to ) for keys $xml;
  }
}

NB! Вывод XMLout() может отличаться от оригинала. Если это критично - можно поиграться с ключами (см. документацию, вопрос "XML::Simple, вывести такую же XML как на входе" и т.д.).

A: perl -i-n -p -e "s!>article<!>word<!igs" file.xml


text:
Q: Getting details from photo I'm working on an app that involves getting information from a photo that is taken with the in-built camera of the iPhone.
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;

picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:picker animated:YES];

I would like to get the info on date/time of capture as well as the coordinates of the place of capture. Any idea how I would do this?

A: Using the Asset framework you can do this:
  #import <AssetsLibrary/AssetsLibrary.h>

  ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
  NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL];

  [library assetForURL:url resultBlock:^(ALAsset *asset) {
    NSLog(@"TIMESTAMP: %@", [asset valueForProperty:ALAssetPropertyDate]);
  } failureBlock:^(NSError *error) {
      NSLog(@"FAIL");
  }];


text:
Q: Unable to communicate with arduino using QSerialPort if the arduino-ide has not opened the connection before I am using the following code to open a serial port to communicate with the arduino.
  const qint32 baud = Global::getInstance().getSettings().value("Hardware/baudRate", 115200).toInt();
  const QString portName = Global::getInstance().getSettings().value("Hardware/port", "COM3").toString();
  port.setPortName(portName);

  if(!port.open(QIODevice::ReadWrite))
  {
    qFatal("Unable to open serial port");
    exit(1);
  }
  if(!port.setParity(QSerialPort::NoParity) ||
     !port.setStopBits(QSerialPort::OneStop) ||
     !port.setDataBits(QSerialPort::Data8) ||
     !port.setFlowControl(QSerialPort::NoFlowControl ) ||
     !port.setBaudRate(baud))
  {
     qFatal("Unable to configure serial port");
     exit(1);
  }
  if(port.error() != QSerialPort::NoError)
  {
    qFatal("some error occurred!");
    exit(1);
  }

Afterwards I try to read from the connection using the following code:
bool Light::waitForReady()
{
  char data[1];
  data[0] = -1;
  if(port.waitForReadyRead(10000))
  {
    const int numRead = port.read(&data[0], 1);
    if(numRead == 1)
    {
      return data[0] == (char)RDY;
    }
    else
    {
      qWarning("Read error, read %d bytes", numRead);
    }
  }
  else
  {
    qWarning("Read timeout");
    return false;
  }
  return false;
}

The read does not work, it times out after waiting for 10 seconds.
However when I open and close the serial monitor inside the arduino-ide before running my QT code it works. My guess is that the ardunio-ide does something to the port that I am missing but as far as I can tell I am using the exact same settings as the arduino-ide to open the serial port.
This is the code that is running on the arduino:
void setup()
{
  Serial.begin(115200);
  Serial.write(RDY);
}

This guy has had a similar problem and he compared the serial port settings of putty and QSerialPort. He found that the settings fDtrControl, fOutX and fIutX differed. I tried changing fDtrControl but it had no effect. I do not know how to set fOutX and fIutX using QT.
Any ideas what might be causing this bug?
edit:
Solution: port.setDataTerminalReady(true) was missing

A:
I do not know how to set fOutX and fIutX using QT.

Please read my answer is in here.
Also be convinced that the Putty (or your arduino-terminal) configuration (parity, flow control, baud rate) are same as QSerialPort configuration. In addition, you can try the Terminal example (from the QtSerialPort examples), e.g. instead of Putty (or your arduino-terminal).
UPD:
You can try to add:
setDataTerminalReady(true);

and
setRequestToSend(true);

after opening of port.


text:
Q: Java Parallel Programming Performance suggestion I am building option valuation (binomial tree) using java . My binomial tree with normal sequential code with 1000 steps takes 0.1 second . But when i try to run it using parallel it takes about 65 seconds . Any suggestion and input will be appreciated..
Binomial Thread is my class which does the calultion
ThreadPoolExecutor threadExecutor = new ThreadPoolExecutor(10000, 10000, 500,
       TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),
       new ThreadPoolExecutor.CallerRunsPolicy());

for (int i = 0; i < 10000; i++) {
Runnable thread = new BinomialThread();
threadExecutor.execute(thread);
}

A: If the number of threads is greater than the number of processors and there is no waiting time (for example waiting from network data, reading from a file and so on) the performance degrades instead of increasing for the time needed to switch from one process to the other.
You have 10.000 threads, that's why your program take more time in a multithreading environment than a single thread environment.

A: For an N cpu processor. The optimal number of threads should is N+1.(Check Java Concurency in Practice Chapter 8). Once you create threads beyond this number(for compute intensive tasks), performance starts to decrease because of the context switches involved. Thus this explains the numbers you were getting.
To determine the number of cpus:
int N_CPUS = Runtime.getRuntime().availableProcessors();

You then should configure the executor to N+1 threads.


text:
Q: Purpose of OnModelCreating - EF Core Database first Approach I am studying EF Core with database first. There is no issue to get entities and DbContext after reverse-engineering. But I couldn't understand the role(or purpose) OnModelCreating Method in DbContext(database first approach).
Here is code snippet.
public partial class VitiLevuContext : DbContext
{
    public virtual DbSet<Order> Orders { get; set; }
    public virtual DbSet<Invoice> Invoices { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Invoice>(entity =>
        {
            entity.ToTable("Invoice");
            entity.Property(e => e.DueAmount)
            .IsRequired();
            entity.Property(e => e.PaidAmount).HasColumnType("money");
            entity.HasOne(d => d.Order)
                .WithMany(p => p.Invoices)
                .OnDelete(DeleteBehavior.Cascade)
                .HasForeignKey(d => d.OrderId)
                .HasConstraintName("FK__Invoice__OrderId__44FF419A");
        });
        modelBuilder.Entity<Order>(entity =>
        {
            entity.ToTable("Order");
        });
        OnModelCreatingPartial(modelBuilder);
    }
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

Database has a relation and "NOT NULL Contraints".

*

*ALTER TABLE [dbo].[Invoice] ADD  FOREIGN KEY ([OrderId]) REFERENCES [dbo].Order     ON DELETE CASCADE.

*ALTER TABLE [dbo].[Invoice] ADD [DueAmount] int NOT NULL

The OnModelCreating method represents well. I created very simple Rest API project and tested add/delete for Order/Invoice.
"NOT NULL Constraints" and "Cascade deleting" may be verified on database not EF model side.
(In case of creating an invoice instance with null DueAmount, I expected exceptions before submitting to SQL)
My question is very simple.
Can I delete "OnModelCreating" method if don't consider migration?
(I thought the OnModelCreating method is only for migration purpose.)

A: If you follow the Entity framework model naming convention and your model directly reflects your database table name, column names and so on, you don't need the OnMOdelCreating method. This is because the entity framework will generate the binding behind the scene.
But, if you want customization, for example, your model field name does not match your database table column name, you configure that on the OnModelCreating method. Another way of using this configuration is called fluent API.
This doesn't mean you have to use the OnModelCreating method. There are other options for customization. Which is DataAnotation.
For example:
If you have a model named User...
public class User
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string Password { get; set; }
}

on your DbContext, you set the following
public AppDbContext : DbContext
{
   public AppDbContext(DbContextOptions<AppDbContext> options) {}

   public DbSet<User> Users { get; set; }
}

So, by convention, the Entity framework expects

*

*A table named Users, because of the name you used on the DbSet property for the User model.

*It uses Id as the primary key.. because the model property name Id

Entity framework will set this all up for you.
When we come to the custom configuration, let's say your model property name Password is not the same as the Users table column name Pwd. You have to tell the entity framework in one of the following ways.

*

*using the OnModelCreating method (fluent API)
 protected override void OnModelCreating(ModelBuilder modelBuild)
 {
     modelBuilder.Entity<User>(entity => {
          entity.Property(p => p.Password)
                .HasColumnName("Pwd");
     })
 }

*The other way is Data annotation
 public class User
 {
     public int Id { get; set; }
     public string FullName { get; set; }

     [Column("Pwd")]
     public string Password { get; set; }
 }


text:
Q: GROUP BY interval overlapping timestamp MySQL query I've been reading other questions and had no luck. I have a table with columns (stamp,value). The 'stamp' column stores hourly timestamps. What I'm trying to do is to retrieve SUM(value) for intervals of 24 hours depending on a range of timestamps specified in the query:
SELECT stamp,
       Sum(value)
FROM   table
WHERE  stamp >= Date_sub('2012-12-02 05:00:00', INTERVAL 1 day)
       AND stamp < '2013-01-01 05:00:00'
GROUP  BY Date(stamp)

The result I'm looking for would look like this:
stamp                      value
2012-12-02 05:00:00        12024
2012-12-03 05:00:00        11211
2012-12-04 05:00:00        19834
...
2013-01-01 05:00:00        10232

Actual table looks like this:
stamp                      value
2012-12-01 01:00:00        345
2012-12-01 02:00:00        100
2012-12-01 03:00:00        104
2012-12-01 04:00:00        103
2012-12-01 05:00:00        101
2012-12-01 06:00:00        102
...
2013-01-01 05:00:00        207
2013-01-01 06:00:00        307
2013-01-01 07:00:00        223
...

*Note that the stamp column's datatype is timestamp

A: I think you just want to set the hours to 5, to be consistent with your range.  If so, you can do this:
SELECT cast(date(stamp) as datetime) + interval 5 hour
       Sum(value)
FROM   table
WHERE  stamp >= Date_sub('2012-12-02 05:00:00', INTERVAL 1 day)
       AND stamp < '2013-01-01 05:00:00'
GROUP  BY Date(stamp)

But, I think you might actually want to phrase this a bit differently:
SELECT cast(date(stamp - interval 5 hour) as datetime) + interval 5 hour
       Sum(value)
FROM   table
WHERE  stamp >= Date_sub('2012-12-02 05:00:00', INTERVAL 1 day)
       AND stamp < '2013-01-01 05:00:00'
GROUP  BY Date(stamp - interval 5 hour)

This actually realigns the dates on the 5-hour boundary.
Note:  these queries are untested, so may contain syntax errors.
This is assuming that the timestamp is really a datetime.  If it is a UNIX timestamp, you need to convert it first.


text:
Q: what is difference between console.time() vs Date.now() in javascript and which one is better performance I have written some nodejs code and I am logging api call response timing.
console.time() and Date.now() but I am not sure which one is better in performance and right to use.

A: Date.now() just returns the number of milliseconds from the linux Epoch, whereas
console.time() is a shortcut to be used together with console.timeEnd(), normally used for measuring the time that takes some operation, for example:
console.time()
doSomething()
console.timeEnd()

The output will be something like:
default: 7042.885ms

You can read more about it here:https://nodejs.org/api/console.html#console_console_time_label


text:
Q: Switch to new browser opened after click on a button [Python][Selenium] I have a situation where I click on a button that opens up a new browser Window. Is there any way to connect to the newly opened  window? And work with it, then return back to original browser (first window).
Thank you.
After some thorough investigation on the net I managed to get some of the code working
Currentwindow = driver.window_handles
Likebutton = driver.find_element_by_css_selector(".single_like_button .btn3").click()
newwindow = driver.window_handles
newwindow = list(set(newwindow) - set(Currentwindow))[0]
driver.switch_to.window(newwindow)
driver.find_element_by_id("watch-like").click()
driver.implicitly_wait(5)
driver.close()

Problem is the command driver.implicitly_wait(5) doesn't work for some reason and the page automatically closes which is not something I want.
How do I get it working?

A: driver.switch_to.window(handle)

switches the focus to the specified window. handle can be a name or window handle.
You can use
driver.window_handles

to find a list of window handles.
There are also these functions which you may find useful:
driver.switch_to.active_element
driver.switch_to.default_content
driver.switch_to.parent_frame
driver.switch_to.alert
driver.switch_to.frame
driver.switch_to.window

A: too late for you , but maybe this will help someone
driver.implicitly_wait(5)

this command wait , while the page is loaded or 5 sec.
If it will be loaded in 1 sec , then
driver.close()

Run after 1 second .
If it be loaded in 7 sec , then
driver.close()

Run after 5 sec
You may use
import time

time.sleep(5)

It will wait exactly 5 sec anyway


text:
Q: How can i get WWDC10 sample code? (104. Designing Apps with Scroll Views) i saw WWDC10 session "104, Designing Apps with Scroll Views".
and i want get sample code using demo. but i can't find it.
i found "ScrollViewSuite" but it's not same demo.
it's not provided?

A: *

*Login to http://developer.apple.com with your Apple developer ID.

*Click on videos.

*Choose any one of the option HD/Standerd to view in iTunes.

*In iTunes you can find the link at Bottom right to the Sample code
You can find all WWDC 2010 sample code there

EDIT: Sample code is under
  wwdc10samplecode\WWDC10-SampleCode\iOS\PhotoScroll


text:
Q: postgres function takes parameter bytea while calling insted of varchar ERROR:  function dharani.fn_generate_ror_1b_citizen(bytea, character varying) does not exist at character 15
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
STATEMENT:  select * from dharani.fn_generate_ror_1b_citizen($1,$2)

ERROR:  function dharani.fn_generate_pahani_citizen(bytea, bytea, character varying) does not exist at character 15
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
STATEMENT:  select * from dharani.fn_generate_pahani_citizen($1,$2,$3)

A: You have to supply function arguments of the appropriate type, if necessary using type casts as the hint says.
SQL is a typed language, and PostgreSQL uses function overloading, so it is essential the data types are resolved properly. The exact rules how this is done are in the documentation.


text:
Q: Correct way to allocate and free arrays of pointers to arrays I want to create an array of pointers to arrays of 3 floats. What is the correct way to do this?
float *array1[SIZE]; // I think it is automatically allocated
// OR
float **array1 = calloc(SIZE, sizeof(float*));
free(array1);

for (int i = 0; i < SIZE; i++) {
    array1[i] = (float[]){0,0,0};
    // OR
    array1[i] = calloc(3, sizeof(float));
}

Then how would I free the data? I'm pretty sure just free(array1); wouldn't work, so would I free each pointer in the array then free the array, or since I allocated three floats, would I free each float, then each 3 float array, then the whole array???

A: If you know the array size at compile time (and you do, if SIZE is a compile-time constant), you should just declare a two-dimensional array. You don't need to free this at all (and must not).
float array1[SIZE][3];

You need to use calloc, and to create an array of pointers, only if the dimensions are not known at compile time. In this case, there should be one call to free for each call to calloc. And since you cannot use an array after you free it, you need to free the row arrays before you free array1.
float **array1 = calloc(nrows, sizeof (float *));
for (int i=0; i < nrows; i++)
    array1[i] = calloc(3, sizeof(float));
// Use it...

// Now free it
for (int i=0; i < nrows; i++)
    free(array1[i]);
free(array1);

Edit: if you won't be rearranging the pointers (to sort the rows in-place, for example), you can do all of this with just one calloc (and one call to free afterwards):
float (*array1)[3] = calloc(3*nrows, sizeof (float));

That's because the number of columns is known at compile-time, and that's all the pointer arithmetic needs to know. Then you can write things like array1[i][j], and you can still pass around array1[i] as if it was a real pointer to a row. C is great that way, take advantage of it!

A:
I want to create an array of pointers to arrays of 3 floats. What is the correct way to do this?

Why do you want an array of pointers to arrays? Wouldn't an array of arrays be sufficient? (Keep in mind that arrays are already pointer-like, they are not passed by value, rather the address of the first element is passed when an array is passed as an argument to a function).
// stack allocation, no need to free
float array[SIZE][3];

for (int i = 0; i < SIZE; i++) {
    // do something with array[i][0], array[i][1], array[i][2]
}

Then how would I free the data?

In this case you wouldn't, since the data is stack allocated (will be cleaned up automatically once out of scope). Just remember the rule of thumb is that for every memory allocation you make, a corresponding free is necessary. So if you allocate memory for an array of floats, as in
float* arr = malloc(sizeof(float) * 3); // array of 3 floats

Then you only need to call free on the array that you malloc'd, no need to free the individual floats. If you perform nested allocation as in
// array of length SIZE, consisting of float pointers
float** arr = malloc(sizeof(float*) * SIZE);

// allocate the array of 3 floats at each index
for (int i = 0; i < SIZE; i++)
    arr[i] = malloc(sizeof(float) * 3);

Then you will need to perform a free for every malloc, as in
// free the individual arrays
for (int i = 0; i < SIZE; i++)
    free(arr[i]);
// free the array of arrays
free(arr);

The lesson to take away here is to avoid dynamic allocation of arrays all-together. Stick with either std::vector or stack-allocated arrays.

A: A general rule is that for each time you call malloc() or calloc() you will need to do a free() call on the returned pointer.
If you want a two dimensional array with compile-time known size, just use a two dimensional array! float val[5][3] is perfectly valid.
If you want a two dimensional array and you don't know it's size during compile-time, you most probably want to use a standard, single diemensional calloc() and an appropriate getter.
#define ARR_COLUMNS 10
#define ARR_ROWS 10
float* arr = calloc (ARR_COLUMNS * ARR_ROWS, sizeof(float));

int get(float* arr, int x, int y) {
  if (x<0 || x>= ARR_COLUMNS) return 0;
  if (y<0 || y>= ARR_ROWS) return 0;
  return arr[ARR_COLUMNS*y+x];
}

void set (int* arr, int x, int y, float val) {
  if (x<0 || x>= ARR_COLUMNS) return;
  if (y<0 || y>= ARR_ROWS) return;
  arr[ARR_COLUMNS*y+x] = val;
}

Of course replace the defines with appropriate variables.
By doing so you will:

*

*save yourself costly allocs and frees

*have less fragmented memory

*simplify your possible realloc calls

*ensure the data is cached better and accessed without the common [x][y] vs [y][x] iteration cache problem.


text:
Q: HTML Agility Pack - Get div without class or id (C#) I've been trying to follow some solutions here on StackOverflow but I need some help.
This is the source HTML:

 STRING_N1

 STRING_N2

And this is my current code:
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(htmlcode);
        var res = doc.DocumentNode.SelectNodes("//div[@class='myclass']");
        foreach (var item in res)
        {
            var firstDiv = item.SelectSingleNode("div");
            var content1 = firstDiv.ChildNodes[0].InnerText.Trim();
            richTextBox1.AppendText(content1.ToString());
        }

So far so good, I can extract "STRING_N1" without a problem. However, I can't figure it out on how to extract STRING_N2 without having a class or id.
Thank you.

A: You can use LINQ to get descendant divs:
var divs = doc.DocumentNode.SelectNodes("//div[@class='myclass']")
              .SelectMany(x => x.Descendants("div"));

var contents = divs.Select(x => x.InnerText.Trim());

richTextBox1.AppendText(string.Join(Environment.NewLine, contents);


text:
Q: Getting overflow-y:scroll to work with fixed positioning html & css I have a Jquery tools scrollable thats set to be fixed to the bottom of the browser window.
All I want to happen is for the page to be able to scroll vertically when the browser is less then 700px high. (so no content gets hidden, as its all fixed place). This feels like it should be simple but its causing me huge headaches. js solutions are fine at this point.
Thanks in advance.
http://www.vagabondbrigade.com/staging/berns/

A: If you are referring to the content that is being cut off at the top of the page, I would recommend putting top and bottom margins on your css page to the proper elements to harness their positioning.
You could do a fixed height or width for the main structure of the page and then the other elements that you want positioned, position them accordingly.
example:
/* html */

      blah blah blah

/* css */
#main_structure {width:100%; height:700px; margin:20px 20px 20px 20px; padding:20px;}
#content {width:200px; height:200px; padding:10px; margin:20px;}

A: Playing with Firebux on your page (the link that you've provided), I've added at div.floor_items a property overflow:auto; and the problem was fixed ;)
The content was bigger that my test screen resolution, and the content wasn't all visible, but with that change, the scroll bar appeared and allow me to scroll and view the "off screen" content!
This is your solution, if that was your problem!

A: Have you tried using css media queries
either by adding  overflow-y: scroll to html or your containing element?
http://www.w3.org/TR/css3-mediaqueries/
@media screen and (max-height: 700px) {
       #your_element_to_scroll {overflow-y: scroll;}
}

This will not work in older version of IE.


text:
Q: Django Calculated fields do not appear in get_fields() I have a calculated field in a model.
class SfShifts(models.Model):
    pr_id = models.PositiveIntegerField(primary_key=True, db_column='pr_id__c')

    def _get_calculated_field(self):
        return {'cal': self.pr_id}
    calculated_field = property(_get_calculated_field)

But when I call get_fields() I don't get it.
field_list = [field.get_attname_column() for field in self.model._meta.get_fields()]

How can I get the calculated field name too?

A: You can try
import inspect

field_list = [f for f, _ in inspect.getmembers(field) if f[0] != '_' ]

It will contain properties as well. However, it will also contain some additional stuff such as "validate_unique", "save" etc, but they are Django-related so can be tracked and excluded manually.
I.e.
django_reserved = set(x for x, _ in inspect.getmembers(models.Model))

# add properties that are not included in base model
django_reserved.add('DoesNotExist')
django_reserved.add('MultipleObjectsReturned')

field_list = [f for f, _ in inspect.getmembers(field) if f[0] != '_' and f not in django_reserved ]

This will give you only the list of fields/properties that are related to the specific model


text:
Q: PHP can't create file, permission denied I am trying to run some PHP applications on CentOS powered server with apache and MySQL. My apps have to create files on server, but it always says that permission is denied to create a file.
Files are located in /var/www/html. I even tried setting 777 permission to html folder and html/*. I changed apache user and group to myuser, that exists, and restarted apache. I changed the ownership of html folder and all files inside to myuser. I even tried changing document root to /home/myuser/public_html
I tried this code to test write permission. File location is /var/www/html/index.php and /home/myuser/public_html/index.php
$handle = fopen("a.txt", "w");
fwrite($handle, "test");
fclose($handle);

I am just more than amazed by this problem. The same configuration works on my another Ubuntu server.
Some geniuses must be here, help me.

A: You need to allow you server user to do write operation on your directory, User the below command, If it is a multilevel directory use -R flag.
sudo chown www-data my-dir

A: Instead of manually giving permission you can try chmod($handle, 0777) within your code.


text:
Q: How to print values using form data? I want to print form data values using formdata.entries function? Reason being I have multiple ng-repeat.

            Coupon Code

            {{coupon.title}}

    <input type="text" name="newcoupon" ng-model="newcoupon" required />
    <button ng-disabled="couponsFrm.$invalid" ng-click="addcoupon()" class="btn btn-primary">Add Coupon</button>

And this is the controller
$scope.submitTrType = function(){
    var formData = new FormData("#my-form");
    console.log(formData);
    formData.append('key1', 'value1');
    formData.append('key2', 'value2');
    for(var pair of formData.entries()) {
        console.log(pair[0]+ ', '+ pair[1]);
    }
}

A: Try this one:
for (var value of formData.values()) {
                alert(value);
           }

A: You have to define ng-model for every text box in the form. Then you can access these text box values in your "submitTrType " function by using $scope.textBox1 (example variable name).

A: You will not get values of the form element using FormData. If you really need it then you can do something like this
var formElements = document.forms['my-form'].elements['nameOfFormElements'].value;

or use JQuery or javascript to get the form values. This is because the FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data".
And if you try to use key/value pair of formData then for this
var formData = new FormData();
formData.append("phone", "1234567890");
formData.append("phone", "9876543210");
formData.get("phone");

This will only return the first phone for that key, in this case it will return '1234567890'. And this may behave unusual in different browsers.


text:
Q: Reordering columns in html table with Angularjs I have a set number of available columns in html table. As soon as the user will filter out which columns they want I'm displaying the table with the selected columns only.
Now, I want to give the option to the user to also set the order of the columns displayed, which column to come first, which second. I have the list and the functionality for reordering the columns in a select list ready, please check the screenshot below:

I want to know how can I actually sort the columns in the table in the same order as they are set in the list on the right.
This is the code I have so far:

                                    Description
                                    Device ID
                                    Update Required
                                    Open Time
                                    Open Time Ada
                                    Keypad Code

{{v.description}}

{{v.extdoorid}}

YesNo

{{v.opentime}}

{{v.opentimeada}}

{{v.keypadcode}}

A: One suggestion is using an array for the current selected columns and of course an array for the current displayed assets.
I created a sample just for demonstration of the logic.
$scope.columns = [
    {id: "col1", description: "col 1", show: true},
    {id: "col2", description: "col 2", show: true},
    {id: "col3", description: "col 3", show: false},
    {id: "col4", description: "col 4", show: true}
];

$scope.assets = [
    {col1: "Some value 1", col2: "Another value 1", col3: "Col 3 1", col4: "Val. 1"},
    {col1: "Some value 2", col2: "Another value 2", col3: "Col 3 2", col4: "Val. 2"},
    {col1: "Some value 3", col2: "Another value 3", col3: "Col 3 3", col4: "Val. 3"}
];

And a simple table in html is:

      {{column.description}}

      {{asset[column.id]}}

If you change the order of the columns inside $scope.columns array, you will see the change happening in html table (through ng-repeat directive).
Hope you get some useful tips and ideas to fit your needs.


text:
Q: Отправить данные(таблицу) в outlook? Добрый день, есть приложение в котором есть формуляр. Его мы наполняем данными и хотим отправить письмом некоторым пользователям. Что хотим реализовать: чтобы человек открыл письмо в outlook(!) и там в body была таблица с данными, которые мы послали. Перенести html table через mailto нельзя, какие есть способы подобного решения? Как автоматизировать, чтобы кажыдй раз в ручную не создавать таблицу там и не вписывать данные.
Спасибо


text:
Q: How to terminate a windows console application that has not associated process? I have an application the when launched in debug mode in visual studio will some times hang but not have an associated process.
The console windows is there, but it does not respond to exit or Ctrl-C.
It prevents me from rebooting as well.
Is there a way to kill this console session?

A: Have you looked with Process Explorer from Sysinternals (free) where it has a "target" that you can use to click a window and it will highlight from the list what the program is associated with to kill it or get information?

A: Known issue with debugging in XP and Server 2003.

A: To exit the console windows just change the return type of the main() to int  and put the return 0; in the last of the main() function. console window automatically terminates.


text:
Q: Is integer column index faster than string column index in case of index range scan? I have a database implementation task on SQL Server, where there is a table A containing a column - yearMonth. I don't need date operations such as calculating how many days or month between two dates etc. currently. The yearMonth can be defined as Date, Int, or varchar(6). From the perspective of saving data space, 4-bytes Int is obviously the best choice as only 6-digit int is needed e.g. 201701. Whereas varchar(6) occupies 6 bytes, Date occupies 2x4 bytes. (applied for most databases)
But what about from the perspective of indexing, esp. in case of index range scan?

*

*If the column yearMonth is defined as varchar(6), the index range scan can happen when using query select .. from A where yearMonth IN (...)

*If the column yearMonth is defined as Int or Date, then index range scan can happen with operator like <=, <= etc.

In the cases above, which type of column definition is more efficient when index range scan happens?

A: Most (if not all) DBMS essentially store a date as an integer anyway, and for DateTime it is two integers, one for the date and one for the time, so there will be little or no difference between the two. I think your biggest consideration would be how you intend to use the column, if you want to do any kind of date operations on the column, then store it as a date (defaulting to the 1st day of the month). For instance, if you want to know how many months between 201604 AND 201701 it is easier using a date, if you want to format your value as something like April 2017 it is a lot easier if it is stored as a date.
Another consideration is validation, if you have a varchar(6) or int, you would need additional check constraints to ensure that any value entered is in fact a valid date, anyone could easily enter 999999, and while the year is valid, the month is not, and for varchar the possibilities are endless for the nonsense that can be entered.

Now that you have tagged SQL Server I can answer more definitively - both DATE and INT take up 4 bytes of storage so there iS no space saved, and from testing both perform pretty much exactly the same (date performs marginally, but not significantly better and often with fewer reads), so there is no benefit to using int (unless you don't want to be restricted to just valid dates)
I have done some quick tests using the following schema:
CREATE TABLE dbo.TDate (ID INT IDENTITY(1, 1) PRIMARY KEY, DT DATE NOT NULL);
INSERT dbo.TDate (DT)
SELECT TOP 100000 DATEADD(MONTH, RAND(CHECKSUM(NEWID())) * 300, '20000101')
FROM sys.all_objects a, sys.all_objects b;

CREATE NONCLUSTERED INDEX IX_TDate_DT ON dbo.TDate (DT);

CREATE TABLE dbo.TInt(ID INT IDENTITY(1, 1) PRIMARY KEY, DT INT NOT NULL);
INSERT dbo.TInt (DT)
SELECT (DATEPART(YEAR, DT) * 100) + DATEPART(MONTH, DT)
FROM dbo.TDate;

CREATE NONCLUSTERED INDEX IX_TInt_DT ON dbo.TInt (DT);

Then running this to compare performance
DECLARE @D1 DATE = (SELECT TOP 1 DT FROM dbo.TDate ORDER BY NEWID());
DECLARE @D2 DATE = (SELECT TOP 1 DT FROM dbo.TDate WHERE DT > @D1 ORDER BY NEWID());
DECLARE @I1 INT = (DATEPART(YEAR, @D1) * 100) + DATEPART(MONTH, @D1),
        @I2 INT = (DATEPART(YEAR, @D2) * 100) + DATEPART(MONTH, @D2);

SET STATISTICS IO ON;
SET STATISTICS TIME ON;

SELECT  COUNT(*)
FROM    dbo.TDate
WHERE   DT >= @D1
AND     DT < @D2;

SELECT  COUNT(*)
FROM    dbo.TInt
WHERE   DT >= @I1
AND     DT < @I2;

SET STATISTICS IO OFF;
SET STATISTICS TIME OFF;

A: Int should be more faster than Varchar(6), as it takes less space.
SQL SELECT speed int vs varchar

A:
But what about from the perspective of indexing, esp. in case of index range scan?

Range scan fastness is not limited by type of index,but its effectiveness is limited by fragmentation .Your range scan query will be faster,if fragmentation is less,less fragmentation means all pages are adjacent and not scattered


text:
Q: Cassini: What information could be gained from the 2017 impact with Saturn? First of all:

*

*Will Cassini be operational in 2017 (pending no unforeseen equipment failures)?

*

*Power

*Communications

*...

*What information could we gain?

*

*Properties of Saturn

*How to build more resistant spacecraft for future atmospheric descents and gas planet impacts

A: There are two main science goals for the Cassini death dive into Saturn that I know of.  One of them is simply higher scale imagery of objects closer to Saturn as it journeys inwards.  The other is that it will fly between the planet and the rings, and based upon the radio signals coming back to Earth, we should be able to, for the first time, directly measure the mass of the rings to within around 1019 kg.  This may seem pretty coarse, but there are several specific prediction papers (including one of mine ...) that estimates the ring mass in multiples of the moon Mimas, which has a mass of $3.8\cdot 10^{19}$ kg.
A third that I thought of a few hours after writing this is that the spectrometers on board should be able to sample the saturnian atmosphere during entry and send back detailed composition information, just as it did when flying through the plumes of Enceladus.


text:
Q: String manipulation to truncate string up to a specified expression on C# How do I remove more than three spaces from each line and end the string right there to look the line on the right using c#?
[Example1]
PO BOX XXX                                       OVERDUE - PAY NOW
then transform to
PO BOX XXX

[Example2]
ClientB                                AMOUNT CARRI
then transform to
ClientB

[Example3]
PO BOX 400                                                    FORWARD TO N
then transform to
PO BOX 400

A: var firstColumn = origString.SubString(0, origString.IndexOf("   "));

A: input = "PO BOX XXX                                       OVERDUE - PAY NOW  ";
input = input.Remove(input.IndexOf("   "));

there are 3 spaces in the indexOf paranthesis
Or you can do a split if you dont know if there is a tab or space -
input = input.Split(new char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries)[0];

A: You can do this:
var input = new string[3] { "PO BOX XXX                                       OVERDUE - PAY NOW  ",
                                      "ClientB                                AMOUNT CARRI",
                                      "PO BOX 400                                                    FORWARD TO N  "
                                    };

    for (int x = 0, len = input.Length; x != len; x++)
    {
         input[x] = Regex.Replace(input[x], @"\s{3}[^\n]+", string.Empty);
    }
     //input is ["PO BOX XXX","ClientB","PO BOX 400"]

Using linq:
 var output = input.Select(str => Regex.Replace(str, @"\s{3}[^\r\n]+$", string.Empty));

if you're reading this string from file, you can do this:
var file = @"D:\file.txt";
var lines = File.ReadAllLines(file);
var output = lines.Select(str => Regex.Replace(str, @"\s{3}[^\n]+$", string.Empty)); // is ["PO BOX XXX","ClientB","PO BOX 400"]

A: You can use the string.Split method which results the string[]. Basing on the array count you can take the elements u need.
string base string = "PO BOX XXX OVERDUE - PAY NOW";
string[] delimittedStringArray = baseString.Split(' ');
if(delimittedStringArray.Length > 3)
{
  // Take the data from array
}
else
{
  // Do what ever
}

// I am not sure whether it is Length or Count in the if condition.


text:
Q: How to slow down cassandra to expose eventual consistency issues I have cassandra with table and materialized views. The materialized views are eventually consistent with the table and dev has to be extra careful implementing algorithms against cassandra of not hitting issues like just added item seems to not be there etc.
What I would like is to be able to create test environment where the eventual consistency of the materialized views is on purpose really high - say 5/10ms. This way I will be at easy that if my integration tests do not hit issues they are not there. Right now my integration tests running against very small cluster that seems to do all this very fast, and I have some issues discovered only after hours of ingestion against almost production size cluster which is very expensive.
My question is: How I can slow down cassandra materialized view syncs with the table.

A: From my point of view you are actually trying to solve consistency issues with the wrong concepts.
I mean, if you rely on strong consistency you shouldn't use materialised views because there is only eventual consistency with MV.


text:
Q: Missing disk space on new installation I've installed from scratch Ubuntu 22.04LTS and I found that the available disk space is half of what it should be. This is the second time it happened but in first case I thought it was by my mistake. For some reason cfdisk or fdisk are reporting that the disk size is 32GB:
Disk /dev/sda: 32 GiB, 34359738368 bytes, 67108864 sectors
Disk model: QEMU HARDDISK
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: DBA31C33-C478-435C-BECA-08D640FCA9DC

Device       Start      End  Sectors Size Type
/dev/sda1     2048     4095     2048   1M BIOS boot
/dev/sda2     4096  4198399  4194304   2G Linux filesystem
/dev/sda3  4198400 67106815 62908416  30G Linux filesystem

but unfortunately df reports only half of it:
Filesystem                         Size  Used Avail Use% Mounted on
tmpfs                              795M 1016K  794M   1% /run
/dev/mapper/ubuntu--vg-ubuntu--lv   15G  2.7G   12G  20% /
tmpfs                              3.9G     0  3.9G   0% /dev/shm
tmpfs                              5.0M     0  5.0M   0% /run/lock
/dev/sda2                          2.0G  127M  1.7G   7% /boot
tmpfs                              795M  4.0K  795M   1% /run/user/1000

and there is no space available to resize the partition so the question is what is going on?
Previously I've seen this on NUC device so I can rule out QEMU issues.

A: lvextend -l +100%FREE /dev/ubuntu-vg/ubuntu-lv and then
resize2fs /dev/ubuntu-vg/ubuntu-lv fixed the issue.

A: You have installed Ubuntu with LVM as the disk partitioner. Good man, I salute you. Its a wise choice. But it will act as a more complex environment.
Open up a command prompt and enter the command: sudo pvs
This will tell you what physical disks you have installed. We are expecting to see /dev/sda here and for it to say that the PSize is somewhere in the vacinity of 32GB
Next do sudo vgs
Now you will see the volume groups. we are expecting to see ubuntu--vg (it may be something slightly different) and for it to report how much is used and how much is free. I would expect to see about 15GB free space here.
If that is roughly what you see, then you are good. What you have is the root partition running in 15GB, which should be OK. And about 15GB of free space. Now you have options. The first is that you mount /home in this free space by creating a new logical volume. That way you can separate your files from the Ubuntu OS files, and if you ever need to rebuild Ubuntu from scratch you don't wipe out all your files in the process.  Or you can extend the root partition in to this free space and get all your data back.
But before you do anything, do the command sudo lvs
This will show you what logical volumes you have defined, even if they are not mounted. Just make sure it really is free space, and not a logical volume that is not, for some reason, mounted. This shouldn't be the case, but just be safe before you nuke something important!
If you need further help on this - reach out. LVM is great, its really cool, and at some point it will get you out of a deep hole. But its not trivial!


text:
Q: Any Concurrency Issues with my code I a trying to create a thread-safe method.
Does anyone see any concurrency issues with following code?
To me it seems fine , though I could never find a way to test for concurrency on this method. Any help would be appreciated.
   //static locker for thread synchronization
   private static readonly System.Object _object3 = new System.Object();

   //this method needs to be thread-safe
   public static void LogToTextFile(string logMessage, LogLevel logType)
    {
       //make sure only one thread executes this file writing code at a time
       lock (_object3)
        {
            using (StreamWriter w = File.AppendText(@"c:\logs\log1.txt");
            {
                w.WriteLine("\r\n{0} logged at {1} {2} : {3}", logType.ToString().ToUpper(), DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString(), logMessage);
            }
        }
    }

A: There are no concurrency problems with this code because you are allowing only a single thread to write to the file due to the lock statement.

A: Considering you'e locking around an appropriately-scoped object, I see no concurrency issues with your code.
However, as millimoose mentioned in the comments, you have a potential performance problem. If two threads try to LogToTextFile at the same time, one is going get the lock first, and the other is going to block while the file is opened, written to, and then closed. This may not be acceptable, depending on what your threads are doing.
If what I mention is a problem, you'll have to implement a more complex thread-safe logger. Typically there would be a queue to which log events are quickly written. Then there is another thread who periodically wakes up, and empties the queue to the file on disk. All operations on the queue are done with a lock.

A: Another, possibly better solution may be to leave the file opened, and use a synchronized TextWriter to perform the writes.  TextWriter.Synchronized provides a thread-safe wrapper around a TextWriter:

All write operations to the returned wrapper will be thread safe. You call this method to ensure that only one thread at a time can execute the methods on the TextWriter instance that is returned.

Here's a simple implementation. Note, this has not been tested.
public static class MyLogger
{
    private static TextWriter s_writer;

    // Not thread-safe. Call this before other threads are allowed to call Log.
    public void Open(string filename) {
        s_writer = TextWriter.Synchronized( File.AppendText(filename) );
    }

    // Also not thread-safe.
    public void Close() {
       s_writer.Dispose();
    }

    // Thread-safe.
    public void Log(string logMessage, LogLevel logType) {
        s_writer.WriteLine("\r\n{0} logged at {1} {2} : {3}",
            logType.ToString().ToUpper(), DateTime.Now.ToLongTimeString(),
            DateTime.Now.ToLongDateString(), logMessage);
    }
}

A: There are no concurrency issues within this specific function.  The lock statement will properly moderate access to the inner code.
However there are still potential concurrency issues with accessing @"c:\logs\log1.txt".  It's possible that another part of your application, or another process on the same machine, will try to write to the file at the same time as your code.  Hence it's possible the StreamWriter code will fail even with this lock.
There is no way to work around this type of concurrency issues.  The file system is a shared resource that you have no true capability to protect.  Instead your code needs to accept that the file system access can fail and properly handle that consequence.
Typically when dealing with logging functions I wrap file system access with a try / catch and swallow any exceptions that occur.  Otherwise you run the risk of a logging function failure taking down an application.  That may or may not be acceptable for your scenario.


text:
Q: Can I substitute 'came' for 'have come' in this context? Today I was given a task including following sentences. I would like to know whether or not I could substitute came for  have come.
Here is the sentence:

You came to the party in your own car. It is a 20 minute drive home. At the end of the party your friend asks you to drive him home but you....

We were supposed to finish the "story" . I don´t remember the end but there was something like that I can´t drive him home because (and here I am not sure what tense was used) I have drunk too much .
Then we talked about possible endings. In my opinion " You came" could be substituted for " "You have come" but I understand that the past simple tense is maybe focuisng on the moment (the beginning of the party maybe) when I arrived. Still.....would it be possible to use the present perfect in the same scenario?

A: I don't think so. "You have come" is possible if the party is still going, and the speaker is at it; but reads very oddly if the party has finished. "Came" is possible whether the party is continuing or not.

A: "You came" is past tense. If talking about an event in the past you would say 'You came'. If using past tense, the end of your sentence "your friend asks" should be "your friend asked" to match the past tense.
"Your friend asks" is present tense and so the beginning of the sentence should be "You come to the party". If using present tense you could also say "you have come to the party".
Often imaginary scenarios are described using present tense. "Imagine the following situation, you come to a party...".