In django 3.1, go to setting of your project and import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:
$.post(url, function (data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
w.document.close();
});
Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)
If you're looking for a minimalist approach to templates, you can check out JSON Template.
A more full-featured alternative is EJS. It's a bit more similar to something you'd get from Django.
Your mileage may vary for each of these - they're designed for a browser Javascript environment, and not Node.js.
You need BEGIN ... END to create a block spanning more than one statement. So, if you wanted to do 2 things in one 'leg' of an IF statement, or if you wanted to do more than one thing in the body of a WHILE loop, you'd need to bracket those statements with BEGIN...END.
The GO keyword is not part of SQL. It's only used by Query Analyzer to divide scripts into "batches" that are executed independently.
Here is a different solution for anyone interested. It uses the new For range in c++11
string str("(555) 555-5555");
string str2="";
for (const auto c: str){
if(!ispunct(c)){
str2.push_back(c);
}
}
str = str2;
//output: 555 5555555
cout<<str<<endl;
One suggestion in other answers is to use ax.set_axis_bgcolor("red")
. This however is deprecated, and doesn't work on MatPlotLib >= v2.0.
There is also the suggestion to use ax.patch.set_facecolor("red")
(works on both MatPlotLib v1.5 & v2.2). While this works fine, an even easier solution for v2.0+ is to use
ax.set_facecolor("red")
Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application.
The simple solution is to set the focus to the ListView
first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load
event, or immediately after you set the Selected
property:
myListView.Select();
The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button).
To fix that, you will need to set the HideSelection
property of the ListView
control to False. That will cause the selected item to remain highlighted, even when the control loses the focus.
When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text.
You can set this property either at design time, or through code:
myListView.HideSelection = false;
Use the open source okHttp
library from Square. okHttp
works from Android 2.3 and up and has an Apache 2.0 license on GitHub.
Sending POST data is as simple as adding the following in an AsyncTask:
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("email", emailString) // A sample POST field
.add("comment", commentString) // Another sample POST field
.build();
Request request = new Request.Builder()
.url("https://yourdomain.org/callback.php") // The URL to send the data to
.post(formBody)
.build();
okHttp
also has a namespace on maven, so adding it to your Android Studio project is simple. Just add compile 'com.squareup.okhttp3:okhttp:3.11.0'
to your app's build.gradle.
Complete Code
Add the following to your activity:
public class CallAPI extends AsyncTask<String, String, String> {
String emailString;
String commentString;
public CallAPI(String email, String commnt){
emailString = email;
commentString = commnt;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("email", emailString) // A sample POST field
.add("comment", commentString) // Another sample POST field
.build();
Request request = new Request.Builder()
.url("https://yourdomain.org/callback.php") // The URL to send the data to
.post(formBody)
.build();
return "";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
And call it using:
new CallAPI(emailString, commentString).execute();
Example :
String teste = " 'Bauru '";
teste = teste.replaceAll(" ' ","");
JOptionPane.showMessageDialog(null,teste);
Okay, this topic is somewhat outdated, but as I found it on google and have a solution this might be interesting for someone:
Basically (of course) this is not possible on every http proxy but works on proxies allowing http connect on port 3690. This method is used by http proxies on port 443 to provide a way for secure https connections. If your administrator configures the proxy to open port 3690 for http connect you can setup your local machine to establish a tunnel through the proxy.
I just was in the need to check out some files from svn.openwrt.org within our companies network. An easy solution to create a tunnel is adding the following line to your /etc/hosts
127.0.0.1 svn.openwrt.org
Afterwards, you can use socat to create a tcp tunnel to a local port:
while true; do socat tcp-listen:3690 proxy:proxy.at.your.company:svn.openwrt.org:3690; done
You should execute the command as root. It opens the local port 3690 and on connection creates a tunnel to svn.openwrt.org on the same port.
Just replace the port and server addresses on your own needs.
It is simple way to use scroll bar to table body
/* It is simple way to use scroll bar to table body*/
table tbody {
display: block;
max-height: 300px;
overflow-y: scroll;
}
table thead, table tbody tr {
display: table;
width: 100%;
table-layout: fixed;
}
_x000D_
<table>
<thead>
<th>Invoice Number</th>
<th>Purchaser</th>
<th>Invoice Amount</th>
<th>Invoice Date</th>
</thead>
<tbody>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
<tr>
<td>INV-1233</td>
<td>Dinesh Vaitage</td>
<td>$300</td>
<td>01/12/2017</td>
</tr>
</tbody>
</table>
_x000D_
--UPDATED--
To download the file first get youtube-dl
for python from here:
youtube-dl: https://rg3.github.io/youtube-dl/download.html
or install it with pip
:
sudo python2.7 -m pip install --upgrade youtube_dl
# or
# sudo python3.6 -m pip install --upgrade youtube_dl
UPDATE:
I just found out this:
Right click on the file you want to download from drive.google.com
Click Get Sharable link
Toggle On Link sharing on
Click on Sharing settings
Click on the top dropdown for options
Click on More
Select [x] On - Anyone with a link
Copy Link
https://drive.google.com/file/d/3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR/view?usp=sharing
(This is not a real file address)
Copy the id after https://drive.google.com/file/d/
:
3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR
Paste this into command line:
youtube-dl https://drive.google.com/open?id=
Paste the id behind open?id=
youtube-dl https://drive.google.com/open?id=3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR
[GoogleDrive] 3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR: Downloading webpage
[GoogleDrive] 3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR: Requesting source file
[download] Destination: your_requested_filename_here-3PIY9dCoWRs-930HHvY-3-FOOPrIVoBAR
[download] 240.37MiB at 2321.53MiB/s (00:01)
Hope it helps
Here is a function that works with jQuery (for height only, not width):
function setHeight(jq_in){
jq_in.each(function(index, elem){
// This line will work with pure Javascript (taken from NicB's answer):
elem.style.height = elem.scrollHeight+'px';
});
}
setHeight($('<put selector here>'));
Note: The op asked for a solution that does not use Javascript, however this should be helpful to many people who come across this question.
There is a jquery plugin available on github that probably just do what you want. It is called jquery-quickfit. It uses Jquery to provide a quick and dirty approach to fitting text into its surrounding container.
HTML:
<div id="quickfit">Text to fit*</div>
Javascript:
<script src=".../jquery.min.js" type="text/javascript" />
<script src="../script/jquery.quickfit.js" type="text/javascript" />
<script type="text/javascript">
$(function() {
$('#quickfit').quickfit();
});
</script>
More information: https://github.com/chunksnbits/jquery-quickfit
this will make the powershell window to wait until you press any key:
pause
Update One
Thanks to Stein. it is the Enter key not any key.
pip
is installed automatically with python2 using brew:
brew install python3
pip3 --version
For me maven was downloading the dependency but was unable to add it to the classpath. I saw my .classpath of the project,it didnt have any maven-related entry. When I added
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/>
the issue got resolved for me.
Late to the party, but node-windows will do the trick too.
It also has system logging built in.
There is an API to create scripts from code, i.e.
var Service = require('node-windows').Service;
// Create a new service object
var svc = new Service({
name:'Hello World',
description: 'The nodejs.org example web server.',
script: 'C:\\path\\to\\helloworld.js'
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
svc.install();
FD: I'm the author of this module.
I tried the code provided by Ranadheer Reddy (above) and it worked great. If you’re using a company computer that has a restricted server you may need to change the SMTP port to 25 and leave your username and password blank since they will auto fill by your admin.
Originally, I tried using EASendMail from the nugent package manager, only to realize that it’s a pay for version with 30-day trial. Don’t waist your time with it unless you plan on buying it. I noticed the program ran much faster using EASendMail, but for me, free trumped fast.
Just my 2 cents worth.
Em dash style:
ul.emdash {
list-style-type: none;
list-style-position: inside;
text-indent: -1.25em;
}
ul.emdash > li:before {
content: "\2014\00A0"; /* em dash + space*/
}
You can always apply CCS class with rotate
property - http://css-tricks.com/snippets/css/text-rotation/
To keep rotated image within your div
dimensions you need to adjust CSS as well, there is no needs to use JavaScript except of adding class.
I just ran into this issue as well. There's an option to "refresh fields", which I found useful. What I didn't find intuitive at first was that one has to enter values used to execute the query in such a fashion as to refresh the fields. Once I figured this out, and refreshed the fields - things worked. The data sets and the shared dataset that's being called have to correlate.
You should \usepackage{longtable}
.
This is for format the date?
def format_date(day, month, year):
# {} betekent 'plaats hier stringvoorstelling van volgend argument'
return "{}/{}/{}".format(day, month, year)
SHA1
is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.
However, breaking a SHA1
hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.
So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.
As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod
eliminate information from your input. Suppose you calculate mod 5
and you get 0
. What was the input? Was it 0
, 5
or 500
? You see, you can't really 'go back' in this case.
Normally this error occurs when you invoke java by supplying the wrong arguments/options. In this case it should be the version
option.
java -version
So to double check you can always do java -help
, and see if the option exists. In this case, there is no option such as v
.
Not sure if there's terrible reasons to do this or not, but it seems to work with me on the latest version of Chrome/Firefox without any visible performance problems with quite a lot of elements on the page.
*:not(:hover)>.parent-hover-show{
display:none;
}
But this way, all you need is to apply parent-hover-show
to an element and the rest is taken care of, and you can keep whatever default display type you want without it always being "block" or making multiple classes for each type.
When you change files or add a new ones in repository you first must stage them.
git add <file>
or if you want to stage all
git add .
By doing this you are telling to git what files you want in your next commit. Then you do:
git commit -m 'your message here'
You use
git push origin master
where origin is the remote repository branch and master is your local repository branch.
Just used jiln's excellent answer from above, but needed to expand to split multiple columns. Thought I would share.
def splitDataFrameList(df,target_column,separator):
''' df = dataframe to split,
target_column = the column containing the values to split
separator = the symbol used to perform the split
returns: a dataframe with each entry for the target column separated, with each element moved into a new row.
The values in the other columns are duplicated across the newly divided rows.
'''
def splitListToRows(row, row_accumulator, target_columns, separator):
split_rows = []
for target_column in target_columns:
split_rows.append(row[target_column].split(separator))
# Seperate for multiple columns
for i in range(len(split_rows[0])):
new_row = row.to_dict()
for j in range(len(split_rows)):
new_row[target_columns[j]] = split_rows[j][i]
row_accumulator.append(new_row)
new_rows = []
df.apply(splitListToRows,axis=1,args = (new_rows,target_column,separator))
new_df = pd.DataFrame(new_rows)
return new_df
It turns out that OpenSSL is compiled and enabled in php 5.3 of XAMPP 1.7.2 and so no longer requires a separate extension dll.
However, you STILL need to enable it in your PHP.ini file the line extension=php_openssl.dll
Here, we can do this way as well:
//category [@name='category name']/author[contains(text(),'authorname')]
OR
//category [@name='category name']//author[contains(text(),'authorname')]
To Learn XPATH in detail please visit- selenium xpath in detail
No one touched on it yet but it is something that every PHP developer should be able to speak at length about: Why is register_globals
bad?
Take a look at JQuery Promises:
http://api.jquery.com/promise/
http://api.jquery.com/jQuery.when/
http://api.jquery.com/deferred.promise/
Refactor the code:
var dfd = new jQuery.Deferred(); function callBack(data) { dfd.notify(data); } // do the async call. myAsynchronousCall(param1, callBack); function doSomething(data) { // do stuff with data... } $.when(dfd).then(doSomething);
Do I even need a for loop to create a list?
No, you can (and in general circumstances should) use the built-in function range()
:
>>> range(1,5)
[1, 2, 3, 4]
i.e.
def naturalNumbers(n):
return range(1, n + 1)
Python 3's range()
is slightly different in that it returns a range
object and not a list, so if you're using 3.x wrap it all in list()
: list(range(1, n + 1))
.
This snippet will always throw a ConcurrentModificationException.
The rule is "You may not modify (add or remove elements from the list) while iterating over it using an Iterator (which happens when you use a for-each loop)".
JavaDocs:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
Hence if you want to modify the list (or any collection in general), use iterator, because then it is aware of the modifications and hence those will be handled properly.
Hope this helps.
#include <windows.h>
double PCFreq = 0.0;
__int64 CounterStart = 0;
void StartCounter()
{
LARGE_INTEGER li;
if(!QueryPerformanceFrequency(&li))
cout << "QueryPerformanceFrequency failed!\n";
PCFreq = double(li.QuadPart)/1000.0;
QueryPerformanceCounter(&li);
CounterStart = li.QuadPart;
}
double GetCounter()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return double(li.QuadPart-CounterStart)/PCFreq;
}
int main()
{
StartCounter();
Sleep(1000);
cout << GetCounter() <<"\n";
return 0;
}
This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).
The StartCounter()
function records the number of ticks the performance counter has in the CounterStart
variable. The GetCounter()
function returns the number of milliseconds since StartCounter()
was last called as a double, so if GetCounter()
returns 0.001 then it has been about 1 microsecond since StartCounter()
was called.
If you want to have the timer use seconds instead then change
PCFreq = double(li.QuadPart)/1000.0;
to
PCFreq = double(li.QuadPart);
or if you want microseconds then use
PCFreq = double(li.QuadPart)/1000000.0;
But really it's about convenience since it returns a double.
Unless you're part of the 0.1% of applications where using open
is an actual performance benefit, there really is no good reason not to use fopen
. As far as fdopen
is concerned, if you aren't playing with file descriptors, you don't need that call.
Stick with fopen
and its family of methods (fwrite
, fread
, fprintf
, et al) and you'll be very satisfied. Just as importantly, other programmers will be satisfied with your code.
Set CSS display property to none.
document.getElementById("test").style.display = "none";
Also, you do not need javascript:
for the onclick
attribute.
<input type="image" src="../images/btnFind.png" id="find" name="find"
onclick="hide();" />
Finally, make sure you do not have multiple elements with the same ID.
If your form goes nowhere, Phil suggested that you should prevent submission of the form. Simply return false
in the onsubmit handler.
<form method="post" id="test" onsubmit="return false;">
If you want the form to post, but hide the div on subsequent page load, you will have to use server-side code to hide the element:
<script type="text/javascript">
function hide() {
document.getElementById("test").style.display = "none";
}
window.onload = function() {
// if form was submitted, PHP will print the below,
// which runs function hide() on page load
<?= ($_POST['ampid'] != '') ? 'hide();' : '' ?>
}
</script>
Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this:
start "" "c:\path with spaces\app.exe" param1 "param with spaces"
You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter.
This maybe way off the track, but there are two things that spring to mind. Both of the following assume that you are running a 32bit version of Linux.
There is a process size limit on linux, seem to remember on CentOS was around 2.5gb and is configured in the kernel (i.e. a recomple to change). Your process might be hitting that once you add up all the JVM code + Permgen space and all the rest of the JVM libraries.
The second thing is something I've come across that you may be running out of address space, sounds wierd I know. Had a problem running Glassfish with a 1.5Gb heap, when it tried to complie a JSP my forking javac it would fail because the OS couldn't allocate enough address space for the newly created process even though there was 12gb of memory in the box. There may be something similar going on here.
I'm afraid the only solutions to the above two where to upgrade to a 64bit kernel.
Hope this is of some use.
When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p
flag to mkdir
... Please update your Dockerfile with
RUN mkdir -p ...
I tested this and it's correct.
<a href="javascript:call_func();">...</a>
where the function then has to return false so that the browser doesn't go to another page.
But I'd recommend to use jQuery (with $(...).click(function () {}))
)
try out this..
document.getElementById("edName").required = true;
Use the Java 8 solution. Note DatatypeConverter can still be used, but it is now within the java.xml.bind
module which will need to be included.
module org.example.foo {
requires java.xml.bind;
}
Java 8 now provides java.util.Base64
for encoding and decoding base64.
Encoding
byte[] message = "hello world".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=
Decoding
byte[] decoded = Base64.getDecoder().decode("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// => hello world
Since Java 6 the lesser known class javax.xml.bind.DatatypeConverter
can be used. This is part of the JRE, no extra libraries required.
Encoding
byte[] message = "hello world".getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=
Decoding
byte[] decoded = DatatypeConverter.parseBase64Binary("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, "UTF-8"));
// => hello world
Quoting the spec
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
And here's a table for typeof
To add some background, there are two data types in JavaScript:
An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.
An array can be considered to be an object with the following properties/keys:
Hope this helped shed more light on why typeof Array returns an object. Cheers!
.md
extension stands for Markdown, which Github uses, among others, to format those files.
Read about Markdown:
http://daringfireball.net/projects/markdown/
http://en.wikipedia.org/wiki/Markdown
Also:
If you are using an AMD CPU, AMD Virtualization (CPUs such as Ryzen) is now officially supported. Make sure you have virtualization switched on in the BIOS.
In "Turn Windows Features On or Off" (you can find it through Windows Search), you'll need to enable
Once you restart and start up the emulator (an x86 build), it should start booting up without the mentioned error.
Getting image resouse as InputStream without context:
Class<? extends MyClass> aClass = MyClass.class;
URL r = aClass.getResource("/res/raw/test.png");
URLConnection urlConnection = r.openConnection();
return new BufferedInputStream(urlConnection.getInputStream());
If you need derectory tree for your files, it will also works (assets supports sub-dirs):
URL r = aClass.getResource("/assets/images/base/2.png");
Firebug lite plugin in Safari extensions didn't work (it's made by slicefactory, I don't think it's offical). btw, #2 works for me!
Good way to solve this in Jquery manner
$("#dropDownMenuKategorie option:selected").index()
For me, what eventually did the trick was adding -clean
at the start of eclipse.ini
user double quote to get the exact value. like this:
echo "${var}"
and it will read your value correctly.
Bind to the change
event instead of click
. However, you will probably still need to check whether or not the checkbox is checked:
$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
}
});
The main benefit of binding to the Redacted in commentschange
event over the click
event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change
event.
Also note that I've used this.checked
instead of wrapping the element in a jQuery object and using jQuery methods, simply because it's shorter and faster to access the property of the DOM element directly.
Edit (see comments)
To get all checkboxes you have a couple of options. You can use the :checkbox
pseudo-selector:
$(":checkbox")
Or you could use an attribute equals selector:
$("input[type='checkbox']")
There is no forumula, as street names and cities are essentially handed out randomly. The address needs to be looked up in a database. Alternatively, you can look up a zip code in a database for the region that the zip code is for.
You didn't mention a country, so I'm going to assume you just want addresses in the USA. There are numerous databases you can use, some free, some not.
You can also use the Google Maps API to have them look up an address in their database for you. That is probably the easiest solution, but requires your application to have a working internet connection at all times.
Specially use this on newsletter -
<sup style="font-size:9px; line-height:8px;">®</sup>
use if var is null
To say that something "is null" means that it is a reference to the null value. Primitives (int, double, float, etc) are by definition not reference types, so they cannot have null values. You will need to find out what your database wrapper will do in this case.
Try this:
CSS
.style1{
background-color:red;
color:white;
font-size:44px;
}
HTML
<div id="foo">hello world!</div>
<img src="zoom.png" onclick="myFunction()" />
Javascript
function myFunction()
{
document.getElementById('foo').setAttribute("class", "style1");
}
I chose to use System.Web.Script.Serialization.JavaScriptSerializer
.
I have a small static helper class defined as follows:
internal static partial class Serialization
{
static JavaScriptSerializer serializer;
static Serialization()
{
serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
}
public static string ToJSON<T>(T obj)
{
return serializer.Serialize(obj);
}
public static T FromJSON<T>(string data)
{
if (Common.IsEmpty(data))
return default(T);
else
return serializer.Deserialize<T>(data);
}
}
To serialize anything I just call Serialization.ToJSON(itemToSerialize)
To deserialize I just call Serialization.FromJSON<T>(jsonValueOfTypeT)
for any Element type
extension Array {
func joined(glue:()->Element)->[Element]{
var result:[Element] = [];
result.reserveCapacity(count * 2);
let last = count - 1;
for (ix,item) in enumerated() {
result.append(item);
guard ix < last else{ continue }
result.append(glue());
}
return result;
}
}
In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml
), you can do so by just putting an array of mappings in the @WebFilter
annotation:
/**
* Filter implementation class LoginFilter
*/
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
...
And just as an FYI, this same thing works for servlets using the servlet annotation too:
/**
* Servlet implementation class LoginServlet
*/
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
...
Here you go. this should work.
questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7)
answerFrame.frame = CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)
void f(const double& v = *(double*) NULL)
{
if (&v == NULL)
cout << "default" << endl;
else
cout << "other " << v << endl;
}
If you're using application.properties in spring boot app, then just put the below line into application.properties and it should work:
spring.datasource.url: jdbc:mysql://google/?cloudSqlInstance=&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=****&password=****
You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.
1) Give Alphas a Beta in the constructor. In class Alpha write:
public class Alpha {
private Beta beta;
public Alpha(Beta beta) {
this.beta = beta;
}
and call cAlpha = new Alpha(cBeta) from main()
2) give Alphas a mutator that gives them a beta. In class Alpha write:
public class Alpha {
private Beta beta;
public void setBeta (Beta newBeta) {
this.beta = beta;
}
and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or
3) have a beta as an argument to doSomethingAlpha. in class Alpha write:
public void DoSomethingAlpha(Beta cBeta) {
cbeta.DoSomethingBeta()
}
Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!
Try this
Get-ChildItem | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }
In your code,
$build-Config
is not a valid variable name. $.FullName
should be $_.FullName
$
should be $_.Name
First Way:
In Kotlin we can create a simple extension for view:
fun View.getLocationOnScreen(): Point
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return Point(location[0],location[1])
}
And simply get coordinates:
val location = yourView.getLocationOnScreen()
val absX = location.x
val absY = location.y
Second Way:
The Second way is more simple :
fun View.absX(): Int
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return location[0]
}
fun View.absY(): Int
{
val location = IntArray(2)
this.getLocationOnScreen(location)
return location[1]
}
and simply get absolute X by view.absX()
and Y by view.absY()
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
string rootNode = XmlDoc.ChildNodes[0].Name;
instead of onmouseout use onmouseleave.
You haven't showed to us your specific code so I cannot show you on your specific example how to do it.
But it is very simple: just replace onmouseout with onmouseleave.
That's all :) So, simple :)
If not sure how to do it, see explanation on:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmousemove_leave_out
Peace of cake :) Enjoy it :)
I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:
inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
int curRow = r * sectors;
int nextRow = (r+1) * sectors;
indices.push_back(curRow + s);
indices.push_back(nextRow + s);
indices.push_back(nextRow + (s+1));
indices.push_back(curRow + s);
indices.push_back(nextRow + (s+1));
indices.push_back(curRow + (s+1));
}
void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
float radius, unsigned int rings, unsigned int sectors)
{
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
for(int r = 0; r < rings; ++r) {
for(int s = 0; s < sectors; ++s) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
texcoords.push_back(vec2(s*S, r*R));
vertices.push_back(vec3(x,y,z) * radius);
push_indices(indices, sectors, r, s);
}
}
}
If you want the effect of a nested for loop, use:
import itertools
for i, j in itertools.product(range(x), range(y)):
# Stuff...
If you just want to loop simultaneously, use:
for i, j in zip(range(x), range(y)):
# Stuff...
Note that if x
and y
are not the same length, zip
will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest
.
UPDATE
Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip
or product
. I think they want a set
:
def equal_elements(t1, t2):
return list(set(t1).intersection(set(t2)))
# You could also do
# return list(set(t1) & set(t2))
The intersection
method of a set
will return all the elements common to it and another set (Note that if your lists contains other list
s, you might want to convert the inner list
s to tuples
first so that they are hashable; otherwise the call to set
will fail.). The list
function then turns the set back into a list.
UPDATE 2
OR, the OP might want elements that are identical in the same position in the lists. In this case, zip
would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:
def equal_elements(t1, t2):
return [x for x, y in zip(t1, t2) if x == y]
This will return a list containing only the elements that are the same and in the same position in the lists.
This code snippet from Convert Datatable to JSON String in C#, VB.NET might help you. It uses System.Web.Script.Serialization.JavaScriptSerializer to serialize the contents to JSON format:
public string ConvertDataTabletoString()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=master;Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,description from LocationDetails", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
}
As a good example may be worth it to navigate to this project and see how to handle exiting processes grammatically or in this snippet from VM found in here
ConsoleOutputStream = new ObservableCollection<string>();
var startInfo = new ProcessStartInfo(FilePath)
{
WorkingDirectory = RootFolderPath,
Arguments = StartingArguments,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
ConsoleProcess = new Process {StartInfo = startInfo};
ConsoleProcess.EnableRaisingEvents = true;
ConsoleProcess.OutputDataReceived += (sender, args) =>
{
App.Current.Dispatcher.Invoke((System.Action) delegate
{
ConsoleOutputStream.Insert(0, args.Data);
//ConsoleOutputStream.Add(args.Data);
});
};
ConsoleProcess.Exited += (sender, args) =>
{
InProgress = false;
};
ConsoleProcess.Start();
ConsoleProcess.BeginOutputReadLine();
}
}
private void RegisterProcessWatcher()
{
startWatch = new ManagementEventWatcher(
new WqlEventQuery($"SELECT * FROM Win32_ProcessStartTrace where ProcessName = '{FileName}'"));
startWatch.EventArrived += new EventArrivedEventHandler(startProcessWatch_EventArrived);
stopWatch = new ManagementEventWatcher(
new WqlEventQuery($"SELECT * FROM Win32_ProcessStopTrace where ProcessName = '{FileName}'"));
stopWatch.EventArrived += new EventArrivedEventHandler(stopProcessWatch_EventArrived);
}
private void stopProcessWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
InProgress = false;
}
private void startProcessWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
InProgress = true;
}
If you are sure there are no leading spaces, you can use bash parameter substitution:
$ string="word1 word2"
$ echo ${string/%\ */}
word1
Watch out for escaping the single space. See here for more examples of substitution patterns. If you have bash > 3.0, you could also use regular expression matching to cope with leading spaces - see here:
$ string=" word1 word2"
$ [[ ${string} =~ \ *([^\ ]*) ]]
$ echo ${BASH_REMATCH[1]}
word1
You're almost there. As you can see, the onItemSelected
will give you a position
parameter, you can use this to retrieve the object from your adapter, as in getItemAtPosition(position)
.
Example:
spinner.setOnItemSelectedListener(this);
...
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
This will put a message on screen, with the selected item printed by its toString() method.
This is how the JDK does it (adapted from OpenJDK 8, String.java/regionMatches):
static boolean charactersEqualIgnoringCase(char c1, char c2) {
if (c1 == c2) return true;
// If characters don't match but case may be ignored,
// try converting both characters to uppercase.
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2) return true;
// Unfortunately, conversion to uppercase does not work properly
// for the Georgian alphabet, which has strange rules about case
// conversion. So we need to make one last check before
// exiting.
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
I suppose that works for Turkish too.
I found this easier to understand:
List<string> names = new List<string> { "One", "Two", "Three", "Four", "Five" };
for (int i = 0; i < names.Count; i++)
{
Console.WriteLine(names[i]);
}
No, Not if your website is on a remote server, i.e not on localhost.
There are a few base64 encoders online to help you with this, this is probably the best I've seen:
http://www.greywyvern.com/code/php/binary2base64
As that page shows your main options for this are CSS:
div.image {
width:100px;
height:100px;
background-image:url(data:image/png;base64,iVBORwA<MoreBase64SringHere>);
}
Or the <img>
tag itself, like this:
<img alt="My Image" src="data:image/png;base64,iVBORwA<MoreBase64SringHere>" />
Its not a good idea to pass Context
objects around. This often will lead to memory leaks. My suggestion is that you don't do it. I have made numerous Android apps without having to pass context to non-activity classes in the app. A better idea would be to get the resources you need access to while your in the Activity
or Fragment
, and hold onto it in another class. You can then use that class in any other classes in your app to access the resources, without having to pass around Context
objects.
How about this:
SELECT MONTH('March' + ' 1 2014')
Would return 3
.
First make sure you have installed Nginx with the HTTP rewrite module. To install this we need to have pcre-library
If the above mentioned are done or if you already have them, then just add the below code in your nginx server block
if ($host !~* ^www\.) {
rewrite ^(.*)$ http://www.$host$1 permanent;
}
To remove www from every request you can use
if ($host = 'www.your_domain.com' ) {
rewrite ^/(.*)$ http://your_domain.com/$1 permanent;
}
so your server block will look like
server {
listen 80;
server_name test.com;
if ($host !~* ^www\.) {
rewrite ^(.*)$ http://www.$host$1 permanent;
}
client_max_body_size 10M;
client_body_buffer_size 128k;
root /home/test/test/public;
passenger_enabled on;
rails_env production;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
if you are using centOs then use
sudo chown -R centos:centos /var/www/html
sudo chmod -R 755 /var/www/html
For Ubuntu
sudo chown -R ubuntu:ubuntu /var/www/html
sudo chmod -R 755 /var/www/html
For Amazon ami
sudo chown -R ec2-user:ec2-user /var/www/html
sudo chmod -R 755 /var/www/html
In addition to running it with mvn exec:java
, you can also run it with mvn exec:exec
mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"
Try purge
sudo aptitude purge phpmyadmin
Not sure this works with plain old apt-get
though
Here is another try:
function stringToColor(str){
var hash = 0;
for(var i=0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 3) - hash);
}
var color = Math.abs(hash).toString(16).substring(0, 6);
return "#" + '000000'.substring(0, 6 - color.length) + color;
}
XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:
[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"
Sendmail should have a sendmail.ini
with it; it should be configured as so:
# Example for a user configuration file
# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"
# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off
# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE
# Set a default account
account default : ACCOUNTNAME_HERE
Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.
It's not possible in Postman yet; But there is a new alternative for Postman, named Postwoman. it's open source and supports realtime Websocket and SSE requests.
Update
It seems they have rebranded Postwoman to Hoppscotch and have improved the Websocket support.
Android Studio Works Perfectly fine with Java 1.8
or Java 8
. I was also having invalid JVM error. The reason was including ";" (semicolon) at the end of JAVA_HOME
path value. The correct format for path value is:
C:\Program Files\Java\jdk1.8.0_xx (Replace xx with your current version)
Do not include ;
(semicolon) at the end of JAVA_HOME
value
min-width
and max-width
properties do not work the way you expect for table cells. From spec:
In CSS 2.1, the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.
This hasn't changed in CSS3.
I'm not entirely sold on the use of IDEs. However, I think that the most valuable aspect of a good IDE, like Eclipse, is the well-integrated Cscope-style functionality rapid comprehension of a large code base.
For example, in Eclipse, you see a method takes an argument of type FooBar, yet you have no idea what it means. Rather than waste a minute finding the definition the hard way (and risk all sorts of distractions along the way), just select FooBar, hit F3, and it opens the relevant source file to the very line that FooBar is defined.
The downside of IDEs, in my opinion, is that they give you a bigger learning curve, except in the case in which you want to use the absolutely default configuration. (This is true for Emacs as well.)
I really needed to do this dirty thing... Here is how
I redefined those dependencies with scope test
. Scope provided
did not work for me.
We use spring Boot plugin to build fat jar. We have module common which defines common libraries, for example Springfox swagger-2. My super-service needs to have parent common (it does not want to do so, but company rules force!)
So my parent or commons has pom.
<dependencyManagement>
<!- I do not need Springfox in one child but in others ->
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>${swagger.version}</version>
</dependency>
<!- All services need them ->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${apache.poi.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
And my super-service pom.
<name>super-service</name>
<parent>
<groupId>com.company</groupId>
<artifactId>common</artifactId>
<version>1</version>
</parent>
<dependencies>
<!- I don't need them ->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-core</artifactId>
<version>2.8.0</version>
<scope>test</scope>
</dependency>
<!- Required dependencies ->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
</dependencies>
This is size of the final fat artifact
82.3 MB (86,351,753 bytes) - redefined dependency with scope test
86.1 MB (90,335,466 bytes) - redefined dependency with scope provided
86.1 MB (90,335,489 bytes) - without exclusion
Also this answer is worth mentioning - I wanted to do so, but I am lazy... https://stackoverflow.com/a/48103554/4587961
I would prefer to store the image in a directory, then store a reference to the image file in the database.
However, if you do store the image in the database, you should partition your database so the image column resides in a separate file.
You can read more about using filegroups here http://msdn.microsoft.com/en-us/library/ms179316.aspx.
In WinForms and WebForms you can do:
txtName.BackColor = Color.Aqua;
I don't know exactly what yum install java
will actually install. But to check for javac existence do:
> updatedb
> locate javac
preferably as root. If it's not there you've probably only installed the Java runtime (JRE) and not the Java Development Kit (JDK). You're best off getting this from the Oracle site: as the Linux repos may be slightly behind with latest versions and also they seem to only supply the open-jdk as opposed to the Oracle/Sun one, which I would prefer given the choice.
Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.
What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.
http://developer.android.com/guide/topics/ui/custom-components.html
I had the same error when connecting to Mongo on AWS EC2 . This is what solved it https://serverfault.com/a/347159/62381 Remove the bind_ip from the config file
categories = ['sprots', 'news'];
categoriesList = ", ".join(categories)
print(categoriesList)
This is the output: sprots, news
I used Retrofit 2.0 for my register users, send multipart/form File image and text from register account
In my RegisterActivity, use an AsyncTask
//AsyncTask
private class Register extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {..}
@Override
protected String doInBackground(String... params) {
new com.tequilasoft.mesasderegalos.dbo.Register().register(txtNombres, selectedImagePath, txtEmail, txtPassword);
responseMensaje = StaticValues.mensaje ;
mensajeCodigo = StaticValues.mensajeCodigo;
return String.valueOf(StaticValues.code);
}
@Override
protected void onPostExecute(String codeResult) {..}
And in my Register.java class is where use Retrofit with synchronous call
import android.util.Log;
import com.tequilasoft.mesasderegalos.interfaces.RegisterService;
import com.tequilasoft.mesasderegalos.utils.StaticValues;
import com.tequilasoft.mesasderegalos.utils.Utilities;
import java.io.File;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
/**Created by sam on 2/09/16.*/
public class Register {
public void register(String nombres, String selectedImagePath, String email, String password){
try {
// create upload service client
RegisterService service = ServiceGenerator.createUser(RegisterService.class);
// add another part within the multipart request
RequestBody requestEmail =
RequestBody.create(
MediaType.parse("multipart/form-data"), email);
// add another part within the multipart request
RequestBody requestPassword =
RequestBody.create(
MediaType.parse("multipart/form-data"), password);
// add another part within the multipart request
RequestBody requestNombres =
RequestBody.create(
MediaType.parse("multipart/form-data"), nombres);
MultipartBody.Part imagenPerfil = null;
if(selectedImagePath!=null){
File file = new File(selectedImagePath);
Log.i("Register","Nombre del archivo "+file.getName());
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
imagenPerfil = MultipartBody.Part.createFormData("imagenPerfil", file.getName(), requestFile);
}
// finally, execute the request
Call<ResponseBody> call = service.registerUser(imagenPerfil, requestEmail,requestPassword,requestNombres);
Response<ResponseBody> bodyResponse = call.execute();
StaticValues.code = bodyResponse.code();
StaticValues.mensaje = bodyResponse.message();
ResponseBody errorBody = bodyResponse.errorBody();
StaticValues.mensajeCodigo = errorBody==null
?null
:Utilities.mensajeCodigoDeLaRespuestaJSON(bodyResponse.errorBody().byteStream());
Log.i("Register","Code "+StaticValues.code);
Log.i("Register","mensaje "+StaticValues.mensaje);
Log.i("Register","mensajeCodigo "+StaticValues.mensaje);
}
catch (Exception e){
e.printStackTrace();
}
}
}
In the interface of RegisterService
public interface RegisterService {
@Multipart
@POST(StaticValues.REGISTER)
Call<ResponseBody> registerUser(@Part MultipartBody.Part image,
@Part("email") RequestBody email,
@Part("password") RequestBody password,
@Part("nombre") RequestBody nombre
);
}
For the Utilities parse ofr InputStream response
public class Utilities {
public static String mensajeCodigoDeLaRespuestaJSON(InputStream inputStream){
String mensajeCodigo = null;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
inputStream.close();
mensajeCodigo = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return mensajeCodigo;
}
}
Just move it :)
command line :
move "C:\Documents and Setings\$USER\project" C:\project
or just drag the folder in explorer.
Git won't care where it is - all the metadata for the repository is inside a folder called .git
inside your project folder.
Thanks to @marmor, I updated my answer.
I think it's a good solution to handle the onClick() in the ViewHolder class constructor and pass it to the parent class via OnItemClickListener interface.
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private LayoutInflater layoutInflater;
private List<MyObject> items;
private AdapterView.OnItemClickListener onItemClickListener;
public MyAdapter(Context context, AdapterView.OnItemClickListener onItemClickListener, List<MyObject> items) {
layoutInflater = LayoutInflater.from(context);
this.items = items;
this.onItemClickListener = onItemClickListener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.my_row_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
MyObject item = items.get(position);
}
public MyObject getItem(int position) {
return items.get(position);
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView title;
private ImageView avatar;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title);
avatar = itemView.findViewById(R.id.avatar);
title.setOnClickListener(this);
avatar.setOnClickListener(this);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
//passing the clicked position to the parent class
onItemClickListener.onItemClick(null, view, getAdapterPosition(), view.getId());
}
}
}
Usage of adapter in other classes:
MyFragment.java
public class MyFragment extends Fragment implements AdapterView.OnItemClickListener {
private RecyclerView recycleview;
private MyAdapter adapter;
.
.
.
private void init(Context context) {
//passing this fragment as OnItemClickListener to the adapter
adapter = new MyAdapter(context, this, items);
recycleview.setAdapter(adapter);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//you can get the clicked item from the adapter using its position
MyObject item = adapter.getItem(position);
//you can also find out which view was clicked
switch (view.getId()) {
case R.id.title:
//title view was clicked
break;
case R.id.avatar:
//avatar view was clicked
break;
default:
//the whole row was clicked
}
}
}
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
public interface A
{
}
public class B implements A
{
}
public static void main(String[] args)
{
A test = new B();
//A test = new A(); // wont compile
}
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test
.
By using exploits or on badly configured servers it could be possible to download your PHP source. You could however either obfuscate and/or encrypt your code (using Zend Guard, Ioncube or a similar app) if you want to make sure your source will not be readable (to be accurate, obfuscation by itself could be reversed given enough time/resources, but I haven't found an IonCube or Zend Guard decryptor yet...).
I'd just use zip
:
In [1]: from pandas import *
In [2]: def calculate(x):
...: return x*2, x*3
...:
In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})
In [4]: df
Out[4]:
a b
0 1 2
1 2 3
2 3 4
In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))
In [6]: df
Out[6]:
a b A1 A2
0 1 2 2 3
1 2 3 4 6
2 3 4 6 9
I think Compiling Python Code would be a good place to start:
Python source code is automatically compiled into Python byte code by the CPython interpreter. Compiled code is usually stored in PYC (or PYO) files, and is regenerated when the source is updated, or when otherwise necessary.
To distribute a program to people who already have Python installed, you can ship either the PY files or the PYC files. In recent versions, you can also create a ZIP archive containing PY or PYC files, and use a small “bootstrap script” to add that ZIP archive to the path.
To “compile” a Python program into an executable, use a bundling tool, such as Gordon McMillan’s installer (alternative download) (cross-platform), Thomas Heller’s py2exe (Windows), Anthony Tuininga’s cx_Freeze (cross-platform), or Bob Ippolito’s py2app (Mac). These tools puts your modules and data files in some kind of archive file, and creates an executable that automatically sets things up so that modules are imported from that archive. Some tools can embed the archive in the executable itself.
File name should match the layout id which in this example is : items_list_item.xml in the layout folder of your application
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView android:id="@+id/R.id.list_item_image"
android:layout_width="100dip"
android:layout_height="wrap_content" />
</LinearLayout>
Basically, if you require a wrong path, PHP throws a fatal error and the shutdown function is called, but when you include a wrong path, PHP will continue execution, but it will just display a warning that the file does not exist.
From the English word require, PHP is told that the execution of the page or file depends on the file required.
From my experience, it's norm to require important files such as configuration files, database classes and other important utilities.
I got rid of the problem by unchecking the option for "Alert before overwriting cells" in Excel options. I'm using Excel 2007
create database if not exists `test`;
USE `test`;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
/*Table structure for table `test` */
***CREATE TABLE IF NOT EXISTS `tblsample` (
`id` int(11) NOT NULL auto_increment,
`recid` int(11) NOT NULL default '0',
`cvfilename` varchar(250) NOT NULL default '',
`cvpagenumber` int(11) NULL,
`cilineno` int(11) NULL,
`batchname` varchar(100) NOT NULL default '',
`type` varchar(20) NOT NULL default '',
`data` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
);***
It will work for any object. Even if you don't know the size:
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
If you wirte to a .csv file in C++ - you should use the syntax of :
myfile <<" %s; %s; %d", string1, string2, double1 <<endl;
This will write the three variables (string 1&2 and double1) into separate columns and leave an empty row below them. In excel the ; means the new row, so if you want to just take a new row - you can alos write a simple ";" before writing your new data into the file. If you don't want to have an empty row below - you should delete the endl and use the:
myfile.open("result.csv", std::ios::out | std::ios::app);
syntax when opening the .csv file (example the result.csv). In this way next time you write something into your result.csv file - it will write it into a new row directly below the last one - so you can easily manage a for cycle if you would like to.
First, you can always grab the current time by
var currentTime = new Date();
Then you could check out this "pretty date" example at http://www.zachleat.com/Lib/jquery/humane.js
If that doesn't work for you, just google "javascript pretty date" and you'll find dozens of example scripts.
Good luck.
Using INSTR:
SELECT *
FROM TABLE a
JOIN TABLE b ON INSTR(b.column, a.column) > 0
Using LIKE:
SELECT *
FROM TABLE a
JOIN TABLE b ON b.column LIKE '%'+ a.column +'%'
Using LIKE, with CONCAT:
SELECT *
FROM TABLE a
JOIN TABLE b ON b.column LIKE CONCAT('%', a.column ,'%')
Mind that in all options, you'll probably want to drive the column values to uppercase BEFORE comparing to ensure you are getting matches without concern for case sensitivity:
SELECT *
FROM (SELECT UPPER(a.column) 'ua'
TABLE a) a
JOIN (SELECT UPPER(b.column) 'ub'
TABLE b) b ON INSTR(b.ub, a.ua) > 0
The most efficient will depend ultimately on the EXPLAIN plan output.
JOIN
clauses are identical to writing WHERE
clauses. The JOIN
syntax is also referred to as ANSI JOINs because they were standardized. Non-ANSI JOINs look like:
SELECT *
FROM TABLE a,
TABLE b
WHERE INSTR(b.column, a.column) > 0
I'm not going to bother with a Non-ANSI LEFT JOIN example. The benefit of the ANSI JOIN syntax is that it separates what is joining tables together from what is actually happening in the WHERE
clause.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
WebElement e = driver.findElement(By
.xpath("html/body/header/div/div[1]/nav/a"));
e.sendKeys(selectLinkOpeninNewTab);//to open the link in a current page in to the browsers new tab
e.sendKeys(Keys.CONTROL + "\t");//to move focus to next tab in same browser
try {
Thread.sleep(8000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//to wait some time in that tab
e.sendKeys(Keys.CONTROL + "\t");//to switch the focus to old tab again
Hope it helps to you..
Usually Header file syntax start with capital letter.I found that code written all in smaller letter
#ifndef DIAG_H
#define DIAG_H
#endif
var jQueryObject = $('<div></div>').html( string ).children();
This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.
Change
Range(DataImportColumn & DataImportRow).Offset(0, 2).Value
to
Cells(DataImportRow,DataImportColumn).Value
When you just have the row and the column then you can use the cells()
object. The syntax is Cells(Row,Column)
Also one more tip. You might want to fully qualify your Cells
object. for example
ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value
This can be massively simplified with just 1 line of code in viewDidAppear:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableViewHeightConstraint.constant = tableView.contentSize.height
}
Here's what worked for me to copy and overwrite a file from B:\ to Z:\ drive in a batch script.
echo F| XCOPY B:\utils\MyFile.txt Z:\Backup\CopyFile.txt /Y
The "/Y" parameter at the end overwrites the destination file, if it exists.
sample code show custom dialog in kotlin:
fun showDlgFurtherDetails(context: Context,title: String?, details: String?) {
val dialog = Dialog(context)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setCancelable(false)
dialog.setContentView(R.layout.dlg_further_details)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
val lblService = dialog.findViewById(R.id.lblService) as TextView
val lblDetails = dialog.findViewById(R.id.lblDetails) as TextView
val imgCloseDlg = dialog.findViewById(R.id.imgCloseDlg) as ImageView
lblService.text = title
lblDetails.text = details
lblDetails.movementMethod = ScrollingMovementMethod()
lblDetails.isScrollbarFadingEnabled = false
imgCloseDlg.setOnClickListener {
dialog.dismiss()
}
dialog.show()
}
Using a simple list-comprehension
and the sum
:
>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5
I believe there is a simpler solution.
You must use Html.Hidden
instead of Html.HiddenFor
. Look:
@Html.Hidden("CRN", ViewData["crn"]);
This will create an INPUT
tag of type="hidden"
, with id="CRN"
and name="CRN"
, and the correct value inside the value
attribute.
Hope it helps!
Refer this link for linux command linux http://linuxcommand.org/man_pages/grep1.html
for displaying line no ,line of code and file use this command in your terminal or cmd, GitBash(Powered by terminal)
grep -irn "YourStringToBeSearch"
There is a new easy and very cool tool (10x to Kfir): xcelite
Write:
public class User {
@Column (name="Firstname")
private String firstName;
@Column (name="Lastname")
private String lastName;
@Column
private long id;
@Column
private Date birthDate;
}
Xcelite xcelite = new Xcelite();
XceliteSheet sheet = xcelite.createSheet("users");
SheetWriter<User> writer = sheet.getBeanWriter(User.class);
List<User> users = new ArrayList<User>();
// ...fill up users
writer.write(users);
xcelite.write(new File("users_doc.xlsx"));
Read:
Xcelite xcelite = new Xcelite(new File("users_doc.xlsx"));
XceliteSheet sheet = xcelite.getSheet("users");
SheetReader<User> reader = sheet.getBeanReader(User.class);
Collection<User> users = reader.read();
Just figured this out after trying numerous things. What finally did it for me was adding require('dotenv').config()
to my .sequelizerc
file. Apparently sequelize-cli doesn't read env variables.
You can't. and the reason is that they do not "live" in the same time. The Razor variables are "Server side variables" and they don't exist anymore after the page was sent to the "Client side".
When the server get a request for a view, it creates the view with only HTML, CSS and Javascript code. No C# code is left, it's all get "translated" to the client side languages.
The Javascript code DOES exist when the view is still on the server, but it's meaningless and will be executed by the browser only (Client side again).
This is why you can use Razor variables to change the HTML and Javascript but not vice versa. Try to look at your page source code (CTRL+U in most browsers), there will be no sign of C# code there.
In short:
The server gets a request.
The server creates or "takes" the view, then computes and translates all the C# code that was embedded in the view to CSS, Javascript, and HTML.
The server returns the client side version of the view to the browser as a response to the request. (there is no C# at this point anymore)
the browser renders the page and executes all the Javascript
@echo off
cd "folder directory to your file"
start filename.ext
For example:
cd "C:\Program Files (x86)\Winamp"
Start winamp.exe
You might want to try to append this to your command
>/dev/null 2>/dev/null &
eg.
shell_exec('service named reload >/dev/null 2>/dev/null &');
You can simply use use $parent.$index .where parent will represent object of parent repeating object .
Answers given above are perfect but I suggest to use multiple smaller regex rather than a big one.
Splitting the long regex have some advantages:
Generally this approach keep code easily maintainable.
Having said that, I share a piece of code that I write in Swift as example:
struct RegExp {
/**
Check password complexity
- parameter password: password to test
- parameter length: password min length
- parameter patternsToEscape: patterns that password must not contains
- parameter caseSensitivty: specify if password must conforms case sensitivity or not
- parameter numericDigits: specify if password must conforms contains numeric digits or not
- returns: boolean that describes if password is valid or not
*/
static func checkPasswordComplexity(password password: String, length: Int, patternsToEscape: [String], caseSensitivty: Bool, numericDigits: Bool) -> Bool {
if (password.length < length) {
return false
}
if caseSensitivty {
let hasUpperCase = RegExp.matchesForRegexInText("[A-Z]", text: password).count > 0
if !hasUpperCase {
return false
}
let hasLowerCase = RegExp.matchesForRegexInText("[a-z]", text: password).count > 0
if !hasLowerCase {
return false
}
}
if numericDigits {
let hasNumbers = RegExp.matchesForRegexInText("\\d", text: password).count > 0
if !hasNumbers {
return false
}
}
if patternsToEscape.count > 0 {
let passwordLowerCase = password.lowercaseString
for pattern in patternsToEscape {
let hasMatchesWithPattern = RegExp.matchesForRegexInText(pattern, text: passwordLowerCase).count > 0
if hasMatchesWithPattern {
return false
}
}
}
return true
}
static func matchesForRegexInText(regex: String, text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
}
I also got the error you mention:
CMake Error: CMake can not determine linker language for target:helloworld
CMake Error: Cannot determine link language for target "helloworld".
In my case this was due to having C++ files with the .cc
extension.
If CMake is unable to determine the language of the code correctly you can use the following:
set_target_properties(hello PROPERTIES LINKER_LANGUAGE CXX)
The accepted answer that suggests appending the language to the project()
statement simply adds more strict checking for what language is used (according to the documentation), but it wasn't helpful to me:
Optionally you can specify which languages your project supports. Example languages are CXX (i.e. C++), C, Fortran, etc. By default C and CXX are enabled. E.g. if you do not have a C++ compiler, you can disable the check for it by explicitly listing the languages you want to support, e.g. C. By using the special language "NONE" all checks for any language can be disabled. If a variable exists called CMAKE_PROJECT__INCLUDE_FILE, the file pointed to by that variable will be included as the last step of the project command.
clip-path
is now (2020) the best way I have found to achieve box-shadows on specific sides of elements, especially when the required effect is a "clean cut" shadow at particular edges, like this:
.shadow-element {
width: 100px;
height: 100px;
background-color: #FFC300;
box-shadow: 0 0 10px 5px rgba(0,0,0,0.75);
clip-path: inset(0px -15px 0px -15px);
/* position and left properties required to bring element out from edge of parent
so that shadow can be seen; margin-left would also achieve the same thing */
position: relative;
left: 15px;
}
_x000D_
<div class="shadow-element"></div>
_x000D_
...as opposed to an attenuated/reduced/thinning shadow like this:
.shadow-element {
width: 100px;
height: 100px;
background-color: #FFC300;
box-shadow: 15px 0 15px -10px rgba(0,0,0,0.75), -15px 0 15px -10px rgba(0,0,0,0.75);
/* position and left properties required to bring element out from edge of parent
so that shadow can be seen; margin-left would also achieve the same thing */
position: relative;
left: 15px;
}
_x000D_
<div class="shadow-element"></div>
_x000D_
Simply apply the following CSS to the element in question:
box-shadow: 0 0 Xpx Ypx [hex/rgba]; /* note 0 offset values */
clip-path: inset(Apx Bpx Cpx Dpx);
Where:
Apx
sets the shadow visibility for the top edgeBpx
rightCpx
bottomDpx
leftEnter a value of 0 for any edges where the shadow should be hidden and a negative value (the same as the combined result of the blur radius + spread values - Xpx + Ypx
) to any edges where the shadow should be displayed.
gcc will typically use logical shifts on unsigned variables and for left-shifts on signed variables. The arithmetic right shift is the truly important one because it will sign extend the variable.
gcc will will use this when applicable, as other compilers are likely to do.
<?php
list($width, $height) = getimagesize("http://site.com/image.png");
$arr = array('h' => $height, 'w' => $width );
?>
Open a new Search pane in Developer Tools by:
You can search across all your scripts with support for regular expressions and case sensitivity.
Click any match to load that file/section in the scripts panel.
Make sure 'Search in anonymous and content scripts' is checked in the DevTools Preferences (F1). This will return results from within iframes and HTML inline scripts:
Because you are outputting to the browser, you have to use <br/>
. Otherwise there is \n
and \r
or both combined.
Trying to give you a brief answer to your doubt, if you execute the skip(n).take(m)
methods on linq (with SQL 2005 / 2008 as database server) your query will be using the Select ROW_NUMBER() Over ...
statement, with is somehow direct paging in the SQL engine.
Giving you an example, I have a db table called mtcity
and I wrote the following query (work as well with linq to entities):
using (DataClasses1DataContext c = new DataClasses1DataContext())
{
var query = (from MtCity2 c1 in c.MtCity2s
select c1).Skip(3).Take(3);
//Doing something with the query.
}
The resulting query will be:
SELECT [t1].[CodCity],
[t1].[CodCountry],
[t1].[CodRegion],
[t1].[Name],
[t1].[Code]
FROM (
SELECT ROW_NUMBER() OVER (
ORDER BY [t0].[CodCity],
[t0].[CodCountry],
[t0].[CodRegion],
[t0].[Name],
[t0].[Code]) AS [ROW_NUMBER],
[t0].[CodCity],
[t0].[CodCountry],
[t0].[CodRegion],
[t0].[Name],
[t0].[Code]
FROM [dbo].[MtCity] AS [t0]
) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t1].[ROW_NUMBER]
Which is a windowed data access (pretty cool, btw cuz will be returning data since the very begining and will access the table as long as the conditions are met). This will be very similar to:
With CityEntities As
(
Select ROW_NUMBER() Over (Order By CodCity) As Row,
CodCity //here is only accessed by the Index as CodCity is the primary
From dbo.mtcity
)
Select [t0].[CodCity],
[t0].[CodCountry],
[t0].[CodRegion],
[t0].[Name],
[t0].[Code]
From CityEntities c
Inner Join dbo.MtCity t0 on c.CodCity = t0.CodCity
Where c.Row Between @p0 + 1 AND @p0 + @p1
Order By c.Row Asc
With the exception that, this second query will be executed faster than the linq result because it will be using exclusively the index to create the data access window; this means, if you need some filtering, the filtering should be (or must be) in the Entity listing (where the row is created) and some indexes should be created as well to keep up the good performance.
Now, whats better?
If you have pretty much solid workflow in your logic, implementing the proper SQL way will be complicated. In that case LINQ will be the solution.
If you can lower that part of the logic directly to SQL (in a stored procedure), it will be even better because you can implement the second query I showed you (using indexes) and allow SQL to generate and store the Execution Plan of the query (improving performance).
#include <algorithm> // std::search
#include <string>
using std::search; using std::count; using std::string;
int main() {
string mystring = "The needle in the haystack";
string str = "needle";
string::const_iterator it;
it = search(mystring.begin(), mystring.end(),
str.begin(), str.end()) != mystring.end();
// if string is found... returns iterator to str's first element in mystring
// if string is not found... returns iterator to mystring.end()
if (it != mystring.end())
// string is found
else
// not found
return 0;
}
Here is a simple way to implement ls
command using c
. To run use for example ./xls /tmp
#include<stdio.h>
#include <dirent.h>
void main(int argc,char *argv[])
{
DIR *dir;
struct dirent *dent;
dir = opendir(argv[1]);
if(dir!=NULL)
{
while((dent=readdir(dir))!=NULL)
{
if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
{
}
else
{
printf(dent->d_name);
printf("\n");
}
}
}
close(dir);
}
Right, click on the project. Go to Maven -> Update Project.
The dependencies will automatically be installed.
Alternatively
with Pool() as pool:
pool.map(fits.open, [name + '.fits' for name in datainput])
I had facing the same issue while writing a simple rest api using node.js eventually found out it was due to wifi blockage and security reason . try once connecting it using your mobile hotspot . if this be the reason it will get resolved immediately.
Better way is to use "bc", an arbitrary precision calculator.
variable=$(echo "OPTIONS; OPERATIONS" | bc)
ex:
my_var=$(echo "scale=5; $temp_var/100 + $temp_var2" | bc)
where "scale=5" is accuracy.
man bc
comes with several usage examples.
$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));
If user inputs
<img src="#">
In the database table just insert character this #
Works for me
Self-contained example
Same technique as in this answer but:
Source:
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button button = new Button(this);
button.setText("click me");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Notification notification = new Notification.Builder(Main.this)
/* Make app open when you click on the notification. */
.setContentIntent(PendingIntent.getActivity(
Main.this,
Main.this.i,
new Intent(Main.this, Main.class),
PendingIntent.FLAG_CANCEL_CURRENT))
.setContentTitle("title")
.setAutoCancel(true)
.setContentText(String.format("id = %d", Main.this.i))
// Starting on Android 5, only the alpha channel of the image matters.
// https://stackoverflow.com/a/35278871/895245
// `android.R.drawable` resources all seem suitable.
.setSmallIcon(android.R.drawable.star_on)
// Color of the background on which the alpha image wil drawn white.
.setColor(Color.RED)
.build();
final NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Main.this.i, notification);
// If the same ID were used twice, the second notification would replace the first one.
//notificationManager.notify(0, notification);
Main.this.i++;
}
});
this.setContentView(button);
}
}
Tested in Android 22.
if (!$_GET) echo "empty";
why do you need such a checking?
lol
you guys too direct-minded.
don't take as offense but sometimes not-minded at all
$_GET is very special variable, not like others.
it is supposed to be always set. no need to treat it as other variables.
when $_GET is not set and it's expected - it is emergency case and that's what "Undefined variable" notice invented for
This is possible in HTML5. Example (PHP 5.4):
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
</body>
</html>
Here's what it looks like in Chrome after selecting 2 items in the file dialog:
And here's what it looks like after clicking the "Upload" button.
This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.
OMG, a XAND gate does exist. My dad is taking a technological class for a job and there IS an XAND gate. People are saying that both OR and AND are complete opposites, so they expand that to the exclusive-gate logic:
XOR: One or another, but not both.
Xand: One and another, but not both.
This is incorrect. If you're going to change from XOR to XAND, you have to flip every instance of 'AND' and 'OR':
XOR: One or another, but not both.
XAND: One and another, but not one.
So, XAND is true when and only when both inputs are equal, either if the inputs are 0/0 or 1/1
Yes. For that ensure that you declare the worksheet
For example
Previous Code
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet3")
Debug.Print ws.Cells(23, 4).Value
End Sub
New Code
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Sheet4")
Debug.Print ws.Cells(23, 4).Value
End Sub
Try using;
PHP_EOL
To terminate each new line in your CSV output.
I'm assuming that the text is delimiting, but isn't moving to the next row?
That's a PHP constant. It will determine the correct end of line you need.
Windows, for example, uses "\r\n". I wracked my brains with that one when my output wasn't breaking to a new line.
This is definitely not the best way to do this but, I got it done by doing something like following.
String imageName = "my_image.png";
String replace = imageName.replace('.','~');
String[] split = replace.split("~");
System.out.println("Image name : " + split[0]);
System.out.println("Image extension : " + split[1]);
Output,
Image name : my_image
Image extension : png
I know I'm late to the party, but I thought I would provide an answer here for people who need to horizontally position an absolute item, when you don't know its exact width.
Try this:
// Horizontal example.
div#thing {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
The same technique can also be applied, for when you might need vertical alignment, simply by adjusting the properties like so:
// Vertical example.
div#thing {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
The number of arguments is $#
Search for it on this page to learn more: http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST
If you want to edit some complex javascript I suggest you use JsFiddle. Alternatively, for smaller pieces of javascript you can just run it through your browser URL bar, here's an example:
javascript:alert("hello world");
And, as it was already suggested both Firebug and Chrome developer tools have Javascript console, in which you can type in your javascript to execute. So do Internet Explorer 8+, Opera, Safari and potentially other modern browsers.
Class Parent cannot be declared because it is PHP reserved keyword so in effect it's already in use
To concatenate strings, use the +
operator.
To insert data into a URI, encode it for URIs.
Bad:
var url = "http://localhost:8080/login?cid='username'&pwd='password'"
Good:
var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;
The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.
… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).
If your dates
column does not contain time information, you could get away with:
WHERE dates BETWEEN '20121211' and '20121213'
However, given your dates
column is actually datetime, you want this
WHERE dates >= '20121211'
AND dates < '20121214' -- i.e. 00:00 of the next day
Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:
WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'
Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.
My solution hides keyboard on outside click in any activity, with of all edit texts. Without specifying them one by one.
First add to root view of layout xml: android:clickable="true" android:focusableInTouchMode="true"
Next, create one parent Acitvity of all activities you want to hide keyboard, and specify onResume() method:
@Override
protected void onResume() {
super.onResume();
//getting Root View that gets focus
View rootView =((ViewGroup)findViewById(android.R.id.content)).
getChildAt(0);
rootView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
hideKeyboard(AbstractActivity.this);
}
}
});
}
Extend your activity with this General activity (Inheritance power !) and that's all, every time any EditText (on any extended Activity) will lose focus, keyboard will be hidden.
P.S. hideKeyboard method :
public static void hideKeyboard(Activity context) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow( context.getCurrentFocus().getWindowToken(), 0);
}
context.getCurrentFocus() doesn't need specifying specific EditText view..
The best simple approach :
error: function (xhr) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
You can use Checkboxes extension for jQuery Datatables.
var table = $('#example').DataTable({
'ajax': 'https://api.myjson.com/bins/1us28',
'columnDefs': [
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
'select': {
'style': 'multi'
},
'order': [[1, 'asc']]
});
See this example for code and demonstration.
See Checkboxes project page for more examples and documentation.
Cookies are basically text, so you can store an array by encoding it as a JSON string (see json_encode
). Be aware that there is a limit on the length of the string you can store though.
(This is my third answer because I misunderstood what your code was doing in my original, and then made a small but crucial mistake in my second—hopefully three's a charm.
Edits: Since this seems to be a popular answer, I've made a few modifications to improve its implementation over the years—most not too major. This is so if folks use it as template, it will provide an even better basis.
As others have pointed out, your MemoryError
problem is most likely because you're attempting to read the entire contents of huge files into memory and then, on top of that, effectively doubling the amount of memory needed by creating a list of lists of the string values from each line.
Python's memory limits are determined by how much physical ram and virtual memory disk space your computer and operating system have available. Even if you don't use it all up and your program "works", using it may be impractical because it takes too long.
Anyway, the most obvious way to avoid that is to process each file a single line at a time, which means you have to do the processing incrementally.
To accomplish this, a list of running totals for each of the fields is kept. When that is finished, the average value of each field can be calculated by dividing the corresponding total value by the count of total lines read. Once that is done, these averages can be printed out and some written to one of the output files. I've also made a conscious effort to use very descriptive variable names to try to make it understandable.
try:
from itertools import izip_longest
except ImportError: # Python 3
from itertools import zip_longest as izip_longest
GROUP_SIZE = 4
input_file_names = ["A1_B1_100000.txt", "A2_B2_100000.txt", "A1_B2_100000.txt",
"A2_B1_100000.txt"]
file_write = open("average_generations.txt", 'w')
mutation_average = open("mutation_average", 'w') # left in, but nothing written
for file_name in input_file_names:
with open(file_name, 'r') as input_file:
print('processing file: {}'.format(file_name))
totals = []
for count, fields in enumerate((line.split('\t') for line in input_file), 1):
totals = [sum(values) for values in
izip_longest(totals, map(float, fields), fillvalue=0)]
averages = [total/count for total in totals]
for print_counter, average in enumerate(averages):
print(' {:9.4f}'.format(average))
if print_counter % GROUP_SIZE == 0:
file_write.write(str(average)+'\n')
file_write.write('\n')
file_write.close()
mutation_average.close()
Use DATEPART to pull apart your interval, and DATEADD to subtract the parts:
select dateadd(
hh,
-1 * datepart(hh, cast('1:15' as datetime)),
dateadd(
mi,
-1 * datepart(mi, cast('1:15' as datetime)),
'2000-01-01 08:30:00'))
or, we can convert to minutes first (though OP would prefer not to):
declare @mins int
select @mins = datepart(mi, cast('1:15' as datetime)) + 60 * datepart(hh, cast('1:15' as datetime))
select dateadd(mi, -1 * @mins, '2000-01-01 08:30:00')
you can turn off the warning message as explained in the other answers or you can understand what's happening and fix it.
As of MySQL 5.7.5, the default SQL mode includes ONLY_FULL_GROUP_BY which means when you are grouping rows and then selecting something out of that groups, you need to explicitly say which row should that selection be made from.
Mysql needs to know which row in the group you're looking for, which gives you two options
group by rect.color, rect.value
which can be what you want in some cases otherwise would return duplicate results with the same color which you may not wantAVG()
MIN()
MAX()
complete list ANY_VALUE()
if you are sure that all the results inside the group are the same. docJNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.
What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");
Here is IBM's reference page.
If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE
Method toFixed()
will also solves the purpose.
var n = 8.434332;
n.toFixed(2) // 8.43
Try this one:
HTML:
<div id="para1"></div>
JavaScript:
document.getElementById("para1").innerHTML = formatAMPM();
function formatAMPM() {
var d = new Date(),
minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
ampm = d.getHours() >= 12 ? 'pm' : 'am',
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;
}
Result:
Mon Sep 18 2017 12:40pm
As all html ids are unique in a valid html document why not search for the ID directly? If you're concerned if they type in an id that isn't a table then you can inspect the tag type that way?
Just an idea!
S
Generally speaking, a software product isn't your "property already", as you said in the comment. Most of the times (I won't be irresponsible to say anything in open), it's licensed to you. A license to use some thing is not the same thing as owning (property rights) that very same thing.
That's because there are authorship, copyright, intellectual property rights applicable to it. I don't know how things work in United States (or in your country), but it's generally accepted that the work of a mind, a creative work, must not be changed in its nature as such to make the expression of art to be different than that expression that the author intended. That applies for example, in some cases, to architectural work (in most countries, you can't change the appearance of a building to "desfigure" the work of art of the architect, without his prior consent). Exceptions are made, obviously, when the author expressly authorizes such changes (e.g., Creative Commons licenses, open source licenses etc.).
Anyway, that's why you see in most EULAs the typical sentence: "this software is licensed, not sold". That's the purpose and reason why.
Now that you understand the reasons why you can't wander around changing other people's art, let me be technical.
There are possible ways to decompile Java programs. You can use dex2jar
, it provides a somewhat good start for you to start looking for things and changes. And perhaps rebuild the code by mounting back the pieces together. Good luck, as most people obfuscate their codes to make that harder.
However, let me say that it's still forbidden to change programs, as I said above. And it's extremely unethical. It makes me sad that people do that with no scruples (not saying it's your case, just warning you). It shouldn't need people to be at the other side to understand that. Or maybe that's just me, who lives in a country where piracy is rampant.
The tools are always out there. But the conscience, unfortunately, not always.
edit: in case it isn't clear enough already, I do NOT approve the use of these programs. I use them myself to check how hard my own applications are to be reverse engineered. But I also think that explaning is always better than denial (better be here).
try: window.document......
var body = window.document.getElementsByTagName("body")[0];
That is actually the declaration for an event handler - a method that will get called when an event is fired. To create an event, you'd write something like this:
public class Foo
{
public event EventHandler MyEvent;
}
And then you can subscribe to the event like this:
Foo foo = new Foo();
foo.MyEvent += new EventHandler(this.OnMyEvent);
With OnMyEvent() defined like this:
private void OnMyEvent(object sender, EventArgs e)
{
MessageBox.Show("MyEvent fired!");
}
Whenever Foo
fires off MyEvent
, then your OnMyEvent
handler will be called.
You don't always have to use an instance of EventArgs
as the second parameter. If you want to include additional information, you can use a class derived from EventArgs
(EventArgs
is the base by convention). For example, if you look at some of the events defined on Control
in WinForms, or FrameworkElement
in WPF, you can see examples of events that pass additional information to the event handlers.
When Command Extensions are enabled (Windows XP and newer, roughly), you can use the syntax %~nF (where F is the variable and ~n is the request for its name) to only get the filename.
FOR /R C:\Directory %F in (*.*) do echo %~nF
should echo only the filenames.
You can use justify-content: space-between
in .test
like so:
.test {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
For those who want to use Bootstrap 4 can use justify-content-between
:
div {_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
There are likely to be many ways to accomplish this. My suggestion is to use Case/When to do it. With 3 columns, it's not too bad.
Select Id,
Case When Col1 < Col2 And Col1 < Col3 Then Col1
When Col2 < Col1 And Col2 < Col3 Then Col2
Else Col3
End As TheMin
From YourTableNameHere
Well, it's unfortunate that you didn't post your own code too, so that it could be corrected.
Anyway, here's my own solution to this:
@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=result.txt
>nul copy nul %OUTPUT_FILE%
for /f %%i in (testservers.txt) do (
set SERVER_ADDRESS=ADDRESS N/A
for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS=%%y
if %%x==Reply set SERVER_ADDRESS=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
)
The outer loop iterates through the hosts and the inner loop parses the ping
output. The first two if
statements handle the two possible cases of IP address resolution:
If the host IP address cannot be resolved, the address is set to "ADDRESS N/A".
Hope this helps.
For a larger object graph, I second the use of Json but with a slightly different strategy. First I have a static class that is easy to call and with a static method that wraps the Json conversion (note: could make this an extension method).
using Newtonsoft.Json;
public static class F
{
public static string Dump(object obj)
{
return JsonConvert.SerializeObject(obj);
}
}
Then in your Immediate Window
,
var lookHere = F.Dump(myobj);
lookHere will auto-show up in the Locals
window prepended with a $ or you can add a watch to it. On the right hand side of the Value
column in the inspector, there is a magnifying glass with a dropdown caret beside it. Choose the dropdown caret and choose Json visualizer.
I am using Visual Studio 2013.
You can also use listView.setOnItemLongClickListener to delete selected item. Below is the code.
// listView = name of your ListView
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int
position, long id) {
// it will get the position of selected item from the ListView
final int selected_item = position;
new AlertDialog.Builder(MainActivity.this).
setIcon(android.R.drawable.ic_delete)
.setTitle("Are you sure...")
.setMessage("Do you want to delete the selected item..?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
list.remove(selected_item);
arrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No" , null).show();
return true;
}
});
You use the available API of JTable
and do not try to mess with the colors.
Some selection methods are available directly on the JTable
(like the setRowSelectionInterval
). If you want to have access to all selection-related logic, the selection model is the place to start looking
npm install @babel/plugin-transform-modules-commonjs
and add to to .babelrc plugins resolved my question.
You can do simply by replacing html
$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
Xcode 9.0.1, swift 4.0
Data
import Foundation
let array = [0,1,2,3,4,5,6,7,8]
Solution 1
extension Int {
func getString(prefix: Int) -> String {
return "\(prefix)\(self)"
}
func getString(prefix: String) -> String {
return "\(prefix)\(self)"
}
}
for item in array {
print(item.getString(prefix: 0))
}
for item in array {
print(item.getString(prefix: "0x"))
}
Solution 2
for item in array {
print(String(repeatElement("0", count: 2)) + "\(item)")
}
Solution 3
extension String {
func repeate(count: Int, string: String? = nil) -> String {
if count > 1 {
let repeatedString = string ?? self
return repeatedString + repeate(count: count-1, string: repeatedString)
}
return self
}
}
for item in array {
print("0".repeate(count: 3) + "\(item)")
}
Another option is to repeat the rules in two prefix locations using an included file. Since prefix locations are position independent in the configuration, using them can save some confusion as you add other regex locations later on. Avoiding regex locations when you can will help your configuration scale smoothly.
server {
location /first/location/ {
include shared.conf;
}
location /second/location/ {
include shared.conf;
}
}
Here's a sample shared.conf:
default_type text/plain;
return 200 "http_user_agent: $http_user_agent
remote_addr: $remote_addr
remote_port: $remote_port
scheme: $scheme
nginx_version: $nginx_version
";
You can use this cool library to make any kind of animated effect on your element: http://daneden.github.io/animate.css/
File Word-Count
If in between words having some symbols then you can split and count the number of Words.
Scanner sc = new Scanner(new FileInputStream(new File("Input.txt")));
int count = 0;
while (sc.hasNext()) {
String[] s = sc.next().split("d*[.@:=#-]");
for (int i = 0; i < s.length; i++) {
if (!s[i].isEmpty()){
System.out.println(s[i]);
count++;
}
}
}
System.out.println("Word-Count : "+count);
On StackOverflow, pressing the up-vote button is AJAX whereas typing in your question or answer and seeing it appear in the real-time preview window below it is JavaScript (JQuery).
This means that the difference between AJAX and Javascript is that AJAX allows you to communicate with the server without doing a page refresh (i.e. going to a new page) whereas JavaScript (JQuery) allows you to embed logic and behaviour on your page. Of course, with this logic you create AJAX as well.
To direct to the point , you can easily use xapth .The exact and simple way to do this using the below code . Kindly try and provide feedback .Thank you .
JavascriptExecutor js = (JavascriptExecutor) driver;
//To click an element
WebElement element=driver.findElement(By.xpath(Xpath));
js.executeScript(("arguments[0].click();", element);
//To gettext
String theTextIWant = (String) js.executeScript("return arguments[0].value;",driver.findElement(By.xpath("//input[@id='display-name']")));
Further readings - https://medium.com/@smeesheady/webdriver-javascriptexecutor-interact-with-elements-and-open-and-handle-multiple-tabs-and-get-url-dcfda49bfa0f
To sum up all of the options for VS 2017, WebHelpers was installed by installing MVC in previous versions of Visual Studio. If you're getting this error, you probably don't have the older versions of VS installed anymore.
So, installing the Microsoft.AspNet.MVC
NuGet package will require Microsoft.AspNet.WebPages
and Microsoft.AspNet.Razor
, and the Microsoft.AspNet.WebPages
includes System.Web.Helpers.dll
.
If you've got direct references to System.Web.Mvc.dll and you don't want to use NuGet for MVC, you can get the Microsoft.AspNet.WebPages
NuGet, or there are some other NuGet packages that only contain System.Web.Helpers.dll
, like the microsoft-web-helpers
or System-Web-Helpers.dll
packages.
There appear to be 2 versions of System.Web.Helpers.dll
, one for .Net 4.0 and one for 4.5. Choosing the correct version of MVC or AspNet.WebPages will ensure you get the right one.
The + operator can work between a string and a string, char, integer, double or float data type value. It just converts the value to its string representation before concatenation.
The concat operator can only be done on and with strings. It checks for data type compatibility and throws an error, if they don't match.
Except this, the code you provided does the same stuff.
my function support removing param
function updateURLParameter(url, param, paramVal, remove = false) {
var newAdditionalURL = '';
var tempArray = url.split('?');
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var rows_txt = '';
if (additionalURL)
newAdditionalURL = decodeURI(additionalURL) + '&';
if (remove)
newAdditionalURL = newAdditionalURL.replace(param + '=' + paramVal, '');
else
rows_txt = param + '=' + paramVal;
window.history.replaceState('', '', (baseURL + "?" + newAdditionalURL + rows_txt).replace('?&', '?').replace('&&', '&').replace(/\&$/, ''));
}
If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"
For example, if your not careful you may be tempted to try something like:
Dim foo As Integer? = If(someTrueExpression, Nothing, 2)
Will give "foo" a value of 0!
I think the '?' operator equivalent in C# would instead fail compilation
Im going to provide an argument against using socket.io.
I think using socket.io solely because it has fallbacks isnt a good idea. Let IE8 RIP.
In the past there have been many cases where new versions of NodeJS has broken socket.io. You can check these lists for examples... https://github.com/socketio/socket.io/issues?q=install+error
If you go to develop an Android app or something that needs to work with your existing app, you would probably be okay working with WS right away, socket.io might give you some trouble there...
Plus the WS module for Node.JS is amazingly simple to use.
python looks for .UFT-8, but you probably have .utf8 try installing the .UFT-8 packages with sudo dpkg-reconfigure locales
sample table
#import "StartreserveViewController.h"
#import "CollectionViewController.h"
#import "TableViewCell1.h"
@interface StartreserveViewController ()
{
NSArray *name;
NSArray *images;
NSInteger selectindex;
}
@end
@implementation StartreserveViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor blueColor];
_startReservetable.backgroundColor = [UIColor blueColor];
name = [[NSArray alloc]initWithObjects:@"Mobiles",@"Costumes",@"Shoes",
nil];
images = [[NSArray
alloc]initWithObjects:@"mobilestitle.jpg",@"costumetitle.jpeg",
@"shoestitle.png",nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"tableview";
TableViewCell1 *cell =[tableView dequeueReusableCellWithIdentifier:cellId];
cell.cellTxt .text = [name objectAtIndex:indexPath.row];
cell.cellImg.image = [UIImage imageNamed:[images
objectAtIndex:indexPath.row]];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
{
selectindex = indexPath.row;
[self performSegueWithIdentifier:@"second" sender:self];
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"second"])
{
CollectionViewController *obj = segue.destinationViewController;
obj.receivename = [name objectAtIndex:selectindex];
}
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
@end
.h
#import <UIKit/UIKit.h>
@interface StartreserveViewController :
UIViewController<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UITableView *startReservetable;
@end
Thanks Mr. Tom Chantler adding that to get the exe http://downloadsvn.codeplex.com/ to pull the SVN source
just note that suppose you're downloading the below project: you have to enter exactly the following to donwload it in the exe URL:
http://myproject.googlecode.com/svn/trunk/
developer not taking care of appending the h t t p : / / if it does not exist. Hope it saves somebody's time.
You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:
<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>
If you use php:
print_r($_POST['comment'])
you will get this:
Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )
Use the command line, as described in this related question: How do I check if my SSL Certificate is SHA1 or SHA2 on the commandline.
Here's the command. Replace www.yoursite.com:443
to fit your needs. Default SSL port is 443:
openssl s_client -connect www.yoursite.com:443 < /dev/null 2>/dev/null \
| openssl x509 -text -in /dev/stdin | grep "Signature Algorithm"
This should return something like this for the sha1:
Signature Algorithm: sha1WithRSAEncryption
or this for the newer version:
Signature Algorithm: sha256WithRSAEncryption
The article Why Google is Hurrying the Web to Kill SHA-1 describes exactly what you would expect and has a pretty graphic, too.
You can use:
cout << "size of datatype = " << sizeof(datatype) << endl;
datatype = int
, long int
etc.
You will be able to see the size for whichever datatype you type.