text:
Q: JBoss Hibernate: Could not load requested class com.mysql.jdbc.Driver I have an instalation of JBoss that was working with postgresql...
I'm tring to change to mySQL.
I've downloaded mysql-connector-java-5.1.36-bin.jar and put it into JBOSS_HOME/module/com/mysql/main, created the module.xml and changed my standalone.xml.
But whem I try start the server i got the folloing stacktrace:
ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 48) MSC000001: Failed to start service jboss.persistenceunit."myapp.war#myapp": org.jboss.msc.service.StartException in service jboss.persistenceunit."myapp.war#myapp": javax.persistence.PersistenceException: [PersistenceUnit: myapp] Unable to build EntityManagerFactory
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:103)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_20]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_20]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_20]
    at org.jboss.threads.JBossThread.run(JBossThread.java:122) [jboss-threads-2.1.1.Final-redhat-1.jar:2.1.1.Final-redhat-1]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: myapp] Unable to build EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:924)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
    at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:76)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl.createContainerEntityManagerFactory(PersistenceUnitServiceImpl.java:200)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl.access$600(PersistenceUnitServiceImpl.java:57)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:99)
    ... 4 more
Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:111)
    at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
    at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1825)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1783)
    at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
    ... 9 more
Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver]
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:151)
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
    ... 21 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:318)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) [rt.jar:1.8.0_20]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) [rt.jar:1.8.0_20]
    at java.lang.Class.forName0(Native Method) [rt.jar:1.8.0_20]
    at java.lang.Class.forName(Class.java:340) [rt.jar:1.8.0_20]
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:148)
    ... 22 more

Can someone help?
My persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
    http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
    version="2.1">
    <persistence-unit name="myapp">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <!-- Annotated entity classes -->
        <class>br.com.programadoremjava.ginga.test.myapp.entity.MyClassA</class>
        <class>br.com.programadoremjava.ginga.test.myapp.entity.MyClassB</class>

        <properties>
            <!-- DADOS CONEXAO -->
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
            <property name="hibernate.connection.username" value="application" />
            <property name="hibernate.connection.password" value="application" />
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/myapp" />

            <!-- CONFIGURACAO -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
        </properties>

    </persistence-unit>

</persistence>

My standalone.xml datasource configuration:
<subsystem xmlns="urn:jboss:domain:datasources:1.2">
    <datasources>
        <datasource jta="true" jndi-name="java:/myapp-ds" pool-name="test" enabled="true" use-java-context="true" use-ccm="true">
            <connection-url>jdbc:mysql://localhost:3306/myapp</connection-url>
            <driver>com.mysql</driver>
            <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
            <pool>
                <min-pool-size>5</min-pool-size>
                <max-pool-size>30</max-pool-size>
                <prefill>true</prefill>
                <use-strict-min>false</use-strict-min>
                <flush-strategy>FailingConnectionOnly</flush-strategy>
            </pool>
            <security>
                <user-name>application</user-name>
                <password>application</password>
            </security>
            <statement>
                <prepared-statement-cache-size>32</prepared-statement-cache-size>
            </statement>
        </datasource>
        <drivers>
            <driver name="com.mysql" module="com.mysql">
                <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
                <driver-class>com.mysql.jdbc.Driver</driver-class>
            </driver>
        </drivers>
    </datasources>
</subsystem>

My JBOSS_HOME/module/com/mysql/main/module.xml
<module xmlns="urn:jboss:module:1.0" name="com.mysql">
    <resources>
        <resource-root path="mysql-connector-java-5.1.36-bin.jar"/>
    </resources>
    <dependencies>
        <module name="javax.api"/>
    </dependencies>
</module>

A: You have to refer to the as datasource in persistence.xml
<jta-data-source>java:/jdbc/myapp-ds</jta-data-source> and remove all hibernate.connection.* properties. The connection is managed by the application server in that scenario you do not need it to redefine it in hibernate.


text:
Q: JSF - Dynamic amount of tabs in tabView, with dynamic tab contents I'm new to JSF and I'd like your suggestions on how to implement what I need the best way possible. Also first post in StackOverflow, so please excuse me if I'm not clear about something.
I've a p:tabView with a dynamic amount of tabs, generated with c:foreach in the following way, with a view scoped backing bean.
<p:tabView id="tabViewId">
    <c:forEach items="#{controller.list}" var="aTab">
          <p:tab title="#{aTab.label}">
              <ui:include src="#{aTab.firstUrl}"/>
          </p:tab>
    </c:forEach>
</p:tabView>

This works and I'm happy with it. Now the thing is each of my tabs have two possible views, and when a certain event is fired (a p:commandLink is clicked in one of the views) I'd like to change what is shown in the tab to the other view that tab has; in other words, I'd like to change the src view that is loaded inside the tab with ui:include. I've tried to return my desired view path in the method associated to this commandLink in the controller, but as expected it redirects to a new page instead of loading it inside the tab.
I'd like to keep the same controller instance when switching the tab contents (my controller is view scoped), and avoid binding.
I've came with two options.
First would be trying something similar to this (obtained from primefaces tabView different tab content with dynamic tabs), getting the view paths from my "aTab" instead of hardcoding them, and then trying to update the tab or the whole tabView on my commandLink after changing the boolean that switches between the two pages in the controller:
<ui:include
    src="#{curSearch.closeable ? '/sections/search/searchInstanceTab.xhtml' : '/sections/search/firstSearchTab.xhtml'}">
</ui:include>

The second one would be including both pages in every tab, but rendering only one using the boolean in the controller. This sounds much worse to me than the first option (it's suggested as an answer in the question I linked before).
Thanks in advance, please feel free to suggest any easier/better way.
::: EDIT :::
Finally did choose to have each tab in a separate xhtml file (being loaded with the c:foreach loop) and in each xhtml/tab all the possible views (also in separate xhtmls) ui:include'd with a rendered clause, hardcoded.
Pretty smooth solution and works great, which possibly would allow to have dynamic contents inside each tab, with another c:foreach loop inside them and a list of pairs in the backing bean which would contain the xhtml names and booleans for rendering (that'd become a bit crazy).

A: The first option, the view build time conditional one, can lead to problems in some cases. E.g. you won't be able to rely on f:param in the conditional expression.

This sounds much worse to me than the first option

It's not much worse. Creating a bunch of components is not that pricey.
It's not a black and white thing, but my general advice would be to not optimize unless you actually have a performance problem and profiling confirmed that this is the bottleneck (unlikely). Stick to the easiest path, which is using rendered.
For Mojarra you can configure logging like this:
<logger category="javax.enterprise.resource.webcontainer.jsf.timing">
    <level name="DEBUG"/>
</logger>

And then you'll see exactly how much time building the view (the Restore View JSF lifecycle phase) takes compared to your logic and rendering (the other phases):

19:47:57,026 DEBUG [timing] (default task-3)  [TIMING] - [7ms] :
  Execution time for phase (including any PhaseListeners) ->
  RESTORE_VIEW 1
  ...
  19:47:57,198 DEBUG [timing] (default task-3)
  [TIMING] - [172ms] : Execution time for phase (including any
  PhaseListeners) -> RENDER_RESPONSE 6

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there an easy way to capture all Frame/Window keystrokes in Python or wxPython I tried EVT_KEY_DOWN but doesn't work. Is there a way to capture any keystroke such as F1, F2 , ENTER, and others. I am using a Frame and Panel.

A: I used EVT_KEY_DOWN in a dialog subclass. In the __init__ method of your dialog class, bind to EVT_KEY_DOWN:
def __init__(self, ....):
    # ...other init code...
    self.Bind(wx.wx.EVT_KEY_UP, self.handle_key_up)

Then provide a method on your dialog like:
def handle_key_up(self, event):
    keycode = event.GetKeyCode()
    lc = self.list_ctrl_fields

    # handle F2
    if keycode == wx.WXK_F2:
        print "got F2"

(Tested in python 2.6, wxPython 2.8.10.)

A: Is this what you mean? You need to look at Global Accelerators. By coincidence I've been looking at this the last day or two as well. Assuming the wxpython app window has focus, the following should call appropriate routine on keypress. Working on my ubuntu 11.04 / py 2.7.1 / wxpython 2.8
Clearly you could potentially consolidate the event method if required.
There is not much to be found on this topic but this link and this link helped me out (same website)
import wx

class MyFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Global Keypress")
        self.panel = wx.Panel(self, wx.ID_ANY)
        self.CreateStatusBar()

        # Global accelerators

        id_F1 = wx.NewId()
        id_F2 = wx.NewId()

        self.Bind(wx.EVT_MENU, self.pressed_F1, id=id_F1)
        self.Bind(wx.EVT_MENU, self.pressed_F2, id=id_F2)

        accel_tbl = wx.AcceleratorTable([
            (wx.ACCEL_NORMAL, wx.WXK_F1, id_F1 ),
            (wx.ACCEL_NORMAL, wx.WXK_F2, id_F2 )
        ])
        self.SetAcceleratorTable(accel_tbl)

    def pressed_F1(self, event):
        print "Pressed F1"
        return True

    def pressed_F2(self, event):
        print "Pressed F2"
        return True

if __name__ == "__main__":
    app = wx.PySimpleApp()
    f = MyFrame().Show()
    app.MainLoop()

A: See these 2 answers
Detect in python which keys are pressed
Is there a cross-platform python low-level API to capture or generate keyboard events?


text:
Q: Connected to VPN but unable to ping hosts on remote network I have PC2 connected to a VPN (L2TP/IPsec) server I have setup on R2. I need PC2 to be able to ping PC3 and PC4, but it's not working. When I use a Windows machine to connect to the VPN I can ping hosts under R2, but that is not the case with my Linux machine (Raspbian Jessie). I believe the solution has to do with the routing table but I have no idea what I am doing there.
I know that I am connected to R2 from PC2 because when I type 192.168.1.1 into the browser I am greeted with the remote router's login screen.

PC2 is 192.168.1.125 under R1, and it is 192.168.1.69 under R2.
The public IP for R2 is 76.73.240.120. Here is the current routing information:
root@raspberrypi:/home/pi# ip route show
default dev ppp0  scope link
default via 192.168.1.1 dev wlan0  metric 303
76.73.240.120 via 192.168.1.1 dev wlan0
192.168.1.0/24 dev wlan0  proto kernel  scope link  src 192.168.1.125  metric 303
192.168.1.1 dev ppp0  proto kernel  scope link  src 192.168.1.69

What do I need to do in order to get PC2 to be able to ping the hosts under R2?

A: This looks a mess! First things first, routers connect different networks together. As a simplification, if things are on the same network then they should be able to talk to each other directly. You have 2 networks 192.168.1.0/24. The simplest solution would be to renumber one of them (PC1, PC2, R1) to be 192.168.2.0/24.
Let us say that PC3 is on 192.168.1.10.
The reason it is a problem is that you have 3 rules for how to get to PC3, one of them because it matches the 192.168.1.0/24 and two because it matches the default rules  which could also be written 0.0.0.0/0 (once via the ppp0 interface (the tunnel) and once via the wlan0 interface).
The rules are ranked in order, because 24 is more than 0 it is more specific, and hence is used.
So this routing table says that PC2 can communicate directly with PC3 via the wlan0 interface. so when you ping PC3 it uses your wireless card.
If you renumbered PC1, PC2 and R1 to be on the 192.168.2.0/24 network then the rules for where PC2 become much simpler. If the packet has to go to 192.168.2.0/24, then send it via wlan0, otherwise send it to 192.168.1.1 via ppp0.
To get to 192.168.1.1 there are 4 choices 0.0.0.0/0 via ppp0, 0.0.0.0/0 via wlan0, 192.168.1.0/24 via wlan0 and 192.168.1.1/32 via ppp0. The /32 route is the most specific and hence is chosen, which explains why you see R2.
You could add extra routes for PC3 and PC4, something like
ip route add 192.168.1.10/32 dev ppp0
ip route add 192.168.1.11/32 dev ppp0

and hope that R2 sorts things out enough to enable packets to come back, but renumbering is much simpler.


text:
Q: What's the minimum amount of transistors I need to operate a stepper motor? I would like to know the minimum amount of transistors to operate a stepper motor.Could I pilote it with one transistor or I need one transistor for every coil?
Thanks in advance!
Edit: the minimum number N of transistors I should connect to ports to drive the stepper motor.
For example, if I have 4 coils, I think I should have 4 bjt to drive my motor .
My question is actually: does exist a stepper motor with 4 coils that could I drive with only one of these bjt like this?
(I know this last circuit is for dc motor but somebody told me I could drive a stepper motor with this same circuit.... is that true?)

A: What's the minimum amount of transistors I need to pilote a stepper motor?
I don't know what you mean by "pilote", but if you are asking what the minimum number of transistors are to operate a stepper motor, then the answer is 0.
To make a stepper motor rotate, at a minimum you need to switch ends of some coils between open, and connected to a power supply.  This does not require transistors.  You could, for example, manually make the sequence of connections, use relays, or other mechanical means.
A interesting demonstration would be to set up brushes on a shaft to go thru one step sequence.  Each rotation of that control shaft would cause one step in the stepper motor.  It would be kindof like a "electrical gearbox".  You could add a little disclamer to the bottom: "No transistors were abused in the making of this demonstration".

A: For an ordinary stepper motor, you do indeed need four transistors or comparable switches for a unipolar motor, and 8 for a bipolar one.
However, there are some variations.  3-wire steppers exist, mostly as the low-torque open-loop mode of brushless DC motors.
There is also a way of wiring a high impedance stepper-like motor with a phase shift capacitor to be operated from a single-phase AC supply.  In theory that could be generated with a single transistor.
And then there are special single-coil stepper motors as found in battery powered clocks.  These are low torque and are not electrically reversible(!).  Regardless of the direction of the current applied, they always step in the same direction determined by the physical topology of magnetically permeable materials forming the flux path.  However, as a result you need only a single transistor or similar switch to step them.  You could almost argue that this is a variation on a solenoid pushing a ratchet, only it is the magnetic design rather than a mechanical ratchet pawl which makes it work.

A:

simulate this circuit – Schematic created using CircuitLab
Figure 1. A typical stepper motor with two coils.
It should be obvious that to generate a rotational sequence that one transistor is not enough to switch even a two-coil stepper motor.
DC motors and stepper motors are quite different. DC motors run continuously and are not capable of stepping.
The minimum number of switches required is shown in your first diagram: four.


text:
Q: joining two tables to be bound on a gridview I was getting confused on how to build the SQL query when it come to joining two tables so that I could bind them later to a gridview.
Basically I have two tables,
tablename: family
 __________________________
|Status |lastName|firstName|
|-------|--------|---------|
|1      |11      |111      |
|2      |22      |222      |
|3      |33      |333      |
''''''''''''''''''''''''''''
            +

tablename: familyStatus
 _____________________
|id        | Notes    |
|----------|----------|
|1         | 1111     |
|2         | 2222     |
|3         | 3333     |
'''''''''''''''''''''''

           =

Joined-tables: family+familyStatus [this is what i want]
 ____________________________
|firstName | lastName |Notes |
|----------|----------|------|
|111       | 11       |1111  |
|222       | 22       |2222  |
|333       | 33       |3333  |
''''''''''''''''''''''''''''''

what your seeing here is that the Status from table family and id from familyStatus is the same key, status and id will be hidden on the gridview.
Lets just assume for now that this is how i get the family table.

SELECT Status, firstName, lastName
FROM family
WHERE firstName= @fN
AND lastName = @lN

What do I need to add here so that the Notes from family table also gets joined?

A: A join:
SELECT F.firstName, F.lastName, FS.Notes
FROM family F
INNER JOIN familyStatus FS
    ON F.[Status] = FS.id
WHERE F.firstName= @fN
AND F.lastName = @lN

A: Add a Status foreign key to the familyStatus table and try the following:
SELECT firstName, lastName, Notes
FROM family JOIN familyStatus
ON family.Status =  familyStatus.Status
WHERE firstName= @fN
AND lastName = @lN


text:
Q: Package pgfplots Error: Could not read table file 'Heat_sources_SH_trial.csv' in 'search path=.' I have recently started using LaTeX for creating graphs for my thesis. So far I've just been focused on using pgfplots...plotting a function is no problem but I am having serious issues plotting a csv file. \
I always get the same error: "Package pgfplots Error: Could not read table file 'Heat_sources_SH_trial.csv' in 'search path=.'".
I've tried with code from several tutorials and people before and they say that it plots no problem for them. Because of this, I don't think this is a syntax issue but it must have something to do with reading the file from my drive. I've also tried several files that I've converted to csv's and several csv files that have been sent to me; but nothing works. I've included the latest code below (which is from a tutorial):
\documentclass{standalone}

\usepackage{tikz}

\usepackage{pgfplots}

\usepackage{siunitx}

\pgfplotsset{compat=newest}

\usepgfplotslibrary{units}

\sisetup{
  round-mode          = places,
  round-precision     = 2,
}

\begin{document}

\begin{tikzpicture}

\begin{axis}[

xmin = 0, xmax = 30,
ymin = -1.5, ymax = 2.0,
xtick distance = 5,
ytick distance = 1,
grid = both,
minor tick num = 1,
major grid style = {lightgray},
minor grid style = {lightgray!25},
width = \textwidth,
height = 0.5\textwidth,

]

\addplot[] table[col sep=comma, x=Time from start of January 1 (h), y=Transformer (W)]
{Heat_sources_SH_trial.csv};

\end{axis}

\end{tikzpicture}

\end{document}

I have opened the csv files in notepad and confirmed that the columns are separated by commas. I'm really at a loss to what is going on, so if anyone has any idea I would appreciate it so much!
Thanks!


text:
Q: Apache Flume stopped streaming Twitter data after Twitter API SSL/TLS mandatory requirements. I have followed cloudera's tutorial (http://blog.cloudera.com/blog/2012/09/analyzing-twitter-data-with-hadoop/) for an application to ingest twitter data into HDFS using Apache Flume.
Twitter has restricted its api connection to SSL/TLS only with effect from 15th January 2014. After this change my Flume agent has stopped streaming the twitter data.
Kindly reply if you have already implemented the respective changes to cater for new requirements based on specs in follwoing article.
https://dev.twitter.com/docs/security/using-ssl
Thanks,
Hussnain

A: issue got resolved after I installed newer version of twitter4j i.e v 3.0.3 that is using HTTPS. For reference see    jira.twitter4j.org/browse/TFJ-632    and comments on
http://www.datadansandler.com/2013/03/making-clouderas-twitter-stream-real.html?showComment=1390047763159#c8713000610110252026


text:
Q: Changing existing image with new one using jquery ajax call I am displaying an image on my web page which is present in the web-inf resources folder. When I click a button, a jquery ajax call is made to the server and the image in the web-inf folder is replaced with a new image but the name is same and immediately I want to display the new image instead of old image without reloading the webpage. I could do it by reloading but i don't want because all this is happening in a dialog. If I reload the dialog disappears. In the browser console I could identify that the url of img resource is pointed to new image only but the old image is being displayed. I also tried cache:false in ajax call.
Thanks in advance.

A: You want to append a timestamp to break cache:
newImage = "http://upload.wikimedia.org/wikipedia/commons/2/22/Turkish_Van_Cat.jpg?" + new Date().getTime();

Here is a fiddle: http://jsfiddle.net/kckekq6d/
This was adapted from this post. See it for more info.


text:
Q: What are the value of Stopwatch's ticks if their duration varies? I'm not talking about the bloodsucking spider-like disease-spreader, but rather the sort of tick I recorded here:
Stopwatch noLyme = new Stopwatch();
noLyme.Start();
. . .
noLyme.Stop();
MessageBox.Show(string.Format(
   "elapsed milliseconds == {0}, elapsed ticks == {1}",
   noLyme.ElapsedMilliseconds, noLyme.ElapsedTicks));

What the message box showed me was 17357 milliseconds and 56411802 ticks; this equates to 3250.089416373797 ticks per millisecond, or approximately 3.25 million ticks per second.
Since the ratio is such an odd one (3250.089416373797:1), I assume the time length of a tick changes based on hardware used, or other factors. That being the case, in what practical way are tick counts used? To me, it seems milliseconds hold more value. IOW: why would I care about ticks (the variable time slices)?

A: From the documentation (with Frequency being another property of the Stopwatch):

Each tick in the ElapsedTicks value represents the time interval equal
  to 1 second divided by the Frequency.

Stopwatch.ElapsedTicks (MSDN)
Ticks are useful if you need very precise timing based on the specifics of your hardware.

A: You would use ticks if you want to know a very precise performance measurement that is specific to a given machine.  Internal hardware mechanisms determine the conversion from ticks to actual time.

A: ticks are the raw, low level units in which the hardware measures time.
It's like asking "what use are bits when we can use ints". Well, if we didn't have bits, ints wouldn't exist!
However, ticks can be useful. When counting ticks, converting them to milliseconds is a costly process. When measuring accurately, you can count everything in ticks and convert the results to seconds at the end of the process. When comparing measurements, absolute values nay not be relevant, it may only be relative differences that are of interest.
Of course, in these days of high level language and multitasking there aren't many cases where you would go to the bare metal in this way, but why shouldn't the raw hardware value be exposed through the higher level interfaces?


text:
Q: Too big nested arrays causes segmentation fault (core dumped) I'm running into a problem, I need to do some big data crunching and creating too big arrays seems to cause Segmentation fault (core dumped). Here is a replication of the problem :
int main() {
struct { char a[2000][12] } b[2000];
return 0; }

I'm using Archlinux 64 bits, cc as a compiler, ulimit -s returns 8192 which is strange since I have 24GB of RAM. Any idea how to fix the problem ? I think it has to do with stack and heap but I have no idea what those are.

A: Basically you are trying to allocate 2000*12*2000/1024 = 46875 KB on the stack but allow to use only 8192 KB. A quick fix is to set ulimit -s 50000.
In short about stack and heap: stack is a private memory of each function call (that's where the contents of function variables reside, i.e. scalar values, addresses and so on), and heap is a public memory with generally less strict limits (see e.g. malloc(3)).

A: ulimit -s

doesn't return the total RAM size. It returns just the available stack size that the current shell has (and all the processes it can create). So, the available RAM size doesn't matter.
You can increase it using ulimit -s unlimited. But I'd suggest using dynamic memory allocation for such large arrays instead as your array size is ~48MB and you can easily run into trouble if that's not unavailable on stack, mainly because "stack allocation" failure is difficult to detect.

A: Your using stack memory by declaring your array with a local variable. Use your heap with memory allocation:
typedef struct {
    char a[2000][12];
} bigArray;

int main(void) {
    bigArray *array;
    array = (bigArray*)malloc(2000 * sizeof(bigArray));

    // Do stuff with array here

    free(array);
    return 0;
}


text:
Q: How to use wait-for-it in docker-stack file? Here is what I want to do.
I want to run myApp1 when myApp2 is up and running. I'm trying to use wait-for-it.sh but I can't seem to make it work. =[ Please help!
version: '3'
services:
  myApp1:
    image: myApp1:latest
    ports:
      - 40400:40400
    volumes:
      - "/etc/localtime:/etc/localtime:ro"
      - "/var/run/docker.sock:/var/run/docker.sock"
    deploy:
      mode: replicated
      replicas: 1
    depends_on:
      - "myApp2"
    command: ["./wait-for-it.sh", "myApp2:40000"]

  myApp2:
    image: myApp2:latest
    ports:
      - 40000:40000
    volumes:
      - "/etc/localtime:/etc/localtime:ro"
      - "/var/run/docker.sock:/var/run/docker.sock
    deploy:
      mode: replicated
      replicas: 1

A: You didn't specify what to do after wait-for-it.sh returned success. Try:
command: ["./wait-for-it.sh", "myApp2:40000", "-s", "--", "<your program>", "your program arguments if any"]


text:
Q: Is it OK to use DecimalSeparator to force Floattostr/Strtofloat functions to use a decimal point Currently, I'm setting DecimalSeparator to a '.' in each procedure which uses these functions.
It would be much easier to set this globally at the start of the program but I found Delphi seems to periodically set this back to the current locale.
I need to make sure that a decimal point is used for all conversions no matter which country the program is used in as this is the standard for this type of program and all files structure and communication protocols, numeric displays in forms/edits etc are required to be formatted in this way.
I've been told in another thread that using decimalseparator is not the correct way to do it but I was not given any alternatives. The other threads concerning this subject that I've read don't seem to offer any formative guidance or are overly complex.
Is there a simple 'correct' way to do this ?

A: To be on the safe side, i would use TFormatSettings, this has two advantages:

*

*The formatting is thread safe, other code/libraries cannot influence your function.

*You do not influence other code, which possibly rely upon certain settings.

Here a possible implementation:
function FloatToStrWithDecimalPoint(const Value: Extended; const Format: String = '0.###'): String;
var
  myFormatSettings: TFormatSettings;
begin
  GetLocaleFormatSettings(GetThreadLocale, myFormatSettings);
  myFormatSettings.DecimalSeparator := '.';
  Result := FormatFloat(Format, Value, myFormatSettings);
end;

A: Yes, the DecimalSeparator global variable might be changed by the RTL during runtime, which caused a lot of headache for me a few years ago before I realised this.
The thing is that DecimalSeparator is updated by the RTL when the Windows decimal separator is changed, for instance, using the Control Panel. This might seem like a rather small problem. Indeed, how often does the end user change the system's decimal separator?
The big issue is that the DecimalSeparator variable is updated (according to the system setting) every time you switch user (in Windows). That came as a surprise to me. That is, if your system setting uses a comma (',') as the decimal separator, and you set DecimalSeparator := '.' at application startup, then DecimalSeparator will revert to a comma if you switch user (and you'll notice that when you switch back).
You can tell the RTL not to update the decimal separator by
Application.UpdateFormatSettings := false;

At any rate, there are better alternatives to DecimalSeparator, as discussed in other answers and comments.

A: You could patch every string before and after calling a RTL function with some ForceLocalSeparator() and ForceDotSeparator() functions.
// before a RTL call
Function ForceLocalSeparator(Const StrValue: String): String;
Var
  SepPos: Integer;
Begin
  Result := StrValue;
  If DecimalSeparator <> '.' Then
    Begin
      SepPos := Pos( '.', Result );
      If SepPos > 0 Then Result[SepPos] := DecimalSeparator;
    End;
End;

// after a RTL call
Function ForceDotSeparator(Const StrValue: String): String;
Var
  SepPos: Integer;
Begin
  Result := StrValue;
  If DecimalSeparator <> '.' Then
    Begin
      SepPos := Pos( DecimalSeparator, Result );
      If SepPos > 0 Then Result[SepPos] := '.';
    End;
End;

A: I am/was under the assumption that the global DecimalSeperator variable would not be touched by the RTL. If not, then all these routines have an optional parameter FormatSettings which you could use. Globaly declare a TFormatSettings variable and use it for each occurance of these routines.
A small benefit of it could be that the routines are thread-safe when you specify your own format settings.

A: It's OK if you have no alternative. Prefer the versions of those functions that accept a TFormatSettings parameter, if your Delphi version is recent enough, so that you don't interfere with any other code that relies on that global variable for locale-aware behavior.
FloatToStr and StrToFloat are locale-sensitive functions. If you need to convert your floating-point value to a string to persist it somewhere that a program will read later (such as to a file, the registry, or a network socket), then you should use the locale-independent functions Str and Val for your conversions instead. They always use . for the decimal separator, regardless of the DecimalSeparator variable or other environmental settings.


text:
Q: How to call back new variable in between array objects using JavaScript I want to call back new variable (section) after 3 objects called from array. I tried that using JavaScript Es6 Map but not getting exact result can somebody please help. Thanks in advance. Below I attached my code
const array = [
{
 id:1,
 name:'naren'
},
{
 id:2,
 name:'naren2'
},
{
 id:3,
 name:'naren3'
},
{
 id:4,
 name:'naren4'
},
{
 id:5,
 name:'naren5'
},
{
 id:6,
 name:'naren6'
},
{
 id:7,
 name:'naren7'
}
{
 id:8,
 name:'naren8'
}
]

//New Section
const section = 'New section';

Expected Output Result in console
Ouput :

naren1
naren2
naren3
New Section
naren4
naren5
naren6
naren7
naren8

A: loop over the array and check the index, this should produce your desired output
array.forEach((el, index) => index === 3
  ? console.log(el.name + '\n' + section)
  : console.log(el.name))


text:
Q: Google Analytics Event Tracking via a jQuery plugin The proof of concept started with this:
<script type="text/javascript">
    $(document).ready(function() {
    $('.evnttrk1').click(function() {
    _gaq.push(['_trackEvent', 'coming_soon', 'footer_icons', $(this).attr('id')]);
});
});

With this, any link with a class of eventrk1 would trigger a Google Analytics Event. This worked just fine.
From there I decide to roll it into a proper plugin, adding some functionality along the way. Everything about the plugin works except I can't get the _gaq.push to send events to Google. I'm not getting an error. I'm not getting anything at all.
I have the plugin running on this coming soon page: http://AcaciaNJ.com
I'd like to tell you this gave me gray hairs but that's not possible since it made me pull all my hair out. Please help. This is really starting to bother me.

A: Maybe try window._gaq.push?
You can detect if the _gaq object is available by testing for window._gaq:
if (window._gaq) {
    alert('_gaq found');
} else {
    alert('_gaq not found');
}

You could also pass an arbitrary function to window._gaq.push() to help with debugging:
window._gaq.push(function() {alert('Pushed function to _gaq')});

I also noticed that your script passes a fifth argument to _trackEvent, val. This has to be an integer, and tracking will not work if it is a string.


text:
Q: Different Lables with Different set of stocks     I modified following public screener pine script .script is
stock = input(title="Stock List", defval="1-10", options=["1-10","11-20","21-30", "31-40", "41-50", "51-60", "61-70", "71-80", "81-90", "91-100"])

rsi_length     = input(14, title = "RSI Length")
rsi_overbought = input(0, title = "RSI Overbought Level")
// Insert Stock Symbol of your screener list
EX = "MYX_DLY:"

stock1   = EX + "COMFORT"
stock2   = EX + "PCHEM"
stock3   = EX + "RUBEREX"
stock4   = EX + "HLT"
stock5   = EX + "PNEPCB"
stock6   = EX + "SCGM"
stock7   = EX + "TGUAN"
stock8   = EX + "DAIBOCI"
stock9   = EX + "SAM"
stock10  = EX + "PIE"
stock11  = EX + "ANNJOO"
stock12  = EX + "CMSB"
stock13  = EX + "ULICORP"
stock14  = EX + "KOBAY"
stock15  = EX + "VITROX"
stock16  = EX + "UWC"
stock17  = EX + "JTIASA"
stock18  = EX + "JFTECH"
stock19  = EX + "MICROLN"
stock20  = EX + "HTPADU"
stock21  = EX + "MPI"
stock22  = EX + "KESM"
stock23  = EX + "FRONTKN"
stock24  = EX + "NOTION"
stock25  = EX + "PENTA"
stock26  = EX + "HONGSENG"
stock27  = EX + "MFCB"
stock28  = EX + "PPB"
stock29  = EX + "PANAMY"
stock30  = EX + "KAWAN"
stock31  = EX + "KAREX"
stock32  = EX + "OCNCASH"
stock33  = EX + "DLADY"
stock34  = EX + "CARLSBG"
stock35  = EX + "BAT"
stock36  = EX + "AJI"
stock37  = EX + "MBMR"
stock38  = EX + "MRDIY"
stock39  = EX + "LIIHEN"
stock40  = EX + "AMWAY"
stock41  = EX + "HARTA"
stock42  = EX + "SUPERMX"
stock43  = EX + "TOPGLOV"
stock44  = EX + "CAREPLS"
stock45  = EX + "KOSSAN"
stock46  = EX + "ADVENTA"
stock47  = EX + "IHH"
stock48  = EX + "PHARMA"
stock49  = EX + "KOTRA"
stock50  = EX + "OPTIMAX"
stock51  = EX + "OIB"
stock52  = EX + "MAHSING"
stock53  = EX + "YNHPROP"
stock54  = EX + "SPSETIA"
stock55  = EX + "IOIPG"
stock56  = EX + "SYMLIFE"
stock57  = EX + "UEMS"
stock58  = EX + "UOADEV"
stock59  = EX + "HENGYUAN"
stock60  = EX + "PETRONM"
stock61  = EX + "WASEONG"
stock62  = EX + "PENERGY"
stock63  = EX + "DIALOG"
stock64  = EX + "ARMADA"
stock65  = EX + "DAYANG"
stock66  = EX + "YINSON"
stock67  = EX + "UZMA"
stock68  = EX + "GAMUDA"
stock69  = EX + "IJM"
stock70  = EX + "EKOVEST"
stock71  = EX + "SUNCON"
stock72  = EX + "WCEHB"
stock73  = EX + "MUHIBAH"
stock74  = EX + "HLBANK"
stock75  = EX + "MAYBANK"
stock76  = EX + "BURSA"
stock77  = EX + "AMBANK"
stock78  = EX + "HLCAP"
stock79  = EX + "MANULFE"
stock80  = EX + "AEONCR"
stock81  = EX + "RCECAP"
stock82  = EX + "LPI"
stock83  = EX + "PBBANK"
stock84  = EX + "TAKAFUL"
stock85  = EX + "HLFG"
stock86  = EX + "ABMB"
stock87  = EX + "CIMB"
stock88  = EX + "TIMECOM"
stock89  = EX + "DIGI"
stock90  = EX + "TM"
stock91  = EX + "AXIATA"
stock92  = EX + "AMTEL"
stock93  = EX + "MAXIS"
stock94  = EX + "BINACOM"
stock95  = EX + "OPCOM"
stock96  = EX + "MISC"
stock97  = EX + "LITRAK"
stock98  = EX + "WPRTS"
stock99  = EX + "AIRPORT"
stock100 = EX + "SCIENTX"

////////////////////////////////////////////////////////////////////////////////
//Selection 1 - Start

s_1 = if stock == "1-10"
    input(stock1 , type=input.symbol)

else
    if stock =="11-20"
        input(stock2 , type=input.symbol)
    else
        if stock =="21-30"
            input(stock3 , type=input.symbol)
        else
            if stock =="31-40"
                input(stock4 , type=input.symbol)
            else
                if stock =="41-50"
                    input(stock5 , type=input.symbol)
                else
                    if stock =="51-60"
                        input(stock6 , type=input.symbol)
                    else
                        if stock =="61-70"
                            input(stock7 , type=input.symbol)
                        else
                            if stock =="71-80"
                                input(stock8 , type=input.symbol)
                            else
                                if stock =="81-90"
                                    input(stock9 , type=input.symbol)
                                else
                                    if stock =="91-100"
                                        input(stock10 , type=input.symbol)

//Selection 1 - End
////////////////////////////////////////////////////////////////////////////////
//Selection 2 - Start

s_2 = if stock == "1-10"
    input(stock11 , type=input.symbol)

else
    if stock =="11-20"
        input(stock12 , type=input.symbol)
    else
        if stock =="21-30"
            input(stock13 , type=input.symbol)
        else
            if stock =="31-40"
                input(stock14 , type=input.symbol)
            else
                if stock =="41-50"
                    input(stock15 , type=input.symbol)
                else
                    if stock =="51-60"
                        input(stock16 , type=input.symbol)
                    else
                        if stock =="61-70"
                            input(stock17 , type=input.symbol)
                        else
                            if stock =="71-80"
                                input(stock18 , type=input.symbol)
                            else
                                if stock =="81-90"
                                    input(stock19 , type=input.symbol)
                                else
                                    if stock =="91-100"
                                        input(stock20 , type=input.symbol)

//Selection 2 - End
////////////////////////////////////////////////////////////////////////////////
//Selection 3 - Star

s_3 = if stock == "1-10"
    input(stock21 , type=input.symbol)

else
    if stock =="11-20"
        input(stock22 , type=input.symbol)
    else
        if stock =="21-30"
            input(stock23 , type=input.symbol)
        else
            if stock =="31-40"
                input(stock24 , type=input.symbol)
            else
                if stock =="41-50"
                    input(stock25 , type=input.symbol)
                else
                    if stock =="51-60"
                        input(stock26 , type=input.symbol)
                    else
                        if stock =="61-70"
                            input(stock27 , type=input.symbol)
                        else
                            if stock =="71-80"
                                input(stock28 , type=input.symbol)
                            else
                                if stock =="81-90"
                                    input(stock29 , type=input.symbol)
                                else
                                    if stock =="91-100"
                                        input(stock30 , type=input.symbol)

//Selection 3 - End
////////////////////////////////////////////////////////////////////////////////
//Selection 4 - Start

s_4 = if stock == "1-10"
    input(stock31 , type=input.symbol)

else
    if stock =="11-20"
        input(stock32 , type=input.symbol)
    else
        if stock =="21-30"
            input(stock33 , type=input.symbol)
        else
            if stock =="31-40"
                input(stock34 , type=input.symbol)
            else
                if stock =="41-50"
                    input(stock35 , type=input.symbol)
                else
                    if stock =="51-60"
                        input(stock36 , type=input.symbol)
                    else
                        if stock =="61-70"
                            input(stock37 , type=input.symbol)
                        else
                            if stock =="71-80"
                                input(stock38 , type=input.symbol)
                            else
                                if stock =="81-90"
                                    input(stock39 , type=input.symbol)
                                else
                                    if stock =="91-100"
                                        input(stock40 , type=input.symbol)

//Selection 4 - End
////////////////////////////////////////////////////////////////////////////////

//Selection 5 - Start

s_5 = if stock == "1-10"
    input(stock41 , type=input.symbol)

else
    if stock =="11-20"
        input(stock42 , type=input.symbol)
    else
        if stock =="21-30"
            input(stock43 , type=input.symbol)
        else
            if stock =="31-40"
                input(stock44 , type=input.symbol)
            else
                if stock =="41-50"
                    input(stock45 , type=input.symbol)
                else
                    if stock =="51-60"
                        input(stock46 , type=input.symbol)
                    else
                        if stock =="61-70"
                            input(stock47 , type=input.symbol)
                        else
                            if stock =="71-80"
                                input(stock48 , type=input.symbol)
                            else
                                if stock =="81-90"
                                    input(stock49 , type=input.symbol)
                                else
                                    if stock =="91-100"
                                        input(stock50 , type=input.symbol)

//Selection 5 - End
////////////////////////////////////////////////////////////////////////////////
//Selection 6 - Start

s_6 = if stock == "1-10"
    input(stock51 , type=input.symbol)

else
    if stock =="11-20"
        input(stock52 , type=input.symbol)
    else
        if stock =="21-30"
            input(stock53 , type=input.symbol)
        else
            if stock =="31-40"
                input(stock54 , type=input.symbol)
            else
                if stock =="41-50"
                    input(stock55 , type=input.symbol)
                else
                    if stock =="51-60"
                        input(stock56 , type=input.symbol)
                    else
                        if stock =="61-70"
                            input(stock57 , type=input.symbol)
                        else
                            if stock =="71-80"
                                input(stock58 , type=input.symbol)
                            else
                                if stock =="81-90"
                                    input(stock59 , type=input.symbol)
                                else
                                    if stock =="91-100"
                                        input(stock60 , type=input.symbol)

//Selection 6 - End
////////////////////////////////////////////////////////////////////////////////
//Selection 7 - Start

s_7 = if stock == "1-10"
    input(stock61 , type=input.symbol)

else
    if stock =="11-20"
        input(stock62 , type=input.symbol)
    else
        if stock =="21-30"
            input(stock63 , type=input.symbol)
        else
            if stock =="31-40"
                input(stock64 , type=input.symbol)
            else
                if stock =="41-50"
                    input(stock65 , type=input.symbol)
                else
                    if stock =="51-60"
                        input(stock66 , type=input.symbol)
                    else
                        if stock =="61-70"
                            input(stock67 , type=input.symbol)
                        else
                            if stock =="71-80"
                                input(stock68 , type=input.symbol)
                            else
                                if stock =="81-90"
                                    input(stock69 , type=input.symbol)
                                else
                                    if stock =="91-100"
                                        input(stock70 , type=input.symbol)

//Selection 7 - End
////////////////////////////////////////////////////////////////////////////////
//Selection 8 - Start

s_8 = if stock == "1-10"
    input(stock71 , type=input.symbol)

else
    if stock =="11-20"
        input(stock72 , type=input.symbol)
    else
        if stock =="21-30"
            input(stock73 , type=input.symbol)
        else
            if stock =="31-40"
                input(stock74 , type=input.symbol)
            else
                if stock =="41-50"
                    input(stock75 , type=input.symbol)
                else
                    if stock =="51-60"
                        input(stock76 , type=input.symbol)
                    else
                        if stock =="61-70"
                            input(stock77 , type=input.symbol)
                        else
                            if stock =="71-80"
                                input(stock78 , type=input.symbol)
                            else
                                if stock =="81-90"
                                    input(stock79 , type=input.symbol)
                                else
                                    if stock =="91-100"
                                        input(stock80 , type=input.symbol)

//Selection 8 - End
////////////////////////////////////////////////////////////////////////////////
//Selection 9 - Start

s_9 = if stock == "1-10"
    input(stock81 , type=input.symbol)

else
    if stock =="11-20"
        input(stock82 , type=input.symbol)
    else
        if stock =="21-30"
            input(stock83 , type=input.symbol)
        else
            if stock =="31-40"
                input(stock84 , type=input.symbol)
            else
                if stock =="41-50"
                    input(stock85 , type=input.symbol)
                else
                    if stock =="51-60"
                        input(stock86 , type=input.symbol)
                    else
                        if stock =="61-70"
                            input(stock87 , type=input.symbol)
                        else
                            if stock =="71-80"
                                input(stock88 , type=input.symbol)
                            else
                                if stock =="81-90"
                                    input(stock89 , type=input.symbol)
                                else
                                    if stock =="91-100"
                                        input(stock90 , type=input.symbol)

//Selection 9 - End
////////////////////////////////////////////////////////////////////////////////
//Selection 10 - Start

s_10 = if stock == "1-10"
    input(stock91 , type=input.symbol)

else
    if stock =="11-20"
        input(stock92 , type=input.symbol)
    else
        if stock =="21-30"
            input(stock93 , type=input.symbol)
        else
            if stock =="31-40"
                input(stock94 , type=input.symbol)
            else
                if stock =="41-50"
                    input(stock95 , type=input.symbol)
                else
                    if stock =="51-60"
                        input(stock96 , type=input.symbol)
                    else
                        if stock =="61-70"
                            input(stock97 , type=input.symbol)
                        else
                            if stock =="71-80"
                                input(stock98 , type=input.symbol)
                            else
                                if stock =="81-90"
                                    input(stock99 , type=input.symbol)
                                else
                                    if stock =="91-100"
                                        input(stock100 , type=input.symbol)

//Selection 10 - End
////////////////////////////////////////////////////////////////////////////////

// Screener Function
screenerFunc() =>
    rsi  = rsi(close, 14) // Value
    cond =close[1]< open[1] and open < close and low > low[1] and close > high[1] and open >= close[1] and open < high[1]
 or close[1]> open[1] and close < open and high < high[1] and close < low[1] and open < close[1] and open > low[1]

    [rsi, cond]

 ////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
[value1, name1]   = security(s_1, timeframe.period, screenerFunc())
[value2, name2]   = security(s_2, timeframe.period, screenerFunc())
[value3, name3]   = security(s_3, timeframe.period, screenerFunc())
[value4, name4]   = security(s_4, timeframe.period, screenerFunc())
[value5, name5]   = security(s_5, timeframe.period, screenerFunc())
[value6, name6]   = security(s_6, timeframe.period, screenerFunc())
[value7, name7]   = security(s_7, timeframe.period, screenerFunc())
[value8, name8]   = security(s_8, timeframe.period, screenerFunc())
[value9, name9]   = security(s_9, timeframe.period, screenerFunc())
[value10, name10] = security(s_10, timeframe.period, screenerFunc())

////////////////////////////////////////////////////////////////////////////////

cs1 = if name1
    s_1 + '  =  '+tostring(value1)
cs2 = if name2
    s_2 + '  =  '+tostring(value2)
cs3 = if name3
    s_3 + '  =  '+tostring(value3)
cs4 = if name4
    s_4 + '  =  '+tostring(value4)
cs5 = if name5
    s_5 + '  =  '+tostring(value5)
cs6 = if name6
    s_6 + '  =  '+tostring(value6)
cs7 = if name7
    s_7 + '  =  '+tostring(value7)
cs8 = if name8
    s_8 + '  =  '+tostring(value8)
cs9 = if name9
    s_9 + '  =  '+tostring(value9)
cs10 = if name10
    s_10 + '  =  '+tostring(value10)

////////////////////////////////////////////////////////////////////////////////
total_cs = cs1+'\n'+cs2+'\n'+cs3+'\n'+cs4+'\n'+cs5+'\n'+cs6+'\n'+cs7+'\n'+cs8+'\n'+cs9+'\n'+cs10

// Plot Label
lab_1 = label.new(
          bar_index, high, total_cs,
          color=color.gray,
          textcolor=color.black,
          style =  label.style_labeldown,
          yloc = yloc.price)

label.delete(lab_1[1]

So now result that i am getting is one set of stock at a time that has stock 1 to 10 or whichever set choose.so there is any possibilities that i can create different set of lables with different set of stocks in it.for example 10 different lables with each has specific set of stock.for example first lable with 1 to 10 stock,second lable with 11 to 20 stock and so on.....Appreciate any help in this.

A: Yes, you can use lists. First of all, you should probably seek to improve your programming knowledge so you can get the skills to do the most basic things as the few ones I am showing you in this answer.
First, you can get the selection as an index, instead of a string:
EX = "MYX_DLY:"
stock_ranges = ["1-10","11-20","21-30", "31-40", "41-50", "51-60", "61-70", "71-80", "81-90", "91-100"]
# Building a dictionary to convert a validated string to an index (integer):
stock_range_dict = {v: i for i,v in enumerate(stock_ranges)}

stock = input(title="Stock List", defval="1-10", options=stock_ranges)
# Converting the input string to an index:
# This all was a "fix" but you should also probably change the return type.
idx_stock = stock_range_dict[stock]

Then, you can store your stock1 to stock100 as elements in a list of 10 lists (of 10 elements each), instead of individual variables:
stock_groups = [["COMFORT" ,"PCHEM", "RUBEREX", "HLT", "PNEPCB", "SCGM", "TGUAN", "DAIBOCI", "SAM", "PIE"],
            ["ANNJOO", "CMSB","ULICORP","KOBAY","VITROX","UWC","JTIASA","JFTECH","MICROLN","HTPADU"],
            ["MPI","KESM", "FRONTKN","NOTION","PENTA","HONGSENG","MFCB","PPB","PANAMY","KAWAN"],
            ["KAREX","OCNCASH", "DLADY","CARLSBG","BAT","AJI","MBMR","MRDIY","LIIHEN","AMWAY"],
            ["HARTA","SUPERMX","TOPGLOV","CAREPLS","KOSSAN","ADVENTA","IHH","PHARMA","KOTRA","OPTIMAX"],
            ["OIB","MAHSING","YNHPROP","SPSETIA","IOIPG","SYMLIFE","UEMS","UOADEV","HENGYUAN","PETRONM"],
            ["WASEONG","PENERGY","DIALOG","ARMADA","DAYANG","YINSON","UZMA","GAMUDA","IJM","EKOVEST"],
            ["SUNCON","WCEHB","MUHIBAH","HLBANK","MAYBANK","BURSA","AMBANK","HLCAP","MANULFE","AEONCR"],
            ["RCECAP","LPI","PBBANK","TAKAFUL","HLFG","ABMB","CIMB","TIMECOM","DIGI","TM"],
            ["AXIATA","AMTEL","MAXIS","BINACOM","OPCOM","MISC","LITRAK","WPRTS","AIRPORT","SCIENTX"]]

Then instead of these monstruous towers of condition statements, you can do a function for your inputs, with the index of the wanted list and the initial selection index as parameters:
def get_input(initial_selection: int, list_idx: int):
    return input(EX + stock_groups[list_idx][initial_selection], type=input.symbol)

You would call it in a loop that is incrementing a counter:
# As list comprehension...
selections = [get_input(idx_sel, i) for i in range(10)]

or:
# as a for_loop:
selections = []
for i in range(10):
    selections.append(get_input(idx_stock, i))


text:
Q: Calculating mean upslope aspect from each cell in DEM using ArcPy? I am trying to write a python script to calculate the mean aspect upslope from each cell in a DEM.  I have the general workflow down, but my final output is restricted to angles between 0 and 90 degrees, which is not correct for the input data.  The general procedure to average an angle is:

*

*Calculate the sine and cosine of each angle.

*Sum the sines and cosines.

*Use atan2 on the sums to find the mean angle.

I have successfully used this technique to find focal and zonal mean aspects, and am trying to adapt my code to calculate upslope aspect.  I am summing up the sine and cosine rasters using a weighted flow accumulation, which is the only difference between this and my zonal/focal workflows.  I have included the script below.
Does anyone have any idea what's different about flow accumulation that causes this, or is there something else in my code that I'm missing?
arcpy.CheckOutExtension("spatial")
import math
from arcpy.sa import *

#collect input parameters
inDEM = arcpy.GetParameter(0)
flowDir = arcpy.GetParameter(1)
outMean = arcpy.GetParameterAsText(2)
scratch = arcpy.GetParameter(3)

#set workspace and snap raster
arcpy.env.workspace=scratch
arcpy.env.snapRaster = inDEM

#Calculate aspect and set flat cells to NoData
rawAspect = Aspect(inDEM)
nullFlat = SetNull(rawAspect,rawAspect,"Value < 0")

#convert aspect to radians and calulate cos/Sin
Radians = Times(nullFlat,0.01745329)
cosAsp = Cos(Radians)
sinAsp = Sin(Radians)

#sum upslope Cos/Sin rasters, use ATan2 to average
cosAccum=FlowAccumulation(flowDir,cosAsp)
sinAccum=FlowAccumulation(flowDir,sinAsp)
ArcTan = ATan2(sinAccum,cosAccum)

#convert mean aspect back to degrees and save output
meanAspect = Mod(360+ArcTan*(180/math.pi),360)
meanAspect.save(outMean)

A: It looks like the problem is that weighted flow accumulation does not support negative values.  The workaround is to split the sin and cos rasters into positive and negative portions, run a weighted accumulation on these, and subtract the negative accumulation from the positive. The negative raster should contain the absolute values of the negative portion.
To split, accumulate, and recombine the cos and sin rasters, I defined a function that replaced the single weighted accumulation step.  I also included a final step to fill in any NoData values on the mean aspect raster with the values from the original raw aspect raster.  The new code is below:
Edit:  I wrote up a blog post that goes into script build in more detail
arcpy.CheckOutExtension("spatial")
import math
from arcpy.sa import *

#define function to calculate flow accumulation
def angleAccum(flowdir,angle):
    pos_angle = Con(angle,angle,0,"Value > 0")
    neg_angle = Abs(Con(angle,angle,0,"Value < 0"))
    pos_accum = FlowAccumulation(flowdir, pos_angle,"FLOAT")
    neg_accum = FlowAccumulation(flowdir, neg_angle,"FLOAT")
    return Minus(pos_accum,neg_accum)

#collect input parameters
inDEM = arcpy.GetParameter(0)
flowDir = arcpy.GetParameter(1)
outMean = arcpy.GetParameterAsText(2)
scratch = arcpy.GetParameter(3)

#set workspace and snap raster
arcpy.env.workspace=scratch
arcpy.env.snapRaster = inDEM

#Calculate aspect and set flat cells to NoData
rawAspect = Aspect(inDEM)
nullFlat = SetNull(rawAspect,rawAspect,"Value < 0")

#convert aspect to radians and calulate cos/Sin
Radians = Times(nullFlat,0.01745329)
cosAsp = Cos(Radians)
sinAsp = Sin(Radians)

#sum upslope Cos/Sin rasters, use ATan2 to average
cosAccum=angleAccum(flowDir,cosAsp)
sinAccum=angleAccum(flowDir,sinAsp)
ArcTan = ATan2(sinAccum,cosAccum)

#convert mean aspect back to degrees and save output
meanAspect = Mod(360+ArcTan*(180/math.pi),360)
finalAspect = Con(IsNull(meanAspect),rawAspect,meanAspect)
finalAspect.save(outMean)


text:
Q: Calculate time between the current time and a certain day I am fairly new to (Java) programming and I am trying to build a little Android app that will tell you if it's already weekend or not.
I already got it so far that it can tell you if it's weekend or not, however I also want to show a little countdowntimer in that app until the weekend starts, or ends.
I am unable to think about an Algorithm to calculate the time (in milliseconds) between the current time and the next Saturday (if it's not in a weekend) or Monday if it's a weekend.
I know how to get the current day in the week using the Calendar class, however I get stuck when I try to get the time until the next Saturday or Monday. I can't think about a way to do this.
This might sound like a stupid question but I have really lost my mind in this. Hopefully one of you guys can help me out.

A: Here's the process, but as a description rather than code, leaving the rest for you as an implementation exercise:

*

*Get the current time in milliseconds, and remember it for later

*Create an appropriate Calendar object

*Work out the day you're trying to aim for (Saturday or Monday)

*Work out how many days you need to add to get there (based on the current "day of week" and the day of week you're aiming for), and add that many days

*

*As a simpler (but less efficient) alternative: keep adding 1 day until the day of week is correct!

*Use multiple set calls to get to the right time of day (so set the hour to 0, the minute to 0, the second to 0, the millisecond to 0) - assuming that you're looking for midnight, of course

*Use getTimeInMillis() to get the point in time you're aiming for

*Subtract the original value, and the result will be the number of milliseconds you need to wait

One thing to bear in mind is that daylight saving time changes can make things "interesting"... so at the very start of Saturday, there might be 47 or 49 hours before you get to the start of Monday, instead of the normal 48. I'd expect the above algorithm to cope in most cases, but if you "aim" for Sunday you could have an odd situation in Brazil (and a few other places) when you try to get to midnight, as that might be skipped entirely... Time zones are annoying like that.
Additionally, if you can use Joda Time it could make your life simpler.

A: java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:
The solution uses following functions:

*

*ZonedDateTime#now(ZoneId): Returns the current date-time from the system clock in the specified timezone.

*ZonedDateTime#getDayOfWeek: Returns the day-of-week field, which is an enum DayOfWeek.

*TemporalAdjusters#next: Returns the next day-of-week adjuster, which adjusts the date to the first occurrence of the specified day-of-week after the date being adjusted.

*ZonedDateTime#toLocalDate: Returns the LocalDate part of this date-time.

*LocalTime#atStartOfDay(ZoneId): Returns a zoned date-time from this date at the earliest valid time according to the rules in the time-zone.

*ChronoUnit#between: Calculates the amount of time between two temporal objects.

Demo:
import static java.time.DayOfWeek.SATURDAY;
import static java.time.DayOfWeek.SUNDAY;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.TextStyle;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Tests
        process(ZonedDateTime.now(ZoneId.systemDefault()));
        process(ZonedDateTime.of(LocalDate.of(2021, 6, 23), LocalTime.of(10, 20, 30, 123456789),
                ZoneId.systemDefault()));
        process(ZonedDateTime.of(LocalDate.of(2021, 6, 26), LocalTime.of(10, 20, 30, 123456789),
                ZoneId.systemDefault()));
    }

    static long millisBetween(ZonedDateTime start, ZonedDateTime end) {
        return ChronoUnit.MILLIS.between(start, end);
    }

    static boolean isWeekend(ZonedDateTime now) {
        DayOfWeek dow = now.getDayOfWeek();
        return dow == SATURDAY || dow == SUNDAY;
    }

    static void process(ZonedDateTime now) {
        String dow = now.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
        if (isWeekend(now)) {
            System.out.printf("It's %s (a weekend) now. Monday is %d milliseconds ahead.%n", dow,
                    millisBetween(now, now.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).toLocalDate()
                            .atStartOfDay(ZoneId.systemDefault())));
        } else {
            System.out.printf("It's %s (a weekday) now. Saturday is %d milliseconds ahead.%n", dow,
                    millisBetween(now, now.with(TemporalAdjusters.next(DayOfWeek.SATURDAY)).toLocalDate()
                            .atStartOfDay(ZoneId.systemDefault())));
        }
    }
}

Output from a sample run:
It's Sunday (a weekend) now. Monday is 30258373 milliseconds ahead.
It's Wednesday (a weekday) now. Saturday is 221969876 milliseconds ahead.
It's Saturday (a weekend) now. Monday is 135569876 milliseconds ahead.

ONLINE DEMO
Note: For the code to work for a timezone different from the JVM's timezone, replace ZoneId.systemDefault() with the applicable timezone ID e.g. ZoneId.of("America/New_York").
Learn more about the modern Date-Time API from Trail: Date Time.

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.


text:
Q: Processing game: Gif images not respawning as intended I am a diploma student making a game based on processing, it's a tower defense game where a heroine would be shooting arrows at zombies charging towards the castle. I have multiple issues with this.

*

*The charger zombies do not respawn after being shot dead.

*All of the charger zombies die together when I shot only one charger zombie.

Supposedly I wanted the zombies to spawn in waves repeatedly after a group of them has been shot down, and then I want the charger zombies to die individually, depending on the one I click on.
Here's my source code:
import processing.opengl.*; // transparency
import gifAnimation.*; // after add gifAnimation library
import ddf.minim.*; // importing music

PImage backgroundImg;
PImage animation;

int counter;

//settings
int score = 50, totalScore = 0;
int titleX = 200, titleY = 200;
boolean shotsFired = false;
PFont scorePoints, castleHealthPoints, font; //font for startingScreen
int chargerKilled;

//Charger class
int maxChargerOnScreen;
Charger[] chargerArr;   //chargerArray undefined
int chargerIndex;
final int numCharger = 300;
ArrayList<Charger> onScreen = new ArrayList<Charger>();

boolean chargerReachedTarget = false, chargerShot = false, chargerDive = true;
Gif chargerCharge, chargerAttack, chargerDied, shootingStance;
int chargerMoveX = 800, chargerMoveY = 450;

// CastleWallHealth
int castleHealth = 1000;

// audio
Minim minim;
AudioPlayer song;
AudioSnippet arrowShoot;

//-------------------------------Codes start here --------------------------------------------------//
void setup() {
    //ipad mini size
    //  frameRate(10);
    frameRate(60);
    size(800, 600);
    smooth();

    minim = new Minim(this);
    // song = minim.loadFile("InGameSoundtrack.mp3");
    // song.play();
    arrowShoot = minim.loadSnippet("arrowSound1.wav");

    backgroundImg = loadImage("GameBackground.jpg");
    backgroundImg.resize(800, 600);
    chargerCharge = new Gif(this, "ChargerCharge.gif");
    chargerAttack = new Gif(this, "ChargerAttack.gif");
    chargerDied   = new Gif(this, "ChargerDie.gif");
    gargoyleFly   = new Gif(this, "GargoyleFly.gif");
    gargoyleAttack = new Gif(this, "GargoyleAttack.gif");
    shootingStance = new Gif(this, "ShootingGif.gif");

    scorePoints =  createFont("Arial", 16, true);
    castleHealthPoints = createFont("Arial", 16, true);
    // loopingGif.play() plays the animation without loop
    // must make charger
    chargerCharge.play();
    chargerAttack.play();
    chargerDied.play();

    resetGames();  // starts with respawning 5 charges
}

void draw() {
    // backgroud
    background(backgroundImg);
    image(shootingStance, 120,200);

    // scores and health
    textFont(scorePoints, 15);
    fill(0);
    text("Score: " + totalScore, 100, 100);
    displayCastleHealth();

  //*********************************************charger settings code********************************************************************
    // If there's no more zombies. prompt reset (screen no zombies) , index from 0 add till 300 then game won
    if (onScreen.size() == 0 && chargerIndex == numCharger) {
        println("Game won! :)");
        // gameWon = true;
    }

    // while onScreen charger less than 5 only and chargerIndex havent reach 300 it will only respawn
    while (onScreen.size () < maxChargerOnScreen && chargerIndex <= numCharger - 1) {

        if (chargerIndex < chargerArr.length) { // <--- this is the problem chargerArrayLength
            Charger chargerMobs = chargerArr[chargerIndex];
            // starts from chargerArray[0] to chargerArray[300]
            onScreen.add(chargerMobs);
            chargerIndex++;
            // chargerIndex keeps looping why?
            // println("ADDED ZOMBIE TO ONSCREEN Zombs on screen: " + onScreen.size());
        }
    }

    // Adjusts maxZombOnScreen based off the current index   Difficulties?
    if (chargerIndex == 10)
        maxChargerOnScreen++;
    else if (chargerIndex == 50)
        maxChargerOnScreen++;
    else if (chargerIndex == 100)
        maxChargerOnScreen += 2;
    else if (chargerIndex == 150)
        maxChargerOnScreen += 2;
    else if (chargerIndex == 190)
        maxChargerOnScreen += 3;
    else if (chargerIndex == 250)
        maxChargerOnScreen += 3;
    else if (chargerIndex == 260)
        maxChargerOnScreen += 3;
    else if (chargerIndex == 270)
        maxChargerOnScreen += 5;

    // removes dead zombies, living zombies act normally
    for(int i = 0; i < onScreen.size(); i++) {
        Charger c = onScreen.get(i);

        // add money when a zombie is dead
        // if (c.getHealth() <= 0)
        if (chargerShot==true) {
            c.chargerDying();
            onScreen.remove(i);
            chargerKilled++;
            i--;
        } else {
            c.act(); ///it should just act
        //  c.displayHealth(); // if gt time only do
    //  }
        }
    }

    // creating list of predetermined zombies and their characteristics
    println("chargerIndex: " + chargerIndex); // debug
    println("onScreenSize: " + onScreen.size());
//  println("ChargerArray: " + chargerArray.length); chargerArray point null?

    // cursor
    if (mouseY > height - 500) {
        noFill();
        stroke(255, 0, 0);
        ellipse(mouseX, mouseY, 35, 35);
        line(mouseX - 25, mouseY, mouseX + 25, mouseY);
        line(mouseX, mouseY - 25, mouseX, mouseY + 25);
    }

}

void resetGames() {
    // resetting variables
    chargerIndex = 0;
    maxChargerOnScreen = 5;
    chargerKilled = 0;
    createNewCharger();
}

void createNewCharger() {

    Charger[] temp = new Charger[numCharger];
    for (int i = 0; i < numCharger; i++)
        temp[i] = new Charger((int) random(800, 1200), chargerMoveY);

    chargerArr = temp;
}

//____________________________________________________________________________________________________________-
class Charger {

    private int chargerMoveX, chargerMoveY;
    Gif chargerGif; // by default
    // chargerGif will change based on input (either it reaches the castle or its shot)

    // no constructor
    Charger() {
        chargerMoveX = 0;
        chargerMoveY = 450;
    }

    // overloaded constructor
    Charger(int cMoveX,int cMoveY) {
        chargerMoveX = cMoveX;
        chargerMoveY = cMoveY;
    }

    void act() { // use

        // if reached castle it wont move
        if (chargerMoveX <= 180) {
            // remove gif images
            chargerDive = false;
            chargerReachedTarget = true;
        }

        // if not shot or reached castle it will move
        if (chargerDive == true) {
            chargerGif = chargerCharge;
            image(chargerGif, chargerMoveX, chargerMoveY);
            chargerMoveX -= 2;
        }

        // if reached castle perform attack animation
        if (chargerReachedTarget == true) {
            chargerGif = chargerAttack;
            image(chargerGif, chargerMoveX - 80, chargerMoveY - 120);
        }

        if (mousePressed &&
            mouseX < chargerMoveX + 180
            && mouseX > chargerMoveX
            && mouseY < chargerMoveY + 120
            && mouseY > chargerMoveY) {

            // score board
            totalScore = totalScore + score ;
            float r = random(50);
            println(r);
            chargerShot = true;
            chargerDive = false;
        }

    }

    void chargerDying() {
        chargerReachedTarget = false;
        chargerGif = chargerDied;
        image(chargerGif, chargerMoveX, chargerMoveY);
    }
}

void displayCastleHealth() {
    if (castleHealth <= 0) {
      fill(250, 70, 0);
      textFont(castleHealthPoints, 20);
      text("HP: 0", 100, 50);
    } else {
      fill(250, 70, 0);
      textFont(castleHealthPoints, 20);
      text("HP: " + castleHealth, 100, 50);
    }
}

void mousePressed() {
    strokeWeight(2);
    arrowShoot.rewind();
    arrowShoot.play();

    for (int i = 0 ; i < 3; i++)
        shootingStance.play();

    shotsFired = true;
}

void mouseReleased() {
    strokeWeight(1);

    if (shotsFired == true)
        shootingStance.pause();
}

public void stop() {
    arrowShoot.close();
}

Majority of the problems from the charger came from here:
if (onScreen.size() == 0 && chargerIndex == numCharger) {
    println("Game won! :)");
    // gameWon = true;
}

// while onScreen charger less than 5 only and chargerIndex havent reach 300 it will only respawn
while (onScreen.size () < maxChargerOnScreen && chargerIndex <= numCharger - 1) {

    if (chargerIndex < chargerArr.length) { // <--- this is the problem chargerArrayLength
        Charger chargerMobs = chargerArr[chargerIndex];
        // starts from chargerArray[0] to chargerArray[300]
        onScreen.add(chargerMobs);
        chargerIndex++;
        // chargerIndex keeps looping why?
        // println("ADDED ZOMBIE TO ONSCREEN Zombs on screen: " + onScreen.size());
    }
}

// Adjusts maxZombOnScreen based off the current index   Difficulties?
if (chargerIndex == 10)
    maxChargerOnScreen++;
else if (chargerIndex == 50)
    maxChargerOnScreen++;
else if (chargerIndex == 100)
    maxChargerOnScreen += 2;
else if (chargerIndex == 150)
    maxChargerOnScreen += 2;
else if (chargerIndex == 190)
    maxChargerOnScreen += 3;
else if (chargerIndex == 250)
    maxChargerOnScreen += 3;
else if (chargerIndex == 260)
    maxChargerOnScreen += 3;
else if (chargerIndex == 270)
    maxChargerOnScreen += 5;

// removes dead zombies, living zombies act normally
for(int i = 0; i < onScreen.size(); i++) {
    Charger c = onScreen.get(i);

    // add money when a zombie is dead
    // if (c.getHealth() <= 0)
    if (chargerShot==true) {
        c.chargerDying();
        onScreen.remove(i);
        chargerKilled++;
        i--;
    } else {
        c.act(); ///it should just act
    //  c.displayHealth(); // if gt time only do
//  }
    }
}

Evaluation and criticism is appreciated.

A: There are several issues with the code, but for now, I'll ignore the parts that are somewhat "not clean" or "not elegant", and focus on the main problem that was the reason for the question:
The state of all Chargers instances was the same. The fields
boolean chargerReachedTarget = false, chargerShot = false, chargerDive = true;

have been defined globally. Just by moving this line (that is, these 3 fields) into the Charger class, and changing the line
if (chargerShot==true) {

to
if (c.chargerShot==true) {

the game already seemed to be much closer to what you presumably have been looking for. After this modification, it was possible to shoot individual opponents, and new opponents kept coming after the old ones had disappeared.
Again: The code is not really nicely structured, and there are many possible minor improvements. For example, something like if (c.chargerShot==true) { ... } should better be if (charger.isShot()) { ... }. But I'm not so familiar with processing and its best practices, so I'm not sure how the "best" solution would look like in a global sense...


text:
Q: customizable PageRank algorithm in Gremlin? I'm looking for a Gremlin version of a customizable PageRank algorithm.  There are a few old versions out there, one (from: http://www.infoq.com/articles/graph-nosql-neo4j) is pasted below.  I'm having trouble fitting the flow into the current GremlinGroovyPipeline-based structure.  What is the modernized equivalent of this or something like it?
$_g := tg:open()
g:load('data/graph-example-2.xml')
$m := g:map()
$_ := g:key('type', 'song')[g:rand-nat()]

repeat 2500
  $_ := ./outE[@label='followed_by'][g:rand-nat()]/inV
  if count($_) > 0
    g:op-value('+',$m,$_[1]/@name, 1.0)
  end

  if g:rand-real() > 0.85 or count($_) = 0
    $_ := g:key('type', 'song')[g:rand-nat()]
  end
end

g:sort($m,'value',true())

Another version is available on slide 55 of http://www.slideshare.net/slidarko/gremlin-a-graphbased-programming-language-3876581.  The ability to use the if statements and change the traversal based on them is valuable for customization.
many thanks

A: I guess I'll answer it myself in case somebody else needs it.  Be warned that this is not a very efficient PageRank calculation.  It should only be viewed as a learning example.
g = new TinkerGraph()
g.loadGraphML('graph-example-2.xml')
m = [:]
g.V('type','song').sideEffect{m[it.name] = 0}

// pick a random song node that has 'followed_by' edge
def randnode(g) {
  return(g.V('type','song').filter{it.outE('followed_by').hasNext()}.shuffle[0].next())
}

v = randnode(g)
for(i in 0..2500) {
  v = v.outE('followed_by').shuffle[0].inV
  v = v.hasNext()?v.next():null
  if (v != null) {
    m[v.name] += 1
  }

  if ((Math.random() > 0.85) || (v == null)) {
    v = randnode(g)
  }
}

msum = m.values().sum()
m.each{k,v -> m[k] = v / msum}
println "top 10 songs: (normalized PageRank)"
m.sort {-it.value }[0..10]

Here's a good reference for a simplified one-liner:
https://groups.google.com/forum/m/#!msg/gremlin-users/CRIlDpmBT7g/-tRgszCTOKwJ
(as well as the Gremlin wiki: https://github.com/tinkerpop/gremlin/wiki)


text:
Q: Javascript not passing through on local webview page Hi I am trying to make an android application that you can draw on a canvas and I found html was the easiest to do this. I grabbed a couple of code samples and created a project, I am only 1/2 way done and I am stuck on this little frustrating part. When I click on a button in the menu to clear the canvas, the javascript doesn't pass through and clear the canvas on the html page. Here is my code...
MainActivity.java
package tk.leoforney.ftcscorer;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final WebView htmlWebView = (WebView)findViewById(R.id.fieldPad);
        WebSettings webSetting = htmlWebView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setDisplayZoomControls(true);
        htmlWebView.setWebChromeClient(new WebChromeClient(){
            public void onPageFinished(WebView view, String url) {
                final Button button = (Button) findViewById(R.id.clearCanvas);
                button.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                            htmlWebView.evaluateJavascript("newCanvas()", null);
                        } else {
                            htmlWebView.loadUrl("javascript:newCanvas()");
                        }
                    }
                });
            }
        });
        htmlWebView.getSettings().setAllowFileAccess(true);

        String htmlFilename = "index.html";
        AssetManager mgr = getBaseContext().getAssets();
        try {
            InputStream in = mgr.open(htmlFilename, AssetManager.ACCESS_BUFFER);
            String htmlContentInStringFormat = StreamToString(in);
            in.close();
            htmlWebView.loadDataWithBaseURL(null, htmlContentInStringFormat, "text/html", "utf-8", null);

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

    }

    public static String StreamToString(InputStream in) throws IOException {
        if(in == null) {
            return "";
        }
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
        }
        return writer.toString();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }
}

index.html
<!doctype html>

    <title>Coaches playbook</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" />

Loading Canvas...

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    tools:context="tk.leoforney.ftcscorer"
    android:orientation="vertical">

    <WebView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fieldPad"
        android:layout_width="match_parent"
        android:layout_height="365dp"
        />
</LinearLayout>

menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">

    <item android:id="@+id/clearCanvas" android:title="@string/action_clear" android:orderInCategory="100" app:showAsAction="never" />
</menu>

If anybody can figure this out that would be awesome! thanks...

A: if you want to load script in local Web-view so you can use loadDataWithBaseURL method.
First of all Put all your javascript under an assets folder  (as you want local so otherwise give URL of javascript file) and give JS file path relative to the assets folder in your script tag (in the html). Don't put a slash in the beginning of src.
Read the HTML into a string (htmlString) and then load it in the webview as following below.
webView.loadDataWithBaseURL("file:///android_asset/", htmlString, "text/html", "UTF-8", null);

It's for fine in my project.

A: Thanks all. I just had to move the button click event down to the oncreateoptionsmenu function.


text:
Q: How to Recreate the Last State of an App the Next Time it is Launched? I have 2 views. When I'm on the 1st view, I have a textfield. I enter some text in the textfield. I exit the app, launch some another application and then return to my application. I want to maintain state of the textfield and that view. Likewise, if I quit with the 2nd view active, when I return to the app I need to return the view to the state it was in when the app quit.
How do I save the information about the state of my app when it last quit so I can recreate it upon the next launch?

A: Use the NSUserDefaults to write the value and selected view index to the user's preferences.

A: Apple's DrillDownSave sample may be helpful


text:
Q: Reverse proxy for a NodeJS website I look for a reverse proxy for my NodeJS website. I thought of Varnish or nginx or something else.
What would you suggest me and why (do not necessarily focus on Varnish vs nginx)?

A: nginx would probably be the best stand-alone solution, however, when I'm working with Node.js, I prefer to keep everything in Node.js so I don't have to worry about the (relatively simple) configuration. I personally use node-reverse-proxy, which allows me to just specify some simple routes in a simple application, and then route it back to the individual applications.
This is the node-reverse-proxy sample code:
var node_reverse_proxy = require('node-reverse-proxy');

var ip = '127.0.0.1';
var reverse_proxy = new node_reverse_proxy({
    'first_host.com' : ip + ':8082',
    'my.second_host.com' : ip + ':8081',
    'my.second_host.com/page/' : ip + ':8080',
    '' : ip + ':8080' // catch all other routes
});

reverse_proxy.start(80);

You might find that nginx better suits your needs, but personally, for a simple reverse proxy setup, I do prefer node-reverse-proxy.


text:
Q: How to attach an image to a border after the border line (not inside the border) Here is the link to get an idea what I am trying to do.
https://stackblitz.com/edit/angular-resizable?file=app%2Fapp.component.css
in here.. instead of darkgrey I want to add an image in that palce.
I have tried something like this but it is not working
this.el.nativeElement.style["border-right"] = this.resizableGrabWidth + "url('image.svg')";

A: A border image can not be specified on "border-right" but only for all borders at once using the border-image style. Try this:
this.el.nativeElement.style["border-right"] = this.resizableGrabWidth + "px solid transparent";
this.el.nativeElement.style["border-image"] = "url(assets/border.png) 30 round";

The border image will only appear on the right when that is the only border with none-zero width.
(See also: w3schools example )


text:
Q: Transparent background turns black after converting into webp format via HTML5 canvas I got a problem with converting PNG image to webp format. The background turns black instead of remaining transparent.
How can I fix this?

var img = document.querySelector('#sample');
var webp = document.querySelector('#webp');
img.onload = function() {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  canvas.width = this.naturalWidth;
  canvas.height = this.naturalHeight;
  ctx.drawImage(this, 0, 0, this.naturalWidth, this.naturalHeight);
  webp.src = canvas.toDataURL('image/webp');
};
img.src = 'data:image/png;base64,[encoded data, 5620 characters]';

A:

var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var img=new Image()
img.src="data:image/png;base64,[encoded data, 5620 characters]";

setTimeout(function(){cxt.drawImage(img,0,0);},2000);
<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>无标题</title>

<canvas id="myCanvas" width="200" height="100"></canvas>

this is my test with your picture,so I think there is no problem in your code.


text:
Q: Bind List to comboBox in C# I have three comboBoxes in a WinForm. To load those combos with data I created three methods.
Two of these methods looks like this:
private void cmbLoadSubjects(List<Subject> subjects)
    {
        BindingSource source = new BindingSource();
        source.DataSource = subjects;

        cmbSubjects.DataSource = source;
        cmbSubjects.DisplayMember = "name";
        cmbSubjects.ValueMember = "id";
    }

private void cmbLoadTeachers(List<Teacher> teachers)
    {
        BindingSource source = new BindingSource();
        source.DataSource = teachers;

        cmbTeachers.DataSource = source;
        cmbTeachers.DisplayMember = "name";
        cmbTeachers.ValueMember = "id";
    }

The idea is to display the subject's name and the teacher's name in the combos.

Given the fact that these methods are very similar, I tried to create a generic method that can load all the combos. So I came up with this:
private void cargarCombo<T>(ComboBox combo, List<T> data, string displayMember, string valueMember)
    {
        BindingSource source = new BindingSource();
        source.DataSource = data;

        combo.DataSource = source.DataSource;
        cmbEstadoAsistencia.DisplayMember = displayMember;
        cmbEstadoAsistencia.ValueMember = valueMember;
    }

If I use this method to load my combos, it only works fine in one of the combos. In the other combos it shows the typical"WorkspaceName.ClassName".

I tried loading teachers and then tried loading subjects in the only combo that works fine and it showed what it was supposed to show:

But when I try to load the other combos using this generic method, despite the class of the objects, I get "Workspace.Teacher", "Workspace.Subject".
I compared the values of the properties of the three combos trying to find something different in order to discover what could be causing this behavior and they only differ in their name and position.
I tried creating a new combo and loading lists of different class of objects but the problems is still there.
One curious thing is that it all works fine if I use the methods I showed you at the beggining of the question. I mean, I could just make use of those methods and forget about this stupid problem, but I'm curious.. I just don't get why the generic method only works fine in one combo.

A: I found the problem. The problem is that I'm an idiot sometimes:
private void cargarCombo<T>(ComboBox combo, List<T> data, string displayMember, string valueMember)
{
    BindingSource source = new BindingSource();
    source.DataSource = data;

    combo.DataSource = source.DataSource;
    cmbEstadoAsistencia.DisplayMember = displayMember;
    cmbEstadoAsistencia.ValueMember = valueMember;
}

cmbEstadoAsistencia should be change to combo
I was hardcoding the name of one of the comboBoxes.
I'm sorry for posting garbage :(

A: Your error could be here
combo.DataSource = source.DataSource;

Change that to
combo.DataSource = source;

A: Maybe the "Subject" class needs to have its get and set in its attributes


text:
Q: how to process one or more items in PayPal shopping cart I would like some recommendations about open source or other solutions for processing one or more items collected using PayPal's shopping cart button. Thanks.
At this point, I am researching, looking for possible solutions.
Logically, PayPal's "add to cart" and "view cart" buttons suggests I will be sending an array and they will be returning verifications for that array. If that is true, I can use Javascript to generate a page with the appropriate images and links to access the purchased items. I will focus on PayPal's articles about the shopping cart data.

A: Almost any ecommerce shopping cart ever made is compatible with PayPal Checkout, so you can essentially use anything that suits your other needs.
Start with searching the web or PayPal's Partner Directory


text:
Q: Laravel 7 auth attempt returns false I just cant seem to find a solution, my Auth::attempt() function always return false and I cant find what I am doing wrong. This is my migration for tblusers:
public function up()
{
    Schema::create('tblusers', function (Blueprint $table) {
        $table->id();
        $table->string('Username')->unique();
        $table->string('FirstName');
        $table->string('LastName');
        $table->string('ContactNo')->unique();
        $table->string('Email')->unique();
        $table->timestamp('EmailVerifiedOn')->nullable();
        $table->string('Password');
        $table->integer('AddedBy');
        $table->rememberToken();
        $table->timestamps();
    });
}

I customized the User model:
class User extends Authenticatable
{

    protected $table = 'tblusers';
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'Password', 'remember_token',
    ];
}

Therefore the password is no longer visible on User:: queries, so I use Auth::attempt instead. This is how I insert my hashed password:
    $password = $request->Password;
    $hash = Hash::make($password);

    $insertData = array(
        ...
        'Email' => $email,
        'Password' => $hash,
        'AddedBy' => 0,
        'created_at' => date('Y-m-d H:i:s')
    );

This is how I use Auth::attempt, can somebody point out what I'm doing wrong as it always returns false.
        $credentials = array(
            "Username" => $username,
            "Password" => Hash::make($password)
        );

        return dd(Auth::attempt($credentials));
        if (Auth::attempt($credentials)) {
            $response = true;
        } else {
            $response = false;
        }

A: The 'password' field that is passed to attempt MUST be named password (exactly like this). Also you will need to adjust the getAuthPassword method on your Model since by default it expects the password field in the database to be 'password'. If this is a new project and database I highly suggest you follow the conventions, but if you want to keep things the way they are, these are the changes you will need to make:
$credentials = [
    'Username' => $username,
    'password' => $password,
];

Notice the key is password and we are not hashing the password, as it is expecting the plain-text version of the password so it can eventually do a hash check on it.
On this Model you will need to override the getAuthPassword method:
public function getAuthPassword()
{
    return $this->Password;
}