Sunday 8 October 2017

pointers - when allocating memory for an array dynamically (in C), what does the (int *) cast do?




C noob here. When declaring an array during runtime, I've seen two methods for doing so. Can someone please explain the (int *) cast in the second one?



// first way

int numberElements = 5;
int *pointer = malloc(numberElements * sizeof(int));

// second way
...
int *pointer = (int *)malloc(numberElements * sizeof(int));


I just don't see what the (int *) cast is doing. With first the allocation, the array can be filled like this...




// first way cont.
...
for (int i = 0; i < numberElements; i += 1){
pointer[i] = 0;\
}


is this not true for the second? what would you have to do differently?


Answer



The cast does nothing. A void pointer can be assigned to any pointer without an explicit cast.




AND you shouldn't. The C99 (or C90, C11) standard does not require the cast.


Saturday 7 October 2017

html - PHP Undefined Index





This is going to sound really stupid, but I cannot figure out why I am getting this error.



I have created a selection box, named "query_age" in my html form:







In the corresponding php form, I have:




$query_age = $_GET['query_age'];


When I run the page, I get this error:




Notice: Undefined index: query_age in index.php on line 19




I don't understand why this is happening, and I'd love to know how to make it go away.



Answer



I don't see php file, but that could be that -
replace in your php file:



$query_age = $_GET['query_age'];


with:



$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);



Most probably, at first time you running your script without ?query_age=[something] and $_GET has no key like query_age.


Android application is not working

I have been trying to run my client/server android program. But whenever I run the client part on android it gives an error Unfortunately your applicatiopn has stopped running. I have tried reading the logcat but havent been able to fix the problem. below is my code... I have been trying from 3 days. Need help with the project



logcat




12-06 21:05:19.948: D/AndroidRuntime(2136): Shutting down VM
12-06 21:05:19.948: W/dalvikvm(2136): threadid=1: thread exiting with uncaught exception (group=0xa4cf8b20)
12-06 21:05:19.980: E/AndroidRuntime(2136): FATAL EXCEPTION: main
12-06 21:05:19.980: E/AndroidRuntime(2136): Process: com.example.simpleclientapp, PID: 2136
12-06 21:05:19.980: E/AndroidRuntime(2136): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.simpleclientapp/com.example.simpleclientapp.New_main_activity}: android.view.InflateException: Binary XML file line #1: Error inflating class linearlayout
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.app.ActivityThread.access$800(ActivityThread.java:135)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.os.Handler.dispatchMessage(Handler.java:102)

12-06 21:05:19.980: E/AndroidRuntime(2136): at android.os.Looper.loop(Looper.java:136)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.app.ActivityThread.main(ActivityThread.java:5001)
12-06 21:05:19.980: E/AndroidRuntime(2136): at java.lang.reflect.Method.invokeNative(Native Method)
12-06 21:05:19.980: E/AndroidRuntime(2136): at java.lang.reflect.Method.invoke(Method.java:515)
12-06 21:05:19.980: E/AndroidRuntime(2136): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-06 21:05:19.980: E/AndroidRuntime(2136): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-06 21:05:19.980: E/AndroidRuntime(2136): at dalvik.system.NativeStart.main(Native Method)
12-06 21:05:19.980: E/AndroidRuntime(2136): Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class linearlayout
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:707)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.view.LayoutInflater.inflate(LayoutInflater.java:469)

12-06 21:05:19.980: E/AndroidRuntime(2136): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
12-06 21:05:19.980: E/AndroidRuntime(2136): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.app.Activity.setContentView(Activity.java:1929)
12-06 21:05:19.980: E/AndroidRuntime(2136): at com.example.simpleclientapp.New_main_activity.onCreate(New_main_activity.java:33)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.app.Activity.performCreate(Activity.java:5231)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
12-06 21:05:19.980: E/AndroidRuntime(2136): ... 11 more
12-06 21:05:19.980: E/AndroidRuntime(2136): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.linearlayout" on path: DexPathList[[zip file "/data/app/com.example.simpleclientapp-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.simpleclientapp-2, /system/lib]]

12-06 21:05:19.980: E/AndroidRuntime(2136): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
12-06 21:05:19.980: E/AndroidRuntime(2136): at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
12-06 21:05:19.980: E/AndroidRuntime(2136): at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.view.LayoutInflater.createView(LayoutInflater.java:559)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:652)
12-06 21:05:19.980: E/AndroidRuntime(2136): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
12-06 21:05:19.980: E/AndroidRuntime(2136): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
12-06 21:05:19.980: E/AndroidRuntime(2136): ... 20 more`



activity_new_main_activity.xml



   






manifest.xml



            android:minSdkVersion="10"
android:targetSdkVersion="21" />






android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >


android:name=".New_main_activity"
android:label="@string/title_activity_new_main_activity" >












new_main_activity.java



package com.example.simpleclientapp;

import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.lang.*;
import java.lang.annotation.*;
import java.lang.ref.*;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class New_main_activity extends Activity
{
private Socket client;
private FileInputStream fileInputStream;

private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;
private Button button;
private TextView text;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_main_activity);


button = (Button) findViewById(R.id.button1); //reference to the send button
text = (TextView) findViewById(R.id.textView1); //reference to the text view

//Button press event listener
button.setOnClickListener(new View.OnClickListener()
{

public void onClick(View v)
{



File file = new File("/mnt/shared/sharedwithemulatot/numbers.txt"); //create file instance

try
{
client = new Socket("127.0.0.1", 6443);

byte[] mybytearray = new byte[(int) file.length()]; //create a byte array to file


fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);

bufferedInputStream.read(mybytearray, 0, mybytearray.length); //read the file

outputStream = client.getOutputStream();

outputStream.write(mybytearray, 0, mybytearray.length); //write file to the output stream byte by byte
outputStream.flush();
bufferedInputStream.close();

outputStream.close();
client.close();

text.setText("File Sent");


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

}


}
});

}
}

wordpress - PHP output buffering: When/whether to use for different kinds of real existing sites and applications?

Working mainly in WordPress contexts, I have mostly done without output buffering in my PHP code, but I have recently begun to experiment with it and try to discern simply as a user whether there was any noticeable performance impact in typical (for me) scenarios. Can't say I've achieved anything definitive there, but I don't know that my experiments really apply to scaled-up situations.



My general impression is that, unless I have a very good reason for using it - probably involving the kind of script in which I'm not generally interested at this time - I should avoid it. Yet I'll read suggestions that I could use buffering in one or another normal context (e.g., a shortcode that renders a large block of HTML), and I often see it being used in code by people whose work I admire and try to emulate. I've seen the familiar ob_start() etc. sequences applied for rendering even very minimal output that is not further adjusted: a menu or other short list, for example.



I have also seen people assert that there is simply no need for output buffering in well-written code, except in peculiar situations. See StackOverflow Q&A's here Why use output buffering in PHP?, to give one example. Others will say it's useful ONLY when some manipulation of the output is necessary - like a preg_replace of content - but you don't need an output buffer to do that kind of thing (any ol' variable will do).



In most real world instances of the sort I encounter, some version of page caching will also be in use, and sometimes several different plug-ins each with its own caching. Considering how many functions will themselves employ numerous nested/secondary HTML-producing functions, you could easily produce thousands of little nested buffered blocks per page: Suppose a foreach loop produces n number of blog-comments within a larger page: Each blog-comment is rendered by a function, and could be buffered separately. The each-comment function could be called within the foreach loop of the function that outputs the comment thread, and its output could also be buffered. Then the function that outputs the post that includes the comment thread could be output-buffered before being rendered. The entire page, including sundry independently output-buffered templates, plug-ins, widgets, menus, etc., etc., could also be output-buffered.




At what point would any of it be useful or, alternatively, completely counterproductive?



If the answer involves any element of "well, you wouldn't notice in your blog, but you'd need it for BuzzFeed or the New York Times," or the reverse, how would I estimate when the point has been reached?



At this point, I'm leaning toward writing the code as cleanly as possible, and letting (what I understand to be) built-in PHP, browser, server, etc., buffering and explicit caching functions do the work of making the page or its elements load efficiently and quickly, which is the real objective, no?

java - How to fix 'android.os.NetworkOnMainThreadException'?



I got an error while running my Android project for RssReader.



Code:



URL url = new URL(urlToRssFeed);

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();



And it shows the below error:



android.os.NetworkOnMainThreadException


How can I fix this issue?


Answer



This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:



class RetrieveFeedTask extends AsyncTask {


private Exception exception;

protected RSSFeed doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();

xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);

return theRSSHandler.getFeed();
} catch (Exception e) {
this.exception = e;

return null;
} finally {

is.close();
}
}

protected void onPostExecute(RSSFeed feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}



How to execute the task:



In MainActivity.java file you can add this line within your oncreate() method



new RetrieveFeedTask().execute(urlToRssFeed);


Don't forget to add this to AndroidManifest.xml file:






go - Golang: Type aliasing Structures That Meet a Interface Requirement



See code below:



I have an odd behavior that I can't understand in Golang. If I want to create a type alias of a structure and that structure meets the requirements of a interface type, then the type alias won't meet the requirements of that interface type. I have no idea why this is happening. Any thoughts?



package main

import (
"fmt"

)

type MyInt struct {
value int
}

func (m MyInt) DoubleIt() int {
return m.value * 2
}


type MyInter interface {
DoubleIt() int
}

type MyIntContainer struct {
d MyInter
}

type MC MyIntContainer
type MI MyInt


func main() {
e1 := MyIntContainer{MyInt{12}} //This is OK
fmt.Printf("%d\n", e1.d.DoubleIt())
e2 := MC{MI{12}} //this fails with error - line 29
fmt.Printf("%d\n", e2.d.DoubleIt())
}


The error message:

Line 29: cannot use MI literal (type MI) as type MyInter in field value:
MI does not implement MyInter (missing DoubleIt method)


Answer



In your code MI is a new type which doesn't carry over the methods from the original type. The DoubleIt method really isn't available:



e2 := MI{12}
fmt.Printf("%d\n", e2.DoubleIt())




e2.DoubleIt undefined (type MI has no field or method DoubleIt)



An alternative if you want to carry over the methods would be to embed MyInt:



type MI struct {
MyInt
}



Then you can say:



e2 := MI{MyInt{12}}
fmt.Printf("%d\n", e2.DoubleIt())





From the spec:





A type may have a method set associated with it. The method set of any
other type T consists of all methods declared with receiver type T. Further rules apply to structs containing anonymous fields, as
described in the section on struct types. Any other type has an empty
method set
.



Adding event listeners to dynamically added elements using jQuery





So right now, I understand that in order to attach an event listener to a dynamically added element, you have to redefine the listener after adding the element.



Is there any way to bypass this, so you don't have to execute a whole extra block of code?


Answer



Using .on() you can define your function once, and it will execute for any dynamically added elements.



for example



$('#staticDiv').on('click', 'yourSelector', function() {
//do something

});

php - Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead




Im developed PHP user login and registration system, i have a displayed always this error in my local host , how to fix it?





Deprecated: mysql_connect(): The mysql extension is deprecated and
will be removed in the future: use mysqli or PDO instead
(C:\wamp\www\registerations\db.php on line 9)




this is my code
db.php




$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('register');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
?>


Answer



  $con = mysqli_connect("localhost","root","","register");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

?>


// try this..


dom - HTML code for bold arrow symbol

I searched internet the maximum I can. But couldn't find the HTML code for the symbol attached below:




enter image description here



I need to use this in a anchor tag.

html - PHP error Parse error: syntax error, unexpected '




i am sorta new to PHP, i mostly use HTML. I have made a PHP script. What the code should do is display a youtube video when i put the code. like this
"website.com/youtube.php?v=1010111" It would display the youtube video but
I keep on getting the error :




Parse error: syntax error, unexpected '<' in [location]/index.php on
line 7





Here is the code:



if( $_GET["v"])
{
$matches = $_GET['v'];
echo "Welcome ". $_GET['v']. "
";







exit();
}
?>




Name:





Answer



You have to write ?> when you want to stop writing PHP code.



At line 7, ou have , just write ?> before that html tag.



dig - Feed Content of a File to a Bash Script





I'm trying to construct a script that will run a command using the contents of two files, and append the results of that command to another file.



My two files:





  1. nameservers - contains the addresses of my DNS.

  2. hostnames - contains hostnames that needs to be resolved against the nameservers.



I need to pass the contents of nameservers and hostnames to this command:



dig @[content of nameservers file] -t a [content of hostnames]


Then each run it will extract the query time value and append it into a file in the following format:




[nameserver1] [query time value]


Like:



1.1.1.1 100
2.2.2.2 120
3.3.3.3 115


Answer



here is a way:



#!/bin/bash
hostnames=`cat hostnamesfile`
cat nameserversfile | while read n; do
echo "$hostnames" | while read h; do
echo -n "$n "
dig @$n -t a $h | grep 'Query time' | grep -o '[0-9]\+'
done

done > resultsfile

regex - Javascript regexp: replace this or that word (have or not whitespaces between words)



I have a string which contains multiple words. I have a phrase that should be replaced. However, there are multiple very similar phrases that should be replaced.




Here are strings that should be replaced (removed):




  • "fox jumps over the lazy dog"

  • "fox jumps over the lazy cat"

  • "fox jumpa over the lazy cat"

  • "fox jumpaoverthe lazy cat" (meaning there could be missing spaces between words)

  • case insensitive, global



    var str = "The quick brown fox jumpa over the lazy dog";

    // result would be "The quick brown "



    str = "The quick brown fox jump over the lazy dog";
    // result would be "The quick brown "



    str = "The quick brown fox jump over the lazy cat";
    // result would be "The quick brown "



    str = "The quick brown fox jumpa over the lazy cat";
    // result would be "The quick brown "




    str = "The quickbrownfoxjumpaoverthe lazy cat";
    // result would be "The quick brown "




My try doesn't work:





    let str1 = "The quick brown fox jumpa overthe lazy cat";

let reg = /The\s*quick\s*brown\s*fox\s*jump[s|a]\s*over\s*the\s*lazy [\bcat\b|\bdog\b]/gi;
let res = str1.replace(reg, "");
console.log(res); //should be empty

str1 = "The quickbrownfox jumps overthe lazy cat";
res = str1.replace(reg, "");
console.log(res); //should be empty





Answer



You can use the following regex : The\s*quick\s*brown\s*fox\s*jump(s|a)?\s*over\s*the\s*lazy\s*(cat|dog)/gi





let str1 = "The quick brown fox jumpa overthe lazy cat";
let reg = /The\s*quick\s*brown\s*fox\s*jump(s|a)?\s*over\s*the\s*lazy\s*(cat|dog)/gi;
let res = str1.replace(reg, "");
console.log(res); //should be empty


str1 = "The quickbrownfox jumps overthe lazy cat";
res = str1.replace(reg, "");
console.log(res); //should be empty




Friday 6 October 2017

Windows MySQL case sensitive

I have a problem. I'm using Windows at work to develop but the server is Linux. I often work with database queries.



Now, I often type the table name in wrong caps (like, in lowercase if first 3 characters are uppercase). How can I turn case sensitivity on Windows on?



I currently have tried putting



lower_case_table_names=1


After




interactive-timeout


And I've also tried putting



lower_case_table_names=0


After




interactive-timeout


None of them work though and my script still works fine on Windows where it would bug in Linux.

How to map and remove nil values in Ruby



I have a map which either changes a value or sets it to nil. I then want to remove the nil entries from the list. The list doesn't need to be kept.



This is what I currently have:



# A simple example function, which returns a value or nil

def transform(n)
rand > 0.5 ? n * 10 : nil }
end

items.map! { |x| transform(x) } # [1, 2, 3, 4, 5] => [10, nil, 30, 40, nil]
items.reject! { |x| x.nil? } # [10, nil, 30, 40, nil] => [10, 30, 40]


I'm aware I could just do a loop and conditionally collect in another array like this:




new_items = []
items.each do |x|
x = transform(x)
new_items.append(x) unless x.nil?
end
items = new_items


But it doesn't seem that idiomatic. Is there a nice way to map a function over a list, removing/excluding the nils as you go?


Answer




You could use compact:



[1, nil, 3, nil, nil].compact
=> [1, 3]





I'd like to remind people that if you're getting an array containing nils as the output of a map block, and that block tries to conditionally return values, then you've got code smell and need to rethink your logic.




For instance, if you're doing something that does this:



[1,2,3].map{ |i|
if i % 2 == 0
i
end
}
# => [nil, 2, nil]



Then don't. Instead, prior to the map, reject the stuff you don't want or select what you do want:



[1,2,3].select{ |i| i % 2 == 0 }.map{ |i|
i
}
# => [2]


I consider using compact to clean up a mess as a last-ditch effort to get rid of things we didn't handle correctly, usually because we didn't know what was coming at us. We should always know what sort of data is being thrown around in our program; Unexpected/unknown data is bad. Anytime I see nils in an array I'm working on, I dig into why they exist, and see if I can improve the code generating the array, rather than allow Ruby to waste time and memory generating nils then sifting through the array to remove them later.




'Just my $%0.2f.' % [2.to_f/100]

c++ - Double free or corruption when using destructor

In the following code when I add the the line which is specified with an arrow gives error:




Error in `./a.out': double free or corruption (fasttop):
0x00000000007a7030 * Aborted (core dumped)




The code works if I do not use destructor. Any idea?




#include
#include

struct Element
{
int *vtx;

~Element ()
{
delete [] vtx;

}
};

int main ()
{
Element *elm = new Element [2];
elm[0].vtx = new int [2]; // <----- adding this gives error

std::vector vec;
vec.push_back (elm[0]);

vec.push_back (elm[0]);

return 0;
}

python - Get artist from spotify api using ClientID

I was using spotify api to get info about a artist with the code below:



spotify_artist = requests.get('https://api.spotify.com/v1/search?q=U2"&type=artist").json()
print(spotify_artist['artists']['items'][0]['genres'])



But I get:



{
"error": {
"status": 401,
"message": "No token provided"
}
}



So I get a spotify clientID but when I use it its not working:



https://api.spotify.com/v1/search?q=U2%22&type=artist&ClientID=key


(key is the ClientID of the spotify)



But I get the same error:



{

"error": {
"status": 401,
"message": "No token provided"
}
}


Do you know why?



I generate a key (cliente id) for the example you can see that dont works properly:




https://api.spotify.com/v1/search?q=U2&type=artist&client_id=38a48a7baeae43b8a74a52fc25a85cd0

What is the Python 3 equivalent of "python -m SimpleHTTPServer"



What is the Python 3 equivalent of python -m SimpleHTTPServer?


Answer



From the docs:




The SimpleHTTPServer module has been merged into http.server in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.





So, your command is python -m http.server, or depending on your installation, it can be:



python3 -m http.server

How can I remove an array element by index,using javaScript?

fruits=["mango","apple","pine","berry"];



If I want to remove an element index wise.How to do that using javaScript.Also you can use library as required.

java - Why no static methods in Interfaces, but static fields and inner classes OK? [pre-Java8]





There have been a few questions asked here about why you can't define static methods within interfaces, but none of them address a basic inconsistency: why can you define static fields and static inner types within an interface, but not static methods?



Static inner types perhaps aren't a fair comparison, since that's just syntactic sugar that generates a new class, but why fields but not methods?



An argument against static methods within interfaces is that it breaks the virtual table resolution strategy used by the JVM, but shouldn't that apply equally to static fields, i.e. the compiler can just inline it?




Consistency is what I desire, and Java should have either supported no statics of any form within an interface, or it should be consistent and allow them.


Answer



An official proposal has been made to allow static methods in interfaces in Java 7. This proposal is being made under Project Coin.



My personal opinion is that it's a great idea. There is no technical difficulty in implementation, and it's a very logical, reasonable thing to do. There are several proposals in Project Coin that I hope will never become part of the Java language, but this is one that could clean up a lot of APIs. For example, the Collections class has static methods for manipulating any List implementation; those could be included in the List interface.






Update: In the Java Posse Podcast #234, Joe D'arcy mentioned the proposal briefly, saying that it was "complex" and probably would not make it in under Project Coin.







Update: While they didn't make it into Project Coin for Java 7, Java 8 does support static functions in interfaces.


javascript - Can't get JS to run

I found a slider menu on CodePen I liked but no matter what I do I can't get the JS to run. I actually tried multiple sources of code and none worked properly.





AOS Slide

















CSS:



html {
height: 100%;
}

body {
height: 100%;

margin: 0;
padding: .1px;
position: relative;
background: url(http://www.adventuresofscatman.com/wp-content/uploads/2015/09/IMG_4273.jpg);
background-size: cover;
overflow-x: hidden;
}

.button{
position: absolute;

top: 30px;
left: 25px;;
width: 55px;
height: 50px;
}

.button div {
height: 20%;
border-top: 7px solid rgb(103, 103, 103);
cursor: pointer;

transition: .5s;
}

.button:hover div {
border-color: rgb(139, 139, 139);
}

.menu-in,
.menu-out {
padding: .1px;

width: 240px;
height: 100%;
background: rgba(0, 0, 0, .65);
overflow: hidden;
position: absolute;
top: 0;
}

.menu-in {
-webkit-animation: menu-in .9s forwards ease;

}

.menu-out{
-webkit-animation: menu-out .4s forwards ease-in;
}

ul {
margin: 68px 0 0 0;
padding: 0;
}


.menu-item {
list-style: none;
}

.link {
display: block;
text-decoration: none;
color: rgb(190, 190, 190);
font: 28px/50px arial;

text-transform: uppercase;
height: 50px;
text-align: center;
transition: .1s;
}

.link:hover {
color: rgb(230, 230, 230);
background: rgba(200, 200, 200, .1);
}


.shadow-in,
.shadow-out{
width: 100%;
height: 100%;
position: absolute;
top: 0;
background: rgba(0, 0, 0, .4);
}


.shadow-in {
-webkit-animation: shadow-in .9s forwards ease;
}

.shadow-out {
-webkit-animation: shadow-out .4s forwards ease-in;
}

.none {
display: none;

}

@-webkit-keyframes menu-in {
0% {
left: -240px;
}
100% {
left: 0;
}
}


@-webkit-keyframes menu-out {
0% {
left: 0;
}
100% {
left: -240px;
}
}


@-webkit-keyframes shadow-in {
0% {
left: 0;
opacity: 0;
}
100% {
left: 240px;
opacity: 1;
}
}


@-webkit-keyframes shadow-out {
0% {
left: 240px;
opacity: 1;
}
99%{
height: 100%;
}
100% {

height: 0;
left: 0;
opacity: 0;
}
}


JS:



document.getElementById('button').addEventListener('click', function() {

showMenu();
});

document.getElementById('menu').addEventListener('click', function() {
showMenu();
});

function showMenu() {
console.log('click');
var menu = document.getElementById('menu');

var shadow = document.getElementById('shadow');
var button = document.getElementById('button');

menu.className = 'menu-in';
shadow.className = 'shadow-in';
button.className = 'none';
}

document.getElementById('shadow').addEventListener('click', function() {
var menu = document.getElementById('menu');

var shadow = document.getElementById('shadow');
var button = document.getElementById('button');

menu.className = 'menu-out';
shadow.className = 'shadow-out';
button.className = 'button';
});

Printing the time between 2 points in a program in Python

I would like to know a way to time between two points in a program. In my situation I will ask the user 10 questions and after display the time it took for them to answer the question (example code below). How would i do this through something like import time ?


Example code:


timer.start
question1 = input("What is your favorite game ?")
timer.end
print(timer.time)

^
The timer.x thing is going to be replaced with your suggestions.

javascript - What's the difference between using "let" and "var"?



ECMAScript 6 introduced the let statement.




I've heard it that it's described as a "local" variable, but I'm still not quite sure how it behaves differently than the var keyword.



What are the differences? When should let be used over var?


Answer





Main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).



function run() {
var foo = "Foo";

let bar = "Bar";

console.log(foo, bar);

{
let baz = "Bazz";
console.log(baz);
}

console.log(baz); // ReferenceError

}

run();


The reason why let keyword was introduced to the language was function scope is confusing and was one of the main sources of bugs in JavaScript.



Take a look at this example from another stackoverflow question:



var funcs = [];

// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see

funcs[j]();
}


My value: 3 was output to console each time funcs[j](); was invoked since anonymous functions were bound to the same variable.



People had to create immediately invoked functions to capture correct value from the loops but that was also hairy.






While variables declared with var keyword are "hoisted" to the top of the block which means they are accessible in their enclosing scope even before they are declared:



function run() {
console.log(foo); // undefined
var foo = "Foo";
console.log(foo); // Foo
}

run();



let variables are not initialized until their definition is evaluated. Accessing them before the initialization results in a ReferenceError. Variable said to be in "temporal dead zone" from the start of the block until the initialization is processed.



function checkHoisting() {
console.log(foo); // ReferenceError
let foo = "Foo";
console.log(foo); // Foo
}

checkHoisting();





At the top level, let, unlike var, does not create a property on the global object:



var foo = "Foo";  // globally scoped
let bar = "Bar"; // globally scoped

console.log(window.foo); // Foo

console.log(window.bar); // undefined




In strict mode, var will let you re-declare the same variable in the same scope while let raises a SyntaxError.



'use strict';
var foo = "foo1";
var foo = "foo2"; // No problem, 'foo' is replaced.


let bar = "bar1";
let bar = "bar2"; // SyntaxError: Identifier 'bar' has already been declared

r - Add new variable (column) in the fly to a reactive dataframe in Shiny

I am trying to add in a reactive dataframe the outpust of both a non-linear regression model and a multivariate analysis. I managed to create the reactive dataframe which is updated anytime I filter my data. I now want to update the model outputs whenever I filter the dataframe and add the prediction values of the model to the reactive dataframe. Below is a subset of the dataset I am using as well as the ui and server files I use to create the shiny App.



Load package



library (shiny)

library(ggvis)
library(dplyr)
library(rbokeh)
library (minpack.lm)
library (hydroGOF)
library(caret)


The dataframe I use:




 Flux_Data_df<- structure(list(Site_ID = structure(c(1L, 3L, 5L, 7L, 8L), .Label = c("AR-Slu", 
"AR-Vir", "AU-Tum", "AU-Wac", "BE-Bra", "BE-Jal", "BE-Vie", "BR-Cax",
"BR-Ma2", "BR-Sa1", "BR-Sa3", "BW-Ma1", "CA-Ca1", "CA-Ca2", "CA-Ca3",
"CA-Gro", "Ca-Man", "CA-NS1", "CA-NS2", "CA-NS3", "CA-NS4", "CA-NS5",
"CA-NS6", "CA-NS7", "CA-Oas", "CA-Obs", "CA-Ojp", "CA-Qcu", "CA-Qfo",
"CA-SF1", "CA-SF2", "CA-SF3", "CA-SJ1", "CA-SJ2", "CA-SJ3", "CA-TP1",
"CA-TP2", "CA-TP3", "CA-TP4", "CA-Wp1", "CN-Bed", "CN-Cha", "CN-Din",
"CN-Ku1", "CN-Qia", "CZ-Bk1", "De-Bay", "DE-Hai", "DE-Har", "DE-Lkb",
"DE-Meh", "DE-Obe", "DE-Tha", "DE-Wet", "DK-Sor", "ES-Es1", "FI-Hyy",
"FI-Sod", "FR-Fon", "FR-Hes", "FR-Lbr", "FR-Pue", "GF-Guy", "ID-Pag",

"IL-Yat", "IS-Gun", "IT-Col", "IT-Cpz", "IT-Lav", "IT-Lma", "IT-Noe",
"IT-Non", "IT-Pt1", "IT-Ro1", "IT-Ro2", "IT-Sro", "JP-Tak", "JP-Tef",
"JP-Tom", "MY-Pso", "NL-Loo", "PA-Spn", "PT-Esp", "RU-Fyo", "RU-Skp",
"RU-Zot", "SE-Abi", "SE-Fla", "SE-Nor", "SE-Sk1", "SE-Sk2", "SE-St1",
"UK-Gri", "UK-Ham", "US-Bar", "US-Blo", "US-Bn1", "US-Bn2", "Us-Bn3",
"US-Dk2", "US-Dk3", "US-Fmf", "US-Fuf", "US-Fwf", "US-Ha1", "US-Ha2",
"US-Ho1", "US-Ho2", "US-Lph", "US-Me1", "US-Me3", "US-Me4", "US-Me6",
"US-Moz", "US-NC1", "US-Nc2", "US-NR1", "US-Oho", "US-So2", "US-So3",
"US-Sp1", "US-Sp2", "US-Sp3", "US-Syv", "US-Umb", "US-Wbw", "US-Wcr",
"US-Wi0", "US-Wi1", "US-Wi2", "US-Wi4", "US-Wi8", "VU-Coc", "CA-Cbo",

"CN-Lao", "ID-Buk", "JP-Fuj", "RU-Ab", "RU-Be", "RU-Mix"), class = "factor"),
Ecosystem = structure(c(5L, 3L, 5L, 5L, 3L), .Label = c("DBF",
"DNF", "EBF", "ENF", "MF", "SHB", "WSA"), class = "factor"),
Climate = structure(c(3L, 3L, 3L, 3L, 4L), .Label = c("Arid",
"Continental", "Temperate", "Tropical"), class = "factor"),
Management = structure(c(4L, 2L, 3L, 4L, 4L), .Label = c("High",
"Low", "Moderate", "None"), class = "factor"), Stand_Age = c(50,
99, 77.0833333333333, 66.2, 97), NEP = c(1262.24986565392,
251.665998718498, 89.590110051402, 467.821910494384, 560),
GPP = c(2437.9937774539, 1837.82835206203, 1353.91140903122,

1740.68843840394, 3630), NEP_GPP = c(0.517741217113419, 0.143353622997247,
0.0760076059028116, 0.270737440100469, 0.1542699725), Uncert = c(7.29706486170583,
12.3483066698996, 7.59406340226036, 8.2523670901841, 12.1
), Gap_filled = c(0.953310527540233, 0.969648973753497, 0.9395474605477,
0.923408280276339, 1), MAT = c(19.0438821722383, 9.67003296799878,
10.7728316162948, 8.2796213684244, 27.341666667), MAT_An = c(-0.0413522012578611,
0.840055031446541, 0.705896226415094, 0.805524109014675,
0.191666666666667), MAT_Trend = c(0.0119577487502016, 0.0196238509917756,
0.0305871364833632, 0.0381007095629741, 0.0194619147449338
), MAP = c(351.700001291931, 1107.49999958277, 844.158499979666,

998.205467054248, 2279.5), MAP_CRU = c(592.2, 850.925, 852.591666666667,
1098.98, 2279.5), SPI_CRU_Mean = c(-0.352735702252502, 0.188298093749456,
0.0830157542916604, 0.397632136136383, 1.31028809089487),
MAP_An = c(4.14188988095238, -15.8198660714286, 5.39074900793651,
2.28799107142857, 1.55565476190476), MAP_Trend = c(1.38787584993337,
0.147192657259031, 0.747167885331603, 0.104885622031644,
0.841903850753408), CEC_Total_1km = c(14.05, 10.25, 17.975,
21, 9.95), Clay_Silt = c(36.65, 42.125, 32.275, 55, 54.825
), Clay_1km = c(26.425, 31.425, 11.25, 22.45, 38.075), Silt_1km = c(10.225,
10.7, 21.025, 32.55, 16.75), Sand_1km = c(63.35, 57.325,

67.65, 45, 45.275), NOy = c(1.73752826416889, 2.76055219091326,
4.96187381895543, 5.06857284157762, 0.90948457442513), NHx = c(2.50363534311763,
2.99675999696687, 11.2747222582845, 13.9207300067467, 1.53292533883169
), Soil_C_1km = c(3.6, 17, 23.575, 26.65, 8.15), Lat = c(-33.4648,
-35.6566, 51.3092, 50.3051, -1.72000003), Long = c(-66.4598,
148.1516, 4.5206, 5.9981, -51.4500008)), .Names = c("Site_ID",
"Ecosystem", "Climate", "Management", "Stand_Age", "NEP", "GPP",
"NEP_GPP", "Uncert", "Gap_filled", "MAT", "MAT_An", "MAT_Trend",
"MAP", "MAP_CRU", "SPI_CRU_Mean", "MAP_An", "MAP_Trend", "CEC_Total_1km",
"Clay_Silt", "Clay_1km", "Silt_1km", "Sand_1km", "NOy", "NHx",

"Soil_C_1km", "Lat", "Long"), row.names = c(NA, 5L), class = "data.frame")


Choose x and y variable to choose



axis_vars <- c(
"NEP observed [gC.m-2.y-1]" = "NEP",
"NEP predicted [gC.m-2.y-1]" = "prediction",
"CUEe" = "NEP_GPP",
"GPP [gC.m-2.y-1]" = "GPP",

"Forest Age [years]" = "Stand_Age",
"MAT [°C]" = "MAT",
"SPI" = "SPI_CRU_Mean",
"MAP [mm.y-1]" = "MAP",
"MAP trend [mm.y-1]" = "MAP_Trend",
"MAT tremd [°C.y-1]" = "MAT_Trend",
"Clay content [kg.kg-1]" = "Clay_1km",
"N deposition [kg N.ha-1.y-1]" = "NHx"
)



The ui file:



        ui<- actionLink <- function(inputId, ...) {
tags$a(href='javascript:void',
id=inputId,
class='action-button',
...)
}



shinyUI(fluidPage(
titlePanel("Data exploration"),
p('Interactive tool for data exploration'),
em('by, ', a('Simon Besnard', href = 'http://www.bgc-jena.mpg.de/bgi/index.php/People/SimonBesnard')),

fluidRow(
column(4,
wellPanel(
selectInput("xvar", "X-axis variable", axis_vars, selected = "Stand_Age"),

selectInput("yvar", "Y-axis variable", axis_vars, selected = "NEP")
),

wellPanel(
h4("Filter data"),

sliderInput("Gap_filled", "Fraction gap filling", 0, 1, value = c(0, 1)),
sliderInput("Uncert", "Uncertainties", 0, 45, value = c(0, 45),
step = 1),
sliderInput("Stand_Age", "Forest age [years]", 0, 400, value = c(0, 400),

0, 400, 400, step = 5),
sliderInput("GPP", "GPP [gC.m-2.y-1]", 0, 4000, value = c(0, 4000),
0, 4000, 4000, step = 100),
sliderInput("MAT", "MAT [°C]", -10, 30, value = c(-10, 30),
-10, 30, 30, step = 1),
sliderInput("MAP", "MAP [mm.y-1]", 0, 4000, value = c(0, 4000),
0, 4000, 400, step = 100),
checkboxGroupInput("Management", "Intensity of management", c("None", "Low", "Moderate", "High"),
selected= c("None", "Low", "Moderate", "High"), inline = T),
checkboxGroupInput("Climate", "Type of climate",

c("Arid", "Continental", "Temperate", "Tropical"),
selected=c("Arid", "Continental", "Temperate", "Tropical"), inline=T),
checkboxGroupInput("Ecosystem",
label="PFTs",
choices=list("DBF", "DNF", "EBF", "ENF", "MF", "SHB"),
selected=c("DBF", "DNF", "EBF", "ENF", "MF","SHB"), inline=T)
)),

mainPanel(
navlistPanel(

tabPanel("Plot", rbokehOutput("rbokeh")),
tabPanel("Statistics", tableOutput("summaryTable")),
tabPanel("Variable importance", plotOutput("Var_Imp")),
tabPanel("Spatial distribution - Flux tower", rbokehOutput("Map_Site"))
),
downloadLink('downloadData', 'Download'))
))
)



And the server file:



         server<- shinyServer(function(input, output, session) {


# A reactive expression for filtering dataframe
Update_df <- reactive({

# Lables for axes
xvar_name <- names(axis_vars)[axis_vars == input$xvar]

yvar_name <- names(axis_vars)[axis_vars == input$yvar]
xvar <- prop("x", as.symbol(input$xvar))
yvar <- prop("y", as.symbol(input$yvar))

Flux_Data_df %>%
filter(
Gap_filled >= input$Gap_filled[1] &
Gap_filled <= input$Gap_filled[2] &
Uncert > input$Uncert[1] &
Uncert < input$Uncert[2] &

Stand_Age >= input$Stand_Age[1] &
Stand_Age <= input$Stand_Age[2] &
GPP > input$GPP[1] &
GPP < input$GPP[2] &
MAT > input$MAT[1] &
MAT < input$MAT[2] &
MAP > input$MAP[1] &
MAP < input$MAP[2]) %>%
filter(
Management %in% input$Management &

Climate %in% input$Climate &
Ecosystem %in% input$Ecosystem) %>% as.data.frame()
})


# A reactive expression to add model predicion to a new dataframe
Update_df<- reactive({
for(id in unique(Update_df()$Site_ID)){
lm.Age<- try(nlsLM(NEP~offset + A*(1-exp(k*Stand_Age)), data = Update_df()[Update_df()$Site_ID != id,],
start = list(A= 711.5423, k= -0.2987, offset= -444.2672),

lower= c(A = -Inf, k = -Inf, offset= -1500), control = list(maxiter = 500), weights = 1/Uncert), silent=TRUE);
Update_df()$f_Age[Update_df()$Site_ID == id] <- predict(object = lm.Age, newdata = Update_df()[Update_df()$Site_ID == id,])
} %>% as.data.frame()
})


#Plot scatter plot
output$rbokeh <- renderRbokeh({
plot_data<- Update_df()
g<- figure() %>%

ly_points(x = input$xvar, y = input$yvar, data=plot_data, hover= c(Site_ID, year)) %>%
x_axis("x", label = names(axis_vars)[axis_vars == input$xvar]) %>%
y_axis("y", label = names(axis_vars)[axis_vars == input$yvar])
return(g)
})


output$Map_Site <- renderRbokeh({
plot_data<- Update_df()
p<- gmap(lat=0, lng=0, zoom = 2, width = 600, height = 600, map_type ="hybrid") %>%

ly_points(x=Long, y=Lat, data = plot_data, hover= c(Site_ID), col = "red", size=5) %>%
tool_box_select() %>%
tool_lasso_select() %>%
tool_reset()
return(p)
})


output$downloadData <- downloadHandler(
filename = function() {

paste('data-', Sys.Date(), '.csv', sep='')
},
content = function(con) {
write.csv(data, con)
}
)


})


shinyApp(ui, server)


Basically, I would like to add a prediction column to the updated dataframe anytime a filtering action is done in the shiny app based on the filtering set-up in the ui file. Anyone can help me out with it?

javascript - single quotes versus double quotes in js







Are there any differences between single and double quotes in javascript?

email - PHP mail() doesn’t send to some accounts



I’m having problems with mailing. I have this code:




$dni = "123456";
$nombre = "dani";
$email = "abcd@gmail.com";

$header = 'De: ' . $email . " \r\n";
$header .= "X-Mailer: PHP/" . phpversion() . " \r\n";
$header .= "Mime-Version: 1.0 \r\n";
$header .= "Content-Type: text/plain";

$mensaje = "Este mensaje fue enviado por " . $nombre . ", con dni " . $dni . " \r\n";

$mensaje .= "Su e-mail es: " . $email . " \r\n";
$mensaje .= "Mensaje: mensaje de prueba \r\n";
$mensaje .= "Enviado el " . date('d/m/Y', time());

$para = '1234@gmail.com,1234@innova.com,1234@educacion.net';
$asunto = '[Mensaje de Web]';

if (mail($para, $asunto, $mensaje, $header))
echo 'Mensaje enviado correctamente';
else

echo 'Error en el envio';
?>


This script print “Mensaje enviado correctamente” in the screen, and it sends well to Gmail account, and innova.com account, but the mail doesn’t arrive to educacion.net account.


Answer



Some email/domains have blocked PHP form emails, I'm surprised Gmail is working, usually you have to apply to be able to receive PHP forms.



You'll need to add your smtpServer connection and call in this function when you want to be able to send PHP emails to whomever you need.





function authgMail($from, $namefrom, $to, $nameto, $subject, $message) {

$smtpServer = "mail.domain.com"; //ip address of the mail server. This can also be the local domain name
$port = "25"; // should be 25 by default, but needs to be whichever port the mail server will be using for smtp
$timeout = "45"; // typical timeout. try 45 for slow servers
$username = "yourusername"; // the login for your smtp
$password = "yourpassword"; // the password for your smtp
$localhost = "localhost"; // Defined for the web server. Since this is where we are gathering the details for the email

$newLine = "\r\n"; // aka, carrage return line feed. var just for newlines in MS
$secure = 0; // change to 1 if your server is running under SSL

//connect to the host and port
$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 4096);
if(empty($smtpConnect)) {
$output = "Failed to connect: $smtpResponse";
echo $output;
return $output;

}
else {
//$logArray['connection'] = "

Connected to: $smtpResponse";
//echo "

connection accepted
".$smtpResponse."

Continuing

";
}

//you have to say HELO again after TLS is started
fputs($smtpConnect, "HELO $localhost". $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['heloresponse2'] = "$smtpResponse";

//request for auth login
fputs($smtpConnect,"AUTH LOGIN" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authrequest'] = "$smtpResponse";

//send the username
fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authusername'] = "$smtpResponse";


//send the password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authpassword'] = "$smtpResponse";

//email from
fputs($smtpConnect, "MAIL FROM: <$from>" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailfromresponse'] = "$smtpResponse";


//email to
fputs($smtpConnect, "RCPT TO: <$to>" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailtoresponse'] = "$smtpResponse";

//the email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data1response'] = "$smtpResponse";


//construct headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
$headers .= "To: $nameto <$to>" . $newLine;
$headers .= "From: $namefrom <$from>" . $newLine;

//observe the . after the newline, it signals the end of message
fputs($smtpConnect, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data2response'] = "$smtpResponse";


// say goodbye
fputs($smtpConnect,"QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['quitresponse'] = "$smtpResponse";
$logArray['quitcode'] = substr($smtpResponse,0,3);
fclose($smtpConnect);
//a return value of 221 in $retVal["quitcode"] is a success
return($logArray);
}


Thursday 5 October 2017

c - Which is the better way to declare dummy variables for nested loops?




  1. The advantage of approach 1 is a slightly smaller file size due to less text characters in the source code:



    int i, j;
    for (i = 0; i < numRows; i++)

    for (j = 0; j < numCols; j++)
    //

  2. The advantage of approach 2 is the smaller scope of local variables.



    int i;
    for (i = 0; i < numRows; i++)
    {
    int j;
    for (j = 0; j < numCols; j++)

    //
    }



Even if the differences in optimizations are negligible in today's modern computers, which approach is considered "better" code?






Edit to clarify that this question is not a duplicate:




This question is based on the current C11 standard, which does not allow for syntax like this:



for (int i = 0; i < numRows; i++)


In C++ and C99, this syntax is perfectly acceptable whereas C11 does not allow for variable declarations inside the for statement.







Edit to correct misinformation:



I thought I was using C11 because I had recently downloaded the compiler from CodeBlocks, so that's why I said C11 didn't allow for variable declarations inside the for statement. But it turns out I was actually using C90, which was the root of my problems.


Answer



For sheer compactness and limiting of scope, I would use:



for (size_t i = 0; i < numRows; i++) {
for (size_t j = 0; j < numCols; j++) {
//
}

}


Note the use of size_t for what appear to be array indices. The size_t type is an unsigned integer type guaranteed to be able to hold any array index. Just a matter of style, but I would also suggest using braces around all loop bodies. This makes it much less likely that you will break your code with inevitable updates and changes.



By making it a habit to declare loop variables with block scope like this, you force yourself to choose to use the values stored in loop variables elsewhere in your code.


Open Popup window using javascript




I am looking to open one aspx page (test.aspx) in two different popup windows at the same time.



what I have till now second replace first one and page recreate in first.




I think it require more clarification here so,



Basicaly I create a graph and place it in test.aspx,
and save that graph as image file.
I put a button on test.aspx which linked with stimulsoft report and that report show pdf format of that image.
Now if i open with test.aspx it replace the image page. but I want to see both graph and pdf same time.
One solution is I create a new blank aspx page to display report but I try avoid to add new page because it is possible to mount report on test.aspx.



The question is just to open a single POPUP window twice on same time, but may be it is posible or not. and each and every popup containing there own dynamic controls and report like mrt.


Answer




Change the window name in your two different calls:



function popitup(url,windowName) {
newwindow=window.open(url,windowName,'height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}


windowName must be unique when you open a new window with same url otherwise the same window will be refreshed.



date - How to get on python current time?

I need to have the date.
The format of the time should be 2017-01-18T07:34:35Z
I have tried this but it does not work:



import datetime
i = datetime.datetime.now()
date = %i.year "-" %i.month "-" %i.day "T" %i.hour ":" %i.minute ":" %i.second "Z"

multithreading - Simulating context switches in JavaScript?



I've been working on implementing a pretty complex system in JavaScript that needs to simulate, among other things, multithreaded processes. In a real multithreaded process (such as a kernel thread) it's possible to switch between threads by context-switching. This works because you can store the current process's program counter and registers to a temporary structure, restore the program counter and registers for some other process, and then resume where you left off in the previous process.




I'm curious whether it's possible to have something similar to this in JavaScript. I currently know no way of doing this and so have been designing the system using cooperative multitasking. In particular, any "function" that I want to run in the multithreading simulator is split up into an array of functions. To execute the "function", I iterate across the array of functions, executing each in order while maintaining a "program counter" of which function to execute next. This allows me to simulate a context switch by calling one of the functions in the array, waiting for the function to return, then switching to some other array of functions that need to be executed.



My current approach works, but it's difficult to write code in this system. Each function has to indicate specifically when it can be interrupted, and because the functions in the array are all separate the logic for communicating data between different parts of the function is complicated. I was hoping to get something closer to preemptive multitasking working instead.



My question is: is it possible to run an arbitrary JavaScript function in a way where it can be suspended and resumed by an external source?


Answer



Check StratifiedJS out


java - Difference between @Mock and @InjectMocks

What is the difference between @Mock and @InjectMocks in Mockito framework?

stunts - Is the street fight in "They Live" the longest clocked street fight in a film? - Movies & TV



Now discounting satires or films that are specifically about fighting...



Is the brawl between Nada and Frank in "They Live" the longest non-stop fight in a film?
It's clocked at around 5 minutes of (well, really silly) brawling.



(The fight in its entirety can be found on YouTube)



Image from



Answer



Added examples, all over 5:05 - hopefully will lose the downvote.



I would say no, principally because of Jackie Chan. His movies like Supercop and Rumble in the Bronx are basically 90-minute street fights punctuated with bursts of dialogue.



A few excerpts from the master of the running non-stop fight:





Also the final act of Kill Bill Pt. 1 is pretty much a non-stop fight:





  • Bride vs. B-squad Crazy 88s and O-Ren Ishii with The Bride versus the Crazy 88s clocks in at over 6:30 (1:15 to 7:45)- warning: includes blood, gore and a gratitutious sword-spanking. She does pause a few seconds between some kills.



Both together would clock in at almost 20 mins but there is a breather after she finishes off Gogo.


php - Skip Submit button in array_keys




I've got a PHP routine that processes a form and outputs the values to a CSV file. I'm using array_keys() to create the header row (skipped if there is one). Everything works perfectly except the final header term is "submit" because, of course, my form includes a Submit button. So the data ends up looking like this:




name,email,cell,dob,study,submit
"Temp One",fred@gmail.com,646-325-1111,1995-03-31,8,Submit
"Temp Two",tom@gmail.com,646-325-2222,1995-03-31,4,Submit


How do I omit the submit button both from the header and the data?



Here's my code:



if(isset($_POST['submit'])) {

$data = array_values($_POST); // get only values
$headers = array_keys($_POST); // keys are headers
if( $fp = fopen('data.csv','a+')) {
$line = fgets($fp);
if(!$line == $headers) {
fputcsv($fp, $headers);
fputcsv($fp, $data);
}
else
{

fputcsv($fp, $data);
}
fclose($fp);
header('Location: thanks.php');
}
}

Answer



Remove it from the array...




$post = $_POST;
unset($post['submit']);
$data = array_values($post); // get only values
$headers = array_keys($post); // keys are headers

java - Fabric/Crashlytics NoClassDefFoundError only on certain devices



I'm seeing a crash in Google Play related to Fabric/Crashlytics. This happened after I updated from normal Crashlytics to the new Fabric Crashlytics. I can only reproduce it on one of my devices (Galaxy S2). All other devices that I have (Nexus 5 and S4) do not have the crash. Here's the stack trace:



08-19 09:32:26.328    7084-7084/com.tsm.countryjam D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 0ms
08-19 09:32:26.653 7084-7088/com.tsm.countryjam D/dalvikvm﹕ GC_CONCURRENT freed 251K, 12% free 9567K/10823K, paused 12ms+2ms, total 70ms
08-19 09:32:26.653 7084-7084/com.tsm.countryjam D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 42ms
08-19 09:32:26.653 7084-7100/com.tsm.countryjam D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 42ms
08-19 09:32:26.668 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Failed resolving Lcom/crashlytics/android/beta/Beta; interface 9027 'Lio/fabric/sdk/android/services/common/DeviceIdentifierProvider;'

08-19 09:32:26.668 7084-7084/com.tsm.countryjam W/dalvikvm﹕ Link of class 'Lcom/crashlytics/android/beta/Beta;' failed
08-19 09:32:26.668 7084-7084/com.tsm.countryjam E/dalvikvm﹕ Could not find class 'com.crashlytics.android.beta.Beta', referenced from method com.crashlytics.android.Crashlytics.
08-19 09:32:26.668 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to resolve new-instance 1791 (Lcom/crashlytics/android/beta/Beta;) in Lcom/crashlytics/android/Crashlytics;
08-19 09:32:26.668 7084-7084/com.tsm.countryjam D/dalvikvm﹕ VFY: replacing opcode 0x22 at 0x000a
08-19 09:32:26.668 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Failed resolving Lcom/crashlytics/android/beta/Beta; interface 9027 'Lio/fabric/sdk/android/services/common/DeviceIdentifierProvider;'
08-19 09:32:26.668 7084-7084/com.tsm.countryjam W/dalvikvm﹕ Link of class 'Lcom/crashlytics/android/beta/Beta;' failed
08-19 09:32:26.668 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to find class referenced in signature (Lcom/crashlytics/android/beta/Beta;)
08-19 09:32:26.673 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Failed resolving Lcom/crashlytics/android/beta/Beta; interface 9027 'Lio/fabric/sdk/android/services/common/DeviceIdentifierProvider;'
08-19 09:32:26.673 7084-7084/com.tsm.countryjam W/dalvikvm﹕ Link of class 'Lcom/crashlytics/android/beta/Beta;' failed
08-19 09:32:26.673 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to find class referenced in signature (Lcom/crashlytics/android/core/PinningInfoProvider;)

08-19 09:32:26.673 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to find class referenced in signature (Lcom/crashlytics/android/core/PinningInfoProvider;)
08-19 09:32:26.673 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to find class referenced in signature (Lcom/crashlytics/android/core/PinningInfoProvider;)
08-19 09:32:26.678 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to find class referenced in signature (Lcom/crashlytics/android/core/CrashlyticsListener;)
08-19 09:32:26.678 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to find class referenced in signature (Lcom/crashlytics/android/core/CrashlyticsListener;)
08-19 09:32:26.678 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Failed resolving Lcom/crashlytics/android/beta/Beta; interface 9027 'Lio/fabric/sdk/android/services/common/DeviceIdentifierProvider;'
08-19 09:32:26.678 7084-7084/com.tsm.countryjam W/dalvikvm﹕ Link of class 'Lcom/crashlytics/android/beta/Beta;' failed
08-19 09:32:26.678 7084-7084/com.tsm.countryjam D/dalvikvm﹕ DexOpt: unable to opt direct call 0x3474 at 0x0f in Lcom/crashlytics/android/Crashlytics;.
08-19 09:32:26.678 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Failed resolving Lcom/crashlytics/android/answers/SessionEventTransform; interface 9072 'Lio/fabric/sdk/android/services/events/EventTransform;'
08-19 09:32:26.678 7084-7084/com.tsm.countryjam W/dalvikvm﹕ Link of class 'Lcom/crashlytics/android/answers/SessionEventTransform;' failed
08-19 09:32:26.678 7084-7084/com.tsm.countryjam E/dalvikvm﹕ Could not find class 'com.crashlytics.android.answers.SessionEventTransform', referenced from method com.crashlytics.android.answers.Answers.initializeSessionAnalytics

08-19 09:32:26.678 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to resolve new-instance 1784 (Lcom/crashlytics/android/answers/SessionEventTransform;) in Lcom/crashlytics/android/answers/Answers;
08-19 09:32:26.678 7084-7084/com.tsm.countryjam D/dalvikvm﹕ VFY: replacing opcode 0x22 at 0x0004
08-19 09:32:26.678 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Could not find method io.fabric.sdk.android.services.common.CommonUtils.logControlledError, referenced from method com.crashlytics.android.answers.Answers.initializeSessionAnalytics
08-19 09:32:26.678 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to resolve static method 59049: Lio/fabric/sdk/android/services/common/CommonUtils;.logControlledError (Landroid/content/Context;Ljava/lang/String;Ljava/lang/Throwable;)V
08-19 09:32:26.678 7084-7084/com.tsm.countryjam D/dalvikvm﹕ VFY: replacing opcode 0x77 at 0x0194
08-19 09:32:26.678 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Could not find method io.fabric.sdk.android.services.settings.Settings.getInstance, referenced from method com.crashlytics.android.answers.Answers.doInBackground
08-19 09:32:26.678 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to resolve static method 59331: Lio/fabric/sdk/android/services/settings/Settings;.getInstance ()Lio/fabric/sdk/android/services/settings/Settings;
08-19 09:32:26.678 7084-7084/com.tsm.countryjam D/dalvikvm﹕ VFY: replacing opcode 0x71 at 0x000c
08-19 09:32:26.678 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Could not find method io.fabric.sdk.android.services.common.CommonUtils.getStringsFileValue, referenced from method com.crashlytics.android.answers.Answers.getOverridenSpiEndpoint
08-19 09:32:26.678 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to resolve static method 59043: Lio/fabric/sdk/android/services/common/CommonUtils;.getStringsFileValue (Landroid/content/Context;Ljava/lang/String;)Ljava/lang/String;

08-19 09:32:26.678 7084-7084/com.tsm.countryjam D/dalvikvm﹕ VFY: replacing opcode 0x71 at 0x0008
08-19 09:32:26.678 7084-7084/com.tsm.countryjam E/dalvikvm﹕ Could not find class 'io.fabric.sdk.android.services.persistence.FileStoreImpl', referenced from method com.crashlytics.android.answers.Answers.getSdkDirectory
08-19 09:32:26.678 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to resolve new-instance 9090 (Lio/fabric/sdk/android/services/persistence/FileStoreImpl;) in Lcom/crashlytics/android/answers/Answers;
08-19 09:32:26.678 7084-7084/com.tsm.countryjam D/dalvikvm﹕ VFY: replacing opcode 0x22 at 0x0001
08-19 09:32:26.678 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Could not find method io.fabric.sdk.android.services.common.Crash$FatalException.getSessionId, referenced from method com.crashlytics.android.answers.Answers.onException
08-19 09:32:26.678 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to resolve virtual method 59056: Lio/fabric/sdk/android/services/common/Crash$FatalException;.getSessionId ()Ljava/lang/String;
08-19 09:32:26.678 7084-7084/com.tsm.countryjam D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000b
08-19 09:32:26.683 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Could not find method io.fabric.sdk.android.services.common.Crash$LoggedException.getSessionId, referenced from method com.crashlytics.android.answers.Answers.onException
08-19 09:32:26.683 7084-7084/com.tsm.countryjam W/dalvikvm﹕ VFY: unable to resolve virtual method 59058: Lio/fabric/sdk/android/services/common/Crash$LoggedException;.getSessionId ()Ljava/lang/String;
08-19 09:32:26.683 7084-7084/com.tsm.countryjam D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000b

08-19 09:32:26.683 7084-7084/com.tsm.countryjam I/dalvikvm﹕ Failed resolving Lcom/crashlytics/android/answers/SessionEventTransform; interface 9072 'Lio/fabric/sdk/android/services/events/EventTransform;'
08-19 09:32:26.683 7084-7084/com.tsm.countryjam W/dalvikvm﹕ Link of class 'Lcom/crashlytics/android/answers/SessionEventTransform;' failed
08-19 09:32:26.683 7084-7084/com.tsm.countryjam D/dalvikvm﹕ DexOpt: unable to opt direct call 0x3455 at 0x0c in Lcom/crashlytics/android/answers/Answers;.initializeSessionAnalytics
08-19 09:32:26.683 7084-7084/com.tsm.countryjam D/dalvikvm﹕ DexOpt: unable to opt direct call 0xe6da at 0x19 in Lcom/crashlytics/android/answers/Answers;.initializeSessionAnalytics
08-19 09:32:26.683 7084-7084/com.tsm.countryjam D/dalvikvm﹕ DexOpt: unable to opt direct call 0xe78c at 0x36 in Lcom/crashlytics/android/answers/Answers;.initializeSessionAnalytics
08-19 09:32:26.683 7084-7084/com.tsm.countryjam W/dalvikvm﹕ Unable to resolve superclass of Lcom/crashlytics/android/answers/SessionAnalyticsFilesManager; (9073)
08-19 09:32:26.683 7084-7084/com.tsm.countryjam W/dalvikvm﹕ Link of class 'Lcom/crashlytics/android/answers/SessionAnalyticsFilesManager;' failed
08-19 09:32:26.683 7084-7084/com.tsm.countryjam D/dalvikvm﹕ DexOpt: unable to opt direct call 0x342a at 0x4b in Lcom/crashlytics/android/answers/Answers;.initializeSessionAnalytics
08-19 09:32:26.683 7084-7084/com.tsm.countryjam I/dalvikvm﹕ DexOpt: unable to optimize static field ref 0x5e1e at 0x72 in Lcom/crashlytics/android/answers/Answers;.initializeSessionAnalytics
08-19 09:32:26.683 7084-7084/com.tsm.countryjam I/dalvikvm﹕ DexOpt: unable to optimize static field ref 0x5e1c at 0x7e in Lcom/crashlytics/android/answers/Answers;.initializeSessionAnalytics

08-19 09:32:26.683 7084-7084/com.tsm.countryjam I/dalvikvm﹕ DexOpt: unable to optimize static field ref 0x5e21 at 0x8a in Lcom/crashlytics/android/answers/Answers;.initializeSessionAnalytics
08-19 09:32:26.683 7084-7084/com.tsm.countryjam D/dalvikvm﹕ DexOpt: unable to opt direct call 0xe78f at 0x115 in Lcom/crashlytics/android/answers/Answers;.initializeSessionAnalytics
08-19 09:32:26.683 7084-7084/com.tsm.countryjam D/dalvikvm﹕ DexOpt: unable to opt direct call 0xe78f at 0x17d in Lcom/crashlytics/android/answers/Answers;.initializeSessionAnalytics
08-19 09:32:26.683 7084-7084/com.tsm.countryjam I/dalvikvm﹕ DexOpt: unable to optimize instance field ref 0x5e91 at 0x20 in Lcom/crashlytics/android/answers/Answers;.doInBackground
08-19 09:32:26.683 7084-7084/com.tsm.countryjam I/dalvikvm﹕ DexOpt: unable to optimize instance field ref 0x5e8c at 0x22 in Lcom/crashlytics/android/answers/Answers;.doInBackground
08-19 09:32:26.683 7084-7084/com.tsm.countryjam I/dalvikvm﹕ DexOpt: unable to optimize instance field ref 0x5e8e at 0x2a in Lcom/crashlytics/android/answers/Answers;.doInBackground
08-19 09:32:26.683 7084-7084/com.tsm.countryjam D/dalvikvm﹕ DexOpt: unable to opt direct call 0xe7ac at 0x07 in Lcom/crashlytics/android/answers/Answers;.getSdkDirectory
08-19 09:32:26.683 7084-7084/com.tsm.countryjam D/AndroidRuntime﹕ Shutting down VM
08-19 09:32:26.683 7084-7084/com.tsm.countryjam W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4127b2a0)
08-19 09:32:26.683 7084-7084/com.tsm.countryjam E/AndroidRuntime﹕ FATAL EXCEPTION: main

java.lang.NoClassDefFoundError: com.crashlytics.android.beta.Beta
at com.crashlytics.android.Crashlytics.(Crashlytics.java:29)
at com.tsm.events.application.TownsquareEvents.onCreate(TownsquareEvents.java:59)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1014)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4251)
at android.app.ActivityThread.access$1400(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1297)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)

at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)


And here's the contents of my build.gradle:



buildscript {

repositories {
jcenter()
maven { url 'https://maven.fabric.io/public' }
}

dependencies {
classpath 'com.android.tools.build:gradle:1.0.+'
classpath 'io.fabric.tools:gradle:1.+'
}
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
jcenter()
flatDir {
dirs 'libs'
}
maven { url 'https://maven.fabric.io/public' }
}



android {
compileSdkVersion 22
buildToolsVersion "22.0.1"

defaultConfig {
applicationId "com.tsm.events"
minSdkVersion 15
targetSdkVersion 22

versionCode 1
versionName "1.0.0"
multiDexEnabled = true
}
dexOptions {
javaMaxHeapSize "4g"
}
buildTypes {
debug {
debuggable true

}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}

}

dependencies {

compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':libraries:ResideMenu')
//compile 'com.android.support:support-v4:20.0.+'
compile 'com.android.support:support-v4:22.0.+'
compile files('libs/universal-image-loader-1.9.3.jar')
compile 'io.realm:realm-android:0.81.1'
compile 'se.emilsjolander:stickylistheaders:2.5.2'
compile 'com.google.android.gms:play-services:6.5.87'
compile 'com.parse.bolts:bolts-android:1.+'
compile fileTree(dir: 'libs', include: 'Parse-*.jar')

compile('com.crashlytics.sdk.android:crashlytics:2.4.0@aar') {
transitive = true
}
// Twitter Kit
compile('com.twitter.sdk.android:twitter:1.6.0@aar') {
transitive = true
}
compile('com.twitter.sdk.android:tweet-composer:0.8.0@aar') {
transitive = true;
}

compile 'com.facebook.android:facebook-android-sdk:3.20.0'
compile 'com.google.maps.android:android-maps-utils:0.3+'
compile(name: 'estimote-sdk-preview', ext: 'aar')
compile files('libs/biweekly-0.4.2.jar')
compile files('libs/jackson-core-2.5.2.jar')
}

Answer



I just figured it out with a hunch! I recently had to add multi-dex support after upgrading to the new Fabric framework, and I had a feeling that maybe I didn't do it correctly. So after adding these additional changes, now it no longer crashes:




In my build.gradle, I added an incremental settings:



dexOptions {
incremental true
javaMaxHeapSize "4g"
}


and an additional dependency:




compile 'com.android.support:multidex:'


and on my application class I'm extending MultiDexApplication:



public class TownsquareEvents extends android.support.multidex.MultiDexApplication

observers - android SurfaceHolder.lockCanvas returns null

I have been trying to do a Draw in an Observer callback and I always get a null return when I try to lock the canvas. The SurfaceHolder seems OK. I added a SurfaceHolder callback and it gets called early in the game.



Here is my Observer update method:



// implements Observer
public void update(Observable observable, Object data) {
Canvas c = null;

Log.i(TAG, "Surface Observer of CbSurfaceState thread: "
+ Thread.currentThread().getName());
try {
synchronized(mCbHolder) {
c = mCbHolder.lockCanvas(null);
if(c == null) {
Log.i(TAG, "lockCanvas returned null");
} else {
doDraw(c);
}

}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mCbHolder.unlockCanvasAndPost(c);
}
}
}



Here is where I first use it in the initialization:



public void initCbSurfaceView(Context context) {
mContext = context;
// register our interest in hearing about changes to our surface
mCbHolder = getHolder();
Log.i(TAG,"got holder");
mCbHolder.addCallback(cbSurfaceHolderCallback);

Log.i(TAG,"added callback");
// initially in preview mode
mCbHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// previewHolder.(SurfaceHolder); Don't know how to replace, but it
// won't work without the above.
...
mCbSurfaceState.addObserver(this);
Log.i(TAG, "Creation of CbSurfaceState thread: "
+ Thread.currentThread().getName());
}



I even set it again when the surface is created, (I recently add that just to be sure)



SurfaceHolder.Callback cbSurfaceHolderCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.i(TAG, "In surfaceCreated callback");
mCbHolder = holder;
}

...
};


Here is some log. I printed the thread because at first it was starting from an Asynch thread and I managed to avoid that.:



02-24 20:31:10.380: I/CbSurfaceView(4013): In surfaceCreated callback

02-24 20:31:10.380: I/CbSurfaceView(4013): SurfaceChanged 854X404


02-24 20:31:10.380: I/CbSurfaceView(4013): initPreview width 854 height 404

...

02-24 20:31:25.974: I/CbTouchListener(4013): onTouch Down x 665.7714 y 194.92023

02-24 20:31:25.974: I/CbSurfaceView(4013): Surface Observer of CbSurfaceState thread: main

02-24 20:31:25.981: I/CbSurfaceView(4013): lockCanvas returned null


02-24 20:31:26.005: I/CbSurfaceView(4013): Surface Observer of CbSurfaceState thread: main

02-24 20:31:26.075: I/CbSurfaceView(4013): lockCanvas returned null


What in the world am I doing wrong? My doDraw was working until it got to trying to draw the bitmap. Then I thought to check for null from the lockCanvas.




I found an answer here How to draw an overlay on a SurfaceView used by Camera on Android?
It seems that you can not draw on a preview. I was getting an exception about PUSH_BUFFER type surface, so I reset it to NORMAL so that it would not complain. I could not lock the surface of the preview and it would throw an exception if it was not NORMAL. Apparently you cannot change the surface type dynamically. That is probably why it is deprecated, but the camera preview will not work unless you set it to PUSH_BUFFER. I will add another, non-Surface view on top for drawing and rendering the pictures taken.




Thanks for looking and I hope this helps someone.

Escape special characters for Oracle and SQL Server in the same query



I have following query:




SELECT *
FROM PRODUCTS
WHERE REDUCTION LIKE '50%'


I'm required to use the LIKE clause. This query needs to run on both Oracle and SQL Server.



Now there is an issue because I want to match all products with a reduction of 50%. But the data might contain a reduction of 50.50%. Because '%' is a special character it matches both of them.



I want to escape all special characters, like the % in my query so that I only get the products with 50% reduction.




Is there an uniform solution to escape special characters on a dynamical way for both Oracle and SQL server?



Using a backslash is not a solution, because we don't know in practice what the input will be.


Answer



The ESCAPE clause works in Oracle and SQL Server.



As for your input, you need to replace the all occurrences of % with \% (preferably before passing the value to RDBMs). You can do this inside a query as well since, fortunately, Oracle REPLACE and SQL Server REPLACE functions have similar signature:



CREATE TABLE tests(test VARCHAR(100));

INSERT INTO tests VALUES('%WINDIR%\SYSTEM32');
SELECT *
FROM tests
WHERE test LIKE REPLACE(REPLACE('%WINDIR%\SYSTEM32', '\', '\\'), '%', '\%') ESCAPE '\'

Python 3 module import error from another folder




Folder Structure:




  main
|__ sub1
|__ __init__.py
|__ sub2
|__ test.py


I need to import inside test.py:



from .. sub1 import SomeClass



It shows this error :




ValueError: attempted relative import beyond top-level package.




Thank you for responses.


Answer




This is a special use case for testing from outside the main source folder. main has no reason to be a package, are there could be reasons for not to make it one.



IMHO, the best way is to start tests from the main directory. As the current directory is always in sys.path, sub1 will be directly importable and this would be enough:



from sub1 import SomeClass


But depending on your dev environment, you may need to launch tests directly from the test directory or any directory other than main. In that case, I am unsure that it is really a best practice, and I only use that for my tests, but a simple trick is to add the parent folder of the test folder to sys.path.



Here is what could be the beginning of test.py:




import os.path
import sys

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from sub1 import SomeClass
...



Take it for what it is: a sys.path trick that just allows to access the main source folder from the test folder.


html - Android monospace space ( ) width is different than character width

I'm developing a little webapp.
I tried displaying some output in an sort of ascii art way, using boxdrawing characters.
However, I noticed that on Android the space ( ) isn't equal width with the other characters, leading to ugly output.



I've put the font as monospace and even tried the monospace,monospace CSS setting.



To see what I'm talking about:
Please open https://tpgnow.herokuapp.com/CERN on Android and on a desktop browser.




Expected Output (desktop browser):
enter image description here



Actual Output (android browser):
enter image description here



I've tried different browsers and platforms and devices.
It seems to work on Win, Mac, Chrome and Firefox, also on iOS, but not on Android (neither Chrome nor Firefox).




Does anybody have a solution for this problem?

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...