text:
Q: Getting a list of results, 1 for each foreign key I have a model, Reading, which has a foreign key, Type. I'm trying to get a reading for each type that I have, using the following code:
    for type in Type.objects.all():
        readings = Reading.objects.filter(
                type=type.pk)
        if readings.exists():
            reading_list.append(readings[0])

The problem with this, of course, is that it hits the database for each sensor reading. I've played around with some queries to try to optimize this to a single database call, but none of them seem efficient. .values for instance will provide me a list of readings grouped by type, but it will give me EVERY reading for each type, and I have to filter them with Python in memory. This is out of the question, as we're dealing with potentially millions of readings.

A: if you use PostgreSQL as your DB backend you can do this in one-line with something like:
Reading.objects.order_by('type__pk', 'any_other_order_field').distinct('type__pk')

Note that the field on which distinct happens must always be the first argument in the order_by method. Feel free to change type__pk with the actuall field you want to order types on (e.g. type__name if the Type model has a name property). You can read more about distinct here https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct.
If you do not use PostgreSQL you could use the prefetch_related method for this purpose:
#reading_set could be replaced with whatever your reverse relation name actually is
for type in Type.objects.prefetch_related('reading_set').all():
        readings = type.reading_set.all()
        if len(readings):
            reading_list.append(readings[0])

The above will perform only 2 queries in total. Note I use len() so that no extra query is performed when counting the objects. You can read more about prefetch_related here https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related.
On the downside of this approach is you first retrieve all related objects from the DB and then just get the first.
The above code is not tested, but I hope it will at least point you towards the right direction.


text:
Q: Есть код, изменения цветовой темы на странице, как записать тему в local storage которую выбрал ползователь Вот код js, в нём я ставлю/убираю атрибут тегу html
themeToggleBtn.addEventListener('click', switchThemeColor);
function switchThemeColor() {
    if (document.documentElement.hasAttribute('theme')){
        document.documentElement.removeAttribute('theme');
    }else {
        document.documentElement.setAttribute('theme', 'color-theme');
    }
}

В css записываю эти стили в css переменные и потом эти переменные использую, например для кнокпи
.toggle-btn{
  color: var(--button-color);
  и тд
}

:root {
    --header-bg-color: #FE6F5E;
    --header-title-color: #F2F2F2;
    --nav-bg-color: darkseagreen;
    --li-bg-color: pink;
    --links-color: #ffffff;
    --aside-bg-color: #DF4A32;
    --main-bg-color: #F26522;
    --content-title-color: #ffffff;
    --content-subtitle-color: #ffffff;
    --img-content-color: #ffffff;
    --img-bg-color: #4682b4;
    --button-wrapper-bg-color: #77608d;
    --button-color: #ffffff;
    --button-bd-color: #F26522;
    --button-bg-color: #FE6F5E;
    --button-active-bg-color: #F26522;
}
:root[theme='color-theme']{
    --header-bg-color: #794f45;
    --header-title-color: #0e0e0e;
    --nav-bg-color: #770F05;
    --li-bg-color: #0B6207;
    --links-color: #000000;
    --aside-bg-color: #848484;
    --main-bg-color: #6E7783;
    --content-title-color: #0e0e0e;
    --content-subtitle-color: #000000;
    --img-content-color: #000000;
    --img-bg-color: #D05F04;
    --button-wrapper-bg-color: #000741;
    --button-color: #0e0e0e;
    --button-bd-color: #714AB2;
    --button-bg-color: #956387;
    --button-active-bg-color: #714AB2;
}

A: Window.localStorage | MDN
themeToggleBtn.addEventListener('click', switchThemeColor);
function switchThemeColor() {
    if (document.documentElement.hasAttribute('theme')){
        document.documentElement.removeAttribute('theme');
        localStorage.removeItem('theme'); // удаляем
    }else {
        document.documentElement.setAttribute('theme', 'color-theme');
        localStorage.setItem('theme', 'color-theme'); // сохраняем
    }
}

// При новом заходе берём сохранённое значение
window.onload = function() {
    if(localStorage.getItem('theme') === 'color-theme'){
        document.documentElement.setAttribute('theme', 'color-theme');
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replace the FirstViewController in a TabBar app with another view controller (Kal)? I created an empty iPad TabBar application using XCode 4, without storyboards.  I placed that app in a workspace.  I then added the Kal source (obtained from the iPad Juice build)  to the workspace as a separate project.  The initial build was clean.
I then went to the Kal example (NativeKal) and added EventKitDataSource.h and .m, and NativeCalAppDelegate.h and .m. (The image below shows what files are in the example project)

This is the code from the NativeCalAppDelegate.h file:

I tried setting the first TabBar UIView controller to "KalViewController" as I would normally do when using Storyboards, but it isn't listed in the drop down list of classes.
The question is: how do I get the NativeCal example view controller to replace FirstViewController in the in my TabBar application?

A: Comments added as Answer.
My recommendation is to switch to storyboards it is a lot easier to do UITabBarControllers in them. You can do this by just creating a new storyboard and copy and paste everything into it and then control drag from the UITabBarController to the UIViewControllers that you want to be linked to the tab bar controller and it does the rest for you, everything else is the same after that. In storyboards you can set the first view controller to be loaded so if you need it to be KalController then you can set it when you set up the UITabBarController. You can also set this in the code. I found that storyboards were a great new feature to xcode, UITabBarCotrollers are a lot easier to do in them then in .nib files I could never get them to work.
Hope this has helped.


text:
Q: Facebook status post error c# sdk I'm developing a facebook app, which I'm unexperianced with it. I wanted to post status from my page, but it posted just for once. Other posting trials didn't give any result. No compile-time or run-time errors, but no posts on my wall either. Here is my code.
fbClient.PostCompleted += (o, v) =>
        {
            if (v.Error == null)
            {
                var resultante = (IDictionary<string, object>)v.GetResultData();
                var newPostID = (string)resultante["id"];
            }
        };
        //dynamic parameters = new ExpandoObject();
        var parameters = new Dictionary<string, object>();
        parameters["message"] = txtWrite.Text;
        lbPosttoWall.Click += lbPosttoWall_Click;
        fbClient.Post("me/feed", parameters);


text:
Q: Php Array when exceed certain numbers I have a php associative array which contains more approximately 900 key-value and i am using it as a string file. The problem is now when I add another key-value , I am unable to retrieve the value by key. How ever if i delete some other key-value it works fine. I wonder if there is any size limit for array. Please help me, i don't want to split my array into different files.
Thank you in advance. This is what y string file looks like
function lang($phrase){
static $lang = array(
't_sust_tour'=>'tour',
'process_report'=>'p report '
);
return $lang[$phrase];
}

A: There is no max or limit, but it is how much memory your script will consume which can be adjusted in the 'memory_limit' in your php.ini configuration.
here is answer from a previous SO post Array size limit in PHP


text:
Q: How to access onclick into many div I need to react to the onclick event of an element that is found within two div

         Repair

Repair is the one I want to access

A: First you should remove the href from the action link. If you are using jquery you can use either:
$("#layout").on('click', function(){
    var repair = $(this).find("a");
    ...
});

or directly :
$("#Repair").on('click', function(){
         ...
    });

there is also a third way with query that i like the most:
$(window).on( "click", "#Repair", function() {
...
});

or if you need plain javascript you can use:
var repairElement = document.getElementById('Repair');

repairElement.addEventListener('click', function() {
    .. some logic
}, false);


text:
Q: How to fix "Assertion failed" when training cv:ml::DTrees I want to train a decision tree with hog features.
When I try to train my cv::ml::DTrees model, I receive the following error:
OpenCV(3.4.3) Error: Assertion failed (n >= 0) in cv::ml::TrainDataImpl::getValues, file C:\build\3_4_winpack-build-win64-vc14\opencv\modules\ml\src\data.cpp, line 890

I understand, that the number of samples(features) have to match the number of responses(labels) and both have to be >=0.
My cv::Mat feats and cv::Mat labels have the same number of rows (388).
This is how I try to do it:
cv::Ptr<cv::ml::DTrees> model = cv::ml::DTrees::create();
cv::Ptr<cv::ml::TrainData> data = cv::ml::TrainData::create(feats, cv::ml::ROW_SAMPLE, labels);
model->train(data);

model->train(data) fails, when it calls this function:
void getValues( int vi, InputArray _sidx, float* values ) const CV_OVERRIDE
    {
        Mat sidx = _sidx.getMat();
        int i, n = sidx.checkVector(1, CV_32S), nsamples = getNSamples();
        CV_Assert( 0 <= vi && vi < getNAllVars() );
        CV_Assert( n >= 0 );
        const int* s = n > 0 ? sidx.ptr<int>() : 0;
        if( n == 0 )
            n = nsamples;
        }
}

Can anyone point me in the right direction to fix this problem?
EDIT:
If I set the MinSampleCount to 388 (the number of samples) I don't get an error, but the prediction won't work correctly (it always returns label 5).


text:
Q: Microsoft MAC, MAG or GCC differences There are several cloud environment provided by Microsoft.
E.g. Microsoft Azure Government Cloud (MAG), Microsoft Azure Commercial (MAC) or public cloud, Office 365 (public) cloud and several other Government cloud in EU and Asia. For US Gov there is  Office 365 GCC cloud.
Is Office 365 GCC meant for US Government only? Or is it available outside US also?

A: Have you seen the Office 365 GCC service description? I think that should help answer the question.


text:
Q: XSLT propagating Parent element into each child in a child list Am new to XSLT and am just not able to wrap my head around this one.
I have an XML as follows:
<root>
  <key>1</key>
  <list>
        <value>1</value>
        <value>2</value>
  </list>
</root>

What I want to achieve is this:
<root>
    <row>
        <key>1</key>
         <value>1</value>
    </row>
    <row>
        <key>1</key>
        <value>2</value>
   </row>
</root>

A: Your requirements are not entirely clear, but let's give it a try:
<xsl:template match="/root">
    <xsl:copy>
        <!-- each first following sibling after <key> -->
        <xsl:apply-templates select="key/following-sibling::list[1]" />
    </xsl:copy>
</xsl:template>

<xsl:template match="list">
    <xsl:apply-templates />
</xsl:template>

<xsl:template match="value">
    <row>
        <!-- the key immediately before the current <list> -->
        <xsl:copy-of select="ancestor::list/preceding-sibling::key[1]" />
        <xsl:copy-of select="." />
    </row>
</xsl:template>

This code assumes a basic understanding of XSLT. And it assumes my understanding that a list element is preceded directly by a key element and that each row/value becomes a row with a value and the preceding key.
You tagged your question XSLT 2.0, but this code works with either XSLT 1.0 or 2.0 (and in this particular case will not be very different if you tried using the 2.0 features).
Tested with a 1.0 (.NET) and two 2.0 (Exselt and Saxon) processors against the following modified input:
<root>
  <key>1</key>
  <list>
        <value>1</value>
        <value>2</value>
  </list>
  <key>2</key>
  <list>
        <value>55</value>
        <value>66</value>
        <value>77</value>
  </list>
</root>

Resulting in the following output:
<root>
   <row>
      <key>1</key>
      <value>1</value>
   </row>
   <row>
      <key>1</key>
      <value>2</value>
   </row>
   <row>
      <key>2</key>
      <value>55</value>
   </row>
   <row>
      <key>2</key>
      <value>66</value>
   </row>
   <row>
      <key>2</key>
      <value>77</value>
   </row>
</root>


text:
Q: How to get records count based on 3 keys in mongodb using mongoose? I have a model named referralLink like this
new Schema({
  referral_link: String,
  referral_code : String,
  isLink : Number,
  offer_name: String,
  offer_desc: String,
  user_email: String,
  companyId: { type : Schema.Types.ObjectId, ref : 'companies'},
  addedByAdmin: { type: Boolean, default: true },
  number_of_clicks: Number,
  referral_country: String,
  link_status: String,
  categoryId : { type: Schema.Types.ObjectId, ref: 'categories' },
  number_of_clicks : { type: Number, default: 0 },
  createdAt: String,
  updatedAt: String,
  userId: { type: Schema.Types.ObjectId, ref: 'users' }
})

Now i want count of Approved, Rejected, Pending referrals in single mongoose query. I want results like this
{
  approved : 2,
  pending : 1,
  rejected : 3
}

How can i do this in mongoose?

A: Assuming the approved, pending and rejected values are in the link_status field, then something like this should work:
let linkStatusSummary = referralLink.find({}, 'link_status', (err, results) => {
  let counts = {};

  // create an object that contains the possible values of link_status and the number of times each occurs
  for (var i = 0; i < results.length; i++) {
    let status = results[i].link_status;
    counts[status] = counts[status] ? counts[status] + 1 : 1;  // if the category is already in the object, add 1 to the count, else create a new element with count 1
  }
  return counts
})


text:
Q: Row of the first positive number preceding a negative number in Postgres? I have a table like:

I'm doing some computations and in some point when I get a negative number in column 2 I must find the first positive number preceding this negative number. For instance, if the negative number were -2.2 I would like to have access to 1.2, if it were -0.8 then I would like to have access to 1.5.
How can I do that?
Thanks.

A: You can use a combination of window functions to do this.  First, use count as a window function, incrementing the count only when column2>0.  This will segregate your rows into the groups you'll need to pick out the positive value.  We can then use first_value to grab the first row from the partition, which will be the positive value:
create table test (column1 int, column2 numeric, column3 date);
insert into test VALUES (30, 2.5, '2019-01-01'), (31, 1.5, '2019-01-02'), (28, -0.8, '2019-01-03'), (29, 1.0, '2019-01-04'), (30, 1.2, '2019-01-05'), (38, -2.1, '2019-01-06'), (37, -2.2, '2019-01-07');

SELECT column1,
       column2,
       first_value(column2) OVER (PARTITION BY col2_group ORDER BY column3)
  FROM (
  select column1,
         column2,
         -- Create groups of rows
         count(column2) FILTER (WHERE column2>0) OVER(ORDER BY column3) as col2_group,
         column3
  FROM test) as sub
ORDER BY column3
;
 column1 | column2 | first_value
---------+---------+-------------
      30 |     2.5 |         2.5
      31 |     1.5 |         1.5
      28 |    -0.8 |         1.5
      29 |     1.0 |         1.0
      30 |     1.2 |         1.2
      38 |    -2.1 |         1.2
      37 |    -2.2 |         1.2
(7 rows)

In the future, it would be very helpful if you would add the data and the expected output, separately, as text, not an image.


text:
Q: single Column Update for multiple rows in oracle10g Update table_1 set col1= 1 where col2 = 'ONE';
update table_1 set col1= 2 where col2 = 'TWO';
Update table_1 set col1= 3 where col2 = 'THREE';
...
update table_1 set col1= 100 where col2 = 'HUNDRED';

Is there any simplified way to achive this in a single query instead of writing 100 update statemnets in oracle10g??

A: I think there might be a solution with Oracle Case-Statement or the decode-function, although it will be a quite long statement and I am not quite sure what the advantage over 100 update statements might be. Also I am not aware of any limitations regarding length of parameter-lists, etc.
Example for Case:
update table_1
set col1 = CASE col2
  WHEN 'ONE' THEN 1
  WHEN 'TWO' THEN 2
  WHEN 'THREE' THEN 3
  WHEN 'FOUR' THEN 4
  WHEN 'FIVE' THEN 5
  WHEN 'SIX' THEN 6
  WHEN 'SEVEN' THEN 7
  WHEN 'EIGHT' THEN 8
  ...
  WHEN 'HUNDRED' THEN 100
  ELSE col2
END;

Example for decode:
update table_1
set col1 = decode(col2,
              'ONE', 1,
              'TWO', 2,
              'THREE', 3,
              'FOUR', 4,
              'FIVE', 5,
              'SIX', 6,
              'SEVEN', 7,
              'EIGHT', 8,
              ...
              'HUNDRED', 100,
              col2);

A: You could make use of the Julian spelling formats (search asktom.oracle.com for more details)
Here's output from my session:-
create table table_1 (col_1 number, col_2 varchar(20))

insert into table_1 (col_1, col_2) values (null, 'THIRTY-THREE')
insert into table_1 (col_1, col_2) values (null, 'SEVEN')
insert into table_1 (col_1, col_2) values (null, 'EIGHTY-FOUR')

select * from table_1
COL_1     COL_2
       THIRTY-THREE
       SEVEN
       EIGHTY-FOUR

update /*+bypass_ujvc*/
(select t1.col_1, spelled.n
from
table_1 t1
inner join
(select n, to_char(to_date (n, 'J'),'JSP') spelled_n from
(select level n from dual connect by level <= 100)) spelled
on t1.col_2 = spelled.spelled_n
)
set col_1 = n

select * from table_1

COL_1 COL_2
33     THIRTY-THREE
7      SEVEN
84     EIGHTY-FOUR

The nasty hint (bypass_ujvc) ignores the fact that the inline view isn't key preserved - in practice you should use a merge statement instead. But this isn't a real-world scenario, right! (And you'll have to treat your 'HUNDRED' as a special case = 'ONE HUNDRED'.)


text:
Q: Encountering parse base error (SAS) I've been stuck on this the whole day and I hope to get some help from the community. I am still learning SAS so this might be a beginner's question. Please bear with me.
Here I have a code that I am currently working on. I'm running this using eclipse dataserver plugins:
libname myInput 'D:\_TD5910372542151565380';

proc datasets lib=myInput;
run;

quit;

ods csv files="D:/_TD5910372542151565380/myTest.csv";

proc print data=myInput.inputContainer;
     title "Random";
run;

ods csv close;

I am trying to print the content in the inputContainer into a CSV file. Here is the console log that I am getting:
[MPRINT] Parsing Base DataServer
/* 0001 */  libname myInput 'D:\_TD5910372542151565380';

NOTE: Library myinput assigned successfully
[MPRINT] Parsing Base DataServer
/* 0002 */  proc datasets lib=myInput;
/* 0003 */  run;

-------------------- 10:34: PROC DATASETS --------------------
NOTE: Time taken: 000:00:00.000
[MPRINT] Parsing Base DataServer
/* 0002 */  quit;

[MPRINT] Parsing Base DataServer
/* 0003 */  ods csv files="D:/_TD5910372542151565380/myTest.csv";
/* 0004 */  proc print data=myInput.inputContainer;
/* 0005 */  title "Random";
/* 0006 */  run;

ERROR: Parsing exception - aborting
ERROR: DS-00274 : Could not parse base DataServer code: Encountered " <ALPHANUM> "ods "" at line 3, column 1.
Was expecting one of:
    <EOF>
    ";" ...
    "*" ...
    "data" ...
    "proc" ...
    (and 9 more)

I checked the lines a lot of time but I am still not sure if I am missing something. I also browsed a lot of websites to find what can fix this error. Hopefully a second pair of eye can point out what exactly has gone wrong.
Thank you in advance. XD

A: Haha... I found the solution myself.The way I solved this is as following:
libname myInput 'D:\_TD5910372542151565380';
proc datasets lib=myInput;
run;

data something;
    set myInput.inputContainer;
run;

proc export data=something
    outfile="D:/Example.csv"
    dbms=csv
    replace;
run;

It seems that you have to set the data first to take the obs file. Then, there are no separated semi colons until replace; Which I did wrong in the above. Hope this help anyone out there.


text:
Q: Using xsl to create localized content part 2 A slightly different requirement to this question
The dictionary stays the same format but grows:
<resources>
    <text name="property.to.match">
        <en_US>The American translation</en_US>
        <en_GB>The British translation</en_GB>
        <en>The language localized, but non locale based generic translation</en>
    </text>
    <text name="other.property.to.match">
        <en>The other language localized, but non locale based generic translation</en>
    </text
    <text name="another.property.to.match">
        <en>Second generic property</en>
    </text>
    <text name="a.label.to.match">
        <en>Generic Checkbox label</en>
    </text>
    <text name="some.text.to.translate">
        <en>This text follows a static bit of text</en>
    </text>
</resources>

But the document in which I would like to match is more complex:

Lot's of html

[property.to.match]

[other.property.to.match]

[another.property.to.match]

        <input type="checkbox"/>[a.label.to.match]

Some text that shouldn't be translated followed by [some.text.to.translate]

So the matcher needs to be able to find multiple text strings within the */text() that start and end with [] but could be in amongst other nodes and bits of untrnaslated text.
Thanks again

A: This XSLT 1.0 transformation:
<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
     <xsl:strip-space elements="*"/>

     <xsl:param name="pLookupPath" select="'file:///c:/temp/delete/lookup2.xml'"/>
     <xsl:param name="pLang" select="'en_GB'"/>

     <xsl:key name="kLookup" match="text/*"
      use="concat(../@name, '+', name())"/>

     <xsl:variable name="vDict" select="document($pLookupPath)"/>

     <xsl:template match="node()|@*">
         <xsl:copy>
           <xsl:apply-templates select="node()|@*"/>
         </xsl:copy>
     </xsl:template>

     <xsl:template name="replaceWithLookup" match=
      "text()[contains(., '[') and contains(., ']')]">
      <xsl:param name="pText" select="."/>

      <xsl:if test="string-length($pText)">
          <xsl:value-of select=
           "substring-before(concat($pText, '['), '[')"/>

          <xsl:variable name="vToken" select=
           "substring-before(substring-after($pText, '['), ']')"/>

        <xsl:variable name="vReplacement">
         <xsl:for-each select="$vDict">
          <xsl:value-of select=
          "(key('kLookup', concat($vToken, '+', $pLang))
         |
           key('kLookup', concat($vToken, '+', substring-before($pLang, '_')))
           )[1]"/>
         </xsl:for-each>
        </xsl:variable>

        <xsl:choose>
         <xsl:when test="$vReplacement">
          <xsl:value-of select="$vReplacement"/>
         </xsl:when>
         <xsl:when test="$vToken">
          <xsl:value-of select="concat('[', $vToken, ']')"/>
         </xsl:when>
         <xsl:otherwise>
           <xsl:value-of select=
            "substring-after
              ($pText,
               substring-before(concat($pText, '['), '[')
               )"/>
         </xsl:otherwise>
        </xsl:choose>

        <xsl:if test="$vToken">
         <xsl:call-template name="replaceWithLookup">
           <xsl:with-param name="pText" select=
            "substring-after($pText, concat('[', $vToken, ']'))"/>
         </xsl:call-template>
        </xsl:if>
      </xsl:if>
     </xsl:template>
</xsl:stylesheet>

when applied on the following XML document (based on the provided one but made more difficult and challenging -- the last text nodes contains two replacement targets):

Lot's of html

[property.to.match]

[other.property.to.match]

            [another.property.to.match]

        <input type="checkbox"/>[a.label.to.match]

Some text that shouldn't be translated followed
        by [some.text.to.translate]
        XXX [other.property.to.match]

produces the wanted, correct result:

Lot's of html

The British translation

The other language localized, but non locale based generic translation

Second generic property

<input type="checkbox">Generic Checkbox label

Some text that shouldn't be translated followed
                by This text follows a static bit of text
                XXX The other language localized, but non locale based generic translation


text:
Q: Apache2 Vhosts and DnsMasq, unable to access website from another computer over LAN : ERR_CONNECTION_REFUSED I'm currently setting up a web server over my LAN to satisfy some needs like using Phabricator or other intranet services. To do this, I installed apache2, php5, mysql and DNSMASQ which allows me to manage a DHCP and DNS server. But now I'm stucked with virtual hosts that are working just fine over the local machine but cannot be accessed from another computer on the local network, I'm getting "ERR_CONNECTION_REFUSED".
To test my settings, I declared a virtual host like this :
Creating the root folder of our website
$ sudo mkdir -p /var/www/test.devbox/public_html
$ chown -R $USER:$USER /var/www/test.devbox/public_html

Placing an index file and add random text
$ nano /var/www/test.devbox/public_html/index.html

Now we create our virtual host file
$ sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/test.devbox.conf
$ sudo nano /etc/apache2/sites-available/test.devbox.conf

Virtual Host Config file
<VirtualHost *:80>
    ServerAdmin admin@test.devbox
    ServerName test.devbox
    ServerAlias www.test.devbox
    DocumentRoot /var/www/test.devbox/public_html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Then we enable it using
$ sudo a2ensite test.devbox

Then I edited my hosts file to fit the servername directive in my test.devbox.config file (server side)
$ sudo nano /etc/hosts

127.0.0.1       localhost
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters

192.168.1.254   bbox

127.0.1.1       MyPie
127.0.0.1       MyPie
127.0.0.1       devbox
127.0.0.1       opcv.devbox www.opcv.devbox
127.0.0.1       test.devbox www.test.devbox

Here is also my dnsmasq.conf file
$ sudo nano /etc/dnsmasq.conf

domain-needed
expand-hosts
bogus-priv
no-resolv
no-poll
localise-queries
no-negcache

# DNS
#interface=eth0
local=/devbox/
domain=devbox

cache-size=10000

server=8.8.4.4
server=8.8.8.8
#server=194.158.122.10
#server=194.158.122.15

# DHCP
dhcp-authoritative
dhcp-range=192.168.1.100,192.168.1.200,10h
dhcp-option=3,192.168.1.254

I then restarted everything
$ sudo reboot
   or
$ sudo /etc/init.d/dnsmasq restart
$ sudo service apache2 reload/restart

And at this point I don't know where I should look, since the virtual host work locally but cannot be accessed from an other computer on the same network.
Using NSLOOKUP from an other machine I actually get
c:\WINDOWS\system32>nslookup test.devbox
Server:   UnKnown
Address:  192.168.1.10 (which is the server)

Nom :    test.devbox
Address:  127.0.0.1

And when I try to access http://test.devbox, I get ERR_CONNECTION_REFUSED.
I don't know where to look anymore.
Here is the answer of the apache2ctl command
$ sudo apache2ctl -S

AH00548: NameVirtualHost has no effect and will be removed in the next release /etc/apache2/ports.conf:5
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this message
VirtualHost configuration:
*:80                   is a NameVirtualHost
     default server 127.0.0.1 (/etc/apache2/sites-enabled/000-default.conf:1)
     port 80 namevhost 127.0.0.1 (/etc/apache2/sites-enabled/000-default.conf:1)
     port 80 namevhost example.devbox (/etc/apache2/sites-enabled/example.devbox.conf:1)
             alias www.example.devbox
     port 80 namevhost opcv.devbox (/etc/apache2/sites-enabled/opcv.devbox.conf:1)
     port 80 namevhost phabricator.devbox (/etc/apache2/sites-enabled/phabricator.devbox.conf:1)
     port 80 namevhost test.devbox (/etc/apache2/sites-enabled/test.devbox.conf:1)
             alias www.test.devbox
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex rewrite-map: using_defaults
Mutex default: dir="/var/lock/apache2" mechanism=fcntl
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33

Thank and I hope we'll be able to solve this issue together.

A: As can be seen from the output of nslookup you have you DNS entry configured wrong, it points test.devbox to 127.0.0.1. It should point to the 192.168.x.x IP of the server instead.
Once fixed this (As per your comments) to do what you want first you must ensure that each client machine that you want to navigate your sites uses your server for DNS resolution.
What happens is, on client machine A you open your browser and put:
http://test.devbox/

In the location bar.
The browser in client machine A asks the DNS server for test.devbox's IP address and get's 192.168.1.10 as a result.
The browser opens a TCP connection to 192.168.1.80 port 80 (HTTP) and send this request (I'm omitting uninteresting headers here):
GET / HTP/1.1
Host: test.devbox
[...]

The http server at that address responds as you've configured it.
So in short, if you're using separate Server and Client machines and want to use a FQDN instead if an IP to navigate your site, you either add the relevant entries at /etc/hosts of the machines (or equivalent under windows) or you ensure that both machines use a DNS server under your control. And no, 127.0.0.1 cant be accessed outside the local machine :-)

A: I figured out my issue, there was two problems.
1 : My dhcp server was still enabled on my router... (though I had already disabled it when I set up my dhcp and dns server...
2 : Indeed my DNSMASQ was wrongly configured. Now it is configured to redirect traffic with a peculiar domain (devbox here) to the apache server. I'm quite the newby, I understand what I did but I wouldn't be able to explain it. (Not a native speaker)
dnsmasq.conf
#domain-needed not needed
no-hosts
#expand-hosts not needed
bogus-priv
no-resolv
no-poll
localise-queries
no-negcache

# DNS
#interface=eth0
#local=/lan/
#domain=lan
address=/devbox/192.168.1.10 -> This is the line redirecting traffic.

cache-size=10000

server=8.8.4.4
server=8.8.8.8
#server=194.158.122.10
#server=194.158.122.15

# DHCP
dhcp-authoritative
dhcp-range=192.168.1.100,192.168.1.200,10h
dhcp-option=3,192.168.1.254


text:
Q: PageInit Jquery mobile not working Hi I'm new on phonegap jquerymobile ios, so I'm just trying to execute a simple alert message in the pageinit, but the event never fired.
Here is my jquery code.
          $('#myPage').live('pageInit', function(event){
                            navigator.notification.alert("PhoneGap is Working");
                            });

and here is the html code

My Title

Hello world

Acura

Audi

BMW

Cadillac

Ferrari

could anybody tell me what am I doing wrong or maybe It's problem of the simulator?

A: The alert message is not firing because the you have used pageInit instead of pageinit in your jquery code.
Replace
$('#myPage').live('pageInit', function(event){
                            navigator.notification.alert("PhoneGap is Working");
                            });

with
$('#myPage').live('pageinit', function(event){
                            alert("PhoneGap is Working");
                            });

Your code will work fine.


text:
Q: smoothState.js - Identifying the referring page When clicking on a link smoothstate loads the new page's content, I'd like to identify the referring page with a class visible on the new page. Is there any way to do this?

A: This isn't the most dynamic solution, but what I ended up doing was setting classes to the anchor tags on the referring page.  SmoothState has the onBefore() callback, which passes $currentTarget, i.e. the anchor element you clicked to start the transition.  You could just as easily read the href off the anchor element and detect what you want to do that way as well (or store it off somewhere until later).
So in my HTML, I could declare a link like so:
New Page

Then when I'm setting up smoothState, I declare my onBefore() callback:
onBefore: function( $currentTarget, $container ) {
  if ( $currentTarget.is( ".special_case" ) ) {
    // Some logic here
    globalSpecialCase = true;
  }
}

Since smoothState actually keeps you in the same place and just does an Ajax call to request new page HTML, then swaps out the page content, your current Javascript environment remains, global variables and all.  So I set up a global flag (or you could make whatever data structure you want), and for that case with the special link, set the flag.
At the new page load, smoothState runs onReady(), that signals it's got the new page content and is ready to replace it and run the intro animations.  You could check your flag here to do things before the page starts rendering, or you could wait until the onAfter() callback happens, which means the page is fully loaded and all the transition animations have run.  At this point, I check the flag, run some logic, and unset it to make sure I'm ready for a new link click later.
onReady: {
  duration: 0,
  render: function( $container, $newContent ) {
    if ( globalSpecialCase ) {
      // Logic because this page was loaded from a special link
      globalSpecialCase = false;
    }

    // Inject the new content
    $container.html( $newContent );
  }
}

One thing to note: pretty much all the smoothState examples have the onReady duration set to 0, which means the onAfter() callback will happen immediately following onReady(), regardless of how long your animations take.  If you actually want onAfter() to wait until the animations are done, make sure to set duration to the milliseconds your animations take.


text:
Q: Export data from Anylogic database I have been struggling with model data exportation using Anylogic.
Some context. When running a parameter variation experiment (several iterations and replicates) using parallelization, I haven't found a systematic way to collect the data to analyze them using Python or R. So, I want just to run experiments and save the output in a custom location (folder).
What I have tried so far:

*

*First, I tried the text file Anylogic features, but they didn't work with a parallel setup (e.g., not all rows were recorded)

*I tried using databases and then exporting the data to Excel. But I had the problem of Excel size limitation (about 1M rows). I am exploring several iterations and replicates so that Excel files wouldn't work.

*I have been trying to connect to the database using R and Python without success. Still, I would need some wrapper to convert the tables into a format I can use with R or Python. That would need to be done within Anylogic, so every experiment data are saved into a given folder.

*

*Connect to the database using Python

*Read the data and convert them to a format I can use independently, let's say a CSV file.

*For now, the only thing that has worked for me is to create as many CSV files as iteration and replicates I have in my experiment, so, if I have 10 iterations with 100 replicates each, I will get 1000 files CSV per dataset I want to collect.

*Another option would be to convert a database (query) into a csv file using Java. Before the experiment starts I clear all the databases. At the end of the experiment, I would like to save the data, and clear the databases, running this code:

try {
    ResultSet rs = selectResultSet("SELECT * from MODEL_PARAMETERS");
    CSVWriter csvWriter = new CSVWriter(new FileWriter("output/model_parameters.csv"), '\t');
    csvWriter.writeAll(rs, true);
    csvWriter.close();
    deleteFrom(model_parameters).execute();
} catch (IOException e)  {
    getEngine().pause();
    traceln("--> An Exception happened during initialization, continue? ...");
    e.printStackTrace();
}

I am getting this error:
The method writeAll(Iterable<String[]>, boolean) in the type CSVWriter is not applicable for the arguments (ResultSet, boolean)

The ResultSet is an interface:
https://help.anylogic.com/index.jsp?topic=%2Fcom.anylogic.help%2Fhtml%2Fjavadoc%2Fcom%2Fanylogic%2Fengine%2Fconnectivity%2FResultSet.html
The selectResultSet is:
selectResultSet
public ResultSet selectResultSet(java.lang.String sql,
                                 java.lang.Object... params)
Get the results as a result set object for the given sql and params
Parameters:
sql - string containing select query
params - array containing select query params
Returns:
ResultSet selected ResultSet

Any ideas on how to deal with this? Thanks!

A: To write dbase records to a csv, use this setup:
Create a "Text file" element and setup as below:

Then, use the code below when the Experiment ends, i.e. last iteration's last replication is done. Obviously adjust headers for your table structure:
File outputDirectory = new File("outputs");
outputDirectory.mkdir();
String outputFileNameWithExtension = outputDirectory.getPath()+File.separator+"output_operations.csv";

file.setFile(outputFileNameWithExtension, Mode.WRITE_APPEND);

// create header
file.println(        "unique_id"+","+"replication");

// Write data from dbase table
List<Tuple> rows = selectFrom(output_operations).list();

for (Tuple row : rows) {
        file.println(        row.get( output_operations.unique_id ) + "," +
                                        row.get( output_operations.replication ));
}
file.close();

A:
For now, the only thing that has worked for me is to create as many CSV files as iteration and replicates I have in my experiment, so, if I have 10 iterations with 100 replicates each, I will get 1000 files CSV per dataset I want to collect.

To make this work better, write your output data into the model dbase at runtime first, then export into 1 csv at the very end of all runs.
In your output dbase tables, have columns for "iteration" and "replication" numbers to ensure every record is absolutely unique (otherwise, some data is lost in parallel runs as you observed as well).
This works and is very reliable (and fast), it really boils down to ensuring that any dbase record done in any parallel run is written into a unique dbase record. You can use getCurrentReplication() and getCurrentIteration() at runtime to ensure data is writtne correctly...

A: This is working for me now, just a function with two parameters: query and filename

Here a more general explanation: https://sdaza.com/blog/2020/anylogic-database/


text:
Q: how to pass http api data to anther page? I was building a demo application for a store (not a specific one) and I got the data from an online JSON file through http requests, is it possible to pass the data to another file?
I tried to pass the data using an object from the where I extracted the data and using sharedPreferences too expecting to pass the data to the other screen and display it, but the actual output was nothing.

A: you can share data from one page to another page using arguments property of push method
Navigator.of(context).pushNamed("routeName",arguments: data);

to extract this data in the second page use this
ModalRoute.of(context)!.settings.arguments;


text:
Q: IF NOT EXISTS INSERT, ELSE UPDATE -- not working for? here i want to update item_quatity if exist else insert row
+----+--------+-----------+---------------+
| id |user_id | item_id   | item_quantity |
+----+--------+-----------+----------------+
|  1 | 16     | 4         | 1             |
|  2 | 5      | 6         | 2             |
+----+--------+-----------+---------------+

INSERT INTO user_items
SET user_id = 16 ,item_id = 4 , item_quantity = 1
ON DUPLICATE KEY
UPDATE item_quantity = item_quantity + '1' ;

OR

    INSERT INTO user_items
         (user_id,item_id,item_quantity) VALUES ('16','4','1')
    ON DUPLICATE KEY
    UPDATE item_quantity= item_quantity + '1' ;

This query always insert row , update is not working ???

A: Exist what? user_id? item_id? or both user_id, item_id?
add a UNIQUE constraint on column user_id,item_id and it will work,
ALTER TABLE user_items ADD CONSTRAINT tb_uq UNIQUE (user_id, item_id)

that is if you want to have unique compound column user_id, item_id

A: insert into user_items (id, user_id ,item_id , item_quantity) values(3,16, 4, 1)
on duplicate key update item_quantity = item_quantity + 1


text:
Q: Error with Salesforce site after making changes to the VF code The Visualforce page works fine when I preview it but when I add the VF page to a site it gives me the below error. I checked the public access settings and it looks fine. All the objects have CRED rights. I tried deleting all the changes that I made recently but still, the site shows it is down. Can you check my below code?

VF Code:
<apex:page controller="i2"  sidebar="false" lightningStylesheets="true" docType="html-5.0"  >

        <meta charset="utf-8" />
        <meta http-equiv="x-ua-compatible" content="ie=edge" />
        <title>SLDS ResponsiveDesign Visualforce Page in Salesforce Mobile</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <apex:slds />

            <apex:form id="theform" >

                <apex:pageBlock id="section1"  >

                    <apex:outputPanel id="errmsg">
                        <apex:pageMessages />
                    </apex:outputPanel>

                        Cleaning Activities

                    <apex:outputPanel styleClass="grey" layout="block">
                        <apex:pageBlockSection title="Login" collapsible="false">
                            <apex:inputField value="{!cle.Password__c}">
                                <apex:actionSupport event="onchange" action="{!assignPassword}"  reRender="CleaningSection" />
                            </apex:inputField>
                        </apex:pageBlockSection>
                    </apex:outputPanel>

                        <apex:commandButton styleClass="slds-button slds-button--brand" value="Retrieve Cleaning Activities" action="{!retrieve}"  />

                    <apex:outputPanel id = "CleaningSection" styleClass="grey" layout="block">
                        <apex:pageBlockSection columns="2" title="Cleaning Activity" id="section1" collapsible="false">
                            <apex:inputField value="{!cle.Operation__c}" required="false"/>
                            <apex:inputField value="{!cle.Cleaning_Company__c}" html-disabled = "true" html-hidden = "hidden" styleClass="hideField" />
                            <apex:inputField value="{!cle.PTW_Number__c}"/>
                             <apex:inputField value="{!cle.Water_Usage_in_litres__c}"/>
                            <apex:inputField value="{!cle.Date_of_Cleaning__c}"/>
                            <apex:inputField value="{!cle.Cleaning_End_Date__c}"/>
                            <apex:inputField value="{!cle.Dry_Cleaning__c}"/>
                            <apex:inputField value="{!cle.Full_Site_Cleaning__c}"/>
                            <apex:inputField value="{!cle.Specific_Size_Cleaned_kWp__c}"/>
                            <apex:inputField value="{!cle.Status__c}"/>
                            <apex:inputField value="{!cle.URL_of_Photos_folder__c}"/>

                            <apex:inputField value="{!cle.Start_Time__c}" type="time" />
                            <apex:inputField value="{!cle.End_Time__c}" type="time"/>
                            <apex:inputField value="{!cle.Number_of_Workers__c}"/>
                            <apex:inputField value="{!cle.Hours_to_Deduct__c}"/>

                        </apex:pageBlockSection>
                    </apex:outputPanel>

                        <apex:commandButton styleClass="slds-button slds-button--brand" value="Save Cleaning Activity" action="{!save1}"  >
                            <apex:param name="buttonId1" value="button1" assignTo="{!paramValue}"/>
                        </apex:commandButton>

                </apex:pageBlock>

                <apex:pageBlock id="section2">

                    <apex:outputPanel styleClass="grey" layout="block">
                        <apex:pageBlockSection columns="2" title="Permit to Work Number"  collapsible="false">
                            <apex:inputField value="{!ptw.PTW_Number1__c}" required="false" />
                            <apex:inputField value="{!ptw.Number_of_Workers__c}"/>
                            <apex:inputField value="{!ptw.Date__c}"/>
                            <apex:inputField value="{!ptw.Cleaning_Activity__c}" />
                        </apex:pageBlockSection>
                    </apex:outputPanel>

                        <apex:commandButton styleClass="slds-button slds-button--brand" value="Save Permit to Work Number" action="{!save1}" reRender="errmsg">

                            <apex:param name="buttonId2" value="button2" assignTo="{!paramValue}"/>
                        </apex:commandButton>

                        <apex:commandButton styleClass="slds-button slds-button--brand" value="Reset PTW" action="{!refresh}" />

                </apex:pageBlock>

                <apex:pageBlock >
                    <apex:pageBlockSection >

                        <apex:pageBlockTable value="{!clelist}" var="a" id="tableBlock" style="width:130%" >
                            <apex:column headerValue="Ticket Number">
                                <apex:outputLink value="https://c.ap2.visual.force.com/apex/Record_detail_Vf_Page?id = {a.Cleaning_Activity__c}">{!a.Name}</apex:outputLink>
                            </apex:column>
                            <apex:column headerValue="Contractor" value="{!a.Cleaning_Company__c}"/>
                            <apex:column headerValue="# of Workers" value="{!a.Number_of_Workers__c}"/>
                            <apex:column headerValue="Start Date" value="{!a.Cleaning_Start_Date__c}"/>
                            <apex:column headerValue="End Date" value="{!a.Cleaning_End_Date__c}"/>
                            <apex:column headerValue="PTW Number" value="{!a.Permit_to_Work_Number__c}"/>
                        </apex:pageBlockTable>

                    </apex:pageBlockSection>
                </apex:pageBlock>

            </apex:form>

Controller:
public class i2{
public Cleaning_Activity__c cle{get;set;}
public Permit_to_Work_Number__c ptw{get;set;}
public List<Cleaning_Activity__c> clelist{get;set;}
public String paramValue{get;set;}

//constructor to create a new record
public i2(){
    cle = new Cleaning_Activity__c();
    ptw = new Permit_to_Work_Number__c();

}

public void refresh(){
    ptw = new Permit_to_Work_Number__c();
}

//Assigning password to Cleaning Company
/* public void assignPassword(){
      system.debug(cle.Password__c);
     if(cle.Password__c != null){
   cle.Cleaning_Company__c = cle.Password__c;
     }}*/

public void retrieve()
{
    if(cle.Password__c == 'pv' || cle.Password__c == 'sunsure')
    {
        clelist = [SELECT Name, Password__c, Cleaning_Company__c, Number_of_Workers__c, Cleaning_Start_Date__c,
                Cleaning_End_Date__c, Permit_to_Work_Number__c,PTW_Number__c FROM Cleaning_Activity__c where Password__c =: cle.Password__c];
        system.debug(clelist);
    }
    else if(cle.Password__c == NULL)
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please key in the password to retreive the details'));
    else
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Password is incorrect'));
}

public void save1(){
    system.debug('paramValue ' + paramValue);
    if(paramValue == 'button2')
    {
        system.debug('Password is ' + cle.Password__c);
        if(cle.Password__c == 'pv' || cle.Password__c == 'sunsure')
        {
            System.debug('I am here');
            upsert ptw;
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'PTW Inserted Successfully'));
            ptw = new Permit_to_Work_Number__c();
        }
        else
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Wrong Password'));
        }
    }
    else
    {

        if(cle.Password__c == 'pv' || cle.Password__c == 'sunsure')
        {
            if(cle.Operation__c != NULL)
            {
                upsert cle;
                clelist = [SELECT Name, Password__c, Cleaning_Start_Date__c,
                            Cleaning_End_Date__c,Number_of_Workers__c,
                           Permit_to_Work_Number__c FROM Cleaning_Activity__c where Password__c =: cle.Password__c];
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Cleaning Activity Inserted Successfully'));
                system.debug(clelist);
                cle = new Cleaning_Activity__c();
            }
            else
            {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please input the Operation Name'));
            }
        }
        else
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Wrong Password'));
        }
    }

}

  }

A: This screenshot shows a GACK Error Id response from Salesforce.

Basically, something went wrong internally and they just returned an error code that can be used to track the cause.
However, the only current official method to decode that error code is to contact Salesforce support via a case.
Please consider voting for the Salesforce Idea Provide a public reference of GACK general stack trace identifiers as a way to improve this situation in the future.


text:
Q: pdf to jpg with ImageMagick Installed on local server imagemagick, but do not understand how to convert ALL pages of pdf file into a single image jpg. And whether it is even possible.
Without specifying the page number only converts the first page
    $im = new imagick( "libs/pdf/files/$Jfile" );
    // convert to jpg
    $im->setImageColorspace(255);
    $im->setCompression(Imagick::COMPRESSION_JPEG);
    $im->setCompressionQuality(60);
    $im->setImageFormat('jpeg');
    //resize
    $im->resizeImage(385, 500, imagick::FILTER_LANCZOS, 1);
    //write image on server
    $im->writeImage("libs/pdf/files/$JPGfile");
    $im->clear();
    $im->destroy();

A: Two options...
Option 1
To make each page of the PDF come out as a separate JPEG, change the 3rd last line from:
$im->writeImage("libs/pdf/files/$JPGfile");

to something like:
$im->writeImages("z%03d.jpg",false);

Option 2
To make all pages of the PDF come out in a long list, change where the comment says "write image on server" to the following:
// Write on server
$im->resetIterator();
$appended = $im->appendImages(true);
$appended->writeImage("appended.jpg");

Change true to false depending on whether you want a tall list of images or a wide one.


text:
Q: SMOTENC: could not convert string to float I have imbalanced data that percentage of M is 80% and F 20%. Below is example of the data:
NAME    COUNTRY HEIGHT  HANDPHONE TYPE  GENDER
NOVI    USA     160 samsung SM-G610F    F
JOHN    JAPAN   181 vivo 1718           M
RICHARD UK      175 samsung SM-G532G    M
ANTHONY UK      179 OPPO F1fw           M
SAMUEL  UK      185 Iphone 8 plus       M
BUNGA   KOREA   170 Iphone 6s           F

So i want to balance the data with percentage of M:F is 50%:50% using SMOTENC. I've try this script:
import numpy as np
import pandas as pd
import scipy.stats as stats
import sklearn
import keras
import imblearn
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('ggplot')

df=pd.read_excel('Data for oversampling.xlsx')
Data = df
Data.GENDER.replace({'M':0,'F':1},inplace=True)
sns.countplot('GENDER', data = Data)
y = Data.GENDER
x = Data.drop('GENDER', axis=1)

from imblearn.over_sampling import SMOTENC
smote_nc = SMOTENC(categorical_features=[0,3], random_state=0)
x_resampled, y_resampled = smote_nc.fit_resample(x, y)

but i getting eror like this:
could not convert string to float

Anyone can help?

A: In your dataset all your features are categorical except feature 2 which is the only non categorical. You need to update your list of categorical_features.


text:
Q: Spark SQL to insert data into Cassandra I am a beginner with Scala and Apache Spark and I am facing the below problem.
I am trying to insert data into a Cassandra table..user (name,favorite_food) using spark SQL.
The code snippet looks like this
val conf = new SparkConf(true)
  .set("spark.cassandra.connection.host", "127.0.0.1")

val sc = new SparkContext("local", "test", conf)
val sqlC = new CassandraSQLContext(sc)
sqlC.setKeyspace("myKeySpace")
sqlC.sql("INSERT into user (name,favorite_food) values ('John Doe','brownies')")

However I face the issue
Exception in thread "main" java.lang.RuntimeException: [1.13] failure: ``table'' expected but identifier user found
I am running a local instance of Cassandra DB
My Maven POM looks like
<dependencies>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.10</artifactId>
            <version>1.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_2.10</artifactId>
            <version>1.6.2</version>
        </dependency>
</dependencies>

My question is;
Please can you let me know why I face the below error (The insert statement works perfectly fine on the cassandra shell)
Exception in thread "main" java.lang.RuntimeException: [1.13] failure: ``table'' expected but identifier user found
PS : I do know I can use the spark connector provided by datastax to save data to Cassandra, however I want to use Spark SQL...is that possible?

A: We can't insert a data to table using Cassandra Context. Spark doesn't provide that option.
You will try it this it will definitely works,
import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import com.datastax.spark.connector._
import com.datastax.spark.connector.UDTValue

//we need define a class
//case class name(column name: datatype,column name: datatype)

case class model(name: String, favorite_food: String)

// define sequence to insert a data
// val coll = sc.parallelize(Seq(classname(data, data), model(data, data)))

val collection = sc.parallelize(Seq(model("John Doe", "brownies")))

 //then save to cassandra
 //collection.saveToCassandra("keyspace_name", "table_name", SomeColumns("col name", "col name"))

collection.saveToCassandra("myKeySpace", "user", SomeColumns("name", "favorite_food"))

Thanks,
Aravinth


text:
Q: Saving to a realtime firebase using android studio I am saving user information to a realtime database on a android studio app. When the user goes to register they select weather they are a PT or client by using radio buttons. As shown in my database all the user information is being saved under the user child node on firebase. Is there a way I can create subheadings called PT and Clients underneath user in the realtime database by using the radio buttons. Sign up code is:
public class RegisterActivity extends AppCompatActivity {
   EditText txt_fullname, txt_email, txt_mobilenumber, txt_repassword, txt_password;
   Button btn_register;
   RadioButton radioJobClient, radioJobPT;
   DatabaseReference databaseReference;
   FirebaseDatabase firebaseDatabase;
   String job ="";
   FirebaseAuth firebaseAuth;

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    txt_fullname = (EditText) findViewById(R.id.editText_fullname);
    txt_email = (EditText) findViewById(R.id.editText_UserEmail);
    txt_password = (EditText) findViewById(R.id.editText_Password);
    txt_repassword = (EditText) findViewById(R.id.editText_rePassword);
    txt_mobilenumber = (EditText) findViewById(R.id.mobilenumber);
    btn_register = (Button) findViewById(R.id.button_reg);
    radioJobClient = (RadioButton) findViewById(R.id.radio_Client);
    radioJobPT = (RadioButton) findViewById(R.id.radio_PersonalTrainer);

    databaseReference = FirebaseDatabase.getInstance().getReference("User");
   // new code

    firebaseAuth = FirebaseAuth.getInstance();

    btn_register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String  fullname = txt_fullname.getText().toString();
            final String  email = txt_email.getText().toString();
            final String  mobilenumber = txt_mobilenumber.getText().toString();
            final String  password = txt_password.getText().toString();
            final String rePassword = txt_repassword.getText().toString();
            if (radioJobClient.isChecked()){
                 job = "Client";
            }
            if (radioJobPT.isChecked()){
                job = "PT";
            }
            if (TextUtils.isEmpty(email)){
                Toast.makeText(RegisterActivity.this, "Please enter Email", Toast.LENGTH_LONG).show();
            }
            if (TextUtils.isEmpty(fullname)){
                Toast.makeText(RegisterActivity.this, "Please enter fullname", Toast.LENGTH_LONG).show();
            }
            if (TextUtils.isEmpty(password)){
                Toast.makeText(RegisterActivity.this, "Please enter password", Toast.LENGTH_LONG).show();
            }

            firebaseAuth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {

                                User user = new User(
                                        fullname,
                                        email,
                                        mobilenumber,
                                        password,
                                        job
                                );

                                FirebaseDatabase.getInstance().getReference("User")
                                        .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                        .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {

                                        Toast.makeText(RegisterActivity.this, "Registration Complete", Toast.LENGTH_SHORT).show();
                                        startActivity(new Intent(getApplicationContext(),MainActivity.class));

                                    }
                                });

                            } else {
                                Toast.makeText(RegisterActivity.this, "Registration Unsuccessful", Toast.LENGTH_LONG).show();

                            }

                            // ...
                        }
                    });

        }
    });

}

A:     if (radioJobClient.isChecked()){
                     job = "Client";
    FirebaseDatabase.getInstance().getReference("User").child(job).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {

                                            Toast.makeText(RegisterActivity.this, "Registration Complete", Toast.LENGTH_SHORT).show();
                                            startActivity(new Intent(getApplicationContext(),MainActivity.class));

                                        }
                                    });
                }
                if (radioJobPT.isChecked()){
                    job = "PT";
FirebaseDatabase.getInstance().getReference("User").child(job).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {

                                            Toast.makeText(RegisterActivity.this, "Registration Complete", Toast.LENGTH_SHORT).show();
                                            startActivity(new Intent(getApplicationContext(),MainActivity.class));


text:
Q: Datamapper Unique Constraint and Paranoid Deletion I have a datamapper object with a few fields and a unique constraint. Effectively, this ensures that only one record can be created per user ID per date code.
class Form
  include Datamapper::Resource
  property :id, Serial
  property :username, String, :required => true, :index => true
  property :termcode, Integer, :required => true
  property :status, Enum[:draft, :review, :approved, :denied], :default => :draft
  ...

  property :deleted_at, ParanoidDateTime

  # only one record per user per term code
  validates_uniqueness_of :username, :scope => [:termcode], :unless => lambda{|r| r.status == :draft }

end

Problem is that if I utilize the paranoid deletion features, the uniqueness constraint prevents additional records from being created with the same data.
For example, if Sue creates a record for the "2015" term code, and deletes it, she's prevented from creating a new one with the same term code because the paranoid functionality persists the original record in the database.
Fields for this model are required for data integrity purposes, and are indexed in many cases as well for sorting and better query optimization.
How do I utilize safe deletion but also allow users to enter more records but tell the unique constraint to ignore the deleted ones?

A: You should create a method and register it before create and before save as a hook.
This is basically the same way the paranoid types operate.


text:
Q: How to resolve this neo4j/python error, my query is working fine in neo4j UI but getting this error here This is the code I am trying to run
def get_label(tx, name):
tx.run("Match(n) where n.name=$name"
     "return labels(n)",
      name=name )
return "labels(n)"

with graphdb.session() as session:
    Label = session.read_transaction(get_label, "usa")

I am getting this syntax error:

neo4j.exceptions.CypherSyntaxError: {code:
Neo.ClientError.Statement.SyntaxError} {message: Invalid input 'a':
expected 'o/O' (line 1, column 36 (offset: 35)) "Match(n) where
n.name=$namereturn labels(n)" ^}

A: First, you're missing a space or newline between $name and return in your query.
It should be:
"MATCH (n) WHERE n.name = $name RETURN labels(n)"

or even shorter:
"MATCH (n {name: $name}) RETURN labels(n)"

Second, you're not returning the results of tx.run, you're returning a string. I'm not experienced in Python but the code should probably be more like:
def get_label(tx, name):
    return list(tx.run("MATCH (n {name: $name}) RETURN labels(n)", name=name))

Finally, get_label is probably a misnomer.
A node defines 0 to many labels and the implementation I suggested here would return as many lists of labels as there are matched nodes.
This might mean a single list if the name is unique among all nodes in your data set.


text:
Q: T-SQL Select dates Sunday through Saturday (2 weeks apart) from Dates table for the last n months I'm trying to select specific date ranges from a dates table and assign a week number (2 weeks = 1 week). Say I have the following table:
Date    WeekOfYear  WeekDayName
12/26/2019  52  Thursday
12/27/2019  52  Friday
12/28/2019  52  Saturday
12/29/2019  53  Sunday
12/30/2019  53  Monday
12/31/2019  53  Tuesday
1/1/2020    1   Wednesday
1/2/2020    1   Thursday
1/3/2020    1   Friday
1/4/2020    1   Saturday
1/5/2020    2   Sunday
1/6/2020    2   Monday
1/7/2020    2   Tuesday
1/8/2020    2   Wednesday
1/9/2020    2   Thursday
1/10/2020   2   Friday
1/11/2020   2   Saturday
1/12/2020   3   Sunday
1/13/2020   3   Monday
1/14/2020   3   Tuesday
1/15/2020   3   Wednesday
1/16/2020   3   Thursday
1/17/2020   3   Friday
1/18/2020   3   Saturday
1/19/2020   4   Sunday
1/20/2020   4   Monday
1/21/2020   4   Tuesday
1/22/2020   4   Wednesday
1/23/2020   4   Thursday
1/24/2020   4   Friday
1/25/2020   4   Saturday
1/26/2020   5   Sunday
1/27/2020   5   Monday
1/28/2020   5   Tuesday
1/29/2020   5   Wednesday
1/30/2020   5   Thursday
1/31/2020   5   Friday
2/1/2020    5   Saturday
2/2/2020    6   Sunday
2/3/2020    6   Monday
2/4/2020    6   Tuesday
2/5/2020    6   Wednesday
2/6/2020    6   Thursday
2/7/2020    6   Friday
2/8/2020    6   Saturday
2/9/2020    7   Sunday
2/10/2020   7   Monday
2/11/2020   7   Tuesday
2/12/2020   7   Wednesday
2/13/2020   7   Thursday
2/14/2020   7   Friday
2/15/2020   7   Saturday
2/16/2020   8   Sunday
2/17/2020   8   Monday
2/18/2020   8   Tuesday
2/19/2020   8   Wednesday
2/20/2020   8   Thursday
2/21/2020   8   Friday
2/22/2020   8   Saturday
2/23/2020   9   Sunday
2/24/2020   9   Monday
2/25/2020   9   Tuesday
2/26/2020   9   Wednesday
2/27/2020   9   Thursday
2/28/2020   9   Friday
2/29/2020   9   Saturday
3/1/2020    10  Sunday
3/2/2020    10  Monday
3/3/2020    10  Tuesday
3/4/2020    10  Wednesday
3/5/2020    10  Thursday
3/6/2020    10  Friday
3/7/2020    10  Saturday
3/8/2020    11  Sunday
3/9/2020    11  Monday
3/10/2020   11  Tuesday
3/11/2020   11  Wednesday
3/12/2020   11  Thursday
3/13/2020   11  Friday
3/14/2020   11  Saturday
3/15/2020   12  Sunday
3/16/2020   12  Monday
3/17/2020   12  Tuesday
3/18/2020   12  Wednesday
3/19/2020   12  Thursday
3/20/2020   12  Friday
3/21/2020   12  Saturday
3/22/2020   13  Sunday
3/23/2020   13  Monday
3/24/2020   13  Tuesday
3/25/2020   13  Wednesday

My end goal would like this:
WeekNum SundayDate  SaturdayDate
1       12/29/2019  1/11/2020
2       1/12/2020   1/25/2020
3       1/26/2020   2/8/2020
4       2/9/2020    2/22/2020
5       2/23/2020   3/7/2020
6       3/8/2020    3/21/2020

If I were to do this across several years, the max WeekNum would be either 26 or 27 depending on the year.
I've attempted several different queries but can't quite get the calculation right:
with MinDate_cte (Cut, MinDate)
as (select Cut = (((WeekOfYear + 1) % 52) / 2) + 1, MinDate = Date
    from DimDate
    where (datediff(day, Date, dateadd(day, 7 - datepart(weekday, getdate()), getdate())) % 14) = 0
        and Date between dateadd(month, -7, dateadd(day, 7 - datepart(weekday, getdate()), getdate())) -- Sunday 7 months ago
        and dateadd(day, 7 - datepart(weekday, getdate()), getdate()) -- next upcomming Saturday
    )

select Cut = (((WeekOfYear + 1) % 52) / 2) + 1, MaxDate = dateadd(day, 1, Date), MinDate
from DimDate
join MinDate_cte on MinDate_cte.Cut = (((WeekOfYear + 1) % 52) / 2) + 1
where (datediff(day, Date, dateadd(day, 7 - datepart(weekday, getdate()), getdate())) % 14) = 0
and Date between dateadd(month, -7, dateadd(day, 7 - datepart(weekday, getdate()), getdate())) -- Sunday 7 months ago
                           and dateadd(day, 7 - datepart(weekday, getdate()), getdate()) -- next upcomming Saturday
and dateadd(day, 1, Date) > MinDate
order by Date

A: I would use much easier SQL and just work off the Sundays. This is untested as I just typed this in here but it should be right or close.
--this is your date range
declare @startdate date = '20191229'
    ,@enddate date = '20200331'

select WeekNum = row_number() over (order by [Sunday]),*
from (
     select date as [Sunday]
        , dateadd(day,14,date) as [Saturday]
        , rn = row_number() over (order by date)
     from [your table]
     where WeekDayName = 'Sunday'
         and date between @startdate and @enddate) a
where rn % 2 = 1


text:
Q: find and replace text within a csv using partial and wildcard up to the first delimiter I have a csv generated from a SQL output and I am trying to replace partial strings of the csv with a generic string.  I have tried FART, (always makes me laugh), FINDSTR and POWERSHELL but Idont think my skills are enough and Google searching is quite hard because of the caveats I stipulate.
The txt file is like this (sample data).
course_id,user_id,role,status
2122-DAC00002,123456,sometxt,active
2122-DAC00002,13456,sometxt,active
2122-DAC00010/1,987654,sometxt,active
2122-DAC00010,55669988,sometxt,active
2122-DAC00010/2,112233,sometxt,active
2122-DAC00010,852349,sometxt,active

The headers can be ignored, the first part is the part I need changing en-masse so search for 2122-* until the first , (the 2122-* may be slightly different character lengths but will always stop at the , delimiter, and then replace all the first iterations of 2122-* with 2122-GCE.
So the final output would be :
course_id,user_id,role,status
2122-GCE,123456,sometxt,active
2122-GCE,13456,sometxt,active
2122-GCE,987654,sometxt,active
2122-GCE,55669988,sometxt,active
2122-GCE,112233,sometxt,active
2122-GCE,852349,sometxt,active

I need to automate this, so within a .bat file, or a .ps1 would be good.
Hope this makes sense?
[EDIT /]
Apologies, missed my code attempts off.
My findstr attempt:
findstr /V /i /R '2122-.*' '2122-GCE' "E:\path to file\file1.csv" > "E:\path to file\output3.csv"

findstr output:
course_id,user_id,role,status
2122-GCENAC00025,123456,sometxt,active
2122-GCENAC00025,568974,sometxt,active
2122-GCENAC00025,223366,sometxt,active
2122-GCENAC00025,987654,sometxt,active

As you can see above, its prefixed and not replaced.
My FART attempt:
E:\path to\fart "E:\path to file\file1.csv" 2122-N* 2122-GCE
E:\path to\fart "E:\path to file\output3.csv" 2122-D? 2122-GCE

My PS1 attempt was in an ISE and I closed without saving.
edit, I had a ps window still open:
((Get-Content -path E:\path to file\file1.csv -Raw) -replace '2122-*','2122-GCE') | Set-Content -Path E:\path to file\file2.csv

Some iterations of the replace command: -replace '[^2122]*'
type file1.csv | ForEach-Object { $_ -replace "2122-*", "2122-GCE" } | Set-Content file2.csv

A: It looks like the first data value always exists with a non-empty value and not starting with ; and must be always replaced by the same value and the second data column contains on all data rows always a value and for that reason there is never ,, after first data value in a data row.
There can be used the following commented batch file under these conditions:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFile=E:\path to file\file1.csv"
set "OutputFile=E:\path to file\file2.csv"
if not exist "%SourceFile%" goto :EOF

rem Read just the header row from source CSV file and
rem create the output CSV file with just this line.
for /F "usebackq delims=" %%I in ("%SourceFile%") do (
    >"%OutputFile%" echo(%%I
    goto DataRows
)

rem Process just all data rows in source file by skipping the header row
rem with splitting each line into two substrings using the comma as string
rem delimiter with first substring assigned to loop variable I and not used
rem further and everything after first series of commas assigned to the
rem next but one loop variable J according to the ASCII table. The command
rem ECHO is used to output the first fixed data value and a comma and the
rem other data values of each data row. This output is appended to just
rem created output CSV file.

:DataRows
(for /F "usebackq skip=1 tokens=1* delims=," %%I in ("%SourceFile%") do echo 2122-GCE,%%J)>>"%OutputFile%"

endlocal

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*echo /?

*endlocal /?

*for /?

*goto /?

*if /?

*rem /?

*set /?

*setlocal /?


text:
Q: LocationListener inconsistently called I'm trying to create my own location provider in android to inject my own positioning data in the system. To do that I'm reusing the LocationManager functions in the system, registering a listener there that I expect to be called, but it is not always called. I've done some research but I can't figure out the pattern that the system use to triggers the events, and there is not extensive official documentation from Google.
Please, note that I don't use any location provider from the system (GPS, network...). I create my own coordinates and timestamp and publish it in the fake location provider, so almost all the questions about this issue are slightly different from this one (so nothing to do with the GPS, whether if I am moving or not, the minimum distance parameter...).
Here I show you the code and the Log generated. You can easily see that some events are never triggered (like onProvider enabled), triggered when it shouldn't (onProviderDisbled) or triggered at wrong times (like onStatusChanged, only triggered if there after a status change AND a location change).
Here's the main code:
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lm = (LocationManager) getSystemService(Service.LOCATION_SERVICE);

        if (!isMockLocationSet()) {
            throw new RuntimeException("Mock Locations are disabled!");
        }

        // 1. Generate a valid random name for the mock provider
        providerName = this.generateValidProviderName();

        // 2. Create the mock provider
        System.out.println("Step 2: Create provider (" + providerName + ")");
        try {
            if (lm.getProvider(providerName) == null) {
                throw new IllegalArgumentException();
            }
        } catch (IllegalArgumentException e) {// Doesn't exist, create
            lm.addTestProvider(providerName, false, false, false, false, false,
                    false, false, Criteria.POWER_MEDIUM, Criteria.ACCURACY_HIGH);
        }

        // 3. Register for updates
        System.out.println("Step 3: Register for updates");
        MyLocationListener l = new MyLocationListener();
        lm.requestLocationUpdates(providerName, 0, 0, l);

        MyAsyncTask task = new MyAsyncTask();
        task.execute();

    }
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            Location loc = new Location(providerName);

            // 4. Enable it!
            System.out.println("Step 4: Enable it");
            lm.setTestProviderEnabled(providerName, true);

            // 5. Change the status
            System.out.println("Step 5: Change the status to AVAILABLE");
            lm.setTestProviderStatus(providerName, LocationProvider.AVAILABLE,
                    null, System.currentTimeMillis());

            // 6. Change the status
            System.out
                    .println("Step 7: Change the status to TEMPORARILY_UNAVAILABLE");
            lm.setTestProviderStatus(providerName,
                    LocationProvider.TEMPORARILY_UNAVAILABLE, null,
                    System.currentTimeMillis());

            // 7.1. Change location
            System.out.println("Step 7.1: Change Location");
            loc.setTime(System.currentTimeMillis());
            loc.setLatitude(52.0f);
            loc.setLongitude(10.0f);
            lm.setTestProviderLocation(providerName, loc);

            // 7.2. Change location
            System.out.println("Step 7.2: Change Location");
            loc.setTime(System.currentTimeMillis());
            loc.setLatitude(52.1f);
            loc.setLongitude(10.1f);
            lm.setTestProviderLocation(providerName, loc);

            // 7.3. Change the status
            System.out.println("Step 7.3: Change the status to AVAILABLE");
            lm.setTestProviderStatus(providerName, LocationProvider.AVAILABLE,
                    null, System.currentTimeMillis());

            // 7.4. Change location
            System.out.println("Step 7.4: Change Location");
            loc.setTime(System.currentTimeMillis());
            loc.setLatitude(52.2f);
            loc.setLongitude(10.2f);
            lm.setTestProviderLocation(providerName, loc);

            // 7.5. Change the status
            System.out.println("Step 7.5: Change the status to OUT_OF_SERVICE");
            lm.setTestProviderStatus(providerName,
                    LocationProvider.OUT_OF_SERVICE, null,
                    System.currentTimeMillis());

            // 7.6. Change location
            System.out.println("Step 7.6: Change Location");
            loc.setTime(System.currentTimeMillis());
            loc.setLatitude(52.3f);
            loc.setLongitude(10.3f);
            lm.setTestProviderLocation(providerName, loc);

            try {
                // 8. Delete provider
                System.out.println("8. Delete provider");
                lm.setTestProviderEnabled(providerName, false);
                lm.removeTestProvider(providerName);
            } catch (IllegalArgumentException e) {
            }
            return null;
        }
    }

And here the log's output:
07-26 11:31:21.271: I/System.out(8721): Step 2: Create provider (Fake_GPS_92A4)
07-26 11:31:21.271: I/System.out(8721): Step 3: Register for updates
07-26 11:31:21.276: I/System.out(8721): Step 4: Enable it
07-26 11:31:21.276: I/System.out(8721): Step 5: Change the status to AVAILABLE
07-26 11:31:21.276: I/System.out(8721): Step 7: Change the status to TEMPORARILY_UNAVAILABLE
07-26 11:31:21.276: I/System.out(8721): Step 7.1: Change Location
07-26 11:31:21.291: I/System.out(8721): Step 7.2: Change Location
07-26 11:31:21.301: D/MainActivity(8721): onProviderDisabled
07-26 11:31:21.306: I/System.out(8721): Step 7.3: Change the status to AVAILABLE
07-26 11:31:21.306: I/System.out(8721): onLocationChanged
07-26 11:31:21.306: D/MainActivity(8721): onStatusChanged: TEMPORARILY_UNAVAILABLE
07-26 11:31:21.306: I/System.out(8721): Step 7.4: Change Location
07-26 11:31:21.306: I/System.out(8721): Step 7.5: Change the status to OUT_OF_SERVICE
07-26 11:31:21.356: I/System.out(8721): Step 7.6: Change Location
07-26 11:31:21.361: I/System.out(8721): 8. Delete provider
07-26 11:31:21.401: I/System.out(8721): onLocationChanged
07-26 11:31:21.401: I/System.out(8721): onLocationChanged
07-26 11:31:21.436: D/MainActivity(8721): onStatusChanged: AVAILABLE

Of course, it is not a permission issue:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

I've spent lot of time with that issue and simplified the code to the minimum expression, so I hope you could at least have a look.
Thanks!


text:
Q: Removing annoying whitespace dots I have some package that's adding indent guides in the form of dots for every whitespace, and I find it really annoying. How can I figure out what package is doing this, or override this thing (I have many packages in sublime text)?
It seems to happen only in my python files without text highlighting, but all files when I highlight text.

I've tried looking through all package settings within Preferences > Package Settings.


text:
Q: Split array ["banana", "apple", "orange", .....etc ] into groups based on other array, ie. [2,7,3] I have a bunch arrays, that I need to split into smaller groups based off the numbers in another matching array. Example:
var myArray1 = ["banana", "apple", "orange", "pear", "pineapple", "grapes", "apricot", "plum"];
var splitArray1 = [3,2,2,1];

I want a function to return 4 sub arrays:
[["banana", "apple", "orange"], ["pear", "pineapple"], ["grapes", "apricot"], ["plum"]];

I have found this code which is apparently meant to do just this, but it returns the full array:
function chunkArray(array, size) {
    var chunked_arr = [];
    for (var i = 0; i < array.length; i++) {
      var last = chunked_arr[chunked_arr.length - 1];
      if (!last || last.length === size) {
        chunked_arr.push([array[i]]);
      } else {
        last.push(array[i]);
      }
    }
    return chunked_arr;
}

This is in google apps script if it makes a difference.

A: You can use Array.splice()

var myArray1 = ["banana", "apple", "orange", "pear", "pineapple", "grapes", "apricot", "plum"];
var splitArray1 = [3,2,2,1];

const output = splitArray1.map(count => myArray1.splice(0, count));
console.log(output)

Above solution updates the original myArray1 array. Here is another solution using Array.slice()

var myArray1 = ["banana", "apple", "orange", "pear", "pineapple", "grapes", "apricot", "plum"];
var splitArray1 = [3,2,2,1];
var startCount = 0;

const output = splitArray1.map(count => myArray1.slice(startCount, startCount += count));
console.log(output)


text:
Q: How do I detect row selection in the Xceed DataGrid for WPF I'm horrible at this WPF thing, so bear with me.
I'm using the Xceed DataGrid for WPF, and I need to know when someone selects a row, but I can't figure out how to do it. I'm sure I need to add some XAML to enable this, but I can't figure out what I should do.

A: I use a MVVM approach and therefor favor data binding.  I will bind the SelectedItem property to a SelectedItem property on my ViewModel object for the grid.
<xcdg:DataGridControl x:Name="grid" SelectedItem="{Binding SelectedItem}">
</xcdg:DataGridControl>

Then on your property setter can do what ever is necessary upon change in the SelectedItemChanged() method.
private IMyItem _selectedItem;
public IMyItem SelectedItem
{
   get { return _selectedItem; }
   set {
          _selectedItem = value;
          OnPropertyChanged("SelectedItem");
          SelectedItemChanged();
       }
}

A: I'm actually struggling a bit with the same thing myself, except I have a prerequisite that the selection notification be done via an ICommand; however, if you do not have this need, you can wire up the SelectionChanged event handler. It's pretty elementary stuff, but I'll include the code just in case:
XAML:
 <Grid>
    <DataGrid:DataGridControl x:Name="gridControl" SelectionChanged="gridControl_SelectionChanged">
        <!-- Content -->
    </DataGrid:DataGridControl>
</Grid>

Code-behind:
private void gridControl_SelectionChanged(object sender, Xceed.Wpf.DataGrid.DataGridSelectionChangedEventArgs e)
        {
        var selectedIndex = gridControl.SelectedIndex; // int index
        var selectedItem = gridControl.SelectedItem;   // instance of bound object
        var selectedItems = gridControl.SelectedItems; // IList of bound objects
        }

All that said, I'm very interested to hear if there are any elegant solutions for getting the selected row from an Xceed DataGrid with an ICommand (in my case, I'm using anonymous types, which can make a difference)...

A: You don't have to write complicated code for something simple... although it can become tedious, here is some code for you. I hope this helps:
<Style TargetType="xcdg:DataRow">
   <EventSetter Handler="dr_PreviewMouseDown" Event="PreviewMouseDown" />
</Style>

void dr_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
   DataRow dr = sender as DataRow;

   Debug.WriteLine(sender);
}

A: So here's what I came up with
    System.ComponentModel.DependencyPropertyDescriptor gridItemsSourceDescriptor = System.ComponentModel.DependencyPropertyDescriptor.FromProperty(DataGridControl.SelectedItemProperty, typeof(DataGridControl));
    gridItemsSourceDescriptor.AddValueChanged(dgBaxRuns, HandleSelectionChanged);

A: I made for me a easiest way.
<xctk:MaterialButton Margin="5,0,5,0" Grid.Column="3" Content="Szűrt sorok kijelölése" Command="{Binding SelectFilteredRowsCommand}" CommandParameter="{Binding ElementName=MyDataGrid}" />

So, i send my datagrid with my commandparameter to the viewmodel.
 public RelayCommand<object> SelectFilteredRowsCommand { get; set; }

SelectFilteredRowsCommand = new RelayCommand<object>((o) =>
            {
                var datagrid = o as DataGridControl;
                if (datagrid != null)
                {
                    var datagriditems = datagrid.Items.Cast<SelectableProduct>();
                    foreach (SelectableProduct selectableProduct in datagriditems)
                    {
                        selectableProduct.IsSelect = true;
                    }
                }
            });

And convert back to datagrid itemsoruce type.


text:
Q: How to group rows by specific range and conditionally? I have a genetic dataset where I want to group genetic variants/rows that are physically close together in the genome. I want to group genes that are within a 500 +/- distance from certain spots in the genome per chromosome.
My 'spots' dataset is of positions that variants need to be within 500 +/- range of and looks like:
     chrom           min          max      low       high
       1             1000         1200     500       1700
       1             20000        20100    19500     20600
       5             900          1000     400       1500

My low and high columns are the ranges that I want to see if any rows in my next dataset fall into, with also accounting that the chromosome must also match.
My other dataset has a position value that I'm looking to see if fits in any of the ranges above with matching chrom:
Gene   chrom position
Gene1   1    1200
Gene2   1    10000
Gene3   5    500
Gene4   1    560
Gene5   1    20100

I've tried using group_by() and between() to set up the range, but I'm struggling to account for the need to match the chromosome (chrom) between the datasets before then searching for range.
Output would look like:
Gene   chrom position   Group
Gene1   1    1200          1  #position is in one of the ranges so is in a group
Gene2   1    10000        NA
Gene3   5    500           2  #position is in one of the ranges so is in a group
Gene4   5    560           2  #position is in the same range as above so joins that group
Gene5   1    20100         3  #position matches a chrom and range and so gets a group corresponding to that particular chrom and range

Gene3 and Gene4 are not in group 1 because they are on a different chrom.
So I am creating a Group column with a shared number for all rows in the same range on the same chromosome, or NA if their position doesn't match in any range in the first dataset. Ideally I am looking for a dplyr solution as that is what I normally use, but my real data is also very large so any guidance that helps that would be appreciated.
Input data:
#df1
structure(list(chrom = c(1L, 1L, 5L),
    min = c(1000L, 20000L, 900L), max = c(1200L, 20100L, 1000L
    ), low = c(500L, 19500L, 400L), high = c(1700L, 20600L, 1500L
    )), row.names = c(NA, -3L), class = c("data.table", "data.frame"))

#df2

structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5"
), chrom = c(1L, 1L, 5L, 1L, 1L), position = c(1200L, 10000L,
500L, 560L, 20100L)), row.names = c(NA, -5L), class = c("data.table",
"data.frame"))

A: you could possibly run the calculation in parallel on multiple cores if that is an option... I am no expert on the topic though, anyhow the example below should work for a try (the main idea is to search for one matching range per iteration/run and bind positive matches to a list)
library(dplyr)
library(plyr)
library(parallel)

# start parallel backend with 4 cores (or how many threads you have)
cl <- parallel::makeCluster(mc <- getOption("cl.cores", 4))
# export the data to the
parallel::clusterExport(cl=cl, varlist=c("df1", "df2"))
# export packages
parallel::clusterEvalQ(cl, {library(dplyr)})
# set the lenght to one variable (could pass in the below function also)
l <- length(df1)
# run function on cluster
res <-parallel::parLapply(cl, 1:l, function(i){
  # select 1 range to match
  dfi <- df1[i, ]
  # full join all df2 with the only one range
  dfr <- dplyr::full_join(df2, dfi) %>%
    # Check if values are in the range and give corresponding gene and chromosome
    dplyr::mutate(GENE_COR = ifelse(position >= low & position <= high, Gene, NA),
                  CHROM_COR = ifelse(position >= low & position <= high, chrom, NA)) %>%
    # filter ever non match
    dplyr::filter(!is.na(GENE_COR))
  # return the info to puild list in parallel
  return(dfr)
})
# reduce result list build in parallel of only positive matches to a tibble
plyr::ldply(res, tibble)

  chrom  min  max low high  Gene position group GENE_COR CHROM_COR
1     1 1000 1200 500 1700 Gene1     1200     1    Gene1         1
2     5  900 1000 400 1500 Gene3      500     2    Gene3         5
3     5  900 1000 400 1500 Gene4      560     2    Gene4         5

Though parallelization is not always better - the dplyr solution is inside the function - just use the whole df2 instead of dfi
==================================================================
New answer:
# Build a group identifier
df1 <- df1 %>% dplyr::group_by(chrom) %>% dplyr::mutate(GROUP = dplyr::row_number(), GROUP2 = paste0(chrom, "_", dplyr::row_number())) %>% dplyr::ungroup()

df2 %>%
  dplyr::full_join(df1) %>%
  dplyr::mutate(CHROM_COR = ifelse(position >= low & position <= high, chrom, NA )) %>%
  dplyr::filter(!is.na(CHROM_COR))

    Gene chrom position   min   max   low  high GROUP GROUP2 CHROM_COR
1 Gene1     1     1200  1000  1200   500  1700     1    1_1         1
2 Gene3     5      500   900  1000   400  1500     1    5_1         5
3 Gene4     1      560  1000  1200   500  1700     1    1_1         1
4 Gene5     1    20100 20000 20100 19500 20600     2    1_2         1


text:
Q: Plotly: How to add extra information to marker of 3D scatter plot? What I'd like to do is adding each string info into only each balloon like below capture. But without showing them next to each plot because it looks messy when plots are many.

My data frame is below, I added info to each row as string.
import plotly.express as px
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.manifold import TSNE

digits = datasets.load_digits()

X_reduced = TSNE(n_components=3, random_state=0).fit_transform(digits.data)

myinfo = ['ID' + str(i+1) for i in range(X_reduced.shape[0])]
df = pd.DataFrame(data=X_reduced, columns=columns, dtype='float')

df['info'] = myinfo          ## <- This is what i want to show in a balloon.

print(df)

              a         b          c    info
0     18.150545 -1.938995   1.192057     ID1
1     -8.773806  2.475938 -10.885373     ID2
2      4.305762  5.132519  -7.347726     ID3
3      5.327038  7.438313   8.786077     ID4
4    -15.810744 -9.374986   0.310686     ID5
...         ...       ...        ...     ...
1792   1.192152 -0.850245  12.781646  ID1793
1793  14.183956 -3.544634  -1.009673  ID1794
1794  -0.907307  2.596647  -4.307703  ID1795
1795   1.608326  0.700724   9.267643  ID1796
1796   1.809730  5.428222  -1.771497  ID1797

What I tried is that I assigned the string info as text='info' of px.scatter_3d() as following code.
fig = px.scatter_3d(df, x='a', y='b', z='c', color='a', size_max=6 , text='info', opacity=0.7)

fig.show()

Does someone know how to get rid of these info beside plots?
Thank you in advance.

A: Using your setup, all you have to do is run:
fig.update_traces(mode = 'markers')

...or:
fig.for_each_trace(lambda t: t.update(mode = 'markers'))

This removes the strings associated with the markers, but retains the added information in the hoverlabel:

This approach lets you keep your call to px.scatter_3d(..., text='info') as it stands.
Another approach would be to edit the hoverinfo directly with a custom_value as described in the post Plotly 3D plot annotations


text:
Q: Scroll to the bottom of a div after an element as loaded? Similar to this question, I also have a page with a div that fills up with chat-style bubbles on click - each click makes one new "bubble" appear. They're all contained in a .content div that does not have a set height.
However, the page does not automatically scroll down if one of the bubbles loads below the height of the browser window, and I've had a couple people complain that they didn't know there was anymore content that was supposed to load.
As recommended in the question I posted, I've tried adding this script to the end of my page:
$(document).ready(function() {
    $(".content").click(function() {
            $(".content").animate({ scrollTop: $(".content")[0].scrollHeight}, 1000);
    });
});

but it doesn't seem to do anything at all... Am I missing something obvious?
I set up a jsfiddle too, taking out the effect of each bubble loading on click. The effect of scrolling down to the bottom of the div on click though doesn't seem to work either. I'm a super newbie and trying to figure this all out, so any help is greatly appreciated!! Thanks in advance

A: Check out my updates
$(document).ready(function() {
  $(".content").click(function() {
    $("html, body").animate({ scrollTop: $(".content")[0].scrollHeight}, 1000);
  });
});

JSFiddle


text:
Q: What is the Big-O performance of this algorithm and how do I solve this normally? Hello I have an algorithm that I am having trouble with finding the performance.
 i=math.ceil(n**0.5)
 while n % i != 0:
  i -= 2

Would this be O(2^n)?

A: I don't know what you are trying to do, but your current code will run give error cannot divide by zero for many cases for example for n=13, but if you do i-=1 in place of i-=2 then your code will work fine without any error for every n and complexity would be O(n^(1\2)).


text:
Q: ReferenceError: _ is not defined on an array .map() call I'm getting a "ReferenceError: _ is not defined" on a .map call like this:
arr.map(async (elem) => {
...
});

There doesn't appear to be any explicit mention of "_" anywhere here. When I look at the source of the error, I see:
eval
webpack-internal:///./src/components/admin/NameOfMyFile.tsx (115:51)
step
node_modules/tslib/tslib.es6.js (102:0)
Object.eval [as next]
node_modules/tslib/tslib.es6.js (83:45)
asyncGeneratorStep
node_modules/@swc/helpers/src/_async_to_generator.mjs (3:0)
_next
node_modules/@swc/helpers/src/_async_to_generator.mjs (25:0)
eval
node_modules/@swc/helpers/src/_async_to_generator.mjs (32:0)

The only lead I have here is that it seems to be trying to use something in tslib.es6.js but in my tsconfig.json, my "target" is "es5". Not really sure if this plays a role or just a red herring.
I'm on Next.js and this is done on the client side. (On the server side, it doesn't appear to have any problems)
Would love some help here if anyone has any ideas. Thanks!

A: if it helps, I had this problem too, and it was because I was nesting awaits, something like this:
const resp = await api(...., {
  headers: {
    Authorization: `Bearer ${await getToken()}`
  }
})

Moving the await getToken() outside like so:
const token = await getToken()
const resp = await api(...., {
  headers: {
    Authorization: `Bearer ${token}`
  }
})

That made the issue go away. I could have sworn I've done this nested await thing before, but I haven't had time so far to figure out what's going wrong.

A: tl;dr Try upgrading Next.js
I experienced something similar. This issue started happening today when I upgraded the caniuse-lite db (npx browserslist@latest --update-db).

(I do have a somewhat of an await within an await)
The app isn't on the latest Next.js version, so I upgraded and the issue went away.
Some notes:

*

*I upgraded Next.js from 12.3.0 to 12.3.4 so the fix is somewhere in patch 1, 2, 3 or 4

*If I revert to the previous version of "caniuse-lite" the issue goes away

*I couldn't find anything related on the Next.js GitHub (issues, nor discussions)


text:
Q: Relations; aRb if ab=k^2 Hi I am supposed to prove that R is an equivalence relation on N (natural number)
We define the relation R on N as aRb if $ab=k^2$ for some k that belongs to N.
I know that I should prove that the relation is reflexive, symmetric and transitive.
The relation is reflexive if aRa for some a that belongs to N.
a^2 is a natural number and therefore a^2 = k^2 and aRa.
The relation is symmetric if aRb then bRa for all a and b that belongs to N.
The relation is symmetric because if aRb then $ab=k^2$ for some k that belongs to Z. This is equivalent to $ba= k^2$ and therefore bRa.
I'm not sure about Transitive tho. I must prove that if aRb and bRc then aRc. How can I do that?

A: Hint. Try to prove transitivity when $a$ and $b$ are both powers of $2$. A few examples should show you how. Then think about the fundamental theorem of arithmetic.

A: Since you know that aRb and bRc, you can conclude that there are natural numbers $m$ and $n$ such that $ab=m^2$ and $bc=n^2$.  Your job is to prove that $ac$ is also the square of some natural number involving $m$ and $n$. (Hint: multiply those two equations together.)


text:
Q: Key as ng-model I have following code.
<select id="block-rule"
   class="form-control"
   name="rule"
   ng-model="forms.block.fields.rule">
      <option ng-repeat="(key, value) in rules" value="{{key}}">{{value}}</option>
</select>

I'm not really familiar with AngularJS, but I can see, that it should iterate "rules" (as specified in ng-repeat), and it works right.
Thing that don't work - default value is not selected. As I can see, value that should be selected initially is need to be passed to ng-model.
forms.block.fields.rule, I think, contains a value, but I need to get a key.
Unfortunately, it's the only part of code I can show.

A: <select ng-options="key as value for (key,value) in rules" ng-model="forms.block.fields.rule">

DEMO FIDDLE

A: You can use ng-options but it may require you to change your rule model slightly (add a name property):
<select id="block-rule"
                        class="form-control"
                        name="rule"
                        ng-    model="forms.block.fields.rule"
                        ng-options="rule as rule.name for rule in rules"
                >
 </select>


text:
Q: Dotted lines there on every indent in VS 2010 I am seeing dotted lines in my C# code in VS 2010. Dotted lines appear in every indent. This really bothers me. I must have typed some shortcut key but I'm not able to revert it back.
How can I disable it? What is the use of the dotted lines anyway?

A: Sounds like "view whitespace" is turned on.  Under VS2010 you find it under:
Edit->Advanced->View

A: the 'dotted lines' are part of the editors way of showing you where the indentation levels begin. this is a very useful feature as it allows you to quickly scan longer code sections to see which logic branch that code belongs to.
to change this:
Edit->Advanced->View White Space (CTRL+E,S)

A: You can disable and enable it from the main menu using Edit->Advanced->View White Space. It just shows all the white spaces in the solution. It means that all the tabs also will be drawn by the arrows