text:
Q: Zonal statistics of polygon overlays in PostGIS I am trying to do a seemingly simple task -- extract mean pixel values from a raster based on a polygon overlay in PostGIS. I consulted several sources, including this blog, this blog, and this post). I loaded a Landsat tile into my database (in-db) and a polygon overlay consisting of three polygons (ID 1,2,3). The Landsat tile is a pansharpened image with a 15m spatial resolution and 4 bands.
Based on help files and the aforementioned posts/questions, I arrived at the following PostGIS query:
SELECT id, (SUM((ST_SummaryStats(a.rast, 1, true)).sum)/SUM((ST_SummaryStats(a.rast, 1, true)).count)) as mean
FROM imagery.l8_2015_09_12 AS a, analysis_results.zonal_stats_test as b
WHERE ST_Intersects(b.geom,a.rast)
GROUP BY id;
The results are:
1: 9902.49
2: 10079.68
3: 12355.90

However, when I test the results against ArcGIS's "zonal statistics to table" tool, I get the following results:
1: 8089.61
2: 7527.62
3: 12290.05

Close, but not identical. I am almost there but I was wondering if someone could help me figure out the source of the difference between both techniques. I suspect that there is something wrong with my ST_summaryStats method.

A: 1) I'm surprised you do not "cut" the raster with ST_Clip(rast, geom) or ST_Intersection(rast, geom) before computing their stats. What you want are the stats on the pixels values intersecting the polygons no? That could be one reason why you end up with a different result but that would only be if only small portions of the rasters are cut, since your result is quite close to the ArcGIS one.
2) Even if you "cut" the raster properly before computing stats, the way PostGIS clip or intersect the raster might be different from ArcGIS: How intersecting pixels are chosen? By their centroid? By the total area intersecting? How nodata values are treated? How polygons are converted to raster before clipping/intersecting if it's the case? How rasters are converted to polygons if its the case? All this depend on the tools you select and sometimes the order in which you do the operations.
I suggest you work with a subset of your data and visualize/analyse the results step by step (in OpenJump for example) to understand the difference with ArcGIS.
See also this tutorial.

A: That could be the case of when you imported the Landsat raster to your database, you hopefully set a parameter -t 300x300, which splits the image in tiles of 300x300 pixels. So, imagine that you have your polygons in a shapefile that you imported to your database.
It is possible that you need more than one raster tile to cover a polygon feature, so, to prevent this issue you should add the St_union function to your query, just like this:
SELECT
id,
(St_SummaryStats(St_Union(ST_Clip(rast,1,geom, true)))).*
FROM  imagery.l8_2015_09_12, analysis_results.zonal_stats_test
WHERE st_intersects(rast,geom)
GROUP BY id;

Also, by using .* you get sum, count, max, min, stddev as bonus. If you want just the mean, change * for mean, that line would end up as this:
(St_SummaryStats(St_Union(ST_Clip(rast,1,geom, true)))).mean


text:
Q: In the SSIS Export package, How to rename the destination excel file with time stamp attached to it? In  the SSIS Export package,  How to rename the destination excel file with  time stamp attached to it?
I have Excel as my Destination file. How to rename the destination file with time stamp attached to its suffix?
such as myfile_010120191100.xls
Generating dynamic file name will help us to avoid overwriting.

A: I just did it a few days ago like that:
Use a File System Task Editor with Rename File operation. The picture below, I have a variable called FilePathTargetCopy, which is hard-coded like C:/Users/MyUser/Desktop/aaa.xlsx. TEST_Copy is a "File Connection Manager" with "Create File" operation.
Create a similar File connection, go to its properties and add a ConnectionString expression with:
REPLACE(@[User::FilePathTargetCopy],".xlsx","")+"-"+
RIGHT("0" + (DT_STR,4,1252) DatePart("yyyy",getdate()),4)+"-"+
Right("0" + (DT_STR,4,1252) DatePart("m",getdate()),2) +"-"+
Right("0" + (DT_STR,4,1252) DatePart("d",getdate()),2) + ".xlsx"

Then, set it as DestinationConnection with OverWrite=true as below.

A: Create a variable in your variable pane for FileName.
You can use Expressions to build a file name like this:
"FilePathHere\FileName_" +  (DT_WSTR,4)YEAR(GETDATE()) + "" +
RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "" +
RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) +
"_" + Right("0" + (DT_STR,2,1252) DatePart("hh",getdate()),2) +
Right("0" + (DT_STR,2,1252) DatePart("mi",getdate()),".xlsx"

You can click Evaluate Expression to ensure it works and gives you the path you want.
Then in your flat file connection manager go to properties and click Expressions -> Connection String.
This is where you select the variable name above for your file name.
Adding note:
In the expression it is doing the RIGHT("0"..  on the string for the month so if it is a 1 digit month it will append a 0 in front of it (same for rest of them) so they will always be 2 digits.

A: I know I am late but I always use a script task to set variables when it comes to datetime and setting expressions vs using variables. I find it easier to follow variables as expressions seem to get lost in the logic.
This table should help you out:
Date And Time Format In C# Programming
Format                                          E.g. Result
DateTime.Now.ToString("MM/dd/yyyy hh:mm tt")    05/29/2015 05:50 AM
DateTime.Now.ToString("MM/dd/yyyy H:mm")        05/29/2015 5:50
DateTime.Now.ToString("MM/dd/yyyy h:mm tt")     05/29/2015 5:50 AM
DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")    05/29/2015 05:50:06

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como ordenar os Contatos por nome? Estou com o seguinte código e gostaria de fazer um ORDER BY name:
try {
        String clsSimPhonename = null;
        String clsSimphoneNo = null;

        Uri simUri = Uri.parse("content://icc/adn");
        Cursor cursorSim = getContentResolver().query(simUri, null,
                null, null, "name ASC");
        while (cursorSim.moveToNext()) {
            clsSimPhonename = cursorSim.getString(cursorSim
                    .getColumnIndex("name"));
            clsSimphoneNo = cursorSim.getString(cursorSim
                    .getColumnIndex("number"));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

A: Utilizando o último parâmetro na query, mude o seu Cursor para algo assim:
Cursor cursor = getContentResolver.query(simUri, null, null, null, "name ASC");

A: Tiver que fazer um metodo para a ordenação:
public List<Telefone> ordenarTelefones(List<Telefone> lista)
        throws Exception {

    Collections.sort(lista, new Comparator<Telefone>() {

        @Override
        public int compare(Telefone tel1, Telefone tel2) {
            return tel1.getNome().compareTo(tel2.getNome());

        }
    });

    return lista;
}


text:
Q: Rails has_many :through #new doesn't set associations on new record As per the Rails docs, one can use has_many :through as a shortcut:

The has_many :through association is also useful for setting up
  "shortcuts" through nested has_many associations. For example, if a
  document has many sections, and a section has many paragraphs, you may
  sometimes want to get a simple collection of all paragraphs in the
  document.

So let's say we have this code:
class User < ApplicationRecord
  has_many :sub_users
  has_many :settings
end

class SubUser < ApplicationRecord
  belongs_to :user
  has_many :settings, through: :user
end

class Setting < ApplicationRecord
  belongs_to :user
end

Based on this, if I run user.settings.new, I get a new Setting instance with user_id set to user.id.
That's great. But if I run sub_user.settings.new, I get a new Setting instance that doesn't have user_id set to sub_user.user.id.
Is this expected behavior?

A: I wouldn't use has_many through: for that, delegate looks like the best idea https://apidock.com/rails/Module/delegate
class SubUser < ApplicationRecord
  belongs_to :user
  delegate :settings, to: :user
end

Your current code is not what has_many through is for, check the docks, the relations are different https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association


text:
Q: Listening to microphone from a website Well question can be general but we would like to understand it more deeply . sorry for not understanding basic stuff, i do other software .
We would like to set owr website, so that when user is open it, he will be asked to let the url open his microphone on his pc/mac .
I wonder also if Apples mac's will allowed that .
Than ,that website will have to listen to the microphone to analyze the data (in the client side= not sending it to server , processing software is in the client side ) .

A: If you're trying to just connect to the Microphone and get the file then you can try HTML5 tag as:
<input type="file" accept="Audio/*" capture />

This will request for permission to access the Microphone from the user's system. Once permission is granted you can continue the work, to either save it, or upload it, or what so ever
Reference:
http://updates.html5rocks.com/2012/09/Live-Web-Audio-Input-Enabled


text:
Q: Can't launch unity bar with wacom tablet I have a Wacom Intuos CTH680 & I can't seem to be able to launch the unity bar with the pen. When I move the pen to the edge of the detection area, the unity bar doesn't reveal itself. The only way I can use the unity launcher with the pen is if I disable autohide, but then the unity launcher obstructs stuff on the left side of my screen. How do I get the pen to be able to reveal the unity launcher?
I am on Ubuntu 14.04—all of the wacom help out there seems to be for much older versions of ubuntu.

A: I experienced this problem. The solution was to just hold the Super key (or "windows") for a moment to make the launcher appear.
I think that any tablet can't do this, because the mouse can 'force' their position, while the pen have their limited area to move in the tablet. Though in my Bamboo Fun Pen & Touch, with the touch I can do this.


text:
Q: Is it a normal practice when there're 2 columns and if one is true the other must false, and vise versa? I have something similar to this, but not precisely it:
I sell only coffee and tea, and for the next 50 years I'll be selling only these. In a table "drinks" I have 2 columns: is_coffee? and is_tea?. Only one of these can be true, obviously, and if one is true, the other must be false.
Also, I have some columns that are specific to only coffee, when is_coffee? is true, and others to only tea.
Does it make sense hold all of them in a single table? Is it a normal situatation when there're 2 columns and if one is true the other must false, and vise versa?

A: This is called transitive functional dependency and should be avoided to have a 3th normal form design.
To solve it you should move it to the type of product to another table.
And then you can have another table linked with specific attributes of coffee entity and another one with specific attributes of the tea entity.
Don't be scared of the number of the tables, be scared of the consequences of not be in normal form.
(i.e. lack of performance, space, scalability)


text:
Q: Aspect oriented programming and/or Enterprise Library 5.0 for Logging/Exception implementation? I can implement both AOP (using Postsharp) and the EntLib (v5.0) for cross cutting concerns as logging and exception handling/strategies.
I'm failing to see if one excludes the other or where they might complement each other. Can somebody please share some experience and/or thoughts on this?
Thanks!
My take on it regarding exceptions:

AOP can easily wrap your code and catch exceptions. Handling could then be delegated to the EntLib which provides strong handling (wrap, replace, swallow) configuration using policies.

The handling strategies (wrap, replace and swallow) could also be implemented in aspects. What would drive the decision? Or am I missing something here perhaps?

A: I have not used Enterprise Lib, so let me talk in terms of log4net and postsharp.

Log4net has great logging stuff, and you can use AOP ( using postsharp
  ) to drive this logging in a declarative way.  In this sense they are
  great compliments.

Here is an example.  I would expect the same to hold true for Enterprise Library based logging or exception handling.
What I wouldn't suggest you use is the two AOP type things together, so the policy injection in Enterprise Library looks like AOP to me, so I wouldn't use it and postsharp.


text:
Q: Using useEffect with React-redux I have a problem. As I understood hook useEffect doen't run.
I have action that should take data from server.
export const getProducts = () => {
    return dispatch => {
        dispatch(getProductsStarted());

        fetch('https://shopserver.firebaseapp.com/get-products')
            .then(res => {
                dispatch(getProductsSuccess(res.json()));
            })
            .catch(err => {
                dispatch(getProductsFailure(err.message));
            });
    }
}

const getProductsSuccess = todo => ({
    type: "ADD_TODO_SUCCESS",
    payload: {
        ...todo
    }
});

const getProductsStarted = () => ({
    type: "ADD_TODO_STARTED"
});

const getProductsFailure = error => ({
    type: "ADD_TODO_FAILURE",
    payload: {
        error
    }
});

I have a reducer.
const initialState = {
    loading: false,
    products: [],
    error: null
}

export const ProductReducer = (state = initialState, action) => {
    switch (action.type) {
        case "ADD_TODO_SUCCESS":
            return {
                ...state,
                loading: false,
                error: null,
                todos: [...state.products, action.payload.products]
            }
        case "ADD_TODO_STARTED":
            return {
                ...state,
                loading: true
            }
        case "ADD_TODO_FAILURE":
            return {
                ...state,
                loading: false,
                error: action.payload.error
            }
        default:
            return state
    }
}

And I have a Component where I want to render a result.
import React from 'react';
import { CardItem } from "./cardItem";
import { useSelector } from 'react-redux';
import { useEffect } from 'react';
import { getProducts } from '../Redux/Actions/productAction'

export const ProductCard = () => {

    useEffect(() => {
        getProducts();
        console.log('111111')
    })

    const data = useSelector(state => state.ProductReducer.products);

    return (
        <div>
            {data.map( element =>
                CardItem (element)
            )}
        </div>
    )
}

After rendering page nothing happens. ReduxDevTools shows that there was no send actions. Please, help me to fix it. Thank you.

A: I think you should be calling your async action like this :
import { useDispatch, useSelector } from 'react-redux';

[...]

export const ProductCard = () => {

  const dispatch = useDispatch();

  useEffect(() => {
      // I guess getProducts is an async redux action using redux-thunk
      dispatch(getProducts());
      console.log('111111')
  }, []);

  [...]

}

I assume you want to load products only when component is born, so I pass an empty array as second argument for useEffect (https://reactjs.org/docs/hooks-reference.html#useeffect).


text:
Q: 3 Tier Winform Application I have a college project that I want to do as 3 Tier Winform Application so that I need only to update my application at one place (ie the server).  Does anyone have suggestion on how to do this?  I have to work with a client machine, and a fairly good server.  I want the server to house the Database and the Business Logic, and want the client machine to be a thin client.

A: Try looking into the CSLA.NET Framework, it's a Use Case oriented way of implementing your business logic.  Comes with UI binding, network communications, and other features like unlimited undo straight out the tin.
Also comes with a book, which teaches you how to use it - worth a read.  It's a very well implemented framework and remains active - though, like me, you might find it a little shift from how you usually program.
The networking capabilities allow you to host an app server, but have that part transparent to the UI.  It adheres to the idea of n-tier, but in a slightly different manner.

A: Write your winform (not quite a thin client though) as you normally would.  We'll call it thin cause it wont to any heavy lifting, just UI logic.  Rather than make references to your business and data assemblies, create an agent class that you will reference from your winforms app.  Then the Agent will have the implementation to talk to the back end, and your front end will not know how the communication happens.  Then create a Service Contract class (that will expose the interfaces to the front end) in a separate project.  The Agent will use this contract.
Since you are in VS2005, i assume you have the .net framework 3.0 extensions installed, but not 3.5.  You can use WCF to communicate to the back end Server, where your interfaces will be exposed to be called by the agents.
If you want to stay away from WCF, you could also use .net remoting, but that may be a little more difficult to configure, and it typically not the preferred transport mechanism over WCF.
So it would look like this:
Client Tier
Winform
Agent
Business Tier
Service Contract
Business Components
Data Access
Database Tier
Database
Here is a article that kinda describes this pattern.


text:
Q: exit code for rsync if there is no modification done to destination folder I'm using rsync in solaris and couldn't find an exit code if there is no file or folder modification/addition or deletion done on the destination folder. How can I get the status if rsync doesn't have one ?
 0     Success
 1     Syntax or usage error
 2     Protocol incompatibility
 3     Errors selecting input/output files, dirs
 4     Requested action not supported: an attempt was made to manipulate 64-bit
       files on a platform that cannot support them; or an option was specified
       that is supported by the client and not by the server.
 5     Error starting client-server protocol
 6     Daemon unable to append to log-file
10     Error in socket I/O
11     Error in file I/O
12     Error in rsync protocol data stream
13     Errors with program diagnostics
14     Error in IPC code
20     Received SIGUSR1 or SIGINT
21     Some error returned by waitpid()
22     Error allocating core memory buffers
23     Partial transfer due to error
24     Partial transfer due to vanished source files
25     The --max-delete limit stopped deletions
30     Timeout in data send/receive
35     Timeout waiting for daemon connection

Thank you

A: There is a work around
rsync --log-format=%f ...

Note that rsync outputs files anytime any attribute changes, not only if the content of the file is updated.
There is also a -i option (or --log-format=%i) that itemizes all of the changes. See the rsync man page for details of the output format.


text:
Q: Start Tomcat on Console from Jenkins I have a batch file which start Tomcat as follows (when running it on Windows it works fine)
...
start C:\Users\root\tomcat\tomcat2\bin\startup.bat

The batch file is called from Jenkins as follows

I have this error in the Jenkins Consol at the end of the build
D:\jenkins\workspace\Start 3T2>start C:\Users\root\tomcat\tomcat2\bin\startup.bat
Process leaked file descriptors. See http://wiki.jenkins-ci.org/display/JENKINS/Spawning+processes+from+build for more information
Finished: SUCCESS

When I check the task manager I see that the server is started but in background. I need actually to start Tomcat it in the Console.
This is what I did :

*

*I added -Dhudson.util.ProcessTree.disable=true in jenkins-slave.xml
used to start jenkins slave service.

*I added set BUILD_ID=dontkillme in startup.bat to stop Jenkins from
stopping the process in the end.

I think Tomcat start correctly in the end but not in Console. I'm running Windows 2012 server/Tomcat7/Jenkins 1.578.
Any idea on how to start Tomcat in a Console ?

A: AFAIK, if you're trying to start Tomcat console on a given machine which has Jenkins configured as service, it will not work. To make it work, you will have to connect to the given machine using JNLP. In case it's a standalone system and you want to open a Tomcat console using Jenkins, you will have to set up a Slave on the same machine and that too using JNLP (Launch slave agents via Java Web Start) in the Launch method section in Jenkins > Manage Jenkins > Manage Nodes > Slave Node's Configure page.
You can connect to the slave using any of the methods shown below. You will see the below option as soon as you configure the slave node and click Save. I ran the highlighted command from the Win command prompt. In my set up, i had configured Master and Slave on the same machine. I have Win 7 Professional, 64-bit laptop.

Once you run the command, you will see a small window that will pop-up and will display 'Connected' message as shown below:

At least for me, i checked that hudson.util.ProcessTree.disable=true & BUILD_ID parameters were not required. The only thing that i needed was to make sure that the following property is unset: HUDSON_SERVER_COOKIE

P.S.: You might have to make sure to start JNLP on reboot. A start-up script will do that. Also, ensure that your project/job is tied to the given slave which is running using JNLP mechanism.

A: i was going crazy with this , as shutdown.sh worked from Window-Master-Jenkin-->Linux-Slave-Jenkins, but startup.sh was not happening on my linux-slave-jenkins though startup.sh execution showed success message, as there were no logs anywhere, it was difficult to troubleshoot, not sure how and why setting up "export HUDSON_SERVER_COOKIE= " just before running startup.sh worked. Anyway Thanks a lot.


text:
Q: Django get_queryset returns 500 instead of 404 Here is my view:
class SampleViewSet(viewsets.ModelViewSet):
      serializer_class = SampleSerializer
      queryset = Sample.objects.all()

      def get_queryset(self):
          queryset = self.queryset
          test_code = self.request.query_params.get('test_code', None)
          if test_code is not None:
             queryset = queryset.filter(test__test_code=test_code)
          return queryset

Here is my Model:
class Sampe(models.Model):
      test = models.OneToOneField(Test, null=True, blank=True, on_delete=models.CASCADE)
      # few more fields- not so important

Here is my serializer:
class SampleSerializer(serializers.ModelSerializer):
      test_code = serializers.CharField(source='test.test_code')

      class Meta:
           model = Sample
           fields = '__all__'

This works when I hit /api/sample?test_code="existing_param"
So when I do /api/sample?test_code="Not_Existing_param", I was expecting it should throw me 404 instead, it throws 500 Test matching query does not exist. Really appreciate any help.
Thank you

A: Well the problem is that the function will raise an error, and the web server can not really interpret what caused this error, so it is more accurate to raise a 500 in general, than a 404.
But what you can do is use a get_list_or_404 which acts like a get_object_or_404, but then with a .filter(..) instead of a .get(..):
from django.shortcuts import get_list_or_404

class SampleViewSet(viewsets.ModelViewSet):
      serializer_class = SampleSerializer
      queryset = Sample.objects.all()

      def get_queryset(self):
          queryset = self.queryset
          test_code = self.request.query_params.get('test_code', None)
          if test_code is not None:
             queryset = get_list_or_404(queryset, test__test_code=test_code)
          return queryset
This will thus filter the queryset, and raise a 404 exception in case the resulting queryset turns out to be empty. In case you chain filters together, it is sufficient to do this on the last element, since then you inspect the actual queryset you will return, and thus avoid checking multiple quersets that are not used later in the process.


text:
Q: A single die is rolled seven times. Find the probability that 2 appears at most twice. A single die is rolled seven times. Find the probability that 2 appears at most twice.
here we rolled die in 7 times so $n(s)=6^7$
from here how to processed

A: Let $A_0$ be the event that 2 doesn't appear at all, $A_1$ be the event that 2 appears exactly once and $A_2$ be the event that 2 appears exactly twice. The probability you need to calculate is the probability that $A_0\cup A_1\cup A_2$ occurs. Note that these events are clearly disjoint, so by additivity of the probability measure, we have:
$$\mathbb{P}(A_0\cup A_1\cup A_2)=\mathbb{P}(A_0)+\mathbb{P}(A_1)+\mathbb{P}(A_2)$$
Now it is easy to see that the desired number is $\frac{5^7+7\cdot 5^6+\binom{7}{2}\cdot 5^5}{6^7}$.


text:
Q: Collecting parameter values from Extended event session I'm using extended events to trace the statements used by our application.
I have created a session that will collect the information that I want, except that I would also like to know the actual values of the parameters that was used.
I am performing this trace on a non-production environment and any performance hit by the trace is acceptable.
All the queries originate from Hibernate and have been parameterized in the form of:
SELECT a, b, c From Customer where CustomerId = @P0

This is my session setup.
CREATE EVENT SESSION [TracingForStatements] ON SERVER
ADD EVENT sqlserver.sp_statement_completed (
    ACTION (
        sqlserver.session_id,
        package0.collect_system_time,
        sqlserver.transaction_id,
        package0.event_sequence
    )
    WHERE (
        sqlserver.database_id=555
    )
)
ADD TARGET package0.ring_buffer(SET max_memory= 128000)
WITH (EVENT_RETENTION_MODE = NO_EVENT_LOSS,
      MAX_DISPATCH_LATENCY = 1 SECONDS)

How can I capture the actual values of the parameters that was used in the captured statements? Is it possible?
-- Edit (Workaround):
Changing the event to rpc_completed gives me the complete sql command(including all parameter values) called from Hibernate. For other cases it would still be good to know how to capture the parameter values, if it is possible.

A: Someone mentioned
"I think only sqlserver.rpc_completed event will give you complete SQL command including parameter values."
Please review answer below:
Capture Passed Parameter Values In Sql Server Extended Sessions


text:
Q: How to set macro for system.profile.name in cloud datafusion pipeline I am trying to send system.profile.name runtime args in below airflow dag:
start_pipeline = CloudDataFusionStartPipelineOperator(
    task_id="start_pipeline",
    location="us-central1",
    pipeline_name="cdf_pipeline",
    instance_name="cdf_instance",
    runtime_args={"system.profile.name":'SYSTEM{COMPUTE_PROFILE}'},
    dag=dag
)

But my cdf_pipeline is deployed and i am not able to macro it. could you please suggest how to pass compute profile name through runtime_args through CloudDataFusionStartPipelineOperator and also how to set macro for compute profile?

A: if you're trying to use CDAP macros, you'll need to prepend your macro with $. For details, see https://cdap.atlassian.net/wiki/spaces/DOCS/pages/1188036697/Macros+and+macro+functions.


text:
Q: Android Saving of Strings I'm wanting to save the value of strings (numeral Strings) to somewhere where i can when the user reloads the app, the values can be passed back into the app. Being saved to local storage is preferrable

A: I would suggest using shared preferences over a SQLLite DB if you are only saving a small amount of strings.
private void saveStringToPreferences(String key, String str){
     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
     SharedPreferences.Editor editor = preferences.edit();
     editor.putString(key, str);
     editor.apply();
}

private void getStringFromPreferences(String key){
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    String previousText = preferences.getString(key, "");
    return previousText;
}

A: You really should do some research before asking such a question.  Here is a link to the options available for  storing data in android:
http://developer.android.com/guide/topics/data/data-storage.html


text:
Q: Decoding MultiType Array and Unknown Length Array within JSON using Swift I've seen questions like this asked before on Stack Overflow, however none match this complexity. When I attempt to apply the same principles I've seen in similar StackOverflow questions, I get stuck. I'm new to using JSONs in Swift, and certainly understand how to decode fairly complex JSONs. However, this is just beyond my reach.
{
  "def": [
    {
      "sseq": [
        [
          [
            "pseq",
            [
              [
                "sense",
                {
                  "sn": "1 a (1)",
                  "dt": [
                    [
                      "text",
                      "{bc}an extremely young child"
                    ]
                  ],
                  "sdsense": {
                    "sd": "especially",
                    "dt": [
                      [
                        "text",
                        "{bc}{sx|infant||}"
                      ]
                    ]
                  }
                }
              ],
              [
                "sense",
                {
                  "sn": "(2)",
                  "dt": [
                    [
                      "text",
                      "{bc}an extremely young animal"
                    ]
                  ]
                }
              ]
            ]
          ],
          [
            "sense",
            {
              "sn": "b",
              "dt": [
                [
                  "text",
                  "{bc}the youngest of a group "
                ],
                [
                  "vis",
                  [
                    {
                      "t": "He is the {wi}baby{/wi} of the family."
                    }
                  ]
                ]
              ]
            }
          ]
        ],
        [
          [
            "sense",
            {
              "sn": "2 a",
              "dt": [
                [
                  "text",
                  "{bc}one that is like a baby (as in behavior) "
                ],
                [
                  "vis",
                  [
                    {
                      "t": "When it comes to getting shots, I'm a real {wi}baby{/wi}."
                    }
                  ]
                ]
              ]
            }
          ],
          [
            "sense",
            {
              "sn": "b",
              "dt": [
                [
                  "text",
                  "{bc}something that is one's special responsibility, achievement, or interest "
                ],
                [
                  "vis",
                  [
                    {
                      "t": "The project was his {wi}baby{/wi}."
                    }
                  ]
                ]
              ]
            }
          ]
        ],
        [
          [
            "sen",
            {
              "sn": "3",
              "sls": [
                "slang"
              ]
            }
          ],
          [
            "sense",
            {
              "sn": "a",
              "dt": [
                [
                  "text",
                  "{bc}{sx|girl||}, {sx|woman||} "
                ],
                [
                  "uns",
                  [
                    [
                      [
                        "text",
                        "often used in address"
                      ]
                    ]
                  ]
                ]
              ]
            }
          ],
          [
            "sense",
            {
              "sn": "b",
              "dt": [
                [
                  "text",
                  "{bc}{sx|boy||}, {sx|man||} "
                ],
                [
                  "uns",
                  [
                    [
                      [
                        "text",
                        "often used in address "
                      ],
                      [
                        "vis",
                        [
                          {
                            "t": "Hey {wi}baby{/wi}, nice car!"
                          }
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            }
          ]
        ],
        [
          [
            "sense",
            {
              "sn": "4",
              "dt": [
                [
                  "text",
                  "{bc}{sx|person||}, {sx|thing||} "
                ],
                [
                  "vis",
                  [
                    {
                      "t": "is one tough {wi}baby{/wi}"
                    }
                  ]
                ]
              ]
            }
          ]
        ]
      ]
    }
  ]
}

To clarify, I only want the object that contains the "sn" and "dt" properties and looks like the following:
{
   "sn":"b",
   "dt":[
          [
              "text",
              "{bc}the youngest of a group "
          ],
          [
                     "vis",
               [
                    {
                         "t":"He is the {wi}baby{\/wi} of the family."
                    }
               ]
          ]
     ]
}

What makes this so complicated is that:

*

*The first "sseq" (for example) contains a 5D array that combines strings with more arrays within the same array, which happens at multiple levels.

*Sometimes, it is unknown how many arrays I have to decode to get to that level.

Any help on this is appreciated!

A: The below function will generate an array with all values that has any of the given keys
func extract(_ keys: [String], from value: Any, to result: inout [String, Any)]) {
    if let dictionary = value as? [String: Any] {
        var anyFound = false
        for key in keys {
            if let value = dictionary[key] {
                result.append((key, value))
                anyFound = true
            }
        }

        if !anyFound {
            for item in dictionary {
                extract(keys, from: item.value, to: &result)
            }
        }
    } else if let array = value as? [Any] {
        for item in array {
            extract(keys, from: item, to: &result)
        }
    }
}

and you can use it like this
var array = [(String:Any)]()
do {
    if let result = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
        extract(["dt", "sn"], from: result, to: &array)
    }
} catch {
    print(error)
}

Then it is only a matter of decoding/converting the content of the array.

A: For completeness-sake, another approach to make this work is to encapsulate the types of values that a JSON could hold as an enum with associated values:
enum Json {
    case obj([String: Json])
    case arr([Json])
    case str(String)
    case int(Int)
    case num(Decimal)
    case bool(Bool)
    case null
}

Then you could make it Decodable by trying to decode either as a dictionary, failing that - as an array, and finally, failing that, as a primitive value:
extension Json: Decodable {
    // Need this to decode arbitrary keys
    struct DynamicKeys: CodingKey {
        var stringValue: String
        var intValue: Int? = nil
        init?(stringValue: String) { self.stringValue = stringValue }
        init?(intValue: Int) { return nil }
    }

    init(from decoder: Decoder) throws {

        // try to decode as a dictionary
        if let container = try? decoder.container(keyedBy: DynamicKeys.self) {
            var dict: [String: Json] = [:]
            for key in container.allKeys {
                let jsonValue = try container.decode(Json.self, forKey: key)
                dict[key.stringValue] = jsonValue
            }
            self = .obj(dict)

        // try to decode as an array
        } else if var container = try? decoder.unkeyedContainer() {
            var array: [Json] = []
            while !container.isAtEnd {
                let jsonValue = try container.decode(Json.self)
                array.append(jsonValue)
            }
            self = .arr(array)

        // try to decode a primitive
        } else if let container = try? decoder.singleValueContainer() {
            if let int = try? container.decode(Int.self) {
                self = .int(int)
            } else if let decimal = try? container.decode(Decimal.self) {
                self = .num(decimal)
            } else if let str = try? container.decode(String.self) {
                self = .str(str)
            } else if let bool = try? container.decode(Bool.self) {
                self = .bool(bool)
            } else if container.decodeNil() {
                self = .null
            } else {
                fatalError("this shouldn't have happened")
            }
        } else {
            fatalError("this shouldn't have happened")
        }
    }
}

You could provide some convenience subscripts to access an array or a dictionary:
extension Json {
    subscript(index: Int) -> Json? {
        if case .array(let array) { return array[index] }
        else { return nil }
    }

    subscript(index: String) -> Json? {
        if case .obj(let dict) { return dict[index] }
        else { return nil }
    }
}

Then you could decode it normally, and you'd get an enum of possibly more enums as a result:
let json = try JSONDecoder().decode(Json.self, jsonData)

let innerJson = json["foo"]?[0]?["bar"]


text:
Q: SSIS External Package - Invalid Class String Error I'm trying to call an SSIS package from another solution, but it gives me an Invalid Class String error when I try to select the external package.  I'm using Windows authentication.
Any ideas on what the issue could be?

Error message
Invalid class string
------------------------------
Program Location:

   at Microsoft.SqlServer.Dts.Runtime.Application.GetPackageInfos(String strFolder, String serverName, String serverUserName, String serverPassword)
   at Microsoft.SqlServer.Dts.Tasks.ExecutePackageTask.PackageBrowser.<>c__DisplayClass3_0.<EditValue>b__0(String path)
   at Microsoft.SqlServer.Dts.Tasks.ExecutePackageTask.PackageBrowser.EditValue(ITypeDescriptorContext context, IServiceProvider provider, Object value)

===================================

Invalid class string
------------------------------
Program Location:

   at Microsoft.SqlServer.Dts.Runtime.Wrapper.ApplicationClass.GetPackageInfos(String bstrPackageFolder, String bstrServerName, String bstrServerUserName, String bstrServerPassword)
   at Microsoft.SqlServer.Dts.Runtime.Application.GetPackageInfos(String strFolder, String serverName, String serverUserName, String serverPassword)

Connection properties

A: Along the lines of what @larnu mentions in the comments, the Execute Package Task can run packages within the current project, or packages stored in the File System or the msdb.
To run a package in the SSISDB, I think that's going to get "interesting."
At it's core, running a package in the SSISDB is a few Stored Procedure calls.
Declare @execution_id bigint
EXEC [SSISDB].[catalog].[create_execution] @package_name=N'Child1.dtsx'
, @execution_id=@execution_id OUTPUT
, @folder_name=N'TestDeply4'
, @project_name=N'Integration Services Project1'
, @use32bitruntime=False
, @reference_id=Null;

Select @execution_id
DECLARE @var0 sql_variant = N'Child1.dtsx'
EXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id, @object_type=20, @parameter_name=N'Parameter1', @parameter_value=@var0

DECLARE @var1 sql_variant = N'Child2.dtsx'
EXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id, @object_type=20, @parameter_name=N'Parameter2', @parameter_value=@var1

DECLARE @var2 smallint = 1
EXEC [SSISDB].[catalog].[set_execution_parameter_value] @execution_id, @object_type=50, @parameter_name=N'LOGGING_LEVEL', @parameter_value=@var2

EXEC [SSISDB].[catalog].[start_execution] @execution_id

That mess would find package 'Child1.dtsx' in the project 'Integration Services Project1' which is in folder 'TestDeply4' and create an execution context. It assigns values for Parameters 1 and 2. Finally, it starts execution.
Therefore, to run an SSIS package in the SSISDB from an "external" project, you'll need to replicate those same calls in an Execute SQL Task
What's so interesting
The stored procedures that the SSISDB uses to do all the magic is CLR based and there's all sorts of impersonation that goes on. This is one of the reasons the account requesting a package to run must be a AD backed account and not a DB only account.
I would encourage you to get a working POC together and deploy to an environment and see what happens. Things might work just fine. Otherwise, I can see attempts at double impersonation fouling this whole approach up.


text:
Q: How to set zero in the cells if the cells are empty using VBA I have an excel file with 3 sheets inside:

*

*Starting Date and Ending Date in Sheet1 (1st screenshot)

*A database in Sheet2 (2nd screenshot)

*Filtered data in Sheet3 based on the date in Sheet1 (3rd screenshot)

I have a script that copy the data from Sheet2 to Sheet3 based on the date in Sheet1. I want the script to be able to put a zero in the empty space if it is detected instead of leaving it as blank.
For example, in the 2nd screenshot above, there is no value in Row 8 for Group 4 and Group 6, so I want the script to be able to put a zero in Group 4 and Group 6 for Row 8 when the data is copied to Sheet3.
I managed to achieve this but some how there will be zero in Row 9 as well (shown in the 3rd screenshot). There should be no zero in Row 9 since the date in Sheet1 is only from December-20 to February-21 (3 months). May I know how should I modified my script so that I'm able to eliminate the zero in Row 9? Any help will be greatly appreciated!
This is my script:
Sub extractdata()

Dim LastRow As Long, erow As Long, i As Long, j As Long, LastRow2 As Long
Dim mydate As Date

LastRow2 = Sheet3.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
Sheet3.Range("B6:H" & LastRow2).ClearContents

LastRow = Sheet2.Cells(Rows.Count, 2).End(xlUp).Row

For i = 6 To LastRow

    mydate = Sheet2.Cells(i, 2)

    If mydate >= Sheet1.Cells(7, 19) And mydate <= Sheet1.Cells(8, 19) Then
    erow = Sheet3.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
    Sheet2.Range(Sheet2.Cells(i, 2), Sheet2.Cells(i, 57)).Copy Destination:=Sheet3.Cells(erow, 2)
    End If

    For j = 3 To 8
        If IsEmpty(Sheet3.Cells(i, j).Value) = True Then
        Sheet3.Cells(i, j) = 0
        End If
    Next j

Next i

End Sub

Edit
Sub extractdata()

Dim LastRow As Long, erow As Long, i As Long, j As Long, LastRow2 As Long
Dim mydate As Date

LastRow2 = Sheet3.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
Sheet3.Range("B6:H" & LastRow2).ClearContents

LastRow = Sheet2.Cells(Rows.Count, 2).End(xlUp).Row

For i = 6 To LastRow

    mydate = Sheet2.Cells(i, 2)

    If mydate >= Sheet1.Cells(7, 19) And mydate <= Sheet1.Cells(8, 19) Then
    erow = Sheet3.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
    Sheet2.Range(Sheet2.Cells(i, 2), Sheet2.Cells(i, 57)).Copy Destination:=Sheet3.Cells(erow, 2)
    End If
Next i

ZeroIsteadBlank
End Sub

I call the function after For loop, but this is what I get:

Row 9 still exist with bunch of zero with additional date in Cell B9

A: Please, use this code at the end. Iterating during the copying code is waste of time and Excel resources:
Sub ZeroIsnteadBlank()
  Dim sh As Worksheet, rngEmpty As Range, LastRow2 As Long

  Set sh = Sheet3
  LastRow2 = sh.Cells(Rows.Count, 2).End(xlUp).Row + 1 '+ 1 for an extra row...

  On Error Resume Next 'Otherwise, the following line will return an error in case of no empty cells...
   Set rngEmpty = sh.Range("C6:H" & LastRow2).SpecialCells(xlCellTypeBlanks)
   If Not rngEmpty Is Nothing Then
        rngEmpty.value = 0
   Else
        MsgBox "No empty cells..."
   End If
  On Error GoTo 0
End Sub

In order to avoid the case of an empty cell of the column C:C (C8 in your example), it should be good to calculate LastRow2 for two columns and choose the bigger one...


text:
Q: Saving multiple fields as array I'm adding a settings section to a theme that will allow the user to enter testimonials which will be randomly displayed on the site. Each testimonial has 2 fields, author and testimonial, I've registered my settings as below:
register_setting( 'settings-website', 'option_testimonials', 'save_testimonials' );

And I want to store an array within that option like this:
array(3) {
  [0]=>
  array(2) {
    ["author"]=>
    string(8) "Person A"
    ["testimonial"]=>
    string(14) "Great website!"
  }
  [1]=>
  array(2) {
    ["author"]=>
    string(8) "Person B"
    ["testimonial"]=>
    string(15) "Excellent work!"
  }
  [2]=>
  array(2) {
    ["author"]=>
    string(8) "Person C"
    ["testimonial"]=>
    string(10) "Brilliant!"
  }
}

My options form looks like this:
<?php
$testimonials = get_option('option_testimonials');
if( !is_array($testimonials) )
    $testimonials = array();
?>

Testimonials

<form method="post" action="options.php">
    <?php settings_fields( 'ddtheme-settings-testimonials' ); ?>

        <?php foreach( $testimonials as $testimonial ) { ?>

        Testimonial

        <?php } ?>

        New testimonial

            Author:

            <input type="text" name="author" style="width: 400px;" />

            Testimonial:

            <textarea name="testimonial" style="width: 400px;"></textarea>

    <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />

</form>

So I thought I could grab the input from the author and testimonial fields inside save_testimonials, combine them into an array and append that to the existing array and save but the $_POST and $_REQUEST are both empty inside that callback.
How can I do this?

A: You'd probably be best to use add_settings_field and add_settings_section...
But in any case, save_testimonials is your validation / save callback function. It is given the data from the form and its job is to check it and then return the validated options. You shouldn't be touching $_POST or $_REQUEST - that's the point of the settings api.
save_callback{$array_of_data_from_form){

     //Validate the $array_of_data_from_form

     $validated=array()//Your settings array after validation

    return $validated;
}`

But it will only recieve data with input name option_testimonials as registered in your register_setting. So your input fields will need names like option_testimonials[testimonial] and option_testimonials[author].
Best practise dictates that you should prefix your option names (option_testimonials is a bit too generic).
As far tutorials go concerning the settings API you can't go far wrong with this post.


text:
Q: How to configure a network bridge without IP (Ubuntu 16.04)? I am trying to set up an LXD hypervisor that is connected to two networks: interface eth0 connects to a private network (i.e. 192.168.192.0/24) and interface eth1 connects to a small network with 16 public IPs (i.e. 8.8.8.0/28).
My goal is to be able to attach the LXD containers to either one of these networks and have corresponding IPs assigned to them by the DHCP service that already is available in these networks. This will require configuration of two bridges on the LXD host in /etc/network/interfaces, for example like this for br0 and eth0:
auto br0
iface br0 inet dhcp
bridge-ifaces eth0
bridge-ports eth0
up ifconfig eth0 up

iface eth0 inet manual

This bridge br0 will be assigned an IP from the private network so the LXD host can be managed through this IP. This is fine.
On the other hand, I want to configure the bridge br1 for the second network with the public IP range so that the LXD host does not get an IP. I want to avoid "sacrificing" one of the few precious 16 public IPs for the host (sice it already has a private IP). In essence, I want to configure a bridge without IP but still allow the LXD containers to use this bridge just like br0.
Is there a way to achieve that and "hide" br1 from the host? Thanks for your help.

A: Create the br1 bridge without IP in your /etc/network/interfaces:
auto br1
iface br1 inet static
    address 0.0.0.0
    bridge_ports eth1

A: As I now found on http://manpages.ubuntu.com/manpages/xenial/man5/bridge-utils-interfaces.5.html, there is an additional and even shorter way of configuring this type of bridge (which by the way appears to be called anonymous bridge):
auto br1
iface br1 inet manual
    bridge_ports eth1


text:
Q: cakephp session id Empty The session id is empty when I do: pr($this->Session);
I receive :
SessionComponent Object
(
    [__active] => 1
    [__bare] => 0
    [valid] => 1
    [error] =>
    [_userAgent] => 5343528de22b8a6d25e7fd391692c911
    [path] => /profiles
    [lastError] =>
    [security] => medium
    [time] => 800-452-3639
    [sessionTime] => 800-452-3639
    [cookieLifeTime] => 720000
    [watchKeys] => Array
        (
        )

    [id] =>
    [host] => xyz.org
    [timeout] =>
    [enabled] => 1
)

How do I either enable the session id or make the session id?

A: If you really want a session id, you need to start the session. Try this in your before filter:
$this->Session->start();
$this->Session->id(session_id());

Then when you pr($this->Session->id()); you will see the new session id.

A: It's passively taken care of by Cake - you don't need to set it.  Just make calls to read(), write() as needed.
$this->Session->write('key', $value);

$value = $this->Session->read('key');

A: Just use

echo $this->Session->id(); //prints like 7gl7bo9gv38rj0sjtqo52dkeu5

in controller. There is no need to start() or something else. Cakephp (tested in 2.7) automatically makes it available for you.


text:
Q: android studio button textwiew gestures They are constantly moving how do I make them fixed
I made a random application but when you press the button, the textview and button are constantly changing. How can I prevent this? As below pictures
enter image description here
enter image description here
enter image description here
the codes I use in these
<TextView
        android:id="@+id/tw1"
        android:textSize="15dp"
        android:text=""
        android:gravity="center"
        android:textIsSelectable="true"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn1"
        android:text="random"
        android:textSize="50dp"
        android:layout_centerInParent="true"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

A: The problem is that you are using a LinearLayout and its children are laid out horizontally by default. Based on the length of the text in your TextView is 'pushing' the Button to the right (horizontally). If you want to change this behavior consider using a different layout or change the orientation of the current LinearLayout by doing so:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

LinearLayout children orientation


text:
Q: Insert empty space before appending div in jquery to a existing element? How do I add a space between my comonpent that I am going to append to and my div that I am dynamically create.
I have some text in my cell and I am dynamically attaching a button to it using jquery. How can I insert a space between the text and the button in the below method so that there is a small gap between the text and the button.
onCellPrepared(e:any) {
    if (e.area == 'row') {
      if (e.cell && e.cell.type == "D") {
        $("<div /> ").dxButton({
          icon: 'fa fa-cog',
          type: 'default',
          height: '25',
          width: '30',
          onClick: function (e) {
            alert(e.rowPath);
          }
        }).appendTo(e.cellElement);
      }
    }
  }

A: add backspace LIKE:
$("<div /> ").html(' ').dxButton({/*..............*/}).appendTo(e.cellElement);

or style for div:
 $("<div /> ").dxButton({/*..............*/}).css('margin-left'.'10px').appendTo(e.cellElement);


text:
Q: How to send multiple parameters to php file via url encoding So, I am trying to post a subject and the content of the textarea whose id is "main" and based on the subject, the php will insert the content to the right database. But something goes wrong and the insertion does not happen, probably because I am doing something wrong with the url. Here is my code:
function saveContent(){
    const note = document.getElementById("main").value;
    console.log(note);
    const subjectToSend = subject;
    let param = "content="+note+"-subject="+subjectToSend;
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
    }
    xmlhttp.open('POST', 'index.php');
    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xmlhttp.send(param);
}


text:
Q: Preventing CSRF in Angular 2 / ASP.NET MVC application I am working on a sample SPA using ASP.NET MVC for back end and Angular 2 for front end.
I followed below steps to prevent cross site request forgery attacks in my application

*

*Since ASP.NET MVC sends a cookie with name "__RequestVerificationToken",  and expects a header with name  "__RequestVerificationToken" in the HTTP request to prevent CSRF , I have added below code in my angular module
{provide: XSRFStrategy, useFactory: xsrfFactory}

where   xsrfFactory is below function
export function xsrfFactory() {
    return new CookieXSRFStrategy('__RequestVerificationToken', '__RequestVerificationToken');
}

*And below is the controller action code with "[ValidateAntiForgeryToken]" attribute , to which an AJAX call will be made using Http service of Angular 2.
[CustomAuth]
[ValidateAntiForgeryToken]
public ActionResult GetAuthors()
{

    List<BookStoreAdmin.ViewModels.Author> authors = BookStoreAdmin.BAL.Author.GetAuthors();

    BookStoreAdmin.ViewModels.Response<List<BookStoreAdmin.ViewModels.Author>> response = new Response<List<ViewModels.Author>>();

    response.success = true;
    response.errorMessage = null;
    response.data = authors;

    return Json(response, JsonRequestBehavior.AllowGet);
}

*Below is the code which makes the AJAX call .
 loadAuthors(): Observable<AuthorModel[]> {

     return this.http.get('http://localhost:57599/author/GetAuthors')
    .map((data) => data.json());

 }

When my application makes an AJAX call using Http angular service , I was expecting it to have request header with name "__RequestVerificationToken" , but this
header is missing   , any idea what could be the reason ?
Please let me know if more information needs to be provided ?

A: I can't see if you are passing a header in angular2 http call.
You can use RequestOptions API which allows you to add header. After adding header when you make request, ValidateAntiForgeryToken should be able to receive sent header.
Read more of RequestOptions here :
https://angular.io/docs/ts/latest/api/http/index/RequestOptions-class.html

A: Late answer but might be useful for someone.
I think the header is not set because this is a GET request. Though this is Angular 2, the angular 4 security docs might be relevant here as they state that

By default, an interceptor sends this cookie on all mutating requests (POST, etc.) to relative URLs but not on GET/HEAD requests or on requests with an absolute URL.

In order to explicitly include this header as @micronyks states in his answer you can use the RequestOptions API. Here's a code sample
var headers = new Headers();
headers.append('__RequestVerificationToken', <token>);
return this.http.get(url, {headers: headers});


text:
Q: Scala: How to decode a List of objects with Circe My GreedIndex decoder is not working but I cannot seem to figure out why; I reckon it is something really silly.
I'm thinking it might be the timeStamp or problems with List[CryptoData]
case class CryptoData(greedValue: String, valueClassification: Sentiment, timeStamp: Long)

case class GreedIndex(name: String, data: List[CryptoData])

object GreedIndex {
  implicit val greedDecoder: Decoder[GreedIndex] = Decoder.instance { json =>

    for {
      name <- json.get[String]("name")
      data <- json.get[List[CryptoData]]("data")
    } yield GreedIndex(name, data)
  }
}

object CryptoData {

  implicit val cryptoDecoder: Decoder[CryptoData] = Decoder.instance { json =>
    val data = json.downField("data").downArray
    for {
      value               <- data.get[String]("value")
      valueClassification <- data.get[Sentiment]("value_classification")
      timestamp           <- data.get[String]("timestamp")
    } yield CryptoData(value, valueClassification, timestamp.toLong * 1000)
  }

}

JSON object I am trying to decode.
{
  "name" : "Fear and Greed Index",
  "data" : [
    {
      "value" : "53",
      "value_classification" : "Neutral",
      "timestamp" : "1631750400",
      "time_until_update" : "17264"
    },
    {
      "value" : "49",
      "value_classification" : "Neutral",
      "timestamp" : "1631664000"
    },
    {
      "value" : "30",
      "value_classification" : "Fear",
      "timestamp" : "1631577600"
    }
  ],
  "metadata" : {
    "error" : null
  }
}

A: Here's how to do it:
import io.circe._
import io.circe.generic.extras.semiauto.deriveEnumerationDecoder
import io.circe.generic.semiauto.deriveDecoder

case class CryptoData(
    greedValue: String,
    valueClassification: Sentiment,
    timeStamp: Long
)

object CryptoData {
  implicit val decoder = Decoder.forProduct3(
    "value",
    "value_classification",
    "timestamp"
  )(CryptoData.apply)
}

sealed trait Sentiment
object Sentiment {
  object Neutral extends Sentiment
  object Fear extends Sentiment

  implicit val decoder: Decoder[Sentiment] = deriveEnumerationDecoder
}

case class GreedIndex(name: String, data: List[CryptoData])

object GreedIndex {
  implicit val greedDecoder: Decoder[GreedIndex] = deriveDecoder
}

The field names for GreedIndex match those in the JSON, so you can just use deriveDecoder in that case. For CryptoData this is not the case, so you need to write it manually with forProduct3.
Since you haven't defined Sentiment, I've modeled it as an enumeration. If you were to use deriveDecoder for this, you'd have to model it like this in the JSON: {"Neutral": {}}. To employ a simple String format, you need to instead use deriveEnumerationDecoder from the circe-generic-extras module.


text:
Q: C++ controlling memory access and pointer dereferencing I am writing an API in C++ where I want to restrict what a programmer can do with pointers to objects the API creates.
For example,
// API
class object {
  // details unimportant
};

// Programmer's code
object o;               // OK
object *op = &o;        // OK
long *lp = (long *)op;  // No
object o2 = op[100];    // No

I understand that some of this is probably difficult or impossible given C++'s type system. Are there ways to enforce this kind of type usage pattern? Are there ways to restrict the available operations on a given pointer type? Would something like overloading object's operator& work?
class object {
  object_pointer operator&();
};

A: There is no way in C++ to prevent C-style casting of pointers.  Any (non-function) pointer may be C-style cast to any other pointer type.
And given a pointer, there is no way to tell the compiler "This is definitely not an array."  So you can't prevent op[100] either.
What you could do is hide all the members of the class itself, e.g. using the Pimpl idiom or C-style opaque structures/classes.  But this won't help you in terms of restricting users' abilities to obtain pointers to your instances and cast them.
C++ is a language for consenting adults.  If you don't consent, use another language.


text:
Q: How to skip enlisting a certain child module from a parent's maven site Suppose, I have a parent pom with following modules:

moduleA
moduleB
moduleC

Note: I have not created a site.xml for the parent project
When I do a mvn clean site:attach-descriptor site site:stage on the parent project, the index.html file generated in the parent-project-folder/target/staging, displays a modules section enlisting all the modules(moduleA,moduleB and moduleC) that link to their respective staged site content. But I have skipped site generation for moduleB and hence site folder for moduleB is not generated. Is there a way by which I can exclude moduleB from being enlisted in the modules section of the parent project's maven site? Because, if it is present, the link refers to a page not found as there is no site content for this module.


text:
Q: Работа с php api и его зашита Здравствуете у меня ест сервер и база данных и готовый api. Надо создать приложения в android, работа с api управлять база данных. Но проблема в том что клиент могут декомпилировать приложения и спокойно увидит адрес api как
private void getResponce(){
   final Request request = new Request.Builder().url("http://localhost/api/welcome.php?user_login=1&user_password=1").build();
   client.newCall(request).enqueue(new Callback() {
       @Override
       public void onFailure(@NotNull Call call, @NotNull IOException e) {
           runOnUiThread(new Runnable() {
               @Override
               public void run() {
                   Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
               }
           });
       }

       @Override
       public void onResponse(@NotNull Call call, @NotNull Response response){
           runOnUiThread(new Runnable() {
               @Override
               public void run() {
                   try {
                       Toast.makeText(context, response.body().string(), Toast.LENGTH_LONG).show();
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
           });
       }
   });
}

вопрос: Как работать с api безопасно и надежно


text:
Q: MVC View trying to parse 2 strings in Details view
x

not a chance.  if its just done in html locally thats fine, shouldnt have to go back to the server.

A: You can use the ternary operator along with an explicit code nugget (wrap the code in ())

@(Model.unittype == "PRP" && Model.name =="TTO" ? "CISCO" : "---")


text:
Q: Change value of a textbox, compared to another text box value with a ratio I am working on ASP.NET C#.
With Javascript, I need to change the value of a textbox, when another text box value changes with the ratio of 3:2.
For example, if the value in a text is 150, the other textbox value should be 100.

A: Try this,
Javascript:
<script type="text/javascript">
    function fill() {
        document.getElementsByName('txt2')[0].value) = (document.getElementsByName('txt1')[0].value) * (2 / 3);
    }
</script>

Code in body tag:
<form id="form1" runat="server">
<div>
    <%--The text boxes must have numeric values--%>
    <asp:TextBox ID="txt1" runat="server" onchange="javascript:fill();"></asp:TextBox>

    <asp:TextBox ID="txt2" runat="server"></asp:TextBox>
</div>

Hope this helps.

A: use something like this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function change() {
    var t1Val = (document.getElementById("t1")).value;
    (document.getElementById("t2")).value = ((t1Val * 2) / 3);
};
</script>
</head>
<body>

<input id="t1" type="text" onchange="change()"/>
<input id="t2" type="text"/>

</body>
</html>

If is there any validation you need you can write inside change() function.
http://jsfiddle.net/bdd63/1/

A: You may use onchange or onkeyup events on the text box
Add the following java-script function to your html
function ChangeValue() {
    if (document.getElementById('txtval1').value) {
        document.getElementById('txtval2').value=document.getElementById('txtval1').value*2/3;
    }
}

then add two text-boxes with ids txtval1,txtval2 to your html, add onkeyup="ChangeValue(); to the first one


text:
Q: Trying to understand the purpose of HAProxy with Kubernetes in this guide Can someone please skim over this guide and tell me the use case of HAProxy in this guide?
Install and configure a multi-master Kubernetes cluster with kubeadm
I've gone through the guide and set this up.  Everything is working properly between my Kubernetes cluster and HAProxy, from what I can tell.
HAProxy has been set up on a VM separate from my Kubernetes cluster.  The HAProxy IP is 10.1.160.170.
I was hoping to visit my HAProxy IP and be redirected to one of my Kuberenetes nodes that is being load balanced.  This isn't the case.
I can set up an Nginx deployment with:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
spec:
  selector:
    matchLabels:
      run: my-nginx
  replicas: 2
  template:
    metadata:
      labels:
        run: my-nginx
    spec:
      containers:
      - name: my-nginx
        image: nginx
        ports:
        - containerPort: 80

Then create the service:
kubectl expose deployment my-nginx --port=80 --type=NodePort

user@KUBENODE01:~$ kubectl get service
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1       <none>        443/TCP        93d
my-nginx     NodePort    10.108.33.134   <none>        80:30438/TCP   46s

If I now try and visit my HAProxy IP 10.1.160.170, I'm not redirected to my Kubernetes node on port 30438.
user@computer:~/nginx_testing$ curl http://10.1.160.170
curl: (7) Failed to connect to 10.1.160.170 port 80: Connection refused

user@computer:~/nginx_testing$ curl https://10.1.160.170
curl: (7) Failed to connect to 10.1.160.170 port 443: Connection refused

user@computer:~/nginx_testing$ curl 10.1.160.170:30438
curl: (7) Failed to connect to 10.1.160.170 port 30438: Connection refused

Is HAProxy not meant to forward connection requests to the actual Kubernetes nodes in this article?
I've also tried this with the service type LoadBalancer.
Here is my haproxy.cfg:
global
        log /dev/log    local0
        log /dev/log    local1 notice
        chroot /var/lib/haproxy
        stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
        stats timeout 30s
        user haproxy
        group haproxy
        daemon

        # Default SSL material locations
        ca-base /etc/ssl/certs
        crt-base /etc/ssl/private

        # See: https://ssl-config.mozilla.org/#server=haproxy&server-version=2.0.3&config=intermediate
        ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:EC>
        ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
        ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        timeout connect 5000
        timeout client  50000
        timeout server  50000
        errorfile 400 /etc/haproxy/errors/400.http
        errorfile 403 /etc/haproxy/errors/403.http
        errorfile 408 /etc/haproxy/errors/408.http
        errorfile 500 /etc/haproxy/errors/500.http
        errorfile 502 /etc/haproxy/errors/502.http
        errorfile 503 /etc/haproxy/errors/503.http
        errorfile 504 /etc/haproxy/errors/504.http

frontend kubernetes
# bind 10.1.160.170:80
bind 10.1.160.170:6443
# http-request redirect scheme https unless { ssl_fc }
option tcplog
mode tcp
default_backend kubernetes-master-nodes

backend kubernetes-master-nodes
mode tcp
balance roundrobin
option tcp-check
server kubenode01 10.1.160.79:6443 check fall 3 rise 2
server kubenode02 10.1.160.80:6443 check fall 3 rise 2
server kubenode03 10.1.160.81:6443 check fall 3 rise 2

A: The port 6443 is for k8s API server.
kubectl access this API server to do its work.
In k8s scenario with one master, you can access k8s API with that masters node IP.
But in k8s scenario with 3 master which is considered HA setup you should use load balancing even you can still access any of master directly because thats the whole point.
For example in HA setup you should set your server address to HAProxy IP in your kubeconfig file so your kubectl commands will be redirect to one of the masters which is healthy, by HAProxy


text:
Q: Strange error in parent descendant jquery selector I have read the tutorial about jquery selectors.
it is mentioned that:
parent descendant - $("div p") - All
 elements that are descendants of a
 element
they provided a demo which works fine:
but i still can't able to figure out why this won't worked:

 The backgroud color don't changed

jsfiddle DEMO

A: Your markup is wrong

 The backgroud color don't changed

you can not have
 tag indside p tag
so browser render this as

 The backgroud color don't changed

So your below selector doesn't work. as there is no span inside class ee
$(".ee span").css("background-color","yellow");

The P element represents a paragraph. It cannot contain block-level
  elements (including P itself).

http://www.w3.org/TR/html401/struct/text.html#h-9.3.1


text:
Q: Nested IF statements in formula field I'd like to have a field which contains the value of the final system size if it exists, the post system size if that exists, or the value of the regular system size otherwise. The formula I have is here: IF(NOT(ISNULL(Final_System_Size__c)),
    VALUE(Final_System_Size__c),
    IF(NOT(ISNULL(Post_System_Size__c)),
        Post_System_Size__c,
        System_Size__c))
This only grabs the final system size, even when its empty and system size and post system size have values. What's causing the other two values to be ignored?

A: Since field Final_System_Size__c is text and formula return type is number.
Empty fields are treated as blanks or zeroes. Meaning that NOT(ISNULL(Final_System_Size__c)) always will return false, thats why you see Final_System_Size__c.
If you select option Treat blank fields as blanks to true, ISBLANK(Final_System_Size__c) will return true/false, based on its parameter.
try to modify to:
IF(NOT(ISBLANK(Final_System_Size__c)),
VALUE(Final_System_Size__c),
IF(NOT(ISBLANK(Post_System_Size__c)),
Post_System_Size__c,
System_Size__c))


text:
Q: Queue Using Deuce STM I am new to Deuce STM and was wondering how do I go about implementing a queue using Deuce STM. Here is my current working implementation -
The Node class contains two fields - value and pointer to the next field.
public class STMQueue {

Node head, tail;

public STMQueue() {
    Node sentinel = new Node(-1);

    tail = sentinel;
    head = sentinel;
}

@Atomic
public void enq(int x) {
    Node node = new Node(x);
    tail.next = node;
    tail = node;
}

@Atomic
public int deq() throws EmptyException{
    Node node = head.next;
    if(node == null) {
        throw new EmptyException();
    }
    int retVal = node.value;
    head = node;
    return retVal;
}

}

Is this the correct way of implementing it? Do we have to manually throw a Transaction Exception? If this is correct, then how do we measure the number of transactions aborted
or retried?

A: I've never worked with DeuceSTM. Having said that, a couple of notes:

*

*It appears your empty check is wrong; Should be if (node == sentinel) based on your constructor.

*This message from Guy Korland leads me to believe that statistics aren't implemented; You'll have to modify the Context object it seems...


text:
Q: Error "data not defined" when trying to use d3.csv? I am trying to plot a scatter graph using the iris dataset in the csv format.Here I am using d3 v4. The HTML code for the same is as follows.
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3 Page Template</title>
        <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">

           d3.csv('iris.csv',function(error,data){

            data.forEach(function(d){

              d.SepalLength= +d.SepalLength;
              d.SepalWidth = +d.SepalWidth;
              d.PetalLength = +d.PetalLength;
              d.Species = d.Species;
            });

          });

          // declare height and width of the svg element

          var w =800;
          var h = 500;

          var svg = d3.select('body')
          .append('svg')
          .attr('height',h)
          .attr('width',w);

          // defining scales
          var xScale = d3.scaleLinear()
          .domain([0,d3.max(function(d){return d.PetalLength})])
          .range([0,w]);
          var yScale = d3.scaleLinear()
          .domain([0,d3.max(function(d){return d.SepalLength})])
          .range([h,0]);

          svg.selectAll('circle')
          .data(data)
          .enter()
          .attr('cx',function(d){return xScale(d.PetalLength);})
          .attr('cy',function(d){return yScale(d.SepalLength);})
          .attr('fill',function(d){return 'red';})

        </script>
    </body>
</html>

The dataset I am using is as follows
"","SepalLength","SepalWidth","PetalLength","PetalWidth","Species"
"1",5.1,3.5,1.4,0.2,"setosa"
"2",4.9,3,1.4,0.2,"setosa"
"3",4.7,3.2,1.3,0.2,"setosa"
"4",4.6,3.1,1.5,0.2,"setosa"
"5",5,3.6,1.4,0.2,"setosa"
"6",5.4,3.9,1.7,0.4,"setosa"
"7",4.6,3.4,1.4,0.3,"setosa"
"8",5,3.4,1.5,0.2,"setosa"
"9",4.4,2.9,1.4,0.2,"setosa"
"10",4.9,3.1,1.5,0.1,"setosa"
"11",5.4,3.7,1.5,0.2,"setosa"
"12",4.8,3.4,1.6,0.2,"setosa"
"13",4.8,3,1.4,0.1,"setosa"
"14",4.3,3,1.1,0.1,"setosa"
"15",5.8,4,1.2,0.2,"setosa"
"16",5.7,4.4,1.5,0.4,"setosa"
"17",5.4,3.9,1.3,0.4,"setosa"
"18",5.1,3.5,1.4,0.3,"setosa"
"19",5.7,3.8,1.7,0.3,"setosa"
"20",5.1,3.8,1.5,0.3,"setosa"
"21",5.4,3.4,1.7,0.2,"setosa"
"22",5.1,3.7,1.5,0.4,"setosa"
"23",4.6,3.6,1,0.2,"setosa"
"24",5.1,3.3,1.7,0.5,"setosa"
"25",4.8,3.4,1.9,0.2,"setosa"
"26",5,3,1.6,0.2,"setosa"
"27",5,3.4,1.6,0.4,"setosa"
"28",5.2,3.5,1.5,0.2,"setosa"
"29",5.2,3.4,1.4,0.2,"setosa"
"30",4.7,3.2,1.6,0.2,"setosa"
"31",4.8,3.1,1.6,0.2,"setosa"
"32",5.4,3.4,1.5,0.4,"setosa"
"33",5.2,4.1,1.5,0.1,"setosa"
"34",5.5,4.2,1.4,0.2,"setosa"
"35",4.9,3.1,1.5,0.2,"setosa"
"36",5,3.2,1.2,0.2,"setosa"
"37",5.5,3.5,1.3,0.2,"setosa"
"38",4.9,3.6,1.4,0.1,"setosa"
"39",4.4,3,1.3,0.2,"setosa"
"40",5.1,3.4,1.5,0.2,"setosa"
"41",5,3.5,1.3,0.3,"setosa"
"42",4.5,2.3,1.3,0.3,"setosa"
"43",4.4,3.2,1.3,0.2,"setosa"
"44",5,3.5,1.6,0.6,"setosa"
"45",5.1,3.8,1.9,0.4,"setosa"
"46",4.8,3,1.4,0.3,"setosa"
"47",5.1,3.8,1.6,0.2,"setosa"
"48",4.6,3.2,1.4,0.2,"setosa"
"49",5.3,3.7,1.5,0.2,"setosa"
"50",5,3.3,1.4,0.2,"setosa"
"51",7,3.2,4.7,1.4,"versicolor"
"52",6.4,3.2,4.5,1.5,"versicolor"
"53",6.9,3.1,4.9,1.5,"versicolor"
"54",5.5,2.3,4,1.3,"versicolor"
"55",6.5,2.8,4.6,1.5,"versicolor"
"56",5.7,2.8,4.5,1.3,"versicolor"
"57",6.3,3.3,4.7,1.6,"versicolor"
"58",4.9,2.4,3.3,1,"versicolor"
"59",6.6,2.9,4.6,1.3,"versicolor"
"60",5.2,2.7,3.9,1.4,"versicolor"
"61",5,2,3.5,1,"versicolor"
"62",5.9,3,4.2,1.5,"versicolor"
"63",6,2.2,4,1,"versicolor"
"64",6.1,2.9,4.7,1.4,"versicolor"
"65",5.6,2.9,3.6,1.3,"versicolor"
"66",6.7,3.1,4.4,1.4,"versicolor"
"67",5.6,3,4.5,1.5,"versicolor"
"68",5.8,2.7,4.1,1,"versicolor"
"69",6.2,2.2,4.5,1.5,"versicolor"
"70",5.6,2.5,3.9,1.1,"versicolor"
"71",5.9,3.2,4.8,1.8,"versicolor"
"72",6.1,2.8,4,1.3,"versicolor"
"73",6.3,2.5,4.9,1.5,"versicolor"
"74",6.1,2.8,4.7,1.2,"versicolor"
"75",6.4,2.9,4.3,1.3,"versicolor"
"76",6.6,3,4.4,1.4,"versicolor"
"77",6.8,2.8,4.8,1.4,"versicolor"
"78",6.7,3,5,1.7,"versicolor"
"79",6,2.9,4.5,1.5,"versicolor"
"80",5.7,2.6,3.5,1,"versicolor"
"81",5.5,2.4,3.8,1.1,"versicolor"
"82",5.5,2.4,3.7,1,"versicolor"
"83",5.8,2.7,3.9,1.2,"versicolor"
"84",6,2.7,5.1,1.6,"versicolor"
"85",5.4,3,4.5,1.5,"versicolor"
"86",6,3.4,4.5,1.6,"versicolor"
"87",6.7,3.1,4.7,1.5,"versicolor"
"88",6.3,2.3,4.4,1.3,"versicolor"
"89",5.6,3,4.1,1.3,"versicolor"
"90",5.5,2.5,4,1.3,"versicolor"
"91",5.5,2.6,4.4,1.2,"versicolor"
"92",6.1,3,4.6,1.4,"versicolor"
"93",5.8,2.6,4,1.2,"versicolor"
"94",5,2.3,3.3,1,"versicolor"
"95",5.6,2.7,4.2,1.3,"versicolor"
"96",5.7,3,4.2,1.2,"versicolor"
"97",5.7,2.9,4.2,1.3,"versicolor"
"98",6.2,2.9,4.3,1.3,"versicolor"
"99",5.1,2.5,3,1.1,"versicolor"
"100",5.7,2.8,4.1,1.3,"versicolor"
"101",6.3,3.3,6,2.5,"virginica"
"102",5.8,2.7,5.1,1.9,"virginica"
"103",7.1,3,5.9,2.1,"virginica"
"104",6.3,2.9,5.6,1.8,"virginica"
"105",6.5,3,5.8,2.2,"virginica"
"106",7.6,3,6.6,2.1,"virginica"
"107",4.9,2.5,4.5,1.7,"virginica"
"108",7.3,2.9,6.3,1.8,"virginica"
"109",6.7,2.5,5.8,1.8,"virginica"
"110",7.2,3.6,6.1,2.5,"virginica"
"111",6.5,3.2,5.1,2,"virginica"
"112",6.4,2.7,5.3,1.9,"virginica"
"113",6.8,3,5.5,2.1,"virginica"
"114",5.7,2.5,5,2,"virginica"
"115",5.8,2.8,5.1,2.4,"virginica"
"116",6.4,3.2,5.3,2.3,"virginica"
"117",6.5,3,5.5,1.8,"virginica"
"118",7.7,3.8,6.7,2.2,"virginica"
"119",7.7,2.6,6.9,2.3,"virginica"
"120",6,2.2,5,1.5,"virginica"
"121",6.9,3.2,5.7,2.3,"virginica"
"122",5.6,2.8,4.9,2,"virginica"
"123",7.7,2.8,6.7,2,"virginica"
"124",6.3,2.7,4.9,1.8,"virginica"
"125",6.7,3.3,5.7,2.1,"virginica"
"126",7.2,3.2,6,1.8,"virginica"
"127",6.2,2.8,4.8,1.8,"virginica"
"128",6.1,3,4.9,1.8,"virginica"
"129",6.4,2.8,5.6,2.1,"virginica"
"130",7.2,3,5.8,1.6,"virginica"
"131",7.4,2.8,6.1,1.9,"virginica"
"132",7.9,3.8,6.4,2,"virginica"
"133",6.4,2.8,5.6,2.2,"virginica"
"134",6.3,2.8,5.1,1.5,"virginica"
"135",6.1,2.6,5.6,1.4,"virginica"
"136",7.7,3,6.1,2.3,"virginica"
"137",6.3,3.4,5.6,2.4,"virginica"
"138",6.4,3.1,5.5,1.8,"virginica"
"139",6,3,4.8,1.8,"virginica"
"140",6.9,3.1,5.4,2.1,"virginica"
"141",6.7,3.1,5.6,2.4,"virginica"
"142",6.9,3.1,5.1,2.3,"virginica"
"143",5.8,2.7,5.1,1.9,"virginica"
"144",6.8,3.2,5.9,2.3,"virginica"
"145",6.7,3.3,5.7,2.5,"virginica"
"146",6.7,3,5.2,2.3,"virginica"
"147",6.3,2.5,5,1.9,"virginica"
"148",6.5,3,5.2,2,"virginica"
"149",6.2,3.4,5.4,2.3,"virginica"
"150",5.9,3,5.1,1.8,"virginica"

When I run this on the browser and open console, the browser throws this error ReferenceError: data is not defined. According to the FireFox documentation, this appears when the mentioned variable is not defined correctly.
Is the d3.csv() function used correctly? Thank you for the help in advance!

A: Here is a slightly modified version of your code whose only goal is to at least display something in your page. There would be a lot more to do to make it pretty, but at least you'll have something to start with:
d3.csv('iris.csv',function(error,data){

  data.forEach(function(d) {
    d.SepalLength= +d.SepalLength;
    d.SepalWidth = +d.SepalWidth;
    d.PetalLength = +d.PetalLength;
    d.Species = d.Species;
  });

  var w = 800;
  var h = 500;

  var svg = d3.select('body')
  .append('svg')
  .attr('height',h)
  .attr('width',w);

  var xScale = d3.scaleLinear()
    .domain([0, d3.max(data.map(p => p.PetalLength))])
    .range([0,w]);
  var yScale = d3.scaleLinear()
    .domain([0, d3.max(data.map(p => p.SepalLength))])
    .range([h,0]);

  svg.selectAll('circle')
    .data(data)
    .enter()
    .append("circle")
    .attr('cx',function(d){return xScale(d.PetalLength);})
    .attr('cy',function(d){return yScale(d.SepalLength);})
    .attr('r', 10)
    .attr('fill',function(d){return 'red';})
});

First, as you need to access data to create the svg graph, you have to include the creation of the graph within the block which extracts data. Thus you should close the d3.csv('iris.csv',function(error,data){ block after the last line which defines your graph.
This first step allows us to get rid of the error you mentioned.

Then the definition of the circles needs some tweaking:
svg.selectAll('circle')
  .data(data)
  .enter()
  .append("circle")
  .attr('cx',function(d){return xScale(d.PetalLength);})
  .attr('cy',function(d){return yScale(d.SepalLength);})
  .attr('r', 10)
  .attr('fill',function(d){return 'red';})

The append("circle") part creates the d3 circle elements.
And the r attribute defines the radius of circles.

Finally, we can tweak the scaling in order to position the circles by adjusting the scale:
var xScale = d3.scaleLinear()
  .domain([0, d3.max(data.map(p => p.PetalLength))])
  .range([0,w]);


text:
Q: Tensor calculation : find interface node using torch calculation I'm a newbie on pytorch. I have a problem with efficient tensor calculation using pytorch. It is not easy for me to avoid using for loop.
What I want to do is:
There are N "guest" groups with M points with x,y,z coordinates. ( G:  N x M x 3 )
There is a "host" group with N points with x,y,z coordinate( H: M x 3 or 1 x M x 3)
I want to identify points of "guest" groups(interface points), which are close enough(distance < 8) with at least K points of host group.
I hope to have list of indexes that can access coordinates of interface points using G (ex. G[x][y][:])
Really thanks for reading.


text:
Q: Как сделать так, что бы все *.php файлы открывались по ссылке *.png? Подскажите пожалуйста, как с помощью .htaccess и mod_rewrite сделать так, что бы все *.php файлы открывались по ссылке *.png?
P.S. Именно для каталога /image/
A: mod_rewrite
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule image/(.*)\.png$ /image/$1.php [L]

на вскидку, можно конечно редиректить на 1 статический файл, например:
RewriteRule image/(.*)$ /image/image.php?file=$1 [L]

а внутри скрипта уже пытатся вывести нужный файл.
A: А еще есть codeigniter, в котором можно к каждому контролеру прибавить любое расширение, хоть index.hfgfgf
Читай добавление суффикса PHP


text:
Q: How to use xpath to count by text content Counting the number of "Hello" occurrences. "Hello" is Case Sensitive.
<test>
    <item>
        <id>hello</id>
    </item>
    <item>
        <id>Hello</id>
    </item>
</test>

A: Ok I got the answer by myself.
The query must be like this:
SELECT

ISNULL(COL_XML.value('count(/test/item/id[text()="Hello"])','INT'), 0)

FROM MY_TABLE;

Be aware that the text you are looking for in this case "Hello" is Case Sensitive.


text:
Q: Firebase Android - create node from keys in an Arraylist I have an ArrayList full of specific keys. How would I go about making a new node with just the keys in the Arraylist?

A: Could you elaborate more? What have you managed to do so far? If for example i have an arraylist of strings containing two items, item1 and item2, then i can loop through the arraylist and pushing the string to your firebase server as the key. For example
ArrayList<String> myArray= new ArrayList<>();
myArray.add(item1);
myArray.add(item2);

for (int i =0; i<myArray.size();i++){
    String key = myArray.get(i) ;

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference();
    ref.child(key);
    ref.child(key).child("itemUnderThisKey").setValue("value you want to set")

}

This is how ur firebase structure will look like :

Best thing is to understand the firebase data structures and you can make them suite your whatever needs. Hope the above will help.

A: Assuming you have an ArrayList that look like this:
List<String> list = new ArrayList<>();

To create a new node using only the keys, please use the folliwing code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
for(String s : list) {
    rootRef.child("yourNode").child(s).setValue(true);
}

And your database structure will look like this:
Firebase-root
   |
   --- yourNode
          |
          --- arraListKey1: true
          |
          --- arraListKey2: true
          |
          --- //and so on


text:
Q: Customer account EDT without referential integrity I maintain a table of some specific configuration informations for customers.
The identifier of this table is the customer account, the CustAccount EDT.
Now I face a problem : this configuration information must sometimes be defined before the customer is created.
Is there a way to create a non-restrictive EDT, which will be related to CustAccount (we can select the value among existing accounts), but which allows other values than existing accounts ?

A: Yes. You want to look at examples in the AOT that use the base enum TableGroupAll. For your case, you'd probably create a new EDT called TableAll (Which exists in AX2012).
Look at how \Data Dictionary\Tables\AssetDisposalParameters works or anything that uses \Data Dictionary\Base Enums\TableGroupAll.
Essentially it's like a 2-field key, where you'd have Table+CustAccount connect to the CustTable, but All would just be a blank CustAccount.

EDIT: Here is an AX 2009 XPO example that you can quickly see working well.
Also, don't do what the other poster suggested. Even in AX 2012 you'd want to do something similar to what I suggested unless you have some very special requirements.

A: You can set IgnoreEDTRelation to yes. Now you can use this EDT without foreign key constraint.
For the lookup part... you need to overwrite a method lookup on the field of a datasource on your form.
public void lookup(FormControl _formControl, str _filterStr)
{
    Query query = new Query();
    QueryBuildDataSource queryBuildDataSource;

    SysTableLookup sysTableLookup = SysTableLookup::newParameters(tableNum(CustTable), _formControl);

    sysTableLookup.addLookupField(fieldNum(CustTable, AccountNum));
    sysTableLookup.addLookupField(fieldNum(CustTable, CustGroup));

    queryBuildDataSource = query.addDataSource(tableNum(CustTable));

    sysTableLookup.parmQuery(query);

    sysTableLookup.performFormLookup();

    //super(_formControl, _filterStr);
}

How to: Add a Lookup Form to a Control
This link shows how to add a custom lookup to a control. But it is more "clean" to overwrite datasource field method so that if you have more than one control on the form using this field all will have this lookup.


text:
Q: gather* and autoaligne errors I am getting errors with this very simple document:
\documentclass{article}

\usepackage{mathtools}
\usepackage{autoaligne}

\begin{document}
\begin{gather*}
  \autoaligne{%
    a_1+a_2=0\\%
    2a_1-a_2=0%
  }
\end{gather*}
\end{document}

The errors are "Missing } inserted." and "Extra }, or forgotten $.". Why are these errors happening?
Also I plan on adding more equations so gather* is necessary.

A: Update
With autoaligne version 1.3, released 2017/02/11, the issue has been solved.

Original answer
It's a bug in autoaligne, which starts its working with
\iffalse{\fi\ifnum`}=0\fi

but doesn't add the corresponding code at the end. Indeed, if I add
\ifnum`{=0\fi\iffalse}\fi

at the end of the code for \autoaligne_iii, your code compiles.
Temporary patch, until the package code is fixed:
\documentclass{article}

\usepackage{mathtools}
\usepackage{autoaligne}

\chardef\saveduscatcode=\catcode`_
\catcode`_=11
\let\saved_autoaligne_iii\autoaligne_iii
\def\autoaligne_iii#1{\saved_autoaligne_iii{#1}\ifnum`{=0\fi\iffalse}\fi}
\catcode`_=\saveduscatcode

\begin{document}

\begin{align}
  \autoaligne{
    a_1+a_2=0\\
    2a_1-a_2=0
  }
\end{align}

\begin{gather*}
  \autoaligne{
    a_1+a_2=0\\
    2a_1-a_2=0
  }
\end{gather*}
\end{document}


text:
Q: Connecting Tableau to a RDS DB in private tier using web proxy I have the following architecture in AWS where the RDS DB is publicly unavailable and is inside a private subnet and I am currently connecting to the database through a ec2 jump box located in the public subnet using ssh port forwarding.

To connect to RDS we have two options.

*

*SSH port forwarding setup on EC2

*Web Proxy on EC2

I am able to connect using the SSH port forwarding option but I am not able to use Tableau as there is no option in Tableau to connect using .pem file which is required for SSH port connection to go through.
I am trying to see if there is documentation that will explain step by step on the process for setting up web proxy on the EC2 so that I can connect Tableau Desktop with the Database using the Elastic IP of the EC2 instance. Any help appreciated.


text:
Q: Serial Port Data Received Event Handler Reliability I am using the Serial Port functionality in C# to communicate with a piece of hardware. Everything writes fine to the serial port, and the serial port is always connected.
For some reason the Serial Port Data Received Handler doesn't always read data coming up (every 1 out of 8 times it fails to read anything or call the event function itself). Everything is fine on the other side. I am only receiving one letter from the serial port which is 1, 2, 3, etc
Here is my code:
Serial Setup:
    //Create new serial port
    SerialPort SerPort = new SerialPort("COM4");

    private void SetupSerial()
    {
        SerPort.BaudRate = 9600;
        SerPort.Parity = Parity.None;
        SerPort.StopBits = StopBits.One;
        SerPort.DataBits = 8;
        SerPort.Handshake = Handshake.None;
        SerPort.ReadTimeout = 4000;
        SerPort.WriteTimeout = 6000;
        SerPort.Open();
        SerPort.DataReceived += new SerialDataReceivedEventHandler(HandleSerialData);

        lblStatus.Text = "Successfully connected to COM port with no errors!";

    }

My Write to Serial function:
       private void WriteToSerial( string data )
    {
        byte[] MyMessage = Encoding.UTF8.GetBytes(data);
        SerPort.Write(MyMessage, 0, MyMessage.Length);

        string time = "[" + DateTime.Now.ToString("HH:mm") + "]";

        bool debug = chkDebug.Checked;
        if (debug ) f.DebugText = time + " Wrote bytes to serial: " + data;
    }

My Recieve event function:
    //Called everytime serial data is recieved
    private void HandleSerialData(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            //Store recieved data in variable
            SerialPort sp = (SerialPort)sender;
            string data = sp.ReadExisting().ToString();

            bool debug = chkDebug.Checked;

            string time = "[" + DateTime.Now.ToString("HH:mm") + "]";
            if( debug ) f.DebugText = time + " Recieved serial data: " + data;

            switch ( data )
            {
                case "1":
                //If Battery is already on
                if( Battery1[0] == "ON")
                {
                    Battery1[0] = "OFF"; //ON or OFF
                    Battery1[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("1");
                    lblST1.Text = "n/a";
                    lblET1.Text = "n/a";
                    if (debug) f.DebugText = time + " Battery 1 testing switched OFF.";
                }
                else
                {
                    Battery1[0] = "ON"; //ON or OFF
                    Battery1[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery1[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST1.Text = Battery1[1];
                        if (debug) f.DebugText = time + " Battery 1 testing switched ON.";
                }
                break;

                case "2":
                //If Battery is already on
                if (Battery2[0] == "ON")
                {
                    Battery2[0] = "OFF";
                    Battery2[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("2");
                    lblST2.Text = "n/a";
                    lblET2.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 2 testing switched OFF.";
                }
                else
                {
                    Battery2[0] = "ON"; //ON or OFF
                    Battery2[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery2[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST2.Text = Battery2[1];
                        if (debug) f.DebugText = time + " Battery 2 testing switched ON.";
                }
                break;

                case "3":
                //If Battery is already on
                if (Battery3[0] == "ON")
                {
                    Battery3[0] = "OFF"; //ON or OFF
                    Battery3[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("3");
                    lblST3.Text = "n/a";
                    lblET3.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 3 testing switched OFF.";
                }
                else
                {
                    Battery3[0] = "ON"; //ON or OFF
                    Battery3[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery3[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST3.Text = Battery3[1];
                        if (debug) f.DebugText = time + " Battery 3 testing switched ON.";
                }
                break;

                case "4":
                //If Battery is already on
                if (Battery4[0] == "ON")
                {
                    Battery4[0] = "OFF"; //ON or OFF
                    Battery4[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("4");
                    lblST4.Text = "n/a";
                    lblET4.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 4 testing switched OFF.";
                }
                else
                {
                    Battery4[0] = "ON"; //ON or OFF
                    Battery4[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery4[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST4.Text = Battery4[1];
                        if (debug) f.DebugText = time + " Battery 4 testing switched ON.";
                }
                break;

                case "5":
                //If Battery is already on
                if (Battery5[0] == "ON")
                {
                    Battery5[0] = "OFF"; //ON or OFF
                    Battery5[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("5");
                    lblST5.Text = "n/a";
                    lblET5.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 5 testing switched OFF.";
                    }
                else
                {
                    Battery5[0] = "ON"; //ON or OFF
                    Battery5[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery5[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST5.Text = Battery5[1];
                        if (debug) f.DebugText = time + " Battery 5 testing switched ON.";
                }
                break;

                case "6":
                //If Battery is already on
                if (Battery6[0] == "ON")
                {
                    Battery6[0] = "OFF"; //ON or OFF
                    Battery6[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("6");
                    lblST6.Text = "n/a";
                    lblET6.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 6 testing switched OFF.";
                }
                else
                {
                    Battery6[0] = "ON"; //ON or OFF
                    Battery6[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery6[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST6.Text = Battery6[1];
                        if (debug) f.DebugText = time + " Battery 6 testing switched ON.";
                }
                break;
            }

            SerPort.DiscardInBuffer();
            SerPort.DiscardOutBuffer();

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error recieving COM data! " + ex.Message);
        }
    }

Is there a better way of reading serial data not using the ReadExisting? Or using a more reliable function?

A: I have had problem in the past with ReadExisting. I don't know what happens in ReadExisting if more data arrives while the buffer is being read.
In serial port even handlers I use the following code. Because it determines the length to read first, new data arriving will be read during the next function call so the buffer can be emptied at the rate data is sent.
private void HandleSerialData(object sender, SerialDataReceivedEventArgs e)
{
    int lengthToRead = sp.BytesToRead;
    byte[] rxBytes = new byte[lengthToRead];
    sp.Read(rxBytes, 0, lengthToRead);
    functionThatInterpratesData(rxBytes);
}

This also has the benefit of being re-usable because you convert the byte array to a string or however you have encoded it separately.
I would create a function to convert you byte array to a string (lots of examples on SO) and another one to handle the case statement.


text:
Q: How can I read from a computed field? In Odoo 9 I have a computed field in a model called page_price.
Class Page(models.Model):
    page_price = fields.Float(compute='compute_page_price')

    def compute_page_price(self):
        self.page_price = 7  # this value is an example

If I show this field in a view, it shows 7.
The problem is when I try to get the value from another model.
Class Book(models.Model):
  book_price = fields.Float(compute='compute_book_price')

  def compute_book_price(self):
    # page_id has the value of a Page row id
    page_price = self.env['Page'].search([('id', '=', page_id)])[0].page_price
    self.book_price = page_price * 10

Here, the value of book_price is always 0 instead of 70.
The vaule of page_price inside the compute_book_price function is 0 instead of 7.
Why is that and how can I obtain the correct value?
Note: If the page_price field is defined as a Float field instead of a computed field, the result of book_price is 70.