text:
Q: Android Launching Robolectric Unit Tests from Ant? I've been having a hell of a time integrating Robolectric and Ant or Maven, although Ant is a bit preferable because it sits closer to the Android SDKs.
Everything works from within eclipse. Robolectric links and the unit tests run, however when I try to run and build tests from the command line it doesn't seem to work.
With the actual Robolectric-sample application, I attempted to do both maven and ant builds.
The build with ant is successful, but the tests all fail.
Maven Output
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building RobolectricSample app 1.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-enforcer-plugin:1.0-beta-1:enforce (enforce-maven) @ robolectricsample ---
[INFO]
[INFO] --- android-maven-plugin:3.0.0-alpha-13:generate-sources (default-generate-sources) @ robolectricsample ---
[INFO] ANDROID-904-002: Found aidl files: Count = 0
[INFO] ANDROID-904-002: Found aidl files: Count = 0
[INFO] C:\Program Files (x86)\Android\android-sdk\platform-tools\aapt.exe [package, -m, -J, C:\repos\Tests\robolectric-sample\target\generated-sources\r, -M, C:\repos\Tests\robolectric-sample\AndroidManifest.xml, -S, C:\repos\Tests\robolectric-sample\res, --auto-add-overlay, -I, C:\Program Files (x86)\Android\android-sdk\platforms\android-10\android.jar]
[INFO]
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ robolectricsample ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\repos\Tests\robolectric-sample\src\main\resources
[INFO] skip non existing resourceDirectory C:\repos\Tests\robolectric-sample\target\generated-sources\extracted-dependencies\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ robolectricsample ---
[INFO] Compiling 1 source file to C:\repos\Tests\robolectric-sample\target\classes
[INFO]
[INFO] --- android-maven-plugin:3.0.0-alpha-13:unpack (default-unpack) @ robolectricsample ---
[INFO]
[INFO] --- maven-resources-plugin:2.5:testResources (default-testResources) @ robolectricsample ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\repos\Tests\robolectric-sample\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ robolectricsample ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.6:test (default-test) @ robolectricsample ---
[INFO] Surefire report directory: C:\repos\Tests\robolectric-sample\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.pivotallabs.api.HttpTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.53 sec <<< FAILURE!
Running com.pivotallabs.tracker.TrackerAuthenticationRequestTest
Warning: an error occurred while binding shadow class: ShadowActivity
Warning: an error occurred while binding shadow class: ShadowActivityGroup
Warning: an error occurred while binding shadow class: ShadowApplication
Warning: an error occurred while binding shadow class: ShadowItemizedOverlay
Warning: an error occurred while binding shadow class: ShadowListActivity
Warning: an error occurred while binding shadow class: ShadowMapActivity
Warning: an error occurred while binding shadow class: ShadowPreferenceActivity
Warning: an error occurred while binding shadow class: ShadowService
Warning: an error occurred while binding shadow class: ShadowTabActivity
Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 0.361 sec <<< FAILURE!
Running com.pivotallabs.tracker.RecentActivityTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.01 sec
Running com.pivotallabs.ViewEnablingTextWatcherTest
Tests run: 3, Failures: 0, Errors: 3, Skipped: 0, Time elapsed: 0.008 sec <<< FAILURE!
Running com.pivotallabs.api.ApiGatewayTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.006 sec <<< FAILURE!
Running com.pivotallabs.NamesAdapterTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE!
Running com.pivotallabs.NotifyDataSetChangedCallbacksTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE!
Running com.pivotallabs.GenericAdapterTest
Tests run: 4, Failures: 0, Errors: 4, Skipped: 0, Time elapsed: 0.01 sec <<< FAILURE!
Running com.pivotallabs.tracker.AuthenticationGatewayTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE!
Running com.pivotallabs.HomeActivityTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE!
Running com.pivotallabs.NamesActivityTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE!
Running com.pivotallabs.tracker.RecentActivitiesTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE!
Running com.pivotallabs.api.ApiResponseTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.pivotallabs.injected.InjectedActivityTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.011 sec <<< FAILURE!
Running com.pivotallabs.MultiCallbacksTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.pivotallabs.tracker.RecentActivityActivityTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE!
Running com.pivotallabs.tracker.RecentActivityRequestTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 sec
Running com.pivotallabs.ViewVisibleWhileOutstandingCallbacksTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.005 sec <<< FAILURE!
Running com.pivotallabs.tracker.SignInDialogTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.004 sec <<< FAILURE!
Running com.pivotallabs.views.LoadingTextViewTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.003 sec <<< FAILURE!
Running com.pivotallabs.tracker.RecentActivityAdapterTest
Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 0.007 sec <<< FAILURE!
Running com.pivotallabs.util.StringsTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec

Results :

Tests in error:
  initializationError(com.pivotallabs.api.HttpTest)
  shouldReturnUsernameAndPassword(com.pivotallabs.tracker.TrackerAuthenticationRequestTest)
  shouldHaveUrl(com.pivotallabs.tracker.TrackerAuthenticationRequestTest)
  shouldNotEnableTheViewIfTheAnyOfTheEditTextsContainWhitespace(com.pivotallabs.ViewEnablingTextWatcherTest)
  shouldEnableTheViewWhenAllEditTextsHaveText(com.pivotallabs.ViewEnablingTextWatcherTest)
  shouldDisableTheViewWhenOneOfTheEditTextsHaveEmptyText(com.pivotallabs.ViewEnablingTextWatcherTest)
  initializationError(com.pivotallabs.api.ApiGatewayTest)
  initializationError(com.pivotallabs.NamesAdapterTest)
  onSuccessShouldNotifyDataSetChanged(com.pivotallabs.NotifyDataSetChangedCallbacksTest)
  getCount_shouldReturnListSize(com.pivotallabs.GenericAdapterTest)
  getItem_shouldReturnObjectAtIndex(com.pivotallabs.GenericAdapterTest)
  getView_shouldCallThroughToGetView(com.pivotallabs.GenericAdapterTest)
  getItemId_shouldReturnIndex(com.pivotallabs.GenericAdapterTest)
  initializationError(com.pivotallabs.tracker.AuthenticationGatewayTest)
  initializationError(com.pivotallabs.HomeActivityTest)
  initializationError(com.pivotallabs.NamesActivityTest)
  initializationError(com.pivotallabs.tracker.RecentActivitiesTest)
  initializationError(com.pivotallabs.injected.InjectedActivityTest)
  initializationError(com.pivotallabs.tracker.RecentActivityActivityTest)
  shouldSetProgressBarVisibility(com.pivotallabs.ViewVisibleWhileOutstandingCallbacksTest)
  initializationError(com.pivotallabs.tracker.SignInDialogTest)
  initializationError(com.pivotallabs.views.LoadingTextViewTest)
  shouldRecycleViews(com.pivotallabs.tracker.RecentActivityAdapterTest)
  shouldCreateViews(com.pivotallabs.tracker.RecentActivityAdapterTest)

ant test output
test:
    [junit] Warning: an error occurred while binding shadow class: ShadowActivity
    [junit] Warning: an error occurred while binding shadow class: ShadowActivityGroup
    [junit] Warning: an error occurred while binding shadow class: ShadowApplication
    [junit] Warning: an error occurred while binding shadow class: ShadowListActivity
    [junit] Warning: an error occurred while binding shadow class: ShadowMapActivity
    [junit] Warning: an error occurred while binding shadow class: ShadowPreferenceActivity
    [junit] Warning: an error occurred while binding shadow class: ShadowService
    [junit] Warning: an error occurred while binding shadow class: ShadowTabActivity
    [junit] Test com.pivotallabs.GenericAdapterTest FAILED
    [junit] Test com.pivotallabs.HomeActivityTest FAILED
    [junit] Test com.pivotallabs.NamesActivityTest FAILED
    [junit] Test com.pivotallabs.NamesAdapterTest FAILED
    [junit] Test com.pivotallabs.NotifyDataSetChangedCallbacksTest FAILED
    [junit] Test com.pivotallabs.ViewEnablingTextWatcherTest FAILED
    [junit] Test com.pivotallabs.ViewVisibleWhileOutstandingCallbacksTest FAILED
    [junit] Test com.pivotallabs.api.ApiGatewayTest FAILED
    [junit] Test com.pivotallabs.api.HttpTest FAILED
    [junit] Test com.pivotallabs.injected.InjectedActivityTest FAILED
    [junit] Test com.pivotallabs.tracker.AuthenticationGatewayTest FAILED
    [junit] Test com.pivotallabs.tracker.RecentActivitiesTest FAILED
    [junit] Test com.pivotallabs.tracker.RecentActivityActivityTest FAILED
    [junit] Test com.pivotallabs.tracker.RecentActivityAdapterTest FAILED
    [junit] Test com.pivotallabs.tracker.SignInDialogTest FAILED
    [junit] Test com.pivotallabs.tracker.TrackerAuthenticationRequestTest FAILED
    [junit] Test com.pivotallabs.views.LoadingTextViewTest FAILED

BUILD FAILED
C:\repos\Tests\robolectric-sample\build.xml:145: Unit test(s) failed.  See reports!

The compilation and linking seems good with the samples, but there is still a lot of failing of tests. I would assume that these samples should have 100% success if they are working properly.
Can anyone shed some light about the mysteries within? Can I include junit and robolectric tests in my build scripts, or is this something that isn't supported properly since the android build system undertook those changes a few months ago.


text:
Q: Is this integral correctly calculated? The problem is that I can't use wolframalpha to check this because he is worried about integration limits: I have $a>0$ and $t \in (-1,1).$
$$(1-t)^{\frac{a}{2}} \int_0^t \frac{1}{(1-x)^{a+1} }dx= \frac{1}{a} \left( \frac{1}{(1-t)^{\frac{a}{2}}} -(1-t)^{\frac{a}{2}} \right)$$

A: $$\int\frac{dx}{(1-x)^{\alpha+1}}=-\int -(1-x)^{-1-\alpha}dx=-\frac{(1-x)^{-\alpha}}{-\alpha}+C=\frac{(1-x)^{-\alpha}}{\alpha}+C$$

A: Yes, it is.
$$\begin{align}(1-t)^{\frac a2}\int_{0}^{t}\frac{1}{(1-x)^{a+1}}dx&=(1-t)^{\frac a2}\left[\frac{(1-x)^{-a}}{a}\right]_{0}^{t}\\&=(1-t)^{\frac a2}\left(\frac{(1-t)^{-a}}{a}-\frac{1}{a}\right)\\&=\frac{1}{a}\left(\frac{1}{(1-t)^{\frac a2}}-(1-t)^{\frac a2}\right)\end{align}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Roblox Studio: if then else error, attempted everything I don't know what is wrong, it keeps repeating the same error of:
Issue
local clicker = script.Parent.ClickDetector
local canclick = true

local chance = math.random(1,3)
if chance == 1 then
clicker.MouseClick:connect(function(Player)
    if canclick then
        if Player:FindFirstChild("Stand").Value == "The World" then
            Player:FindFirstChild("Stand").Value = "Nightmare World"
            canclick = true
            Player:LoadCharacter()
            script.Parent:Remove()
        else
    clicker.MouseClick:connect(function(Player)
    if canclick then
            Player:FindFirstChild("Stand").Value = "None"
            canclick = true
            Player:LoadCharacter()
            script.Parent:Remove()
        end
    end
end)

I've tried putting ends and then replacing ends and even added parentheses, but nothing will work.
If you could somehow rewrite the code, or help me with it, that would be greatly appreciated.

A: local clicker = script.Parent.ClickDetector
local canclick = true

local chance = math.random(1,3)
if chance == 1 then
clicker.MouseClick:connect(function(Player)
    if canclick then
        if Player:FindFirstChild("Stand").Value == "The World" then
            Player:FindFirstChild("Stand").Value = "Nightmare World"
            canclick = true
            Player:LoadCharacter()
            script.Parent:Remove()
        else
            clicker.MouseClick:connect(function(Player)
                if canclick then
                    Player:FindFirstChild("Stand").Value = "None"
                    canclick = true
                    Player:LoadCharacter()
                    script.Parent:Remove()
                end
            end) -- here
        end
    end
end)

You forgot the closing bracket and an end statement!  I highlighted it with a comment. :)  I didn't test it, but if it doesn't work I'll look over it again.


text:
Q: Unity Button dont want to close a canvas Hello i made a canvas in unity.
when the player preses the Esc button a canvas opens
In the canvas i made a button when the player clicks on the button the
Canvas need to close but nothing happens when i press the button.
Can somebody help me with this problem?
The Canvas
 using UnityEngine;
using System.Collections;
using System;
using UnityEngine.SceneManagement;

public class PauseMenu : MonoBehaviour
{
    private Canvas PlayerPauseMenu;

    // Use this for initialization
    void Start()
    {
        PlayerPauseMenu = GetComponentInChildren<Canvas>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        HandleInput();

    }

    private void HandleInput()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            PlayerPauseMenu.enabled = true;

        }
    }
    public void CloseCanvas()
    {

            PlayerPauseMenu.enabled = false;
    }

    }


text:
Q: Grails View Renders Extra Comma For DTO Object List I am working on upgrading a Grails 4.0.0 app to 4.0.4. Application is mostly working working.
I am having trouble with one GSON view that returns a collection of DTO's (not a domain object).
Versions: Grails 4.0.4, GORM 7.0.6.RELEASE, Win10, openjdk 1.8.0_262
It returns an array of expected objects but, in 4.0.4, with an extra comma before the fields after the opening curly bracket i.e.:
[{,*MY EXPECTED OBJECT 1 DATA*} , {,*MY EXPECTED OBJECT 2 DATA*}]

which upsets the client. The view looks like:
    import com.myapp.dto.MyDTO

    model {
        List<MyDTO> MyDTOList
    }

    json g.render(template: "itemView", collection: MyDTOList)

The MyDTOList view causes the problem even with just one field:

    json g.render(MyDTO) {
    afield MyDTO.afield
    }

If I remove the afield from the view (i.e. a blank view) then no extra comma is inserted. Please let me know if I can provide more information. Thanks.

A: You haven't described the desired structure of the response but here is a reasonable guess...
See the project at https://github.com/jeffbrown/daftspanieljson.
https://github.com/jeffbrown/daftspanieljson/blob/dc54db2dc55db36df16338c88c106e67b1c6ecc4/grails-app/controllers/daftspanieljson/MyDTOController.groovy
package daftspanieljson

import com.myapp.dto.MyDTO

class MyDTOController {
    static responseFormats = ['json', 'xml']

    def index() {
        def data = [new MyDTO(afield: 'MY EXPECTED OBJECT 1 DATA'),
                    new MyDTO(afield: 'MY EXPECTED OBJECT 2 DATA')]

        respond data
    }
}

https://github.com/jeffbrown/daftspanieljson/blob/dc54db2dc55db36df16338c88c106e67b1c6ecc4/grails-app/views/myDTO/index.gson
import com.myapp.dto.MyDTO

model {
    List<MyDTO> myDTOList
}

json tmpl.itemView(myDTOList)

https://github.com/jeffbrown/daftspanieljson/blob/dc54db2dc55db36df16338c88c106e67b1c6ecc4/grails-app/views/myDTO/_itemView.gson
import com.myapp.dto.MyDTO

model {
    MyDTO myDTO
}

json {
    afield myDTO.afield
}

When I run that app and send a request to that action, I get the following response:
[
    {
        "afield": "MY EXPECTED OBJECT 1 DATA"
    },
    {
        "afield": "MY EXPECTED OBJECT 2 DATA"
    }
]


text:
Q: PHP Get Id from Url .$_GET['id']; How can I use the
.$_GET['id'];

After Domain.com Like This
Domain.com/.$_GET['id'];
($curl = curl_init('https://nombre.is/stream.php?mid=.$_GET['id']');)

If I try to do it, it's contradictory to the page file.
<?php
  $curl = curl_init('https://nombre.is/stream.php?mid=.$_GET['id'];');
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
  $page = curl_exec($curl);
  if(curl_errno($curl)) // check for execution errors
  {
    echo 'Scraper error: ' . curl_error($curl);
    exit;
  }
  curl_close($curl);
?>

Has anyone an idea on how to fix this?

A: You should use string concatenation with the dot . operator, like so.
$curl = curl_init('https://nombre.is/stream.php?mid=' . $_GET['id']);

A: i am assuming you want to use id value from $_GET into string URL ?
  $id = $_GET['id'];
  $curl = curl_init("https://nombre.is/stream.php?mid=$id");

OR
  $curl = curl_init("https://nombre.is/stream.php?mid=" . $_GET['id']);

both will work
an other example as per your comment
$page_url = curPageURL();
$curl = curl_init('nombre.is/' . $page_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$page = curl_exec($curl);

or
$curl = curl_init('nombre.is/' . curPageURL());
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$page = curl_exec($curl);

A: There's two ways of doing this! You can either use { } around the $_GET variable, which you should use when trying to pull a value from an array into a string, or you can use the concatenation operator . to join the two values together and append the $_GET['id'] to the end of the URL string.
Option 1:
$curl = curl_init("https://nombre.is/stream.php?mid=${_GET['id']});

Or using the . operator:
$curl = curl_init("https://nombre.is/stream.php?mid=" . $_GET['id']);


text:
Q: Find index of an element in a vector given a pointer to that element I have a vector of structs, like so: std::vector<mystruct> elems.
If I then have a mystruct pointer, which I know is pointing to one of the elements of elems, how can I get its index within elems?

A: Elements must be stored contiguously. Therefore:
mystruct * elem; // definitely within the vector
mystruct * first = &elems[0];
std::vector<mystruct>::size_type index = elem - first;

technically though should use ptrdiff_t rather than size_type to subtract pointers.

A: ptr - &elems[0];
As of C++03, vector storage is required to be contiguous, and the definition of "contiguous" in the standard is that &v[n] == &v[0] + n;
[Edit: from a fairly theoretical portability point of view, beware that implementations are permitted to define SIZE_MAX and ptrdiff_t such that it's possible to subtract two pointers within the same object with undefined result. You'd hope that no implementation will arrange for that to actually cause problems, but you never know. It's fairly easy for the implementation to avoid - just don't return allocations that big]


text:
Q: From a place outside my home network how can I use RDP to connect to a computer at home that is using a vpn Sorry for the loaded question, but its rather specific.
So, I have a second computer that I currently use a VPN with a static IP on. I would like to be able to control this computer remotely while it is connected to the vpn. I am able to forward the connection so that I am able to connect to my it on the home network's IPv4 (When not connected to the vpn) but if it is connected to the VPN, it receives no respond / the connection is terminated if I connect to the VPN while connected. How can I get around this.
Please let me know if I'm leaving out any crucial information. Thank you


text:
Q: avoid full index scan I use test db from  MySQL employees - test db
I want to optimize query
SELECT emp_no, SUM(salary)
FROM salaries
WHERE from_date < '1999-01-01'
group by emp_no;

Query cost: 287790
which indexes can help me ?
I try to create index with emp_no and salary, and emp_no and from_date but there is no result. There is a full scan index.
Also tried to use OVER(PARTITION BY) instead GROUP BY
SELECT emp_no, SUM(salary) OVER (PARTITION by emp_no)
FROM salaries
WHERE from_date < '1999-01-01';

to avoid full index scan for instance or use OVER instead GROUP BY

A: To get an execution plan that avoids a full scan, MySQL would need an index that has from_date as the leading column.
Optimally, the index would contain all of the other columns referenced in the query, to avoid looking up values in the underlying data pages.
Note that if the execution plan makes use of that index, then it will need to invoke a "Using filesort" operation to satisfy the GROUP BY.

A: It depends on what version you are running.
Older version:  INDEX(from_date, emp_no, salary) is "covering" and will do a "range" scan of part of the index.  However the GROUP BY will probably involve a sort.
Newer version:  INDEX(emp_no, from_date, salary) is also "covering", but can hop through the index without having to touch every row.  This can probably avoid the sort.
Here's another thing to test:
SELECT emp_no,
       ( SELECT SUM(salary) FROM salaries
             WHERE emp_no = e.emp_no
               AND from_date < '...')
    FROM employees AS e

Note:  I am assuming employees has one row per employee, unlike salaries??  This approach avoids the GROUP BY, but has the overhead of a correlated subquery.  Now salaries needs INDEX(emp_no, from_date, salary) -- in this order, and does a smaller range scan in the index each time.


text:
Q: Compile time error while integrating Level Helper code in Cocos2d project I am trying to add Levels into my cocos2d game using sprite builder and level helper. After I add all the files into the project that are generated by level helper, my project starts giving me error. I have attached an image which shows the error that I am getting. Any help will be greatly appreciated.Thanks

A: I just tested LevelHelper code against ARC (again) and all is compiling just fine. Please, when you have LevelHelper related problems write on GameDevHelper.com forum so that i can answer you asap.
Your problems seam to be related with a missing inclusion as Steffen mentioned.

A: No interface for NSObject could mean there's a #import <Foundation/Foundation.h> missing.


text:
Q: Group all lines with the same word in first column in csv I have two columns in my csv file: first_column and second_column. I would like to group all the rows in second column into one string separated by "," if they all have the same word in the first column then output them into a text file.
first_column   second_column
a              Chris
a              Jake
a              Paula
b              Anita
b              Lionel
b              Sheila

Desired output
a: Chris, Jake, Paula
b: Anita, Lionel, Sheila

This is what I tried. I seem to be only getting the first letter from the second_column. Any pointers would be great.
$csv_file = fopen("test.csv", "r");
$text_file = fopen("test.txt","w");

$data = array();

if ($csv_file)
{
    while (($line = fgets($csv_file)) !== false)
    {
        $column_1 = $line[0];
        $column_2 = $line[1];

        if (!empty($column_1))
        {
            $data [$column_1] = column_2;
        }
    }

    fclose($csv_file);
    fclose($text_file);
}

else
{
    // error opening the file.
}

//print_r($data);

A: This should work for you:
Here I first get your .csv file into an array with file(). Then I loop through each line and create an array, where the first column is the key and the second column a value of the sub array.
After this you can loop through your created array and implode() each sub array with the key to the expected line which you want. Then you can just save the data with file_put_contents() into your .txt file.
<?php

    $csv_file = "test.csv";
    $text_file = "test.txt";

    $lines = file($csv_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    array_shift($lines);
    foreach($lines as $line) {
        list($key, $value) = explode(",", $line);  //Change your .csv delimiter here, if you use something else than ,
        $data[$key][] = $value;
    }

    foreach($data as $key => $arr)
        $content[] = $key . ": " . implode(",", $arr) . PHP_EOL;

    file_put_contents($text_file, $content);

?>

A: Storing result in an data array and then wring it bacj to text file should work.
$csv_file = fopen("test.csv", "r");
$text_file = fopen("test.txt","w");

$data = array();

if ($csv_file)
{
  while (($line = fgets($csv_file)) !== false)
  {
     $column_1 = $line[0];
     $column_2 = $line[1];

     if (!isset($data[$column_1]))
     {
        $data[$column_1] = column_2
     } else {
        $data[$column_1] = $data[$column_1] .',' . $column_2
     }
  }

   foreach($data as $k=>$d ){
      fputs($text_file, "$k: $d") ;
  }

   fclose($csv_file);
   fclose($text_file);
}
else
{
  // error opening the file.
}


text:
Q: Customizing aesthetics of faceted barplot I am trying to do some analysis of the recent MLB draft with some ggplots in R
selection <- draft[c("Team","Division","Position")]
head(selection)

  Team   Division Position
1  pit NL Central        P
2  sea AL West           P
3  ari NL West           P
4  bal AL East           P
5  kc  AL Central        O
6  was NL East           I

where P = Pitcher , O=Outfield etc.
I want to show the number of players selected by team by position within each division
p <- ggplot(data=selection, aes(x=Team, fill= Position))  + geom_bar(position="stack")
p <-  p + coord_flip()
p <- p+ ylab("Players Selected")
p <- p + facet_wrap(~Division)
p

This gets me part of the way there but is very unattractive
a) the groupings work but all teams are shown in each divison grid - even though only the 5 or 6 team in each division  actually - and correctly - show data
b) With the co-ord flip, the teams are listed in reverse alphabetical order down page. can I resort. It would also be nice to have left justification
c) How do i set the legend to Pitching, Outfield rather than P and O - is this a vector i somehow need to set and include
d) It would also be interesting to see the proportion of each teams selection committed to each type of player. This is accomplished by  setting position= "fill". Can i set the axes to % rather than 0 to 1. I also tried setting a geom_vline(aes(xintercept=0.5) -and yintercept in case the flip factored in -
 but the line did not appear at halfway mark along the x axis
Help much appreciated

A: edit: complete revamping, including info from other answer, after grabbing the data (and storing it in a text file called mlbtmp.txt) and some more experimentation:
selection <- read.table("mlbtmp.txt",skip=1)
names(selection) <- c("row","League","Division","Position","Team")
## arrange order/recode factors
selection <- transform(selection,
       Team=factor(Team,levels=rev(levels(Team))),
                   Position=factor(Position,levels=c("P","I","C","O"),
                                  labels=c("Pitching","Infield",
                                    "Center","Outfield")))

I played around with various permutations of facet_grid, facet_wrap, scales, coord_flip, etc.. Some worked as expected, some didn't:
library(ggplot2)
p <- ggplot(data=selection, aes(x=Team, fill= Position))  +
  geom_bar(position="stack")
p + facet_grid(.~Division,scales="free_x") + coord_flip()  ## OK

## seems to fail with either "free_x" or "free_y"
p + facet_grid(Division~.,scales="free") + coord_flip()

## works but does not preserve 'count' axis:
p + facet_wrap(~Division,scales="free")

I ended up with facet_wrap(...,scales="free") and used ylim to constrain the axes.
p + facet_wrap(~Division,scales="free") + coord_flip() +
  ylim(0,60) + opts(axis.text.y=theme_text(hjust=0))

In principle there might be a way to use ..density.., ..ncount.., ..ndensity.., or one of the other statistics computed by stat_bin instead of the default ..count.., but I couldn't find a combination that worked.
Instead (as is often the best solution when stuck with ggplot's on-the-fly transformations) I reshaped the data myself:
## pull out Team identification within Division and League
stab <- unique(subset(selection,select=c(Team,Division,League)))
## compute proportions by team
s2 <- melt(ddply(selection,"Team",function(x) with(x,table(Position)/nrow(x))))
## fix names
s2 <- rename(s2,c(variable="Position",value="proportion"))
## merge Division/League info back to summarized data
s3 <- merge(s2,stab)

p2 <- ggplot(data=s3, aes(x=Team, fill= Position,y=proportion))  +
  geom_bar(position="stack")+scale_y_continuous(formatter="percent")+
  geom_hline(yintercept=0.5,linetype=3)+ facet_wrap(~Division,scales="free") +
  opts(axis.text.y=theme_text(hjust=0))+coord_flip()

There's obviously a little more prettying-up that could be done here, but this should get you most of the way there ...

A: Filling in some gaps from @Ben Bolker's answer...
To order the teams differently, you'll need to store that column as a factor. There probably won't be a short, quick way to specify the order you want, since you most likely want to order the teams in each division separately. This means you'll need to order all teams such that each division subset remains properly ordered. Something like (this is schematic, not syntatically correct):
selection$Team <- factor(selection$Team,
    levels=c( (AL East teams in desired order),
              (AL Central teams in desire order), etc))

Depending on what other stuff you have calculated there may be a quick way to specify that, or you might have to write them out by hand.
Axis text justification can be modified via
opts(axis.text.x=theme_text(hjust=1))

Stepping back a bit, notice that with ggplot2 the solution is often found by modifying your data that is used to build the plot, not the plot itself. It's a different way of thinking about things, but handy once you get used to it.


text:
Q: JSFiddle code cannot run when out of JsFiddle environment My code for a simple anti-cyberbullying plugin works perfectly in JSFiddle, but doesn't run in my website, even when I add document.ready and use a c+p cleanser like jslint. The code does not have any warnings on JSFiddle. I have reviewed this page:(JSFiddle code not working in my own page), but this doesn't seem to be applicable to my question. Why does the code not run in other environments when it is functional on JSFiddle?
Here's the JSFiddle:
The Code
Here is the exact JS I am using in my website:
$(document).ready(function() {
  var triggerWords = ["stupid",
    "ugly",
    "fat",
    "kill",
    "dumb",
    "idiot",
    "freak",
  ];
  $(document).on('keyup', 'textarea', function humhm {
    for (var i = 0; i < triggerWords.length; i++) {
      if ($(this).val().toLowerCase().indexOf(triggerWords[i]) != -1) {

        document.getElementById("styled").className = "mystyle";
        document.getElementById("shover").className = "mason";
        const messages = ['Words mean a lot. Their echoes can brighten someone\'s day. Or they can make a bad day worse. Consider the person behind the screen.', 'Your words can be a force for happiness or dejection. Choose carefully.', 'Be mindful of your words. Would you say this in real life?', 'Consider the impact your words may have. A couple insults slung casually can be much more significant to others.', 'Words that are insignificant to you can deeply hurt another. Be empathetic. Be nice.'];
        const randomIndex = Math.round(Math.random(messages.length * 10 - 0.5));
        document.getElementById("shover").innerHTML = messages[randomIndex];
        document.getElementById("usual").className = "noshow";
        document.getElementById("trigger").className = "norm";
      }
    }
  });

});
'

A: Are you importing JQuery? Commonly 'rare' errors coming from simple problems.

I recommend to you make your code more human readable taking advantage of JQuery you can replace all document.getElementById("ID_VALUE") for $('#ID_VALUE')
PD: Good luck with that anti-cyberbulling. Important stuff.

A: You need to import jQuery.
The JSFiddle does indeed import it.


text:
Q: regex pattern fails for length of intermediate string I need to check if the string provided by the user starts with abc and ends with de with 4 characters in between like
"abc<4 characters>de".

I tried using pattern ("^abc.*(4)de$")
But it fails for the 4 characters in middle. Is there any problem with pattern.

A: To say you need exactly four characters, you can use one of those:
"^abc.{4}de$"
"^abc....de$"

A: Change the () brackets with {}
^abc.{4}de$

which means that the matching word should start with abc and end with de and in between there should be excactly 4 characters.
A simpler solution is just to place a . between the start and the end pattern to describe that there should be exactly four characters:
^abc....de$

A: Use this regular expression :
^abc.{4}de$

.{4} is exactly what it seems : any character (.) exactly 4 times.

A: Modify RegEx to following
Pattern p = Pattern.compile("^abc.{4}de$");
         Matcher m = p.matcher("abc11111de");
         boolean b = m.matches();
         System.out.println(b);


text:
Q: $\mathbb Z_n^*$ has a unique subgroup of order $2$ then it is cyclic for $n >2$ If $\mathbb Z_n^*$ has a unique subgroup of order $2$  then it is cyclic, where $n>2$. That is, we have to show $n= 4, p^k,2p^k, p $ is odd prime.
I don't know if it is correct statement or not. But I suppose it is correct. If it is true please provide some hints to prove, otherwise please give some counter-example.

A: $Hint:$ If an abelian group $G$ can be written as $A \times B \times C$, with $A$ and $B$ of even order, then $G$ has at least two elements of order $2$.
Apply this to the decomposition
$$
(\mathbb{Z}/n\mathbb{Z})^\times\cong (\mathbb{Z}/{p_1^{k_1}}\mathbb{Z})^\times \times (\mathbb{Z}/{p_2^{k_2}}\mathbb{Z})^\times  \times (\mathbb{Z}/{p_3^{k_3}}\mathbb{Z})^\times \times \cdots
$$
given by the Chinese remainder theorem when $n=p_1^{k_1}p_2^{k_2}p_3^{k_3}\cdots$.


text:
Q: 'AxesSubplot' object has no attribute 'colorbar' I'm trying to run a python code to build a ternary vertex diagram A, B and C, in which I want to visualize a scatterplot, using the matplotlib library, but I'm getting the error AttributeError: 'AxesSubplot' object has no attribute 'colorbar '
The error message is
AttributeError                            Traceback (most recent call last)
<ipython-input-52-e3818f5603ff> in <module>
    136 bounds = [1, 2, 3, 4, 5, 10]
    137 norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
--> 138 ter.plot2(ax, fig, cmap, norm, bounds)

<ipython-input-52-e3818f5603ff> in plot2(self, ax, fig, cmap, norm, bounds, scale_factor, weight_label, color_label, label, tet_marks, graduation_step, show_scale, show_legend)
     78         divider = make_axes_locatable(ax)
     79         cax = divider.append_axes('right', size='5%', pad=0.05)
---> 80         cbar = fig.colorbar(dat, cax=cax, format='%.2f', ticks=bounds)
     81         cbar.ax.tick_params(labelsize=12)
     82         if len(self.labels) > 0:

AttributeError: 'AxesSubplot' object has no attribute 'colorbar'

import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import matplotlib.cm as cm
import numpy as np
import matplotlib as mpl
import pandas as pd
import matplotlib as mpl
from math import sqrt
from matplotlib.ticker import LogFormatter
from mpl_toolkits.axes_grid1 import make_axes_locatable

dataset = pd.read_excel('/content/Sequecia BC74 teste v2.xlsx')

class Ternary:
    font_size = 12
    plot_size = 12

    def __init__(self, label_A: str = "A", label_B: str = "B", label_C: str = "C",
                 min_ternary: float = 0):
        self.label_A = label_A
        self.label_B = label_B
        self.label_C = label_C
        self.min_ternary = min_ternary
        self.weights = []
        self.colors = []
        self.labels = []
        self.X = []
        self.Y = []
        self.Z = []

    def append_data(self, A, B, C, weights=None, colors=None, tick_label: list=[]):
        self.weights = []
        self.colors = []
        self.labels = []
        if len(A) != len(B) or len(B) != len(C):
            print("ERROR in append_data, table length are different")
        else:
            for i in range(len(A)):
                if A[i] + B[i] + C[i] >= self.min_ternary:
                    self.X.append(0.5 * (2 * C[i] + B[i]) / (A[i] + B[i] + C[i]))
                    self.Y.append(sqrt(3) * 0.5 * B[i] / (A[i] + B[i] + C[i]))
                    if weights is not None:
                        self.weights.append(weights[i])
                    else:
                        self.weights.append(1)
                    if colors is not None:
                        self.colors.append(colors[i])
                    else:
                        self.colors.append(1)
                    if len(tick_label) > 0:
                        self.labels.append(tick_label[i])

    def plot2(self, ax, fig, cmap, norm, bounds, scale_factor: int = 1, weight_label: str = None, color_label: str = None,
              label: str = "Ter", tet_marks: bool = False, graduation_step: float = 10,  show_scale: bool = True,
              show_legend: bool = True):
        self.plot_frame(ax=ax, graduation_step=graduation_step, tetrahedron_marks=tet_marks)
        #
        #Label
        label_points = label + " - " + str(len(self.X)) + " inclusions"
        if weight_label is not None:
            label_mean = "Mean " + weight_label + ": " + str(np.round(np.mean(np.asarray(self.weights)), 2))
        else:
            label_mean = "Mean"
        if color_label is not None:
            label_mean += " / color coding: " + color_label
        #
        #Plot data
        if len(self.labels) > 0:
            if len(np.unique(np.asarray(self.labels))) > 10:
                cmap = cm.tab20
            else:
                cmap = cm.tab10
            unique, index, inverse = np.unique(self.colors, return_index=True, return_inverse=True)
            self.colors = inverse
            bounds = range(len(np.unique(np.asarray(self.labels)[index])))
        dat = ax.scatter(self.X, self.Y, s=[x * scale_factor for x in self.weights], label=label_points, c=self.colors,
                         cmap=cmap, norm=norm, edgecolors="k", linewidth=0.25)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        cbar = fig.colorbar(dat, cax=cax, format='%.2f', ticks=bounds)
        cbar.ax.tick_params(labelsize=12)
        if len(self.labels) > 0:
            cbar.ax.set_yticklabels(np.asarray(self.labels)[index])
        #
        #Plot Mean
        ax.scatter(np.mean(np.asarray(self.X)), np.mean(np.asarray(self.Y)),
                   s=scale_factor * np.mean(self.weights), label=label_mean, edgecolors="k", linewidth=0.25,
                   color="black")
        ax.legend(fontsize="large", loc="upper right")
        return dat

    def plot_frame(self, ax, graduation_step: float = 10, tetrahedron_marks: bool = False):
        T1 = [0, 0.5]
        TT1 = [x * sqrt(3) for x in T1]
        T2 = [0.5, 1]
        TT2 = [(-x * (sqrt(3))) + sqrt(3) for x in T2]
        T3 = [0, 1]
        TT3 = [0 * x for x in T3]
        ax.plot(T1, TT1, c='black', lw=0.5)
        ax.plot(T2, TT2, c='black', lw=0.5)
        ax.plot(T3, TT3, c='black', lw=0.5)
        for x in np.linspace(graduation_step, 100 - graduation_step, int((100 / graduation_step) - 1)):
            x = x/100
            T = [x, x + 0.5 * (1 - x)]
            TT = [sqrt(3) * (y - x) for y in T]
            ax.plot(T, TT, c='grey', lw=0.2)
            T = [0.5 * x, 1 - 0.5 * x]
            TT = [sqrt(3) * 0.5 * x for y in T]
            ax.plot(T, TT, c='grey', lw=0.2)
            T = [(1 - x) * 0.5, 1 - x]
            TT = [-sqrt(3) * y + sqrt(3) * (1 - x) for y in T]
            ax.plot(T, TT, c='grey', lw=0.2)
        ax.axis([-0.1, 1.1, -0.025, 1])
        ax.text(-0.05, 0, self.label_A, fontsize=self.font_size)
        ax.text(0.5, (0.5 * sqrt(3)) * (1 + 0.02), self.label_B, fontsize=self.font_size)
        ax.text(1 + 0.02, 0, self.label_C, fontsize=self.font_size)
        if tetrahedron_marks:
            T1 = [0, 0.5]
            TT1 = [x * 2 * sqrt(1 / 12) for x in T1]
            T2 = [0.5, 1]
            TT2 = [(-x * 2 * sqrt(1 / 12) + 2 * sqrt(1 / 12)) for x in T2]
            T3 = [0.5, 0.5]
            TT3 = [sqrt(1 / 12), sqrt(3) / 2]
            ax.plot(T1, TT1, c='black', lw=0.5)
            ax.plot(T2, TT2, c='black', lw=0.5)
            ax.plot(T3, TT3, c='black', lw=0.5)
        ax.set_aspect(aspect="equal")
        ax.axis("off")

ter = Ternary()
ter.append_data(dataset['CaOMnOMgO'], dataset['SiO2'], dataset['Al2O3'],dataset['Tamanho'],dataset['O2'])
fig = plt.subplot()
ax = plt.subplot()
cmap = mpl.cm.coolwarm
bounds = [1, 2, 3, 4, 5, 10]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
ter.plot2(ax, fig, cmap, norm, bounds)

My goal is to generate this ternary diagram (attached image)

A: This issue is how you create your fig object. Here you are calling the plt.subplot() function twice:
fig = plt.subplot()
ax = plt.subplot()

This will create to Axes instances, one called fig, and one called ax. What you actually want is a Figure instance and an Axes instance. You can use the plt.subplots() function to get both in one go.
fig, ax = plt.subplots()

Then your code should work as expected; .colorbar() is a function of the Figure class, not the Axes class.


text:
Q: How to combine 2 tables and insert values into a 3rd table I have 2 tables formatted the following ways listed below...
T1
ID   SUB_ID   NAME   NUM
123  ABC      TEST   5
456  XYZ      HELLO  10

T2
ID   SUB_ID   NAME   NUM  CAT  ACTY
123  ABC      TEST   5    sjq  h5h
456  XYZ      HELLO  10   hwl  888

I want to look at these 2 tables and match based on ID and SUB_ID and join them together so I get all the columns from T1 and those columns missing from T1 that are in T2
Both these tables contain thousands of rows but I simplified for this example.
This is the code I have tried but I am getting to many rows back..
SELECT *
FROM T1 YY
INNER JOIN T2 ZZ
WHERE YY.ID = ZZ.ID and YY.SUB_ID = ZZ.SUB_ID

Any help on how to execute this would be GREATLY appreciated. THANKS!!

A: I am  going to go out on a "guess" here with (THE WHERE CLAUSE IS A GUESS ONLY)
INSERT INTO T3
 (ID, SUB_ID, NAME, NUM, CAT, ACTY)
SELECT T1.ID, T1.SUB_ID, T1.NAME, T1.NUM,
      T2,CAT,  T2.ACTY
FROM T1
INNER JOIN T2
    ON T1.ID = T2.ID
       AND T1.SUB_ID = T2.SUB_ID
WHERE (T1.ID = 123 AND T1.SUB_ID = 'ABC')
   OR (T1.ID = 456 AND T1.SUB_ID = 'XYZ')

IF T3 has an identity on the ID you may have to alter query to account for that.
In reference to my comment this seems to be the same result:
INSERT INTO T3
 (ID, SUB_ID, NAME, NUM, CAT, ACTY)
SELECT T2.ID, T2.SUB_ID, T2.NAME, T2.NUM, T2,CAT, T2.ACTY
FROM T2
WHERE (T1.ID = 123 AND T1.SUB_ID = 'ABC')
   OR (T1.ID = 456 AND T1.SUB_ID = 'XYZ')

A: Your code (something similar to below) is correct, but may surprise you if one or the other tables has more than one row with the same ID and SUB_ID.
SELECT *
FROM T1 YY
INNER JOIN T2 ZZ
WHERE (YY.ID = ZZ.ID AND YY.SUB_ID = ZZ.SUB_ID)

The following example records will return 4 rows, not 2, because each of the rows in the first table matches 2 rows in the second table.
T1
ID   SUB_ID   NAME   NUM
123  ABC      TEST   5
123  ABC      TEST2  10

T2
ID   SUB_ID   NAME   NUM  CAT  ACTY
123  ABC      TEST   5    sjq  h5h
123  ABC      TEST2  10   hwl  888


text:
Q: Is it possible to return multiple values from an external file to Dymola? For example, I have a C external function that returns a structure. Is it possible to return the structure to Modelica?
struct point{
   double x;
   double y;
}

struct point return_Struct(double a, double b){
    struct point pt;
    pt.x = a;
    pt.y = b;
    return pt;
};

In Modelica,
function structReturn
  input Real x;
  input Real y;
  output ??????;
external"C" ????? = return_Struct(x,y)
  annotation (Include="#include <cStructReturn.c>");
end structReturn;

A: Use a record and pass it by reference. See section 12.9.1.3 Records in the Modelica specification. Note that the record may have a different name in the Modelica tool from what you expect, so pass it through void* and cast it explicitly. Use a library not an included C-file to hide the interface or the code might not compile.
void return_Struct(double a, double b, void* result){
    struct point *pt = result;
    pt->x = a;
    pt->y = b;
};
record R
  Real x,y;
end R;

function structReturn
  input Real x;
  input Real y;
  output R r;
external"C" return_Struct(x,y,r)
  annotation (Library="cstructreturn");
end structReturn;
But I recommend passing 2 reals as output of the external function and constructing the record in a Modelica wrapper function instead.
function multipleReturn
  input Real x;
  input Real y;
  output Real ox;
  output Real oy;
external"C" return_notStruct(x,y,ox,oy)
  annotation (Library="cstructreturn");
end multipleReturn;


text:
Q: How to get values from a column based on values in another column in pandas I have a dataframe that looks like sample DF below:
import pandas as pd
df = pd.DataFrame({'user_id' :
                   ['aefc6',
                    '7edc3',
                    '6f85b',
                    '6f99b',
                    '6f85b'],
                   'user_name' : ['john', 'jack', 'jill', 'tom', 'jill'],
                   'Event' : ['A','B','C','D', 'E'],
    'Collabs' : ['adsfkj', '6f85b,asdfad', 'adfad', '9b123', '101bv']
})

The scenario is the user_id, user_name columns are those of event managers. But some event managers are also collaborators for some other event as can be seen in the example of "jill" who was a collaborator for Event B.
The "collabs" column is a CSV column and I unnest it as below:
df['new'] = df['Collabs'].str.split(',')
df = df.explode('new')
df['exist'] = df['new'].map(lambda x : x in '|'.join(df['user_id']))

As mentioned above, we can see that 'jill' with user_id 6f85b is present in the Collab column. My requirement is I need to get the user_id and user_name of those who appear in the new column or where exist column is True. I.E I need to get the ids and names of managers who acted as collaborators for other events.
Expected output:
    user_id user_name   Event    Collabs        new     exist   collab_user_id  collab_user_name
0   aefc6   john        A        adsfkj         adsfkj  FALSE   NaN             NaN
1   7edc3   jack        B        6f85b,asdfad   6f85b   TRUE    6f85b           jill
1   7edc3   jack        B        6f85b,asdfad   asdfad  FALSE   NaN             NaN
2   6f85b   jill        C        adfad          adfad   FALSE   NaN             NaN
3   6f99b   tom         D        9b123          9b123   FALSE   NaN             NaN
4   6f85b   jill        E        101bv          101bv   FALSE   NaN             NaN

I tried joining:
pd.merge(df, df.loc[:,['user_name', 'new']], left_on = 'user_id', right_on = 'new', how = 'left')

But instead of "jill" the output (understandably) is having "jack". Could someone please let me know how to get the desired output.

A: You can use isin to create exist column then use np.where to create collab_user_id and map the user_name to collab_user_name
df['exist'] = df['new'].isin(df['user_id'])
df['collab_user_id'] = np.where(df['exist'], df['new'], np.nan)
df['collab_user_name'] = df['collab_user_id'].map(dict(zip(df['user_id'], df['user_name'])))

  user_id user_name Event       Collabs     new  exist collab_user_id collab_user_name
0   aefc6      john     A        adsfkj  adsfkj  False            NaN              NaN
1   7edc3      jack     B  6f85b,asdfad   6f85b   True          6f85b             jill
1   7edc3      jack     B  6f85b,asdfad  asdfad  False            NaN              NaN
2   6f85b      jill     C         adfad   adfad  False            NaN              NaN
3   6f99b       tom     D         9b123   9b123  False            NaN              NaN
4   6f85b      jill     E         101bv   101bv  False            NaN              NaN


text:
Q: Angular material datepicker does't arrange items on a single row In my web application I'm using an angular material datepicker.
The issue is that it does not show all the elements in a row.
This is my view:
Datepicker
To avoid that my customized css has an impact on the view I removed every customized style.
This way, my html is very simple. I simply copied and pasted the angular material example from angular official portal (basic datepicker item):
<mat-form-field appearance="fill">
  <mat-label>Choose a date</mat-label>
  <input matInput [matDatepicker]="picker">
  <mat-hint>MM/DD/YYYY</mat-hint>
  <mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

But according to the angular material exaple on-line the image should be something like this:
Basi datepicker from angular material online help
In what am I wrong?

A: Try using matSuffix instead of matIconSuffix in your mat-datepicker-toggle.
Edit following @TotallyNewb's comment.
Angular version <= v14: matSuffix
Angular version >= v15: matIconSuffix


text:
Q: Down-vote reputation penalty is too big Over my time using many of the Stack forums, I have of course asked questions that others thought weren't adequate. I could hardly see why and frankly, it felt somewhat unfair as I could spot many far worse questions than mine which were getting lots of up-votes.
This conundrum has meant that I have been almost incapable of getting my reputation above 5, making it very difficult to effectively contribute to the sites. I have seen my reputation go from almost 100, all the way down to 20 overnight because of one question or one answer (this is an exaggeration).
It's also not explained well how a question is defined as fitting for this site. Nearly all questions except research-able ones have some degree of opinion tied to them - be it in choice of method or choice of answer where there may be multiple. As a result, almost all of the questions I've had have fallen into this category and have received almost cruel responses. What few comments that are left tend not to offer suggestions for improving a question, but instead simply name a vague problem which is of no help what-so-ever.
This could be improved in two ways:

*

*Increasing the reputation penalty to a user who down-votes a question or answer, or add further requirements to allow a down-vote to be acknowledged.

*Decreasing the reputation penalty to a user when one of their questions or answers is down-voted.

The definition of a good question on this site could also be made more clear and understandable. I've asked questions and gone through the entire page on asking a question - making sure I've ticked every box - and then logged on the next morning to find it's on hold for not being specific enough, despite me virtually spoon-feeding all the information I have to the reader and all of the points related to an answer.
UPDATE:
A slightly more significant change that could happen is that questions could enter an admission phase in which questions may be approved or edits suggested. Once 5 suggestions have been completed or the question remains fully approved for an amount of time, it is published to the forum to be answered. This then makes the down-vote virtually obsolete as all questions would be approved.

A: To adress both of your suggestions:

*

*Implementing a penalty to downvote questions and increasing the penalty for downvoting answers is a very bad idea—Voting is an integral part of how the Stack Exchange system works and discouraging people from voting will seriously limit peoples ability to judge the quality of questions and answers.

*The penalty for a downvote (-2) is rather inconsequential already but it is there for a reason, it is there to encourage you to post good questions and answers. If you're getting enough of a penalty for it to significantly affect your reputation then you're doing something wrong. Get to know what is acceptable for the site you are posting on, do your research and post good questions and answers.
With regards to the definition of a good question, that varies a lot depending on which site you are on. There are common sense things that make a good question everywhere (like doing some research first) but anything that is site-specific should be taken up on that sites meta, not here.
With regards to your updated suggestion, you are suggesting a significant change to the entire way StackExchange works. In my opinion it is a terrible idea but regardless of that it's such a change that I doubt it is feasible.

A: It takes five times as many downvotes to reduce your rep by one answer upvote. You have to attract an insane amount of downvotes to lose 80 rep: you really got 40 downvotes, plus 5 more for every upvote? I don't think the problem is the rep system here.
Honestly, I often feel a little bit underpowered with my downvotes. It's death by a thousand papercuts. That can be especially annoying when 5 votes gets unceremoniously eradicated by a stray upvote.


text:
Q: How to globally set the message for a Hibernate Validation constraint? I have the following class that I'm trying to validate via Hibernate:
public class LoginForm
{
    @NotBlank(message = "{myCustomMessage}")
    private String user;

    @NotBlank(message = "{myCustomMessage}")
    private String pw;

   //....
}

This works fine and my custom message is correctly displayed for NotBlank, however if I have to specify the (message = "{myCustomMessage}") line for every single constraint, for every single member, in every single class, its going to become very repetitive.
Is there a way to globally set this message, so it doesn't have to be specified individually for every member? I.e so it will, by default, fetch myCustomMessage for @NotBlank? (And for all the other constraints that I specify it for).
Edit: So if I rename the message key from myCustomMessage to org.hibernate.validator.constraints.NotBlank.message , then I no longer need to specify the (message..) line. However, I'd still prefer if it could be made to work with myCustomMessage globally.

A: As you already found out, the only way would be to specify a value for the default key org.hibernate.validator.constraints.NotBlank.message. You also could define your own NotBlank constraint which specifies the value you want as default value for the message attribute, but I would not really recommend that.


text:
Q: ST STM32H743XI (ARM M7 based) MCU - ADC Configuration I am using the ST STM32H743XI (ARM M7 based) MCU,
I want to use the ADC to measure 7 Hall sensors (use both slow and fast channels),
i need the conversion time for all seven ADC channels to be the same,
How to make the conversion time for the slow and fast channels be exactly the same?

A: In Reference manual section 24.3.13: Channel-wise programmable sampling time:

Constraints on the sampling time for fast and slow channels: For each channel, SMP[2:0] bits must be programmed to respect a minimum sampling time as specified in the ADC characteristics section of the datasheets.

So difference between fast and slow channels is only in minimum sample time.
To have same conversion time check section 24.3.17: Timing in same datasheet. Easiest way would be to have all parameters equal (sample time, data resolution).
If you actualy want to have same sampling frequncy on all channels then you only need to have conversion time smaller (and not equal) than period of ADC.


text:
Q: How do I create a Show instance for b->a in Haskell? I'm trying to construct a datatype that is essentially a binary tree whose: each node's left branch is a function that can act on the variable in each node's right branch. I'm new to Haskell, and I'm not sure I'm going about this the right way, but my current problem is that I can't figure out how to add my type to the Show typeclass. Here is my attempt:
{-# LANGUAGE ExistentialQuantification #-}
-- file: TS.hs

data TypeSentence a = forall b. Apply (TypeSentence (b->a)) (TypeSentence b)
                    | Expr a

instance (Show a) => (Show (TypeSentence a)) where
        show (Expr x) = show x
        show (Apply x y) = (show x) ++ " " ++ (show y)

instance (Show (TypeSentence b->a)) where
    show (Expr x) = show "hello"

x = Expr 1
f = Expr (+1)
s = Apply f x

However, when I load this into ghci I get the following error:
TS.hs:9:24:
     Could not deduce (Show (b -> a)) from the context ()
     arising from a use of `show' at TS.hs:9:24-29
      Possible fix:
      add (Show (b -> a)) to the context of the constructor `Apply'
      or add an instance declaration for (Show (b -> a))
        In the first argument of `(++)', namely `(show x)'
        In the expression: (show x) ++ " " ++ (show y)
        In the definition of `show':
           show (Apply x y) = (show x) ++ " " ++ (show y)
 Failed, modules loaded: none.

Any ideas how I go about adding the Show (b->a) declaration?
Thanks.

A: There are a few problems with your code as written, so I'm going to go through them one by one.

*

*You can't add a particularly informative instance for Show (a -> b).  Consider how you'd have to write it:
instance Show (a -> b) where
  show f = error "What goes here?"

Since f is a function, there's nothing you can do with it other than apply it to a value; and since a is a fully-polymorphic type, you can't create a value of type a to apply f to.  So your only option is something like
instance Show (a -> b) where
  show _ = "<function>"

As Daniel Fischer said in a comment, this is available in the Text.Show.Functions module.  I wouldn't actually bother with this, though; I'd just write something like
instance Show a => Show (TypeSentence a) where
  show (Apply _ x) = "Apply _ " ++ show x -- This still won't work; see below
  show (Expr x)    = "Expr " ++ show x

Since show can only return the one string for any function, just inline that directly.

*Even then, though, you still can't write that Show instance.  If you try to compile the instance above, you get the following error:
TS.hs:8:36:
    Could not deduce (Show b) arising from a use of `show'
    from the context (Show a)
      bound by the instance declaration
      at TS.hs:7:10-40
    Possible fix:
      add (Show b) to the context of
        the data constructor `Apply'
        or the instance declaration
    In the second argument of `(++)', namely `show x'
    In the expression: "Apply _ " ++ show x
    In an equation for `show': show (Apply _ x) = "Apply _ " ++ show x

The problem is that, in your definition of TypeSentence, Apply hides a variable (bound as x in the definition of show) of TypeSentence parametrized by some arbitrary existentially-hidden type b.  But there's no guarantee that b is showable, so show x won't type check, which is the error produced above: there's no instance for Show b, because b is arbitrary.  So to get rid of that, the simplest approach would be
instance Show a => Show (TypeSentence a) where
  show (Apply _ _) = "Apply _ _"
  show (Expr x)    = "Expr " ++ show x

And that's not particularly useful.  So maybe there's not a good Show instance for TypeSentence.  (And that's fine.  Many useful types don't have Show instances.)

*This one's unrelated to everything else.  The instance Show (TypeSentence b -> a) declaration tries to declare an instance of Show for functions from TypeSentence b to a; if you reparenthesize that as instance Show (TypeSentence (b -> a)), you still need both the FlexibleInstances and OverlappingInstances extension to get that to compile.  So that you should probably just axe.

A: Well, let's reason this through.  Your proposed Show instance's show method  will be called with some function f :: b -> a.
instance Show (b -> a) where
    show f = ...

What can your show method do?  Well, it must produce some String, but how will it do it?
Well, since the type of f is b -> a, the only thing you can do with f is apply it to something of type b.  Yet show has no argument of type b, and your Show class doesn't have any constants of type b, so the only thing that this show method could do with f is apply it to undefined.  Which may or may not produce an error, depending on whether f is strict or not—which you have no control over, and I'm sure you don't want show to error out on some arguments anyway.
But in any case, even if you did get a result from f undefined, this result it would have type a, and there really is nothing your definition can do with an a anyway, since you don't have any functions of type a -> whatever available. (And if you did have one, unless whatever was String, you'd still be in the same position.)
So there's nothing sensible you can do with f, and since you have no other arguments, this means that the only thing your method can do is return a value that doesn't depend on f or any other argument.  Thus, your method's return value has to be a constant, or undefined.  Since using undefined would be silly, the only sensible thing this show method can do is return a constant String:
instance Show (b -> a) where
    show _ = "<function>"

As Daniel Fischer mentions in his comment to your question, this is already available in Text.Show.Functions.
But the lesson here is to take this as an example on how to reason through your question.  This is one of the neat things about Haskell: you can often prove what a function can, can't or must do just by looking at the types.  For example, if you have foo :: (a -> b) -> [a] -> [b], assuming foo is not silly enough doesn't use undefined gratuitously, you can infer that the bs in the [b] result are obtained by applying the a -> b type argument to elements of the [a] argument.  There is no other way for foo to produce values of type b.  (If you didn't guess already, the most natural function of that type is map :: (a -> b) -> [a] -> [b].)

A: I think the @Davorak 's comment is what you want.
https://stackoverflow.com/a/15846061/6289448
I just share it here. Pass test in ghc 8.6.5.
There is a partial solution that goes beyond just a fixed string for all functions using Data.Typeable.
{-# LANGUAGE ScopedTypeVariables #-}

import Data.Typeable

instance (Typeable a, Typeable b) => Show (a->b) where
  show _ = show $ typeOf (undefined :: a -> b)

in ghci
> let test :: Int->Int; test x = x + x
> test
Int -> Int

Unfortunately without a type signature the type will go to it default.
> let test x = x + x
> test
Integer -> Integer

This solution works on multiple function arities because a -> b -> c is the same as a -> (b -> c) which you might as well write as a -> d where d = b -> c.
> let m10 a b c d e f g h i j = a * b * c * d * e * f * g * h* i * j
> m10
Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> Integer
        -> Integer -> Integer -> Integer -> Integer

This method does not work however when it is unknown if parameters of the function have the typeable class however so while map (+1) will work map will not.
> map (+1)
[Integer] -> [Integer]
> map

<interactive>:233:1:
...

After glancing at the internals of Data.Data and an experiment or two it seems like it could be refactored to be a little more generalized cover more functions.

If you dont like implemention above, just implement it by yourself!
(Let me know If there's a better way, please!)
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE ScopedTypeVariables #-}

newtype GenType a =
    GenType
        { asTypeStr :: String
        }

class GenTypeArbitrary a where
    gtArbitrary :: a -> GenType a

instance GenTypeArbitrary String where
    gtArbitrary :: String -> GenType String
    gtArbitrary _ = GenType "String123"

instance GenTypeArbitrary Bool where
    gtArbitrary :: Bool -> GenType Bool
    gtArbitrary _ = GenType "Bool123"

instance GenTypeArbitrary Int where
    gtArbitrary :: Int -> GenType Int
    gtArbitrary _ = GenType "Int123"

instance (GenTypeArbitrary a, GenTypeArbitrary b) => GenTypeArbitrary (a -> b) where
    gtArbitrary :: (GenTypeArbitrary a, GenTypeArbitrary b) => (a -> b) -> GenType (a -> b)
    gtArbitrary _ = GenType $ aTypeStr' ++ " --> " ++ bTypeStr
      where
        aTypeStr = asTypeStr (gtArbitrary (undefined :: a))
        aTypeStr' =
            if "-->" `isInfixOf` aTypeStr
                then "(" ++ aTypeStr ++ ")"
                else aTypeStr
        bTypeStr = asTypeStr (gtArbitrary (undefined :: b))

instance  (GenTypeArbitrary a, GenTypeArbitrary b) => Show (a -> b) where
  show f = asTypeStr $ gtArbitrary f

test1 :: Int -> String
test1 x = ""

test2 :: Int -> String -> Int -> Bool -> Bool
test2 _ _ _ _ = False

test3 :: Int -> ((String -> Int) -> Bool) -> Bool
test3 _ _ = False

test4 :: Int -> (Bool -> (String -> Int)) -> Bool
test4 _ _ = False

λ > show  (test4)
    "Int123 --> (Bool123 --> String123 --> Int123) --> Bool123"
it :: String

...

λ > show  (test3)
    "Int123 --> ((String123 --> Int123) --> Bool123) --> Bool123"
it :: String

A: If your function's domain is a finite set then you can print the value of your function at all the points. In Haskell you can do that with the typeclasses Ix and Bounded by using a function like:
rangeF :: (Ix a, Bounded a) => [a]
rangeF = range (minBound, maxBound)


text:
Q: Difference (or quotient) between two 2D (not 1D) histograms (not KDEs) plotted using R and ggplot2? Similar questions have been asked in the past, but I haven't been satisfied with any of the answers and none matches what I require. I believe the problem has been that the questions have been ambiguously posed. I'll try to do better.
Imagine that you have data that describes a process that consists of two components; a signal component and a background component. The data is x, y, and a label that indicates if the (x,y) data point is signal or background. You notice that a 2D histogram (perhaps plotted with ggplot2) of the data seems to look like a flat inclined plane or something similar (this is the background component), with a bump or peak (the signal component) that may be modelled as a 2D Gaussian or something like that. So here's what I want to do: I want to subtract the background component from the data so I just see the signal component. But maybe it's not obvious that there's a bump in the data. Maybe the bump is very small compared to the background component. So what I want to do is subtract the background so that I can search for bumps. And I'd rather not manufacture a bump by some unfortunate choice of parameters for a difference of two KDEs. I just want to bin the data, stratify it by label (signal/background) and subtract one 2D histogram from the other 2D histogram. And then I want to plot that using ggplot2, because I want a nice publication-ready plot. Hexbin plot, tile plot, 2D contour plot, or poly plot with ggplot2 will do nicely. Any ideas on how to do this?
Other similar questions have answers that suggest creating two KDEs and subtracting those, but I don't want this extra layer of complexity. I just want the difference of the raw 2D bin counts. Surely there is a simple way to do this?


text:
Q: Image resolution not showing up in "Get info" dialog in Mac OS X When I bought a Mac Mini with Mac OS X, I could show image dimensions in the Get Info dialog.
After that, I installed some mobile application development software and later I noticed, Get Info was not showing the image dimensions anymore. I need to check the dimensions of those images to include artwork in my project. Now, I reinstalled my Mac OS X and it's working fine – it is showing the dimensions:

Before that, 516x314 was missing. Why did that happen? How can I prevent it from happening again?

A: The dimensions (and other metadata) of a file are stored in the Spotlight index, which allows you to effectively search for specific features. If the image dimensions are not available, this is likely caused by the files not being indexed, or the index being broken.
To solve this, try the following:

*

*In any case, check System Preferences » Spotlight » Privacy. Is any folder containing these images listed there? If yes, remove it from the list.

*To force-reindex Spotlight, you can just add your entire hard drive to this Privacy list, and immediately remove it again.

A: This worked for me (on Mac):

*

*Open the picture in Preview App

*Either:

*

*

*click: Cmd+i

*Or:

*

*

*click: Tools menu

*

*

*click: Show Inspector

*Inspector opens a General Info window. Pixes are shown in the Image Size row.


text:
Q: Python Selenium drag_and_drop promlem I'm trying to perform DND action, and I'm facing a problem that drives me crazy!
For some reason Selenium keeps using my cursor instead of browsers own cursor. Doesn't matter what method I use (I tried drag_and_drop and also combination of click_and_hold() + release() methods, but without any luck), the element is always dropped where my real mouse cursor is. I've seen this problem raised before (here is similar one on Java, also an issue on gitHub, another one), but unfortunately I found no solution. I've spent many hours trying to make it work and I hope someone actually has an experience of solving this problem.
def test_dnd():
  driver = webdriver.Chrome()
  driver.get("https://www.w3schools.com/html/html5_draganddrop.asp")
  driver.find_element(By.CSS_SELECTOR, "#accept-choices").click()
  src = driver.find_element(By.CSS_SELECTOR, "#drag1")
  target = driver.find_element(By.CSS_SELECTOR, "#div2")
  ActionChains(driver).drag_and_drop(src, target).release().perform()


text:
Q: Loop in visual studio We are supposed to create a program that accepts 15 telephone numbers. All numbers consist of 8 digits. Fixed lines start with 17 and mobile lines start with 39. Prog should cout the number of fixed and mobile lines.
Also, prog should stop when the user enters a negative number.
Here is my code:
#include <iostream>
using namespace std;
void main ()
{

int n, c=1, cm=0, cf=0;

cout << "Enter a telephone number or enter a negative number to stop ";

while (c <= 15){
    cin >> n;

    if (n/1000000 == 39){
        c++;
        cm++;
    }

    else if (n/1000000 == 17){
        c++;
        cf++;
    }

    else cout << "Wrong telephone number" << endl;

    cout << "Enter the next telephone number or enter a negative number to stop ";
    cin >> n;

}

cout << "The number of fixed lines is " << cf << endl;
cout << "The number of mobile lines is " << cm << endl;

system ("PAUSE");

}
I have two problems:

*

*I don't know how to end the program when the user enters a negative number.

*Program doesn't cout "Enter the next telephone number or enter a negative number to stop " after entering the second number.

A: *

*to stop loop when user enters negative number you need to use break statement

*check how your logic works: at the end of the loop you're output string, ask for number and go to the start of loop, where you're asking for number again

consider following code:
int n, c=1, cm=0, cf=0;
while (c <= 15) {
    std::cout << "Enter the next telephone number or enter a negative number to stop ";
    std::cin >> n; // output prompt and ask for number only once per loop iteration
    if (n <= 0)
        break; // ends while loop if user entered incorrect value
    if (n/1000000 == 39)
        cm++, c++;
    else if (n/1000000 == 17)
        cf++, c++;
    else
        std::cout << "Wrong telephone number" << std::endl;
}
std::cout << "The number of fixed lines is " << cf << std::endl;
std::cout << "The number of mobile lines is " << cm << std::endl;

A: Problem 1:

*

*you could check for negative and use the keyword break to exit the while loop.

Problem 2:

*

*place: cout << "Enter a telephone number or enter a negative number to stop "; within the while loop.


text:
Q: Using systemdiagnostics.process to run background jobs in Powershell I know Powershell has background job functionality with Start-Job, Wait-Job, etc., but is it possible to use the Process class from System.Diagnostics in .Net to achieve the same thing?  If so, what would be the best way to do it/what advantages would it have over the default Powershell mechanism of running background jobs?

A: You can certainly use the Process object to "start" the executable asychronously and with the process object you get back you can test to see if the EXE is done or kill the process.  The trick is getting the output and error stream information back without interfering with the console while the program is runnng so you can do other stuff.  From the MSDN docs, it looks like using the BeginOutputReadLine might do the trick:
// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

Although if you want the background behavior you would need to perform the StandardOutput.ReadToEnd() on a background thread and then create a mechanism to retrieve that output from the main console thread which seems like a lot of work and at the moment I can think of any advantages over PowerShell background jobs.
Another approach is to create a runspace to do the bg job work as this blog post by Jim Truher points out.

A: This isn't elegant or well documented.  It creates a System.Diagnostic.Process object and performs some common initializations on it.  Once you get the Process object, you can perform additional adjustments on it, then call Process.Start to start the process.
function New-Process($cmd, $arguments, [switch]$stdout, [switch]$stdin, [switch]$stderr, [switch]$shellexec, [switch]$showwindow)
{
    $process = New-Object "System.Diagnostics.Process"
    $startinfo = New-Object "System.Diagnostics.ProcessStartInfo"

    $startinfo.FileName = $cmd
    $startinfo.Arguments = $arguments
    $startinfo.WorkingDirectory = $pwd.Path
    $startinfo.UseShellExecute = $shellexec
    $startinfo.RedirectStandardInput = $stdin
    $startinfo.RedirectStandardOutput = $stdout
    $startinfo.RedirectStandardError = $stderr

    if (!$showwindow) {
        $startinfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
    }

    $process.StartInfo = $startinfo

    return $process
}


text:
Q: CRM 2011 plugin works but giving an error I'm working on a CRM 2011 plugin that changes one field's value on an account entity if user deactivates the account. I spent a lot of time wondering what's wrong because I received the following error every time I deactivated some account
"Error. An error has occured. Try this action again. If the problem continues, check the Microsoft Dynamics CRM Community for solutions or contact your organization's Microsoft Dynamics CRM Administrator. Finally, you can contact Microsoft Support"
But after some time I noticed that even if the error my plugin actually works perfectly. My code is below just in case (notice that we call our accounts as clients)
Entity client = (Entity)context.InputParameters["Target"];

OptionSetValue state = (OptionSetValue)client["statecode"];

if (state.Value == 1)
{
    OptionSetValue clientStatus = new OptionSetValue(100000000);
    client["customertypecode"] = clientStatus;
    service.Update(client);
}

So does anyone has any thoughts what could cause this problem? If I disable my plugin and then deactivate any account it works perfectly without any errors.
My plugin is registered at Pre-operation stage synchronously.
Thank you in advance!

A: So your plugin is registered on the Pre-Operation of the SetStateDynamic message?  And all you're attempting to do is update the customertypecode?  My guess, since you haven't shown your code, is that you're not getting the IOrganizationService from the plugin context.

A:
When your plugin is subscribed to the SetState or SetStateDynamicEntity message, the entity is not in the IPluginExecutionContext.InputParameters["Target"].
These messages have three InputParameters:

*

*"EntityMoniker" (EntityReference)

*"State" (OptionSetValue)

*"Status" (OptionSetValue)

So there is no "Target".
EntityReference clientRef = context.InputParameters["EntityMoniker"] as EntityReference;
OptionSetValue newStateCode = context.InputParameters["State"] as OptionSetValue;

if (newStateCode.Value == 1)
{
    Entity updateClient = new Entity(clientRef.LogicalName);
    updateClient.Id = clientRef.Id;
    updateClient["customertypecode"] = new OptionSetValue(100000000);

    service.Update(updateClient);
}

When your plugin is subscribed to the Update message:
Since you're in the Pre-operation stage and the target Entity is the actual Entity you want to update, why do you call service.Update? Just add the property to the target Entity and be done with it...
Entity client = (Entity)context.InputParameters["Target"];

OptionSetValue state = (OptionSetValue)client["statecode"];

if (state.Value == 1)
{
    OptionSetValue clientStatus = new OptionSetValue(100000000);
    client["customertypecode"] = clientStatus;
}


text:
Q: Networkx Minimum Spanning Tree - precision issues? I am creating a graph from a weighted adjacency matrix the size of 222 x 222 nodes. All of the weights given in the matrix are a floating point numbers between 0.42757498546089029 and 1.6671726002927263. nx.minimum_spanning_tree(G, weight = "weight") method gives me the first picture below, meanwhile if I multiply all matrix values by 100.0 the same method gives me the second picture. This doesn't occur while plotting the same with igraph. Documentation of Networkx is silent about precision issues. Do you know why it might occur?

networkx code:
G=nx.from_numpy_matrix(M)
G1=nx.minimum_spanning_tree(G, weight = "weight")

labels = {i : node_names[i][1] for i in G1.nodes()}
colors = {i : node_attributes[labels[i]] for i in G1.nodes()}
for i in G1.nodes():
    G1.node[i]["color"] = 'white'
    G1.node[i]["style"] = "filled"
    G1.node[i]["fillcolor"] = colors[i]
color=nx.get_node_attributes(G1,'color')
fillcolor=nx.get_node_attributes(G1,'fillcolor')
H=nx.relabel_nodes(G1,labels)
nx.draw(H, scale=30, nodelist=H.nodes(), linewidths=0, with_labels = True, node_size=500,font_size=8)

igraph code:
    g = igraph.Graph.Weighted_Adjacency(M.tolist())
    for i, v in enumerate(g.vs):
        v["color"] = colors[i]
        v["label"] = labels[i]
        v["frame_color"] = colors[i]
        v["label_size"] = 10
        v["size"] = 26
    G = g.spanning_tree(weights='weight', return_tree=True)
    G.to_undirected()
    igraph.plot(G, labels=False, bbox = (900, 900), margin=40, loops=False

)

A: What you see is expected behaviour and not a precision issue at all. As the name suggests, the spring layout "simulates" the action of springs between your nodes onto their positions. The node positions are initialised on a circle, and then the force of the springs is applied to your nodes for a certain number of iterations (50 by default). With weak connection weights, your nodes will more or less remain on the circle (first case), with strong weights your nodes will gravitate towards the centre (second case).
In igraph, by default, the unweighted graph is used to compute the layout and you need to give the plotting routine the weights explicitly. I suspect that you might have plotted the graph without specifying the "weights" parameter.


text:
Q: How does appending a row and a column change eigenvalues of a non-symmetric matrix? This question asks about the changes in eigenvalues when a row and a column is added to a symmetric matrix. Cauchy's interlacing theorem gives us a way to understand this case.
I am interested in knowing if there is any result or study for a real and non-symmetric matrix. That is, if $$B=\left[\begin{array}{ccc}
A & x\\\\
y & z \end{array}\right]$$
how do we relate the eigenvalues of $B$ to the eigenvalues of $A$ and the values in the vectors $x$ and $y%$ and the scalar $z$? Are there some bounds for the spectrum?

A: You need more than just $x$, $y$, $z$ and the eigenvalues of $A$ to determine or bound the eigenvalues of $B$.  For example, consider
$$ B = \pmatrix{1 & 0 & | & 1\cr t & 0 & | & 0\cr \hline 0 & 1 & | & 0\cr}$$
where $A$ has eigenvalues $1$ and $0$, but any real number $\lambda$ will be an eigenvalue of $B$ for suitable $t$ (namely $t = \lambda^3 - \lambda^2$).
If $S$ diagonalizes $A$ so that $S^{-1} A S = \Lambda$ is diagonal, then
$$ \pmatrix{S & 0\cr 0 & 1}^{-1} B \pmatrix{S & 0 \cr 0 & 1\cr} = \pmatrix{\Lambda & S^{-1}x\cr y S & z\cr} $$
so by Gerschgorin's theorem, the eigenvalues of $B$ are contained in the union of the disks
centred at $\lambda_j$ of radii $\left|(S^{-1} x)_j\right|$ and the disk centred at $z$ of
radius $\left\|yS\right\|_1$.


text:
Q: AOP like construct with objective-c I am looking for a simple, cheap, reliable solution to intercept method calls with objective-c 2.0. It should be possible to execute pre / post blocks and run the original method in between.
I know i can swizzle methods  - replace the IMP with something which would call the original method and allow me to exec pre / post blocks. This looks simple, is pretty fast and should work in standard cases. Any idea if there is a better - runtime magic approach - to this problem ?
PS Portability does not matter - it will run only with apples runtime on OS X and iOS.

A: There is an aspect oriented approach for Objective-C:
AspectOrientedObjectiveC
I never used it and so I do not know how reliable it is.


text:
Q: How can I use my OTF signature font in LaTeX? I have managed to create an OTF font for my signature using the FontForge font editor. The signature is mapped to a single printable character on the keyboard. I am aware that I need to rely on the package fontspec in order to use the signature font in a LaTeX document. However, I am not able to figure out the command that I should use to insert the signature in a LaTeX document.
Could someone help we figure out what I should do, given that the signature font is different from the main font that I could use in any document.
Kind regards to the TeX/LaTeX Stack Exchange community.

A: If my understanding is correct, you have a custom .otf file that contains just 1 glyph -- your signature -- and, moreover, this glyph is stored in slot "0". If this understanding is correct, you may proceed as in the following example. (Since I don't have access to your font file, the example works with the Zapfino font and uses the Apple logo, which happens to be in slot F8FF, in lieu of your actual signature.)

\documentclass{article}
\usepackage{fontspec}
\newfontfamily\mysigfont{Zapfino.ttf} % substitute real filename here
\newcommand{\mysig}{{\mysigfont\char"F8FF}} % use "0000 in your doc
\begin{document}
\tiny\mysig \normalsize\mysig \Huge\mysig \fontsize{90}{108}\selectfont\mysig
\end{document}

A: The following adaptation of @Mico's solution works for me:
\documentclass{article}
\usepackage{fontspec}
\newfontfamily\mySigFF{Sigfont}[
Path = /home/myDir/texmf/fonts/,
Extension = .otf
]
\newcommand{\mysig}{{\mySigFF\char"004F}}
\begin{document}
\Huge\mysig
\end{document}


text:
Q: kube-arangodb: Can not connect with `arangosh` I am using  arango-single-server on minikube. Installed using kubectl by following: https://www.arangodb.com/docs/stable/tutorials-kubernetes.html
Following the error message:
➜ kubectl exec -it arango-single-server-sngl-d0leq3in-d9649f -- arangosh --server.endpoint "tcp://localhost:8529" --server.database "_system"
Defaulted container "server" out of: server, init-lifecycle (init), uuid (init)
Please specify a password:

                                       _
  __ _ _ __ __ _ _ __   __ _  ___  ___| |__
 / _` | '__/ _` | '_ \ / _` |/ _ \/ __| '_ \
| (_| | | | (_| | | | | (_| | (_) \__ \ | | |
 \__,_|_|  \__,_|_| |_|\__, |\___/|___/_| |_|
                       |___/

arangosh (ArangoDB 3.9.3 [linux] 64bit, using jemalloc, build tags/v3.9.3-0-gb9cd8359a1a, VPack 0.1.35, RocksDB 6.27.0, ICU 64.2, V8 7.9.317, OpenSSL 1.1.1q  5 Jul 2022)
Copyright (c) ArangoDB GmbH

Command-line history will be persisted when the shell is exited. You can use `--console.history false` to turn this off
Could not connect to endpoint 'tcp://localhost:8529', database: '_system', username: 'root'
Error message: 'Connection closed'

localhost:8529@_system>

following the result of netstat;
➜  kubectl exec -it arango-single-server-sngl-d0leq3in-d9649f -- netstat -a
Defaulted container "server" out of: server, init-lifecycle (init), uuid (init)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:56568         localhost:8529          ESTABLISHED
tcp        0      0 :::8529                 :::*                    LISTEN
tcp        0      0 localhost:8529          localhost:56568         ESTABLISHED
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node Path
unix  3      [ ]         DGRAM                    3845565
unix  3      [ ]         DGRAM                    3845564

Any idea, what is the issue ?
I can access the gui interface.

A: It works by putting --server.endpoint "https://localhost:8529" or --server.endpoint "http+ssl://localhost:8529" instead of --server.endpoint "tcp://localhost:8529"
I got help from https://www.arangodb.com/docs/stable/programs-arangosh-examples.html


text:
Q: My datetime ticks do not align when I am plotting with pyplot Here's my data:
index       Notifications  Pct
2022-05-31  35336.0        36.0
2022-06-30  18365.0        38.0
2022-07-31  12851.0        31.0
2022-08-31  18650.0        19.0
2022-09-30  5665.0  NaN

The month marker is one month off. July should be lower than August, not higher. The index is from:
data.resample('m', on='Notif Date').count()
The code I am using is:
plt.plot(df['Notifications'], color='C2', lw=4 , marker='s', label='Open Notifications');

It seems to me that while the index plots according to the last date of the resample (i.e. 8/31), pyplot is using the first of the month to plot, thereby a gap of a month is created.


text:
Q: Function that generate Code returns the same things There is a MySQL function in our web system to generate Code. The structure of the code is
district_cd(length:2) + date(length:8) + sequence no(length:5,start at 1).<like : ab2016090800001>

The sequence no was saved in table and will be updated (+1) when generate a new code.
But sometimes it returned two same codes and makes us fall in trouble. Here are the captures to replicate this problem, I will attach the DDL after this.
Step 1.Client1->change to manual commit then generate a code, but do not commit.
SET autocommit = 0;
select * from applies;
select * from sequence where apply_date = "2016-09-08";
select nextval("ab");
insert into applies (apply_id,apply_no,created,district_cd) values (2,"ab2016090800002","ab",now());
select * from sequence where apply_date = "2016-09-08";

Step2.Client2->change to manual commit then generate a code, stuck as Client1 locked
SET autocommit = 0;
select * from applies;
select * from sequence where apply_date = "2016-09-08";
insert into applies (apply_id,apply_no,created,district_cd) values (3,"ab20160908123456780","ab",now());

Step3.Client1->commit;
commit;
select * from sequence where apply_date = "2016-09-08";

Step4.Client2->code was generated and two records appeared in sequence table
select * from sequence where apply_date = "2016-09-08";

capture of Step4
Step5.Client2->commit;one of the two records that appeared in sequence table was deleted.The codes generated are duplicated.
commit;
select * from sequence where apply_date = "2016-09-08";
select * from applies;

capture of Step5
※DDL
Table:applies   (apply_no:save the code)
CREATE TABLE `applies` (
  `apply_id` varchar(100) NOT NULL DEFAULT '',
  `apply_no` varchar(100) NOT NULL DEFAULT '',
  `district_cd` varchar(100) DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  PRIMARY KEY (`apply_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Table:sequence (current_value:save current sequnce value)
CREATE TABLE `sequence` (
  `district_cd` varchar(3) NOT NULL DEFAULT '',
  `current_value` int(11) NOT NULL DEFAULT '0',
  `apply_date` date NOT NULL DEFAULT '0000-00-00',
  PRIMARY KEY (`district_cd`,`current_value`,`apply_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Function:currval->get current sequence value by district_cd
DELIMITER ;;
CREATE DEFINER=`usr`@`%` FUNCTION `currval`(d VARCHAR(3)) RETURNS int(11)
    DETERMINISTIC
BEGIN
    DECLARE value INTEGER;
    DECLARE needInitSequence INTEGER;
    DECLARE today DATE;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET needInitSequence = 1;

    SET value = 0;
    SET today = current_date();

    SELECT `current_value` INTO value
        FROM `sequence`
        WHERE `district_cd` = d AND `apply_date` = today limit 1;

    IF needInitSequence = 1 THEN
        INSERT INTO `sequence` (`district_cd`, `current_value`, `apply_date`) VALUES (d, value, today);
    END IF;

    RETURN value;
END
;;
DELIMITER ;

Function:nextval->generate code by district_cd
DELIMITER ;;
CREATE DEFINER=`usr`@`%` FUNCTION `nextval`(d VARCHAR(3)) RETURNS varchar(16) CHARSET utf8
    DETERMINISTIC
BEGIN
    DECLARE value INTEGER;
    SET value = currval(d);

    UPDATE `sequence`
        SET `current_value` = `current_value` + 1
        WHERE `district_cd` = d AND `apply_date` = current_date();

    RETURN concat(d, date_format(now(), '%Y%m%d'), LPAD(currval(d), 5, '0'));
END
;;
DELIMITER ;

Triggers of applies->a business logic,if the length of apply_no is greater than 18,it will call the function:nextval to generate a new code
DELIMITER ;;
CREATE TRIGGER `convert_long_no` BEFORE INSERT ON `applies` FOR EACH ROW BEGIN
    IF ((SELECT LENGTH(NEW.apply_no)) >= 18) THEN
        SET NEW.apply_no = (SELECT nextval(NEW.district_cd));
    END IF;
END
;;
DELIMITER ;

My Questions:

*

*Why did the function:nextval returns two same codes?

*Why did two records appear in sequnce when update the record.


text:
Q: Aproximar a decimal SQL Deseo aproximar al decimal 0.5 mas cercano en SQL
Es decir:
2.3 que se aproxime a 2.5
2.8 que se aproxime a 3

A: La opción más sencilla es multiplicar por 2, redondear a enteros y dividir entre 2. Dejo un ejemplo junto con los datos de prueba.
WITH
E(n) AS(
    SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0))E(n)
),
E2(n) AS(
    SELECT a.n FROM E a, E b
),
E4(n) AS(
    SELECT a.n FROM E2 a, E2 b
),
cteTally(n) AS(
    SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) /10. n
    FROM E4
)
SELECT n,
     ROUND( n * 2, 0) / 2 -- Esta linea es lo único que es necesita la solución. El resto es para mostrar datos de prueba.
FROM cteTally;


text:
Q: Android simple calculator application I'm new to android. I'm developing a simple calculator application.
There is some problem in my code. There is no syntax error.
When I run it, it gives some error. Written all code in a try catch but I'm still unable to catch it.
       b1.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            //char x = lbldisp.getText().toString().charAt(1);

        try
        {
            String x = lbldisp.getText().toString();
            if(x.charAt(0)=='0' && x.charAt(1)!='.')
            {
                    lbldisp.setText("1");
            }
            else
            {
                lbldisp.setText(x+"1");
            }

        }
        catch(Exception e)
        {
            Toast.makeText(Calculator.this,e.getMessage().toString(), Toast.LENGTH_SHORT).show();
        }
        }
    });

A: Try to replace this string
 if(x.charAt(0)=='0' && x.charAt(1)!='.')

By this String
 if(x.charAt(0).equals("0") && x.charAt(1).equals("."))

You have Converted the value to String so try to use .equals Method.


text:
Q: Is there a way to set the text in the text view to invisible? I can't change its color or use alpha because the background may change and I won't know its color!
Is there any other way to set it to invisible ?
Also I don't want to set the text view invisible since I want the background to be visible!

A: Try:
textView.setTextColor(getResources().getColor(android.R.color.transparent));

A: You can set a textview to INVISIBLE:
myTextView.setVisibility(View.INVISIBLE);

That way the textview will still be present but not seen

A: Something like this..
String text = "Invisible Text";

TextView text1 = new TextView();
text1.setTag(text);

A: why not,  set text value as empty string when you want to make it invisible. keep backup of the original value so that you can use it later when required.


text:
Q: Issue with Webfont/font-face in child theme I've uploaded a free webfont to my child theme. It's placed in a folder labelled 'fonts'.
I can't for the life of me get it to link correctly and work.
This is the code I'm using in the child theme stylesheet
@font-face {
  font-family: 'GlacialIndifference';
  src: url('http://MYWEBSITEURL.com/wp-content/themes/atmosphere-child/fonts/GlacialIndifference-Regular.eot'); /* IE9 Compat Modes */
  src: url('http://MYWEBSITEURL.com/wp-content/themes/atmosphere-child/fonts/GlacialIndifference-Regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('http://MYWEBSITEURL.com/wp-content/themes/atmosphere-child/fonts/GlacialIndifference-Regular.woff2') format('woff2'), /* Super Modern Browsers */
       url('http:/MYWEBSITEURL.com/wp-content/themes/atmosphere-child/fonts/GlacialIndifference-Regular.woff') format('woff'), /* Pretty Modern Browsers */
       url('http://MYWEBSITEURL.com/wp-content/themes/atmosphere-child/fonts/GlacialIndifference-Regular.ttf')  format('truetype'), /* Safari, Android, iOS */
       font-weight: 400;
       font-style: normal;
}

@font-face {
  font-family: 'GlacialIndifference';
  src: url('http://MYWEBSITEURL.com/wp-content/themes/atmosphere-child/fonts/GlacialIndifference-Bold.eot'); /* IE9 Compat Modes */
  src: url('http://MYWEBSITEURL.com/wp-content/themes/atmosphere-child/fonts/GlacialIndifference-Bold.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('http://MYWEBSITEURL.com/wp-content/themes/atmosphere-child/fonts/GlacialIndifference-Bold.woff2') format('woff2'), /* Super Modern Browsers */
       url('http://MYWEBSITEURL.com/wp-content/themes/atmosphere-child/fonts/GlacialIndifference-Bold.woff') format('woff'), /* Pretty Modern Browsers */
       url('http://MYWEBSITEURL.com/wp-content/themes/atmosphere-child/fonts/GlacialIndifference-Bold.ttf')  format('truetype'), /* Safari, Android, iOS */
       font-weight: 700;
       font-style: normal;
}

I've also tried the following:
@font-face {
  font-family: 'GlacialIndifference';
  src: url('.../fonts/GlacialIndifference-Regular.eot'); /* IE9 Compat Modes */
  src: url('.../fonts/GlacialIndifference-Regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('.../fonts/GlacialIndifference-Regular.woff2') format('woff2'), /* Super Modern Browsers */
       url('.../fonts/GlacialIndifference-Regular.woff') format('woff'), /* Pretty Modern Browsers */
       url('.../fonts/GlacialIndifference-Regular.ttf')  format('truetype'), /* Safari, Android, iOS */
       font-weight: 400;
       font-style: normal;
}

@font-face {
  font-family: 'GlacialIndifference';
  src: url('.../fonts/GlacialIndifference-Bold.eot'); /* IE9 Compat Modes */
  src: url('.../fonts/GlacialIndifference-Bold.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('.../fonts/GlacialIndifference-Bold.woff2') format('woff2'), /* Super Modern Browsers */
       url('.../fonts/GlacialIndifference-Bold.woff') format('woff'), /* Pretty Modern Browsers */
       url('.../fonts/GlacialIndifference-Bold.ttf')  format('truetype'), /* Safari, Android, iOS */
       font-weight: 700;
       font-style: normal;
}

I feel like both of those snippets above should work so I'm at a loss as to what I should try next.
I copied the font path directly from cPanel.
Help would be appreciated!
Cheers,
Rob