text:
Q: c# why is the intersect method returning this? I have two arrays, array testAnswer holds "answers to a exam" and array inputAnswers holds "students answers to the exam".
I am trying to display the correct, and incorrect answers. In other words, trying to show what values testAnswer has that inputAnswers doesnt(incorrect answers), and also the values both arrays have in common(correct answers).
For this I have used the .Except and .Intersect method using linq; however I am getting this weird output:
B, D, A, C

Can anyone PLEASE help me, i've been at this for ages!
MY CODE:
private void button1_Click(object sender, EventArgs e)
  {
      string[] testAnswer = new string[20] { "B", "D", "A", "A", "C", "A", "B",
           "A", "C", "D", "B", "C", "D", "A", "D", "C", "C", "B", "D", "A" };
      string a = String.Join(", ", testAnswer);

     // Reads text file line by line. Stores in array, each line of the
     // file is an element in the array
      string[] inputAnswer = System.IO.File
              .ReadAllLines(@"C:\Users\Momo\Desktop\UNI\Software tech\test.txt");
      string b = String.Join(", ", inputAnswer);

      var inter = inputAnswer.Intersect(testAnswer);
      foreach (var s in inter)
       {
          listBox1.Items.Add(s);
        }
     }

A: Intersect does set intersection, so it discards duplicate values. If you want to compare answers, a better option would be to go through the arrays in parallel:
for(int i=0; i<testAnswer.Length; i++) {
    if(testAnswer[i] == inputAnswer[i])
        listBox1.Items.Add(inputAnswer[i]); // or testAnswer[i], as appropriate
}


text:
Q: insert a list of object to table context.AddObject("User",myuserobjetc)
This add a user to the User table.
how can i insert a list of users to user table(with out looping)?
entity-framework-4

A: I'm afraid you can not do bulk insert with EF4. Here is another topic about that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix "ValueError: invalid literal for int() with base 10: '' occuring. whenever pyobjc is needed including installing pyobjc I need to import a number of packages into python that require installation. From the command line (zsh) I've attempted to use pip, python and homebrew(I'm using Mac OS Big Sur) but get an error when pyobjc is required: "ValueError: invalid literal for int() with base 10: ''". This is the same error I get when trying to install pyobjc (I've tried pip, brew and downloading the source and running setup.py). I've tried using version 2.7 and 3.9 of pip and python. How can I go about debugging this? I see the end of the error:
  File "/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/distutils/dist.py", line 985, in run_command
    cmd_obj.run()
  File "/private/var/folders/hf/7khqn6yn0nz3mny8210jr0380000gn/T/pip-install-ropcjbe2/pyobjc-core/setup.py", line 619, in run
    % (tuple(map(int, get_sdk_level(self.sdk_root).split("."))))
ValueError: invalid literal for int() with base 10: ''

I'm not sure what file to look at to see where this problem is

A: After doing some research, I've found a few threads that shed some light on this subject.
In this forum, there is an explanation of why the error occurs at install.

...the data it's parsing here is the output of /usr/bin/xcrun -sdk macosx --show-sdk-path. That should return the full SDK path on Xcode 5 and later...

It should return something like /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk. The parsing code takes the last path component (MacOSX10.14.sdk), strips off the first 6 characters (MacOSX) and the last 4 characters (.sdk), which should leave just the version number (10.14), which is split on . and the two parts are cast as integers. In your case, this seems to be empty.

I am also running Big Sur, and when I run /usr/bin/xcrun -sdk macosx --show-sdk-path, I get back /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk. The install system removes both 'MacOSX' and '.sdk' to check the version, and then casting the empty string to an integer seems to be the cause of the crash.
I also looked at the PyObjC repository for existing issues, and voila, here is a very recent one: https://github.com/ronaldoussoren/pyobjc/issues/333. As per the developer's comment, this should be fixed with the upcoming release of version 7 of PyObjC.


text:
Q: oracle listagg to return all records for certain values I am trying to create an Oracle query that returns all groups and users for empno 1 & 2. any help is greatly appreciated.
emp table:
 emp_no
 ------
   1
   2

group table:
 group_id  emp_no
  --------  ----
    1          1
    1          2
    2          3
    2          4
    3          5
    3          6

-------------
  result
-------------
 group 1  empno 1, group 1 empno 2, group 2 empno 3, group 2 empno 4

A: It seems the group table is enough for your assignment.
The group table causes errors because of the name. I put it in double apostrophes (Oracle 11g R2).
You can use string functions in the listagg clause.
Even for listagg, you can get certain values using a where clause.   Multi-line results would use the group by clause, which is not the case.
Schema:
CREATE TABLE emp (
  emp_no number
);

CREATE TABLE "group" (
  group_id number,
  emp_no number
);

insert into emp (emp_no) values (1);
insert into emp (emp_no) values (2);

insert into "group" (group_id,emp_no) values (1,1);
insert into "group" (group_id,emp_no) values (1,2);
insert into "group" (group_id,emp_no) values (2,3);
insert into "group" (group_id,emp_no) values (2,4);
insert into "group" (group_id,emp_no) values (3,5);
insert into "group" (group_id,emp_no) values (3,6);

Select:
select
listagg ('group ' || "group".group_id || ' empno ' || "group".emp_no, ', ')
  within group (order by "group".group_id, "group".emp_no) "result"
from "group"
where "group".group_id in (1,2);

Output:

result

group 1 empno 1, group 1 empno 2, group 2 empno 3, group 2 empno 4

Select corresponding to your assignment:
select
listagg ('group ' || "group".group_id || ' empno ' || "group".emp_no, ', ')
  within group (order by "group".group_id, "group".emp_no) "result"
from emp left join "group" on emp.emp_no="group".emp_no
where emp.emp_no in (1,2);

The output you have requested does not match:

result

group 1 empno 1, group 1 empno 2

Edit 1:
As @MT0 have mentioned in the comment, for reversed columns emp_no and group_id in the group table there is a better result for the second select:
CREATE TABLE emp (
  emp_no number
);

CREATE TABLE "group" (
  group_id number,
  emp_no number
);

insert into emp (emp_no) values (1);
insert into emp (emp_no) values (2);

insert into "group" (emp_no,group_id) values (1,1);
insert into "group" (emp_no,group_id) values (1,2);
insert into "group" (emp_no,group_id) values (2,3);
insert into "group" (emp_no,group_id) values (2,4);
insert into "group" (emp_no,group_id) values (3,5);
insert into "group" (emp_no,group_id) values (3,6);

Output:

result

group 1 empno 1, group 2 empno 1, group 3 empno 2, group 4 empno 2

!!I messed the selection to reach the correct output:
select
listagg ('group ' || "group".emp_no || ' empno ' || "group".group_id, ', ')
  within group (order by "group".group_id, "group".emp_no) "result"
from emp left join "group" on emp.emp_no="group".emp_no
where emp.emp_no in (1,2);

Output:

result

group 1 empno 1, group 1 empno 2, group 2 empno 3, group 2 empno 4


text:
Q: images folder is not included in the release build This may be another simple question. I did my research and I couldn't find a way to resolve the issue. I have .net 6 web api project. the project folder does not have a wwwroot folder. I placed images folder within the project root. i.e. src\WebUI\images\ where src\WebUI\WebUI.csproj exists. these images are being used only for email templates.
I had no issues with the development environment. but when I try to deploy files to the server, I noticed that the image folder was not included in the release build.
I have following middleware in program.cs
app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(app.Environment.ContentRootPath, "images")),
    RequestPath = "/images"
});

Could someone please tell me what am I missing here?

A: I've just realized after posting the question that I need to add following to my src\WebUI\WebUI.csproj
<ItemGroup>
  <Content Include="images\*">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </Content>
</ItemGroup>


text:
Q: cmdargs value arguments without equals sign I use cmdargs to write CLI parsers for my Haskell programs.
Let's assume this program, derived directly from their example:
{-# LANGUAGE DeriveDataTypeable #-}
import System.Console.CmdArgs.Implicit

data Sample = Sample {hello :: String} deriving (Show, Data, Typeable)

sample = Sample{hello = def &= help "World argument" &= opt "world"}
         &= summary "Sample v1"

main = print =<< cmdArgs sample

If this program is called cmdtest.hs, I can execute
$ runghc cmdtest.hs --hello=world
Sample {hello = "world"}

However, if I leave off the equals sign (like in the -o option in gcc -o foo foobar.c), cmdargs tries to recognize world as a positional argument
$ runghc cmdtest.hs --hello world
Unhandled argument, none expected: world

Is there any option / annotation I can set to allow this syntax in cmdargs?
Update: Using the short option exposes the same problem:
$ runghc cmdtest.hs -h world
Unhandled argument, none expected: world

Update 2: The FlagInfo data in the cmdargs Explicit module seems to suggest it is somehow possible, at least if using Explicit instead of Implicit

A: Your problem is that you're using opt which makes the value of --hello optional. So --hello world is taken to mean --hello without a value, followed by world as a positional parameter. This is of course a design choice in cmdargs, but I think it's a reasonable one, and it matches the behaviour of most other programs. Take out the opt and see if it works the way you want.


text:
Q: iOS Push Notification on Production Not Working I'm working with push notifications and like 2-3 weeks ago they were working fine on production and dev, but now they stopped working on Production.
I revoked and generated new certificates and provision profiles, but still not working on production.
If I use the dev certificate/provision profile they work.
On production I don't receive any notifications and that's the problem.
Does anyone know where the problem might be?

A: First Check that What is problem u have ?
You use a APN Tester software to check for notification is get or not ?
You can DownLoad APN Tester here => APN Tester for MAC

*

*Using APN Tester notification is get then Problem with your backend Backend problem.

*Using APN Tester Notification is not get then problem with your Certificates.


text:
Q: Android Studio - Can't load resource from some_lib.aar file located in the libs folder (or from the mipmap folder) I searched about this issue and didn't find any answer that related to my problem yet. i hope someone handle this problem before and could help me (-:.

*

*I have an android studio project that have inside the 'libs' folder an
aar library (for example: some_lib.aar).

*Inside the aar library i have the 'mipmap' and 'raw' folders that have
resources inside (The 'mipmap' has PNGs and the 'raw' has sound
file called: sound.wav).

*In my project i'm trying to load some *.png file from the mipmap and
sound file from the 'raw' folder as follows:

Uri soundUri = loadSoundFromLocal(context, "sound.wav");

private Uri loadSoundFromLocal(Context context, String sound) {

    try {

        // Get resource id.
        boolean isGmeResource = true;
        int soundResource = UtilsResources.getResId(sound, R.raw.class);
        if (soundResource == -1 || soundResource == 0) {

            soundResource = UtilsResources.getIdentifier(context, sound, "raw");
            if (soundResource != -1 && soundResource != 0) {
                isGmeResource = false;
            }
        }

        // Create the uri string for the sound file.
        if (soundResource == -1 || soundResource == 0) {

            return RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        } else {

            return UtilsResources.getUriFromResId(context, soundResource, isGmeResource);
        }

    } catch (Exception e) {
        return null;
    }
}

public static int getResId(String resourceName, Class<?> c) {

    if (TextUtils.isEmpty(resourceName)) { return -1; }
    if (c == null) { return -1; }

    try {

        Field field = c.getField(resourceName);
        if (field == null) {
            return -1;
        }

        return field.getInt(null);

    } catch (Exception e) {
        return -1;
    }
}

public static int getIdentifier(Context context, String name, String defType) {

    String appPackageName = UtilsData.getAppPackageName(context);
    if (TextUtils.isEmpty(appPackageName)) {
        return -1;
    }

    if (context.getPackageManager() == null) { return -1; }
    if (TextUtils.isEmpty(name)) { return -1; }
    if (TextUtils.isEmpty(defType)) { return -1; }

    try {

        Resources resources = context.getPackageManager().getResourcesForApplication(appPackageName);
        if (resources == null) {
            return -1;
        }

        return resources.getIdentifier(name, defType, appPackageName);

    } catch (NameNotFoundException e) {

        // Should never happen
        UtilsLogger.e(LOG_TAG, (e != null)? e.getMessage() : "Could not get package name");
        return -1;

    } catch (Exception e) {

        UtilsLogger.e(LOG_TAG, (e != null)? e.getMessage() : "Could not get identifier version code");
        return -1;
    }
}

*I have an exception like this (also for the 'mipmap' folder):

THE EXCEPTION:
Process: com.growmobile.engagement.sample, PID: 20883
        java.lang.NoClassDefFoundError: Failed resolution of: Lcom/growmobile/engagement/R$raw;
        at com.growmobile.engagement.ModelPushMessage.loadSoundFromLocal(ModelPushMessage.java:451)
        at com.growmobile.engagement.ModelPushMessage.parseMessageData(ModelPushMessage.java:375)
        at com.growmobile.engagement.ModelPushMessage.<init>(ModelPushMessage.java:174)
        at com.growmobile.engagement.ManagerNotification.buildPushMessageObjectAndSaveItToDB(ManagerNotification.java:139)
        at com.growmobile.engagement.ManagerNotification.buildGMENotificationObject(ManagerNotification.java:108)
        at com.growmobile.engagement.ManagerNotification.initializeNotification(ManagerNotification.java:77)
        at com.growmobile.engagement.GMEGcmListenerService.executePushAction(GMEGcmListenerService.java:152)
        at com.growmobile.engagement.GMEGcmListenerService.handleMessage(GMEGcmListenerService.java:118)
        at com.growmobile.engagement.GMEGcmListenerService.onMessageReceived(GMEGcmListenerService.java:79)
        at com.google.android.gms.gcm.GcmListenerService.zzq(Unknown Source)
        at com.google.android.gms.gcm.GcmListenerService.zzp(Unknown Source)
        at com.google.android.gms.gcm.GcmListenerService.zzo(Unknown Source)
        at com.google.android.gms.gcm.GcmListenerService.zza(Unknown Source)
        at com.google.android.gms.gcm.GcmListenerService$1.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
        Caused by: java.lang.ClassNotFoundException: Didn't find class "com.growmobile.engagement.R$raw" on path: DexPathList[[zip file "/data/app/com.growmobile.engagement.sample-1/base.apk"],nativeLibraryDirectories=[/data/app/com.growmobile.engagement.sample-1/lib/arm64, /vendor/lib64, /system/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
        at com.growmobile.engagement.ModelPushMessage.loadSoundFromLocal(ModelPushMessage.java:451)
        at com.growmobile.engagement.ModelPushMessage.parseMessageData(ModelPushMessage.java:375)
        at com.growmobile.engagement.ModelPushMessage.<init>(ModelPushMessage.java:174)
        at com.growmobile.engagement.ManagerNotification.buildPushMessageObjectAndSaveItToDB(ManagerNotification.java:139)
        at com.growmobile.engagement.ManagerNotification.buildGMENotificationObject(ManagerNotification.java:108)
        at com.growmobile.engagement.ManagerNotification.initializeNotification(ManagerNotification.java:77)
        at com.growmobile.engagement.GMEGcmListenerService.executePushAction(GMEGcmListenerService.java:152)
        at com.growmobile.engagement.GMEGcmListenerService.handleMessage(GMEGcmListenerService.java:118)
        at com.growmobile.engagement.GMEGcmListenerService.onMessageReceived(GMEGcmListenerService.java:79)
        at com.google.android.gms.gcm.GcmListenerService.zzq(Unknown Source)
        at com.google.android.gms.gcm.GcmListenerService.zzp(Unknown Source)
        at com.google.android.gms.gcm.GcmListenerService.zzo(Unknown Source)
        at com.google.android.gms.gcm.GcmListenerService.zza(Unknown Source)
        at com.google.android.gms.gcm.GcmListenerService$1.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
        Suppressed: java.lang.ClassNotFoundException: com.growmobile.engagement.R$raw
        at java.lang.Class.classForName(Native Method)
        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
        ... 18 more
        Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

*

*I must to say that when the library is imported as a module and not as
*.aar file everything working great!!!

*I need to import the library as *.aar file so I'm stuck and need a
solution soon as possible!

*Is my code OK? if not, What is wrong here?

Thanks for advance for any help from anyone
hope i will get answer quickly (-:


text:
Q: Updating a row in cakephp I need to update a particular row. This doesn't seem to work. Any help is appreciated.
View updated:
<?php
echo $this->Form->create("Setting", array('action' => 'index'));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->checkbox('blog_state');
echo $this->Form->end('Save Post');
?>

Controller updated:
public function index($id = 0){
    $this->Setting->id = $id;
    if (empty($this->request->data)) {
        $this->request->data = $this->Setting->read();
    } else {
        if ($this->request->is('post')) {
            $this->request->data['Setting']['id'] = $id;
            $this->Setting->save($this->request->data);
            $this->Session->setFlash('This should have saved...');
        }
    }
}

Edit:
blog_state is a boolean, and works fine. It loads the value from the DB normally and saves it to the new row normally. (I need it to update the existing row it is being pulled from, which is where my problem is)

A: Update your view:
<?php
echo $this->Form->create("Setting", array('action' => 'index'));
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->checkbox('blog_state');
echo $this->Form->end('Save Page');
?>

You will also need to make sure you set the id in the function so it will populate the value correctly. The record cannot be updated unless it knows the PK ID it is updating.
The way you can accomplish this is by setting it in the request data:
$this->request->data['Setting']['id'] = $id;

Then it will automatically be set in the view.
UPDATE
It looks like your logic may be flawed. The form will not necessarily pass the ID back on the URL. So update you form like so and check again if it works. It looks like the way you currently have it it will set ID to null which will create a new record.
public function index($id = 0){
    if (empty($this->request->data)) {
        $this->Setting->id = $id;
        $this->request->data = $this->Setting->read();
    } else {
        if ($this->request->is('post')) {
            $this->Setting->save($this->request->data);
            $this->Session->setFlash('This should have saved...');
        }
    }
}

A: Well you need to know what row it is effecting (this will usually be argument to your function).
public function index() {
    // Things here
}

This will create the index page for that controller.
Create an edit function like
public function edit($id = null) {
    $this->Setting->id = $id;
    if (!$this->Setting->exists()) {
        // Exception.
    }

    if ($this->Setting->save($this->request->data)) {
        $this->Session->setFlash(__('Saved'));
    }
}

Then you can access it like http://example.com/setting/edit/45

A: Make sure you have primary key id column in your DB if not override the your chosen primary key in model like below.
<?php

class Test extends AppModel{
public $primaryKey = 'primarykey column name';

}
?>


text:
Q: openhtmltopdf / flying saucer: many links in huge PDF are not clickable (PDF annotations not set) I generate huge catalogs (~ 1500 pages) as HTML and convert is via Jsoup to and openhtmltopdf (which uses flying saucer) to PDF. In the resulting PDF many links are not clickable, and I can't find out why.
Consider the following program:
import org.jsoup.helper.W3CDom;
import org.w3c.dom.Document;
import org.jsoup.Jsoup;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

    public static void main(String[] args) throws Exception {

        PdfRendererBuilder pdfBuilder = new PdfRendererBuilder();

        String html = "";
        for (Integer i = 0; i < 10000; i++) {
            html += "blabla
";
        }
        html += "";

        File file = new File("/tmp/tmp.pdf");
        FileOutputStream fop = new FileOutputStream(file);

        W3CDom w3cDom = new W3CDom();
        Document w3cDoc = w3cDom.fromJsoup(Jsoup.parse(html));

        pdfBuilder.withW3cDocument(w3cDoc, "/");
        pdfBuilder.toStream(fop);
        try {
            pdfBuilder.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

It creates a PDF with 176 pages and 10.000 links. On page 1 to 3 they are clickable, afterwards they are not, although identical. The last clickable link is the number 112 and in the source code I find:
870 0 obj
<<
/W 0.0
/S /S
>>
endobj
871 0 obj
<<
/S /URI
/URI (http://www.google.de?q=111)
>>
endobj
872 0 obj
<<
/W 0.0
/S /S
>>
endobj
873 0 obj
<<
/S /URI
/URI (http://www.google.de?q=112)
>>
endobj
874 0 obj
<<
/W 0.0
/S /S
>>
endobj
875 0 obj
<<
/F1 1049 0 R
>>
endobj

Apparently after number 112 there are no URLs stored anymore in the annotation objects.
My Program is much more complicated naturally. On the first five or six pages of it's result all the links are clickable, after that some are and most are not. Which ones are still clickable seems to be completely random though.
Can anyone help here? Any Idea what may cause this issue or how to fix it? A bug in openhtmltopdf?
--
edit 1:
Using withHtmlContent instead of withW3cDocument has the same problem.

A: The generated PDF works perfectly with jsoup 1.11.2 and openhtmltopdf-pdfbox-0.0.1-RC11.
The problem is likely caused by a bug in an older version of openhtmltopdf, which has been fixed.


text:
Q: Read RGB from bitmap - wrong values (of RGB); c++ I want to read the RGB values of all pixels from a BMP file.
I have code in c++, which look like:
#include <iostream>
#include <fstream>

using namespace std;

int main () {
    FILE *streamIn;
    streamIn = fopen("./Untitled.bmp", "r");
    if (streamIn == (FILE *)0) {
        printf("File opening error ocurred. Exiting program.\n");
        return 0;
    }

    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, streamIn);

    int width = *(int*)&info[18];
    int height = *(int*)&info[22];

    int image[width*height][3];
    int i = 0;

    for(i=0;i<width*height;i++) {
        image[i][2] = getc(streamIn);
        image[i][1] = getc(streamIn);
        image[i][0] = getc(streamIn);
        printf("pixel %d : [%d,%d,%d]\n",i+1,image[i][0],image[i][1],image[i][2]);
    }

    fclose(streamIn);

    return 0;
}

and an image like this (grid overlaid):

which are 6x12 pixels file with two colors - black and white.
I try to find out why after executing the above code with the image as a parameter I don't get just pixels with RGB: [0,0,0] and [255,255,255] but also [0,248,0], [7,224,0] and others.
Hex dump of that file is:
0000-0010:  42 4d 9a 01-00 00 00 00-00 00 7a 00-00 00 6c 00  BM...... ..z...l.
0000-0020:  00 00 08 00-00 00 0c 00-00 00 01 00-18 00 00 00  ........ ........
0000-0030:  00 00 20 01-00 00 13 0b-00 00 13 0b-00 00 00 00  ........ ........
0000-0040:  00 00 00 00-00 00 42 47-52 73 00 00-00 00 00 00  ......BG Rs......
0000-0050:  00 00 00 00-00 00 00 00-00 00 00 00-00 00 00 00  ........ ........
0000-0060:  00 00 00 00-00 00 00 00-00 00 00 00-00 00 00 00  ........ ........
0000-0070:  00 00 00 00-00 00 00 00-00 00 02 00-00 00 00 00  ........ ........
0000-0080:  00 00 00 00-00 00 00 00-00 00 ff ff-ff ff ff ff  ........ ........
0000-0090:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-00a0:  ff ff ff ff-ff 00 00 00-00 00 00 00-00 00 00 00  ........ ........
0000-00b0:  00 00 00 00-00 00 00 ff-ff ff ff ff-ff 00 00 00  ........ ........
0000-00c0:  00 00 00 00-00 00 00 00-00 00 00 00-00 00 00 ff  ........ ........
0000-00d0:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-00e0:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-00f0:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-0100:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-0110:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-0120:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-0130:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-0140:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-0150:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-0160:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-0170:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-0180:  ff ff ff ff-ff ff ff ff-ff ff ff ff-ff ff ff ff  ........ ........
0000-0190:  ff ff 00 00-00 ff ff ff-00 00 00 ff-ff ff 00 00  ........ ........
0000-019a:  00 ff ff ff-00 00 00 ff-ff ff                    ........ ..

File size is 410 bytes. It should be 270 (6*12*3 + 54). That means that there is some extra information in this file.

A: Your Bitmap file consists:
Bitmap File Header: 14 Bytes
42 4d 9a 01-00 00 00 00-00 00 7a 00-00 00
The last 4 bytes is the offset of where rgb values begin, 7A = after 122 Bytes
DIB header
The first 4 bytes is the size:
6c 00 00 00 -> 108 Bytes so BITMAPV4HEADER
The next 8 Bytes are the width and height in pixels:
08 00-00 00 0c 00-00 00
 width       height each 4 Bytes
So your bitmap is not 6x12 but 8x12! There is no need for padding because 8x3 = 24 which is multiple of 4.
The actual pixels are from 0x7A - 0x199
Beginning from the last row and going upwards, from left to right, the bitmap is:

The file size is correct:
file size = Bitmap File Header + DIB header + rgb Bytes = 14 + 108 + 8 * 12 * 3 = 410
To read a specific pixel in your image:
Load the whole bitmap file
char *buff;
char rgb[8 * 12 * 3]; //for simplicity
fptr = fopen("....bmp", "rb");

fseek(fptr, 0, SEEK_END);
int file_Size = ftell(fptr);
fseek(fptr, 0, SEEK_SET);

buff = malloc(file_Size * sizeof(char));

fread(buff, sizeof(char), file_Size, fptr);

memmove(rgb, buff[0x7A], 8 * 12 * 3);

Now rgb contains the actual pixels but the order is left->right and down->up meaning the first pixel is the one at the left bottom of the image.


text:
Q: @PostConstruct initializer runs before Spock setup() metod, can't mock service in time I have a service (A) that I'm writing a Spock unit-test for. This service uses an init()-method, annotated with @PostConstruct which calls another service (B) method.
My problem is that the init() method seems to be called before the Spock setup() method, so I get a NullPointerException from init() as my service B is null (not mocked yet). How can I solve this?
Service A to be tested:
class MasseJournaliseringService {

    BeskedModtagerService beskedModtagerService
    SagslagerIntegrationService sagslagerIntegrationService
    ExecutorService executorService

    private static String s9identity = ConfigHelper.hentConfig(ConfigNoegler.MASSEUDSENDELSESMODUL_FAGSYSTEM_ENTITETSID) as String
    private Principal udfoertAf
    List<Future<String>> futures = []

    @PostConstruct
    void init() {
        udfoertAf = sagslagerIntegrationService.opretPrincipal(s9identity) // NullPointerException!!
        int corePoolSize = ConfigHelper.hentConfig(ConfigNoegler.MSG_BROKER_MU_JOURNALISER_COREPOOLSIZE) as int
        int maxPoolSize = ConfigHelper.hentConfig(ConfigNoegler.MSG_BROKER_MU_JOURNALISER_POOLSIZE) as int
        int queueCapacity = ConfigHelper.hentConfig(ConfigNoegler.MSG_BROKER_MU_JOURNALISER_QUEUE_CAPACITY) as int
        int keepAliveTime = ConfigHelper.hentConfig(ConfigNoegler.MSG_BROKER_MU_JOURNALISER_KEEPALIVETIME) as int
        this.executorService = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(queueCapacity),
                new CustomizableThreadFactory(threadNamePrefix: 'mu-journ-'))
    }
}

Spock unit-test:
package beskedfordeler.core.service.broker

import beskedfordeler.core.configuration.ConfigHelper
import beskedfordeler.core.configuration.ConfigNoegler
import beskedfordeler.core.helpers.MasseudsendelseLogHelper
import beskedfordeler.core.service.domain.BeskedModtagerService
import beskedfordeler.core.service.integration.SagslagerIntegrationService
import grails.testing.services.ServiceUnitTest
import org.grails.spring.beans.factory.InstanceFactoryBean
import spock.lang.Specification

import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

class MasseJournaliseringServiceSpec extends Specification implements ServiceUnitTest<MasseJournaliseringService> {

    def setup() {
        GroovyMock(ConfigHelper, global: true)
        ConfigHelper.hentConfig(ConfigNoegler.BF_FAGSYSTEM_ENTITETSID) >> "FAGSYSTEM"
        ConfigHelper.hentConfig(ConfigNoegler.MYNDIGHED_ERST) >> "MYNDIGHED"
        ConfigHelper.hentConfig(ConfigNoegler.MASSEUDSENDELSESMODUL_FAGSYSTEM_ENTITETSID) >> "FAGSYSTEM_ID"
        service.sagslagerIntegrationService = Mock(SagslagerIntegrationService) // BeanCreationException caused by NullPointerException
        service.beskedModtagerService = Mock(BeskedModtagerService)
        ConfigHelper.hentConfig(ConfigNoegler.MSG_BROKER_MU_JOURNALISER_COREPOOLSIZE) >> 5
        ConfigHelper.hentConfig(ConfigNoegler.MSG_BROKER_MU_JOURNALISER_POOLSIZE) >> 5
        ConfigHelper.hentConfig(ConfigNoegler.MSG_BROKER_MU_JOURNALISER_QUEUE_CAPACITY) >> 10
        ConfigHelper.hentConfig(ConfigNoegler.MSG_BROKER_MU_JOURNALISER_KEEPALIVETIME) >> 60
    }

    // Test cases...
}


text:
Q: Rest can MediaType.MULTIPART_FORM_DATA be used with @Produces I have a rest service which produces the object of this format :
FileDetailsObject{
byte[] data;
String position_of_logo;
String username;
}
Is there a way to accomplish this in rest?
If it was just byte[] , I could use the Octet_Stream. But I need to return an object with a byte[].
I read about MediaType. Multipart_Form_Data but as far as I understand it seems to be associated with @Consumes where you can send it to  a service post request.
Any pointers would be helpful.
Thanks

A: You can use a multipart response like in this answer1 or you can base64 the byte array using an automatic converter like in this answer. On deciding which way to go, I would say the deciding factor would be who are the clients. Some clients can't handle multipart responses, but pretty much all languages have some kind of base64 conversion method.

1. This solution is Jersey specific. You didn't specify which JAX-RS implementation you are using.


text:
Q: Syntax-Highlighting won't recognize all CSS keywords I just discovered a strange behavior of the CSS syntax highlighting feature which you can see in the following code example:
.first_rule {
   color: red;
}
.second_rule:hover {
   color: blue;
}

.first_rule will have a plain black color, but .second_rule will be highlighted in blue because it is interpreted a keyword. It seems as if .first_rule would also become a keyword, as soon as I append a pseudo class (or anything else beginning with a  colon) to it. This lets the user assume that there is a difference between the two kinds of identifiers, but indeed there isn't.
Is this worth the effort to fix it, in order to keep StackOverflow the most user friendy page on the web? :-)
PS: Sorry, StackOverflow Meta uses a very low contrast for syntax highlighting. Please use Firebug, if you can't see this properly or temporarily paste it to the real StackOverflow.

A: As mentioned in comments, SO depends on Prettify to do the heavy lifting here. Get a fix into that, and we'll deploy it.


text:
Q: ESLint: Unexpected property "indent" in eslintrc As documented here, there is an ESLint property for indentation called indent. The example looks like this:

Or for tabbed indentation:
{
    "indent": ["error", "tab"]
}

However, if I paste this exact code into my .eslintrc file, VS Code shows this as an error:

ESLint: ESLint configuration in .eslintrc is invalid: - Unexpected top-level property "indent". . Please see the 'ESLint' output channel for details.

The .eslintrc file that I had before has a number of rules already, and there are no errors printed with those. If I add "indent" to that list, or by itself, it fails.
Here is the error and stack trace printed in the ESLint output channel in VS Code:

[Error - 10:38:55 PM] ESLint stack trace:
[Error - 10:38:55 PM] Error: ESLint configuration in .eslintrc is invalid:
    - Unexpected top-level property "indent".
    at validateConfigSchema (/home/aaronfranke/workspace/OddJobs/node_modules/eslint/lib/shared/config-validator.js:286:15)
    at ConfigArrayFactory._normalizeConfigData (/home/aaronfranke/workspace/OddJobs/node_modules/eslint/lib/cli-engine/config-array-factory.js:469:9)
    at ConfigArrayFactory._loadConfigDataInDirectory (/home/aaronfranke/workspace/OddJobs/node_modules/eslint/lib/cli-engine/config-array-factory.js:445:33)
    at ConfigArrayFactory.loadInDirectory (/home/aaronfranke/workspace/OddJobs/node_modules/eslint/lib/cli-engine/config-array-factory.js:401:18)
    at CascadingConfigArrayFactory._loadConfigInAncestors (/home/aaronfranke/workspace/OddJobs/node_modules/eslint/lib/cli-engine/cascading-config-array-factory.js:305:46)
    at CascadingConfigArrayFactory.getConfigArrayForFile (/home/aaronfranke/workspace/OddJobs/node_modules/eslint/lib/cli-engine/cascading-config-array-factory.js:250:18)
    at CLIEngine.executeOnText (/home/aaronfranke/workspace/OddJobs/node_modules/eslint/lib/cli-engine/cli-engine.js:860:47)
    at /home/aaronfranke/.vscode/extensions/dbaeumer.vscode-eslint-1.9.1/server/out/eslintServer.js:1:60107
    at /home/aaronfranke/.vscode/extensions/dbaeumer.vscode-eslint-1.9.1/server/out/eslintServer.js:1:61116

What's going on? Is this option not valid somehow? Is the example config wrong? Is there something wrong with my ESLint extension? Is there something wrong with VS Code? I'm using Ubuntu 18.04 Linux 64-bit with VS Code 1.40.1, ESLint extension 1.9.1, and eslint --version is v5.16.0.

A: It is not allowed to put this settings as a top level property, which means it has to be nested in another property, which is "rules". So you have to write it like this:
{
    //... other stuff ...

    "rules": {
        "indent": [ "error", "tab" ]
    }
}


text:
Q: javascript external file is not executing code properly showing error I am creating a website that has a onclick popup login box system and a live date/time system.
The whole JS code is in main.js (external file). the popup login system is working fine but the live date/time system is not working. when separating date/time code to the HTML page then it is working fine otherwise not.

// pop up login
const loginBtn=document.querySelector("#login");
const loginWrap=document.querySelector("#login-wrap");
const cancelBtn=document.querySelector("#cancel-btn");
const mainContainer=document.querySelector("#main-div");

function loginPop(){
  loginWrap.classList.add("main-wrap-login");
  mainContainer.classList.add("login-blur");
}

loginBtn.onclick=function(){
  loginPop();
}

function loginClose(){
  loginWrap.classList.remove("main-wrap-login")
  mainContainer.classList.remove("login-blur");
}

cancelBtn.onclick=function(){
  loginClose();
}

$(function(){
    $('#notify').slimScroll({
        height:'auto',
        size:'7px',
        wheelstep:'100',
        barClass:'notify-scrollbar'
    });
});

// live date/time system
const dateWrap=document.querySelector('#profile-date');
const timeWrap=document.querySelector('#live-time');

let date=new Date();
let day=date.getDate();
let month=date.getMonth()+1;
let year=date.getFullYear();

dateWrap.textContent=day+'-'+month+'-'+year;

// get real time
let h=date.getHours();
let m=date.getMinutes();
let s=date.getSeconds();

function liveTime(){
   let time=new Date();

   let hour=time.getHours();
   let min=time.getMinutes();
   let sec=time.getSeconds();

   min=checkTime(min);
   sec=checkTime(sec);

   timeWrap.textContent=hour+':'+min+':'+sec;

   setTimeout(function(){
    liveTime();
   },1000);
}

window.onload=function(){
  liveTime();
}

// adding 0 before number
function checkTime(i){
  if(i<10){
    i="0"+i;
  }
  return i;
}

// profile angle down
const logoutBtn=document.querySelector('#profile-angle-down');
const logoutDrop=document.querySelector('#logout-dropdown');

function logout(){

  logoutDrop.classList.toggle("logout-dropdown");
}

logoutBtn.onclick=function(){
  logout();
}

// search box
const searchBtn=document.querySelector('#profile-search');
const searchBox=document.querySelector('#search-box');

function displaySearch(){

  searchBox.classList.toggle("profile-search-box");
}

searchBtn.onclick=function(){
  displaySearch();
}

                          |

                        Suraj Udai Aswal

                             Logout

                            <form action="#" method="post">
                                <input type="search" name="p_search" id="p_search" placeholder="Search here...">
                            </form>


text:
Q: magento 2 shows 404 error on product detail page I am getting 404 error on ALL product detail pages. This happened right after I imported new products. Yes I did reindex several times. Everything else loads as it should. I thought maybe it is because of url rewrite module but if that was the case then I had to have the same problem for categories but I don't. Also I created a new product to see maybe there is a problem with my import file but the new product throw 404 as well.
Here is an url example for product detail(throws 404 error): http://example.com/index.php/09wx6359.html
Here is an url example for categories which works fine: http://example.com/index.php/product/resistor/film/metal.html. So Problem is not re-indexing or rewrite url. I'm using Magento 2.0.4. Please HELP

A: Problem was from my template files. There is an error in one of the files that renders product detail page. When I changed my template to Luma it got fixed. Such a relief I'm so happy now

A: For me this happened when i migrated a new staging environment. I copied the production db and uploaded my develop branch code. after all Megento commands the product pages kept saying 404.
After truncating the tables:

*

*report_event

*session

*customer_visitor

Deleting some folders in the var folder with command:
    rm -rf var/cache var/generation var/pagecache var/di

My product pages are working again. Magento ver. 2.1.8

A: This answer may help newbies to Magento 2.
If you are getting 404 message while accessing product page or category page, few things might not right. Thus, the simple one might be because of your catalog configuration that is:
Stores->Configuration->Catalog->Search Engine Optimization->Product URL Suffix
Stores->Configuration->Catalog->Search Engine Optimization->Category URL Suffix
If this value is .htmland you are accessing product or category URL like this https://www.qyqhair.co.uk/brazilian you will get 404 error. The best way to get correct URL, in this case, will be to add the .html suffix i.e. /brazilian.html.
If you want to  access the page as shown in the sample URL, then, you need to remove the .html value from Product URL Suffix and or both Category URL Suffix and leave it blank.
You might want to also run this command php bin/magento indexer:reindex && php bin/magento cache:flush && php bin/magento cache:clean after you made the changes.
Hope this help someone, one day.

A: I got similar issue and fixed in following ways:

*

*correct 'special price from' date

*assign 'default category'

*run command index:reindex

*flush cache

Issue resolved.


text:
Q: Getting rid of temp-xxxx.rdb files When starting redis from a directory with a redis.conf that includes:
save 60 10000
dir ./

it saves a temporary temp-1234.rdb (with the number always changing) to keep persistence. Problem is, I fire up redis-server from inside my git repo and these temp files are generated there and show up as untracked.
Is there a way to keep redis from generating them (or generating them elsewhere)?
Or should I just add them to .gitignore?

A: You can change the default of dir ./ (current working directory) in redis.conf to somewhere outside of your git repo.
# For default save/load DB in/from the working directory
# Note that you must specify a directory not a file name.
#dir ./
dir /home/octopus/redis_server/

A: You can change your Redis Persistence strategy by config the .conf file. but the temp-**.rdb  will always locate in the same dir path which is ./ by default.
the numeric ** indicates the pid who belong to the process forked by redis server to save the DB on disk, a atomic rename is engaged after work completed. it exists just a while with the old rdb file.
whether you should add them to .gitignore depends your opportunity when execute "git add **". it chance to include when bgSaving is working just now.  Of cause you could make such a rule with no harm only if you guarantee it excludes other normal files.
look up the rdb.c in redis src directory:
the line "snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());"
 /* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
int rdbSave(char *filename) {
    dictIterator *di = NULL;
    dictEntry *de;
    char tmpfile[256];
    char magic[10];
    int j;
    long long now = mstime();
    FILE *fp;
    rio rdb;
    uint64_t cksum;

    snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
    fp = fopen(tmpfile,"w");
    if (!fp) {
        redisLog(REDIS_WARNING, "Failed opening .rdb for saving: %s",
            strerror(errno));
        return REDIS_ERR;
    }


text:
Q: Maximum sum such that no two elements are adjacent Now the available solution every where is to have an include and exclude sum . At the end max of these two will give me the output.
Now initially I was having difficulty to understand this algorithm and I thought why not going in a simple way.
Algo:
Loop over the array by increasing array pointer two at a time

*

*Calculate the odd positioned element sum in the array

*Calculate the even positioned element sum
At the end, take max of this two sum.
in that way, I think complexity will be reduced to half O(n/2)
Is this algo correct?

A: It's a case of dynamic programming. The algorithm is:

*

*Do not take (sum up) any non-positive items

*For positive numbers, split the problem in two: try taking and skiping the item and return the maximum of these choices:

Let's show the 2nd step, imagine we are given:
[1, 2, 3, 4, 5, 6, 10, 125, -8, 9]

1 is positive, that's why
take_sum = max(1 + max_sum([3, 4, 5, 6, 10, 125, -8, 9])) // we take "1"
skip_sum = max_sum([2, 3, 4, 5, 6, 10, 125, -8, 9])       // we skip "1"
max_sum =  max(take_sum, skip_sum)

C# implementation (the simplest code in order to show the naked idea, no further optimization):
private static int BestSum(int[] array, int index) {
  if (index >= array.Length)
    return 0;

  if (array[index] <= 0)
    return BestSum(array, index + 1);

  int take = array[index] + BestSum(array, index + 2);
  int skip = BestSum(array, index + 1);

  return Math.Max(take, skip);
}

private static int BestSum(int[] array) {
  return BestSum(array, 0);
}

Test:
Console.WriteLine(BestSum(new int[] { 1, -2, -3, 100 }));
Console.WriteLine(BestSum(new int[] { 100, 8, 10, 20, 7 }))

Outcome:
101
120

Please, check, that your initial algorithm returns 98 and 117 which are suboptimal sums.
Edit: In real life you may want to add some optimization, e.g. memoization and special cases tests:
private static Dictionary<int, int> s_Memo = new Dictionary<int, int>();

private static int BestSum(int[] array, int index) {
  if (index >= array.Length)
    return 0;

  int result;

  if (s_Memo.TryGetValue(index, out result)) // <- Memoization
    return result;

  if (array[index] <= 0)
    return BestSum(array, index + 1);

  // Always take, when the last item to choose or when followed by non-positive item
  if (index >= array.Length - 1 || array[index + 1] <= 0) {
    result = array[index] + BestSum(array, index + 2);
  }
  else {
    int take = array[index] + BestSum(array, index + 2);
    int skip = BestSum(array, index + 1);

    result = Math.Max(take, skip);
  }

  s_Memo.Add(index, result); // <- Memoization

  return result;
}

private static int BestSum(int[] array) {
  s_Memo.Clear();

  return BestSum(array, 0);
}

Test:
  using System.Linq;

  ...

  Random gen = new Random(0); // 0 - random, by repeatable (to reproduce the same result)

  int[] test = Enumerable
    .Range(1, 10000)
    .Select(i => gen.Next(100))
    .ToArray();

  int evenSum = test.Where((v, i) => i % 2 == 0).Sum();
  int oddSum = test.Where((v, i) => i % 2 != 0).Sum();
  int suboptimalSum = Math.Max(evenSum, oddSum); // <- Your initial algorithm
  int result = BestSum(test);

  Console.WriteLine(
    $"odd: {oddSum} even: {evenSum} suboptimal: {suboptimalSum} actual: {result}");

Outcome:
  odd: 246117 even: 247137 suboptimal: 247137 actual: 290856

A: dynamic programming inclusion exclusion approach is correct your algorithm would not work for test cases like 3 2 7 10 in this test case the two elements we take are 3 10 and sum is 13 instead of 3,7 or 2,10.may you understand what i am saying and for further clarity code is below
Java Implementation
public int maxSum(int arr[]) {   // array must contain +ve elements only
 int excl = 0;
 int incl = arr[0];
 for (int i = 1; i < arr.length; i++) {
   int temp = incl;
   incl = Math.max(excl + arr[i], incl);
   excl = temp;
 }
 return incl;
}


text:
Q: Variable 'pathname' Issue with ngRoute I've been searching the forum for an issue similar to mine but haven't had any luck. However I have found a solution I'm going to share.
My problem was when I want to change my route it doesn't direct me to the correct location. For instance my url is www.dnndev.me/Projects/Project#/dashboard. I tried to create a few links like so:
// goes to www.dnndev.me#/tasks.

// same as above however what's between my {{}} is rendered blank.

'window.location.pathname' provides the missing piece of my url but it won't render. I thought about storing this in a variable but that didn't seem very Angular to me.
I tried using $location but it has no pathname property. I did come across $location.path('path) and it did what I needed. However I did not care to inject every controller with the $location service. After thinking for a bit I came up with an idea to create a function on the $rootscope in my applications run function and it does what I need.
# this is written in coffeescript
run = ['$location', '$rootScope', ($location, $rootScope) ->
    $rootScope.route = (path) ->
        $location.path(path)

//html
<button ng-click="$root.route('task')">
</button>

The reason I need this is because 'pathname' is variable. I'm working in the DNN framework and this module could be dropped on any path such as 'www.website.com/foo/bar#/dashboard'.
Is there a better way to acomplish this?
Thanks.

A: You can use $location.path to navigate with the info you have provided.
$location.path('/task');

And this /task should be mapped in your routing. You dont have to worry about anything. Something like below,
$routeProvider.when('/task', {
    templateUrl : "where you wish to navigate", // This should be replaced by your need
    controller : "taskController"
})


text:
Q: User location is not displaying in signed apk I have build a signed apk and it is working fine except it is getting crashed on the Google Map as it is not showing current location of the user. the .apk from the project is working fine and is showing current location of the user.

A: you need to sign your maps with release key ;) you signed your map with debug.keystore
how to get a Google Maps API v2 release key
Google Maps v2 Getting started
1) create a release key, for sign your app. SHA1 that you have you need to go to Google Api console. Create new Android key like SHA1_number;your.package
2) with this key you need to add in your manifest like:
<meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_key_for_release" />

put that code inside  application tag
That's it. check logcat to see exactly which message you recive from Google Maps


text:
Q: Match multiple instances using RegExp and store values (JavaScript) I would like to match all values with this pattern: @[\S]+. This will be used to get all names after an @ in a comment. Example:
Here are some people: @Name1, @Name2, @Name3, @Name4
should return: ["Name1", "Name2", "Name3", "Name4"]
I have tried to use comment.match(/@[\S]+/ig) but this returns an array with the @ symbol. I have tried to encapsulate the pattern with brackets: comment.match(/@([\S]+)/ig) but this doesn't help either. There may be more than 10 names that are matched so RegExp can't be used, and I'd rather not have to iterate through the array and strip it out.
Help appreciated :) .

A: Use positive look behind
 /(?<=@)\S+/

/Edit
I've read that JavaScript doesn't support lookbehinds. So I recommend using:
result.map(function(a) {a.slice(1)})

On each

A: As @KrzysztofWende you can use a look behind approach, or you can use capture groups:
With the regex:
/@(\w+)/ig

I replaced \S with \w, since otherwise the comma (,) is matched with Name1 as well.
Then the code reads:
var myString = "Here are some people: @Name1, @Name2, @Name3, @Name4";
var myRegexp = /@(\w+)/ig;
var match = myRegexp.exec(myString);
alert(match[1]);//do something useful with match[1]

Or in case you need to iterate over all possible matches:
var myString = "Here are some people: @Name1, @Name2, @Name3, @Name4";
var myRegexp = /@(\w+)/ig;
var match = myRegexp.exec(myString);
while (match != null) {
    alert(match[1]);
    match = myRegexp.exec(myString);
}

The solution makes use of capture groups: it numbers brackets starting from 1 (0 is the total match). In this case group 1 is thus (\w+).
JSFiddle demo.


text:
Q: MFC App Can't Maximize Only In Administrator Mode I've got an MFC app on Windows 10 that has the maximize button disabled as it wasn't designed to be resized. If the program is run not as administrator/elevated then the user can minimize the window to the taskbar and then restore/maximize it like normal. However, if the app is run as administrator/elevated privileges then the window can be minimized to the taskbar but never restored/maximized.
Things I've tried:

*

*Left-clicking the icon on the taskbar - nothing happens.

*Hovering over the icon on the taskbar then hovering over the tiny preview
above the icon - this shows the window but goes away as soon as you stop
hovering and clicking on the small preview does nothing.

*Enabling the maximize button and setting the NoActivate property to true - doesn't help.

*Alt-tabbing to the application does not do anything.

*I've inspected the app when it has this issue using spy++ 64 and I can see the messages but I'm not sure what's wrong. See below

This is the log of the successful (non-admin) minimize then maximize where the maximize attempt happened around ID 290: https://pastebin.com/kRT4ABrC
This is the log of the unsuccessful (admin) minimize then maximize where the maximize attempt happened around ID 176: https://pastebin.com/nAiXUa8p
Anyone have any ideas what is wrong? It does look like the unsuccessful log is missing a bunch of WM_ACTIVATEAPP messages, but I'm not sure what else looks off.
"code" necessary for pastebin link posts

A: Found the issue! I searched our code for "WM" and found a few custom message handlers including one for ON_WM_MOVE (See for more info.). I still don't understand why it causes an issue, but removing it gives us the desired effect. Below is the code that was causing the issue for anyone curious. The positionPages method is custom code that may be the culprit:
void CMyDlg::OnMove(int x, int y)
{
    CDialogEx::OnMove(x, y);
    positionPages(false); // This keeps the page being displayed in the right location
}


text:
Q: Detecting/intercepting insertion of  into DOM We're using a third-party analytics reporting script provided by this analytics company. It adds a 1x1 pixel image into the DOM with reporting data in the URL of the image.
Is there any way for me to monitor the DOM and intercept this <img> element and change its "src" attribute before the browser requests the image?
Sounds like a really odd thing to do, I know, but there's a feature we'd like to hack onto this reporting script (the script is obsfucated).

A: In non-IE browsers, you can detect the insertion of a DOM node by using the DOMNodeInserted event. I don't know if the browser will have made the HTTP request by the time the event is fired; it appears not to in Firefox from a quick test. Since this doesn't work in IE, this may not be an acceptable solution anyway.
document.body.addEventListener("DOMNodeInserted", function(evt) {
    var node = evt.target;
    if (node.nodeType == 1 && node.tagName == "IMG") {
        node.src = "http://www.gravatar.com/avatar/be21766f09e0e5fd3a2f8cc721ceba2e?s=32&d=identicon&r=PG"; // Your gravatar
    }
}, false);

A: Give this a go. I don't know how useful it will be, but I felt like tinkering and it somewhat accounts for the scenario whereby the third party purposefully incorporates a delay:
$(document).ready(function() {
// match an image with specific dimension, return it
function imgNinja() {
    var $img =  $("img").filter(function() {
        return ($(this).height() == 1 && $(this).width() == 1);
    });
    return $img;
}

// periodically execute this to check for matches
function keepSeeking() {
    $img = imgNinja();
    if($img.length) {
        alert('found it');
        clearInterval(i);
        // do something with image
    }
}

// insert a fake into the DOM at a bit of an interval
function addNastyImage() {
   var $invader = $('<img src="foo.jpg" height="1px" width="1px"/>');
    $('html').append($invader);
}

setTimeout(addNastyImage, 5000);
var i = setInterval(keepSeeking, 1000);
});

Demo: http://jsfiddle.net/NyEdE/3/

A: If the third-party script uses a method (like .appendChild) to add the element to the document, you can probably do this by replacing that method of the relevant object with your own function.
That would have the advantage of working in all browsers, and I think you would only generate one HTTP request (for the changed URL, not for the original one).

A: Building on what Adam suggested:
$(document).ready(function() {
  $("img[src='http://example.com/example.gif']").attr('src','http://example.com/new_src.gif');
});


text:
Q: very simple vue.js component generate maximum call stack size exceeded I have a very simple vue.js component which display list of data (2 objects with 2 fields).
component vue.js code :
    <template>

Genre

</template>

But when I displayed this component I have a error :

[Vue warn]: Error in nextTick: "RangeError: Maximum call stack size
  exceeded"

I don't understand why my loop "for" throws that error dealing with my few data.
I have another component that retrieve data by SQL promise (on mounted()) and I don't generate this error. Moreover I have more data for this component but no call stack error. This is very strange for me.
What nicety I forget ?

A: The problem is the following:

*

*You defined a component genre with name: "genre"

*The tag="genre" in your b-card tries to use the genre component as the card

The result is that you are loading your own component recursively, who goes through the same loop and loads your component again. Until you hit the maximum stack size.
The following sandbox shows that if you rename your component, Vue will complain about a non-existent genre element that it tries to load. Otherwise you get your maximum call stack error.


text:
Q: VSTO Word Office Interop: Find References to Bookmark Given a selection in Word which contains a Bookmark - e.g. a heading such as this (this is inside the SelectionChange event):
var selectionWithBookmark = e.Selection.Bookmarks.Cast<dynamic>().Select(b => b.Range as Range).FirstOrDefault();

How do I find all cross-references (i.e. Type == WdFieldType.wdFieldRef) in the document that refer to this bookmark?
I would like to find not just the Fields themselves, but the paragraphs containing those fields as well.
Looking for answers in either C# or VB.
I can loop/iterate all references in the document, but there is no way to link them to the Bookmark (aside from the Code property - but the REF number doesn't actually exist on the bookmark either from what I can see).  What it is missing is some form of Target property that I can compare to the bookmark itself.

A: The following statement in the question makes me wonder...

the REF number doesn't actually exist on the bookmark either from what
  I can see.

The bookmark name should contain the REF number, but it will be preceded by an underscore _ so the name won't show up in the UI by default.
In the Bookmarks dialog box there's a little checkbox "Hidden bookmarks": click it two, three times and a list should show up, as illustrated in the following screen shot.

Debug.Print(bookmark.Name) should also show this.
Once the bookmark name is known, it shouldn't be difficult to locate the corresponding REF fields.


text:
Q: SWC typescript is not affect fast reload I'm trying to improve nodemon server/start speed.
my script command in package.json is
installed npm install --save-dev ts-node @swc/core @swc/helpers regenerator-runtime
scripts: {
        "dev": "nodemon --watch src server.ts"
    }

and tsconfig.json  is
{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "ES6",
    "module": "commonjs",
    "removeComments": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "types": [
      "node",
      "bytebuffer"
    ],
    "moduleResolution": "node",
    "pretty": true,
    "sourceMap": true,
    "skipLibCheck": true,
    "suppressImplicitAnyIndexErrors": true,
    // "noImplicitAny": false,
    "resolveJsonModule": true,
    "outDir": "./build",
    "typeRoots": [
      "./src/interfaces/index.d.ts",
      "node_modules/@types"
    ],
    "paths": {
      "@config/*": [
        "./src/config/*"
      ],
      "@controllers/*": [
        "./src/controllers/*"
      ],
      "@dao/*": [
        "./src/dao/*"
      ],
      "@json/*": [
        "./src/json/*"
      ],
      "@lib/*": [
        "./src/lib/*"
      ],
      "@mappers/*": [
        "./src/mappers/*"
      ],
      "@models/*": [
        "./src/models/*"
      ],
      "@plugins/*": [
        "./src/plugins/*"
      ],
      "@routes/*": [
        "./src/routes/*"
      ],
      "@utils/*": [
        "./src/utils/*"
      ]
    }
  },
  "ts-node": {
    "swc": true
  },
  "filesGlob": [
    "./src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "src/lib/customTypings"
  ]
}

and mainly also mentioned in tsconfig.json file
ts-node: {
    "swc": true
  }

after Configuring all the steps still nodemon server taking 2 min to restart after changes.
Are there any changes that need to do to the current setup? and I followed this question
I did all the changes still it is not effect in speed of compile


text:
Q: I want to split a value which is stored in a String while using window handles This is my code
Set<String> winHandle = driver.getWindowHandles();
System.out.println(winHandle);

I want to split winHandle. The value I get when i print the winHandle is like this
[{0dd5d2e3-da7f-4a57-ad06-52c19336d3c6}, {a32fd7a5-040f-488f-8bc0-64d9a4496509}]

I want to select the Second Value {a32fd7a5-040f-488f-8bc0-64d9a4496509}

A: Assuming that your question is "how to get second item in set" you would need to iterate over elements until you will get element you are looking for.
So your code can look like
Iterator<String> it = winHandle.iterator();
it.next();//read and ignore first element
String value = it.next();//read and store second element

If your question is more general like "how to get last element" you could use
String last = null;
Iterator<String> it = winHandle.iterator();
while(it.hasNext()){
    last = it.next();
}
//when loop will end `last` will hold last element.

A: Method driver.getWindowHandles() is often used for switching between tabs/windows of browser. If your question is "how to switch into the last opened tab/window" you could try this code:
Set<String> oldWindowsSet = driver.getWindowHandles();
//action that produce opening new tab/window (ex. webElement.click())
Set<String> newWindowsSet = driver.getWindowHandles();
newWindowsSet.removeAll(oldWindowsSet);
String newWindowHandle = newWindowsSet.iterator().next();
driver.switchTo().window(newWindowHandle);


text:
Q: A fraction less than something? I encountered a question which is phrased:

A book store stocks 1/5 of its books as fiction works, and 1/3 less
  than the fiction books as self-help books. What fraction of books are
  fiction and self-help books?

I have a problem with the highlighted part. The (1/3) just seems to hang there, without explicitly applying to the number of fiction books.
The solution manual interprets this as:
number of self-help books = number of fiction - (1/3 x number of fiction)

Is this question phrased correctly?

A: The phrasing is correct and it seems to be precise enough – there seems to be no obvious way to misinterpret it.  Part of the purpose of doing math "word problems" is to develop skill in interpreting what is meant.  But for clearer communication of the intended meaning, as one would use when not posing a word problem, a phrasing like  "1/5 of its books are fiction works, and 2/3 as many as that are self-help books" might be better.
Note that the question as asked cannot be answered, because it does not tell how many of the self-help books are fictional or vice versa.  Those books will be counted twice if we just add 1/5 to 2/15 and give an answer of 1/3.


text:
Q: Program that generates a serie of carachtere from 1 to 1000 that includes numbers and letters I would like to create a program that generates a serie of carachtere from 1 to 1000 that includes numbers and letters .
for example : 0001 0002 0003 0004 0005 0006 0007 0008 0009 000a 000b 000c 000d 000e 000f ... 000z 0010 00011 ...

A: Just put your digits in a string and loop through them
#include <string>
#include <iostream>

const std::string digits = "0123456789abcdefghijklmnopqrstuvwxyz";

int main()
{
    for (auto a : digits)
    {
        for (auto b : digits)
        {
            for (auto c : digits)
            {
                for (auto d : digits)
                {
                    std::cout << a << b << c << d << '\n';
                    if (a == '1') // stop at 1000
                        return 0;
                }
            }
        }
    }
}

Four digits, four loops. Put whatever letters or numbers you like in digits. Add a stop condition if you wish.
There's more sophisticated ways you can do this, but the above should work for you.


text:
Q: audacius warning After
audacious -p song.mp3

I got the following:

** WARNING **
Audacious has detected that your ALSA device has a broken timer.  A workaround is being used to prevent CPU overload. Please report this problem to your Linux distributor or to the ALSA developers.

Is it important? How to solve it?
I'm using Audacious 2.4.4 (Ubuntu package) with
Linux vaio 3.0.0-16-generic-pae #28-Ubuntu SMP Fri Jan 27 19:24:01 UTC 2012 i686 i686 i386 GNU/Linux


text:
Q: How not to use dependency in domain context when using vendor event dispatcher I'm looking into using DDD for a sample application, for now I'm stuck on  Domain Events. Since there are pretty good EventDispatchers out there I don't want to reinvent the wheel. But these implementations all require that my events are implementing their EventInterface. I want to keep the implementation of my Domain Events seperate from any kind of implementation. How should I approach this problem?

A: Two possibilities I can think of
1) Introduce the idea of an adapter in front of the EventDispatcher; the adapter accepts events in the format produced by the domain, and "serializes" that same data into the form required by the specific dispatcher implementation you are using.
2) Create the domain events using a builder api; the domain defines the builder contract, but the implementation under the covers is specific to the event dispatcher you are using.

A: Here is my impl:
/// <summary>
/// Contains the contract for publishing domain events.
/// </summary>
public interface IDomainEventPublisher
{
    /// <summary>
    /// Publishes the domain events.
    /// </summary>
    /// <param name="domainEvents">events to be published</param>
    Task Publish(IEnumerable domainEvents);

    /// <summary>
    /// Subscribes the list of subscribers.
    /// </summary>
    /// <param name="subscribers">event subscriptions</param>
    void Subscribe(params IDomainEventSubscription[] subscribers);

    /// <summary>
    /// Subscribes to the event.
    /// </summary>
    /// <typeparam name="T">event to subscribe too</typeparam>
    /// <returns>event subscription</returns>
    DomainEventSubscription<T> SubscribeTo<T>();
}

/// <summary>
/// Publishes events to registered subscribers.
/// </summary>
public class DefaultDomainEventPublisher : IDomainEventPublisher
{
    readonly List<IDomainEventSubscription> subscriptions;

    /// <summary>
    /// Creates a new instance of the object.
    /// </summary>
    public DefaultDomainEventPublisher()
    {
        subscriptions = new List<IDomainEventSubscription>();
    }

    /// <summary>
    /// Subscribes to the event.
    /// </summary>
    /// <typeparam name="T">event to subscribe too</typeparam>
    /// <returns>event subscription</returns>
    public DomainEventSubscription<T> SubscribeTo<T>()
    {
        var subscription = new DomainEventSubscription<T>();

        subscriptions.Add(subscription);

        return subscription;
    }

    /// <summary>
    /// Subscribes the list of subscribers.
    /// </summary>
    /// <param name="subscribers">event subscriptions</param>
    public void Subscribe(params IDomainEventSubscription[] subscribers)
    {
        subscriptions.AddRange(subscribers);
    }

    /// <summary>
    /// Publishes the domain events.
    /// </summary>
    /// <param name="domainEvents">events to be published</param>
    public virtual async Task Publish(IEnumerable domainEvents)
    {
        foreach (var @event in domainEvents)
        {
            var subscribers = subscriptions.Where(s => s.CanHandleType(@event.GetType()));

            foreach (var subscriber in subscribers)
            {
                await subscriber.Handle(@event);
            }
        }
    }
}

/// <summary>
/// Handles the subscription services for an event.
/// </summary>
/// <typeparam name="T"></typeparam>
public class DomainEventSubscription<T> : IDomainEventSubscription
{
    readonly List<object> subscriptionMethods;

    /// <summary>
    /// Constructs a new instance.
    /// </summary>
    public DomainEventSubscription()
    {
        this.subscriptionMethods = new List<object>();
    }

    /// <summary>
    /// Adds the subscription method to the subscription.
    /// </summary>
    /// <param name="subscriptionMethod">subscription method</param>
    public void AddSubscriptionMethod(ISubscriptionMethod subscriptionMethod)
    {
        subscriptionMethods.Add(subscriptionMethod);
    }

    /// <summary>
    /// Returns whether or not the subscription can handle the specified type.
    /// </summary>
    /// <param name="type"></param>
    /// <returns>whether it can handle the type</returns>
    public bool CanHandleType(Type type)
    {
        return type.IsAssignableFrom(typeof(T));
    }

    /// <summary>
    /// Publishes the event.
    /// </summary>
    /// <param name="event">event to publish</param>
    public async Task Handle(object @event)
    {
        foreach (var subscriptionMethod in subscriptionMethods)
        {
            await (subscriptionMethod as dynamic).Handle(@event);
        }
    }
}

/// <summary>
/// Contains the contract for event subscribers.
/// </summary>
public interface IDomainEventSubscription
{
    /// <summary>
    /// Publishes the event.
    /// </summary>
    /// <param name="event">event to publish</param>
    Task Handle(object @event);

    /// <summary>
    /// Returns whether or not the subscription can handle the specified type.
    /// </summary>
    /// <param name="type"></param>
    /// <returns>whether it can handle the type</returns>
    bool CanHandleType(Type type);
}

/// <summary>
/// Contacts the contract for subscription methods.
/// </summary>
public interface ISubscriptionMethod
{
    /// <summary>
    /// Publishes the event.
    /// </summary>
    /// <param name="event">event to publish</param>
    Task Handle(object @event);
}

/// <summary>
/// Base class for subscription method implementations.
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class SubscriptionMethod : ISubscriptionMethod
{
    /// <summary>
    /// Publishes the event.
    /// </summary>
    /// <param name="event">event to publish</param>
    public abstract Task Handle(object @event);
}

/// <summary>
/// Publishes events using delegates.
/// </summary>
/// <typeparam name="T"></typeparam>
public class DelegateSubscriptionMethod<T> : ISubscriptionMethod
{
    readonly Func<T, Task> delegateAction;

    /// <summary>
    /// Constructs a new instance.
    /// </summary>
    /// <param name="action">delegate used for publishing</param>
    public DelegateSubscriptionMethod(Func<T, Task> action)
    {
        delegateAction = action;
    }

    /// <summary>
    /// Publishes the event using a delegate.
    /// </summary>
    /// <param name="event">event to publish</param>
    public async Task Handle(object @event)
    {
        await delegateAction(@event as dynamic);
    }
}

/// <summary>
/// Provides an extension method for publishing an event using a delegate.
/// </summary>
public static class DomainEventSubscriptionExtensions
{
    /// <summary>
    /// Adds an event subscription for publishing using the specified delegate.
    /// </summary>
    /// <typeparam name="T">event the subscription is subscribed too</typeparam>
    /// <param name="subscription">event subscription</param>
    /// <param name="action">delegate used for publishing</param>
    /// <returns>event subscription</returns>
    public static DomainEventSubscription<T> UsingDelegate<T>(this DomainEventSubscription<T> subscription, Func<T, Task> action)
    {
        var subscriptionMethod = new DelegateSubscriptionMethod<T>(action);

        subscription.AddSubscriptionMethod(subscriptionMethod);

        return subscription;
    }
}

Here is some basic usage:
publisher.SubscribeTo<DocumentOwnerChanged>()
    .UsingDelegate(
        async a => await messageGateway.DocumentOwnerChanged(1, 1, 1));

I also have an implementation to auto-subscribe using my DI container. Let me know if you would like to see this as well.


text:
Q: Bash substring from position not printing I am using the following format #{string:start:length} to extract the file name from wget's .listing file, line by line.
The format for the file is something I think we are all familiar with:
04-30-13  01:41AM              7033614 some_archive.zip
04-29-13  08:13PM       <DIR>          DIRECTORY NAME 1
04-29-13  05:41PM       <DIR>          DIRECTORY NAME 2

All file names start at pos:40, so setting :start to 39, with no :length should (and does) return the file name for each line:
#!/bin/bash
cat .listing | while read line; do
    file="${line:40}"
    echo $file
done

Correctly returns:
some_archive.zip
DIRECTORY NAME 1
DIRECTORY NAME 2

However, if I get any more creative, it breaks:
#!/bin/bash
cat .listing | while read line; do
    file="${line:40}"
    dir=$(echo $line | egrep -o '<DIR>' | head -n1)
    if [ $dir ]; then
        echo "the file $file is a $dir"
    fi
done

Returns:
$ ./test.sh
 is a <DIR>ECTORY NAME 1
 is a <DIR>ECTORY NAME 2

What gives?  I lose "the file " and the rest of the test looks like it prints on top of "the file DIRECTORY NAME 1" from pos:0.
It's weird, what's it on account of?

A: The answer, as I am learning more and more with linux as I progress, is non-printing control characters.
Adding a pipe to egrep for only printing characters solved the problem:
#!/bin/bash
cat .listing | while read line; do
    file=$(echo ${line:39} | egrep -o '[[:print:]]+' | head -n1)
    dir=$(echo $line | egrep -o '<DIR>' | head -n1)
    if [ $dir ]; then
        echo "the file $file is a $dir"
    fi
done

Correctly returns:
$ ./test.sh
the file DIRECTORY NAME 1 is a <DIR>
the file DIRECTORY NAME 2 is a <DIR>

Wish there were a better way to visualize these control characters, but what the above does is basically take the string segment, pull out the first string of printable characters, and assign it to the variable.
I assume there is a control character at the end of the line that returns the cursor to the beginning of the line.  Causing the rest of the echo to be printed there, overwriting the previous characters.'
Odd.

A: You can remove the \r control characters from the whole file by using the tr command on the first line of your script:
#!/bin/bash
cat .listing | tr -d '\015' | while read line; do
    file="${line:39}"
    dir=$(echo $line | egrep -o '<DIR>' | head -n1)
    if [ $dir ]; then
        echo "the file $file is a $dir"
    fi
done


text:
Q: How to serve static assets from custom folders in phoenix I want to use ckeditor in my phoenix project.
If I place ckeditor files in /web/static/assets/ckeditor, the ckeditor folder gets copied to /priv/static, but if I access the file at http://localhost:4000/ckeditor/ckeditor.js it shows me a

no route found for GET /ckeditor/ckeditor.js

However, if I move the whole of ckeditor folder underneath a folder of the standard name (js, css, image) then it gets served.
The static assets documentation http://www.phoenixframework.org/docs/static-assets suggested that anything placed there would be copied over and served. But seems like only js/css/image/font folders are getting served, not any custom named folder.
How can I have these files be served?

A: Take a look at the Plug.Static config in lib/YOUR_APP/endpoint.ex
Here's the default:
plug Plug.Static,
  at: "/"
  only: ~w(css fonts images js sitemaps favicon.ico robots.txt)

You can add additional folders to the only list and they'll be served as well.


text:
Q: Me gustaría mostrar en mi NavigationDrawer las opciones en horizontal. (Como se ve en la imagen de abajo)
Me gustaría mostrar en mi NavigationDrawer las opciones en horizontal y que sea seleccionable como en la imagen que se ve, según lo que se seleccione modificaría el RecyclerView que tengo pensado implementar.
El proyecto lo tengo alojado aquí en GitHub.
Muchas gracias!


text:
Q: ImportError: win32 only when deploying a django app on heroku The error :
from asyncio.windows_events import NULL
File "/app/.heroku/python/lib/python3.10/asyncio/windows_events.py", line 6, in
raise ImportError('win32 only')
ImportError: win32 only
please how can i fix this ?

A: I had the same error while trying to deploy:
File "/tmp/build_4a1c8563/base/models.py", line 1, in <module>
       from asyncio.windows_events import NULL
File "/app/.heroku/python/lib/python3.9/asyncio/windows_events.py", line 6, in <module>
       raise ImportError('win32 only')

I deleted the "from asyncio.windows_events import NULL" in models.py and the issue was solved. Wasn't event using that module...

A: I had the same error while deploying:
your IDE have imported from asyncio.windows_events import NULL line automatically while you were typing NULL
Just delete this line
from asyncio.windows_events import NULL


text:
Q: salq and sarq in x86-64 Assembly Language I am learning x86-64 assembly language with a textbook, and I am having difficulty understanding what specific lines of the code do.
the function in C that have the prototype

long doSth(long x, long y, long z):

and GCC generates the following assembly code;
#x->%rdi, y->%rsi, z->%rdx.

doSth:
subq    %rdx, %rsi
imulq   %rsi, %rdi
movq    %rsi, %rax
salq    $63, %rax
sarq    $63, %rax
xorq    %rdi, %rax
ret

I want to figire out how I would write C code that have an equivalent effect to the assembly code.
what I dont understand is that salq and sarq lines.
salq left shifts %rax by 63, but then in the next line sarq right shifts %rax by 63 back again.
So what is this doing in here? is it basically same as nothing happended?
How can I interpret these line so that I can write C code for these lines?
Thank you !


text:
Q: implicit conversion from scala Set to Java Set I have the following:
    class Goo
    trait Bar[D] {
     def toD : D
    }
    class Moo extends Bar[Goo] {
      def toD : Goo = new Goo
    }

    object Foo {
      import scala.collection.JavaConversions._
      import java.util

      implicit def scalaSetToJavaSet[D](bars: Set[Bar[D]]) : util.Set[D] = bars.map(_.toD)
    }

    trait Zoo {
      import java.util
      import Foo._

      var javaSet : util.Set[Goo] = Set(new Moo) //compile error

      var explicitJavaSet: util.Set[Goo] = scalaSetToJavaSet(Set(new Moo)) //works!!!
    }

When I try to compile this code I get an error:
"error: type mismatch;
   found   : scala.collection.immutable.Set[Moo]
   required: java.util.Set[Goo]
           var javaSet : util.Set[Goo] = ***Set(new Moo)***"

The explicit definition compiles. Why doesn't the implicit conversion work?

A: This is indeed tricky. Basically your idea is correct. You define a conversion method scalaSetToJavaSet that is imported. The problem comes from the fact that (Scala's) Set[A] is invariant in its type parameter A. That means that Set[Moo] is not a sub-type of Set[Bar[_]].
In order to fix that, you need to tell the implicit conversion that the set element can be a sub-type of bar:
implicit def scalaSetToJavaSet[D, B <: Bar[D]](bars: Set[B]): java.util.Set[D] =
  bars.map(_.toD)

val javaSet: java.util.Set[Goo] = scala.Set(new Moo)  // ok

You can read this now as: Given a type D and some sub-type of Bar whose type parameter is D, conduct the conversion. This method is now called as scalaSetToJavaSet[Goo, Moo] (and not scalaSetToJavaSet[Goo, Bar[Goo]]).

As the others have pointed out, it is easier to use a ready-made conversion from JavaConversions instead of writing your own.

A: Firstly implicit function scalaSetToJavaSet does not work because it expects Set[Bar[D]] and you are passing Set[Moo]. This is because type parameter of Set is invariant and not co-variant (It would had worked in case of List).
So a short answer is
import scala.collection.JavaConversions._
var javaSet : util.Set[Moo] = Set(new Moo)

Or you can change your declaration to:
implicit def scalaSetToJavaSet[D,T <:Bar[D]](bars: Set[T]) : util.Set[D] = bars.map(_.toD)

var javaSet : util.Set[Goo] = Set(new Moo)

Now it says that you can pass any type which extends Bar[D] and hence works with Moo


text:
Q: Responsive Text in Inputfield I have an input field and in this I add values via JavaScript.
How can I do it, if my input field is "full" at for example 30 characters, that the font will be smaller, so that everything is always visible?

input {
  height:50px;
  width:200px;
  font-size:20px;
  padding:5px;
}
<input type="text">

A:

<input type="text" name="input" id="input">

Best I could do it, Is this what you are looking for?


text:
Q: How I am getting double internet speed? Just wondering I was wondering, how it is possible that I am getting double speeds?
I am paying for 100mbps, but sometimes I am getting over 200mbps (pic below).
I have fiber cable run to my apartment, then fiber to digital converter, Mikrotik RB2011UiAS-2HnD-IN, Cat 5e cable to my pc.
This behaviour is observed while downloading torrents.

Speedtest result

EDIT: 200mbps is DOWNLOAD speed, not total of both directions.

A: For home high-speed internet service, at least in the United States, if only one speed number is quoted, it's usually just the download speed, not the sum of both directions.
Service is often designed to be asymmetric, with upload speed often only a fraction (1/2 to 1/10th) of the download speed. However, it's not uncommon for fiber service to be symmetric.
So you've got symmetric 100mbps fiber internet service: 100 mbps down and 100mbps up, for a total of 200mbps of aggregate bandwidth.


text:
Q: How do I map the root directory to a controller in c# using web api? I have a c# web api (.net 4) web application. I have several controllers. I'd like to map a new controller to the root directory for the web app.
So, I have http://localhost/listproducts
I'd like the url to be http://localhost
But I don't know how to tell the controller to use the root directory. It seems to be configured based on the name.
The solution I went with is:
config.Routes.MapHttpRoute(
      name: "ListProductsApi",
             routeTemplate: "",
             defaults: new { controller = "ListProducts" } // Parameter defaults
);

The trick is the defaults: new { controller = "ListProducts" }  line. (I need a POST action so I just left action out. Apparently when you want the root route "/" you need to explicitly name the controller.

A: You simply need to change the default route you already have. It should currently look something like this:
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index",
                    id = UrlParameter.Optional }
);

Change controller = "Home" to controller = "listproducts".

A: It should be fairly easy, just change a default route in your global.asax.cs and instead of
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

change it to
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "ListProducts", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);


text:
Q: Here-Maps Android SDK not having WaypointParameterType to add as waypoint I am using Here Android SDK for Navigation, I am planning a route which has around 100 waypoints b/w source and destination.
So i am adding waypoints for the RoutePlan as
routePlan.addWaypoint(new RouteWaypoint(new GeoCoordinate(XXXXXXXXXXX,  YYYYYYYYYYYY), RouteWaypoint.Type.VIA_WAYPOINT)
But as per documentation https://developer.here.com/documentation/routing/topics/resource-param-type-waypoint.html
We can set TransitRadius and Heading parameters also for waypoints, Can i know the these parameters context and how to use in my code ?

A: Keep care not to mix the Routing REST API (you linked in the original post) with the MobileSDK documentation. Even many features are the same, there are differences.
If you use the MobileSDK for Navigation, you probably refer to the Premium Mobile SDK, and the documentation is here: https://developer.here.com/documentation/android-premium/
For waypoints, you can set the WaypointDirection in the RouteWaypoint class: https://developer.here.com/documentation/android-premium/api_reference_java/com/here/android/mpa/routing/RouteWaypoint.html
TransitRadius is not implemented in the Premium MobileSDK at the moment.
Btw: In case you use the Starter Mobile SDK (that has no Navigation support), also the WaypointDirection is not supported there.

A: To add a waypoint, you can simply use:
Waypoint waypoint1 = new Waypoint(new GeoCoordinates(your geocordinates));
Waypoint waypoint2 = new Waypoint(new GeoCoordinates(your geocordinates));

Also, now in explore edition as well, you can route type as well. Route Type means whether your route is Stopover type or Pass-Through type, below I am showing how to set waypoint as pass-through type. By Default, all the waypoints added will be STOP Over type.
waypoint1.type = WaypointType.PASS_THROUGH;
waypoint2.type = WaypointType.PASS_THROUGH;


text:
Q: ErrorException Array to string conversion when Attaching I have a many to many relationship between two tables: atentions and procedimientos. it looks like this
As you can see, my pivot table has 2 extra columns, cantidad, and descuento, along with the keys from both tables.
However, when i try to insert data in that table, i get the error message ErrorException
Array to string conversion and if i format those values using json_encode, i get the following
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '["1","1"]' for column `dentalg`.`atencion_procedimientos`.`cantidad` at row 1 (SQL: insert into `atencion_procedimientos` (`atencion_id`, `cantidad`, `created_at`, `descuento`, `procedimientos_id`, `updated_at`) values (11, ["1","1"], 2020-05-06 02:19:20, ["1","1"], 1, 2020-05-06 02:19:20), (11, ["1","1"], 2020-05-06 02:19:20, ["1","1"], 2, 2020-05-06 02:19:20))

This is my store function
public function store(Request $request)
    {
        //
        $this->validate($request,[
            'asunto' => 'required',
            'cantidad' => 'required',
            'descuento' => 'required',
            'total_pago' => 'required'
        ]);

        if(Auth::user()->role_id ==1 or Auth::user()->role_id==2){

            $atencion = new Atencion();
            $atencion->doctor_id = Auth::id();
            $atencion->pacientes_id = $request->paciente_id;
            $atencion->asunto = $request->asunto;
            $atencion->tipo_pago = 0; //Tratar de Modificar
            $atencion->estado_pago = 0;
            $atencion->observaciones = $request->observaciones;
            $atencion->total = $request->total_pago;
            $atencion->save();

            $atencion->procedimientos()->attach($request->procedimientos_id,[
                'cantidad' => $request->cantidad,
                'descuento' => $request->cantidad,
            ]);

            Toastr::success('Tratamiento añadido con éxito','success');
            return redirect()->route('admin.Atenciones.index');

        } else {
            Toastr::error('You are not authorized to do this operation','Error');
            return redirect()->back();
        }

Models
public function procedimientos(){
        return $this->belongsToMany('App\Procedimientos')->withPivot('cantidad', 'descuento')->withTimestamps();
    }

and
public function atenciones(){
        return $this->belongsToMany('App\Atencion')->withPivot('cantidad', 'descuento')->withTimestamps();
    }


text:
Q: how to create stacked bar/progress bar in flutter like this image I want to display
i dont know the name of this kind of visualization.
Right now,
I have 3 data here(sum, net, cancel)
The right side will display is cancel number, the left side display is net number inside the stacked bar
with this bar, user will immediately know the sum number by (net + cancel)
is there some kind of package that can help me to display this bar

A: Here is the widget builder that you want. Maybe the MediaQuery is a bad choice. But you can use any other sizing options.
  Widget _buildProgress(BuildContext context, int progress, int limit) {
    return SizedBox(
      height: 30,
      width: double.infinity,
      child: Stack(
        children: <Widget>[
          Positioned.fill(
            child: Container(
              decoration: const BoxDecoration(
                color: Color(0xFF038918),
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
              alignment: Alignment.centerRight,
              padding: const EdgeInsets.only(right: 20),
              child: Text(
                '$limit',
                style: const TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          Container(
            width: MediaQuery.of(context).size.width / limit * progress,
            decoration: const BoxDecoration(
              color: Color(0xFFe40808),
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            alignment: Alignment.center,
            child: Text(
              '$progress',
              style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }


text:
Q: Example of infinite group with infinitely many simple subgroups What is an example of an infinite group with a composition series and infinitely many simple subgroups?

A: One example is the direct sum of all the finite simple groups (more precisely, pick one for each isomorphism class).
Another (perhaps less cheat-y) one is the group of permutations of $\mathbb N$, which contains all the alternating groups $A_n$ as subgroups.


text:
Q: Replacing null and undefined values in json value with empty("") I'mm getting a JSON response with lots of null and undefined values. I need to replace all null and undefined values with an empty string (""). Below is a sample response I'm getting:

{
  lecCicode: null
  lecOrderNo: null
  loccType: "Z"
  nccrCode: null
  nciCode: null
},
{
  lecCicode: null
  lecOrderNo: null
  loccType: "Z"
  nccrCode: null
  nciCode: null
},
{
  lecCicode: null
  lecOrderNo: null
  loccType: "Z"
  nccrCode: null
  nciCode: null
}

A: You can try like:
JSON.parse(JSON.stringify(yourjson).replace(/null/g, '""'))


text:
Q: vector/array bounds check only when a define is declared I've create my own container that is inherited from a vector. I would like to reimplement operator[] in a way that makes checking for bounds decided by a #define.
So putting an example, and ignoring template parmameters as they're complicated and irrelevant
class MyArray : vector<double>
{
    //...
    virtual double& operator[](const size_type& index);
    virtual const double& operator[](const size_type& index) const;
    //...
}

double& MyArray::operator[](const size_type& index)
{
    #ifdef DEBUG_ENABLED
        return this->at(index);
    #else
        return (*this)[index];
    #endif
}

However, this doesn't work because since operator[] is overloaded, calling operator[] at #else would become recursive.
I would like to make the check for bounds based on my #define, and not based on whether I use std::vector<>::at() or std::vector<>::operator[].
How can I resolve this?
EDIT: Since it's offered a lot to use std::vector as a member instead of inheriting, I have to mention that doing that isn't a good solution for me because i'll have to reimplement ALL the member functions of std::vector. That's not so pleasant to do!

A: Simply call the base class member functions as required:
double& operator[](size_type index)
{
    #ifdef DEBUG_ENABLED
        return std::vector<double>::at(index);
    #else
        return std::vector<double>::operator[](index);
    #endif
}

You should provide a const version of this too. Also note you probably don't want to make this operator virtual.

A: Firstly, it is not a good idea to derive from standard containers, because they lack features (e.g. virtual destructor) that properly supports being used as a base class.    The intent of standard containers is that they will not be used as bases.
If you must do this however, add this;
class MyArray : vector<double>
{
    //   all your other stuff

    typedef vector<double> Base;

};

double& MyArray::operator[](const size_type& index)
{
    #ifdef DEBUG_ENABLED
        return this->at(index);
    #else
        return (*((Base *)this))[index];
    #endif
}

The type conversion in the function is often considered better done using a static_cast, but you get the idea.
It is better to make the container a member of your class, and various members of operator functions forward to the contained member.
class MyArray
{
    //   all your other stuff

   private:
       std::vector<double> data;

};

double& MyArray::operator[](const size_type& index)
{
    #ifdef DEBUG_ENABLED
        return data.at(index);
    #else
        return data[index];
    #endif
}

Lastly, either way, the operator[]() need not be virtual.

A:
"Since it's offered a lot to use std::vector as a member instead of inheriting, I have to mention that doing that isn't a good solution for me because i'll have to reimplement ALL the member functions of std::vector. That's not so pleasant to do!

You don't have to. I used inheritance here to save the stress.
#include <iostream>
#include <vector>

using namespace std;

template <typename T>
class Vector_ : private vector<T>
{
public:
    virtual ~Vector_(){}
    virtual const T& operator[](const size_t index);
    virtual const T& at(const size_t index);
};

/*
<<I would like to make the check for bounds based on my #define, and  not based on
std::vector<>::at() or std::vector<>::operator[]. >>
*/
template <typename T>
const T& Vector_<T>::operator[](const size_t index)
{
#ifdef DEBUG_ENABLED
    return (*((vector<T>*)this))->at(index)
#else
    return (*((vector<T> *)this))[index];
#endif
}
template <typename T>
const T& Vector_<T>::at(const size_t index)
{
#ifdef DEBUG_ENABLED
    return (*((vector<T>*)this))->at(index)
#else
    return (*((vector<T>*)this))[index];
#endif
}

//test...
Vector<int>_ vec;
vec.push_back(3);

vec[2]; or vec.at(2); //no exception

#define DEBUG_ENABLED
vec[2]; or vec.at(2);  //exception


text:
Q: calculating percentage in MDX I'm trying to write a mdx query that would calculate the income percentage for each product in 3 different columns, depending on the percentage "base" - the Group (that the product is in) income, the subgroup income and total income. So far this is my code
    with
member [Measures].[Percent] as
([Measures].[Income]) /
([Products].[product].currentmember.parent,
[Measures].[Income])
,format_string = "percent"

select
    {
        [Measures].[Percent]
    }
    on columns,
    {
        [Products].[Product].[Product]
    }
    on rows
from [CUBE]

It calulates the percentage based on the total income, but I have no idea how to change the code to fill the criteria I mentioned earlier. I tried rearrenging the code many times in many different ways, (trying to calculate the sobgroup percentage example)
 with
member [Measures].[Percent] as
([Measures].[Income], [Products].[Subgroup]) /
([Products].[product].currentmember.parent,
[Measures].[Income])
,format_string = "percent"

etc but I only get the same result or errors. I'm still very new to mdx so any help or tip would be much appreciated.

A: I'm still a little unsure of the requirements but you can add an extra parent if you like:
WITH
MEMBER [Measures].[Percent_ofSubCategory] as
   DIVIDE(
     [Measures].[Income]
    ,([Measures].[Income], [Towary].[Hierarchy].currentmember.parent)
   )
,format_string = "percent"
MEMBER [Measures].[Percent_ofCategory] as
   DIVIDE(
     [Measures].[Income]
    ,([Measures].[Income], [Towary].[Hierarchy].currentmember.parent.parent)
   )
,format_string = "percent"
MEMBER [Measures].[Percent_ofAll] as
   DIVIDE(
     [Measures].[Income]
    ,([Measures].[Income], [Towary].[Hierarchy].[All])
   )
,format_string = "percent"
SELECT
    {
      [Measures].[Percent_ofSubCategory]
     ,[Measures].[Percent_ofCategory]
     ,[Measures].[Percent_ofAll]
    }
    on 0,
    [Towary].[Hierarchy].[Towar].[Towar].members
    on 1
from [CUBE];


text:
Q: Html Emails - Outlook 2010 - Table Align Issue I have two tables aligned left at 30% each so that when it goes responsive the change to 100% and stack underneath each other.
Problem is as per the screenshot below the second one has a gap at the top and i have no idea why?
My snippet of code is here

1 FIRST AND LAST NAME

2 FIRST AND LAST NAME

3 FIRST AND LAST NAME

4 FIRST AND LAST NAME

5 FIRST AND LAST NAME

6 FIRST AND LAST NAME

7 FIRST AND LAST NAME

8 FIRST AND LAST NAME

9 FIRST AND LAST NAME

10 FIRST AND LAST NAME

Outlook 2010 - Screenshot

A: Doesn't look like the same code from the screenshots, background colors are missing and fonts as well. Either way I think you need a ghost column between the tables to align, try the code below:

6 FIRST AND LAST NAME

7 FIRST AND LAST NAME

8 FIRST AND LAST NAME

9 FIRST AND LAST NAME

10 FIRST AND LAST NAME

6 FIRST AND LAST NAME

7 FIRST AND LAST NAME

8 FIRST AND LAST NAME

9 FIRST AND LAST NAME

10 FIRST AND LAST NAME

You can change the width of the ghost column if you need to. let me know how you go.