text:
Q: SQL server compress backup for lower version databases Recently our development team migrated couple of sql server 2000 Databases onto SQL2K8R2.
Now we creating the backup strategy, and just had a doubt, that:
1) Compatibility level  of those DB's still show 80, we asked the team if that can be changed to current , they had no clue. I searched on web, but could not find any such stuff which clarifies on what point should we or should we not change the compatibility level of the migrated db's.
2) For  the Migrated DB's having compatibly 80, are we good to take compressed backups? I am just curious because if we try to restore on the same or upper version , it might not have any conflict.?
Please advice, thanks!

A:
I searched on web, but could not find any such stuff which clarifies on what point should we or should we not change the compatibility level of the migrated db's.

As a good practice and suggested by Microsoft you should change compatibility level of database to match with server version on which it is hosted. There are few legacy applications which might require version as 80 for that you have to test, I cannot tell upfront whether you change it or not. You should see what all features were deprecated in 2008 R2 as compared to SQL Server 2000 below two articles would help you
Breaking Changes to DB feature in SQL server 2008 R2
Deprecated database engine features in SQL Server 2008 R2
Deprecated SQL Server features in SQL Server 2008 R2
Regarding changing compatibility level if you face any issue you can immediately change it back to 80, that is why i said a round of testing is required. If you read Change compatibility Level of database it would really help you

For the Migrated DB's having compatibly 80, are we good to take compressed backups?

Yes you can take compressed backup of 80 compatibility database hosted on SQL Server 2008 R2 subject to condition SQL Server edition is Standard or higher edition


text:
Q: Installing Homebrew on Macbook running El Capitan When I run this command:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

I get the following error:
It appears Homebrew is already installed. If your intent is to reinstall you
should do the following before running this installer again:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
The current contents of /usr/local are bin CODEOFCONDUCT.md git include lib libexec Library LICENSE.txt n share var .git .github .gitignore

However, when I run brew doctor, this error is thrown:
bash: brew: command not found

And when I try to un-install Homebrew using this script:
sudo  ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

my command prompt responds with:
Failed to locate Homebrew!

Please help.

A: First delete all homebrew files manually. Then reinstall Homebrew from scratch. Prefix sudo at your own discretion:
# packages
rm -rf /usr/local/Cellar

# executable
rm /usr/local/bin/brew

# meta
rm -rf /usr/local/.git
rm /usr/local/.github
rm /usr/local/.gitignore
rm /usr/local/.travis.yml
rm /usr/local/.yardopts
rm /usr/local/CODEOFCONDUCT.md
rm /usr/local/LICENSE.txt
rm /usr/local/README.md

# home
rm ~/.rvm/bin/brew
rm ~/.homebrew
rm -rf ~/Library/Caches/Homebrew
rm -rf ~/Library/Logs/Homebrew

# other
rm -rf /Library/Caches/Homebrew

# find more files to delete; delete Homebrew files only!
find / -name "*brew*"

IMPORTANT: because of permission errors upon reinstall, you may have to do one of the following steps before reinstallation; see: https://github.com/Homebrew/legacy-homebrew/issues/15138
# via: https://github.com/Homebrew/legacy-homebrew/issues/15138#issuecomment-19258042
cd /usr/local
sudo mv -v Library Library.old

# --OR--

# via: https://github.com/Homebrew/legacy-homebrew/issues/15138#issuecomment-33338868
# see: http://linuxcommand.org/man_pages/chmod1.html
cd /usr/local
chmod -R 775 Library

Reinstall Homebrew; see: http://brew.sh
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

A: There is a problem related to the latest version of XCode and Homebrew. Open a terminal and run:
rm -rf /usr/local/Cellar /usr/local/.git
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

If you get permission denied error use sudo. Directory /usr/local/Cellar/ is completely removed when uninstalling Homebrew, so it is safe to remove it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I install gnucap or octave? I have tried to install gnucap (I downloaded it from the website http://ftp.gnu.org/gnu/gnucap/  with the extension .tar.gz) in the Ubuntu live-usb. I have tried to do it in the terminal with:
sudo apt-get install gnucap

But the problem is that it always tell me :

E:Unable to Locate Package

Could someone tell me what should I do to install the software?

A: The way to install a file *.tar.gz is first decompress it with tar -zxvf file.tar.gz and then running the binary file or installing with, ./configure; make install.
Octave is in the Ubuntu universe and can be installed with synaptic or apt-get. The package name is "octave".

A: If you're on a LiveCD you need to sudo apt-get update first, then try your install command.
Try that and then please update your question with the results.


text:
Q: Replace search prmNames Looking at documentation I didn't find any way to change prmNames of search, is that possible?
I want to replace "searchField", "searchString", "searchOper".
I tried here http://www.trirand.com/jqgridwiki/doku.php?id=wiki:singe_searching and here http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options but couldn't find any answer

A: You can use sField, sOper and sValue parameters of (the parameter sFilter can be used in case of advanced searching) to change the default values of the values by changing the $.jgrid.search. For example
$.extend($.jgrid.search, {sField: 'field', sOper: 'oper', sValue: 'value'});


text:
Q: Annotate based on calculation in ManyToManyField I am trying to annotate a Django model by calculating a non-trivial expression using a property of a ManyToManyField in the model.
The situation can be translated into the following simple example structure of "payments" that should be split between a number of "companies" according to their relative sizes. Which companies participate in a given payment is stored as a ManyToManyField:
class Company:
  relative_size = models.DecimalField()   ## can be assumed to add up to 1 among all companies

class Payment(models.Model):
  companies = models.ManyToManyField(Company, related_name='payments', blank=True)
  amount = models.DecimalField()

I'm now trying to query for the total amount that each company participated in. If the share was the same in each of the payments, this would be as simple as
companies = Company.objects.annotate(total_payments=Sum(F('payments__amount')*F('relative_size')))
for company in companies:
  print("Company %s: %s" (str(company), total_payments))

But how to do this in the case where I have to calculate the correct fraction for every payment based on which companies participated? I suspect I have to use Subquery but couldn't really adapt the examples in the documentation to my case.
PS: As a workaround I have implemented this in "Python" instead of in queries as follows:
payments_annotated = Payment.objects.annotate(sum_involved_companies_sizes=Sum(F('companies__relative_size')))
companies = Company.objects.all()
for c in companies:
  c.sum = Decimal('0.0')
  for p in payments_annotated.filter(companies__id=c.id):
    c.sum += p.amount * c.relative_size/p.sum_involved_companies_sizes

But I guess this must be possible and more efficient within the queries system, so I'm hoping an expert can help out? Thanks!


text:
Q: Nontrivial critical exponents in exactly solvable models? Are there any exactly solvable models in statistical mechanics that are known to have critical exponents different from those in mean-field theory, apart from the two-dimensional Ising model? I wonder about this because most easily solved models are either mean-field or do not exhibit a phase transition (Ising chain).

A: Yes, take e.g. the 6 and 8 vertex models. Mean field theory will typically fail in 2d models and so far we only have exactly solvable models for 2d systems. The book by Rodney Baxter that can be downloaded free of charge here, is compulsory literature for every student in this field.

A: If you want to expand your search to all critical exponents, I would recommend the following article:
Géza Ódor, Universality classes in nonequilibrium lattice systems, REVIEWS OF MODERN PHYSICS, VOLUME 76, JULY 2004
This contains lots of different systems that can be (are) modeled with lattices (e.g. Ising, percolation and interface growth). The contents list is actually pretty good starting point for simple listed classification. Some of them are exactly solvable, however most are not (try searching the word 'exactly' in the document).
URL: http://link.aps.org/doi/10.1103/RevModPhys.76.663
DOI: 10.1103/RevModPhys.76.663
There is more on this topic in this question: Where can I find a good classification for phase transitions?


text:
Q: Sawfish and fvwm bindings not working when logging in with a display manager On one machine running Debian squeeze, when I log in with a display manager (I tried xdm, gdm or kdm), none of my Sawfish key or mouse bindings have any effect. If I log in in text mode then run startx, everything works fine.
If I try fvwm, most bindings don't work either, but some mouse bindings do.
When I log in with a display manager, I execute a custom session that loads my ~/.xsession. That file is essentially . ~/.profile; . ~/.xinitrc, so my session should be exactly the same in both cases (same environment variables, same programs, etc.).
What is causing Sawfish and Fvwm not to recognize my bindings? How is using a display manager different from running startx? How can I make my bindings work?

A: I know what is ailing Sawfish, and how to fix it, but not why using a display manager causes this behavior.
My personal keyboard layout has no Num Lock key, and does not assign any key to the modifier Mod2. Sawfish ignores the modifier assigned to Num Lock when it starts. If no key is assigned to a modifier, Sawfish does not ignore it, so a binding for key is not triggered when Mod2 is on (there would have to be a binding for ).
Fvwm behaves similarly. There's an additional subtlety that bindings with A in the modifiers column work all the time, regardless of whether Mod2 is on; it's only the bindings with explicit modifiers set that don't work.
For some reason that I haven't figured out, when I log in with a display manager, the Num Lock modifier is recorded as on (even though it is off while I'm typing my user name and password, and the Num Lock LED on the keyboard is off). This causes Fvwm and Sawfish to receive Mod2+key keyboard events rather than the key that has a command bound to it.
Since I'm not using Mod2, I can fix this by turning off Num Lock in my .xsession:
python -c 'from ctypes import *
X11 = cdll.LoadLibrary("libX11.so.6")
display = X11.XOpenDisplay(None)
X11.XkbLockModifiers(display, c_uint(0x0100), c_uint(16), c_uint(0))
X11.XCloseDisplay(display)'

or completely disable Mod2 with
xkbset nullify mod2


text:
Q: Как сверстать облако тегов на css? Сейчас готов кусок html и css к нему, но верстка не соответствует макету и непонятно, как сделать hover при наведении и всплывающую подсказку над тегом.

.tags {
  padding: 80px;
  width: 380px;
  /* Style for "jQuery" */
  color: #ffffff;
  font-family: Roboto;
  font-size: 17px;
  font-weight: 300;
  line-height: 40px;
}

.tags a {
  white-space: nowrap;
  /* Style for "Rounded Re" */
  width: auto;
  border-radius: 13px;
  background-color: #090a0b;
  padding: 5px 10px 5px 10px;
  text-decoration: none;
  color: #ffffff;
}

  Супер тег
  Еще один тег
  И еще тег
  Классный тег
  Вот тег последний

При этом на выходе должно получится облако тегов с возможностью раскрыть его и при наведении hover с подсказкой https://yadi.sk/i/t7ATcCq23SqXoq

A: ну вот как вариант

body {
  background: #1e2429;
}
.tags {
  padding: 80px;
  width: 380px;
  /* Style for "jQuery" */
  color: #ffffff;
  font-family: Roboto;
  font-size: 17px;
  font-weight: 300;
  line-height: 40px;
}

.tags a {
  white-space: nowrap;
  /* Style for "Rounded Re" */
  width: auto;
  border-radius: 13px;
  background-color: #090a0b;
  padding: 5px 10px 5px 10px;
  text-decoration: none;
  color: #ffffff;

  position: relative; /* для подсказки */
}

/* это нужно, если есть необходимость что бы можно было навести курсор на подсказку. Иначе будет исчезать */
.tags a:after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  bottom: 100%;
  height: 20px;
  visibility: hidden;
}
.tags a:hover:after {
  visibility: visible;
}
.tags a:hover {
  background: #eb1f63;
}

/* оформление плашки */
.tags__hide {
  position: absolute;
  left: 50%;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  color: #000;
  background: #fff;
  padding: 5px 10px;
  line-height: 1;
  transition: all .3s;

  /* параметры для изчезновения/появления. Можете настроить как вам угодно */
  visibility: hidden;
  opacity: 0;
  bottom: 0;
}
.tags a:hover .tags__hide {
  visibility: visible;
  opacity: 1;
  bottom: calc(100% + 15px);
}
/* треугольник */
.tags__hide:before {
  content: '';
  width: 10px;
  height: 10px;
  background: #fff;
  position: absolute;
  bottom: -5px;
  left: 50%;
  margin-left: -5px;
  transform: rotate(45deg)
}

    Супер тег
    text hide

  Еще один тег
  И еще тег
  Классный тег
  Вот тег последний

A: Пример

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.tags-list {
  padding: 20px;
  margin: 25px 0;
}

.tags-list>li {
  display: inline-block;
  vertical-align: top;
  margin-right: 5px;
  margin-bottom: 5px;
}

.tags-list>li>a {
  position: relative;
  display: block;
  padding: 10px 15px;
  background: #000;
  color: #fff;
  border-radius: 15px;
}

.tags-list>li>a:hover {
  background: #f00;
}

.tags-list>li>a[data-tooltip]:before {
  position: absolute;
  left: 50%;
  top: -100%;
  background: #ccc;
  color: #000;
  height: 30px;
  line-height: 30px;
  padding: 0 15px;
  content: attr(data-tooltip);
  white-space: nowrap;
  transform: translateX(-50%);
}

.tags-list>li>a[data-tooltip]:after {
  position: absolute;
  left: 50%;
  top: -10px;
  margin-left: -7px;
  border-top: 7px solid #ccc;
  border-left: 7px solid transparent;
  border-right: 7px solid transparent;
  content: "";
}

.tags-list>li>a[data-tooltip]:before,
.tags-list>li>a[data-tooltip]:after {
  pointer-events: none;
  visibility: hidden;
  opacity: 0;
  transition: all .3s ease;
}

.tags-list>li>a[data-tooltip]:hover:after,
.tags-list>li>a[data-tooltip]:hover:before {
  visibility: visible;
  opacity: 1;
}

Супер тег

Супер тег

Супер тег

Супер тег

Супер тег

Супер тег

Супер тег

Супер тег

Супер тег

A: Можно попробовать добавить псевдоэлемент ::before и скрыть его display: none;, а при наведении display: block;, скачать иконочный шрифт в виде всплывающего облака, но не уверен, надо проверять.
При наведении:
.tags a:hover {
    background: linear-gradient(to top right, #f5755a, #f136ef);
}


text:
Q: Accessing Hive, HDFS from mapr in local Spark I have just installed the mapr 5.1 sandbox virtual machine running in virtualbox, in mode Bridge mode. What I am trying to do is accessing Hive and HDFS from a local Spark(same operation I did it with the HDP 2.4 sandbox) but without success.
I have installed a MapR Client on my machine (using the command hadoop fs -ls I can reach a hdfs url).
I also have a java/scala project with a main application that I tried to run it but gives me the following error:

Failed on local exception: java.io.IOException: An existing connection
  was forcibly closed by the remote host; Host Details : local host is:
  "DESKTOP-J9DMAUG/192.168.1.133"; destination host is: "maprdemo":7222

Here are the details about the project:
pom.xml
<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <encoding>UTF-8</encoding>
    <scala.tools.version>2.10</scala.tools.version>
    <scala.version>2.10.4</scala.version>
    <spark.version>1.4.1</spark.version>
</properties>
 <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-library</artifactId>
        <version>${scala.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_${scala.tools.version}</artifactId>
        <version>${spark.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_${scala.tools.version}</artifactId>
        <version>${spark.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-hive_${scala.tools.version}</artifactId>
        <version>${spark.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-hdfs</artifactId>
        <version>2.7.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.7.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-core</artifactId>
        <version>1.2.1</version>
    </dependency>

The main class:
    object MainApp {

  def main(args: Array[String]) {
    val conf = new SparkConf()
      .setAppName("SampleSparkApp")
      .setMaster("local[*]")

    val sc = new SparkContext(conf)
    val rdd = sc.textFile("/user/mapr/aas/sample.txt")
    println(s"count is: ${rdd.count()}")
    rdd.foreach(println(_))

    val sqlContext = new HiveContext(sc)

    val df = sqlContext.sql("select * from default.agg_w_cause_f_cdr_datamart_fac")
    df.show(10)
    sc.stop()
  }
}

On the classpath, as resources I also have core-site.xml and hive-site.xml
core-site.xml
<configuration>
<property>
    <!--<name>fs.defaultFS</name>-->
    <name>fs.defaultFS</name>
    <value>hdfs://maprdemo:7222</value>
</property>
<property>
    <name>fs.hdfs.impl</name>
    <value>org.apache.hadoop.hdfs.DistributedFileSystem</value>
</property>

hive-site.xml
<configuration>
<property>
    <name>hive.metastore.uris</name>
    <value>thrift://maprdemo:9083</value>
</property>

If you need any other details please let me know.
Worth mentioning that submitting the same code, as jar, using the spark-submit command on the mapr machine runs ok.


text:
Q: How to unmount flash drive gparted says busy I have a 4GB usb storage drive that I cannot save files to. I have copied the information I want from it, so now I would like to rescue is as a freshly formatted drive, if that is possible. There is no read-only lock switch on this device.
This is what happens:
[root@localhost]/home/Harry# cd /run/media/Harry/2030-0761
[root@localhost]/run/media/Harry/2030-0761# ls -l
ls: cannot access iambic11: Input/output error
total 40
drwx------ 35 Harry Harry 8192 Sep 16 16:46 arduinos
drwx------  5 Harry Harry 4096 Sep 16  2013 cranksmall
drwx------  2 Harry Harry 4096 Sep 18 13:08 iambic10
d?????????  ? ?     ?        ?            ? iambic11
drwx------  4 Harry Harry 4096 Sep 15  2013 Phasor1
drwx------  5 Harry Harry 4096 Sep 15  2013 Phasor2
drwx------  3 Harry Harry 4096 Sep 16 16:44 readfromarduino04
drwx------  3 Harry Harry 4096 Sep 19 18:18 readfromarduino07
drwx------  5 Harry Harry 4096 Aug  1  2013 SWR
drwx------  5 Harry Harry 4096 Sep 15  2013 SwrWinExe
[root@localhost]/run/media/Harry/2030-0761# rm iambic11
rm: cannot remove 'iambic11': Read-only file system
[root@localhost]/run/media/Harry/2030-0761# chmod 777 iambic11
chmod: cannot access 'iambic11': Input/output error
[root@localhost]/run/media/Harry/2030-0761#

gparted shows this drive but says it cannot be unmounted, and still shows the same even after:
[Harry@localhost]~% fuser -k /run/media/Harry/2030-0761
[Harry@localhost]~%

I am floundering in areas that are seldom visited by me, please can anyone help?

A: Try sudo umount -v /run/media/Harry/2030-0761.  If it says "device busy", try lsof /run/media/Harry/2030-0761; this will show applications that have something in the filesystem open.  It will likely be shells and file browsers.  Check those and navigate out of the filesystem and try umount again.
If that doesn't work, since you've said you intended to reformat this anyway, just pull it out, disable automounting, put it back in again and do what you want.


text:
Q: Trigger not saving due to incorrect method signature Everything is perfect . Just a short code with few lines . But still the trigger is not saving . It works in other ORGs but not in my Developer Edition ORG . Please help me with it.

Task Trigger:

trigger taskTrigger on Task (before insert, after insert, after update, before update, before delete, after delete) {

   TaskHandler.checkOwner(Trigger.old);

}

Task Handler:

public class TaskHandler {

   public static void checkOwner(List<Task> triggeredTaskRecord){

       System.debug('This is a Task trigger');

   }

}

I even tried with sharing , tried non static methods but still the problem exists . Don't know what to do


text:
Q: Ошибка ESlint (TypeError: this.cliEngineCtor is not a constructor) скачал create-react-app с оф. репозитория, открыл проект в VSCode, запустил, ошибок линтера нет, но в PhpStorm 2020.2.4 запустил - работает, но выдает ошибку, скрины приложил, никаких изменений кроме App.js не делал

A: ESLint@8.x поддерживается начиная с версии 2021.2.2, см. WEB-52236. Попробуйте обновить PHPStorm


text:
Q: Efficiently read and validate csv file in python I've multiple csv files (<10 G) and I need to validate files one by one in an memory efficient way. my validations include
1-> file in properly delimited
2-> validate certain columns, as integers/decimals
3-> validate date format (eg. yyyy/MM/dd) for certain columns.
currently I'm using
with open(file_name, 'r') as myCSV:
        CSVreader = csv.reader(myCSV)
        for row in CSVreader:
                my_logic

and looping each row and validating conditions per row. is there any better libraries/methods available? I've heard about pandas don't know if it is memory efficient.

A: I had some similar loop that took forever using pandas and was able to speed it up quite a bit by using this trick:
for row in dataframe:
    some logic over row.col1, row.col2, etc...

becomes:
for (col1, col2, ...) in zip(dataframe.col1.values, dataframe.col2.values, ...):
    some logic over col1, col2, etc...

not sure how it goes with memory, but was able to handle pretty big files using a 64bit version of python.


text:
Q: Get the max value from a slice of a JSON Array? I would like to get the max value within a slice of a Json object (typicaly [1,2,3,5,6,7,9,10]) which is contained in a field named Data of the table raw.
The limits Start & End of the slice are contained in an other Json object named Features contained in a table named features
Here is the input:
CREATE TABLE raw (
    id     int PRIMARY KEY
      GENERATED BY DEFAULT AS IDENTITY

    data   json
);

INSERT INTO raw (data) VALUES
  ('[1,2,3,5,6,7,9,10]');

CREATE TABLE features (
    id         int,
    features   json
);

INSERT INTO features (id, features) VALUES
  (1, '{"Start" : 1, "End": 5}');

The output I would like is 7, i.e. the max value of the slice [2,3,5,6,7]
Here is what I came up with looking at other posts, but it does not work...
SELECT
    R."ID",
    F."Features"->>'Start' AS Start,
    F."Features"->>'End' AS End,
    sort_desc((array(select json_array_elements(R."Data")))[F."Features"->>'Start':F."Features"->>'End'])[1] as maxData
FROM
    raw AS R
INNER JOIN
    features AS F ON R."ID" = F."ID"

The approximate error message I get is concerning sort_desc :

No function corresponding to this name or this type of arguments. You
  should convert the type of data

A: You can unnest json array:
Postgres WITH ORDINALITY:

When a function in the FROM clause is suffixed by WITH ORDINALITY, a bigint column is appended to the output which starts from 1 and increments by 1 for each row of the function's output. This is most useful in the case of set returning functions such as unnest().

Have a look at this answer of Erwin Brandstetter:

*

*PostgreSQL unnest() with element number
  SELECT
     r."ID",
     MAX(t.elem::int) MaxElem
  FROM
      raw r
  JOIN
      features f
      ON f."ID" = r."ID"
  JOIN LATERAL
      json_array_elements_text(r."Data")
      WITH ORDINALITY AS t(elem, n) ON TRUE
  WHERE
      n >= (f."Features"->>'Start')::int + 1
      AND
      n <= (f."Features"->>'End')::int + 1
  GROUP BY
      r."ID";

ID | maxelem
-: | ------:
 1 |       7

db<>fiddle here
Or if you prefer to use intarray module:
SELECT
    r."ID",
    (sort_desc(((ARRAY(SELECT json_array_elements_text(r."Data")))::int[])[(f."Features"->>'Start')::int + 1:(f."Features"->>'End')::int + 1]))[1]
FROM
    raw r
JOIN
    features f
    ON f."ID" = r."ID";

rextester here

A: This is all around a horrible schema. You shouldn't be using json (as compared with jsonb) at all, ever (practically). If you're querying on the field, it should be jsonb. In your case, that's still a bad idea though, you likely want an sql array..
CREATE TABLE raw (
    raw_id   int  PRIMARY KEY
      GENERATED BY DEFAULT AS IDENTITY,
    data     int[]
);

INSERT INTO raw (data) VALUES ('{1,2,3,5,6,7,9,10}');

CREATE TABLE features (
    feature_id   int REFERENCES raw,
    low          smallint,
    high         smallint
);

INSERT INTO features ( feature_id, low, high ) VALUES ( 1, 1, 5 );

Now you can query it like this, note remember sql is 1-based,
SELECT max(unnest)
FROM raw
CROSS JOIN features AS f
CROSS JOIN LATERAL unnest(data[f.low:f.high]);

Also check out the intarray module, because it'll optimize the above,
CREATE EXTENSION intarray;

SELECT max(unnest)
FROM raw
CROSS JOIN features AS f
CROSS JOIN LATERAL unnest(subarray(data,f.low,f.high-f.low+1))

You can further optimize this if you know you just need the last element of the array.

Note if this is a GIS problem, you're still probably doing it wrong, but at least this method is sane.


text:
Q: How can I get the income details from the below xml for each employer tag? I've been trying to parse an XML file(I've pasted the minimal reproducible code below) and get the values of Year and income fields for all the income tags for every employer code. Please see the following output so that you can understand me better
What I'm trying to get:
{"1234": [["2006", "12085"], ["2005","23071"], ["2004","21364"]],
"5678" : [["2015", "12345"],["2014", "13071"]]}

I've been trying and meddling with the file in so many ways using elementtree and/or beautifulsoup to finally print only this:
What I actually got:
[["2006", "12085"], ["2005","23071"], ["2004",["2015", "12345"],["2014", "13071"]]

I'm unable to group them based on their employer code.
PS: I'm a newbie to posting questions at Stackoverflow. I hope I meet all the community guidelines.
This is XML that is eating my brain:
<DETAILS>
    <RESPONSE>
        <EMPLOYER>
            <EMPLOYERCODE>1234</EMPLOYERCODE>
            <NAME1>ABC Service Corporation</NAME1>
        </EMPLOYER>
        <INCOME>
            <YEAR>2006</YEAR>
            <TOTAL>12085</TOTAL>
        </INCOME>
        <INCOME>
            <YEAR>2005</YEAR>
            <TOTAL>23071</TOTAL>
        </INCOME>
        <INCOME>
            <YEAR>2004</YEAR>
            <TOTAL>21364</TOTAL>
        </INCOME>
        <ID>18700763721</ID>
    </RESPONSE>
    <RESPONSE>
        <EMPLOYER>
            <EMPLOYERCODE>5678</EMPLOYERCODE>
            <NAME1>DEF Service Corporation</NAME1>
        </EMPLOYER>
        <INCOME>
            <YEAR>2015</YEAR>
            <TOTAL>12345</TOTAL>
        </INCOME>
        <INCOME>
            <YEAR>2014</YEAR>
            <TOTAL>13071.73</TOTAL>
        </INCOME>
        <ID>18700763721</ID>
    </RESPONSE>
</DETAILS>

A: Iterate over the responses first, because they contain both employer code and the income statements. Then it's just connecting employers to their incomes.
xml = '''
<DETAILS>
    <RESPONSE>
        <EMPLOYER>
            <EMPLOYERCODE>1234</EMPLOYERCODE>
            <NAME1>ABC Service Corporation</NAME1>
        </EMPLOYER>
        <INCOME>
            <YEAR>2006</YEAR>
            <TOTAL>12085</TOTAL>
        </INCOME>
        ...
    </RESPONSE>
    <RESPONSE>
        ...
    </RESPONSE>
</DETAILS>
'''
soup = BeautifulSoup(xml, 'html.parser')
employers = {}
for res in soup.select('response'):
    emp_code = res.select_one('employercode').text
    incomes = []
    for income in res.select('income'):
        year = income.select_one('year').text
        total = income.select_one('total').text
        incomes.append([year, total])
    employers[emp_code] = incomes

print(employers)

output:
{'1234': [['2006', '12085'], ['2005', '23071'], ['2004', '21364']], '5678': [['2015', '12345'], ['2014', '13071.73']]}

A: This is the elementtree version of this problem
import xml.etree.ElementTree as ET
tree = ET.parse('_filename_.xml')
root = tree.getroot()
dic ={}
for child in root:
    for schild in child:
        if schild.tag=='EMPLOYER':
            emp=schild[0].text
            dic[emp]=[]
        if schild.tag=='INCOME':
            arr=[]
            arr.append(schild[0].text)
            arr.append(schild[1].text)
            if emp not in dic:
                dic[emp]=arr
            else:
                dic[emp].append(arr)
print(dic)

output:
{'1234': [['2006', '12085'], ['2005', '23071'], ['2004', '21364']], '5678': [['2015', '12345'], ['2014', '13071.73']]}

A: You can utilize dict comprehension and BeautifulSoup'get_text()method and then split` data. This results in very short code:
data = '''<DETAILS>
... your data ...
</DETAILS>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'html.parser')
data = {response.select_one('employercode').text: [i.get_text(strip=True, separator='|').split('|') for i in response.select('income')] for response in soup.select('response')}

from pprint import pprint
pprint(data)

Prints:
{'1234': [['2006', '12085'], ['2005', '23071'], ['2004', '21364']],
 '5678': [['2015', '12345'], ['2014', '13071.73']]}


text:
Q: Php Header linking to different links depending on page I recently changed my bilingual website of 23 html pages to 23 php pages (The site is: www.creativemindspcs.org.) With this change, I included php headers, footers, and navigation.
I cannot figure out how to change the header links based on what page I am on.
Example. The About Us page in English. In the header, I have a link that says "Espanol". When you click on that link, it should take you to the About Us Spanish page but now since the php header is included on all of the pages, it only links to one page and not the correct one.
How do I change those links depending on what page it needs to go to? Anyone have a good tutorial?
HTML Code:
<insert php code here> include('includes/header.php');

Includes Header Code:

English

Español

Contact Us

        <form id="main-search" action="search.php"  >

        <input type="text" name="search"  style="background-color:#CCCCCC" >

        </form>

Donate  Apply

A: So the approach to bilingual pages is normally to store a hash of the different pieces of the site in different languages and then serve up the same template page. But in your case it looks like you have gone in a different but similar direction utilizing links. I'd say take a look here for starters https://stackoverflow.com/questions/1228018/php-multilingual-site

A: You can use PHP $_SERVER['variable_name']
Check the array variables here: http://br2.php.net/manual/en/reserved.variables.server.php
I would probably use $_SERVER['SCRIPT_FILENAME'], $_SERVER['PHP_SELF'] or $_SERVER['REQUEST_URI'].
You can see the possible results adding this on your included header to check the variable:
echo "
";
print_r($_SERVER);
echo "
";

So, your link could be something like:
<a href="<?php $_SERVER['REQUEST_URI']; ?>spanish.html">

A: Assuming you are using Apache, I would suggest using mod_rewrite to rewrite your URLs. So for example, when the user accesses the page esp-content.html the URL will be rewritten to content.html?lang=esp. Then just include the language code in all your links:
$lang = (isset($_GET['lang'])) ? urlencode($_GET['lang']) . '-' : null;
echo '';


text:
Q: Is this a valid proof of the Area of a Circle, assuming we do not already know $\pi$? In my AP Calculus class my friend and I decided we wanted to prove the area of a circle, without knowing $\pi$ to begin with. My friend and I each did it a different way. My method was to split the circle into a bunch of sectors, then find the area of each sector and multiply by the number of sectors to approximate the area of a circle. Here is what I came up with:
$f(r, n) = \frac{r^2 n \sin(\frac{180}{n})}{\sin(90 - \frac{180}{n})}$
With $r$ being the radius, and $n$ being the number of sides.
Then I rewrote it as
$f(r, n) =  \lim \limits_{n \to \infty} r^2  \frac{ n \sin(\frac{180}{n})}{\sin(90 - \frac{180}{n})}$
or
$f(r) =  r^2 \pi$
I have tested this many times and found it to work for finding the area of a circle. My question: Is my logic sound? Does this work without knowing $\pi$ beforehand?

A: The $180$ in your answer is really $\pi$ in disguise. The most natural definition of the sine function ends up using radian measure. Computing the sine in degrees then involves scaling by $\frac{\pi}{180}$. That is how your calculator is computing the sine (unless it is using lookup tables, which I highly doubt a modern calculator would be doing). In radians your limit becomes
$$\lim_{n\to\infty}{r^2\frac{n\sin{\frac{\pi}n}}{\sin{(\frac{\pi}2-\frac{\pi}{n})}}}$$
The denominator actually is not needed as it approaches $1$. So really the statement is that
$$\pi=\lim_{n\to\infty}{n\sin{\frac{\pi}{n}}}$$
This follows from the fact that
$$\lim_{x\to 0}{\frac{\sin{x}}{x}}=1$$
in radians.
In any case, if the question is whether your formula is correct, the answer is yes, and if there were some way of exactly calculating sine in degrees without knowing the value of $\pi$, then you wouldn't have to know the value of $\pi$. But I know of no such way.


text:
Q: reading a line in text file twice I have this text sample
Ahmed 10
kmal 5
doola 6

And I am using this code to read it
if (myfile.is_open())
{
  while ( myfile.good() )
{

    myfile >> name;
    myfile >> phone;
    cout << name <<" "<<phone<<endl;

}
myfile.close();

}
I get this output
Ahmed 10
kmal 5
doola 6
doola 6

Why does this code read the last line twice ?

A: myfile.good() becomes false AFTER the read fails.  Same with myfile.eof().
What you want is basically:
myfile >> name;
myfile >> phone;
if (!myfile.good()) break;

And this can be shortened to:
if (!(myfile >> name >> phone)) break;

or finally:
while (myfile >> name >> phone) { ... }

A: Try
while( myfile >> name >> phone ) {
    // your code here
}

I believe the problem with the other approach is that eof isn't signaled until you actually try to read more than you should. That is, when you attempt to myfile >> name on the last round. That fails, as does myfile >> phone and only then do you break out of the loop.

A: Don't use while(myfile.good()). It will still say true, even when you have read the last line in your file. And then the next >> will fail, leaving the name and phone variables unchanged from the last input. Use this instead: while(myfile >> name >> phone) {...}

A: iostream status is not predictive.  It reports the results of the
previous operation, not of the next (which would be impossible to
implement anyway).  And myfile.good() isn't even a reliable indicator
of the results of the previous operation: if the operation failed, it
will be false, but if the operation succeeded, it's not necessarily
true.  Forget that function.
Use the fact that the stream can act as a boolean to test success of the
previous operation.  Once you have failure, you can then use eof(),
and bad() to determine why (but with regards to eof(), only after
failure---eof() may return true even if the previous operation
succeeded).  Thus:
while ( myfile >> name >> phone ) {
    //  ...
}
if ( myfile.bad() ) {
    std::cerr << "Hardware read error" << std::endl;
} else if ( !myfile.eof() ) {
    std::cerr << "Format error in file" << std::endl;
}


text:
Q: OpenCV FindContours Causes stop working I'm using OpenCV 2.4.9 on VisualStudio V10.0.30319.1 RTMRel trying to compile this sample code:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;
using namespace std;

Mat src; Mat src_gray;
int thresh = 100;
  int max_thresh = 255;
  RNG rng(12345);

  /// Function header
  void thresh_callback(int, void* );

  /** @function main */
  int main( int argc, char** argv )
  {
    /// Load source image and convert it to gray
   VideoCapture capture;
    capture.open(0);
capture.set(CV_CAP_PROP_FRAME_WIDTH,1280);
capture.set(CV_CAP_PROP_FRAME_HEIGHT,960);
char qq=0;
while(qq!=32)
{
    qq = waitKey(30);
    capture.read(src);
    if(!src.empty())
    imshow("Space",src);
}
 /// Convert image to gray and blur it
 cvtColor( src, src_gray, CV_BGR2GRAY );
 blur( src_gray, src_gray, Size(3,3) );

 /// Create Window
 char* source_window = "Source";
 namedWindow( source_window, CV_WINDOW_AUTOSIZE );
 imshow( source_window, src );

 createTrackbar( " Canny thresh:", "Source", &thresh, max_thresh, thresh_callback );
 thresh_callback( 0, 0 );

 waitKey(0);
 return(0);
  }

  /** @function thresh_callback */
  void thresh_callback(int, void* )
  {
 Mat canny_output;
 vector<vector<Point> > contours;
 vector<Vec4i> hierarchy;

 /// Detect edges using canny
 Canny( src_gray, canny_output, thresh, thresh*2, 3 );
 /// Find contours
 findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

 /// Draw contours
 Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
 for( int i = 0; i< contours.size(); i++ )
    {
      Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
      drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() );
    }

 /// Show in a window
 namedWindow( "Contours", CV_WINDOW_AUTOSIZE );
 imshow( "Contours", drawing );
  }

It's a sample code and should work just find but when I try to run the code just after pressing Space to capture the image the program just crashes and says "Ashkan.exe has stopped working" without any error at all!
I know the problem is with the FindContours line because as i comment that line the program runs just fine.
In debug mode when passing findContours line it says: Unhandled exception at 0x76f2320e in Ashkan.exe: 0xC0000005: Access violation reading location 0xffffffffffffffff.
Does anyone know any possible cause for this problem?!


text:
Q: Having a problem with applying realm plugin to gradle file I wanted to apply realm to my project,
It went well, I added jcenter() repositories and synced it which had no problem. But when I went to the buildgradle(Module:3_8), and added a code:
apply plugin:'realm-android'

this error was raised:
A problem occurred evaluating project ':part3_8'.
> Failed to apply plugin 'realm-android'.
   > Build was configured to prefer settings repositories over project repositories but repository 'BintrayJCenter' was added by plugin 'realm-android'

this is my build.gradle(project:letmein)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
        jcenter()
    }

    dependencies {
        classpath "com.android.tools.build:gradle:7.0.1"
        classpath "io.realm:realm-gradle-plugin:3.5.0"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and this is where the problem is:
//plugins {
//    id 'com.android.application'
////    id 'realm-android'
//}

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    compileSdk 31

(plus, I use Android studio:)

A: In gradle settings replace the line
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)

With
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)


text:
Q: Android Studio (Kotlin): Error when starting the debugger I am a novice at Android and Kotlin, and I've started to follow the "fundamentals" codelabs.  I also have an experimental app of my own that I wrote from scratch.  It runs nicely on the emulator and the device, but now I can no longer run it in the debugger (using the "bug" icon).  When I do that, I immediately get this stack trace:
access:-1, Linux (libcore.io)
access:131, ForwardingOs (libcore.io)
access:76, BlockGuardOs (libcore.io)
access:131, ForwardingOs (libcore.io)
access:7719, ActivityThread$AndroidOs (android.app)
checkAccess:281, UnixFileSystem (java.io)
exists:813, File (java.io)
updateLoader:75, ResourceOverlays (com.android.tools.deploy.instrument)
addResourceOverlays:37, ResourceOverlays (com.android.tools.deploy.instrument)
addResourceOverlays:110, InstrumentationHooks (com.android.tools.deploy.instrument)
getResources:1312, LoadedApk (android.app)
createSystemContext:2993, ContextImpl (android.app)
getSystemContext:2647, ActivityThread (android.app)
handleBindApplication:6621, ActivityThread (android.app)
access$1500:256, ActivityThread (android.app)
handleMessage:2090, ActivityThread$H (android.app)
dispatchMessage:106, Handler (android.os)
loopOnce:201, Looper (android.os)
loop:288, Looper (android.os)
main:7842, ActivityThread (android.app)
invoke:-1, Method (java.lang.reflect)
run:548, RuntimeInier (com.android.internal.os)
main:1003, ZygoteInit (com.android.internal.os)

In this frame:
exists:813, File (java.io)

I see:
this = {File@19636} "/data/data/com.example.codegame/code_cache/.overlay/base.apk/res"

Any idea which file this is supposed to be?  There is no /data/ folder on my machine!
I should add that:

*

*Earlier, I was able to start the app in the debugger.  I guess at some point I made some changes that are causing the problem, but I have no idea what!

*If I just run the app (in the emulator), I can attach the debugger after it started.

*This doesn't happen with other projects.

*This error persists when I close and re-open Studio.

Any suggestions or hints would be appreciated.
Thanks!


text:
Q: Excel: EnableOutlining seems to default to False on opening workbook Like many other people, I want to be able to enable grouping and ungrouping with the little +/- buttons on a protected worksheet. Everyone seems to have succeeded with the same sort of code that protects the worksheet, enables outlining and then unprotects it again, which is great and it works except if I save the sheet and then re-open it again EnableOutlining is always set as False, and if the sheet is protected I cannot use the +/- buttons. Is there something else I am supposed to do to save this setting permanently, and not just for the duration of the session?
Here's the code I have been using:
Private Sub Workbook_Open()
MsgBox ActiveSheet.EnableOutlining
End Sub

Sub EnableOutliningWithProtection_AllSheets()
'PURPOSE: Allow Outline functionality during Protection in all Sheets
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
'(Except edited by me to include the Errorcatch)

Dim sht As Worksheet
On Error GoTo Errorcatch
'Loop through each Worksheet in ActiveWorkbook
  For Each sht In ActiveWorkbook.Worksheets
    'Password Protect Current Sheet
      sht.Protect Password:="", UserInterfaceOnly:=True

    'Enable Group Collapse/Expand Capabilities
      sht.EnableOutlining = True

    'Unprotect Sheet
      sht.Unprotect ""

  Next sht

Exit Sub
Errorcatch:
MsgBox Err.Description

End Sub

(I've got the Workbook_Open() bit to check if EnableOutlining was still True)
I've seen the 'protect UserInterfaceOnly and EnableOutlining' question, but I didn't think the results applied as the code was written for C#, and I'm not looking at protecting UserInterfaceOnly.

A: You can't save it permanently. You have to use the Open event to reset it when the workbook is opened.
Private Sub Workbook_Open()
    EnableOutliningWithProtection_AllSheets
End Sub


text:
Q: How to take preference with virtual method overriding and inheritance So at the moment I have 3 classes. Shape, Square, Triangle. Triangle and Square inheriting from Shape. In Shape I have the virtual methods:

virtual bool myMethod();

virtual bool myMethod(Shape& sha);

And for example in Triangle I have:

virtual bool myMethod(Square& sqa);

virtual bool myMethod(Shape& tri);

Now in my main method I have:
Shape* m[3];
m[0] = new Square;
m[1] = new Triangle;
m[2] = new Square;
cout << m[0]->myMethod(*m[1]);
cout << m[0]->myMethod(*m[2]);

When I call it in the first cout, it works fine and goes to the method with (Shape& tri), but on the second one it also goes to the (Shape& tri) method. I understand why this is happening, but is there any way I can make it so it goes to the (Square& squ) method instead of Shape?
Thank you

A: C++ selects the method to be called using overload resolution. Overload resolution is entirely based on the static type of the arguments. If the called overload is a virtual function it may be overridden in a derived class in which case the call is dispatch at run-time to the override.
As far as I can tell, you want the system to do a multiple dispatch based on the object and the argument type. C++ doesn't directly support multi dispatch but there are some ways to simulate it. To deal with the dispatch you want, can arrange your calls to find the appropriate override at run-time. One way to do so is to split the functions into multiple versions.
struct Square;
struct Triangle'
struct Circle;

struct Shape {
    virtual ~Shape() {}

    virtual bool doMethod(Square& s) { return doMethod(static_cast<Shape&>(s)); }
    virtual bool doMethod(Triangle& s) { return doMethod(static_cast<Shape&>(s)); }
    virtual bool doMethod{Circle& s) { return doMethod(static_cast<Shape&>(s)); }

    virtual bool doMethod(Shape&) = 0;
    virtual bool myMethod(Shape&) = 0;
};

struct Triangle: Shape {
    bool myMethod(Shape& other) { return other.doMethod(*this); }
    bool doMethod(Shape& other) { /* general case */ }
    bool doMethod(Square& other) { /* special case */ }
};

A: You're looking for a feature that does not exist in the C++ language. In C++, dynamic dispatch occurs only from the caller, not on any of the arguments.
So when you call myMethod(*m[2]), *m[2] is a Shape so it will call bool myMethod(Shape& ) since that's what overload resolution prefers.
Now, if you really want something special in the Triangle/Square case, you might want to look at double dispatch:
virtual bool Triangle::myMethod(Shape& shape) {
    return shape.myMethodImpl(*this);
}

That way, you can have:
virtual bool Square::myMethodImpl(Triangle& triangle) {
    // ...
}

Which can only be called via that 2nd dispatch.


text:
Q: PHP How to sort results ASC Can someone help me add a sort function here... I need the "if" results to be sorted ASC by floorplan_price.
if ($this->floorplan=ipropertyHTML::getcatfloorplan($this->catinfo->id))
{
echo '
Available Floorplans To Build
';

  $this->k = 0;
  $this->floorplan=ipropertyHTML::getcatfloorplan($this->catinfo->id);

  foreach($this->floorplan as $fp)
  {
    $this->floorplan_price=$fp->floorplan_price;
    $this->floorplaninfo=ipropertyHTML::getfloorplaninfo($fp->floorplan_id);
    $this->p= $this->floorplaninfo;
    echo $this->loadTemplate('floorplan');
    $this->k = 1 - $this->k;
  }}
else { // no results tmpl

    echo '
Available Floorplans To Build
';
    echo '
No floor plans are available to build at the time. Check back soon!
';

}

A: The usort function allows you to provide the logic for sorting.
Define the sorting method:
function sortByPrice($a, $b)
{
    if ($a->floorplan_price == $b->floorplan_price) {
        return 0;
    }
    return ($a->floorplan_price < $b->floorplan_price) ? -1 : 1;
}

Then above your foreach loop
usort($this->floorplan, "sortByPrice");

I will note, as @Sébastien did, that this should be a job for MySQl not php if at all possible, simply for performance.


text:
Q: Build a Joomla site around/parallel a Zend Framework app My team has a rather large web application that was built with the Zend Framework, which has become mission-critical to our organization in the past year.  It was built as part of an existing ZF corporate web site that no longer meets our needs.
The ZF app has its own users table in a database.  It also uses Zend_Acl, and some database tables, to control access to modules, and to individual records.  The records largely pertain to people in the system.
Thanks to new business needs, we're now faced with building a new public web site in Joomla.  So, we need: (1) to keep running the old system, in some capacity, and (2) a shiny new Joomla site, (3) integration between the two.
-We can't move custody of the users away from our legacy system, because the people those users represent are elemental to the legacy system's purpose.
-We need the usernames and passwords to be the same, and work the same (we have a 60 day reset policy, our usernames aren't fixed values / are a bit convoluted)
-I looked at Zend_Ldap hoping I could expose our users to Joomla that way, but it seems to be just an LDAP client, and I'm not sure implementing an Ldap server in Zend that uses our existing tables is a good use of time.  An extension that replaces Joomla's authentication would probably be wiser.
-Can our ACL control Joomla or should we have two ACLs exist in parallel.
-Do we write SOAP services in the Zend app to expose the data to the extension, or do we just give database credentials to the Joomla extensions directly.
A pretty broad question, I know, but I am only looking for broad answers: how would you tackle this?
Thanks!

A: *

*The first step sounds like integrating the Auth system across Joomla! and your ZF app from there you can direct link to the ZF App's pages for logged in users. I would recommend the use of JFusion to integrate the Joomla! authorisation process and match the ACL groups across the two systems. You will have to write your own plugin for JFusion but that will be very simple compared to porting your entire app to a Joomla! extension. JFusion's GitHub repo is here.

*Given the data provided you will need to run the ZF App as the master for authentication and sync user data to Joomla! via your custom plugin.

*Once you have your plugin doing the authentication you can use JFusion's direct link mode to link to the ZF App as user that login to Joomla! will be automatically logged into the ZF app (and vice versa).


text:
Q: how to sort durations with Qt? i'm trying to make QSortFilterProxyModel sort items by duration.
preconditions:

*

*hours and minutes must not have leading zeros

*if duration is less than an hour, then hours must not be displayed, but only minutes and seconds

*if duration is less than a minute, then 0 minutes and the corresponding number of seconds must be displayed [0:42]

tried to store durations in the source model as H:mm:ss (http://doc.trolltech.com/4.6/qtime.html#toString) if they are one hour or longer, and as m:ss - if less than an hour, but since sorting of QStrings is alphabetical, then, for instance, 5:20 is "more" than 12:09 as its first digit is greater.
is there an elegant way to do the sorting?

A: *

*When call "setData" to set an item's data, set q QTime object directly

*Subclass QItemDelegate and handle display by simply draw a text, override sizeHint if necessary

*Call QAbstractItemView::setItemDelegateForColumn to set your delegate for the duration column.

By this approach, you can display your QTime data with your approach, and sort correctly.

A: my implementation of the accepted answer [DurationDelegate is a subclass of QStyledItemDelegate]:
void DurationDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    Q_ASSERT(index.isValid());
    QStyleOptionViewItemV4 v4option = option;
    initStyleOption(&v4option, index);
    const QWidget *widget;
    const QStyleOptionViewItemV4 *v4 = qstyleoption_cast<const QStyleOptionViewItemV4 *>(&option);
    v4 ? widget = v4->widget : widget = 0;
    QStyle *style = widget ? widget->style() : QApplication::style();
    if (index.model()->data(index, Qt::DisplayRole).type() == QVariant::Time) {
        QTime length = index.model()->data(index, Qt::DisplayRole).toTime();
        QString format;
        length >= QTime(1, 0) ? format = QString("H:mm:ss") : format = QString("m:ss");
        v4option.text = length.toString(format);
    }
    style->drawControl(QStyle::CE_ItemViewItem, &v4option, painter, widget);
}


text:
Q: A problem occurred configuring root project 'DaggerTest'. > Could not resolve all artifacts for configuration ':classpath' After a while, I opened Android Studio and created a project called 'DaggerTest'. Unfortunately, when my Gradle is getting built, I face this error
A problem occurred configuring root project 'DaggerTest'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find bundletool-1.1.0.jar (com.android.tools.build:bundletool:1.1.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/bundletool/1.1.0/bundletool-1.1.0.jar
   > Could not find transform-api-2.0.0-deprecated-use-gradle-api.jar (com.android.tools.build:transform-api:2.0.0-deprecated-use-gradle-api).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/transform-api/2.0.0-deprecated-use-gradle-api/transform-api-2.0.0-deprecated-use-gradle-api.jar
   > Could not find jetifier-processor-1.0.0-beta09.jar (com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta09).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/jetifier/jetifier-processor/1.0.0-beta09/jetifier-processor-1.0.0-beta09.jar
   > Could not find jetifier-core-1.0.0-beta09.jar (com.android.tools.build.jetifier:jetifier-core:1.0.0-beta09).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/jetifier/jetifier-core/1.0.0-beta09/jetifier-core-1.0.0-beta09.jar

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html

Here are the things that I have done and they did not work:

*

*I allowed Android Studio(studio.exe, studio64.exe) and all java executable files in the windows firewall

*I have disabled the windows firewall and it did not work.

*I have tried some proxies in Android Studio HTTP proxy settings

*I have changed my build Gradle file from this:

buildscript {
    repositories {
        google() // <-- here
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:4.2.0-beta03'

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

To this:

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.0-beta03'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


text:
Q: ReferenceError: user is not defined in user api When I open localhost:1337/user I got Internal Server Error
Something isn't right here.

ReferenceError: user is not defined

How can I fix it? My API is not working. I can't insert data in database using html forms in sailsjs.
My user model is:
    module.exports = {
    attribute: {
 firstname: {
    type: 'string',
    unique: true
  },
  lastname: {
    type: 'string',
    unique: true
},
 organisationName: {
    type: 'string',
    unique: true
},
 DepatmentName: {
    type: 'string',
    unique: true
},
 DOB: {
    type: 'date',
    unique: true
},
 DOJ: {
    type: 'date',
},
 DOL: {
    type: 'date',
},
 Address: {
    type: 'string',
},
 City: {
    type: 'string',
},
 State: {
    type: 'string',
},
 Country: {
    type: 'string',
},
  email: {
    type: 'string',
    email: true,
    required: true,
    unique: true
    },
    encryptedPassword: {
        type: 'string',
    },
    ContactNumber: {
        type: 'integer',
    },
    //toJSON: function() {
//      var obj = this.toObject();
//
//  }
}
};

A: You are calling a variable "user" and it doesn't exist or it's empty. Check youre code for this variable..
In youre usermodel, you only have firstname and lastname. I guess you need one of this. If you want more specific help, then you have to show us some extra coding of the page, not only the model.


text:
Q: put and change the place of the player in pacman in C I'm creating a function that places the player randomly and another function that updates his place. I'm using another function valide(); to verify that the case is available to move (not a wall ..etc).
I'm having a problem when updating a player's position..
This is the function that will place the player randomly it doesn't work either.
joueur_t* placer_j(int** pl)
{
  joueur_t* joueur= NULL;
  joueur->name='J';
  // pl = plateau .. the table of pacman
  //joueur = player

  joueur->x=rand() % P_SIZE+15; // P_SIZE +15 = WIDTH WALL =30
  joueur->y=rand() % P_SIZE; //y P_SIZE HEIGHT =15

  // a voir si la case est vide pour placer un joueur en utilisent la function valide();

  if (valide(pl, joueur->x,joueur->y=='4'))
  {
    pl[joueur->x][joueur->y]=joueur->name;

    return joueur;
  }
}

This one is for updating the position I couldn't even start..
void update_j(int** pl, joueur_t* jou)
{

}

valid function( if there's no wall the player can move otherwise no)
int valide(int** pl, int i, int j) // if the case is empty then the player can move
{
  for (i = 0; i <P_SIZE; i++)
  {
    for (j = 0; j < P_SIZE+15; j++)
    {
      if ((pl[i][j] == 2)) // 2 = WALL
      {
        return 0;
      }
    }
    return 1;
  }
}

So i need help with my function update_j when a player take a move (i'm using WASD keys) i need to update his position with the new location.
I would be thankful for some advice.
Thank you

A:  if (valide(pl, joueur->x,joueur->y=='4'))
  {
    pl[joueur->x][joueur->y]=joueur->name;

    return joueur;
  }
}

The function rand() returns an integer type.
joueur->y=='4'

Checks whether the y position of the player is equal to character '4' which corresponds to int value 52.
In addition, by using the binary operator '==' you are passing to the function valide()
int valide(int** pl, int i, int j)

a binary result (0 or 1) as its third argument. As far as I understand that is meant to be the y position of the player.


text:
Q: HDD randomly becomes read-only even after fsck I'm using a six year old notebook. The old HD died after it started to make some noises. The new one, after months of good use, started getting noisy too. However, the noise would stop for a whole day if i just restarted it twice before using it.
So yesterday, the screen freezes while using a lot of the processor, and  after the forced reboot, Ubuntu booted an initramfs terminal.
I ran fsck /dev/sda1 -y and Ubuntu booted normally, but the HD was read-only (and freezing for some seconds, which isn't common). After trying some solutions I figured out that the HD didn't boot read-only, it became read-only after using it for a while. Usually during downloads, such as updates, but i'm not quite sure what causes it to become read-only.
I'm not good with hardware, but i think this notebook might be a Hard-Drive killer.
english screenshots :

A: You may, or may not, get a little more use out of the drive, before it fails entirely, by bad blocking it. You do not have a heat problem. You have 27 potentially bad blocks waiting to get remapped. Re-run the SMART diags after doing the bad blocking, to confirm status of the drive. A diags FAIL does not necessarily mean that the drive is unusable.
Understand that ultimately you'll probably have/want to replace the HDD. I recommend Western Digital drives, which is what you have now. You won't be able to purchase a 320G drive any more though.
Note: do NOT abort a bad block scan!

Note: do NOT bad block a SSD

Note: backup your important files FIRST!

sudo e2fsck -fcky /dev/sdXX # read-only test
or
sudo e2fsck -fccky /dev/sdXX # non-destructive read/write test (recommended)
The -k is important, because it saves the previous bad block table, and adds any new bad blocks to that table. Without -k, you loose all of the prior bad block information.
The -fccky parameter...
   -f     Force checking even if the file system seems clean.

   -c     This option causes e2fsck to use badblocks(8) program  to  do  a
          read-only  scan  of  the device in order to find any bad blocks.
          If any bad blocks are found, they are added  to  the  bad  block
          inode  to  prevent them from being allocated to a file or direc‐
          tory.  If this option is specified twice,  then  the  bad  block
          scan will be done using a non-destructive read-write test.

   -k     When combined with the -c option, any existing bad blocks in the
          bad blocks list are preserved, and any new bad blocks  found  by
          running  badblocks(8)  will  be added to the existing bad blocks
          list.

   -y     Assume  an answer of `yes' to all questions; allows e2fsck to be
          used non-interactively.  This option may not be specified at the
          same time as the -n or -p options.

A: Unfortunately it sounds like you may have a hardware issue. Likely the laptop is overheating. Try the following:
1. Ensure you fan is working
Do you hear the fan come on? Is it ALWAYS on? If it never comes on, you may need to replace your fan. If it's always on, your ducts might be clogged.
2. Clean dust from cooling areas
Try blowing out your fan ducts with compressed air. If you are comfortable doing so, open up the laptop and clean out the fan ducts with compressed air and a soft brush. Maybe even use a little rubbing alcohol.
3. Boot from a live USB and fsck your HD from there
You can also try booting from a live USB so that your HD is unused. You can now use disk utilities like fsck to really examine and treat your HD (although you probably were able to do the same in intramfs mode).


text:
Q: How delete all pushable commits? I try to use the git filter-branch to remove some big files. This was not a good idea because it rewrite the history and create a new branch doubling all commits.
Now I want to redo this. I see in SmartGit (a git graphic interface) that it create a lot of pushable commits. How can I delete it and undo all this commits?
I will have to delete one by one using the SHA ID?

A: If you didn't yet push them you can do a git reset --hard HEAD~X where X is the number of commits.

A: git filter-branch will create a backup copy of your unwritten refs inside the .git/refs/original/ directory.
You might get lucky by moving those refs to their previous location (.git/refs/heads/) – be sure to make a backup copy of your complte repository first ;)
That way you don't have to reset each branch head separately.


text:
Q: Connect the Seekbar to the EditText I need help connecting the seekbar to the edit text. I want to limit the number of lines of the text.
On the seekbar, I put the number from 1-50, and for example, I put the number on 20, the number of lines is limited to 20 lines.

A: in your xml file add this code
<EditText
android:id="@+id/editText2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:maxLines="20"
android:lines="20">

or programmatically
editText.setLines(maxlines); //maxlines=20


text:
Q: Play bytestream on client site with web audio api I'm sending an stereo audiofile (WAV) via websockets and want to play it via the Web Audio Api. The Serversite technology is asp.net.
Currently i have this:
 ws.onmessage = function(evt) {

        var d2 = new DataView(evt.data);

        var data = new Float32Array(d2.byteLength / Float32Array.BYTES_PER_ELEMENT);
        for (var jj = 0; jj < data.length; ++jj) {
            data[jj] = d2.getFloat32(jj * Float32Array.BYTES_PER_ELEMENT, true);
        }

        var buffer = context.createBuffer(1, data.length, 44100);
        buffer.getChannelData(0).set(data);

        source = context.createBufferSource();
        source.buffer = buffer;
        source.start(startTime);
        source.connect(context.destination);

        startTime += buffer.duration;

    }

With this i can hear the song but with A LOT of noise... i believe this might be because it is an stereo file and i only use 1 channel?
If yes, how could i do it with two channels? I tried some things but the result was always the same or worse.
And i have another problem in understanding why it is working with Float32Array? In my first approach i used Uint8Array because i'm sending bytes to the client so i thought i would need Uint8Array to get the same values i send. But with Uint8Array i just hear noise and nothing from the song at all.
thanks for your help in advance!
Best Regards,
metabolic


text:
Q: Getting mean value of set of variables after grouping by date using R Here is my dataset: https://app.box.com/s/x5eux7mhdc0geyck4o47ttmpynah0wqk
Snapshot:

I'd like a create a data frame in which the average value of the sentiments would be present in a group of 2 months.
I tried the following code:
sentiment_dataset$created_at <- ymd_hms(sentiment_dataset$created_at)

sentiment_time <- sentiment_dataset %>%
  group_by(created_at = cut(created_at, breaks="2 months")) %>%
          summarise(negative = mean(negative),
                    positive = mean(positive)) %>% melt

It gave the following error:
Using created_at as id variables
Error in match.names(clabs, names(xi)) :
  names do not match previous names

A: I'm not sure you can create the grouping variable in the group_by statement. Looks like using mutate beforehand works, though.
library(dplyr)
library(tidyr)

sentiment_time <- sentiment_dataset %>%
  mutate(created_at = cut(created_at, breaks="2 months")) %>%
  group_by(created_at) %>%
  summarize(negative = mean(negative),
            positive = mean(positive)) %>%
  gather('sentiment', 'mean_value', negative, positive)

A: I'd checkout the tibbletime package:
library(tibbletime)
library(tidyverse)

sentiment_dataset %>%
  arrange(created_at) %>%
  as_tbl_time(index = created_at) %>%
  collapse_by("2 months", clean = TRUE) %>%
  group_by(created_at) %>%
  summarise(negative = mean(negative),
            positive = mean(positive))

# A time tibble: 48 x 3
# Index: created_at
   created_at          negative positive
   <dttm>                 <dbl>    <dbl>
 1 2010-09-01 00:00:00    0.143    1.43
 2 2010-11-01 00:00:00    0.273    0.727
 3 2011-01-01 00:00:00    0.208    0.792
 4 2011-03-01 00:00:00    0.5      1.38
 5 2011-05-01 00:00:00    0.25     0.75
 6 2011-07-01 00:00:00    1        1
 7 2011-09-01 00:00:00    0        1.5
 8 2011-11-01 00:00:00    0.333    1
 9 2012-01-01 00:00:00    0        0
10 2012-03-01 00:00:00    0        1.6
# ... with 38 more rows

Naturally, you may want to pipe a gather() command after that...for example:
sentiment_dataset %>%
  arrange(created_at) %>%
  as_tbl_time(index = created_at) %>%
  collapse_by("2 months", clean = TRUE) %>%
  group_by(created_at) %>%
  summarise(negative = mean(negative),
            positive = mean(positive)) %>%
  gather(sentiment, mean_sentiment, -created_at) %>%
  ggplot(., aes(created_at, mean_sentiment, color = sentiment)) +
  geom_point() +
  geom_line() +
  geom_smooth()


text:
Q: convert the pseudo code into assembly code The following is pseudo-code:
int array_list[] = {0, 11, 13, 18, 21, 23, 24, 17, 45};
int array_size = sizeof array_list/sizeof sample;
int index = 0; // index for while loop
int sum = 0;   // accumulate the result
for (current_size = array_size ; current_size > 0; current_size--){
    while (index<current_size){
        if(array_list[index]is even){
           sum += array_list[index];
        }
        index += 1;
     }
}

My work is:
.data
sum DWORD 0
sample DWORD 0
array_list DWORD 10,11,13,18,21,23,24,17,45
array_size = ($-array_list)/Type array_list

.code
main PROC

mov eax,0
mov edx,sample
mov esi,0
mov ecx,array_size

L1:
cmp esi,ecx
jl L2
jmp L5

L2:
cmp array_list[esi*4], edx
jg L3
jmp L4

L3:
add eax,array_list[esi*4]

L4:
inc esi
jmp L1

L5:
mov sum,eax

I'm confusing how to do for_while loops in .asm file. My question is how can I code

for (current_size = array_size ; current_size > 0; current_size--){

to my code?


text:
Q: How to use file picker in Android 11 In my application I want user can open file picker and select file.
I write below codes, but after clicking up upload show me error and application crashed!
But below of android 11 everything is OK and not any problem!
I write below codes in Activity:
class AddMaangramActivity : BaseActivity() {

    private lateinit var requestBody: RequestBody
    private val multiPart by lazy {
        MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("_method", "post")
    }
    private lateinit var resultIntent: ActivityResultLauncher<Intent>
    private var uploadFile: File? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityAddMaangramBinding.inflate(layoutInflater)
        setContentView(binding.root)

    //Open file picker
        item2ImgLay.setOnClickListener { openFilePicker() }

        //Activity result
        resultIntent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val data = result.data
                data?.let {
                    val uri = it.data
                    uri?.let { itUri ->
                        binding.coverImg.load(itUri)
                        uploadFile = File(getRealPathFromURIWithProvider(this, itUri))
                    }
                }
            }
        }

        //Upload
        uploadBtn.setOnClickListener {
            //File
            val fileName = URLEncoder.encode(uploadFile?.absolutePath, "UTF-8")
            val reqFile = uploadFile?.asRequestBody("multipart/form-data".toMediaTypeOrNull())
            multiPart.addFormDataPart("file", fileName, reqFile!!)
            val filePart = MultipartBody.Part.createFormData("file", fileName, reqFile)
            body.file = filePart
            //Submit
            requestBody = multiPart.build()
    }

    }

    private fun openFilePicker() {
        var intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "*/*"
        val type: Array<String> = arrayOf("image/*", "video/*")
        intent.putExtra(Intent.EXTRA_MIME_TYPES, type)
        intent = Intent.createChooser(intent, "Choose file")
        resultIntent.launch(intent)
    }
}

Error message:
java.io.FileNotFoundException: : open failed: ENOENT (No such file or directory)
        at libcore.io.IoBridge.open(IoBridge.java:492)
        at java.io.FileInputStream.<init>(FileInputStream.java:160)
        at okio.Okio__JvmOkioKt.source(JvmOkio.kt:182)
        at okio.Okio.source(Unknown Source:1)
        at okhttp3.RequestBody$Companion$asRequestBody$1.writeTo(RequestBody.kt:167)
        at okhttp3.MultipartBody.writeOrCountBytes(MultipartBody.kt:157)
        at okhttp3.MultipartBody.writeTo(MultipartBody.kt:93)
        at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.kt:202)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
        at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:517)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)
        Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@7b44291, Dispatchers.IO]
    Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
        at libcore.io.Linux.open(Native Method)
        at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
        at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
        at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
        at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7542)
        at libcore.io.IoBridge.open(IoBridge.java:478)

Also, I added this line android:requestLegacyExternalStorage="true" to manifest in application tag! again show me error
How can I fix it?

A: You use ACTION_OPEN_DOCUMENT to let the user pick a file.
For that you do not need any permission or request legacy of any kind.
You are blaming the filepicker. But ACTION_OPEN_DOCUMENT gives you a nice uri. That all works ok.
The trouble only starts where to mess around with the uri: uploadFile = File(getRealPathFromURIWithProvider(this.
Awfull. Dont do such nasty things. Use the uri directly to upload the choosen file.
Has nothing to do with scoped storage too.


text:
Q: indent error in python while using if statements inside for loop I used the following code:
for item in users_dict['items']:
    sl_no = sl_no + 1
    user_id_pass = item['user_id']
    account_id_pass = item['account_id']
    Name_pass = item['display_name']

    if 'age' in item:
        age_pass = item['age']
    else:
        age_pass = 0

    stack_link_pass = item['link']
    user_type_pass = item['user_type']
    Location_pass = item['location']

    if 'website_url' in item:
        website_link_pass = item['website_url']
    else:
        website_link_pass = 'NA'

I am getting this error:
 user_id_pass = item['user_id']
    ^
IndentationError: unexpected indent

please help me out

A: As I see that all your lines are indented with the correct amount of spaces, please check that your using either tabs or spaces to indent.
For example you may have run into this situation:
    {4 spaces}sl_no = sl_no + 1
    {--1 tab-}user_id_pass = item['user_id']
    {4 spaces}account_id_pass = item['account_id']

A: In Python, you can only use one or the other, tabs or spaces, to indent your code. Since tabs and spaces are encoded differently, the interpreter can't tell where your if statement ends. Backspace over all of your indentations, then just tab or space every line the number of indents you prefer.

A: To Enhance it more for someone who gets into this situation. In your most widely used code editors. VSCode or Sublime Text.
Type a sequence "Ctrl+Shift+P" a command box will open
In that type "Indentation: Convert to Spaces" or similarly "Indentation: Convert to Tabs".
It will manage all the tabs and spaces and convert them to a uniform type.
Correct the formatting and you are good to go.


text:
Q: Randomly Generate force layout D3js I'm trying to randomly generate a multiple points with d3js then add and remove the connections randomly while maintaining constant movement. Here is what I have so far:
<meta charset="utf-8">
<style>

.link {
  stroke: #000;
  stroke-width: 1.5px;
}

.node {
  fill: #000;
  stroke: #fff;
  stroke-width: 1.5px;
}

.node.a { fill: #1f77b4; }
.node.b { fill: #ff7f0e; }
.node.c { fill: #2ca02c; }

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var color = d3.scale.category10();

var nodes = [],
    links = [];

var force = d3.layout.force()
    .nodes(nodes)
    .links(links)
    .charge(-900)
    .linkDistance(220)
    .on("tick", tick);

var svg = d3.select("body").append("svg");

var node = svg.selectAll(".node"),
    link = svg.selectAll(".link");
    resize();
  d3.select(window).on("resize", resize);
function resize() {
    width = window.innerWidth, height = window.innerHeight;
    svg.attr("width", width).attr("height", height);
    force.size([width, height]).resume();
  }
// 1. Add three nodes and three links.
setTimeout(function() {
  var a = {id: "a"}, b = {id: "b"}, c = {id: "c"};
  nodes.push(a, b, c);
  links.push({source: a, target: b}, {source: a, target: c}, {source: b, target: c});
  start();
}, 0);

// 2. Remove node B and associated links.
setTimeout(function() {
  nodes.splice(1, 1); // remove b
  links.shift(); // remove a-b
  links.pop(); // remove b-c
  start();
}, 3000);

// Add node B back.
setTimeout(function() {
  var a = nodes[0], b = {id: "b"}, c = nodes[1];
  nodes.push(b);
  links.push({source: a, target: b}, {source: b, target: c});
  start();
}, 6000);

function start() {
  link = link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });
  link.enter().insert("line", ".node").attr("class", "link");
  link.exit().remove();

  node = node.data(force.nodes(), function(d) { return d.id;});
  node.enter().append("circle").attr("class", function(d) { return "node " + d.id; }).attr("r", 8);
  node.exit().remove();

  force.start();
}

function tick(d) {
    console.log('tick')
    var randomX = d3.random.normal(width / 2, 80),
    randomY = d3.random.normal(height / 2, 80);
     d.x = randomX();
  d.y = randomY();
  console.log(d.y);
  node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })

  link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });
}

</script>

Most the code I got from here. Basically I am trying to create something similar to this example, but instead of using hexbin, I just want to randomly generate and move nodes/circles around. Something similar to the functionality on this page, where the nodes are constantly moving and changing links. Any help on how to achieve this functionality would be appreciated. Also here is a jsfiddle of what I have so far.


text:
Q: Passing `null` reference for a `ref struct` parameter in interop method I am using C# to call a DLL function.
[DllImport("MyDLL.dll", SetLastError = true)]
public static extern uint GetValue(
        pHandle handle,
        ref somestruct a,
        ref somestruct b);

How can I pass a null reference for argument 3?
When I try, I am getting a compile-time error:

Cannot convert from <null> to ref somestruct.

I also tried IntPtr.Zero.

A: You have two options:

*

*Make somestruct a class, and change the function signature to:
[DllImport("MyDLL.dll", SetLastError = true)]
public static extern uint GetValue(
    pHandle handle, somestruct a, somestruct b);

Usually this must not change anything else, except that you can pass a null as the value of a and b.

*Add another overload for the function, like this:
[DllImport("MyDLL.dll", SetLastError = true)]
public static extern uint GetValue(
    pHandle handle, IntPtr a, IntPtr b);

Now you can call the function with IntPtr.Zero, in addition to a ref to an object of type somestruct:
GetValue(myHandle, ref myStruct1, ref myStruct2);
GetValue(myHandle, IntPtr.Zero, IntPtr.Zero);

A: Since .NET 5.0 there is System.Runtime.CompilerServices.Unsafe.NullRef<T>()
GetValue(myHandle, ref myStruct1, ref myStruct2);
GetValue(myHandle, ref Unsafe.NullRef<somestruct>(), ref Unsafe.NullRef<somestruct>());

A: This answer suggests to make SomeStruct a class. I would like to show an implementation of that idea which appears to work nicely… even when you cannot change the definition of SomeStruct (such as when it is a predefined type like System.Guid; see also this answer).

*

*Define a generic wrapper class:
[StructLayout(LayoutKind.Explicit)]
public sealed class SomeStructRef
{
    [FieldOffset(0)]
    private SomeStruct value;

    public static implicit operator SomeStructRef(SomeStruct value)
    {
        return new SomeStructRef { value = value };
    }
}

The basic idea here is identical to boxing.

*Change your interop method definition to the following:
[DllImport("MyDLL.dll", SetLastError = true)]
public static extern uint GetValue(
    pHandle handle,
    ref SomeStruct a,
    [MarshalAs(UnmanagedType.LPStruct)] SomeStructRef b);

The third parameter b will then be "nullable". Since SomeStructRef is a reference type, you can pass a null reference. You can also pass a SomeStruct value because an implicit conversion operator from SomeStruct to SomeStructRef exists. And (at least in theory), due to the [StructLayout]/[FieldOffset] marshalling instructions, any instance of SomeStructRef should get marshalled just like an actual instance of SomeStruct.
I'd be happy if someone who is an interop expert could validate the soundness of this techinque.

A: Another obvious solution is to resort to unsafe code and change the interop method declaration to this:
[DllImport("MyDLL.dll", SetLastError = true)]
unsafe public static extern uint GetValue(
        pHandle handle,
        ref somestruct a,
        somestruct* b);

Notice that the method is now marked unsafe, and that the parameter has changed from ref somestruct to somestruct*.
This has the following implications:

*

*The method can only be called from inside an unsafe context. For example:
somestruct s;
unsafe { GetValue(…, …, &s);   }  // pass a struct `s`
unsafe { GetValue(…, …, null); }  // pass null reference

*In order for the above to work, unsafe code must be allowed for the project (either in the project settings, or via the /unsafe command-line compiler switch).

*Using unsafe leads to unverifiable IL code. IIRC, this means that loading this assembly will require full trust (which can be problematic in some situations).


text:
Q: Trying to parse JSON in swift with swiftyJSON The issue is i am not able to populate an array with what I thought would be correct code to parse a JSON file with swiftyJSON.
As well as I am not sure if the process at which i send the request is correct.
JSON format: this should be simplified to what it truly represents: A dictionary with a "string" key and value of an array of dictionaries. then a string key with a value of a dictionary. then a string with a value of a string which i need.
 {
    "string1" : [
       { "string2" : {
            "string3" : "DataINeed"
          }
        }
     ]
  }

my code
func downloadSecondJSONData(completed: DownloadComplete)
{

    let API_ServerKey = "My API Key"
    let URL_Search = "URL Address"

    let urlString = "\(URL_Search)"
    let url = NSURL(string: urlString)!

    Alamofire.request(.GET,url).responseJSON { (response) -> Void in
        switch response.result
        {
        case .Success:
            if let value = response.result.value
            {
                let json = JSON(value)
                if let data = json["string1"]["string2"]["string3"].string
                {
                    self.dataArray.append(data)
                }

            }
        case .Failure(let error):
            print(error)
        }
        completed()
    }

}

func printData()
{
    print(self.dataArray.count)

}

How I am attempting to call the methods
downloadFirstJSONData { () -> () in
        self.randomMethod() //data i use with the downloadFirstJSONData is required to use in the downloadSecondJSONData

        self.downloadSecondJSONData({ () -> () in
            self.printData() //check if data has been stored
        })

    }

A: Looks like you're not accessing the array after the first dictionary.
I guess the safe way to access the first object would be:
if let array = json["string1"].array,
    let firstDict = array.first,
    let data = firstDict["string2"]["string3"].string {
        self.dataArray.append(data)
}

But I suppose with SwiftyJSON you can also do a variation of what you had:
if let data = json["string1"][0]["string2"]["string3"].string {
    self.dataArray.append(data)
}


text:
Q: Serialize to json nested one-to-many (opposite of many to one) I have Installs which have many Modules which each have many Versions.
a-la:
class Module(Models.Model):
    install = models.ForeignKey(Install)

One Install has many Modules.
I want to serialize this whole set to a json structure.
I found that I can use the wad of stuff serializer to serialize in this way:
 serializers.serialize("json", Version.objects.all(), indent=4,
                        relations={'module':{'relations':('install',)}})

But this is starting from the inside out (a many-to-one view - many versions have one module, but I want to know what versions each module has).   I get  list of Versions at the top level, with each Version calling out it's Module, so the each Module is listed many times:
[
    {
        "pk": 1,
        "model": "cmh_server.version",
        "fields": {
            "name": "v1",
            "module": {
                "pk": 1,
                "model": "cmh_server.module",
                "fields": {
                    "install": {
                        "pk": 1,
                        "model": "cmh_server.install",
                        "fields": {
                            "name": "CMBN"
                        }
                    },
                    "name": "CMBN",
                }
            }
        },
        "pk": 2,
        "model": "cmh_server.version",
        "fields": {
            "name": "v1.1",
            "module": {
                "pk": 1,
                "model": "cmh_server.module",
                "fields": {
                    "install": {
                        "pk": 1,
                        "model": "cmh_server.install",
                        "fields": {
                            "name": "CMBN"
                        }
                    },
                    "name": "CMBN",
                }
            }
        }
    }
]

See how the same Module is listed twice.   That's "not right".
I want to say something like
serializers.serialize("json", Install.objects.all(), indent=4,
                      relations={'module':{'relations':('version',)}})

but of course that doesn't work because the Install model does not have a field called "module".

A: You can try using django rest framework.
Define a model serializer for Module model and Version model:
class VersionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Version

class ModuleSerializer(serializers.ModelSerializer):
    versions = VersionSerializer(many=True)
    class Meta:
        model = Module
        fields = ('id', ..... , 'versions')

Now define your Install model serialiser:
class InstallSerializer(serializers.ModelSerializer):
    modules = ModuleSerializer(many=True)
    class Meta:
        model = Install
        fields = ('id', ..... , 'modules')

This will serialize install data with all modules for each install and also all versions for each of the modules in a install.
EDIT:
I forgot to mention this, the name of the field of the related model should be the same as the value of related_name in the foreign key field.
For example in the Module model:
class Module(Models.Model):
    install = models.ForeignKey(Install, related_name='modules')

Now you have to use 'modules' as the name of the field in the serializer.


text:
Q: Unable to get the data to textView in activity public class About extends AppCompatActivity {
ImageView imageView;
TextView textView;

String mediaUrL;
private  FirebaseFirestore firebaseFirestore;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about);
    firebaseFirestore = FirebaseFirestore.getInstance();
    imageView = findViewById(R.id.showGraphImage);
    textView = findViewById(R.id.jkbdsjfdvshf);
    firebaseFirestore.collection("crimeData").document("graph").get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot snapshot) {
            mediaUrL = snapshot.getString("imageUrl");
            textView.setText(mediaUrL);
            System.out.println(snapshot.getString("imageUrl"));
        }
    });
    Glide.with(this).load(mediaUrL).into(imageView);
    System.out.println(mediaUrL);

I am new to android and I am using Cloud Firestore to store the data online .the variable mediaUrl prints on the console but don't show in the activity. I got the answer but still, now it is not working. Further, I added a used mediaUrl to display the image but it is also not showing on the activity.

A: As Sahil Goyal wrote, you need to use TextView.
final TextView textView = findViewById<TextView>(R.id.textView);

    ...
    public void onSuccess(DocumentSnapshot snapshot) {
        mediaUrL = snapshot.getString("imageUrl")
        System.out.println(snapshot.getString("imageUrl"));
        textView.setText(mediaUrL);
    }

A: You must have to add an adapter item and initiate that with a template adapter item in order to work with it.
Make a adapter class and inside oninstantiateitem() function create a itemview -
val itemView: View = LayoutInflater.from(container.context).inflate(
        R.layout.pageadapteritem, container, false
    )

After you have created itemview set -
itemView.textView.setText(mediaUrl)

PS - This code is in Kotlin, kindly change it to java when android studio asks to do so while pasting.

A: The problem in your code lies in the fact that you are trying to set the image using the following lines of code:
Glide.with(this).load(mediaUrL).into(imageView);
System.out.println(mediaUrL);

Outside the "onSuccess()" callback. Any code that needs data from Cloud Firestore, needs to be inside the onSuccess method, or be called from there. So the simplest solution is to move both lines of code right after:
System.out.println(snapshot.getString("imageUrl"));

This is happening because Firebase API is asynchronous. For more info about this topic, please see my answer from the following post:

*

*How to return a DocumentSnapShot as a result of a method?

A: If you want to show the image onto the ImageView, you should consider the following first:
1.- Please, double check if the image on your firebase has public access, you can set that permissions from the Google Cloud console through the shell console with this command.
gsutil acl ch -u AllUsers:R gs://<YOUR_BUCKET>/<IMAGE_NAME>
After that, to validate if your image has public access you can copy and paste the url string on a web browser, you must see your image in there.
2.- Also verify, if the path on the code to your image on firebase database has no typos and is correct. After checking the previous, If you see the "imageURL" value is printed on the console.
3.- You should move this line
Glide.with(getApplicationContext()).load(mediaUrl).into(imageView);
inside the onSuccess() method like this:
public void onSuccess(DocumentSnapshot snapshot) {
    mediaUrl = snapshot.getString("imageUrl");
    textView.setText(mediaUrl);
    Glide.with(getApplicationContext()).load(mediaUrl).into(imageView);
}

then it will be set on your imageView.
Good luck!


text:
Q: React material ui appbar made responsive I am trying to use material ui's appbar and code in some custom responsiveness to it. I am creating a personal project that will be accessed from a Galaxy s8 smartphone. Ultimately I would like the nav-links and logout button on the navbar to consolidate into a hamburger button when the viewport is small. I am not quite sure how to achieve this however as I am using flexbox on the webpage when it is at full size and it keeps messing me up.
Here is the appbar at full size:

Here is the appbar at phone size with the hamburger button:

Here is the desired effect I would like with items, posts, groups, and the log out button being pushed to an accordion like menu on mobile:

Here is my navbar component code:
import { withStyles } from "@material-ui/core/styles";
import styles from "./styles/NavBarStyles";
import { LoggedInContext } from "./contexts/LoggedIn";
import { ThemeContext } from "./contexts/ThemeContext";

function Navbar(props) {
  const { isDarkMode, toggleTheme } = useContext(ThemeContext);
  const { loggedIn, changeLogIn, token, setToken } = useContext(
    LoggedInContext
  );
  const { classes } = props;
  const [mobileHamburgerOpen, setMobileHamburger] = useState(false);

  const handleMobileClick = () => {
    setMobileHamburger(!mobileHamburgerOpen);
    console.log(mobileHamburgerOpen);
  };
  return (

      <AppBar
        position="static"
        style={{ background: isDarkMode ? "#2E3B55" : "#715AFF" }}
      >
        <Toolbar>
          <Typography className={classes.title} variant="h6" color="inherit">
            {isDarkMode ? "" : ""}
          </Typography>
          <Switch onChange={toggleTheme} />

          {loggedIn && (

                <NavLink
                  to="/items"
                  activeStyle={{ background: "rgba(0, 0, 0, 0.5)" }}
                >
                  Items
                </NavLink>
                <NavLink
                  to="/facebookitems"
                  activeStyle={{ background: "rgba(0, 0, 0, 0.5)" }}
                >
                   Posts
                </NavLink>
                <NavLink
                  to="/groups"
                  activeStyle={{ background: "rgba(0, 0, 0, 0.5)" }}
                >
                   Groups
                </NavLink>

              <Button
              className={classes.logOutButton}
                variant="contained"
                color="secondary"
                onClick={handleClick}
              >
                Log Out
              </Button>
              <Button
                className={classes.hamburgerMenu}
                variant="contained"
                color="primary"
                onClick={handleMobileClick}
              >

              </Button>

          )}
        </Toolbar>
      </AppBar>

  );
}
export default withStyles(styles)(Navbar);

Here is my style sheet code:
import { fade } from "@material-ui/core/styles/colorManipulator";

const styles = theme => ({
  root: {
    width: "100%",
    marginBottom: 0
  },
  grow: {
    flexGrow: 1
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20
  },
  title: {
    display: 'block'
  },
  search: {
    position: "relative",
    borderRadius: theme.shape.borderRadius,
    backgroundColor: fade(theme.palette.common.white, 0.15),
    "&:hover": {
      backgroundColor: fade(theme.palette.common.white, 0.25)
    },
    marginLeft: 0,
    width: "100%",
    [theme.breakpoints.up("sm")]: {
      marginLeft: theme.spacing(1),
      width: "auto"
    }
  },
  searchIcon: {
    width: theme.spacing(9),
    height: "100%",
    position: "absolute",
    display: "flex",
    alignItems: "center",
    justifyContent: "center"
  },
  inputRoot: {
    color: "inherit",
    width: "100%"
  },
  inputInput: {
    paddingTop: theme.spacing(1),
    paddingRight: theme.spacing(1),
    paddingBottom: theme.spacing(1),
    paddingLeft: theme.spacing(10),
    transition: theme.transitions.create("width"),
    width: "100%",
    [theme.breakpoints.up("sm")]: {
      width: 120,
      "&:focus": {
        width: 200
      }
    }
  },
  loggedIn: {
    width: "100%",
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    paddingLeft: "2rem"
  },
  navlinks: {
    // [theme.breakpoints.down("sm")]: {
    //   position: 'absolute',
    //   backgroundColor: "rgba(0,0,0,.7)",
    //   top: '0%',
    //   right: '0%',
    //   width: '100vw',
    //   height: '100vh'
    // },
    "& a": {
      color: "white",
      fontWeight: "bold",
      fontSize: "1.5rem",
      textDecoration: "none",
      marginRight: '1rem',
      padding: ".5rem",
      borderRadius: "15px"
    },
    "& a:active": {
        backgroundColor: "rgba(0, 0, 0, 0.5)"
    }
  },
  hamburgerMenu: {
    display: 'none',
    [theme.breakpoints.down("sm")]: {
      display: 'block',
      marginLeft: "auto",
      backgroundColor: "white",
      color: "#715AFF"
    }
  },
  logOutButton: {
    // [theme.breakpoints.down("sm")]: {
    //   display: 'none'
    // }
  }
});

export default styles;


text:
Q: Run Application Command to open Terminal Question: What command do you type in to the "Run Application" box on ubuntu to open the terminal?

Info:
I'm having horrible horrible driver issues on my netbook. I might be able to solve some of these problems if I could just get to Terminal, but all I have is my keyboard, no mouse, so i need to know what command to type in to run application (Which I can get to with alt-f2) to open terminal.

A: The easiest is to use hotkey: CRTL+ALT+T

A: The command you are looking for is:
gnome-terminal

You can also run bash, selecting "run in terminal"