text:
Q: gvnix over Jboss 6 and Oracle I have installed gvnix geo-petclinic example over Tomcat and Postgis without problems. Next I tried to install it over Jboss and Oracle
I changed roo script with:
jpa setup --provider HIBERNATE --database ORACLE --userName user --databaseName dbname --password pass --hostName host

When I tried to run it, I get this error:
13:24:57,781 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 48) MSC000001: Failed to start service jboss.persistenceunit."geo-gvnix-jboss-oracle2.war#persistenceUnit": org.jboss.msc.service.StartException in service jboss.persistenceunit."geo-gvnix-jboss-oracle2.war#persistenceUnit": java.lang.IllegalStateException: java.lang.ClassNotFoundException: Can't find a delegate
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:103) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_45]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_45]
    at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_45]
    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: java.lang.IllegalStateException: java.lang.ClassNotFoundException: Can't find a delegate
    at net.bull.javamelody.JpaPersistence.guessDelegate(JpaPersistence.java:202)
    at net.bull.javamelody.JpaPersistence.loadOrGuessDelegate(JpaPersistence.java:170)
    at net.bull.javamelody.JpaPersistence.findDelegate(JpaPersistence.java:162)
    at net.bull.javamelody.JpaPersistence.createContainerEntityManagerFactory(JpaPersistence.java:124)
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl.createContainerEntityManagerFactory(PersistenceUnitServiceImpl.java:200) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl.access$600(PersistenceUnitServiceImpl.java:57) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
    at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:99) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
    ... 4 more
Caused by: java.lang.ClassNotFoundException: Can't find a delegate
    ... 11 more

A: gvNIX generates Java standard applications, so you should run your application on JBoss EAP 6.2+ server without problem... but you need to apply some little changes ;)...

*

*Provided libraries: JBoss provides persistence libraries unlike tomcat. You should set as provided persistence components on pom.xml (remember set your oracle driver as provided if needed and add oracle driver to JBOSS Server)
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.2.2.Final</version>
   <scope>provided</scope>
</dependency>
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>4.2.2.Final</version>
   <scope>provided</scope>
   <exclusions>
     <exclusion>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
     </exclusion>
     <exclusion>
       <groupId>dom4j</groupId>
       <artifactId>dom4j</artifactId>
     </exclusion>
   </exclusions>
</dependency>
<dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.0-api</artifactId>
   <version>1.0.1.Final</version>
   <scope>provided</scope>
</dependency>
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-validator</artifactId>
   <version>4.3.1.Final</version>
   <scope>provided</scope>
</dependency>

*Path conflicts: JBoss doesn't like '*' on classpath configuration, so you need to modify web.xml file with:
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:META-INF/spring/applicationContext.xml,classpath:META-INF/
spring/applicationContext-security.xml
  </param-value>
</context-param>

*DataSource: gvNIX applications running on JBoss EAP 6.2.0+ needs to configure a valid JNDI Datasource for data access. So you need to modify your  Datasource configuration on applicationContext.xml file as the following:

*

*Comment current BasicDatasource

*Add the following JNDI Datasource configuration:
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
<tx:jta-transaction-manager />
<jee:jndi-lookup id="entityManagerFactory" jndi-name="java:jboss/medaleaEntityManagerFactory"
expected-type="javax.persistence.EntityManagerFactory" />

*Modify transaction-type to JTA on persistence.xml. Your persistence.xml file will be as follow:
[...]
<persistence-unit name="persistenceUnit" transaction-type="JTA">
 <provider>org.hibernate.ejb.HibernatePersistence</provider>
 <jta-data-source>java:jboss/datasources/YOURDATASOURCENAME</jta-data-source>
 <properties>
   [...]
   <property name="jboss.entity.manager.factory.jndi.name"
value="java:jboss/medaleaEntityManagerFactory"/>
 </properties>
</persistence-unit>
</persistence>
With changes above, your project should run on JBoss EAP 6.2+ server ;)

A: The Java EE spec says:

EE.8.2.3
Library Conflicts If an application includes a bundled
  version of a library, and the same library exists as an installed
  library, the instance of the library bundled with the application
  should be used in preference to any installed version of the library.
  This allows an application to bundle exactly the version of a library
  it requires without being influenced by any installed libraries. Note
  that if the library is also a required component of the Java EE
  platform version on which the application is being deployed, the
  platform version may (and typically will) take precedence.

gvNIX generates apps that include bundled libraries, so jcgarcia showed the way to customize a generated app to remove the persistence module (because its a required component) from it and configure the app to get the persistence resources from JBoss.
You only have to install H-Spatial as JBoss module in order to be provided by JBoss.


text:
Q: Show div using button and hide it if click outside the div I tried to create a function to show and hide a div, to hide the div user can use close button or click outside the div, but the problem is the close function to hide the div if user click element outside the div run first before i the div is showed:
html:

$('#close-add').on('click', function() {
  $("#add-shipping-modal").hide();
});

$('#new-shipping').on('click', function() {
  $("#add-shipping-modal").show();
});

$('body').click(function(event) {
  setTimeout(
    if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
      if ($("#add-shipping-modal").css('display') != 'none') {
        $("#add-shipping-modal").hide();
      }
    }
  });
});

<button id="new-shipping'">Open Div</button>

  <button id="close-add">Close Div</button>

 Show Me

when i click the #new-shipping button, the hidden div won't show up, i guess it's because when i click the #new-shipping button, it shows the div first and then trigger the body click function

A: There is already a solution provided at W3Schools.
Check Here: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal
Snippet

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}

Modal Example

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

A: You have added ' extra in your code after new-shipping
<button id="new-shipping'">Open Div</button>

should be
 <button id="new-shipping">Open Div</button>

https://jsfiddle.net/bntnfhLm/
Also please change the body click function by using preventdefault/stopPropagation
$("#add-shipping-modal").click(function(e){
    e.stopPropagation();
});

$(document).click(function(){
    $("#add-shipping-modal").hide();
});

A: try this
 $('#new-shipping').on('click', function () {
            $("#add-shipping-modal").show();
            return false;
        });

        $(document).click(function (event) {
            $("#add-shipping-modal").hide();
        });

A: try this
$('#close-add').on('click', function () {
            $("#add-shipping-modal").hide();
        });

        $('#new-shipping').on('click', function () {
            $("#add-shipping-modal").show();
            return false;
        });
        $("#add-shipping-modal").click(function () { return false; });

        $(document).click(function (event) {
            $("#add-shipping-modal").hide();
        });

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I repair a Disk (is not booting) My hard drive will not boot. The screen comes up blank. It was working fine yesterday. No changes made. I am using Ubuntu 13.10 on 64-bit.
On the same computer, I am using an USB emergency installation to do this work. It booted just fine, all computer hardware also tested OK; hence, the problem is the Ubuntu installation.
This computer is ubuntu dedicated (no dual boot.)

A: Try use Boot-Repair for repair.
To add Boot-Repair to the repository use:
$ sudo add-apt-repository ppa:yannubuntu/boot-repair

To update your repository:
$ sudo apt-get update

To install boot-repair:
$ sudo apt-get install -y boot-repair

Once Installation completes, run boot-repair on terminal by typing the following command or select it by System → Administration → Boot Repair.
$ boot-repair


text:
Q: full width submenu with relative links I wanted to know how to achieve full width submenu. I did it but the content drop down always starts from left and not relative
this is my fiddle
http://jsfiddle.net/cancerian73/RB9jX/1/
.megamenu {
list-style:none;
padding:0;
position:relative; /* For IE7 */
margin:0;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
line-height:1;
}

the problem is all content starts from left I want them to start relatively as per the item list keeping the submenu width 100%
Please see the screenshot. The menu when hover on about should start relative and not from the left having the full width submenu
Please let me know
Thanks

A: Here is a sample menu

    Menu

            Fruits

Apple

Orange

Grape

Banana

            Vegetables

Lemon

Cucumber

Melon

// css
  .dropdown {
          position: relative;
          display: inline-block;
          font-size: 110%;
  }

  .dropdown ul {
         position: absolute;
         top: -100%;
         left: 100%;
         display: none;
         background-color: inherit;
         padding: 0;
         list-style: none;
         border: 1px solid #ccc;
  }

  .dropdown ul li {
         position: relative;
         list-style: none;
         margin: 5px 0;
         background-color: inherit;
  }

  .dropdown ul li a {
         display: block;
         padding: 3px 10px;
  }

  .dropdown ul li a:hover {
         background-color: #18b6f2 !important;
  }

  .dropdown ul li:hover > ul {
        display: block;
        top: 0;
        background-color: inherit;
  }

  .dropdown ul li:hover > a {
        background-color: #85ddff;
  }

  .dropdown:hover > ul {
        display: block;
  }

A:     ul.mega-dropdown {
      list-style: none;
      padding: 0;
    }
    ul.mega-dropdown li.menu-item {
      position: relative;
      list-style: none;
      background-color: #5b5b5b;
      padding: 10px 5px;
      -moz-transition: all 0.3s ease-in;
      -o-transition: all 0.3s ease-in;
      -webkit-transition: all 0.3s ease-in;
      transition: all 0.3s ease-in;
      cursor: pointer;
    }
    ul.mega-dropdown li.menu-item:hover {
      background-color: #373737;
    }
    ul.mega-dropdown li.menu-item:hover > .description {
      display: block;
    }
    ul.mega-dropdown li.menu-item > a {
      display: block;
      font-size: 120%;
      color: white;
    }
    ul.mega-dropdown li.menu-item .description {
      display: none;
      position: absolute;
      background-color: white;
      border: none;
      border-bottom: 2px solid;
      border-left: 2px solid;
      border-right: 2px solid;
      border-color: #373737;
      height: 500%;
      top: 100%;
      left: 0;
      right: 0;
      z-index: 99;
      padding: 10px;
    }

Is this what you want?

            Eatables

                I wanted to know how to achieve full width submenu.

                I did it but the content drop down always starts from left and not relative

            Nothing

                I wanted to know how to achieve full width submenu.

                I did it but the content drop down always starts from left and not relative


text:
Q: OCRA missing submodules of libraries if rack/grape api endpoints aren't called I'm trying to pack my REST app into into an executable with OCRA. I have a few gems required in my script:
require 'rack'
require 'rack/server'
require 'grape'
require 'grape-entity'
require 'rubygems'

I skip starting the server with this:
if not defined?(Ocra)
    Rack::Server.start options
end

When I try to run my server.exe:
Temp/../server.rb:221:in `default_middleware_by_environment':
cannot load such file -- rack/content_length (LoadError)

Which means that it doesn't detect submodules of rack that exist, but aren't used and therefore not included. If I add a require 'rack/content_length' it continues with cannot load such file -- rack/chunkedEven` and so on.
When I interrupted my server by hand before I also had to call a few api endpoints to have everything included.
I think my options are either:

*

*Tell OCRA to include all the submodules of rack and grape, but compiling that list is a bit time consuming and would increase the file size
I already tried ocra server.rb --gem-full=rack --gem-full=grape, which get my server started, but when calling the API 'rack/mount/strexp' is missing again..

*Calling the API within my script, but I couldn't figure out how to do that. I can't add a block to Rack::Server.start options and it does only continue when I interrupt the server.
Any ideas to implement either option, or is there another solution?

A: If we run the rack app with a rack handler (webrick / thin / else), we can shutdown the server in another thread so that ocra can finish packing (not sure how to do same thing with Rack::Server).
app     = Rack::Directory.new ENV['HOME'] # a sample app
handler = Rack::Handler.pick %w/ thin webrick /
handler.run app do |server|
  # handler.run yields a server object,
  # which we shutdown when ocra is packing
  if ocra_is_packing # replace with proper condition
    Thread.new { sleep 10; server.shutdown }
  end
end

You may have to do something else (access the server etc.) to have ocra pack appropriate dependencies.


text:
Q: Assembly Code If then statement Everything in my code is functioning up until the 3 rows of exclamation marks. It prints out the fibonacci sequence up until the limit that the user inputs is where the sequence will stop. But after the 3 rows of exclamation marks i want it to print a string using if multiple if then statements. But when i run it, it doesn't print that string for some reason. So the error is somewhere after the exclamation points. Im just not sure what is the problem. If(J >= 2584) then you print this statement, if(J >= 1597) then you print this , and so on and i want to do this with a bunch more if then statements. Thankyou for your help
.section ".data"

prompt: .asciz "\nEnter a limit on the largest number to be displayed: "
format: .asciz "%d"
format2: .asciz "%d "
myString: .asciz "\n1 "                   !print leading 1
myString2: .asciz "\n"                  !double space

string: .asciz "\nThe last number %d is divisible by %d\n""

prompt2: .asciz "\nDo you want to print a different sequence (Y/N): "
format3: .asciz "%s"

noString: .asciz "\nGoodbye.\n"
NOstring: .asciz "\nGoodbye.\n"

TESTSTRING: .asciz "You entered the character: %s\n"
input2: .asciz "  "

.align 4
input: .word 0
nl: .asciz "\n"

!    input2: .byte 0
!    nl2: .asciz "\n"

define(f, l0)
define(i, l1)
define(j, l2)
define(g1, l3)
define(g2, l4)
define(g3, l5)

.align 4
.section ".text"
.global main
main:
save %sp, -96, %sp

!BIGLOOP:

clr   %f
mov   1, %j
clr   %i

set   prompt, %o0           !point o0 to the prompt
call  printf                        !call printf to print the prompt
nop

set   format, %o0           !address of the format
set   input, %o1            !address of the location for the max
set   nl, %o2
call  scanf                 !reads user input, coverts to a
nop                         !number and stores at the memory referenced by input

set   format2, %o0
set   input, %o1
ld    [%o1], %o1             !userInput loaded into o1

mov   %o1, %g1                 !g1 = user input
set   myString, %o0       !print leading 1
call  printf
nop

test:

  add   %i, %j, %f            !f=i+j
  cmp   %f, %g1               !while(f<=userInput)
  bg    done
  nop
  mov   %j, %i                !i=j
  mov   %f, %j                !j=f
  mov   %j, %o1               !%o1=j
  set   format2, %o0
  call  printf
  nop
  mov   %j, %g2
  ba    test
  nop

done:

  set   myString2, %o0         !double space
  call  printf
  nop

  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  !divisible
  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  set     1, %o2
ctz_loop:
  andcc   %g2, %o2, %g0
  bne     ctz_end
  nop
  ba      ctz_loop
  add     %o2, %o2, %o2
ctz_end:
  set     string, %o0
  mov     %g2, %o1
  call    printf
  nop

  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  ! Do you want to print another sequence
  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!

 ! invalidloop:

  set    prompt2, %o0                    !do you want to print a different sequence
  call   printf
  nop

  set    format3, %o0
  set    input2, %o1

  call   scanf
  nop
  set    input2, %o1                  <<<------------------------
  ldub     [%o1], %g3                       !loading user answer to %g3

  set    TESTSTRING, %o0       !!!!!!!TestString
  mov    %g3, %o1              !!!!!!!TestStromg
  set    input2, %o1           !!!!!!!
  call   printf                !!!!!!!
  nop                          !!!!!!!

  /*

  cmp    %g3, "y"                         !comparing answer to y
  bne    YES
  nop
  ba     BIGLOOP                         !loop back to the beginning of the program
  nop
YES:
  cmp    %g3, "Y"                        !comparing answer to Y
  bne    no
  nop
  ba     BIGLOOP                         !loop baack to the beginning of the program
  nop
no:
  cmp    %g3, "n"                        !comparing answer to n
  bne    NO
  nop
  set   noString, %o0
  call  printf
  nop
  ba    finish
  nop
NO:
  cmp    %g3, "N"                         !comparing answer to N
  bne    invalid
  nop
  set   NOstring, %o0
  call  printf
  nop
  ba    finish
  nop

invalid:                             !if neither Y,y,N,n was answered then it should ask if you still want to print another sequence again until the correct is chosen
  ba    invalidloop
  nop

finish:

*/

ret
restore

!!!ERROR!!!!
!!!!!!!!!!!!
!!!ERROR!!!!

!Undefined                       first referenced
!symbol                             in file
!invalid                             /var/tmp//cc87QWAM.o
!BIGLOOP                             /var/tmp//cc87QWAM.o
!ld: fatal: Symbol referencing errors. No output written to mai4
!collect2: ld returned 1 exit status

A: Knowing that the real problem to solve is printing the largest power-of-two divisor, here is a possible algorithm: for(mask = 1; (mask & x) == 0; mask += mask);
The assembly version could look like:
string: .asciz "\nThe last number %d is divisible by %d\n"
...
  set 1, %o2 ! mask
ctz_loop:
  andcc %g2, %o2, %g0
  bne ctz_end
  nop
  ba ctz_loop
  add %o2, %o2, %o2 ! next bit
ctz_end:
  set string, %o0
  mov %g2, %o1
  call printf
  nop


text:
Q: request qs key value encoded, How to disable encode string? var Request = require("request")

var options = {
    url: option.apiUrl,
    qs: {
      apiKey: "T%2BLkADWTX0OzgMMDmEPHffxQNYcgNMyfYJcXyR0cl0%2BNe8w0g%3D%3D",
    }
    json: true
}

function handleResponse (error, response, body) {

    console.log(response) //apiKey is changed to T%252BLkADWTX0OzgMMDmEPHffxQNYcgNMyfYJcXyR0cl0%252BNe8w0g%253D%253D

}

Request(options, handleResponse);

Hi,
the apiKey is changed to wrong Key.
What option should I add for disable string encode on request qs?
or What is alternative way to get Json API?

A: its because your api key is uri encoded with encodeURIComponent() as a query string , so specials char like %3D become 25%3D when the request is encoded again, if you use decodeURIComponent you can have the right apiKey that will be encoded properly
   var string = "T%2BLkADWTX0OzgMMDmEPHffxQNYcgNMyfYJcXyR0cl0%2BNe8w0g%3D%3D"
   decodeURIComponent(string) // "T+LkADWTX0OzgMMDmEPHffxQNYcgNMyfYJcXyR0cl0+Ne8w0g=="

PS: you shouldnt share API keys on SO


text:
Q: Populating a generator. Is it possible? I have a generator that generates a circle(SKShapeNode) every 2 seconds from the y-axis. (Moves up). I would like to know if it is possible to populate this generator uniformly(every x number of points.
Here is my code for said generator:
class CircleGen: SKShapeNode {
    var circles = [WhiteCircles]()
    var circleTracker = [WhiteCircles]()
    var generationTimer: NSTimer!
    var circ: WhiteCircles!

    func generateCircles() {
        for var i = 0; i < 4; i++ {
            var scale: CGFloat
            let rand = arc4random_uniform(10)
            if rand == 0 {
                scale = -15.0
            } else {
                scale = 15.0
            }
            let circle = WhiteCircles()
            circle.position.x = lineGen.position.x

            circle.physicsBody?.affectedByGravity = false
            circle.position.y = 35
            self.circles.append(circle)
            circleTracker.append(circle)
            foregroundNode.addChild(circle)
        }
    }

    func startGeneratingEvery(seconds: NSTimeInterval) {
        let callGenerateAction = SKAction.runBlock { () -> Void in
            self.generateCircles()
        }
        let waitOneSecond = SKAction.waitForDuration(seconds)

        let sequenceAction = SKAction.sequence([callGenerateAction, waitOneSecond])

        let circleGenerateAction = SKAction.repeatActionForever(sequenceAction)
        self.runAction(circleGenerateAction, withKey: "generateCircles")
    }
}

Will post more code if necessary. Thank you in advance.


text:
Q: How to obtain the memory space used by a jar during its execution I've coded a java program that I can run using its resulting jar
java -jar foo.jar

I'm interested in obtaining the maximum memory size that my jar program request during its execution. Actually to do that I just look the memory management (like htop), but its not accurate.
I wonder if there is a special parameter that one set while launching the jar that allow to obtain such information at the end of the execution ?

A: Have you tried visualVM, its free and powerful tool to track the java performance application, it'll show you how much your JVM committed from the physical memory, also the total memory of the application that the current JVM running, and some features:

*

*Provide a CPU profiling.

*Provide all info about Threads.

*Provide the JVM Heap and the memory states.

*Provide Info about the GC activities.

Its come with the JDK package, so you don't have to install it, for more info check this
In your case you can do the following :
java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=8484 -Dcom.sun.management.jmxremote.ssl=false -jar foo.jar

Open the visualVM,then select File -> Add JMX connection, then type your host ip and the port that you have been specified in the parameters "in our case its 8484" separated by :, eg localhost:8484, then you ready to go.


text:
Q: Bash programming: get name of one-and-only subfolder of given directory In bash, I'd like to get the name of the one-and-only subfolder of a:
cd /tmp; mkdir -p a/b; v=$(ls -1 a); echo "$v"

outputs:
b

Which is what I wanted.
This works, because I know there will be only one-and-only subfolder inside a.
Feel free to assume this is guaranteed in all cases in my scenario.
What I feel uneasy about, is this recommendation from Bash pitfalls
In addition to this, the use of ls is just plain unnecessary.
It's an external command whose output is intended specifically
to be read by a human, not parsed by a script.

This is even more intimidating and lapidary (from the same link as above):

parsing the output of ls -- a utility whose output should never ever be parsed.

It resonates with me but this, an attempt at using bash globbing, obv. does not work:
 cd /tmp; mkdir -p a/b; v=a/*; echo "$v"

outputs:
a/*

Sadness.
So, how can I get globbing for a variable assignment?
I think I know how to leverage globbing outside of assignment..
for d in a/*; do echo "$(basename $d)"; done

outputs:
b

"The right answer" (TM).
Could you kindly teach me how to do this right and explain the principle behind it too, please?
** NOTE: I don't like the output of this command:**
cd /tmp; w='name with blanks'; mkdir -p "$w/b"; v=$(echo "$w"/*); echo "$v"

which is:
name with blanks/b

I'd like to just get:
b

do I have to use basename afterwards, or could I get b directly, somehow?

A: v=$(cd a;echo *)

Wildcards are expanded inside command substitution, and echo will output it so it will be used in the assignment.
The cd will allow you to just get the basename without calling basename.

A: Pretty sure I wrote that pitfalls sentence. Anyway... yours fails because brace expansions, globs, and word-splitting don't apply to scalar assignments.
printf -v v %s */

And a little-known trick that will only work using the coreutils printf(1) (assuming there were multiple directories).
v=$(LC_COLLATE=C; /usr/bin/printf '%s\c' */)

Or alternatively, this is probably closest to what you're after (GNU find):
v=$(find . -maxdepth 1 -type d -name '[^.]?*' -printf %f -quit)

See also: http://mywiki.wooledge.org/ParsingLs


text:
Q: How many ghosts haunt Hogwarts? The PotterMore website says

Hogwarts is the most heavily haunted dwelling place in Britain (and this is against stiff competition, as there are more reported ghost sightings/sensings on these damp islands than anywhere else in the world). The castle is a congenial place for ghosts, because the living inhabitants treat their dead friends with tolerance and even affection, no matter how many times they have heard the same old reminiscences.

So what is the spectral population on the school grounds?

A: There are seven named ghosts in the books

*

*Nearly Headless Nick: Gryffindor House Ghost

*The Fat Friar: Hufflepuff House Ghost

*Helena Ravenclaw: Ravenclaw House Ghost

*The Bloody Baron: Slytherin House Ghost

*Professor Binns: History of Magic teacher

*Moaning Myrtle: Basilisk victim

*Sir Patrick: Head of the Headless Hunt

We also know that there are at least 20 that are around continually.

About twenty ghosts had just streamed through the back wall. Pearly-white and slightly transparent, they glided across the room talking to each other and hardly glancing at the first-years.
Philosopher's Stone - Chapter 7: The Sorting Hat

And potentially upwards of hundreds.

The dungeon was full of hundreds of pearly-white, translucent people, mostly drifting around a crowded dance floor, waltzing to the dreadful, quavering sound of thirty musical saws, played by an orchestra on a black-draped platform.
Chamber of Secrets - Chapter 8: The Deathday Party

(Though some of the attendees may have been invited from outside Hogwarts)
And then of course you have Peeves, who while not a ghost, is certainly spectral.


text:
Q: Running a Java TCP server from a WAR file deployed to Tomcat I have a Java-based server which listens on port 12345 for requests over TCP. Once it is compiled to javanix-server.class, I invoke it via $ java javanix-server and thereafter, whenever the above process is running I can interact with it by running telnet localhost 12345.
I would like this server to be deployed as part of an application - what is the simplest way for me to add it to a WAR file and deploy that WAR on Apache Tomcat, such that whenever Tomcat is running with the WAR deployed I can interact with my server via telnet localhost 12345?
I have tried this:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>mina-sshd-tomcat</display-name>
  <servlet>
    <servlet-name>SSHD</servlet-name>
    <servlet-class>org.apache.sshd.SshServer</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
</web-app>

Despite the class appearing to start without incident, the ports bound to via the main method in org.apache.sshd.SshServer are not actually open once Tomcat is running. Running the same main method without modification outside of Tomcat (eg, directly on the JVM) works fine.


text:
Q: String concatenation in Fortran DATA statement I'd like to define some length-two characters variables using DATA statements, concatenating two named constants referring to single characters, directly in the DATA statement.
Is it possible? If so, what is the correct syntax? Is there a better, concise way to do that?
Example
use m_ascii_chars              ! this defines ch_* stuff as single character named constants
...
character(2) :: pairs(100)
...
DATA pair(1) /   ch_plus // ch_verticalbar   /  ! would be the best one, but it does not work,
                                                ! given the meaning of the slash in the DATA
                                                ! statement

DATA pair(1) / ( ch_plus // ch_verticalbar ) /  ! does not work !!
DATA pair(1) / [ ch_plus // ch_verticalbar ] /  ! does not work !!

! This works, but it is rather verbose
DATA pair(1)(1:1) / ch_plus /
DATA pair(1)(2:2) / ch_verticalbar /
...

! Of course, this works too, but does not fit the requirements.
DATA pair(1) / '+|' /

A: Character concatenation cannot appear in a value for a data statement. For the purposes of the question, the value to initialize a variable must be a constant. '+' // '|' is a constant expression but not a constant.  The statement
DATA pair(1) / '+|' /

as noted is fine, because '+|' is a (literal) constant.  A named constant with that value can be used similarly, and in the initialization expression for a named constant character concatenation (of constants) can be used:
character(*), parameter :: plusbar = ch_plus//ch_verticalbar
data pair(1) / plusbar /

As also seen,
DATA pair(1)(1:1) / ch_plus /
DATA pair(1)(2:2) / ch_verticalbar /

works.  Although verbose, this can be written (slightly) more concisely:
DATA pair(1)(1:1), pair(1)(2:2) / ch_plus, ch_verticalbar /

Your compiler may support an implied-do for the substring, but this is non-standard.
If you want to provide initial values in pieces then you are stuck with data statements and here cannot use string concatenation. However, if you are able to provide an expression for the whole array then you can use concatenation:
character(2) :: pair(100) = [ch_plus//ch_verticalbar, ...]

Such an expression may well be cumbersome, but you have access to various techniques for building up this array.

The difficulty with '+'//'|' isn't with a parsing conflict of // with / of the separator.  Similar restrictions apply with other expressions, such as not being allowed to have
integer i
data i /1+2/

(and of course 3*2 in the value list means 2,2,2 not 6)


text:
Q: state being forgotten on componentDidMount react I'm having an issue where I have a method called userLogin, where a user makes a post request to my server, and if they correctly login with user/pass, they have access to the boards data on the server. I also set a state called isloggedin so react keeps track of the state of whether the user is logged in.
On logging it it works, isloggedin is set to true, they have access to the boards, however the page doesn't reload and show the boards, even though it is successfully GET requesting the data. On reloading the page, the boards show, however isloggedin is then set to false. Not sure why it's not rerendering "/" because the state of isloggedin has changed, and I thought react rerenders on state change. Any help would be appreciate, cheers.
import React from 'react';
import Home from './homePage/home';
import Board from './boardPage/board';
import Signup from './signupPage/signup';
import Login from './loginPage/login';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import axios from 'axios';

class App extends React.Component {

  constructor() {
    super();
    this.state = {
      boards: {},
      loggedin: false
    }
    this.addBoard = this.addBoard.bind(this)
    this.addList = this.addList.bind(this)
    this.addCard = this.addCard.bind(this)
    this.userSignup = this.userSignup.bind(this)
    this.userLogin = this.userLogin.bind(this)
    this.handleDelete = this.handleDelete.bind(this)
    this.handleLogout = this.handleLogout.bind(this)
  }

  componentDidMount() {
    axios.get('/boards').then((res) => {
      this.setState({
        boards: res.data
      })
    })
  }

  addBoard(board) {
    axios.post('/boards', board).then((res) => {
      this.setState({
        boards: res.data
      })
    }).catch((error) => {
      console.log("Not logged in")
    })
  }

  addList(boardId, list) {
    axios.post('/boards/' + boardId + '/lists', list).then((res) => {
      this.setState({
        boards: res.data
      })
    }).catch((error) => {
      console.log(error)
    })
  }

  addCard(boardId, listId, Card) {
    axios.post('/boards/' + boardId + '/lists/' + listId + '/cards', Card).then((res) => {
      this.setState({
        boards: res.data
      })
    }).catch((error) => {
      console.log(error)
    })
  }

  userSignup(userAndPass) {
    axios.post('/signup', userAndPass).then().catch((error) => {
      console.log(error)
    })
  }

  userLogin(userAndPass) {
    axios.post('/login', userAndPass).then((res) => {
      this.setState({
        boards: res.data,
        loggedin: true
      })
    }).catch((error) => {
      console.log(error)
    })
  }

  handleDelete(e, id) {
    this.setState({boards: delete this.state.boards.id})
  }

  handleLogout() {
    this.setState({loggedin: false})
  }

  render() {
    console.log(this.state)
    return (
      <Router>
        <div>
          <Route exact path="/" component={(props) => <Home {...props} boards={this.state.boards} addBoard={this.addBoard} loggedin={this.state.loggedin} handleLogout={this.handleLogout}/>}/>
          <Route path="/boards/:boardId" component={(props) => <Board {...props} boards={this.state.boards} addList={this.addList} addCard={this.addCard} userSignup={this.userSignup}/>}/>
          <Route path="/signup" component={(props) => <Signup {...props} userSignup={this.userSignup}/>}/>
          <Route path="/login" component={(props) => (
            this.state.loggedin
            ? <Redirect to="/"/>
            : <Login {...props} userLogin={this.userLogin}/>
          )}/>
        </div>
      </Router>
    )
  }
}

export default App;


text:
Q: Display png image xamarin.ios I have a Xamarin.ios project running on Visual Studio for Imac.
I would like to display a png image file using XAML and C#.  Would it be best to use a dependency service to construct the image object in C#?
code snippet:
<StackLayout Orientation="Horizontal">
         <Image Name="MyImage" Width="180" />
</StackLayout>

I placed my png file in the assets.xcassents folder. The file name is  picture.png.  How would I get this code to display in the xaml? What would the
code look like.  Thanks for your input.

A: In your case you can use the property Source of the Image tag in XAML. Than you are able to use the following code snippet:
<StackLayout Orientation="Horizontal">
    <Image x:Name="MyImage" Source="picture.png" WidthRequest="180" />
</StackLayout>

And there was another issue in your XAML snippet, because the property Width is a readonly property for internal use by Xamarin.Forms. So if you want to specify the width of the image you must use the WidthRequest property.

A: Got the code working! Changed to BundleResouces and  do not copy for the property on the image file.  Also move  image File to a separate folder.


text:
Q: What should I do when at the end of the running times in NetLogo the model stop working? I was running a model in NetLogo 5.3.1 through behavior space for 5000 timesteps and 100 times run. I set output as a spreadsheet. However, the running time stop at 93 and 5000 timesteps for 24 hours. The clock of the model works and the commend on updating the view and plots also works. What should I do? should I wait for more than 24 hours? should I abort the order? or there is any other solution to not losing the data. The model has worked for about 700 hours.

A: a) BehaviorSpace can look like it's stopped while it's still running-- as long as the total time clock is still increasing, it's still running.
b) If you want to see how it is doing, find the BehaviorSpace output file, make a copy of it, and open the copy. If you do that two times, you can confirm that it's still running.
c) The "Spreadsheet" output format is usually a bad idea. It uses up a great deal of memory and the file is usually harder to use than the "table" format. Sometimes a BehaviorSpace experiment can crash because the spreadsheet output file used up all the computer's RAM.


text:
Q: TableView issue with reuse system and design programmatically I have a problem with my cells where I remove/insert to my tableView, I delete and insert my cells like that :
self.tableView.beginUpdates()
user.lobbySurvey.remove(at: 0)
self.tableView.deleteRows(at: [IndexPath(row: 0, section: 0)], with: .fade)
self.tableView.endUpdates()

Insert:
self.tableView.beginUpdates()
user.lobbySurvey.insert(surveyEnded, at: rowToInsert)
self.tableView.insertRows(at: [IndexPath(row: rowToInsert, section: 0)], with: .fade)
self.tableView.endUpdates()

lobbySurvey is the data array of the TableView.
Problem is the cell I add keep the design of the first cell that I delete previously.
I think this issue is because I check if the card is draw or not. If not checked: the view of the card is added each time the cell is reuse.
this is how I check if the cell is draw or not :
func drawSurveyEnded(){
    if(cardIsDraw == false){
        surveyEnded.draw(cardView: self.cardView)
        surveyEnded.delegate = self
        self.addCardShadow()
        cardIsDraw = true
    }
}

The function is called many times cause to the reuse system of iOS. So I think my problem come from here.
Why my cell in my tableView keep the design of the previous cell that I deleted?
Other code :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"Celll") as! CardCell
for survey in user.lobbySurvey{
    let index = user.lobbySurvey.index(where: {
        //get the current index is nedeed else the cells reuse lazy
        $0 === survey
    })
    if indexPath.row == index{
        var surveyState : UserSurvey.state
        surveyState = survey.state
        switch surveyState{
        case .selectSurvey:
            cell.drawCard(statutOfCard: .selectSurvey)
        case .goSurvey:
            cell.drawCard(statutOfCard: .goSurvey(picture: survey.picture))
        case .surveyEnded:
            cell.drawCard(statutOfCard: .surveyEnded(picture: survey.picture))
        case .surveyWork:
            print("survey in progress to vote")
        case .surveyWaiting:
            cell.drawCard(statutOfCard: .surveyWaiting(selfSurveyId: survey.id, timeLeft: survey.timeLeft, picture: survey.picture))
        case .buyStack:
            cell.drawCard(statutOfCard: .buyStack(supView : self.view))
        }
    }
}

cell.delegate = self
cell.delegateCard = self
cell.layer.backgroundColor = UIColor.clear.cgColor
cell.backgroundColor = .clear
tableView.backgroundColor = .clear
tableView.layer.backgroundColor = UIColor.clear.cgColor
return cell
}

Draw card is a simple switch of the state of the survey where called the good function to create the card like this one I posted before : drawSurveyEnded

A: In your CardCell you have to implement prepareForReuse and clean the cell's view from there. So when cells are recycled, they are cleaned from the previous views that were drawn.

A: You should implement:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    // Update the cell here
}

This way you can make sure the cell gets updated whenever it is ready to be shown.
Remember the UIKit framework keeps a cache for the cells, so it can just reuse them.


text:
Q: Adding additional class with ng-class I used yeoman angular generator to scaffold my app, and now I'm working on a specific view.
I'm building a simple ng-repeat function, in order to clean up my html and avoid repeating the same markup 4 times.
I am making content panels, and want to add a class specific to the content, so I can style it with Sass. I tried using ng-class but so far I've been unable to make it work.
I am new to AngularJS, I tried reading the official ng-class documentation and this writeup but so far I'm unable to make it work. I guess it just takes a while to get used to Angular.
here's my view:

            {{ panel.title }}

and the controller:
'use strict';

angular.module('angularApp')
    .controller('LandingController', function ($scope) {
        $scope.panels = [
            {
                title: 'lokacija',
                contentClass: 'location',
                content:'
Institut Jožef Stefan
Jamova 30
1000 Ljubljana

'
            },
            {
                title: 'kontakt',
                contentClass: 'location',
                content: ''
            },
            {
                title: 'delovni čas',
                contentClass: 'location',
                content: ''
            },
            {
                title: 'katalog',
                contentClass: 'location',
                content: ''
            }
        ];
    });

A: ng-class operates in three different ways, depending on which of three types the expression evaluates to:

*

*If the expression evaluates to a string, the string should be one or more space-delimited class names. (this will match with your case)

*If the expression evaluates to an object, then for each key-value pair of the object with a truthy value the corresponding key is used as a class name.(EX: 'ng-class="{'my-class': (true/false expression)}")

*If the expression evaluates to an array, each element of the array should either be a string as in type 1 or an object as in type 2. This means that you can mix strings and objects together in an array to give you more control over what CSS classes appear. See the code below for an example of this. (EX: ng-class="[style1, style2, style3]") refer ng-class doc and you will get more info.
so you can directly use ng-class="panel.contentClass" this will match with the first list item witch is If the expression evaluates to a string, the string should be one or more space-delimited class names..
you can simply change ng-class="{{panel.contentClass}}" to ng-class="panel.contentClass" because ng-class accepts a expression not a interpolated value.

DEMO

A: You are using ng-class in wrong way. ng-class is use to add/remove class conditionally and dynamically.
Here is full documentation of ng-class.
ng-class requires json in which key is class name and value is condition. if value satisfies, it add that class else not.
for Ex.

it adds my-class if value of panel.contentClass is true.
if you are taking class name from panel.contentClass then better way to use class attribute only instead of ng-class. Here is reference.
For ex.


text:
Q: Finding a formula for a relationship between a target and multiple predictor variables I have a dataset named "covid" of the following shape and head:
number of instances:  19345
number of attributes:  7
  submission_date state  new_case  new_death    density   latitude   longitude
0      2020-06-01    KS       292          9  71.401302  39.011902  -98.484246
1      2020-06-01    WA       271          6  96.704458  47.751074 -120.740139
2      2020-06-01    MT         8          0   6.837955  46.879682 -110.362566
3      2020-06-01    IA       146         15  54.642103  41.878003  -93.097702
4      2020-06-01    KY       136          6        NaN  37.839333  -84.270018

Each row represents a jurisdiction's (state column) per diem covid data along with some info about the jurisdiction- 365 objects per jursidiction (states and some territories).
How can I find a relationship between the submission_date, longitude, and latitude columns as independent variables and the new_case column as the dependent variable? I guess this would be a multiple regression, but I am new to the field and have never created a regression.

A: There are many model types and packages that you could use. I'll show an example using catboost:
from catboost import CatBoostRegressor, Pool
from sklearn.model_selection import train_test_split

# Initialize data
df['submission_date_feature'] = df['submission_date'].as(int)
train_cols = ['submission_date_feature', 'longitude', 'latitude']
label_col = 'new_case'

X_train, y_train, X_test, y_test = train_test_split([df[train_cols], df[label_col]], test_size=0.2)

train_data = Pool(X_train, y_train)
eval_data = Pool(X_test, y_test)

# Initialize CatBoostRegressor
model = CatBoostRegressor(iterations=10,
                          learning_rate=1,
                          depth=3)
# Fit model
model.fit(train_data, eval_set=eval_data)

A: As a benchmark, you can run an OLS regression:
import statsmodels.api as sm
Y = df['new_case'].values
df['submission_date_int'] = df['submission_date'].astype(int)
X = df[['submission_date_int', 'longitude', 'latitude']].values
X = sm.add_constant(X)
model = sm.OLS(Y,X)
results = model.fit()
print(results.summary())

Or use sklearn.linear_model.LinearRegression.

A: You can see the regression equation in sklearn using multiple linear regression the following way.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

y = df['new_case'].values
df['submission_date_int'] = df['submission_date'].astype(int)
X = df[['submission_date_int', 'longitude', 'latitude']].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)

reg_coeff = pd.DataFrame(regressor.coef_, X.columns, columns=['Reg_coeff'])
reg_coeff


text:
Q: Java FX Scene builder didn't recognize css custom color constants(or variables) If the Defined css is plain, scene builder renders the controls with the defined styles...
but if css custom color constants are used, scene builder renders the controls in white...
When I run the application, the style is applied properly(this is done by javaFX libraries) for the scene
note: linking the css file in the scene builder with preview > Scene StyleSheets > add a StyleSheet is implied and that's why the basic stylesheet(without the css color constants) was working.
My Question is:
How do I make it(Scene builder) understand the CSS(color constants) styles

CSS:
.root {
   -color1: #1BA1E2;
   -color2: #F8F8F8;

   -primary-color: -color1;
   -secondary-color: -color2;
}

.windowbox {
    -fx-border-radius: 50 0 50 0;
    -fx-background-radius: 50 0 50 0;
    -fx-background-color: -primary-color;
}

.lbl {
    -fx-background-color: derive(-primary-color, -10%);
    -fx-text-fill: -secondary-color;
}

the above css works perfectly during execution (in the runtime) but scene builder is oblivious to the styles

A: In Scene Builder, select Preview, then Scene Style Sheets, then Add a Style Sheet, as described here. Then select your .css file. To get more info, use the CSS Analyzer functionality.
Also, since your example uses the css class selector ("."), be sure to reference the style class in your fxml (e.g., styleClass="lbl").
Alternatively, you can use the css id selector ("#"). With that approach, you can specify an id in the fxml (id="lbl"). Or you can omit the id attribute from your fxml and by default the fx:id value will be used as the css id selector (fx:id="lbl").
Some info here and here.


text:
Q: Super.init isn't called before returning from initializer I try to give my UITableViewCell Class a custom initilizer but i can't figure it out what I am doing wrong.
Here is my Code:
init(dataObject: [NSManagedObject]!, objectAttributeValues: [String]!,placeholder: String!, segmentedControl: UISegmentedControl?, cellHeight: CGRect, cellWidth: CGRect) {
    self.dataObject = dataObject
    self.Placeholder.text = placeholder
    self.objectAttributeValues = objectAttributeValues

    if segmentedControl != nil {
        self.segmentedControl = segmentedControl!
        didHaveSegmentedControl = true
    }

}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

I tried to call super.init(frame: CGRect(...)) but by implementing this I get another error: Must call a designated initializer of the superclass 'UITableViewCell'
What can I do?
Thank you a lot!

A:     override init(frame: CGRect) {
        super.init(frame: frame)
    }
    convenience init(frame: CGRect, dataObject: [NSManagedObject]!, objectAttributeValues: [String]!,placeholder: String!, segmentedControl: UISegmentedControl?, cellHeight: CGRect, cellWidth: CGRect){
        self.init(frame: frame)
        self.dataObject = dataObject
        self.Placeholder.text = placeholder
        self.objectAttributeValues = objectAttributeValues

        if segmentedControl != nil {
            self.segmentedControl = segmentedControl!
            didHaveSegmentedControl = true
        }

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

I hope this will help you Override init method of UIView in swift

A: The way initialisers work, is they will add their own properties, constants and functions to that instance, then call back to the superclass for an object of it's type. More info here.
For this reason you must call a superclass' initialiser before exiting the initialiser. Here I suggest you call super.init() on the last line of your initialiser. You can choose which of the init methods on UITableViewCell is most appropriate.

A: You have to call the superclasses designated initializer.
For example, I tried to create a subclass of UIView and had the exact same problem you had.
The designated initializer for UIView is super.init(frame: CGRect)
For UITableViewCell the designated initializers are as follows.
// Designated initializer.  If the cell can be reused, you must pass in a reuse
identifier.  You should use the same reuse identifier for all cells of the same
form.
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:
(nullable NSString *)reuseIdentifier NS_AVAILABLE_IOS(3_0)
NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
NS_DESIGNATED_INITIALIZER;

Hope this helped.


text:
Q: Delegatecall: function doesn't change a parentContract array element I deployed two contracts (A,B). Function A.delegateUpdateIDX[contract_B,1] triggers function B.updateIDX[1]
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;

contract A {

string[] private arr = ['a','b','c'];

function showIDX(uint _IDX) public view returns(string memory)
    {
    return arr[_IDX];
    }

function delegateUpdateIDX(address _contractB, uint _IDX) external returns(bool _success)
    {
    (bool b,)=_contractB.delegatecall( abi.encodeWithSignature("updateIDX(uint _IDX)", _IDX) );
    return b;
    }

}

//###################################

contract B {

string[] private arr;

function updateIDX(uint _IDX) external
    {
    arr[_IDX]='X';
    }

}

Then I call functions (in Remix):
A.showIDX[1]
    returns 'b'

A.delegateUpdateIDX(B.address,1)
    no errors
    (should update A.storage and set A.arr[1] to 'X')
    but the delegateCall() returns 'success=false' for some reason
    and A.arr[1] doesn't change to 'X'

A.showIDX[1]
    returns 'b' again (not 'X' as expected)

So, basically, I have no idea why delegateCall() returns 'success=false' and therefore why doesn't A.arr[1] change from 'b' to 'X'. What am I doing wrong?

A: Managed to make it work

*

*abi.encodeWithSignature("updateIDX(uint _IDX)", _IDX) shouldn't have '_IDX' name in it, so I changed it to abi.encodeWithSignature("updateIDX(uint)", _IDX)

-- it still didn't work, the delegateCall() kept returning 'false' --

*changed 'uint' to 'uint256' in both encodeWithSignature() and B.updateIDX()

worked fine this time


text:
Q: HTML Table: How to resize data cells when already specified "colspan"? I have tabular data to display, which has a meaning to both rows and columns.  Columns are time blocks, rows are days. A particular datacell is confined to a single day, but can be in multiple time block. To show this, I am using the colspan tag.

Or Whatever.
I'm trying to apply CSS formating to the entire table, and for changing colors, etc, things are fine, but wanting to have a consistent width is where I am running into problems.
Right now, each data cell's width seems tied to the maximum width in its column (everything auto lines up).  Some columns are itty bitty, others are huge. I'm trying to make columns consistently sized (even if that means every column is as big as the biggest column needs to be), but setting an individual datacells width (either via css or in the tag itself) is getting me nowhere.
I'm thinking maybe the colspan tag is overriding my manual width? If that's the case, how can I change the width of a column as a whole, especially since they aren't explicitly defined? (CAN you explicitly define columns?)
Examples of the CSS I'm using:
#GuideTable td{
background:#ffffff;
border-style: solid;
border-width: 1px;
width: 100px;
}

A: If you could give an example that would be great.
Table's have many special properties, cells must always fill up to 100% of the width of the table - period.
If you give a width property to a cell, that will work. CSS gets iffy as many things won't work.

A: So I ran a little experiment using the following code

            First Row

            Second
            Row

            The
            Third
            Row

And The resulting table had a total width of 300px (give or take).  and each cell was 100px wide.  Perhaps there's something else that's affecting your cell widths.  Try stripping away the CSS and adding it back part by part, even rediculious stuff can totally mess up CSS (like font-family causing a table to fly way off to the left, as I'm dealing with at the moment)

A: (Just found this while searching for something else)
If you don't need to support IE6 you can use the attribute selector to reset widths to cells with colspan:
td { width: 100px; }
td[colspan] { width: auto; }

If you do have to support IE6 you'll need to add a class to each cell with colspan:
...

and
td { width: 100px; }
td.colspan { width: auto; }


text:
Q: CKeditor issue with show hide on radio Button I have implemented CKeditor in one of my textarea. When i use radio button to show & hide textarea on click of radio button, javascript does not work..
After removing CKEditor from textarea.. javascript works properly..
Below is the code of HTML :
Option :
<input type="radio" name="adOption" id="adOption" value="Ads" data-rule-required="true"/> Ads

<input type="radio" name="adOption" id="adOption" value="Page Content" data-rule-required="true" checked/> Page Content

Textarea :
<textarea name="pgContent" id="pgContent" class="ckeditor" data-rule-required="true" style="width: 100%;"></textarea>

TextBox :
  <input type="text" name="adUrl" id="adUrl" class="input-xxlarge" data-rule-required="true" />

Javascript :
$(document).ready(function(){
                    $('input[type="radio"]').click(function(){
                        if($(this).attr("value")=="Ads"){
                            document.getElementById("adURL").style.display="block"
                            document.getElementById("pgCon").style.display="none"
                        }
                        if($(this).attr("value")=="Page Content"){
                            document.getElementById("adURL").style.display="none"
                            document.getElementById("pgCon").style.display="block"
                        }
                    });
                });

What the issue, i m not getting. please help me for this..
Thanks in advance..

A: See the first paragraph of my answer to find out how CKEditor actually works and how it deals with <textarea> to which it is attached.
<textarea> remains hidden as long as editor instance exists. You should manipulate editor UI instead. Use:
CKEDITOR.instances[ 'instanceName' ].container.hide(); // also container.show()

or
CKEDITOR.instances[ 'instanceName' ].container.$.style.display = '...';

to control visibility of the editor. Also see element.setStyle method in CKEditor API.


text:
Q: zipAlignDebug input file does not exist Error Ever since I updated to gradle alpha 6, I've been getting this error and can't build:
Error:A problem was found with the configuration of task ':app:zipalignDebug'.
> File 'C:\User\...\app\build\outputs\apk\app-debug-unaligned.apk' specified for property 'inputFile' does not exist.

I've tried all the suggestions and nothing is fixing this. Any tips? It was working on alpha 2, but now it gives me an error saying my version is too old and I need to move to a newer one. Thanks!
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0-alpha6'

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

allprojects {
    repositories {
        jcenter()
    }
}

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

.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.nwoodthorpe.waterloohacks"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
}

A: Try to run build every time before Run 'app'.


text:
Q: If $M \otimes M \simeq M$ is there anything we can say about $M$? Over a commutative (and unital) ring, if $M \otimes M \simeq M$ can we say anything about $M$?
If we base change to a point, ie tensor with a map from the ring into a field, then $M$ becomes a vector space and we know that it must be one-dimensional.
Is there anything else we can say? I'd like to work as generally as possible, and I'm willing to assume that $M$ is of finite presentation.


text:
Q: Script para abrir index.html de múltiplas pastas Como fazer um script em bash que:

*

*Com base nessa url de exemplo: http://www.exemple.com.br/1/43530/12620/index.html

*Selecione a pasta 12620.

*Abra o index.html dessa pasta em uma aba do Firefox no Kali (Debian)

*Selecione a pasta 12620 acrescente +1, ficando 12621, e abra o index.html dessa pasta em uma nova aba.

*E assim por diante.

Pensei em algo como:
FOLDER=12620
for (($FOLDER, $FOLDER =< 12660, $FOLDER++))
  do
    firefox -new-tab http://www.exemple.com/1/43530/.'$FOLDER'./index.html
  done

Eu fiz em JavaScript, só queria passar para Bash e abrir no Firefox

<!DOCTYPE html>
<html>
<body>

<button onclick="abrirHTML()">Abrir</button>

<script>
function abrirHTML() {
var folder = 12690;

for (folder = 12690; folder < 12695; folder++) {
    window.open("http://www.exemple.com/1/43530/" + folder + "/index.html");
}
}
</script>

</body>
</html>

A: Um exemplo simples de loop com bash seria assim:
 #!/bin/bash
 COUNTER=12690
 while [  $COUNTER -lt 12695 ]; do
     firefox -new-tab "http://www.exemple.com/1/43530/${COUNTER}/index.html"
     let COUNTER=COUNTER+1
 done

Fonte e dicas: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html

A: Sei que a questão não envolve exatamente Python, mas desde que Python está presente em quase todos os linux, por que não fazer o script nessa linguagem? Bom, aqui está a versão em Python, mas vou postar depois em Bash:
import os, sys
import webbrowser
import urllib2 as net
from urllib2 import HTTPError

FOLDER   = 12620
BASE_URL = 'http://localhost/folders'
BASENAME = 'index.html'

while True:
    try:
        url = "{}/{}/{}".format(BASE_URL, FOLDER, BASENAME)
        net.urlopen(url)
        webbrowser.open(url)
    except HTTPError:
        break
    FOLDER += 1

sys.exit()


text:
Q: Modify stream in c# I have a simple http server where people upload files and I just compress them and save them to disk. This is what I am doing I think people will understand better with code
/// <summary>
/// Client uploads files through here
/// </summary>
private static void Server_ProcessRequest(HttpListenerContext context)
{
    // I know that context.Request.InputStream starts like: ------WebKitFormBoundaryePkpFF7tjBAqx29L
    // and it also ends with that boundary

    // 1. I read from context.Request.InputStream and skip the headers
    // (I read until I find 4 new lines)

    // 2. I then write the file to disk
    // var sizeOfFile = context.Request.ContentLength64;
    // etc... read from stream

    // 3. create a new stream in order to compress file later
    var newStream = System.IO.File.Open("FileJustCreated");

    // 4. MySealedLibraryThatICannotModify.CompressFile(newStream,"CompressedFileLocation.zip");
}

So my question in here is how can I avoid writing the file to disk? I cannot pass context.Request.InputStream to the method that compresses the file because it contains header and other stuff that is not part of the file. It will be great if I could create a method that will return a new stream. The files might be large and I do not want to hold everything on memory so I was looking to create a method like the System.IO.File.OpenRead where it returns a stream where only the part that you read is on memory.
I know I can use a different library to compress the files but it will be nice if I stick to this library and also learn something new.

A: You can write into memory instead of a file:
using (var buffer = new MemoryStream())
{
    context.Request.InputStream.CopyTo(buffer, sizeOfFile);
    MySealedLibraryThatICannotModify.CompressFile(buffer, path);
}


text:
Q: Led Matrix multiplexing: sinking/sourcing current + LED brightness I am trying to make an 8x8 LED matrix (actually a bigger one, but for now it would be easier to discuss this more simplified version) and I have gotten too confused about a few things concerning the current I need to source or sink as well as the brightness of the LEDs.
For multiplexing I am using two 74HC595 parallel out shift registers each connected to the 8 rows (anodes) and 8 columns (cathodes) respectively. In the case where I have a walking bit (0) for the cathodes, meaning I ground each column at a time and give HIGH to the rows I need to light in that column, I need to sink the current for up to 8 LEDs in one pin. Since the 74HC595 can source/sink up to 25mA per pin and up to 70mA in total, it's not possible to sink the current for all 8 LEDs, neither can it source (to the rows) that current to 8 LEDs. For sinking the current I have found an IC, namely the ULN2803 darlington transistor array, which can sink up to 500mA. So that seems to be fine, considering each LED can handle up to ~20mA of "Continuous Forward Current".
Accordingly, for sourcing current to the rows, I could add a circuit to each of the 595's outputs, consisting of an NPN transistor and a shunt regulator (TLV431) as explained in this video.
This circuit can allow me to provide constant current at each row.
On the other hand there is the problem of LED brightness that comes with multiplexing. Since each column would be on just for 1/8 of the time (1/8 duty cycle) that means I would need to provide more current than the 20mA given for Continuous Forward Current to perceive the same brightness, and from what I've understood I would need to give it about 8 times as much (~160mA). In the specs of an LED there is the "Peak Forward Current" which, depending on the LED, could be ~150mA, but a note says "1/10 Duty Cycle, 0.1ms Pulse Width." The microcontroller I am using (Beaglebone Black with Bela cape) gives me a slow frequency of 2756.25Hz (for 8 bits), which means my pulse width would be 0.36ms 3-4 times more than specified, and also my duty cycle would be 1/8 instead of 1/10. That means that I shouldn't provide the peak current specified but something rather less (in order for the LED to be able to dissipate the heat). Even if it would be possible to provide 100mA to each LED, then the column should be able to sink up to 800mA even though the ULN2803 can sink up to 500mA.

*

*How much current do I need to provide each row so that I perceive a good brightness, considering the duty-cycle and pulse width of my application?

*Is the NPN & TLV431 circuit a good choice for supplying constant current or is there a better alternative?

*Do you think the ULN2803 is a good choice for sinking the current of 8 LEDs or would I need something to sink more current?

A: Short Answer First
The short answer to your general question is that you provide active switches on the anode side with active current mirror sinks on the cathode side to limit the current; or else you provide active switches on the cathode side with active current mirror sources on the anode side to limit the current. If all that makes total sense to you, then nothing more needs be said.
Slightly Longer Answer
There's plenty of information available for turning a MOSFET or a BJT into an active switch. You can use either for the purpose. Usually, the choice is determined by a host of factors that include the peak currents involved, availability of parts, features, manufacturer support, part variations that must be managed, cost, and more.
There's plenty of information available about current mirrors, too. And this is what's used inside of fancy ICs used to drive some LED displays. Again, a current mirror can be composed of MOSFETs or BJTs. And again, which you choose to use will depend. But since there are ICs out there, you should actually research the subject. If I were doing this kind of project, I'd probably avoid "going discrete" (unless I wanted to prove something) because a current mirror done on an IC is so much better than one done with discrete parts. That said, there are circumstances where you have no choice but to use discrete parts. So, like everything, there are no bright lines.
You should definitely look through all the IC offerings for driving LEDs. Don't limit yourself to serial-to-parallel shift registers! There are really good ICs available to provide settable current limits for your LED driving needs and that work very well for applications such as yours. If you haven't already done so, take a look and learn about the various ICs that are available to help. They often include the shift register, as well as many other useful features.
The TLV431 video you mentioned works for one LED. (Though, you can also use that approach with discrete BJTs or MOSFETs for a larger number of them, if you know how to mirror currents around with discrete parts.) But it's probably not nearly as good a solution as using ICs (so long as the ICs support the current range you need, of course.) And even for the one-LED approach, I think the TLV431 is over-kill. (I have thousands of various varieties of the TLV431 -- more than I'm likely to use in my remaining lifetime. I love the devices and use them. Just not in this way.)
Your LED
There's not a lot of data in that datasheet you provided. All it says is that if there is a forward current of \$20\:\text{mA}\$ then the voltage across the LED can be as much as about \$2.5\:\text{V}\$ with a more typical value of \$2.0\:\text{V}\$. (There's nothing on the lower limit, but I doubt it can get much lower than \$1.8\:\text{V}\$.) So that's probably my guess about this LED in continuous operation. And this wide voltage range means the parts are pretty much anything that comes out of the FAB and meets some very basic specs are sold without any further binning.
It may also be interesting to read what I wrote here about LED current regulation using a resistor. Given the percent voltage variations possible between LEDs, your desire to seriously over-drive them, and the fact that your IC choices suggest a \$5\:\text{V}\$ power rail voltage, I don't think you should just rely upon a resistor for the current-limiting purpose.
General Approach
In general, the multiplexing approach looks like this:

simulate this circuit – Schematic created using CircuitLab
(The above schematic shows high-side switches with low-side current sinks. It could just as well have been low-side switches with high-side current sources.)
The \$X_i\$ lines are switch-enable lines. No more than one of these should be enabled at a time. These switches must be able to carry the entire sum of the multiplexed, over-driven LED currents in their group, as you may enable zero, one or all of the \$Y_j\$ current-sink lines when a particular \$X\$-switch is turned on.
These \$X\$-switches have to support that maximum current sum and do it without dropping much voltage. There are two primary reasons for this.

*

*Keeping the switch voltage drop as small as possible allows you to use a lower voltage rail magnitude. This means a lower supported wattage for the power supply. Which means cheaper, easier, better, etc.

*Keeping the switch voltage drop as small as possible means less wasted dissipation in the switches (which means smaller heat sinks, less airflow required, cheaper parts, etc.) and in the current sink sections (which again means cheaper, easier, better.)

(The \$Y_i\$ lines are current-sink-enable lines, of course.)
The first thing you need to decide about is just how much current over-drive you can tolerate in the LEDs. Usually, if an LED is intended for multiplexing (or, at least, the manufacturer wants to widen its market for them) then the datasheet will include at least some information with an example case with higher currents that they recommend considering.
Your LED, Revisited
In your LED case, the manufacturer says "SUITABLE FOR LEVEL INDICATOR" and it says in the "ABSOLUTE MAXIMUM RATINGS" (at \$25^\circ\,\text{C}\$) that \$I_\text{F}\le 30\:\text{mA}\$. (That's continuous.)
They do add, in the "ABSOLUTE MAXIMUM RATINGS," that \$I_\text{F}\le 160\:\text{mA}\$. And yes, they do have a footnote about how they achieved that absolute maximum spec. But I don't interpret that to mean that you should actually operate the device anywhere near that absolute maximum spec. It is, after all, listed in the absolute maximum ratings section. Perhaps half that? But I'm guessing. If you want to find out, you should contact the manufacturer (directly, or through representation) and get an answer. You should also ask them if they have any detailed information about the voltage range of the LEDs when operated at higher-than-continuous pulse currents.
Even with an answer from the manufacturer, you should "trust, but verify." This means buying some and sitting down at a bench to run tests. If all you have is a voltmeter/ammeter, you can do all the testing required. In that case, perform short tests, so that you don't put the LED into unsafe operating temperatures. So only keep the LED active long enough to "get a reading" and then immediately shut it down and let it cool down before attempting another test.
You need information. And the datasheet doesn't really provide it for your use.
But don't design for the "absolute maximum rating" of a device. That's not good practice.
At this point, I have to stop any additional thoughts. I can't recommend an approach here as I don't have numbers to work with.
Note:
You mentioned 16 LEDrings / 16 Encoders Control Surface PCB as a similar project to yours. I think this is wonderful. It's very attractive but also useful and designed with human factors in mind. I like that. But did you also notice on that page a comment:

"Since Tk discovered a brightness problem with some rectangular
5x2x7mm LEDs, we found useful to create a list of LEDs wich are
successfully or unsuccessfully tested."

Brightness perception is another complex topic. My experience is that different LEDs, even from the same batch, can have sufficiently different brightness perceptions in a darkened environment (or lightened, too) that they cannot be successfully operated at exactly the same current when you are using them in a single display. LED manufacturers creating 7-segment displays or other devices like that will go to some lengths to pre-bin their LEDs before assembling a single display. And where these displays may be used in combination, they will bin the entire display systems so that their customers can be assured that when they put display 1 next to display 2 in, say, an aircraft instrumentation panel, that the LEDs will all "look the same brightness" when operating. It turns out (or at least for those years I was involved about a decade ago) that FABs just aren't good enough to produce identical LEDs even on the same wafer. Human perception is very, very good and can detect subtle differences.
If you were really serious about producing beautiful LED display systems like this, you have a few options.
You can buy pre-binned LED devices (they exist) where the manufacturer has done all the work for you and all you need to do is supply the same pulse currents in your multiplexed system and all the LEDs will look very much the same and very professional. This is fine if you just build one display system. But suppose you have to build another one in a year's time? Will the manufacturer be able to give you the exact same binned LED then next time you order from them? Maybe. Maybe not. Some manufacturers will be very careful about they binning and provide coded values which mean you really can re-order similar devices. But not all do that for you. Just another thing to consider.
You can also just buy grab-bag LEDs (no pre-binning) and instead plan to write software which carries a "calibration" value that is unique for each LED you will multiplex. You still use the exact same currents in all the LEDs (using ICs that do this easily for you), but now you "adjust" the pulse width differently for each LED.
In this latter case, let's say you have a multiplexing system with those switches and current sinks I mentioned in the general approach above. The current sinks are all set for, let's say, \$80\:\text{mA}\$ (and your switches can handle their maximum load just fine) because you will be using a \$\times 4\$ multiplexing approach (25% for each time-slice.) Let's say you are using a \$1\:\text{kHz}\$ rate, so that each time slice is \$250\:\mu\text{s}\$. This means that, without calibration involved, you'd operate an LED (if on) at \$80\:\text{mA}\$ for \$250\:\mu\text{s}\$, with a dead time of \$750\:\mu\text{s}\$ before coming back to that LED in the multiplexing process.
If you now add an LED calibration feature to this, one way might be to build up the entire system with random LEDs and then identify which one of them was the least bright. That one gets the full on-time of \$250\:\mu\text{s}\$. You'd now go through all of the nearby LEDs and adjust their timing downward from there until they appeared the same brightness. In this way, with unique time periods per LED you'd be able to get them all looking the same.
If you need to make different panels similarly adjusted all look the same, then you'd make the set current limit (which I'd suggested might be \$80\:\text{mA}\$ earlier) to a different value. By providing "set current" adjustability, you allow yourself a way of making all the displays look the same if they are placed into the same, larger system.
As you can see, none of the above can reasonably be done "with resistors."
BUY THIS BOOK
While there are many books out there on this topic, there is one and only one seminal public textbook on the subject matter:
    Optoelectronics/
    Fiber-Optics Applications
    Manual    Second Edition

    Prepared by The Applications Engineering Staff of the
    HEWLETT-PACKARD OPTOELECTRONICS DIVISION

    Stan Gage, Applications Engineering Manager       Hans Sorensen, Applications Engineer
    Dave Evans, Applications Engineer                 Dick Jamison, Applications Engineer
    Mark Hodapp, Applications Engineer                Bob Krause, Applications Engineer

    McGraw-Hill Book Company
    1981 (and 1977 for the first edition)

Your question suggests to me that you are embarking on a trek of which, perhaps out of consideration for our time, you are not fully sharing the details here. Given that, you need extra resources that will help you navigate as you go. And I cannot think of a better book to have on hand. It stands alone in the industry.
This book is comprehensive in scope and detailed down to a fine point, too. If you have a question about LEDs, any question at all, then the odds are very high there will be a section on the subject within this single textbook.
(I have five remaining copies of the book, here at home, though I originally bought closer to 20 of them about 20 years ago. The reason is that I was able to buy them cheaply and I wanted to make sure my customers got a copy, if they didn't already have one. Part of the service I offered, so to speak.)
This book is also old school, which is where your question is coming from. Modern LED display systems use specialized ICs for the purpose -- and I mean custom ICs that are not available on the open market and are designed to a very specific purpose. I worked on these back RGB LED display modules (circa 2002, for Siemens-OSRAM):

That's my signature (j.k.) on the back, there. Inside each module are (6) custom ICs that are simply unobtainium to the outside world: custom designed for this product. These were paneled up into those outside active LED displays you might see alongside a freeway, attracting your attention away from your driving, for example. Each module was rated for about \$80-100\:\text{W}\$ of dissipation and they used three separate voltage rails, one for each color, in order to help minimize the module's dissipation under normal operation.
These devices use switches and current sinks, similar to what I discussed above. The current sinks were settable "per color" and this was treated as a "100%" current for the LEDs. (Red would have one value, green another, and blue yet another.) Within that setting, PWM was used to dim within the multiplexed time slot. So if the full time slot period was \$100\:\mu\text{s}\$ for a particular LED's current sink, for example, then the PWM value also for that LED would be used to change the period for which that current sink was enabled. A 25% PWM value for the LED would mean that the current sink was enabled for only \$25\:\mu\text{s}\$. This doesn't affect the switch time, though. That would still be enabled for the full \$100\:\mu\text{s}\$, because there are other LEDs also being switched; each of which may have differing PWM values. So the switch would remain enabled for a fixed time. But the current sinks would be enabled for varying times, but where a 100% PWM value meant they were enabled for the entire time slot.
In the above units, we even included features such as a "column stagger" which could be set from \$0\:\text{ns}\$ to \$15\:\text{ns}\$. This delayed the turn-on of the column current sources and helped to reduce the generated EMI.
The point I'm trying to make here is that LEDs are not easy to drive. They seem really easy when it's just one; or just a few blinky lights. But the moment you start talking about serious numbers of them? And serious levels of multiplexing? This is when the serious sit-down thinking time happens while you balance various approaches towards your goal and knock out a very detailed, very exact plan of attack.


text:
Q: Login php error What am I doing wrong here? It says Database Count Failed (on the $count line in Process.php) without giving reason. When I take our the "or die" part of that line, it always displays "user account created" no matter which button I pressed and it doesn't actually create an account...
Form.php

<title>Forms</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.css" />

    <form action="process.php" method="post">
        Email:
        <input type="email" name="username" value="" id="username"/>

        Password:
        <input type="password" name="password" value="" id="password"/>

        <input type="submit" name="submit" value="Sign in"/>
        <input type="submit" name="submit" value="Sign up"/>
    </form>

Process.php
<?php
    //1. Create a database connection
    $connection = mysql_connect("localhost","web","1234") or die("Database connection failed: " . mysql_error());

    //2. Select a database to use
    $db_select = mysql_select_db("tongue", $connection) or  die("Database selection failed: " .mysql_error());
?>

<title>Form processing</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.css" />

    <?php
        $username = $_POST['username'];
        $password = trim($_POST['password']);
        $hashed_password = sha1($password);

        $action = $_POST['submit'];

    //3. Select email, password from database
        $query = "
                SELECT email, password FROM user
                WHERE email='$username' AND password='$hashed_password'";
        $user = mysql_query($query, $connection)
            or die ("Database query failed: ".mysql_error());

        $count = mysql_num_rows($user) or die ("Database count failed: ".mysql_error());

    //4. Authenticate user
        if ($count == 1) {
            if($action="Sign up"){
                echo "User already exists";
            } else if ($action="Sign in"){
                echo "User signed in";
            };
        } else if ($count == 0){
            if($action="Sign up"){
            $query = "
                INSERT INTO users (email, password)
                VALUES ('$username', '$hashed_password')";
            $signup = mysql_query($query, $connection);
            echo "User account created";
            } else if ($action ="Sign in"){
                echo "Username and/or password incorrect";
            };
        };

    ?>

A: This line
 $count = mysql_num_rows($user) or die ("Database count failed: ".mysql_error());

Will die when $count == 0, as 0 would be evaluated as false. Aborting on $count==0 is unnecessary as you handle the case where you get no rows back. Plus, you've already checked that the query executed successfully, so this is actually pretty unlikely to fail.
If do you want to check for failure, check the result is actually false, rather than 'falsy'
  $count = mysql_num_rows($user);
  if ($count === false)
  {
      die ("Database count failed: ".mysql_error());
  }

Note the use of === rather than ==, this ensure we check both type and value.

A: I suggest you test the connection first using a simple SELECT * FROM user and printing out the elements. If the connection is OK, then there might be an error in your SQL query. The $user variable is supposed to contain a resource, and mysql_num_rows() will fail otherwise. Use is_resource() to verify that the object returned by mysql_query() is in fact valid.

A: Try running this example:
$a = 0 OR die('foobar');
var_dump($a);

You will see, that the OR die() will be executed any time the value is considered false.
That said .. your code is quite bad.

*

*The script is open to an SQL injection

*You are using mysql_* API, which is more then 10 years old, and should not be used in any newly written code. Instead you should learn to use either PDO or MySQLi.

*It's pointless to select by both username and password, if you already have a unique username column

*This is not how you should hash your password

*Do not create new accounts without telling people beforehand. What if i make a mistake in my email address ?

This is something like how i would do it:
$connection = new PDO( 'mysql:host=hostname;dbname=tongue', 'web', '1234');
$connection->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

$statement = $connection->prepare('
     SELECT
         email,
         hash, -- instead of password, because thats what it is
         salt
     FROM user
     WHERE email = :username
');
$statement->bindParam( ':username', $_POST['username'], PDO::PARAM_STR, 127);
if ( $statement->execute() )
{
    $data = $statement->fetch( PDO::FETCH_OBJ );
}

if ( $data )
{
    $hash = crypt( $_POST['password'], '$2a$07$' . $data->salt . '$' );
    if ( $hash === $data->hash )
    {
        // user OK
    }
    else
    {
        // login failed
    }
}
else
{
    //login failed
}

This is obviously a bit simplified version, because, if you read manual entry for 'crypt()`, you will notice that the resulting hash already contains the original salt. You can extract if from it. But the intention was to make a point, not to add too much detail.
Also the if condition for login could have been wrapped into single if, because, when you do if( $condition_1 && $condition_2 && $condition_3 ), PHP will stop checking at the first failed condition.

A: Here's the final code (thanks a lot @_tereko) :
<?php
        try{
        $username_signup = "Tst@gmail.com";
        $password_signup = "est";
        $hash = crypt($password_signup, '$3a$08$2'); // salt

        $connection = new PDO ('mysql:host=localhost;dbname=tongue', 'web', '1234');
        $connection -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $connection -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        function login ($query, $connect, $user) {
        $statement  =   $connect->prepare($query);
        $statement  ->  bindParam(':username', $user, PDO::PARAM_STR, 127);
        $statement  ->  execute();
        $data = $statement->fetch (PDO::FETCH_OBJ); // fetches the columns defined as $property
        return $data;
        }

        function create ($query, $connect, $user, $pass) {
        $statement  =   $connect->prepare($query);
        $statement  ->  bindParam(':username', $user, PDO::PARAM_STR, 127);
        $statement  ->  bindParam(':password', $pass, PDO::PARAM_STR, 127);
        $statement  ->  execute();
        }

        $sql = 'SELECT email, hash FROM user WHERE email=:username'; // must be defined before calling

        if ($row = login ($sql, $connection, $username_signup)) {
            echo "Account already exists!";
        }
        else {
            $sql = 'INSERT INTO user(email, hash) VALUES (:username, :password)';
            create($sql, $connection, $username_signup, $password_signup);
            echo "account created";
        };

    $connection = null;

    } catch(PDOException $e) {
        echo $e->getMessage();
    }

?>


text:
Q: Compile Error: Comparison arguments must be compatible types Can someone tell me why this error would show up in this canned code I am using from SF's dev site?   Enterprise Release 12 of SF....

*

*Error: Compile Error: Comparison arguments must be compatible types:
Schema.SObjectField, String at line 50 column 42
Lead dup1 = new Lead(LastName='Test1Dup',
                   Company='Test1Dup Inc.',
                   Email='test1@duptest.com');
try {
  insert dup1;
  System.assert(false);
 } catch (DmlException e) {
  System.assert(e.getNumDml() == 1);
  System.assert(e.getDmlIndex(0) == 0);
  System.assert(e.getDmlFields(0).size() == 1);
  System.assert(e.getDmlFields(0)[0] == 'Email');
  System.assert(e.getDmlMessage(0).indexOf(
     'A lead with this email address already exists.') > -1);
}

I am not even clear on the use of System.assert at all, and I've proven to myself that I have next to no clue on what to do to rectify this.  :-(
The error is referencing the "System.assert(false)" line.

A: The line provoking the error is actually
System.assert(e.getDmlFields(0)[0] == 'Email');

The error is complaining that you're comparing a Schema.SObjectField value with a String, which isn't allowed. It looks like getDmlFields() has changed over the releases. I'll raise a doc bug to get that example code fixed. Changing that line to
System.assert(e.getDmlFields(0)[0].getDescribe().getName() == 'Email');

should fix the error.
System.assert(condition) is used in test code to check that a given condition is true. If the condition is false, the test as a whole fails, and the location of the failure is given in the test output log.
Working through the asserts in that example:

*

*System.assert(false); says that you should never get to that line - the insert is expected to throw an exception.

*System.assert(e.getNumDml() == 1); says that the failure concerns a single record

*System.assert(e.getDmlIndex(0) == 0); says that the failure was on the very first inserted record

*System.assert(e.getDmlFields(0).size() == 1); says that the failure was caused by a single field in the offending record

*System.assert(e.getDmlFields(0)[0].getDescribe().getName() == 'Email'); says that offending field is called 'Email'

*System.assert(e.getDmlMessage(0).indexOf(
 'A lead with this email address already exists.') > -1); says that the error message should match the expected value.

Basically, the test method is checking that the trigger executed EXACTLY as intended!
The exception methods, such as getNumDml(), are listed here.


text:
Q: Azure App Service - run crontab/scheduled task besides flask server I have an Azure App Service which runs a flask server. The startup command of the container is
gunicorn --bind=0.0.0.0 --workers=4 app:app

where app.py contains the flask server.
Is it possible to run a recurring task (python script) on the same machine? Any solution (crontab, launching a second python process) would be fine. I googled this but didn't find a way to do it in practice.
Any hints?
Thanks!

A: Yes, you can use Azure Functions (which supports Python) with time trigger (cron format) and deploy it into the same app service you already have.


text:
Q: Differential equation for heat equation
Consider the equation $$\frac{\partial u}{\partial t}=\frac{\partial^2 u}{\partial x^2} + a\frac{\partial u}{\partial x}$$ for a function $u(x,t)$ with initial value $$u(x,0)=f(x).$$ Let $\hat{u}(y,t)$ and $\hat{f}(y)$ denote the Fourier transform in the $x$ variable of $u$ and $f$. For each fixed $y$, find the ordinary differential equation for $\hat{u}(y,t)$ formally (assuming the derivatives all make sense). Then solve the equation for $\hat{u}$ in terms of $\hat{f}$.

Taking the Fourier transform, I get $$\frac{\partial}{\partial t}\hat{u}(y,t)=(iy)^2\hat{u}(y,t)+aiy\hat{u}(y,t)=-y^2\hat{u}(y,t)+aiy\hat{u}(y,t)$$
But how can I solve the equation for $\hat{u}$ in terms of $\hat{f}$?

A: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert #1 \right\vert}%
 \newcommand{\yy}{\Longleftrightarrow}%
 \newcommand{\uu}{\,{\rm u}}$
$\ds{\partiald{\uu}{t} = \partiald[2]{\uu}{x} + a\partiald{\uu}{x}\,,\quad \uu\pars{x,0} = \fermi\pars{x}}$.

$$
\uu\pars{x,t} \equiv \int_{-\infty}^{\infty}
\tilde{\uu}\pars{k}\exp\pars{\ic kx - {t \over \tau_{k}}}\,{\dd k \over 2\pi}
\quad\imp\quad
-\,{1 \over \tau_{k}} = -k^{2} + \ic ka
$$

\begin{align}
&\uu\pars{x,t} \equiv \int_{-\infty}^{\infty}
\tilde{\uu}\pars{k}\expo{\ic kx + \pars{-k^{2} + \ic ka}t}\,{\dd k \over 2\pi}\
\imp\
\uu\pars{x,0} = \fermi\pars{x} = \int_{-\infty}^{\infty}
\tilde{\uu}\pars{k}\expo{\ic kx}\,{\dd k \over 2\pi}\tag{1}
\end{align}

Notice that $\tilde{\uu}\pars{k}$ is the $\fermi\pars{x}$ Fourier transform $\hat{\fermi}\pars{k}$ ( in the OP notation ):
$\hat{\fermi}\pars{k} \equiv \tilde{\uu}\pars{k}$. In terms of it ( $\underline{\mbox{as required by the OP}}$ ) the solution is ( see expressions $\pars{1}$ ):
$$\color{#ff0000}{\large\bf%
\uu\pars{x,t} = \int_{-\infty}^{\infty}
\hat{\fermi}\pars{k}\expo{\ic kx + \pars{-k^{2} + \ic ka}t}\,{\dd k \over 2\pi}}
\tag{2}
$$

\begin{align}
&\tilde{\uu}\pars{k} = \int_{-\infty}^{\infty}\fermi\pars{x}\expo{-\ic k x}\,\dd x
\quad\imp\quad
\uu\pars{x,t} = \int_{-\infty}^{\infty}{\rm K}\pars{x - x',t}\fermi\pars{x'}\,\dd x'
\\[3mm]&
\mbox{where}\quad
{\rm K}\pars{x,t}
\equiv
\int_{-\infty}^{\infty}\expo{\ic kx - \pars{k^{2} - \ic ka}t}\,{\dd k \over 2\pi}
\end{align}
Let's evaluate ${\rm K}\pars{x,t}$:
\begin{align}
{\rm K}\pars{x,t}
&\equiv
\int_{-\infty}^{\infty}\expo{-t\bracks{k^{2} - \ic\pars{x/t + a}k}}\,{\dd k \over 2\pi}
=
\int_{-\infty}^{\infty}
\expo{-t\bracks{k - \ic\pars{x/t + a}/2}^{2} - t\pars{x/t +a}^{2}/4}
\,{\dd k \over 2\pi}
\\[3mm]&=
\expo{-\pars{x + at}^{2}/4t}\int_{-\infty}^{\infty}\expo{-tk^{2}}
\,{\dd k \over 2\pi}
\quad\imp\quad
{\rm K}\pars{x,t} = {\expo{-\pars{x + at}^{2}/4t} \over \root{2\pi}\root{2t}}
\end{align}
$$\color{#0000ff}{\large%
\uu\pars{x,t}
=
\int_{-\infty}^{\infty}\fermi\pars{x'}
{\expo{-\pars{x\ -\ x'\ +\ at}^{2}/4t} \over \root{2\pi}\root{2t}}\,\dd x'}
$$

A: Taking the Fourier transform in $x$ converts the $x$ derivatives to multiplication, so the only derivative left will be with respect to $t$ - hence giving an ODE.


text:
Q: Image hover caption with zoom effect in bootstrap I am unable to align image to the width of caption with maintaining the gutter width. I am using bootstrap and also the image is flowing outside the div on hover. Can anybody help me out ?
This is what i am trying to achive : https://awwapp.com/s/43b68655-83a6-4133-ab28-0ec9a4152316/
Pen : http://codepen.io/anon/pen/XbxOMq
HTML :

          HOTSPOT TEXTf

      HOTSPOT TEXTf

      HOTSPOT TEXTf

CSS:
.hotspot-wrapper {
  position: relative;
  overflow: hidden;
  margin-bottom:20px;
}
.hotspot-text {
  width:100%;
    height: 102px;
    position: absolute;
    bottom: -50px;
  transition: all .2s linear;
  background: rgba(0,0,0,.7);
  color:#fff;
}
.hotspot-wrapper:hover .hotspot-text {
  bottom: 0;
}

.hotspot-wrapper img {

  -webkit-transition: all 0.7s ease;
transition: all 0.7s ease;
}

.hotspot-wrapper:hover img {
  -webkit-transform:scale(1.3);
transform:scale(1.3);
}

A: You should make your CSS for these two classes like this, so the hotspot for the text will be aligned with the image :
.hotspot-text {

    height: 102px;
    position: absolute;
    bottom: -50px;
    right:0px;
    left:0px;
    transition: all .2s linear;
    background: rgba(0,0,0,.7);
    color:#fff;
}
.hotspot-wrapper:hover .hotspot-text {
  bottom: 0;
  left:0;
  right:0;
}

And you should overwrite the padding on the left and on the right set there by default with bootstrap. Like that, the image will have the full width of the div.
.col-lg-4 ,.col-md-4,col-sm-4,col-xs-4{
    padding-left:0px;
    padding-right:0px;
}

Here's a Fiddle