Sunday, 31 January 2016

css - How to make a pie chart from highcharts responsive

I am trying since some days to make a pie chart from highcharts responsive. I am working on a medium size project and sometimes it is easy to lose the overview.



I already checked this : http://www.angulartutorial.net/2014/03/responsive-highchart.html but no success.



Problem: The highchart looks good when the width is 1920px.
When it is 900px then the description of the pie (series -> data) is outside the browser and one can not read it, moreover, the pie is for me to small.



Question: How can I avoid this behaviour? I would like a bigger pie and be able to read the (series-> data).



I provide the following code:




My HTML code is:





Title plot

Bla blablabla blab bl % blabla =
% blablabla blablabla







The CSS code:



#container-independency{
width: 90%;
max-width: 1620px;
background-color: #b8860b;
clear: both;

padding: 1%;
display: none;
box-sizing: border-box;
}

#independency{
width: 80%;
margin-left: auto;
margin-right: auto;
padding: 1%;

background-color: #ffb6c1;
box-sizing: border-box;
}

#highcharts_container{
width: 100%;
margin-left: auto;
margin-right: auto;
box-sizing: border-box;


}


Highcharts:



('#highcharts_container').highcharts({ 
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,

type: 'pie'
},

title:{
text:''
},

credits: {
enabled: false
},


navigation: {
buttonOptions: {
enabled: false
}
},

tooltip: {
pointFormat: '{point.percentage:.1f}%'
},

plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '{point.name}: {point.percentage:.2f} %',
style: {
color: '#58585a',
fontFamily: 'klavika-web, sans-serif', fontSize: '12px'

}
}
}
},
series: [{

name: '',
data: [
['Property1aaa/Property2aaa/Property3aaaaaa', independency],
['More blablabla blablabla', 100-independency],

]
}]
});//highcharts_container


Update:



Labels are hidden

javascript - Why does Math.cos(90 * Math.PI/180) yield 6.123031769111... and not zero?

I convert degrees to radians (degrees * Math.PI/180) but why does the following:



Math.cos(90 * Math.PI/180)


yield 6.123031769111... and not zero?




I'm trying to perform 2D rotations uses matrixes and the results are completely out of whack.

Android gradle, what is it?




There are some other related questions in this same website, but I just cannot get my head around this.



In their website they're extremelly abstract.




Gradle is build automation evolved. Gradle can automate the building, testing, publishing, deployment and more of software packages or other types of projects such as generated static websites, generated documentation or indeed anything else.




What does that really mean?

Thanks


Answer



Gradle is software for building software.



Let's assume for the moment, given in your question, that you are working on an Android app.



You may be using Eclipse to develop your app. Eclipse, as part of that, will use its own build automation engine to compile your Java, cross-compile the bytecode into Dalvik bytecode, compile the resources and manifest, package all that up into an APK, sign it with a signing key, and zipalign the results (among other steps).



Instead (or in addition to) Eclipse, you might have used android update project to generate a build.xml file, one that allows your app to be built via Apache Ant. Ant, like Gradle, is a build automation engine -- software for building software. Gradle happens to be newer and more powerful than Ant, but they have the same basic role in our lives: taking all stuff we type in (like, say, Java source) and get an APK out as a result.




If you have used Maven for project builds, or have used other IDEs (e.g., IntelliJ IDEA, NetBeans), you have used their build automation engines as part and parcel of that work.



Gradle is not only available for command-line builds as a replacement for Ant, but it is also the build automation engine used (by default) in Android Studio. Quoting the Android developer documentation:




The Android Studio build system consists of an Android plugin for Gradle. Gradle is an advanced build toolkit that manages dependencies and allows you to define custom build logic. Many software projects use Gradle to manage their builds. The Android plugin for Gradle does not depend on Android Studio, although Android Studio is fully integrated with it. This means that:




  • You can build your Android apps from the command line on your machine or on machines where Android Studio is not installed (such as continuous integration servers).

  • You can build your Android apps from Android Studio with the same custom build configuration and logic as when you build from the command line.




The output of the build is the same whether you are building a project from the command line, on a remote machine, or using Android Studio.



java - What does "?" and ":" do in boolean statements?




I think this question is a general programming question,

but let's assume I'm asking this for Java.



what does the following statement do ?



return a ? (b || c) : (b && c);


I have seen the syntax with ?'s and :'s in many topics at SO, this particular one I found in Check if at least two out of three booleans are true



But I don't know what they mean, so how to use them, and I believe it's something very useful for me.




Thanks !


Answer



That's the conditional operator. It means something like:



condition ? value-if-true : value-if-false;


So in your case, it returns b || c if a is true, and b && c if a is false.


design patterns - Naming Classes - How to avoid calling everything a "Manager"?




A long time ago I have read an article (I believe a blog entry) which put me on the "right" track on naming objects: Be very very scrupulous about naming things in your program.



For example if my application was (as a typical business app) handling users, companies and addresses I'd have a User, a Company and an Address domain class - and probably somewhere a UserManager, a CompanyManager and an AddressManager would pop up that handles those things.




So can you tell what those UserManager, CompanyManager and AddressManager do? No, because Manager is a very very generic term that fits to anything you can do with your domain objects.



The article I read recommended using very specific names. If it was a C++ application and the UserManager's job was allocating and freeing users from the heap it would not manage the users but guard their birth and death. Hmm, maybe we could call this a UserShepherd.



Or maybe the UserManager's job is to examine each User object's data and sign the data cryptographically. Then we'd have a UserRecordsClerk.



Now that this idea stuck with me I try to apply it. And find this simple idea amazingly hard.



I can describe what the classes do and (as long as I don't slip into quick & dirty coding) the classes I write do exactly one thing. What I miss to go from that description to the names is a kind of catalogue of names, a vocabulary that maps the concepts to names.




Ultimately I'd like to have something like a pattern catalogue in my mind (frequently design patterns easily provide the object names, e.g. a factory)




  • Factory - Creates other objects (naming taken from the design pattern)

  • Shepherd - A shepherd handles the lifetime of objects, their creation and shutdown

  • Synchronizer - Copies data between two or more objects (or object hierarchies)

  • Nanny - Helps objects reach "usable" state after creation - for example by wiring to other objects


  • etc etc.





So, how do you handle that issue? Do you have a fixed vocabulary, do you invent new names on the fly or do you consider naming things not-so-important or wrong?



P.S.: I'm also interested in links to articles and blogs discussing the issue. As a start, here is the original article that got me thinking about it: Naming Java Classes without a 'Manager'






Update: Summary of answers



Here's a little summary of what I learned from this question in the meantime.





  • Try not to create new metaphors (Nanny)

  • Have a look at what other frameworks do



Further articles/books on this topic:





And a current list of name prefixes/suffixes I collected (subjectively!) from the answers:





  • Coordinator

  • Builder

  • Writer

  • Reader

  • Handler

  • Container

  • Protocol

  • Target


  • Converter

  • Controller

  • View

  • Factory

  • Entity

  • Bucket



And a good tip for the road:





Don't get naming paralysis. Yes, names are very important but they're not important enough to waste huge amounts of time on. If you can't think up a good name in 10 minutes, move on.



Answer



I asked a similar question, but where possible I try to copy the names already in the .NET framework, and I look for ideas in the Java and Android frameworks.



It seems Helper, Manager, and Util are the unavoidable nouns you attach for coordinating classes that contain no state and are generally procedural and static. An alternative is Coordinator.



You could get particularly purple prosey with the names and go for things like Minder, Overseer, Supervisor, Administrator, and Master, but as I said I prefer keeping it like the framework names you're used to.




Some other common suffixes (if that is the correct term) you also find in the .NET framework are:




  • Builder

  • Writer

  • Reader

  • Handler

  • Container


python - SMTP works in Linux but not on Mac

When I run the following code in Linux, it sends, the email, however, in Mac, it fails to run at line server = smtplib.SMTP("smtp.gmail.com", "587")



import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

import subprocess as s
import sys
import os

def send_email(predicted_change, sentiment, coin, toaddr):
fromaddr = "****@gmail.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Predicted Price Change Of " + coin


body = "The sentiment of the last 60 minutes for " + coin + " is : " +
sentiment + " - The predicted change in price is : " + predicted_change
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP("smtp.gmail.com", "587")
server.starttls()
server.ehlo()
server.login(fromaddr, "****")
text = msg.as_string()
print(text)

server.sendmail(fromaddr, toaddr, text)
server.quit()
print("Over")


I get this error



 socket.error: [Errno 60] Operation timed out

Saturday, 30 January 2016

Can comments be used in JSON?



Can I use comments inside a JSON file? If so, how?


Answer



No.



The JSON should all be data, and if you include a comment, then it will be data too.



You could have a designated data element called "_comment" (or something) that would be ignored by apps that use the JSON data.




You would probably be better having the comment in the processes that generates/receives the JSON, as they are supposed to know what the JSON data will be in advance, or at least the structure of it.



But if you decided to:



{
"_comment": "comment text goes here...",
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",

"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]

},
"GlossSee": "markup"
}
}
}
}
}

php - Is mysql_real_escape_string is really safe to use?





OK, I have one question before I start coding MySQL in my school project. Is mysql_real_escape_string is really safe to use? I've heard that it's still not really safe to use..So are there any tweaks which makes SQL query secure? I've used mysql_real_escape_string before many times, but not I am building a website for my school, so first thing I've to check is security.


Answer



UPDATE: The answer below was to the best of my knowledge correct at the time of writing. The fact is mysql_real_escape_string is not safe and never really was. You should always use prepared statements instead.



As mysql_* has been removed completely as of PHP 7 the situation has become moot. I've left my original answer for historical purposes below.






mysql_real_escape_string is safe to use if used properly (ie, everywhere you're inserting PHP variables into your queries), but as has been pointed out in the comments it's not the only thing you need to worry about. For example, HTML markup could be inserted into your DB and used for Cross Site Scripting attacks.




You might also want to consider prepared statements as an alternative to mysql_real_escape_string, as they will automatically escape input for you so there's no chance of accidentally forgetting to escape a parameter.


What does [:-1] mean/do in python?




Working on a python assignment and was curious as to what [:-1] means in the context of the following code: instructions = f.readline()[:-1]



Have searched on here on S.O. and on Google but to no avail. Would love an explanation!


Answer



It slices the string to omit the last character, in this case a newline character:



>>> 'test\n'[:-1]
'test'



Since this works even on empty strings, it's a pretty safe way of removing that last character, if present:



>>> ''[:-1]
''


This works on any sequence, not just strings.



For lines in a text file, I’d actually use line.rstrip('\n') to only remove a newline; sometimes the last line in the file doesn’t end in a newline character and using slicing then removes whatever other character is last on that line.



Friday, 29 January 2016

Android NDK: Linking "error: undefined reference to" GLES functions

So I have the following on my Android.mk....



...
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include /Users/myname/Development/Android/android-ndk-r8c/platforms/android-14/arch-arm/usr/include
...
LOCAL_LDLIBS := -ldl -lGLESv1_CM -llog


However, when I try running ndk-build I get the following....




/Users/myname/Development/Android/android-ndk-r8c/toolchains/arm-linux-androideabi-4.6/prebuilt/darwin-x86/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: ./obj/local/armeabi/libSDL.a(SDL_render_gles.o): in function GLES_CreateRenderer:jni/SDL/src/render/opengles/SDL_render_gles.c:189: error: undefined reference to 'glDisableClientState'
collect2: ld returned 1 exit status




This of course appears to be an issue linking, however, the compiler worked just fine. I am confused as to why the linking wouldn't work but the compilation would. Anyonw know how I could fix it?



From ndk-build V=1 >Build.log Output



UPDATE:



Ok so I am taking the code found here this compiles fine, however, I am trying to upgrade to PRBoom+ so I dl the code from here and tweak the Android.mk to include the new classes. Once this is done it seems to compile fine, however, it fails to properly link. There are two main errors I see...



First is involving multiple definitions, however, the original (compiled linked fine) code had the same multiple definitions....




/Users/me/Development/Android/android-ndk-r8c/toolchains/arm-linux-androideabi-4.6/prebuilt/darwin-x86/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: error: ./obj/local/armeabi/objs-debug/prboom_jni/w_mmap.o: multiple definition of 'W_InitCache'




The other type is the OpenGL issues...




/Users/me/Development/Android/android-ndk-r8c/toolchains/arm-linux-androideabi-4.6/prebuilt/darwin-x86/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: ./obj/local/armeabi/libSDL.a(SDL_render_gles.o): in function GLES_ResetState:/Users/jackiegleason/Development/Code/prboom4android-base/jni/SDL/src/render/opengles/SDL_render_gles.c:181: error: undefined reference to 'glDisable'




If I copy everything back (using the prboom4android code) everything compiles and links just fine.



Here is a diff of the 2 Android.mk files...



< LOCAL_C_INCLUDES:= $(LOCAL_PATH) $(LOCAL_PATH)/include $(LOCAL_PATH)/../SDL_net/include $(LOCAL_PATH)/../SDL/include $(LOCAL_PATH)/MUSIC $(LOCAL_PATH)/MUSIC/include $(LOCAL_PATH)/TEXTSCREEN $(LOCAL_PATH)/TEXTSCREEN/include
---
> LOCAL_C_INCLUDES:= $(LOCAL_PATH) $(LOCAL_PATH)/include $(LOCAL_PATH)/../SDL_net/include $(LOCAL_PATH)/../SDL/include
28c28
< f_finale.c p_enemy.c p_spec.c r_plane.c w_mmap.c i_capture.c \
---
> f_finale.c p_enemy.c p_spec.c r_plane.c w_mmap.c \
31,36c31,33
< m_bbox.c p_inter.c p_tick.c r_things.c z_zone.c s_advsound.c memio.c \
< d_client.c i_video.c i_network.c i_system.c PCSOUND/pcsound.c PCSOUND/pcsound_sdl.c SDL/i_sshot.c \
< i_main.c sc_man.c SDL/i_sound.c jni_doom.c mus2mid.c pcm2wav.c e6y.c SDL/i_joy.c \
< r_screenmultiply.c hu_tracers.c i_smp.c g_overflow.c i_pcsound.c \
< MUSIC/dbopl.c MUSIC/flplayer.c MUSIC/portmidiplayer.c MUSIC/midifile.c MUSIC/opl_queue.c MUSIC/vorbisplayer.c MUSIC/dumbplayer.c MUSIC/oplplayer.c MUSIC/madplayer.c MUSIC/opl.c \
< TEXTSCREEN/txt_button.c TEXTSCREEN/txt_separator.c TEXTSCREEN/txt_gui.c TEXTSCREEN/txt_widget.c TEXTSCREEN/txt_checkbox.c TEXTSCREEN/txt_radiobutton.c TEXTSCREEN/txt_inputbox.c TEXTSCREEN/txt_spinctrl.c TEXTSCREEN/txt_window.c TEXTSCREEN/txt_desktop.c TEXTSCREEN/txt_scrollpane.c TEXTSCREEN/txt_io.c TEXTSCREEN/txt_strut.c TEXTSCREEN/txt_window_action.c TEXTSCREEN/txt_dropdown.c TEXTSCREEN/txt_sdl.c TEXTSCREEN/txt_label.c TEXTSCREEN/txt_table.c
---
> m_bbox.c p_inter.c p_tick.c r_things.c z_zone.c \
> d_client.c i_video.c i_network.c i_system.c \
> i_main.c i_sound.c jni_doom.c mmus2mid.c pcm2wav.c

excel - VBA - Too Slow with With and selection Command. How Can I optimize it better to run faster?

I am selecting a range and using that selection inside the With Command and as you all know, the .Selection command is going to slow down the process. What is the better way to write this code, to run it faster?



Here goes my code:



Sheets(Currentsheetname).Range("A" & SelRowNumber + 1 & ":A" & lastrow).Select


With .Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="Remove"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = "Warning"
.InputMessage = ""

.ErrorMessage = "Please select a value from the list available in the selected cell."
.ShowInput = True
.ShowError = True
End With

php - Issues with header while redirecting it to the current page




I have wriiten as




if (isset($_POST['delete'])):
$size = count($_POST['checkbox']);
for ($i=0; $i<=$size-1; $i++) {
$id = $_POST['checkbox'][$i];
$wpdb->query("DELETE FROM wp_submitted_form WHERE id =".$id);
}
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
endif;
?>



When submit button is clicked it throws error message as:



Cannot modify header information - headers already sent by (output started at /home/wizcorea/public_html/wp-admin/includes/template.php:1657) in /home/wizcorea/public_html/wp-content/plugins/submitted-form/view.php on line 54



I want that page should get refreshed after submit button is clicked


Answer



Use the ob_flush function of PHP. add this function at the top of the code.





ob_flush();


And this will work.



EDITED:



INstead of this code:




header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);


Use this code:



echo '';

Thursday, 28 January 2016

python - How to access environment variable values?




I set an environment variable that I want to access in my Python application. How do I get this value?


Answer



Environment variables are accessed through os.environ



import os
print(os.environ['HOME'])


Or you can see a list of all the environment variables using:




os.environ


As sometimes you might need to see a complete list!



# using get will return `None` if a key is not present rather than raise a `KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))

# os.getenv is equivalent, and can also give a default value instead of `None`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))



Python default installation on Windows is C:\Python. If you want to find out while running python you can do:



import sys
print(sys.prefix)

parsing - Parse query string in JavaScript








I need to parse the query string www.mysite.com/default.aspx?dest=aboutus.aspx.
How do I get the dest variable in JavaScript?

sort array on specific value with php

I have an array with specific values in it and i would like to sort the array on a specific value in it. For instance, TOTCOM_METIER DESC.
Ex :



Array
(

[0] => Array
(
[TOTCOM_METIER] => 1
[metier] => Traiteur
)

[1] => Array
(
[TOTCOM_METIER] => 4
[metier] => Restauration traditionnelle

)

[2] => Array
(
[TOTCOM_METIER] => 2
[metier] => Coiffure
)

)



I would like to sort it on TOTCOM_METIER DESC to have this result :



Array
(
[0] => Array
(
[TOTCOM_METIER] => 4
[metier] => Restauration traditionnelle
)


[1] => Array
(
[TOTCOM_METIER] => 2
[metier] => Coiffure
)

[2] => Array
(
[TOTCOM_METIER] => 1

[metier] => Traiteur
)

)

oracle - Delphi - prevent against SQL injection




I need to protect an application from SQL injection. Application is connecting to Oracle, using ADO, and search for the username and password to make the authentication.



From what I've read until now, the best approach is by using parameters, not assigning the entire SQL as string. Something like this:



query.SQL.Text := 'select * from table_name where name=:Name and id=:ID'; 
query.Prepare;
query.ParamByName( 'Name' ).AsString := name;
query.ParamByName( 'ID' ).AsInteger := id;
query.Open;



Also, I'm thinking to verify the input from user, and to delete SQL keywords like delete,insert,select,etc...Any input character different than normal ASCII letters and numbers will be deleted.



This will assure me a minimum of security level?



I do not want to use any other components than Delphi 7 standard and Jedi.


Answer



Safe




query.SQL.Text := 'select * from table_name where name=:Name';


This code is safe because you are using parameters.
Parameters are always safe from SQL-injection.



Unsafe



var Username: string;
...
query.SQL.Text := 'select * from table_name where name='+ UserName;



Is unsafe because Username could be name; Drop table_name;
Resulting in the following query being executed.



select * from table_name where name=name; Drop table_name;


Also Unsafe




var Username: string;
...
query.SQL.Text := 'select * from table_name where name='''+ UserName+'''';


Because it if username is ' or (1=1); Drop Table_name; --
It will result in the following query:



select * from table_name where name='' or (1=1); Drop Table_name; -- '



But this code is safe



var id: integer;
...
query.SQL.Text := 'select * from table_name where id='+IntToStr(id);


Because IntToStr() will only accept integers so no SQL code can be injected into the query string this way, only numbers (which is exactly what you want and thus allowed)




But I want to do stuff that can't be done with parameters



Parameters can only be used for values. They cannot replace field names or table names.
So if you want to execute this query



query:= 'SELECT * FROM :dynamic_table '; {doesn't work}
query:= 'SELECT * FROM '+tableName; {works, but is unsafe}


The first query fails because you cannot use parameters for table or field names.
The second query is unsafe but is the only way this this can be done.
How to you stay safe?




You have to check the string tablename against a list of approved names.



Const
ApprovedTables: array[0..1] of string = ('table1','table2');

procedure DoQuery(tablename: string);
var
i: integer;
Approved: boolean;

query: string;
begin
Approved:= false;
for i:= lo(ApprovedTables) to hi(ApprovedTables) do begin
Approved:= Approved or (lowercase(tablename) = ApprovedTables[i]);
end; {for i}
if not Approved then exit;
query:= 'SELECT * FROM '+tablename;
...



That's the only way to do this, that I know of.



BTW Your original code has an error:



query.SQL.Text := 'select * from table_name where name=:Name where id=:ID'; 


Should be




query.SQL.Text := 'select * from table_name where name=:Name and id=:ID'; 


You cannot have two where's in one (sub)query


pandas - Python still having issues with try-except clause




I am using the tld python library to grab the first level domain from the proxy request logs using a apply function. When I run into a strange request that tld doesnt know how to handle like 'http:1 CON' or 'http:/login.cgi%00' I run into an error message like the following:



TldBadUrl: Is not a valid URL http:1 con!
TldBadUrlTraceback (most recent call last)
in engine
----> 1 new_fld_column = request_2['request'].apply(get_fld)

/usr/local/lib/python2.7/site-packages/pandas/core/series.pyc in apply(self, func, convert_dtype, args, **kwds)

2353 else:
2354 values = self.asobject
-> 2355 mapped = lib.map_infer(values, f, convert=convert_dtype)
2356
2357 if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer (pandas/_libs/lib.c:66440)()

/home/cdsw/.local/lib/python2.7/site-packages/tld/utils.pyc in get_fld(url,
fail_silently, fix_protocol, search_public, search_private, **kwargs)

385 fix_protocol=fix_protocol,
386 search_public=search_public,
--> 387 search_private=search_private
388 )
389

/home/cdsw/.local/lib/python2.7/site-packages/tld/utils.pyc in process_url(url, fail_silently, fix_protocol, search_public, search_private)
289 return None, None, parsed_url
290 else:
--> 291 raise TldBadUrl(url=url)

292
293 domain_parts = domain_name.split('.')


To overcome this it was suggested to me to wrap the function in a try-except clause to determine the rows that error out by querying them with NaN:



import tld
from tld import get_fld

def try_get_fld(x):

try:
return get_fld(x)
except tld.exceptions.TldBadUrl:
return np.nan


This seems to work for some of the "requests" like "http:1 con" and "http:/login.cgi%00" but then fails for "http://urnt12.knhc..txt/" where I get another error message like the one above:



TldDomainNotFound: Domain urnt12.knhc..txt didn't match any existing TLD name!



This is what the dataframe looks like total of 240,000 "requests" in a dataframe called "request":



request
request count
0 https://login.microsoftonline.com 24521
1 https://dt.adsafeprotected.com 11521
2 https://googleads.g.doubleclick.net 6252
3 https://fls-na.amazon.com 65225
4 https://v10.vortex-win.data.microsoft.com 7852222

5 https://ib.adnxs.com 12
6 http:1 CON 6
7 http:/login.cgi%00 45822
8 http://urnt12.knhc..txt/ 1


My code:



from tld import get_tld
from tld import get_fld

import pandas as pd
import numpy as np
#Read back into to dataframe
request = pd.read_csv('Proxy/Proxy_Analytics/Request_Grouped_By_Request_Count_12032018.csv')
#Remove rows where there were null values in the request column
request = request[pd.notnull(request['request'])]
#Find the urls that contain IP addresses and exclude them from the new dataframe
request = request[~request.request.str.findall(r'[0-9]+(?:\.[0-9]+){3}').astype(bool)]
#Reset index
request = request.reset_index(drop=True)


import tld
from tld import get_fld

def try_get_fld(x):
try:
return get_fld(x)
except tld.exceptions.TldBadUrl:
return np.nan


request['flds'] = request['request'].apply(try_get_fld)

#faulty_url_df = request[request['flds'].isna()]
#print(faulty_url_df)

Answer



It fails because it's a different exception. You expect a tld.exceptions.TldBadUrl: exception but get a TldDomainNotFound



You can either be less specific in your except clause and catch more exception with one except clause or add another except clause to catch the other type of exception:




try: 
return get_fld(x)
except tld.exceptions.TldBadUrl:
return np.nan
except tld.exceptions.TldDomainNotFound:
print("Domain not found!")
return np.nan

PHP MySQL $_GET Hack prevention

This summary is not available. Please click here to view the post.

javascript - AngularJS: Promise in app.run() stuck in loop forever

I'm using app.run() in my AngularJS app to check whether a user is logged in before displaying the site to block access to various sites for non-registered users. I tried doing it with a promise because before, whenever I reloaded the page the isLoggedIn function would return false the getStatus hasn't returned the answer from the server yet.



Now using the promise, the site just calls itself in a loop forever, I guess because the process just repeats itself when the promise is resolved. Where am I going wrong and how could I fix this? Thanks in advance, help is much appreciated!




This is my code in app.js:



app.run(function($rootScope, $state, authService){
$rootScope.$on('$stateChangeStart', function(event, next, nextParams, from, fromParams){
event.preventDefault();
authService.getUserStatus().then(function(){
console.log(authService.isLoggedIn());
if(next.access.restricted && !authService.isLoggedIn()){
$state.go('index', {}, { reload: true });

} else {
$state.go(next, {}, { reload: true });
}
});
});
});


Here's the service authService.js:




(function(){
var app = angular.module('labelcms');
app.factory('authService', ['$q', '$timeout', '$http', function($q, $timeout, $http){

var user = null;

var isLoggedIn = function(){
if(user){
return true;
} else {

return false;
}
};

var getUserStatus = function(){
var deferred = $q.defer();

$http.get('/api/user/status')
.success(function(data){
if(data.status){

user = data.status;
deferred.resolve();
} else {
user = false;
deferred.resolve();
}
})
.error(function(data){
console.log('Error: ' + data);
user = false;

deferred.resolve();
});

return deferred.promise;
};

return ({
isLoggedIn: isLoggedIn,
getUserStatus: getUserStatus,
login: login,

logout: logout,
signup: signup
});

}]);
})();

line endings - How can I normalize the EOL character in Java?



I have a linux server and many clients with many operating systems. The server takes an input file from clients. Linux has end of line char LF, while Mac has end of line char CR, and
Windows has end of line char CR+LF



The server needs as end of line char LF. Using java, I want to ensure that the file will always use the linux eol char LF. How can I achieve it?


Answer



Combining the two answers (by Visage & eumiro):



EDIT: After reading the comment. line.
System.getProperty("line.separator") has no use then.
Before sending the file to server, open it replace all the EOLs and writeback
Make sure to use DataStreams to do so, and write in binary



String fileString;
//..
//read from the file
//..
//for windows
fileString = fileString.replaceAll("\\r\\n", "\n");
fileString = fileString.replaceAll("\\r", "\n");
//..
//write to file in binary mode.. something like:
DataOutputStream os = new DataOutputStream(new FileOutputStream("fname.txt"));
os.write(fileString.getBytes());
//..
//send file
//..


The replaceAll method has two arguments, the first one is the string to replace and the second one is the replacement. But, the first one is treated as a regular expression, so, '\' is interpreted that way. So:



"\\r\\n" is converted to "\r\n" by Regex
"\r\n" is converted to CR+LF by Java

Wednesday, 27 January 2016

email - PHP 7 Mail() not working




I have read I believe every post on here related to this. I have a feeling that this is Linux file rights related, but not to sure. My environment is a test Centos7 box running Apache 2.4 and Php7 with phpMyAdmin etc. I can send mail using the sendmail somename@domain.com. I have tested this.
In my php.ini file(s) I have "sendmail_path = /usr/sbin/sendmail -t -i;"



$to = "Jesse.---@-----------.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";
$mail = mail($to,$subject,$txt,$headers); //I have tried with no headers as well.


The mail function returns a false.


Answer



This problem can have so many reasons, that's why I am not using mail() anymore, I use PHPMailer with an external SMTP (GMAIL for example), but if you still want to use mail(), make sure that Sendmail, Exim or Postfix is installed on your server.



Test the mail() on the terminal first, if you can send on terminal, the problem may be some configuration on the php.ini, if the message fails on the terminal, you need to check the Postfix / Sendmail / Exim logs for the error message.



Make sure with your server provider too, if you are authorized to use mail(). Some servers block this function due to spam, and they require manual authorization.


Comprehensive Security Against User Input - PHP, MySQL










Goal: Properly sanitize all inputs from text boxes before entering into DB, which is then output to a page. For my use case, I need to prevent potential problems while not eliminating the data input. Also, the charset is explicitly set to UTF-8 in both the HTTP header and the META tag to prevent problems with malformed encoding. The DB is also set to UTF-8.



Specs: PHP, MySQL, Apache



Sample Code:



    function secureinput($input)
{
$input = htmlspecialchars($input, ENT_QUOTES ,'UTF-8');
$input = strip_tags($input); //fail-safe for anything that gets through
$input = mysql_real_escape_string($input);

return $input;
}


Question: What vectors of attack (XSS, SQL Injection, etc.) is this still vulnerable to?



A huge thanks to anyone who can help. This is my first time posting, though I've always turned to SO first for looking up answers to my questions. Unfortunately, this time I couldn't find any other questions that answered my problem, only small parts of it.


Answer



XSS Attacks



By using htmlspecialchars() whenever you output user-inputted content, you can ensure you will be safe from XSS attacks.



SQL Injection



Steve Friedl provides some examples of SQL Injections and limitations of input sanitization on his website: http://www.unixwiz.net/techtips/sql-injection.html



Even though your code may be secure from SQL injection attacks with mysql_real_escape_string(), you are better off using parameterized SQL and eliminating the risk of SQL injection altogether. You will also be much more secure if you use PDO or mysqli in PHP instead of the deprecated mysql functions.


javascript - PHP if else condition inside JS file Wordpress theme customizer condition

$('.class1').append( '' );
var button = $('.class1.load-more');


the above is a code from the .js file of WP infinite scroll Wordpress plugin.



Can we somehow put a PHP condition inside a js file:




If( logical condition 1 )  {
$('.class1').append( '' );
var button = $('.class1.load-more');
} elseif( logical condition 2 ) {
$('.class2').append( '' );
var button = $('.class2 .load-more');
}



P.S.: PHP logic should go inside a js file not script<> tags.

oop - Accessing private from static method in PHP



Why this works? I mean, accessing the private variable.




class Test {
private $q = 0;
public function __construct() {
$this->q = 1;
}
public static function EpicConstruct() {
$test = new self();
$test->q = 2;
return $test;
}
}

$test = Test::EpicConstruct();

Answer



Because you are accessing the member in the correct context, namely: the class that defines the private member.


Detect whether a Python string is a number or a letter




How can I detect either numbers or letters in a string? I am aware you use the ASCII codes, but what functions take advantage of them?


Answer





You may use str.isdigit() and str.isalpha() to check whether given string is positive integer and alphabet respectively.



Sample Results:




# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True

# For digit
>>> '1'.isdigit()
True

>>> '1'.isalpha()
False




str.isdigit() returns False if the string is a negative number or a float number. For example:



# returns `False` for float
>>> '123.3'.isdigit()

False
# returns `False` for negative number
>>> '-123'.isdigit()
False


If you want to also check for the negative integers and float, then you may write a custom function to check for it as:



def is_number(n):
try:

float(n) # Type-casting the string to `float`.
# If string is not a valid `float`,
# it'll raise `ValueError` exception
except ValueError:
return False
return True


Sample Run:




>>> is_number('123')    # positive integer number
True

>>> is_number('123.4') # positive float number
True

>>> is_number('-123') # negative integer number
True

>>> is_number('-123.4') # negative `float` number

True

>>> is_number('abc') # `False` for "some random" string
False




The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:




>>> is_number('NaN')
True


In order to check whether the number is "NaN", you may use math.isnan() as:



>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)

True


Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:



# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False



Hence, above function is_number can be updated to return False for "NaN" as:



def is_number(n):
is_number = True
try:
num = float(n)
# check for "nan" floats
is_number = num == num # or use `math.isnan(num)`
except ValueError:
is_number = False

return is_number


Sample Run:



>>> is_number('Nan')   # not a number "Nan" string
False

>>> is_number('nan') # not a number string "nan" with all lower cased
False


>>> is_number('123') # positive integer
True

>>> is_number('-123') # negative integer
True

>>> is_number('-1.12') # negative `float`
True


>>> is_number('abc') # "some random" string
False




The above function will still return you False for the complex numbers. If you want your is_number function to treat complex numbers as valid number, then you need to type cast your passed string to complex() instead of float(). Then your is_number function will look like:



def is_number(n):
is_number = True

try:
# v type-casting the number here as `complex`, instead of `float`
num = complex(n)
is_number = num == num
except ValueError:
is_number = False
return is_number


Sample Run:




>>> is_number('1+2j')    # Valid 
True # : complex number

>>> is_number('1+ 2j') # Invalid
False # : string with space in complex number represetantion
# is treated as invalid complex number

>>> is_number('123') # Valid
True # : positive integer


>>> is_number('-123') # Valid
True # : negative integer

>>> is_number('abc') # Invalid
False # : some random string, not a valid number

>>> is_number('nan') # Invalid
False # : not a number "nan" string



PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.


How to send email in Windows command prompt using only pipes (no files) with newlines?

I want to send email using only pipes without writing the message to a temporary file in Windows XP command prompt. I can do it with for example blat.exe, but I can't get the newlines to work.




I tried this kind of command:



echo something something & echo.more of something | blat.exe - -to my.email.address@domain.com


But this just sends "more of something" and ignores the everything before the last newline (& echo.).

PHP Page redirect problem - Cannot modify header information




I have a page that displays various elements even if the id it's calling from the database does not exist or was deleted (which throws up all sorts of ugly errors along with search engines continuing to list non-existent pages).



Can you modify the first part of the page code shown below to send a 404 (or at least to projecterror.php which has 404 headers) if $id does not exist? Many thanks!




include_once("includes/linkmysql.php");
$adda=$_GET['a'];
$cont=$_GET['c'];
$select="SELECT * FROM projects where id='$id'";
$qselect = mysql_query($select);
while ($row = mysql_fetch_array($qselect)) {



The following modification as kindly suggested by Matt Wilson as a result of an original comment by
Vivek Goel results in valid entries showing the page correctly but non-existent pages are showing the errors below this modified code:



include_once("includes/linkmysql.php");
$adda=$_GET['a'];
$cont=$_GET['c'];
$select="SELECT * FROM projects where id='$id'";
$qselect = mysql_query($select);
if( mysql_num_rows( $qselect ) === 0 )

{
header("HTTP/1.1 301 Moved Permanently");
header( 'Location: http://examplesite.domain/errorpage' ) ;
exit;
}
while ($row = mysql_fetch_array($qselect)) {


Errors resulting from the above modifications:




Warning: Cannot modify header information - headers already sent by (output started at /home/website/public_html/header1.php:14) in /home/website/public_html/header1.php on line 22 
Warning: Cannot modify header information - headers already sent by (output started at /home/website/public_html/header1.php:14) in /home/website/public_html/header1.php on line 23 Lines 22 and 23 are the two header lines in your example above


Lines 22 and 23 are the two header lines as below:



header("HTTP/1.1 301 Moved Permanently");
header( 'Location: http://examplesite.domain/errorpage' ) ;

Answer




I have much easier solution for you - it is simple! Just add this command at the very start of the php source:



ob_start();


This will start buffering the output, so that nothing is really output until the PHP script ends (or until you flush the buffer manually) - and also no headers are sent until that time!
So you don't need to reorganize your code, just add this line at the very beginning of your code and that's it :-)


android - HTTP Request in Kotlin



I'm completely new to Kotlin. I want to do a login validation using POST method and to get some information using GET method. I've URL, server Username and Password already of my previous project. I didn't find any proper example project which uses this thing. Anyone please suggest me any working example where I can use GET and POST method in HTTP request


Answer



For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client.



However, you can use standard libraries you would use in Java. For example, with HttpURLConnection you can do:



fun sendGet() {
val url = URL("http://www.google.com/")

with(url.openConnection() as HttpURLConnection) {
requestMethod = "GET" // optional default is GET

println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")

inputStream.bufferedReader().use {
it.lines().forEach { line ->
println(line)
}
}
}
}


Or simpler:



URL("https://google.com").readText()

Tuesday, 26 January 2016

html - How to link button?




Very simple question here, sorry if it's stupid.




I have the code here - but the button is not linking anywhere, can people help please?





Answer



A simple CSS button, use your button CSS to create one for to make it a button look link.






Permission denied when opening or creating files with PHP







I can't create files with php, because the file dosent got permission for that.

I get this error:




Warning: fopen(test.txt): failed to open stream: Permission denied in /web/com/example.com/index.php on line 20
Warning: fwrite() expects parameter 1 to be resource, boolean given in /web/com/example.com/index.php on line 21
Warning: fclose() expects parameter 1 to be resource, boolean given in /web/com/example.com/index.php on line 22




This is the code I was using:



 $file = fopen("test.txt","w");

echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>


Simple as that! This is example code from w3schools.



So I need help to find out how to give the file the needed permissions.
I'm uploading files to my site with the net2ftp FTP web application, if it matters.

java - What's the difference between @Component, @Repository & @Service annotations in Spring?

Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?



In other words, if I have a Service class and I change the annotation from @Service to @Component, will it still behave the same way?



Or does the annotation also influence the behavior and functionality of the class?

Monday, 25 January 2016

c# - Regex - match a string, but only where the next word is not 'x'



If I have this string:



"The quick brown fox jumped over the lazy dog. What a nice brown fox that is."



What regex would I use to match the text 'brown fox' but not where the following word is 'that', i.e. (matches in italic):



"The quick brown fox jumped over the lazy dog. What a nice brown fox that is."


Answer



You need a zero-width negative lookahead assertion, i.e.,



brown fox(?! that)

Sunday, 24 January 2016

x men cinematic universe - Why is the production team making prequels of X-Men rather than sequels?


I am a die-hard fan of the X-Men animated series X-Men Evolution and I also like the X-Men Movie Trilogy


In addition to the main trilogy there are two more movies (X-Men Origins: Wolverine and X-Men: First Class) which are prequels.


Why have the writers and directors decided to do prequels rather than a sequel?


Wikipedia says that they are planing for a sequel for the X-Men First Class movie but there is no clarification about an X-Men 4 movie.


Answer


I think this quote on the X-men: First Class wiki page gives us a decent amount of insight as to why they're making "prequels":



As producer Simon Kinberg read the comic series X-Men: First Class, he
suggested studio 20th Century Fox to adapt it. Kinberg, however, did
not want to follow the comic too much, as he felt "it was not fresh
enough in terms of storytelling", considering them too similar to John
Hughes movies, and also that the producers wanted an adaptation that
would introduce new characters. Both Kinberg and Shuler Donner said
they wanted characters with visuals and powers that had not been seen
yet, and that worked well as an ensemble even if they did not work
together in the comics.[11] Shuler Donner later said the original idea
was to green-light First Class depending on the success of X-Men
Origins: Magneto



So we see that they wanted a shift in focus from the main set of characters established in the X-Men trilogy. While quite a few characters were introduced, the main plots revolved around only a hand full of characters.


Another reasoning is that the X-Men universe is quite vast and dynamic. Each character has more than one story arc that just can't be covered in one or two movies. For example, if we look at the story arcs for Wolverine, we get something like this:



  • Pre-Memory loss (X-Men Origins: Wolverine)

  • Post Memory Loss (X-Men Origins: Wolverine 2)

  • Wolverine and the X-Men (X-Men 1-3)


Also, character story arcs criss-cross in the X-Men universe. It is literally a giant bowl of spaghetti, complicated even more by time travel in some instances.


pointers - how does the ampersand(&) sign work in c++?











This is confusing me:



class CDummy 
{
public:
int isitme (CDummy& param);
};


int CDummy::isitme (CDummy& param)
{
if (¶m == this)
{
return true; //ampersand sign on left side??
}
else
{
return false;

}
}

int main ()
{
CDummy a;
CDummy* b = &a;

if ( b->isitme(a) )
{

cout << "yes, &a is b";
}

return 0;
}


In C & usually means the address of a var. What does it mean here? Is this a fancy way of pointer notation?



The reason I am assuming it is a pointer notation because this is a pointer after all and we are checking for equality of two pointers.




I am studying from cplusplus.com and they have this example.


Answer



To start, note that



this


is a special pointer ( == memory address) to the class its in.
First, an object is instantiated:




CDummy a;


Next, a pointer is instantiated:



CDummy *b;


Next, the memory address of a is assigned to the pointer b:




b = &a;


Next, the method CDummy::isitme(CDummy ¶m) is called:



b->isitme(a);


A test is evaluated inside this method:




if (¶m == this) // do something


Here's the tricky part. param is an object of type CDummy, but ¶m is the memory address of param. So the memory address of param is tested against another memory address called "this". If you copy the memory address of the object this method is called from into the argument of this method, this will result in true.



This kind of evaluation is usually done when overloading the copy constructor



MyClass& MyClass::operator=(const MyClass &other) {
// if a programmer tries to copy the same object into itself, protect

// from this behavior via this route
if (&other == this) return *this;
else {
// otherwise truly copy other into this
}
}


Also note the usage of *this, where this is being dereferenced. That is, instead of returning the memory address, return the object located at that memory address.


javascript - How to write for loop in JSX in React?




I want to write a simple program where using for loop it will print numbers from 0 to 10. I am trying to use a for loop which will print numbers from 0 to 10 and will pass the props to child component. Here is my code:



import React, { Component } from 'react';
class App extends Component {




render() {

return(


{
for(var i=0;i<11;i++)
{
// var data=i;


}
}



);
}
}

const Print=(props)=>{
return(


{props.value}

);
}

export default App;

Answer



You can push the JSX to an array and render that.






class App extends React.Component {
render() {
const result = [];

for (var i = 0; i < 11; i++) {
result.push();
}


return
{result}
;
}
}

const Print = props => {
return
{props.value}
;
};

ReactDOM.render(, document.getElementById("root"));









Saturday, 23 January 2016

javascript - What is the best way to add options to a select from as a JS object with jQuery?



What is the best method for adding options to a

Blog Archive