How do I use goto and make my Log in page the first thing the user sees?

Question: Does anyone know what I'm doing wrong? My homepage is at src/routes/+page.server and I want users to be redirected there after they log in/sign up. Also, when I run this website, the first thing I see is the home page. Is there a way to not have the homepage be seen before logging in? I am using Supabase for user auth. I was suggested to verify in hooks.server.js that the user is not logged in and redirect to the login/sign-in page. Another idea is to add a popup login window on the home page. If the user isn't logged in, the home page won't work fully and will ask the user to log in. After logging in, a cookie is sent and stored. You can determine if the user is logged in by checking for the presence of a correct cookie – if found, the user is logged in; otherwise, they're not. But, I don't know how to do any of these things work.

// src/routes/+page.svelte - my homepage

Welcome to studyclock!

 Start a study session!

Set your daily goal!  {goalHours} hr {goalMinutes} min

Hours
<input type="number" id="hoursInput" bind:value={goalHours} bind:this={hoursInput} min="0">

Minutes
<input type="number" id="minutesInput" bind:value={goalMinutes} bind:this={minutesInput} min="0" max="59">

<button on:click={setGoal}>Set Goal</button>

{#if completed}

Great job! You completed your daily study goal!

{/if}

 Total study time: {formatStudyTime(totalStudyTime)}

// src/routes/login/+page.svelte

Login

    <form class="loginForm" on:submit={handleSubmit}>
        <input type="email" bind:value={email} placeholder="email@example.com"/>
        <input type="password" bind:value={password} placeholder="Password"/>
        <button type="submit">Login</button>
    </form>
    Not a member? Sign up!

// src/routes/signup/+page.svelte

Comment: in any page that requires a user to be logged in, check if the user is logged in, if not, "goto" login page (sorry, I don't know svelte enough to write actual code, but that's the general idea)
Comment: Here is a radical idea: Make the homepage the login-page. And if the user goes to the "home page" while they are logged in, redirect them to the app.
Answer: I will suggest you the solution, but not actually will be referencing to a Supabase setup.
You can check if the user is logged in on your home page load function, if not redirect it to the login page.
// src/routes/+page.server.ts

import type { PageServerLoad } from './$types'
import { redirect } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ cookies }) => {
    // getUser is some method that determines if the user is logged or not based on a cookie, usually checking a session on DB.
    const user = await getUser(cookies);

    if (!user) {
        // User not logged in.
        throw redirect(302, '/login');
    }

    return {
        // Return your home page data here.
    }
}

And in your login page a similar, but contrary, approach, if the user is already logged redirect it to the home page.
// src/routes/login/+page.server.ts

import type { PageServerLoad } from './$types'
import { redirect } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ cookies }) => {
    // getUser is some method that determines if the user is logged or not based on a cookie, usually checking a session on DB.
    const user = await getUser(cookies);

    if (user) {
        // User already logged.
        throw redirect(302, '/');
    }

    return {
        // Return your login page data here if needed.
    }
}

My actual suggestion to solve your problem is that you should leverage the load patterns offered by SvelteKit by using the load functions.
SvelteKit offers an example similar to what I propose you by using redirects. You should check the documentation for data loading in general.


Prove that if $K$ is compact, then $J^{+}(K)$ is closed.

Question: I'm trying to solve this problem and I don't know how to start

Let $M$ be a connected time-oriented Lorentz manifold of dimension $n$.
  Let $$J^{+}(K)=\{q\in M: \text{there is a $p\in K$ with $p\leq q$}\}.$$
  $p\leq q$ means that there exist a causal curve from $p$ to $q$.
  Suppose that for every $p\in M$, the sets $J^{+}(p)$ and $J^-(p)$ are closed. Prove that if $K$ is compact, then $J^{+}(K)$ is closed.

I tried to prove that a convergent sequence un $J^{+}(K)$ converge to a point in $J^+(K)$, but nothing...
Comment: Please define your terms? What is $M$, $J^+(p)$ and $J^-(p)$?
Comment: Sorry, I've forgotten it. Done. @HennoBrandsma
Answer: My last comment was not very accurate.
Edit:
Actually my comment is not so useful ... I think that the argument goes in this way: Consider $q \in \overline{J^{+}(K)}$, so, for any $w \in I^{+}(q)$ we have that $I^{-}(w) \cap J^{+}(K) \neq \emptyset$. Therefore by taking a sequence $\{q_{n}\} \subset I^{+}(q)$ such that $q_{n+1} \ll q_{n}$ and $q_{n} \rightarrow q$. We can consider the following subset of $K$: $K \cap J^{-}(q_{n})$ which will not be empty and nested, so, $\cap_{n \in N}(K \cap J^{-}(q_{n})) \neq \emptyset$ and use a point $p$ of this set to show that $q \in J^{+}(p) \subset J^{+}(K)$. There are some hidden steps in here, but if you work it out it will be a good exercise.


How do you tell if you should use a one-tailed test or a two-tailed test in a t-test?

Question: For example, how would you decide between which tailed test to do in the following experiment:
Ethanol dilutions were made with different proportions and Daphnias were submerged in them to collect their heart rates. The Daphnias were also submerged into beakers with different temperatures.
My null hypothesis was that the Daphnia will not be affected by the changing variables and if they are, it is due to a purely kinesis response (caused by chance).
My alternative hypothesis was that Ethanol would decrease the heart rates of the Daphnias as the dilution concentrations increase. I assumed this because Ethanol is a respiratory and nervous system depressant that acts as an anesthetic and potentially leads to death after an overdose. I also assumed that the Daphnias' heart rates would fall and become steadier in lower temperatures because they usually inhabit cooler, freshwater habitats.
Comment: The body text of your question is very unclear, but in respect of your title -- it depends on whether your alternative hypothesis is one sided or two sided ... and we can't really tell you what to hypothesize.
Comment: I must agree with the first comment by Glen_b. However, even if we cannot tell you what to hypothesize, it could be beneficial for you to learn more about both options. See, for example, [here](http://www.ats.ucla.edu/stat/mult_pkg/faq/general/tail_tests.htm) (sections "When is a one-tailed test appropriate?" and "When is a one-tailed test NOT appropriate?"). By the way, your question should be quite popular in general so there is quite likely a lot of material about it. Introductory statistics textbooks should have some discussion on the topic.
Answer: If your result was significant in either direction, would this be note-worthy? In other words, if the data shows that Ethanol actually increases, rather than decreases, the heart rates of the Daphnias as the dilution concentrations increases would this be an interesting result worthy of being noted? If so, do a two tail test.
If it is not possible that Ethanol actually increases the heart rates of the Daphnias, based on past research in the field or common knowledge, do a one-tail test. Of course, due to random chance, the data could suggest Ethanol increases the heart rates. In this situation, we can chalk this up to error hence not note-worthy.


cl : Command line error D8021 : invalid numeric argument '/Wno-cpp'

Question: I met a problem in windows 10 CMD, when I try to compile a .py file for coco dataset, then the problem occurred. The information can be see below:
    running build_ext
    building 'pycocotools._mask' extension
    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IE:\Anaconda2\Lib\site-packages\numpy\core\include -I../common -IE:\Anaconda2\include -IE:\Anaconda2\PC /Tcpycocotools/_mask.c /Fobuild\temp.win-amd64-2.7\Release\pycocotools/_mask.obj -Wno-cpp -Wno-unused-function -std=c99
    cl : Command line error D8021 : invalid numeric argument '/Wno-cpp'
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\amd64\\cl.exe' failed with exit status 2

I have searched for some information to solve it,but I only do it in my cmd line,not with Visual studio,perhaps the system really use it,but I also set it by " SET VS90COMNTOOLS=%VS140COMNTOOLS%",this is my version,but it doesn't work.
Thank you for advice!
Comment: sounds like gcc options slipped in the MSVC command line...
Comment: I would search through the config files to remove those `-Wno-xxx` options from the scripts. There may exist some more config options, but those are generally hell, yes, designed for linux and ported to windows, with minimum effort.
Comment: @Jean-François Fabre  Because this job was did in windows system, it seems more likely to run in ubuntu? Right? Here is the website: https://github.com/weiliu89/caffe/tree/ssd/data/coco
Answer: Please, refer to the following updated repo that solves the cl : Command line error D8021 : invalid numeric argument '/Wno-cpp': https://github.com/philferriere/cocoapi
Clone the repo and navigate to the PythonAPI folder and run python setup.py install. Make sure that you have downloaded the latest build-in tools for Visual Studio https://www.scivision.dev/python-windows-visual-c-14-required/


Uncaught exception thrown in shutdown

Question: I am trying to solve this issue from last three days. Searched lot regarding this issue but not getting any solution.
I have also visited these links link1 link2 or duplicate questions
This error is occurring at the time of installation, I am installing Drupal7 on linux
I am using PostgreSQL 9.4.8 database, php PHP 5.5.9
The database user has granted all permissions
following are the exceptions
first exception
    Uncaught exception thrown in shutdown function.

    PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "semaphore" does not exist LINE 1: DELETE FROM semaphore ^: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 2108550473576798c2ab0410.91648409 ) in lock_release_all() (line 269 of /var/www/html/rentspeak/includes/lock.inc).

second exception
Uncaught exception thrown in session handler.

PDOException: SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "sessions" does not exist LINE 3: sessions sessions ^: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) ); Array ( [:db_condition_placeholder_0] => AqE0DsCH1bG6qk3nMspgcEW1J_FUDbF15vNkX5nSdUU [:db_condition_placeholder_1] => ) in _drupal_session_write() (line 209 of /var/www/html/rentspeak/includes/session.inc).

Answer: I just tried to setup a fresh Drupal 7.44 with Postgresql and I haven't encountered any issues. The setup went fine. Here are the steps I did.

$ su root - Switch to root user.
$ su - postgres - Switch to Postgres user. Note that you need to be root first before doing this.
$ createuser --pwprompt --encrypted --no-createrole --no-createdb gerald - Create a new user called gerald.
$ createdb --encoding=UTF8 --owner=gerald drupal - Create a new database called drupal.
Run the installation and select the Postgresql type.

Another way to determine the culprit is by reading the logs.
For Postgresql
$ sudo tail -f /var/log/postgresql/postgresql-9.3-main.log. In you case it should be $ sudo tail -f /var/log/postgresql/postgresql-9.4-main.log.
For PHP (if you're using Apache)
$ sudo tail -f /var/log/apache2/error.log
Additional Troubleshooting
Also check if there is a problem with timeout in PHP. You may want to increase to default timeout settings.
My stack:
gerald@von-viel ~/ $ psql --version
psql (PostgreSQL) 9.3.13
gerald@von-viel ~/ $ php --version
PHP 5.5.9-1ubuntu4.17 (cli) (built: May 19 2016 19:05:57)

Note: I am using the default configuration of Postgresql.
Hope this helps!

Uncaught exception thrown in shutdown


MultiGroup Factor Analysis CFI gets better as model gets more restricted

Question: I have 2 data sets from two different groups (GRP1 N = 130. GRP2 N = 471)
I am trying to check to see if the scale is invariant across groups but im coming up with a problem that the CFI is
getting better as we add constraints. To keep it short I'll only include the results of the CFI and the RMSEA
I first ran the CFA for all the data combined using the code below
psc <- "PSC =~ X3 + X5 + X6 + X7 + X9r + X10r + Xrr"

# Fit the model Standardizing on the latent variable
fit <- cfa(psc, data = psc, meanstructure = TRUE, std.lv = TRUE)

Which gave me the following results
CFI 0.972, RMSEA = 0.062 CI (0.038 - 0.087)

I then ran the CFA twice on the two different groups to confirm MGCFA could be used
GROUP 1 CFI = 0.992, RMSEA = 0.034
GROUP 2 CFI = 0.958, RMSEA = 0.076

I then ran the invariant testing with the below results for CFI
Configural invariance 0.966
Metric Invariance 0.963
Scalar Invariance 0.967
Residual Error Invariance 0.971

Can anyone explain to me why this is happening? Is it just because my GRP1 is very small.
Comment: Can you confirm that you're using the generic ML estimator (from your code, it looks like you are)? Using a robust estimator (e.g., MLR) can sometimes cause this to happen, when the scaling parameter changes between levels of invariance. See https://stats.stackexchange.com/questions/234232/testing-measurement-invariance-with-robust-estimators-yields-bizarre-improved
Answer: One possibility is that the change in chi-square associated with increasing model constraints is not larger than the increase in the degrees of freedom associated with the addition of those constraints.
Consider the equation for calculating CFI:
$$
CFI = 1-\frac{max[(\chi_M^2-df_M),0]}{max[(\chi_M^2-df_M),(\chi_I^2-df_I),0]}
$$
where $\chi_M^2$ is the chi square statistic for the model being tested and $\chi_I^2$ is the chi square statistic for the independence model.
Note that the numerator is governed by the difference between the $\chi_M^2$ and $df_M$. Thus, if the model fit is only slightly worsened by adding constraints, the chi-square statistic may increase at a slower rate than the degrees of freedom earned by imposing said constraints. The result? A numerator that gets smaller and a CFI value that gets larger (with an upper limit of 1).
This property is the reason why CFI serves as a parsimony-adjusted fit index as it penalizes you for including paths that do not add much value in terms of reproducing the observed covariance matrix.


When hook_field_info_alter is invoked?

Question: I am trying drush cc all, but no luck.
https://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook_field_info_alter/7
I need to programmatically hide a field and thinks that this is place to go.
Answer: It's invoked in several places. It happens in _field_info_collate_types(), which is called from

field_info_cache_clear()
field_info_field_types()
field_info_formatter_types()
field_info_storage_types()
field_info_widget_types()

So there's a fairly large surface area for invocation.
hook_field_info() is for providing metadata about fields, though, so using it to programatically hide a field is doomed to failure. You simply don't have that option in the info hook.
Depending on what you mean by "hide" you'll either want to implement a form alter hook (to remove a field from a form), or a preprocess/view hook to hide it from being rendered, or maybe both. Obviously YMMV if you mean something other than those options.
Comment: I mean set programmatically what is possible to do via Manage Display -> Format (hidden)
Comment: You'll need to ask that as a separate question, it's not related to what you've asked (which is simply where the hook is invoked from)

When hook_field_info_alter is invoked?


Why does converting data into a Time Series change the values and how do you change them back?

Question: I imported data and converted into a simple time series.
  claims <- read.csv("C:/claimsrawdatabyweek.csv")

   # time series with 52 data points per year
   em<-ts(claims[,4],start=c(2009,44),frequency=52)

It changed the values from
3496
2453
2311
2559
3149
5103
4951
4165
4340
4868
3862
2811
3583
3469
3171
2660
2772
2223
2115

to
138
105
97
109
130
155
154
146
148
153
142
119
139
137
132
112
116
93
82

How do I calculate what these new values indicate?
I am using the tbats forecast function   fitem<-tbats(em)  and it is giving me forecast values that are base on these numbers. Even when I don't convert the data and use tbats, it automatically converts to these numbers.
Stated simply, I must convert the new ts values into the actuals. Why does 3496 equal 138?
Any help is appreciated.
Comment: Can you post a small, reproducible example with a subset of data? What does the original csv file contain? Note that if your data actually contain commas within the numbers, that might be a problem for a *comma separated value* format.
Answer: I found that the the data had imported the variables from Excel as factors str(claims). When the time series function read the variables as functions, it assigned a unique digit to each value, one which was virtually untranslatable to the original. I fixed the problem by changing the class of the variables to a integer.
Comment: Argh, no. The REASON that R has imported your numbers as factors is because of the embedded comma. Changing them to integers just means you're swapping one meaningless result for another. What you SHOULD do is go back to your Excel sheet, remove the formatting, re-export and re-import your data.
Comment: Hong Ooi, good reason. I changed the question to better reflect the actual data I put into R (removed the comma).


How do I translate view's page path alias that has a dynamic path?

Question: I have a view that has a dynamic path and I want to create a path alias for each language installed on my site. Following the answer on How do I translate view's page path alias? I'm able to create a path alias when no dynamic path is involved in the view, but when a contextual filter with dynamic path is in the view I can't find how to create the path alias.
The view is a simple view like this:

So, how do I translate view's page path alias that has a dynamic path like <code>/jobs/%</code> ?
Comment: @NoSssweat How do you think that I should create the alias? /jobs/% ?
Comment: I guess, worth a try.
Comment: @NoSssweat is not working, can you try on your side to see if is something here in my environment?
Comment: Didn't work, I got `Either the path '/taxonomy/term/%' is invalid or you do not have access to it.`
Answer: Views pages generate routes including route parameters for contextual filters. So you could add for each language a duplicate page, set a language specific path and inherit all other properties from the master display.
But as the routing system is not language specific this has some shortcomings. You get multiple language prefix/route path combination, which is not good for SEO and makes it difficult to build outgoing links.
Language specific path handling is outside of the routing system. The standard tool for this is path aliasing, so you would need to set for each dynamic value and language combination an alias in the lookup table. Don't know if you can generate them with Pathauto, but I wouldn't recommend it anyway in this case, because the path has a clear pattern you can easily transform in a custom path processor to match the internal view's page display route.
Comment: Yes, exactly, you need tagged services. A path processor usually contains two, inbound and outbound. More important to start with would be inbound to get the translated path working you enter in the browser.
Comment: Thanks for your answer, is not possible with pathauto, or at least I can't find how to do it. I was thinking in generate with some custom code an alias for each possible combination. It seems to be one way, and I'm trying to do something similar to path_alias_xt tagging a service with path_processor_outbound and it seems to work, I'm doing tests now. Do you think that using a service tagged with path_processor_outbound will works fine?
Comment: Thanks for the detailed explanation. Would be nice if there where some sample code to help solving the issue.
Answer: For the moment the only solution that is working for our team is implementing the Inbound and Outbound Processor plugins to allow you to interfere with the process of processing incoming and outgoing URLs.
You can check an example in the PathProcessorAlias page and there is a good article in Russian named Drupal 8: Inbound and Outbound Processor (The automatic translation of Google Chrome is working fine for this article)
Another good article talking about how this works is How to hide Order ID from commerce checkout process in Drupal 8
Answer: Even this is an old post, I'm still struggling with this use case in many projects. As depicted in previous answers and comments the solution is both, a combination of path alias (core) and a path processor plugin. The Translate Views Path module provides the proper path processor plugin, so you can go and add the path alias for your language using % wildcard as usual.
The only caveat is, for example, if you are using term's name (and probably any other entity) as your argument. If so, you must also include the Taxonomy term: Translation language condition to properly match the translated term name and remove the criteria validation from the context filter in order to work, since the validation criteria and the context filter use the entity original language instead the one selected by the user.


How to pass redux props to styled component in react typescript

Question: i'm pretty new to typescript and there's something that is not very clear to me.
I'm trying to pass a prop to styled-component file, the prop arrive from redux using a selector, but seems that is not working and i'm not able to log values in styled component cause to wrong syntax.
Here's my code so far:
type ButtonProps = {
  title: string
  reducerName: string
  flowName: string
  actionType: string
  disabled: boolean
  route?: string
  customAction?: string
  id?: number
  active?: string
  isActiveBtn?: any
  isActive?: string
  onClick: () => void
} & StyledButtonProps

const MyButton: React.FC<ButtonProps> = ({
  id,
  title,
  customAction,
  actionType,
  reducerName,
  flowName,
  route,
  ...rest
}) => {
  const dispatch = useDispatch()
  const navigate = useNavigate()

  const isActive = useSelector(selectType)
  const [active, setActive] = useState('')

  const onClick = useCallback(() => {
    setActive(title)
    dispatch(
      createAction<ButtonActionPayload>(customAction || actionType)({
        id,
        title,
        flowName,
        reducerName
      })
    )
    route && navigate(`${route}`)
  }, [
    dispatch,
    customAction,
    actionType,
    title,
    reducerName,
    flowName,
    route,
    navigate,
    id
  ])
  return (

  )
}
export default MyButton

and here the styled component:
import { Button } from 'antd'
import styled from 'styled-components'
import styledMap from 'styled-map'

export type StyledButtonProps = {
  borderColor: string
  borderType: string
  buttonColor: string
  buttonBgColor: string
  margin: string
  paddingRight: string
  paddingLeft: string
  variant: string
  isActive?: string
}

export const StyledButton = styled(Button)

Solution
Pass both an isActive and title prop to the styled button and fix the color string value.
const StyledButton = styled(Button)

Answer: Change the props name isActiveBtn={isActive} to isActive={isActive}
or
if you want the props name as isActiveBtn, fix all the styled component isActive value to isActiveBtn.
import { Button } from 'antd'
import styled from 'styled-components'
import styledMap from 'styled-map'

export type StyledButtonProps = {
  borderColor: string
  borderType: string
  buttonColor: string
  buttonBgColor: string
  margin: string
  paddingRight: string
  paddingLeft: string
  variant: string
  isActiveBtn?: string
}

export const StyledButton = styled(Button)


How can I test if a website is infected with malware?

Question: Some friends of mine have a website (www.kennelsoffie.dk) and I'm trying to help them when there is any trouble. However this time I, can't figure it out. When I visit the site using Google Chrome, I'm presented with a warning page claiming that the page that I'm trying to visit contains elements from stopssse.info.
I don't know any PHP, so I simply downloaded the complete website including backups of the database (which are .sql files). Then, I searched all the files for stopssse, but I didn't find anything.
I also tested the site with siteadvisor.com it says "We tested this site and didn't find any significant problems".
Can PHP hide a reference to the malware site so I cant find it with a simple search? If so, how can you find it?
Answer: I found this in the generated source

It was right below the body tag, it's not in the actual page source, it's being added by obfuscated javascript
edit: if you look at the bottom of http://www.kennelsoffie.dk/includes/jscript.js you'll see a really odd looking javascript function. That's the obfuscated javascript function I was telling you about. It starts with
function lIIlOlIllI1000llII10l0OIIIlIOlIOI1O010l0(O00I10I0l00I0IOIO1Ol10O0Ol1Il1lI10OI00Il){var

Best bet is to find and remove it.
Comment: +1 Definitely the culpret want to remove it and also importantly find out how it got in there.
Comment: Yes good point, I imagine that because it's powered by php fusion that there is some security hole in the product itself, it's worth checking whether your version is up to date, you may also be able to replace all the files with the exception of the main configuration file without losing any content.
Comment: Web Developer toolbar in firefox allows you to see the generated source code.
Comment: Firebug is also quite useful for that
Comment: Thank you very much. That did the trick. How did you did you see the generated source? If i right clic in the browser and picked show source I didnt that part of the code.
Answer: Your are most probably dealing with XSS attacks.
In that case, two steps :

Scan the DB, looking for "scripts" tags, and get rid of them.
Hire a guy who knows PHP to fix the holes in your data input and set some efficient sanitizing policy.
Answer: The malware might not be on the site, but might be coming from material brought in from external sources, such as advertisements.
Answer: If the site was "infected" via cross-site scripting, then what you have is probably a user-submitted comment somewhere that contains something like this:

But note that there are many variations that attempt to hide the fact that an external script is executed, and which may also modify the source URL, causing your simple string search to fail.
Answer: The version of PHP-Fusion that's running on the site appears to be v6.01.3, which looks to be a pretty old version, so it would probably be a good idea to upgrade that.
There seems to have been quite a few security advisories for PHP-Fusion, including a number of SQL injections issues.
Full list of advisories for PHP-Fusion here: http://secunia.com/advisories/product/5291/?task=advisories
Answer: Look for any peculiar files in the actual directories. There may be a file that was uploaded via an unsecure upload-form that writes additional data to the output. Tell your friend to change his account information, and start reviewing the security of his site.
Answer: It's there, check the PHP files (search for stopssse).
Answer: In the general case, looking for obfuscated javascrot, this tool is often useful: Wepawet


Count Ifs for Unique Values based on Unique Name

Question: I have a list of records submitted by customers and my list of records contains duplicate submissions.
What formula can I use in a macro to count the list of unique records based on each customer?
See my example data
Record Name       Submitted By           Status
Lead-123           Peter H               Rejected
Lead-495           Carlos Sinbad         Rejected
Lead-496           Carlos Sinbad         Approved
Lead-101           Timothy Johnson       Approved
Lead-421       Timothy Johnson       Approved
Lead-421       Timothy Johnson       Approved
Lead-421       Timothy Johnson       Approved
Lead-421       Timothy Johnson       Rejected
Lead-393       Derik Fauster         Recalled
Lead-393       Derik Fauster         Approved
Lead-422       Derik Fauster         Rejected
Lead-422       Derik Fauster         Rejected
Lead-422       Derik Fauster         Rejected

What I want
# of Unique Records Submitted     Submitted By
1                                 Peter H
2                                 Carlos Sinbad
2                                 Timothy Johnson
2                                 Derik Fauster

I have tried this
Sub CountUniqueValues()
Dim LstRw As Long, Rng As Range, List As Object
LstRw = Cells(Rows.Count, "A").End(xlUp).Row
Set List = CreateObject("Scripting.Dictionary")

For Each Rng In Range("A2:A" & LstRw)
  If Not List.Exists(Rng.Value) Then List.Add Rng.Value, Nothing
Next

MsgBox "There are " & List.Count & " unique values in column A from row 2 down."

End Sub

But I can only get the unique records for Record Name and I can't tie it with a unique Submitted By.
Comment: use a pivot table.
Comment: I have a list of over 1000 records.

And when I do create a pivot table I'll have to carry those values onto another worksheet.

I'd rather use a formula so that I can simply place my values onto my intended worksheet.
Comment: Then please show what you have tried and where it errors so we can help you overcome the error.  Stack Overflow is not a code for me site.
Comment: `
Sub CountUniqueValues()
Dim LstRw As Long, Rng As Range, List As Object
LstRw = Cells(Rows.Count, "A").End(xlUp).Row
Set List = CreateObject("Scripting.Dictionary")

For Each Rng In Range("A2:A" & LstRw)
  If Not List.Exists(Rng.Value) Then List.Add Rng.Value, Nothing
Next

MsgBox "There are " & List.Count & " unique values in column A from row 2 down."

End Sub
`
Comment: I can get the list of unique values for Record Name but I can't tie it into the Submitted By field.
Comment: Please [edit] the post with clarifications, not in the comments.  Comments cannot be formatted.
Comment: This is exactly what pivot tables are for.  Using another method is like using a hammer for screws.  Can be done but not logical.
Comment: If you really don't want to use a pivot table, set up a query and run SQL on your data.
Comment: I think you've almost got it.  You just need to change your dictionary key value pair to `List.Add Rng.Value, Rng.Offset(1,0)`  Which would tie the unique record with the person submitting it.  Then you could loop over your dictionary to pull each key and value.
Answer: I have answered my own question. I am able to count unique records based on a name criteria.
Below is my modified code that captures all the data in my range and counts the records accordingly.
Dim lnNumber2 As Long
Dim rnFormula2 As Range

With ActiveSheet
    lnNumber2 = .Range("B5000").End(xlUp).Row
    Set rnFormula2 = .Range("I15:I" & lnNumber2)
    rnFormula2.FormulaR1C1 = _
        "=SUMPRODUCT(((Sheet2!R2C2:R5000C2=Sheet1!RC[-7]))/COUNTIFS(Sheet2!R2C1:R5000C1,Sheet1!R2C1:R5000C1&"""",Sheet2!R2C2:R5000C2,Sheet2!R2C2:R5000C2&""""))"

End With


Is is possible to get a permanent URL to a file uploaded to Google drive?

Question: I can't find the answer to this in the API docs or elsewhere.  I see in the docs says you can get a downloadURL of a file, but it refers to it as a 'short lived URL'.  What does that mean?
I need to upload images and get a permanent URL of that image that is the direct URL than can be embedded into emails or web docs etc.  Is that possible?
Thanks
Answer: Yes, you can get a permalink to any file hosted on Google Drive in a public folder. Just note the folderID:

and paste it to the following URL:
http://googledrive.com/host/<folderID>/<filename>
or you can create a short custom alias using G Drives: http://gdriv.es/<alias>/<filename>
Comment: This feature will be discontinued after August 31, 2016 see http://googleappsupdates.blogspot.cz/2015/08/deprecating-web-hosting-support-in.html
Comment: That sucks, I just needed this today Sept 2nd :D
Comment: me too... damn!
Comment: Note: The folder has to be shared as "Public on the web" ("Anyone can find and view"), not just "Anyone can view", or it won't work.
Comment: That's great! Do you have any ideas how to implement the same on Dropbox?
Answer: https://developers.google.com/drive/v2/reference/files#webContentLink
downloadUrl is short lived, but webContentLink is a permanent link.  It's odd that one is a URL and the other is a "link", but I guess it probably has to do with the additional query params in the strong.  Maybe that makes it not just a URL?  :)
That property is only available for files that are publically readable, so you may have to use the SDK/API to set the permissions first.
Answer: In case someone encounter the same problem and don't want to do with deprecated Google Drive solution above and requires frequently changed files with exact same url, you can use Dropbox. Steps:

Download the program and share a folder (tutorial)
Copy a file into that folder; wait for sync with Dropbox
Go to your dropbox.com account
Share your file by button, get something like:
https://www.dropbox.com/s/d28d8scvr3rfy48/foo.exe?dl=0
Rename it to:
https://dl.dropboxusercontent.com/s/d28d8scvr3rfy48/foo.exe?dl=0

Now you have a public, unchanged url for all your foo.exe changes.
Enjoy, don't waste time with sites offering you file hosting and they change the URL for same files.
Comment: This solution does not work anymore. I think dropbox in general changed. Overwriting a file changes the url
Answer: If you share a file publicly in GDrive, you can use the following link to make the file download directly:
https://drive.google.com/uc?export=download&id=FILEID
The problem happens when you want to change the file (for version controlled download, in instance) and keep the same downloading link.
You can use a URL Shortener like bitly.com and use a Branded Bitlink to change the destination URL keeping the input URL.
I hope it works, good luck!
Answer: It seems if you have file ID you can access it with such url:
https://drive.google.com/open?id=file-id-here

If file is public, you'll see it immediately but if not, you're be asked to login
Answer: I don't know how often this changes but I was looking for a dynamic solution where I wouldn't need to manually upload to another site and the provided solutions weren't working.
Here's the url that worked for me:
https://lh3.google.com/u/0/d/<file_id>
Where file_id is the getId() using the google apps script drive API. Secondly the file must be shared publicly like posted previously
Secondly I imagine the lh3 are different cdn's though I cannot confirm since lh1/2 don't work and everything higher than 3 redirects to lh3
Comment: but how to make it work, with videos ```https://lh3.google.com/u/0/d/=m18```? @Maruf
Comment: Worked great for images. Thanks,
Answer: I don't know if such API for google drive exists, but I think you should also have a look at dropbox,
which will meet all the demands that you mention in your question.
Also there are some very cool applications developed just for dropbox, like pancake.io which lets you share links of text, html files, in an html page format.
that + permanent link is always there.
Answer: You can use gdriveurl.com, it got updated and now allows users to log in with their google drive account and share the list of files instantly, getting for each file "View" & "Download" short permalink.
There's also the old solution (login to Google Drive, set everything to "Public on web", copy share link, convert it into the gdriveurl.com textarea in the homepage), but it's just a waste of time, you should try "MyDrive" api.
Answer: Not sure if the link generated here is guaranteed to be permanent, but Google Drive Direct Link Generator does the job of generating a direct download link.
Just make sure your file's sharing setting is set to Anyone with the link
Comment: worked but after monitoring the http traffic in developer console I see the generated link is invalid and redirected to a valid link


If you colored every point of a circle 1 of 2 colors, is there always 2 same-colored points of distance $R$ apart?

Question: If every point on a circle of radius $R$ in $\mathbb{R}^{2}$ were colored one of two colors, is there necessarily two points that are of the same color and of distance $R$ apart? what about $>2$ colors?
On the $2$-color case, I'm thinking that if we have two points of different colors on the circle, say red and blue, then consider the chord of length $R$ from the blue point to another point on the circle. This new point must then be red. Continuing, we get a hexagon if I'm not mistaken, which doesn't help. But we can place another hexagon inscribed in the circle with the same colorings, ad infinitum. Intuitively, this leaves me to believe that there must be two points of the same color of distance $R$ apart on the circle due to some induction or something. I'm not sure! Does this hold for more than two colors?
Answer: Given the point $(\cos \phi,\sin\phi)$, colour it red if $\phi\in[0,\frac\pi6[\cup [\frac\pi 3,\frac\pi2[\cup [\frac{2\pi} 3,\frac{5\pi}6[$ and blue otherwise. This is just your hexagon repeated over an interval.
Answer: The answer to the question in the title is No. The circle is the disjoint union of six-element sets consisting of regular hexagon vertices. You can color the vertices of any such hexagon alternatively red and blue. Any two vertices of different hexagons cannot have distance $R$; therefore the chosen colorings do not interfer.


PostgreSQL - "Ten most frequent entries"

Question:
We've got a table with two colums: USER and MESSAGE
An USER can have more than one message.
The table is frequently updated with more USER-MESSAGE pairs.

I want to frequently retrieve the top X users that sent the most messages. What would be the optimal (DX and performnce wise) solution for it?
The solutions I see myself:

I could GROUP BY and COUNT, however it doesn't seem like the most performant nor clean solution.
I could keep an additional table that'd keep count of every user's messages. On every message insertion into the main table, I could also update the relevant row here. Could the update be done automaticaly? Perhaps I could write a procedure for it?
For the main table, I could create a VIEW that'd have an additional "calculated" column - it'd GROUP BY and COUNT, but again, it's probably not the most performant solution. I'd query the view instead.

Please tell me whatever you think might be the best solution.
Comment: I'd start with a view, doing GROUP BY etc. Will always have consistent data (is that important?) Do you need instant updates, or will once per day be fine too?
Answer: Some databases have incrementally updated views, where you create a view like in your example 3, and it automatically keeps it updated like in your example 2.  PostgreSQL does not have this feature.
For your option 1, it seems pretty darn clean to me.  Hard to get much simpler than that.  Yes, it could have performance problems, but how fast do you really need it to be?  You should make sure you actually have a problem before worrying about solving it.
For your option 2, what you are looking for is a trigger.  For each insertion, it would increment a count in the user table.  If you ever delete, you would also need to decrease the count.  Also, if ever update to change the user of an existing entry, the trigger would need to decrease the count of the old user and increase it of the new user.  This will decrease the concurrency, as if two processes try to insert messages from the same user at the same time, one will block until the other finishes.  This may not matter much to you.  Also, the mere existence of triggers imposes some CPU overhead, plus whatever the trigger itself actually does.  But unless our server is already overloaded, this might not matter.
Your option 3 doesn't make much sense to me, at least not in PostgreSQL.  There is no performance benefit, and it would act to obscure rather than clarify what is going on.  Anyone who can't understand a GROUP BY is probably going to have even more problems understanding a view which exists only to do a GROUP BY.
Another option is a materialized view.  But you will see stale data from them between refreshes.  For some uses that is acceptable, for some it is not.
Answer: The first and third solutions are essentially the same, since a view is nothing but a "crystallized" query.
The second solution would definitely make for faster queries, but at the price of storing redundant data. The disadvantages of such an approach are:

You are running danger of inconsistent data. You can reduce that danger somewhat by using triggers that automatically keep the data synchronized.
The performance of modifications of message will be worse, because the trigger will have to be executed, and each modification will also modify users (that is the natural place to keep such a count).

The decision should be based on the question whether the GROUP BY query will be fast enough for your purposes. If yes, use it and avoid the above disadvantages. If not, consider storing the extra count.


How to use strstr() in C to count keywords from another file?

Question: I am attempting to get my program to read strings from another file, parse them for certain keywords, and then add to a counting variable whenever they appear in the other file. However, I can't seem to get anything but the number of lines to count. What could I be doing wrong here?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// check that fp is not null omitted but needed
const char getLine[1] = "";
const char getFor[4] = "for";
char line[500];
int lineCount = 0;
int forCount = 0;
int x = 0;
int main() {
    FILE* fp = fopen("file.txt", "r");
    if (fp == NULL) {
        perror("Error opening file");
        return(-1);
    }
        while (fgets(line, 499, fp) != NULL) {
            strstr(line, getLine);
            lineCount++; //Essentially counting the number of lines in file.
        }

    printf("Line count is %d.\n", lineCount);
    memset(line, 0, sizeof(line)); //Resetting the memory of line.
    while (fgets(line, 499, fp) != NULL) {
        char *findFor;
        findFor = strstr(line, getFor);
        if (findFor != NULL) { //Attempting to count each time an instant of 'for' appears.
            forCount++;
        }

    }

    printf("For count is %d.\n", forCount);
    fclose(fp);
}

Comment: Is the keyword `for` in the line `"foobarforqux"`? in "`foobar for(qux`"? in `"foobar for qux`"? In the first case, `strstr()` is your friend. For the 2nd you'd have to also check if `"for"` is the very first thing of the line or preceded by whitespace and followed by "`(`". For the third the same applies, but the `"for"` must also be followed by whitespace and `sscanf()` would be your friend. But as I said in response to your previous question about basically the same topic, parsing C is not easy and would require to build an AST go get it right. You might want to use `libclang`.
Answer: The code is reading through the whole file to count the lines, but then trying to read through it again (without a rewind() / fseek()).  So on the second loop the file is at end-of-file.
It's not necessary to count the lines, and the "for"s in two separate loops, just do it in one.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// check that fp is not null omitted but needed
const char getFor[4] = "for";
char line[500];
int lineCount = 0;
int forCount = 0;

int main(  )
{
    FILE *fp = fopen( "file.txt", "r" );
    if ( fp == NULL )
    {
        perror( "Error opening file" );
        return ( -1 );
    }

    while ( fgets( line, sizeof( line ), fp ) != NULL )
    {
        char *findFor;
        findFor = strstr( line, getFor );
        if ( findFor != NULL )
        {
            // Attempting to count each time an instance of 'for' appears.
            forCount++;
        }
        lineCount++;
    }

    printf( "Line count is %d.\n", lineCount );
    printf( "For count is %d.\n", forCount );
    fclose( fp );

    return 0;
}

Also you're not counting the number of "for"s in the file, you're counting the number of lines with "for" in them.  If a line has multiples, it's just counted as one.


MonkeyRunner and MySQL

Question: I got a problem using MySQL with MonkeyRunner, need a help with MySQL Driver Name. The starting of my script is:
<code>#coding : utf-8

from com.android.monkeyrunner import MonkeyRunner,MonkeyDevice
from com.ziclix.python.sql import zxJDBC

db = zxJDBC.connect('jdbc:mysql://localhost/android','dani','123456','com.mysql.jdbc.Driver')
.
.
etc
</code>
Each time I got an error that com.mysql.jdbc.Driver not found even when using org.git.mm.mysql.Driver. I set classpath as following :
<code>export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java.5.1.10.jar
</code>
Any tips or hits?
Regards,,,
Answer: You need to include the relevant jar in the correct location.  There should be a libs folder where you need to put the jar.  It should be in the top level of your project folder, at the same level as the src and res folders.
Comment: You mean if my project in /home/..../Project
The I need to create a file /home/..../Project/lib and put that jar inside?
Comment: Take a look at the top answer here, it explains where to put the jar http://stackoverflow.com/questions/1334802/how-can-i-use-external-jars-in-an-android-project

MonkeyRunner and MySQL


Unknown formula for "z" in a textbook page describing Fisher's transformation

Question: From a chapter dedicated to the sampling distribution of Pearson's r:

What is this formula for z called? This seems to be the first time I'm coming across it, or maybe I've forgotten. And what is z here? It does not have the notch at its right end, so it must be not the z' described in the chapter.
Comment: [Standardization](http://stats.stackexchange.com/search?q=standardize) (the link has over 2000 hits on our site!).
Comment: "What we tell you three times is true" (compare the Bellman, in _The Hunting of the Snark_).
Comment: z is the z you are used to seeing which is computed as a statistic divided by the standard error of the statistic; z' (unfortunate choice of symbols) is the transformed value of r. The statistic z' is normally distributed (pretty much) and has a known standard error which is used to calculate z.
Comment: That's the formula to center a variable around its mean and scale it by its standard deviation.
Comment: The context doesn't seem crucial to your question. $z$ here is just a standard score or standardized variable based on subtracting the mean and dividing by the standard deviation. In context it's often taken to have a  Gaussian or normal distribution.
Comment: @NickCox - and by "table" they mean the table of values (area under the curve) for each z value? Since, as I read, it "standardizes" a variable so that its distibution assumes a mean of 0 and a standard deviation of 1?
Comment: @CopperKettle not exactly, it makes mean of your data equal to zero and standard deviation of your data equal to one.
Comment: Why use tables when your software should tell you the answer directly?  My usual (Stata) after `di normal(.841)` will show .79982603 and after `di normal(-.841)` will show .20017397. I think even MS Excel has similar functions.
Comment: @Nick You're correct, Excel does have such a function - in fact in newish versions of Excel there are several such functions -- e.g. in versions of Excel  of almost any vintage `normsdist` will do the standard normal.  (In R it would be `pnorm` for the cdf)
Answer: Subtracting the mean of a random variable and dividing the result by its standard deviation is called standardizing (or sometimes normalizing, though that's a somewhat overloaded term).
The result is sometimes called a z-score.
The same terms may sometimes be used even when estimates of $\mu$ and $\sigma$ are used instead.
Calling the result $Z$ (given as $z$ in the text you show) is simply a convenient (and conventional) label for the standardized variable. On the other hand, since the section is also talking about Fisher's transformation of the correlation (which was also called $z$), the author here has added the $'$ mark to the Fisher's transformed correlation to distinguish it from the first $z$. Calling the second thing $z'$ rather than $z$ is not conventional - they're both typically called $z$ but this usually isn't an issue because it's not usually the case that we need to talk about both at the same time.
When it does happen that both are present in close proximity - as here - it's necessary to in some way distinguish them (so its clear which we're talking about). [It's like if you're in a group of people talking, one of whom is called John Anderson and another person - John Baker - later joins in. Now you need to be clear about which John you mean when you say "John". You'll either start calling one by some other name (maybe one is often called "Johnathan" while the other isn't, or maybe you start calling them by their surnames) or add something to distinguish them, maybe calling them John A and John B. The $'$ on the second $z$ is for exactly this purpose, just to make clear which thing you're referring to - just as if you'd continued to call the first guy "John" but now called the second John "John B". This doesn't imply you'll call the second one anything but John the next time you meet him. Or to make the analogy more precisely match the situation, in the linked page we seem to have have been waiting around for John A to show up and so started calling the other John who was present "John B" right from the start, since everyone knows John A and will want to call him "John".]


Combining setTimeout with setInterval

Question: I would like to use polling to try and grab data from a backend service.  If the data does not appear after x seconds, I would like to cancel out and log an error to the console.
Is there an easy way to do this? I'd assume it's something close to the code below
Ex:
<code>// Keep polling for something every 2.5 seconds
const intervalId = setInterval(() => {
  const isFound = doSomePollingQuery();
  if (isFound) {
    window.clearInterval(intervalId);
  }
}, 2500);

// If the polling interval hasn't been found by 17 seconds,
// cancel it and output a message
setTimeout(() => {
  clearInterval(intervalId);
  console.log("Not found in time"); // Where should this be
                                    // moved to as it doesn't belong here?
}, 17000);
</code>
Comment: Why does the console not belong there?
Comment: Because it will run regardless of success
Comment: So you cancel the timeout in the interval
Comment: Then also cancel the setTimeout when ur Polling was successful?!?
Comment: I don't understand either of your comments, sorry
Comment: You clear the interval. So clear the timeout. It is the same thing. Store the timeout id. Clear it.
Comment: I still don't see how to do it. code example please?
Comment: `window.clearTimeout(timeoutId);` and `const timeoutId = window.setTimeout(...)`
Comment: I don't see how that ties in with the console.log and how that gets placed. Please use my example code to show me
Answer: <code>// Keep polling for something every 2.5 seconds
const intervalId = setInterval(() => {
  const isFound = doSomePollingQuery();
  if (isFound) {
    console.log("Found in time")
    window.clearInterval(intervalId);
    window.clearTimeout(timeoutId);
  }
}, 2500);

// If the polling interval hasn't been found by 17 seconds,
// cancel it and output a message
const timeoutId = setTimeout(() => {
  clearInterval(intervalId);
  console.log("Not found in time"); // Where should this be
                                    // moved to as it doesn't belong here?
}, 17000);
</code>
Comment: Seems to be working, thanks!  I do get compiler errors about using timeoutId before it was defined though, which I have to explicitly ignore

Combining setTimeout with setInterval


How to fix onclick Function is not working using JavaScript

Question: Anyone can help me? this is my problem. When I tried to click the button using this function $(".btn_cellophane").on("click",function(){}); I did not get any response or even the error. I guess the onclick function is not working. Here's my code below.
METHOD CALLING
$(".btn_cellophane").on("click",function(){
     alert("Tester true");
         if($(this).hasClass("btn-warning")){
              $(this).removeClass("btn-warning");
              $(this).addClass("btn-success");

              // add_amount_for_cellophane();

         }else if($(this).hasClass("btn-success")){
              $(this).addClass("btn-warning");
              $(this).removeClass("btn-success");

              // add_amount_for_cellophane();
         }
});

CONTENT DISPLAY
var html_cellophane = "";
$.each(data, function(key,product){

        $.each(product.sizes, function(pro_id,variant){

             if(variant.prod_type == 1){
                   var label = (variant.size+" "+variant.unit).toUpperCase();
                   var var_id = variant.variant_id;
                   var price = variant.price;

                       html_cellophane += '
'+
                                                'Cellophane ('+price+' pesos)'+
                                           '
'+
                                           '
'+
                                           '
'+
                                                 '<button type="button" class="btn btn-warning btn_cellophane" id="cp_id_btn" data-var_id="'+var_id+'" data-qty="'+1+'" data-price="'+price+'">1</button>'+
                                                 '<button type="button" class="btn btn-warning btn_cellophane" id="cp_id_btn" data-var_id="'+var_id+'" data-qty="'+2+'" data-price="'+price+'">2</button>'+
                                                 '<button type="button" class="btn btn-warning btn_cellophane" id="cp_id_btn" data-var_id="'+var_id+'" data-qty="'+3+'" data-price="'+price+'">3</button>'+
                                                 '<button type="button" class="btn btn-warning btn_cellophane" id="cp_id_btn" data-var_id="'+var_id+'" data-qty="'+4+'" data-price="'+price+'">4</button>'+
                                                 '<button type="button" class="btn btn-warning btn_cellophane" id="cp_id_btn" data-var_id="'+var_id+'" data-qty="'+5+'" data-price="'+price+'">5</button>'+
                                                  '
'+
                                           '
';

              }

         });

});

$('.btn_cellophane_div ').html(html_cellophane);

Comment: `.btn_cellophane` element does not exist at the time you're attaching the event. jQuery always returns an object, that's why the error isn't fired.
Comment: https://stackoverflow.com/questions/1359018/how-do-i-attach-events-to-dynamic-html-elements-with-jquery this might help you.
Comment: have you put your click handler in $(document).ready() ?
Answer: You've created the button dynamically. So while you are attaching the event listener the element doesn't exists till then. So you have to use event delegation for working the click event.
Just change your event listener like this-
$(document).on("click",".btn_cellophane", function(){});


evento do button em React.JS

Question: eu quero adicionar o grafico ao painel quando eu clicar no botão de acesso, como eu faço apra ele aparecer dentro do painel que eu estilizei sem colocar ele direto lá, só depois de clicar no button accessos???
import React, { useEffect, useState } from 'react';
import { Bar } from 'react-chartjs-2'

import { Container, Graficos, Gerar } from './styles'

// Components
import SectionTopBar from '../../components/SectionTopBar'
import NavigationBar from '../../components/NavigationBar'

const Dashboard = () => {

  const access = () => {
    //MANDAR ADICIONAR A FUNÇÃO CHART() AQUI
  }

  const [charData, setCharData] = useState({})

  const chart = () => {
    setCharData({
      labels: ['Jorge', 'Lucas', 'Ana', 'Antonio', 'Luiza', 'Matheus', 'Luana'],
      datasets: [
        {
          label: 'Acessos',
          data: [25, 30, 13, 9, 47, 10, 21],
          backgroundColor: [
            'rgba(6, 196, 131, 0.4)'
          ],
          borderColor: [
            'rgba(6, 196, 131, 1)'
          ],
          borderWidth: 1
        }
      ]
    })
  }

  useEffect(() => {
    chart()
  }, [])

  return (
      <Container>
        <Graficos>

          <Gerar>
            <button className="card" onClick={access} >

                <text className="textbtn" >Acessos</text>
                <text className="quantidade" >12.000</text>

            </button>

            </button>
          </Gerar>

             //ADICIONAR AQUI NO PAINEL

<Bar data={charData} />

        </Graficos>
      </Container>
  );
}

Answer: Nesse caso o ideal seria uma renderização condicional. Quando uma variável no seu programa for true, renderizar o gráfico.
Podemos fazer isso com o hook useState do React.
const Dashboard = () => {
  // Variáveis que vão armazenar o estado da página (Se o gráfico deverá ser mostrado ou não)
  const [displayChart, setDisplayChart] = useState(false);

  // Função para mostrar o gráfico ao clicar no botão
  const showChart = () => setDisplayChart(true);

  const chartData = {
    labels: ["Jorge", "Lucas", "Ana", "Antonio", "Luiza", "Matheus", "Luana"],
    datasets: [
      {
        label: "Acessos",
        data: [25, 30, 13, 9, 47, 10, 21],
        backgroundColor: ["rgba(6, 196, 131, 0.4)"],
        borderColor: ["rgba(6, 196, 131, 1)"],
        borderWidth: 1,
      },
    ],
  };

  return (

      ... Conteúdo da página
      <button onClick={showChart}>Acessos</button>
      {/* Renderização condicional - Se a variável displayChart for "true" o gráfico será renderizado */}
      {displayChart && <Bar data={chartData} />}

  );
};

evento do button em React.JS


Preventing users from deleting SQL data

Question: We just purchased a program that requires the users to have an account in the MS SQL server, with read/write access to the program's database.
My concern is that since these users will now have write access to the database, they could directly connect to the SQL server outside of the program's client and then mess with the data directly in the tables.
Is there anyway I can prevent access to the database while still allowing access via the client program?
Edit : SQL 2008 Express, can upgrade to SQL 2008 R2 Standard if needed.
Every workstation will need access due for people to log their hours/schedule. The workstations are locked down, so no one has osql, studio manager or anything like that which. However they could setup an ODBC datasource and then connect via Excel/Access.
Just thinking about this now, messing with the data is not the bigger concern anymore, there are privacy issues since everyone's rates of pay, etc will be in this system.
I agree it's a very poor design.
Comment: Can you get your money back? This sounds like a terribly-designed application.
Comment: Which version of SQL Server?
Comment: You had better make sure you have binary logging turned on (or whatever MS calls it in MSSQL world).
Comment: I wish I could get the money back (it wasn't cheap either). It was purchased without any consultation from me, but it's going to be a business critial piece of software for us. Payrole & Scheduling, hence the need for the security.
Comment: Your payroll/scheduling app requires every user to have write access to the database? That is the -opposite- of security.
Comment: Every user needs R/W access to the DB, then within the app they have the permissions on the specific sections. So if someone wants to by-pass the permissions in the app, they can just go straight to the DB. The access to the DB could be set to a dedicated account, but the password for that account must be in a plain text file on the workstation.
Answer: No.  If the users have read/write access to the database and they are able to connect to it not using the program, they could do something like UPDATE sometable SET attribute = NULL; and destroy your dataset, or make any arbitrary changes they want.
Unfortunately, SQL permissions do not have the capability to express the concept of normal vs. malicious changes made by people who otherwise have access, and I suspect denying them permission to update records would be somewhat self-defeating.
Much like Joel's comment, I'd be asking for a refund if this is a concern in your environment.  Keep frequent backups and logs ;)
If you have a way to prevent logins not using the application (eg. by restricting connections to a single source, if your application runs through terminal services or citrix), you could definitely use that to improve security.
Comment: That's what I was figuring, thanks for the confirming it.....I'm wondering if I published the application in our Windows Terminal server, if it would still connect to the DB correctly. Then I could limit the connection to only the terminal server. If that works, it will mean we have to buy another bunch of terminal server licenses but for the security it would be worth it.
Answer: I'm a little late on this, and I agree that you should point the blamethrower at the application's developers and I'd put my concerns in writing and get someone with political power to understand the risks, but I hope to give you some more options.
If I were really stuck, I would look into creating a trigger for the LOGON event. In the trigger, I would find a way to discriminate between what I'll call a "legitimate" logon and an "illegitimate" logon and stop the illegitimate ones from completing. Legitimate logons would be users connecting to the proper database with the proper application, plus any administrative logins, job logins, etc. that you might need. I'd be very careful when writing this, since it seems like a good way to lock yourself out of the server. BOL says that LOGON TRIGGERS are available in SQL 2008, I'm pretty sure that they are available in Express.
The problem with this tactic is that you might find yourself playing "whack-a-mole", where you exclude Excel and Access, then someone figures out how to write a quick vb.net application that lets them get in, then you block that, then someone modifies the connection string to change the application name, etc. The more knowledgeable your users are, the more difficult this would be to stop them. If you've got developers, they might see it as a challenge. I'd say that anyone who is aggressively trying to find a way around security controls, even if those controls aren't perfect) is a problem. (If I lock the screen door on my home, it's pretty obvious that I don't want anyone to come in. If someone uses a pocket knife to slash the screen and step in, they have certainly done something wrong.)
Another thing to do is to simply run a query on the DMVs to find users who are not playing by the rules. You can get user, host and application name information from the system DMVs. If you run the query periodically (once a minute or so) and save the results in a table, you can have a look every day (or week) and then go rap the bad actors on the knuckles. Or have HR do it.
Another thing to try is, if you have anything that looks for and reports on long-running queries, you can look for "weird" queries. I actually caught someone doing something once, while reviewing logs for problem queries. Often, inexperienced users that are poking around will run inefficient queries that either read a lot of data or cause long-duration blocks. Sometimes, if the application has a certain, definite "style" to the way it write queries, you can pick out queries that are written by someone (or something) else. IOW, to use a very contrived example, there is a big difference between:
select * from salary where employee = "me"
and
select * from salary order by salary_amount
To sum up:
Fixing the application would be best.
Preventing logins might be OK.
Trying to find violators after-the-fact might be all you can do.
Comment: I like the idea of DMVs, I'll have to look more into that. Any futher information you can quickly expand on for that? Haven't Googled it yet :)  I'm going to do a call with the vendor next week and walk them though how easy it is to get in as a normal user and then tell them they need to fix this and I'm recommending against deployment until then. It will still be deployed but at least the issues will be down in writing.
Comment: +1, this a good solution to a bad problem.
Comment: The TS solution will help prevent the unauthorized disclosure or damage from occurring in the first place, though.  I'd actually recommend both that and auditing, but this isn't an especially novel recommendation (eg. you should be able to audit no matter what).
Comment: You could schedule a job to run a query like "select session_id, login_time, host_name, program_name,login_name from master.sys.dm_exec_sessions where session_id > 50" and store the results in a table, somewhere. I would tweak the WHERE clause to eliminate more "known good" things, like program_name like 'Microsoft SQL Server Management Studio%' first. This is easier to handle if the client application is well-behaved and actually fills in the "program_name" filed when it creates the database connection.

Preventing users from deleting SQL data


Google sheets: publish some but not all worksheets

Question: I have a Google spreadsheet which compiles scheduling info for an event. The file has five worksheets. There are two worksheets which I want to publish to the web; the other three are for my use and to drive calculations.
I can see how to publish the entire file, and how to publish an individual worksheet. However, I cannot figure out how to publish say, sheet1 and sheet2 to a single document.
As a short-term workaround I have tried the following, which works after a fashion but I'm not a fan:

Create a new file with two sheets
Sheet1 uses an importrange call to grab the data from the original sheet1
Sheet2 uses an importrange call to grab the data from the original sheet2
I then publish the entirety of the new document

The finished product must be in Google Apps; that is a requirement I cannot dodge.
Answer: What worked for me is that after publishing the spreadsheet, copy the link, then through "Published content & settings" remove the check next to "entire document" and select the ones you want to share.
The details in the upper part of the window will disappear including the link, and the publish button will be green again "pressable".
Your copied link is still active, you can still use it, and only the selected sheets will be seen on the web. It is also modifiable; if you checked different sheets, web share will be updated accordingly.
Answer: Solution 1:
You can hide the sheets that you don't want to publish, and then publish the entire document:

Published sheet:

Solution 2:
You can publish selected sheets using the Published Content & Settings options on the Publish to the Web dialog box. In the dropdown menu you can select which sheets to include:

The published spreadsheet would look like this:

Note: It seems that the web page may not display all the selected sheets, only the first sheet. You can file a feature/bug request here:
https://support.google.com/a/answer/6284762?hl=en
Comment: Thank you! I tried that, but for some reason I do not see the tab selectors in the published view; instead I only see the first sheet. Tried it in Firefox and Chrome; same result.
Comment: Are some of your sheets hidden? Please unhide all sheets first before publishing. Also, you should click the ````Start Publishing```` white button instead of the ````Publish```` green button to publish the selected unhidden sheets.
Comment: Just tried it again, and I'm still not seeing those selector tabs
Comment: Do you have a sample of the sheet that you are working on so I can check?
Comment: https://docs.google.com/spreadsheets/d/1zmG4ZTOI78nWwIuJb-49AVm0bzLxQh12dNPBVpIgfA0/edit
Comment: Thanks. It's interesting that I can replicate the problem on the sample sheet, and it seems like a bug on the Sheets part. Anyway, a workaround for this is that you can hide the sheets you don't want to publish and then publish the entire document. That would publish only the unhidden sheets.
Comment: Same problem here: cannot publish selected tabs to the Web. Either all or one tab is published. The settings work against each other.
Answer: Adding to ibkhayyat:
You can append ?gid=sheet code number to the original entire-document link to set the landing sheet.
And, if you didn't copy that original entire-document link while it was there, instead of redoing everything, you can just use any of the links to individual sheets. Just delete &single=true from the end of the link address. You can also delete ?gid=sheet code number to get back to the original link, but you can also leave it to set the landing sheet with the respective sheet code number.


dual behaviour on passing referrer between http and https with 301 redirects

Question: We have a client that is using https but has two 301 redirects, first redirect from https to http, and second from http to https.
One of his referrers is sending from https referrer to https but the referrer parameter is not sent further to http.
Another referrer is sending from http referrer to https and curiously this referrer gets on to the first http 301 redirect and then further on to the second 301 https redirect.
I must mention that the referrers sites are NOT using any meta tags like .
Of course, our client does not have any access to any of the referrers sites.
The client needs the referrer parameter sent on through the redirects in all cases, but this does not happen.
I am completely overthrown by this behavior and would like to know if there are others that have encountered this kind of situation, and, if any, what solution/solutions might there be for this.
Answer: For security reasons referer is not passed in https=>http redirection expect if you use a special meta:
http://smerity.com/articles/2013/where_did_all_the_http_referrers_go.html
For security reasons you should use https everywhere, which will solve your problem too.


Python IF Statement With Communicate() Function

Question: I am using a terminal command in my Python code using subprocesses, I am trying to check the communicate() function to check what the function returns and see if something is contained inside it. My function current returns both of the following depending on the outcome of the plates:
(b'No license plates found.\n', None)
Plate Not Found

(b'plate0: 10 results\n    - SBG984\t confidence: 85.7017\n    -
SBG98\t confidence: 83.3453\n    - S8G984\t confidence: 78.3329\n    -
5BG984\t confidence: 76.6761\n    - S8G98\t confidence: 75.9766\n    -
SDG984\t confidence: 75.5532\n    - 5BG98\t confidence: 74.3198\n    -
SG984\t confidence: 73.3743\n    - SDG98\t confidence: 73.1969\n    -
BG984\t confidence: 71.7671\n', None) Plate Not Found

The code is the following:
def read_plate():
    alpr_out = alpr_subprocess().communicate()
    print(alpr_out)
    if "No license plates found." in alpr_out:
        print ("No results!")
    elif "SBG984" in alpr_out:
        print ("Found Plate")
    else:
        print("Plate Not Found")

As you can tell from this code, it should print "No results!" but it is instead printing "Plate Not Found", if the function returns the plate which is SBG984 the code will still return "No results!". I am guessing I am missing something simple and maybe somebody can spot it.
Comment: The print is above in the question but the type is  @arsho
Comment: What is the output of `print(alpr_out)` and `print(type(alpr_out))`?
Comment: Double check what the variable types are in your code.
Comment: @BaileyKocin What do you mean what variable types? alpr_out is tuple? Should still be able to check if something is contained the way I have done it
Comment: @CurtusB We just wanted to make sure it was a tuple. How would we know for sure?
Comment: That is what the print type is returning so i'd say that is it, the print out is in my question, it must be something very simple @BaileyKocin
Comment: Hint: consider the simpler example `print("zqu" in ("foobar", "bazqux"))`. This outputs `False`, even though the letters "zqu" appear inside "bazqux".
Comment: I posted after @arsho responded. If it were so simple why couldn't you figure it out yourself?
Answer: alpr_out is a tuple: (b'No license plates found.\n', None)
What you want to do is check the substring is in the first element of the tuple, not in the tuple itself:
def read_plate():
    alpr_out = alpr_subprocess().communicate()
    print(alpr_out)
    # Index first element with [0]
    if "No license plates found." in alpr_out[0].decode():
        print ("No results!")
    elif "SBG984" in alpr_out[0].decode():
        print ("Found Plate")
    else:
        print("Plate Not Found")

Comment: Your code is returning an error, I will add it to your answer
Comment: @CurtisB check now, I added `decode()` to convert from bytes to string


Eclipse says I need to import a class, when I already imported it's whole package

Question: In a class, I have this line:
import javax.swing.*;

However on the StyledDocument doc = new DefaultStyledDocument(); Eclipse gives me an error (red line under the text) and offers to import StyledDocument (javax.swing.text)
Weird. I imported the entire swing package, why do I also need to import the class specifically?
Comment: Try to avoid `*` (star) form of imports.
Answer: Because the class is not in the javax.swing package, but in the javax.swing.text package. Imports are not recursive.
Comment: Really? Weird. Why not?
Comment: Because [subpackages in Java aren't really subpackages](https://stackoverflow.com/questions/23521857/design-of-java-classes-and-packages/23522042#23522042)
Comment: Because the Java designers decided so. And it makes sense. Most of the time, the classes you mainly use are at the top-level of a package tree (in javax.swing, for example), and the other packages mainly contain classes that are used internally by the root package. If there were recursive, importing org.hibernate.*, for example, would import hundreds of useless classes, that would clutter the namespace and potentially cause conflicts with other classes. Star imports are generally considered bad practice anyway. Use Ctrl-Shift-O, and Eclipse will import just what you need.


Indexes in Oracle

Question: Can you tell us how to find out which indexes are fragmented in Oracle?  Is there a script to get a list of fragmented indexes?
And what should be done with such indexes to get performance improvement? Should they be rebuilt?
Answer: I'm not sure what you mean by a "fragmented" index, but in general there is almost never any need to rebuild indexes in Oracle - at least, not to improve performance.
See this article by Jonathan Lewis on when to rebuild indexes, and Tom Kyte's views here - quote:

My opinion -- 99.9% of all reorgs, rebuilds, etc are a total and utter
  waste of time and  energy.  We spend way way way too much time losing
  sleep over this non-event.
Comment: The only time you should be rebuilding an INDEX is when it is invalid (eg: `SELECT status FROM user_indexes` shows it's `UNUSABLE`)
Answer: It is more important to have current statistics for your objects

Indexes in Oracle


Can't configure nginx for multiple domains

Question: I'm trying to host multiple domains (with simple static pages) on a single VPS, running Ubuntu 12.04 LTS, nginx. The basic nginx configs for all domains are similar to this one (all separated in sites-available dir) :
server {
 listen 80;
 server_name www.example.com;
 return 301 $scheme://example.com$request_uri;
}

server {
 listen 80;
 server_name example.com;

 root /home/username/example.com;
 index index.html;
}

it works for first domain, for second domain it works only if I removed the first server block, for third domain it doesn't work at all. nginx fails to start. I don't what I'm doing wrong.
Comment: You'll need to actually post the configuration which is giving you trouble.
Comment: I just found the solution, in the nginx error log it was saying "could not build the server_names_hash, you should increase server_names_hash_bucket_size: 64". I think it was due to the longer domain names.
Answer: The problems was the lengthy domain names. When I checked the nginx error log, I found this error message:
could not build the server_names_hash,
you should increase server_names_hash_bucket_size: 64

So, I un-commented the following line in /etc/nginx/nginx.conf file.
http {
 ....
 #server_names_hash_bucket_size 64;
 ....
}

Now, everything works as expected :)
Comment: Holy crap, I had the same problem. Thanks! The limit in default nginx seems to be 14 characters per domain, which seems ridiculously short.
Answer: If you want to test your sub-domains on localhost you may have to add the name of it to your local hosts file.
normally localted in /etc/hosts
Somehow those sub domains have to be resolved, try adding sub.localhost 127.0.0.1, and if your going to the web add an A record with your server ip, and check the DNS with
dig www.myexample.com
it should come back with an IP if its working, and do the same with each sub domain.
Let me know if this works
Comment: Does Nginx give you any sort of error when restarting or does it just start a new command line without any feedback?
Comment: I don't think it's a DNS issue here, nginx fails to start - so that's where the problem lies. BTW, I've tested that by editing my `/etc/hosts` file - it works fine when the server is running.
Comment: no, i don't get any error. It doesn't start or restart(if already running) silently.
Comment: thats usually because you have a syntax error in your config, please check this for multiple domains;

http://pastebin.com/nFxHhFjb
This usses sub domains but the template is easily adapted for more domains
Comment: syntax error ? where exactly, can you please clarify that.
Comment: It would be easier to debug if you edit your question with the actual domainnames.
Comment: @etagenklo my main problem is that "with above configuration" I can't even start the nginx server.
Answer: Change the "return 301" to "rewrite..."
server {
 listen 80;
 server_name www.example.com;
 rewrite ^(.*)$ $scheme://example.com$request_uri;
}


Replicar mensagem a todos os clientes de um chat

Question: Preciso replicar a mensagem de um cliente para todos que estiverem conectados, menos pro próprio cliente que enviou. Abaixo se encontra as classes que tenho até agora. Como poderia replicar essas mensagens?
public class Servidor {
  public static final int porta = 4444;
  private ServerSocket serverSocket;

public static void main(String[] args) {
    try {
        new Servidor().iniciarServidor();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void iniciarServidor() throws IOException {
    serverSocket = new ServerSocket(porta);
    System.out.println("Servidor esperando conexões..");
    while (true) {
        Socket socket = serverSocket.accept();
        ThreadServidor st = new ThreadServidor(socket);
        st.start();
    }
}

}

public class Cliente {
private static Socket socket;
private Scanner scanner;

public static void main(String[] args) throws UnknownHostException, IOException {
    new Cliente().iniciarCliente();
}

public void iniciarCliente() throws UnknownHostException, IOException {
    System.out.println("Digite seu nome: ");
    scanner = new Scanner(System.in);
    String nome = scanner.nextLine();
    socket = new Socket("localhost", 4444);
    PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader bf = new java.io.BufferedReader(new InputStreamReader(System.in));
    while (true) {
        String leitura = bf.readLine();
        pw.println(nome + ": " + leitura);
    }
}

}

public class ThreadServidor extends Thread {
private Socket socket;
PrintWriter printWriter = null;

public ThreadServidor(Socket socket) {
    this.socket = socket;
}

public void run() {
    try {
        String mensagem = null;
        BufferedReader bf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while ((mensagem = bf.readLine()) != null) {
            System.out.println("Mensagem do cliente: " + mensagem);
        }
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

Comment: O que está errado no código?
Comment: Nada, apenas não envia para todos os clientes conectados.
Answer: Basicamente você precisa armazenar uma lista dos sockets dos clientes e criar uma rotina que itera sobre todos eles, escrevendo no OutputStream de cada um.
Outra alternativa seria criar no servidor threads de escrita além das threads de entrada.
Eu fiz um exemplo completo de chat usando a segunda técnica no qual você pode se basear.
As partes importantes estão a seguir.
A primeira é o mapa com as filas de mensagens a serem enviadas para cada cliente:
private final ConcurrentHashMap<String, BlockingDeque<Message>> users = new ConcurrentHashMap<>();

A chave do mapa é o nome do usuário e cada valor é uma fila que armazena mensagens a serem enviadas para cada cliente.
A classe BlockingDeque é uma implementação especial de fila onde, caso ela esteja vazia, a thread que tenta ler um item da fila fica aguardando aparecer algum item.
Então, crio threads para cada cliente que ficam esperando as mensagens serem adicionadas nessa fila e, assim que chega alguma a thread escreve para o cliente.
O código da thread que envia as mensagens é este:
for (;;) {
    final Message message = outgoingMessagesToClient.take();
    ...
    outputStream.writeObject(message);
    outputStream.flush();
    ....
}

Para mandar uma mensagem para todos os usuários, basta adicionar a mensagem em todas as filas, assim:
private void sendMessageForAll(final Message message) {
    users.values().stream().forEach(q -> q.add(message));
}

Note que simplifiquei o código aqui para evitar detalhes mais complexos, como o caso onde há uma mensagem de saída do chat que encerra a conexão. Minha sugestão é implementar aos poucos e depois você começa a inserir mais detalhes,
Comment: Obrigado, muito útil!


How loudly should one sing while warming up?

Question: In the limited about of vocal warm-ups I've done when singing in amateur choirs, etc, I normally sing pretty quietly and it seems others do to.
Should a warm-up focus at all on volume and if so, how should volume vary over the warm-up? I'm guessing "start quiet and get louder" but how quiet, and how loud? Should you be belting out those "oohs" by the end?!
Answer: Warmups, among other things, help increase the flexibility of your vocal cords. Singing too quietly won't properly warm them up, and singing too loudly can damage them.
Your instinct to start a bit quieter and gradually increase the volume is probably a good one - it mimics any other kind of physical stretch. That said, you should seldom be belting in a choir setting in the first place, and almost certainly not during warmups.
I would suggest that during warmups, unless you have a specific reason (usually an explicit direction), you should sing in a comfortable middle dynamic, mp or mf. Depending on your section, this middle dynamic might be a bit variable (in a typically complemented choir, for example, there are many more altos than tenors, so altos tend to have a quieter "middle volume" than tenors).
Answer: This is just from 2 years of class voice at the uni, so if there is anyone better qualified to answer, take their answer over mine.
The different warm ups do different things.
Most warmups stretch range, and you certianly don't want to belt at the end of those, because you're already at the top (or bottom) of your range, and belting at the edges of your range can hurt your vocal chords. In fact, at the highest pitches of your range, you should be soft enough the notes are almost "breathy," because pushing can cause nodules to form.
So, most warm ups are done "at a comfortable level." You should never push to note and/or volume that has you straining.
There are warm ups for dynamic range, and these should be done at the volume intended. Typically the involve staying on the same pitch in the middle of your range with a cresendo and decrescendo or to hum or buzz a simple melodic pattern (typically arpeggios).
"Lip trills" or "buzzing" are also meant to increase the breath support and thus the volume, but it doesn't need to be loud as the second set of vibrations created forces you to push air like you were belting without actually belting.
Comment: I'm going to disagree with you on one very important point: breath support doesn't strictly correlate to volume. Extra support is often needed when singing very quietly, otherwise the sound "breaks up". Warm-ups focusing on breath support don't need to (and probably shouldn't) focus on volume.


How to link multiple graph networks in d3js so that an event in one calls the same event in other networks

Question: I am drawing four network graphs of the same data but using different properties to color the node. Currently, I am able to generate all 4 networks and for each network I am able to double click a node to see the connected nodes of the network. My question is how do I extend this functionality so that if I click a node on any of the graph networks, the other 3 also show me the node I clicked and the connected nodes therein.
This question asked previously Mouseover event on two charts at the same time d3.js does a similar thing for pie charts but I am not sure how I can adapt it to my code.
var drawNetworkFunction = function(descriptor, chartId) {
var width = 470;
var height = 310;
var toggle = 0;
var activenode;

var svg = d3.select(chartId).append("svg")
    .attr("width", width)
    .attr("height", height);

var container = svg.append("g")
    .attr("class", "everything");

if (descriptor == "id" || descriptor == "cluster") {
    var color = d3.scaleOrdinal(d3.schemeCategory10);
}

var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) {
        return d.id;
    }))
    .force("charge", d3.forceManyBody().strength(-7))
    .force("center", d3.forceCenter(width / 2, height / 2));

d3.json("Perovskite_info.json", function(graph) {

    if (descriptor == "cohesive") {
        var cscale = d3.scaleLinear()
            .domain([1.6, 7.2])
            .range([0, 1]);
    } else if (descriptor == "similarity") {
        var cscale = d3.scaleLinear()
            .domain([0, 1])
            .range([0, 1]);
    }

    var link = svg.append("g")
        .attr("class", "links")
        .selectAll("line")
        .data(graph.links)
        .enter().append("line")
        .attr("stroke", "#000")
        .attr("stroke-opacity", "0.1");

    var node = svg.append("g")
        .attr("class", "nodes")
        .selectAll("circle")
        .data(graph.nodes)
        .attr("pvs_id", function(d) { return d.id; })
        .enter().append("circle")
        .attr("r", 5)
        .attr("fill", function(d) {
            var col = '';
            if (descriptor == "id") {
                col = color(d.group);
            } else if (descriptor == "cluster") {
                col = color(d.cluster);
            } else if (descriptor == "cohesive") {
                col = d3.interpolatePurples(cscale(d.cohesive));
            } else if (descriptor == "similarity") {
                col = d3.interpolateReds(cscale(d.similarity));
            }
            return col;
        })
        .call(d3.drag()
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragended))
        .on("dblclick", connectedNodes);

    node.append("title")
        .text(function(d) {
            return ["Perovskite :" + d.id,
                "Cluster :" + d.cluster,
                "Cohesive Energy :" + d.cohesive,
                "Similarity to CaTiO3 :" + d.similarity
            ];
        });

    simulation
        .nodes(graph.nodes)
        .on("tick", ticked);

    simulation.force("link")
        .links(graph.links);

    function ticked() {
        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;
            });

        node
            .attr("cx", function(d) {
                return d.x;
            })
            .attr("cy", function(d) {
                return d.y;
            });
    }

    var linkedByIndex = {};
    for (i = 0; i < graph.nodes.length; i++) {
        linkedByIndex[i + "," + i] = 1;
    };

    graph.links.forEach(function(d) {
        linkedByIndex[d.source.index + "," + d.target.index] = 1;
    });

    function neighboring(a, b) {
        return linkedByIndex[a.index + "," + b.index];
    }

    function HS_f(activenode) {

        if (activenode != null) {

            var fing_plot = d3.select("#HSA_fingerprint")
                .append("svg")
                .attr("id", "fin_pl")
                .attr("width", 300)
                .attr("height", 300);

            fing_plot.append('svg:image')
                .attr("xlink:href", function() { return "./finger_prints_lo/" + activenode + "_lo.png" })
                .attr("width", 250)
                .attr("height", 250);

            return fing_plot;

        }
    }

    function connectedNodes() {

        if (toggle == 0) {

            d = d3.select(this).node().__data__;

            node.style("opacity", function(o) {
                return neighboring(d, o) | neighboring(o, d) ? 1 : 0.15;
            });

            toggle = 1;
            activenode = d.id;
            window.activenode = activenode;
            console.log(activenode);
            HS_f(activenode);
        } else {
            node.style("opacity", 1);;
            toggle = 0;
            d3.select("#fin_pl").remove();
        }

    }
});

function dragstarted(d) {
    if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
}

function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
}

function dragended(d) {
    if (!d3.event.active) simulation.alphaTarget(0);
    d.fx = null;
    d.fy = null;
}

return svg;

}

For the json file please refer to the link: https://api.myjson.com/bins/m3gd8
Also my html file is below:
<!DOCTYPE html>

<meta charset="utf-8">

<title>Library of Perovskite structures from Materials Project Database</title>

Graph Network of Perovskite structures from Materials Project Database

<link rel="stylesheet" href="pvs-net.css" />

Isomap Graph Network

Spectral Clustering on Isomap Graph Network

Calculated Cohesive Energy

Similarity score against CaTiO3

Hirschfeld Surface Fingerprint Plot

Comment: I have added the link to the complete json file
Comment: Can you create a working code snippet by providing some sample data rows?
Answer: Glad you came back with the data and the HTML. It makes it easier to debug and come up with a solution.
I just changed a couple of lines of code in the connectedNodes function:
Instead of node.style("opacity", function(o) {...}), I replaced it with:
d3.select('#Perovskite_Network').selectAll('.nodes').selectAll('circle').style("opacity", function(o) {
    return neighboring(d, o) | neighboring(o, d) ? 1 : 0.15;
});

This would select all circles from all the the SVGs. Let me know if that doesn't help or if you need any improvements.
Snippet:

var drawNetworkFunction = function(descriptor, chartId) {
var width = 470;
var height = 310;
var toggle = 0;
var activenode;

var svg = d3.select(chartId).append("svg")
    .attr("width", width)
    .attr("height", height);

var container = svg.append("g")
    .attr("class", "everything");

if (descriptor == "id" || descriptor == "cluster") {
    var color = d3.scaleOrdinal(d3.schemeCategory10);
}

var simulation = d3.forceSimulation()
    .force("link", d3.forceLink().id(function(d) {
        return d.id;
    }))
    .force("charge", d3.forceManyBody().strength(-7))
    .force("center", d3.forceCenter(width / 2, height / 2));

d3.json("https://api.myjson.com/bins/m3gd8", function(graph) {

    if (descriptor == "cohesive") {
        var cscale = d3.scaleLinear()
            .domain([1.6, 7.2])
            .range([0, 1]);
    } else if (descriptor == "similarity") {
        var cscale = d3.scaleLinear()
            .domain([0, 1])
            .range([0, 1]);
    }

    var link = svg.append("g")
        .attr("class", "links")
        .selectAll("line")
        .data(graph.links)
        .enter().append("line")
        .attr("stroke", "#000")
        .attr("stroke-opacity", "0.1");

    var node = svg.append("g")
        .attr("class", "nodes")
        .selectAll("circle")
        .data(graph.nodes)
        .attr("pvs_id", function(d) { return d.id; })
        .enter().append("circle")
        .attr("r", 5)
        .attr("fill", function(d) {
            var col = '';
            if (descriptor == "id") {
                col = color(d.group);
            } else if (descriptor == "cluster") {
                col = color(d.cluster);
            } else if (descriptor == "cohesive") {
                col = d3.interpolatePurples(cscale(d.cohesive));
            } else if (descriptor == "similarity") {
                col = d3.interpolateReds(cscale(d.similarity));
            }
            return col;
        })
        .call(d3.drag()
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragended))
        .on("dblclick", connectedNodes);

    node.append("title")
        .text(function(d) {
            return ["Perovskite :" + d.id,
                "Cluster :" + d.cluster,
                "Cohesive Energy :" + d.cohesive,
                "Similarity to CaTiO3 :" + d.similarity
            ];
        });

    simulation
        .nodes(graph.nodes)
        .on("tick", ticked);

    simulation.force("link")
        .links(graph.links);

    function ticked() {
        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;
            });

        node
            .attr("cx", function(d) {
                return d.x;
            })
            .attr("cy", function(d) {
                return d.y;
            });
    }

    var linkedByIndex = {};
    for (i = 0; i < graph.nodes.length; i++) {
        linkedByIndex[i + "," + i] = 1;
    }

    graph.links.forEach(function(d) {
        linkedByIndex[d.source.index + "," + d.target.index] = 1;
    });

    function neighboring(a, b) {
        return linkedByIndex[a.index + "," + b.index];
    }

    function HS_f(activenode) {

        if (activenode != null) {

            var fing_plot = d3.select("#HSA_fingerprint")
                .append("svg")
                .attr("id", "fin_pl")
                .attr("width", 300)
                .attr("height", 300);

            fing_plot.append('svg:image')
                .attr("xlink:href", function() { return "./finger_prints_lo/" + activenode + "_lo.png" })
                .attr("width", 250)
                .attr("height", 250);

            return fing_plot;

        }
    }

    function connectedNodes() {

        if (toggle == 0) {

            d = d3.select(this).node().__data__;

            d3.select('#Perovskite_Network').selectAll('.nodes').selectAll('circle').style("opacity", function(o) {
                return neighboring(d, o) | neighboring(o, d) ? 1 : 0.15;
            });

            toggle = 1;
            activenode = d.id;
            window.activenode = activenode;
            //console.log(activenode);
            HS_f(activenode);
        } else {
            d3.select('#Perovskite_Network').selectAll('.nodes').selectAll('circle').style("opacity", 1);
            toggle = 0;
            d3.select("#fin_pl").remove();
        }

    }
});

function dragstarted(d) {
    if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
}

function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
}

function dragended(d) {
    if (!d3.event.active) simulation.alphaTarget(0);
    d.fx = null;
    d.fy = null;
}

return svg;

}

drawNetworkFunction('id', '#Network1');
drawNetworkFunction('cluster', '#Network2');
drawNetworkFunction('cohesive', '#Network3');
drawNetworkFunction('similarity', '#Network4');
<meta charset="utf-8">

<title>Library of Perovskite structures from Materials Project Database</title>

Graph Network of Perovskite structures from Materials Project Database

<link rel="stylesheet" href="pvs-net.css" />

Isomap Graph Network

Spectral Clustering on Isomap Graph Network

Calculated Cohesive Energy

Similarity score against CaTiO3

Hirschfeld Surface Fingerprint Plot

And a fiddle link: https://jsfiddle.net/shashank2104/bj76ckh4/4/
I have a few suggestions though:

The file is being fetched for every drawNetworkFunction call which slows down the rendering of the page.
Along with fetching of the file, the object linkedByIndex is created in every call which is independent of the descriptor or chartId.

Suggestion: Move the above steps in a single function and pass the linkedByIndex and graph (data) to the drawNetworkFunction and then the rest. Hope this helps.
Comment: Thanks a lot! This worked great! Also taught me a few things as well about d3.
Comment: Glad I could help. Use [Code Review](https://codereview.stackexchange.com/) (if you feel it necessary) to refine your code by posting a working snippet.


Alguém conhece um programa para descompilar um apk e obter o código fonte?

Question: Utilizei o 7zip, porém ele não descompila o código que é o que interessa, ele descompila somente os arquivos xml. Alguém conhece um programa que faça isso? Agradeço desde já!
Answer: Tem essas ferramentas online = http://www.decompileandroid.com/ e http://www.javadecompilers.com/apk, tem também o APK Studio, que faz a engenharia reversa do apk = https://github.com/vaibhavpandeyvpz/apkstudio.
Comment: obrigadão! O javadecompilers funcionou perfeitamente!