You don't really need it today, because the current standard makes it optional -- and every useful browser currently assumes that a style sheet is CSS, even in versions of HTML that considered the attribute "required".
With HTML being a "living standard" now, though -- and thus subject to change -- you can only guarantee so much. And there's no new DTD that you can point to and say the page was written for that version of HTML, and no reliable way even to say "HTML as of such-and-such a date". For forward-compatibility reasons, in my opinion, you should specify the type.
You can use mkdir:
#include <sys/stat.h>
#include <sys/types.h>
int result = mkdir("/home/me/test.txt", 0777);
It would be
yourTextView.setTypeface(null,Typeface.DEFAULT_BOLD);
and italic should be able to be with replacing Typeface.DEFAULT_BOLD
with Typeface.DEFAULT_ITALC
.
Let me know how it works.
JSONArray jArray = new JSONArray();
jArray.remove(position); // For remove JSONArrayElement
Note :- If remove()
isn't there in JSONArray
then...
API 19 from Android (4.4) actually allows this method.
Call requires API level 19 (current min is 16): org.json.JSONArray#remove
Right Click on Project Go to Properties
Select Android from left site option
And select Project Build Target greater then API 19
Hope it helps you.
The Main Differences:
Example
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i));
s.close(); `
BufferedReader:
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
Source:Link
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
Just need to move the map below this box. Work to me.
From Google
A proper way to search for a substring is to use position
function instead of like
expression, which requires escaping %
, _
and an escape character (\
by default):
SELECT id FROM TAG_TABLE WHERE position(tag_name in 'aaaaaaaaaaa')>0;
You can use querySelectorAll:
document.querySelectorAll('[data-foo]');
The size of an array is static in C++. You cannot dynamically resize it. That's what std::vector
is for:
std::vector<int> v; // size of the vector starts at 0
v.push_back(10); // v now has 1 element
v.push_back(20); // v now has 2 elements
v.push_back(30); // v now has 3 elements
v.pop_back(); // removes the 30 and resizes v to 2
v.resize(v.size() - 1); // resizes v to 1
If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a
and b
:
import json
a = json.loads("""
{
"errors": [
{"error": "invalid", "field": "email"},
{"error": "required", "field": "name"}
],
"success": false
}
""")
b = json.loads("""
{
"success": false,
"errors": [
{"error": "required", "field": "name"},
{"error": "invalid", "field": "email"}
]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False
... but that doesn't work, because in each case, the "errors"
item of the top-level dict is a list with the same elements in a different order, and sorted()
doesn't try to sort anything except the "top" level of an iterable.
To fix that, we can define an ordered
function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value)
pairs so that they're orderable):
def ordered(obj):
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj
If we apply this function to a
and b
, the results compare equal:
>>> ordered(a) == ordered(b)
True
It seems like the other answers here all misunderstood your question. If I understand correctly, you want to make requests to localhost:6379 (the default for redis) and have them be forwarded, automatically, to the same port on your redis container.
https://unix.stackexchange.com/a/101906/38639 helped me get to the right answer.
First, you'll need to install the nc
command on your image. On CentOS, this package is called nmap-ncat, so in the example below, just replace this with the appropriate package if you are using a different OS as your base image.
Next, you'll need to tell it to run a certain command each time the container boots up. You can do this using CMD.
# Add this to your Dockerfile
RUN yum install -y --setopt=skip_missing_names_on_install=False nmap-ncat
COPY cmd.sh /usr/local/bin/cmd.sh
RUN chmod +x /usr/local/bin/cmd.sh
CMD ["/usr/local/bin/cmd.sh"]
Finally, we'll need to set up port-forwarding in cmd.sh. I found that nc
, even with the -l
and -k
options, will occasionally terminate when a request is completed, so I'm using a while-loop to ensure that it's always running.
# cmd.sh
#! /usr/bin/env bash
while nc -l -p 6379 -k -c "nc redis 6379" || true; do true; done &
tail -f /dev/null # Or any other command that never exits
In Python 3.4 and above, you can use the object oriented pathlib module interface which includes wrappers for much of the os module. Here is an example of getting the file stats.
>>> import pathlib
>>> fname = pathlib.Path('test.py')
>>> assert fname.exists(), f'No such file: {fname}' # check that the file exists
>>> print(fname.stat())
os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272)
For more information about what os.stat_result
contains, refer to the documentation. For the modification time you want fname.stat().st_mtime
:
>>> import datetime
>>> mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime)
>>> print(mtime)
datetime.datetime(2018, 10, 17, 10, 49, 0, 249980)
If you want the creation time on Windows, or the most recent metadata change on Unix, you would use fname.stat().st_ctime
:
>>> ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime)
>>> print(ctime)
datetime.datetime(2018, 4, 11, 16, 57, 52, 151953)
This article has more helpful info and examples for the pathlib module.
One solution: add isAdmin: 0/1 flag to your post collection document.
Other solution: use DBrefs
Lengthy But "Works With No Surprises & No Installations"
This script handles filenames with spaces, quotes, other unusual characters and Unicode, works on case insensitive filesystems and most Unix-y environments that have bash and awk installed (i.e. almost all). It also reports collisions if any (leaving the filename in uppercase) and of course renames both files & directories and works recursively. Finally it's highly adaptable: you can tweak the find command to target the files/dirs you wish and you can tweak awk to do other name manipulations. Note that by "handles Unicode" I mean that it will indeed convert their case (not ignore them like answers that use tr
).
# adapt the following command _IF_ you want to deal with specific files/dirs
find . -depth -mindepth 1 -exec bash -c '
for file do
# adapt the awk command if you wish to rename to something other than lowercase
newname=$(dirname "$file")/$(basename "$file" | awk "{print tolower(\$0)}")
if [ "$file" != "$newname" ] ; then
# the extra step with the temp filename is for case-insensitive filesystems
if [ ! -e "$newname" ] && [ ! -e "$newname.lcrnm.tmp" ] ; then
mv -T "$file" "$newname.lcrnm.tmp" && mv -T "$newname.lcrnm.tmp" "$newname"
else
echo "ERROR: Name already exists: $newname"
fi
fi
done
' sh {} +
References
My script is based on these excellent answers:
https://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names
Boost String Algorithms Library way:
#include <boost/algorithm/string/replace.hpp>
{ // 1.
string test = "abc def abc def";
boost::replace_all(test, "abc", "hij");
boost::replace_all(test, "def", "klm");
}
{ // 2.
string test = boost::replace_all_copy
( boost::replace_all_copy<string>("abc def abc def", "abc", "hij")
, "def"
, "klm"
);
}
As @Matt answered the reason of [object object]
, I will expand on how to inspect the value of the object. There are three options on top of my mind:
JSON.stringify(JSONobject)
console.log(JSONobject)
Basic example.
var jsonObj={
property1 : "one",
property2 : "two",
property3 : "three",
property4 : "fourth",
};
var strBuilder = [];
for(key in jsonObj) {
if (jsonObj.hasOwnProperty(key)) {
strBuilder.push("Key is " + key + ", value is " + jsonObj[key] + "\n");
}
}
alert(strBuilder.join(""));
// or console.log(strBuilder.join(""))
In this simple example you can just put synchronized
as a modifier after public
in both method signatures.
More complex scenarios require other stuff.
For Java 7+ doc you can use this:
BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
Here are all Charsets doc
For example if your file is in CP1252, use this method
Charset.forName("windows-1252");
Here is other canonical names for Java encodings both for IO and NIO doc
If you do not know with exactly encoding you have got in a file, you may use some third-party libs like this tool from Google this which works fairly neat.
The radio buttons are sent on form submit when they are checked only...
use isset()
if true then its checked otherwise its not
I found the solution:
public class DefaultPostgresKeyServer
{
private Session session;
private Iterator<BigInteger> iter;
private long batchSize;
public DefaultPostgresKeyServer (Session sess, long batchFetchSize)
{
this.session=sess;
batchSize = batchFetchSize;
iter = Collections.<BigInteger>emptyList().iterator();
}
@SuppressWarnings("unchecked")
public Long getNextKey()
{
if ( ! iter.hasNext() )
{
Query query = session.createSQLQuery( "SELECT nextval( 'mySchema.mySequence' ) FROM generate_series( 1, " + batchSize + " )" );
iter = (Iterator<BigInteger>) query.list().iterator();
}
return iter.next().longValue() ;
}
}
On codeplex was released new XNA Extension for Visual Studio 2012/2013. You can download it from: https://msxna.codeplex.com/releases
It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the HttpClient docs:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" +
"goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
I was having some trouble with this so let me be very explicit so noobs like me can understand.
Lets say that we have a data file or something like that
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
import sympy as sym
"""
Generate some data, let's imagine that you already have this.
"""
x = np.linspace(0, 3, 50)
y = np.exp(x)
"""
Plot your data
"""
plt.plot(x, y, 'ro',label="Original Data")
"""
brutal force to avoid errors
"""
x = np.array(x, dtype=float) #transform your data in a numpy array of floats
y = np.array(y, dtype=float) #so the curve_fit can work
"""
create a function to fit with your data. a, b, c and d are the coefficients
that curve_fit will calculate for you.
In this part you need to guess and/or use mathematical knowledge to find
a function that resembles your data
"""
def func(x, a, b, c, d):
return a*x**3 + b*x**2 +c*x + d
"""
make the curve_fit
"""
popt, pcov = curve_fit(func, x, y)
"""
The result is:
popt[0] = a , popt[1] = b, popt[2] = c and popt[3] = d of the function,
so f(x) = popt[0]*x**3 + popt[1]*x**2 + popt[2]*x + popt[3].
"""
print "a = %s , b = %s, c = %s, d = %s" % (popt[0], popt[1], popt[2], popt[3])
"""
Use sympy to generate the latex sintax of the function
"""
xs = sym.Symbol('\lambda')
tex = sym.latex(func(xs,*popt)).replace('$', '')
plt.title(r'$f(\lambda)= %s$' %(tex),fontsize=16)
"""
Print the coefficients and plot the funcion.
"""
plt.plot(x, func(x, *popt), label="Fitted Curve") #same as line above \/
#plt.plot(x, popt[0]*x**3 + popt[1]*x**2 + popt[2]*x + popt[3], label="Fitted Curve")
plt.legend(loc='upper left')
plt.show()
the result is: a = 0.849195983017 , b = -1.18101681765, c = 2.24061176543, d = 0.816643894816
It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.
There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit()
method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.
CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.
Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.
For those who still stumble upon this like I did, it's worth checking to make sure the attempted GRANT
does not already exist:
SHOW GRANTS FOR username;
In my case, the error was not actually because there was a permission error, but because the GRANT
already existed.
#include <QFile>
#include <QCoreApplication>
#include <QTextStream>
int main(int argc, char *argv[])
{
// Create a new file
QFile file("out.txt");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << "This file is generated by Qt\n";
// optional, as QFile destructor will already do it:
file.close();
//this would normally start the event loop, but is not needed for this
//minimal example:
//return app.exec();
return 0;
}
The jQuery Audit plugin plugin should let you do this through the normal Chrome Dev Tools. It's not perfect, but it should let you see the actual handler bound to the element/event and not just the generic jQuery handler.
You can add FrameLayout
to the fragment and replace it with another fragment when it initializes.
This way , you could consider the other fragment to be inside the first fragment.
Jenkins determines the success/failure of a step by the return value of the step. For the case of a shell, it should be the return of the last value. For both Windows CMD and (POSIX) Bash shells, you should be able to set the return value manually by using exit 0
as the last command.
string cat = "cat";
string human = "human";
cout << cat.compare(human) << endl;
This code will give -1 as a result. This is due to the first non-matching character of the compared string 'h' is lower or appears after 'c' in alphabetical order, even though the compared string, 'human' is longer than 'cat'.
I find the return value described in cplusplus.com is more accurate which are-:
0 : They compare equal
<0 : Either the value of the first character that does not match is lower in the compared string, or all compared characters match but the compared string is shorter.
more than 0 : Either the value of the first character that does not match is greater in the compared string, or all compared characters match but the compared string is longer.
Moreover, IMO cppreference.com's description is simpler and so far best describe to my own experience.
negative value if
*this
appears before the character sequence specified by the arguments, in lexicographical orderzero if both character sequences compare equivalent
positive value if
*this
appears after the character sequence specified by the arguments, in lexicographical order
You can use sp_executesql with output parameter.
declare @S nvarchar(max) = 'select @x = 1'
declare @xx int
set @xx = 0
exec sp_executesql @S, N'@x int out', @xx out
select @xx
Result:
(No column name)
1
Edit
In my sample @S
is instead of your @template
. As you can see I assign a value to @x
so you need to modify @template
so it internally assigns the comma separated string to the variable you define in your second argument to sp_executesql
. In my sample N'@x int out'
. You probably want a varchar(max)
output parameter. Something like N'@Result varchar(max) out'
Here is another example building a comma separated string from master..spt_values
declare @template nvarchar(max)
set @template =
'select @Result += cast(number as varchar(10))+'',''
from master..spt_values
where type = ''P''
'
declare @CommaString varchar(max)
set @CommaString = ''
exec sp_executesql @template, N'@Result varchar(max) out', @CommaString out
select @CommaString
SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).
(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).
You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.
It's embedded in a standard XML comment, and looks like this:
<!--#include virtual="top.shtml" -->
It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.
You can read more in this Wikipedia article.
If you want your log file to be place at a specified location which will be decided at run time may be your project output directory then you can configure your .config
file entry in that way
<file type="log4net.Util.PatternString" value="%property{LogFileName}.txt" />
and then in the code before calling log4net configure
, set the new path like below
log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
log4net.Config.XmlConfigurator.Configure();
How simple is it? :)
I used these code Hope it could help
dataGridView2.Rows[n].Cells[3].Value = item[2].ToString();
dataGridView2.Rows[n].Cells[3].Value = Convert.ToDateTime(item[2].ToString()).ToString("d");
Try:
$(document).ready(function() {
$('#contact-form').validate({submitHandler: function(form) {
var data = $('#contact-form').serialize();
$.post(
'url_request',
{data: data},
function(response){
console.log(response);
}
);
}
});
});
you need to write this structure on your bean configuration (this is your datasource):
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP" />
<property name="connectionTestQuery" value="SELECT 1" />
<property name="dataSourceClassName" value="${hibernate.dataSourceClassName}" />
<property name="maximumPoolSize" value="${hibernate.hikari.maximumPoolSize}" />
<property name="idleTimeout" value="${hibernate.hikari.idleTimeout}" />
<property name="dataSourceProperties">
<props>
<prop key="url">${dataSource.url}</prop>
<prop key="user">${dataSource.username}</prop>
<prop key="password">${dataSource.password}</prop>
</props>
</property>
</bean>
<!-- HikariCP configuration -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
This is my example and it is working. You just need to put your properties on hibernate.properties and set it before:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:hibernate.properties</value>
</list>
</property>
</bean>
Obs.: the versions are
log4j: 1.2.16
springframework: 3.1.4.RELEASE
HikariCP: 1.4.0
Properties file (hibernate.properties):
hibernate.dataSourceClassName=oracle.jdbc.pool.OracleDataSource
hibernate.hikari.maximumPoolSize=10
hibernate.hikari.idleTimeout=30000
dataSource.url=jdbc:oracle:thin:@localhost:1521:xe
dataSource.username=admin
dataSource.password=
My solution is to use ggplot2
. It takes care of these types of things automatically. The biggest thing is to arrange the data appropriately.
y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
df <- data.frame(x=rep(x,2), y=c(y1, y2), class=c(rep("y1", 5), rep("y2", 5)))
Then use ggplot2
to plot it
library(ggplot2)
ggplot(df, aes(x=x, y=y, color=class)) + geom_point()
This is saying plot the data in df
, and separate the points by class
.
The plot generated is
Join like this:
ON a.userid = b.sourceid AND a.listid = b.destinationid;
After spending hours on this issue, none of the answers above helped me so I found a really useful tool.
Firstly, I used Telerik's Fiddler 4 to study my Web Requests in details
Secondly, I came across this useful plugin for Fiddler:
https://github.com/sunilpottumuttu/FiddlerGenerateHttpClientCode
It will just generate the C# code for you. An example was:
var uriBuilder = new UriBuilder("test.php", "test");
var httpClient = new HttpClient();
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uriBuilder.ToString());
httpRequestMessage.Headers.Add("Host", "test.com");
httpRequestMessage.Headers.Add("Connection", "keep-alive");
// httpRequestMessage.Headers.Add("Content-Length", "138");
httpRequestMessage.Headers.Add("Pragma", "no-cache");
httpRequestMessage.Headers.Add("Cache-Control", "no-cache");
httpRequestMessage.Headers.Add("Origin", "test.com");
httpRequestMessage.Headers.Add("Upgrade-Insecure-Requests", "1");
// httpRequestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
httpRequestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
httpRequestMessage.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
httpRequestMessage.Headers.Add("Referer", "http://www.translationdirectory.com/");
httpRequestMessage.Headers.Add("Accept-Encoding", "gzip, deflate");
httpRequestMessage.Headers.Add("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8");
httpRequestMessage.Headers.Add("Cookie", "__utmc=266643403; __utmz=266643403.1537352460.3.3.utmccn=(referral)|utmcsr=google.co.uk|utmcct=/|utmcmd=referral; __utma=266643403.817561753.1532012719.1537357162.1537361568.5; __utmb=266643403; __atuvc=0%7C34%2C0%7C35%2C0%7C36%2C0%7C37%2C48%7C38; __atuvs=5ba2469fbb02458f002");
var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result;
var httpContent = httpResponseMessage.Content;
string result = httpResponseMessage.Content.ReadAsStringAsync().Result;
Note that I had to comment out two lines as this plugin is not totally perfect yet but it did the job nevertheless.
DISCLAIMER: I am not associated or endorsed by either Telerik or the plugin's author in anyway.
XCODE 10.1 / SWIFT 4.2 :
Add required permissions (others mentioned)
Add this class to your view:
import UIKit
import Photos
import Foundation
class UploadImageViewController: UIViewController, UIImagePickerControllerDelegate , UINavigationControllerDelegate {
@IBOutlet weak var imgView: UIImageView!
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
checkPermission()
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
}
@IBAction func btnSetProfileImageClickedCamera(_ sender: UIButton) {
}
@IBAction func btnSetProfileImageClickedFromGallery(_ sender: UIButton) {
self.selectPhotoFromGallery()
}
func selectPhotoFromGallery() {
self.present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
self.imgView.contentMode = .scaleAspectFit
self.imgView.image = pickedImage
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
print("cancel is clicked")
}
func checkPermission() {
let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
switch photoAuthorizationStatus {
case .authorized:
print("Access is granted by user")
case .notDetermined:
PHPhotoLibrary.requestAuthorization({
(newStatus) in
print("status is \(newStatus)")
if newStatus == PHAuthorizationStatus.authorized {
/* do stuff here */
print("success")
}
})
print("It is not determined until now")
case .restricted:
// same same
print("User do not have access to photo album.")
case .denied:
// same same
print("User has denied the permission.")
}
}
}
How to design table like this in mongodb?
First, to clarify some naming conventions. MongoDB uses collections
instead of tables
.
I think there are no foreign keys!
Take the following model:
student
{
_id: ObjectId(...),
name: 'Jane',
courses: [
{ course: 'bio101', mark: 85 },
{ course: 'chem101', mark: 89 }
]
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
Clearly Jane's course list points to some specific courses. The database does not apply any constraints to the system (i.e.: foreign key constraints), so there are no "cascading deletes" or "cascading updates". However, the database does contain the correct information.
In addition, MongoDB has a DBRef standard that helps standardize the creation of these references. In fact, if you take a look at that link, it has a similar example.
How can I solve this task?
To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.
#!/bin/bash
echo "The number of arguments is: $#"
a=${@}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$@"
do
echo "The length of argument '$var' is: ${#var}"
(( count++ ))
(( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"
To resolve this error:
ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name
Just run this PL/SQL
command for extended tablespace size automatically on-demand:
alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;
I get this error in import big dump file, just run this command without stopping import routine or restarting the database.
Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.
More info: alter_autoextend_on
Yes. This is safe as long as you are using standard ascii characters, like you are in this example.
android:background="#E1E1E1"
// background add in layout
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff">
</EditText>
You can add a sequence of numbers very easily with
data$ID <- seq.int(nrow(data))
If you are already using library(tidyverse)
, you can use
data <- tibble::rowid_to_column(data, "ID")
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
You can set the height
and width
of your divs
with css
.
<style type="text/css">
.box {
height: 150px;
width: 150px;
}
</style>
Is this what you're looking for?
For axios POST request, the request should be something like this:
The key here is that the responseType
and header
fields must be in the 3rd parameter of Post. The 2nd parameter is the application parameters.
export const requestDownloadReport = (requestParams) => async dispatch => {
let response = null;
try {
response = await frontEndApi.post('createPdf', {
requestParams: requestParams,
},
{
responseType: 'arraybuffer', // important...because we need to convert it to a blob. If we don't specify this, response.data will be the raw data. It cannot be converted to blob directly.
headers: {
'Content-Type': 'application/json',
'Accept': 'application/pdf'
}
});
}
catch(err) {
console.log('[requestDownloadReport][ERROR]', err);
return err
}
return response;
}
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
This article may help you along the way: http://drewww.github.io/socket.io-benchmarking/
I wondered the same question, so I ended up writing a small test (using XHR-polling) to see when the connections started to fail (or fall behind). I found (in my case) that the sockets started acting up at around 1400-1800 concurrent connections.
This is a short gist I made, similar to the test I used: https://gist.github.com/jmyrland/5535279
For me it was a simple case of specifying the path to the 'sdk' subfolder rather than the top level folder.
In my case I needed to input
/Users/Myusername/Documents/adt-bundle-mac-x86_64-20140321/sdk
instead of
/Users/Myusername/Documents/adt-bundle-mac-x86_64-20140321
If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.
def foo():
print(self.bar)
>NameError: name 'self' is not defined
def foo(self):
print(self.bar)
This can be also thought of as a simple map reduce operation if you would like to think of it from a functional programming perspective.
import os
folders = [("home",".vim"),("home","zathura")]
[reduce(lambda x,y: os.path.join(x,y), each, "") for each in folders]
reduce
is builtin in Python 2.x. In Python 3.x it has been moved to itertools
However the accepted the answer is better.
This has been answered below but answering if you have a list of items that needs to be joined.
Thought about using the test to pass in the vars? Something like:
Test input would be something like:
{
"TABLE_NAME": "MyDevTable",
"PARTITION_KEY": "REGION",
"SORT_KEY": "COUNTRY"
}
Adjusted your code to accept the inputs:
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10' });
exports.handler = async (event) => {
const TABLE_NAME = event.TABLE_NAME;
const PARTITION_KEY = event.PARTITION_KEY;
const SORT_KEY = event.SORT_KEY;
let params = {
TableName: TABLE_NAME,
};
console.log(`keys: ${PARTITION_KEY} ${SORT_KEY}`);
let items = [];
let data = await docClient.scan(params).promise();
items = [...items, ...data.Items];
while (typeof data.LastEvaluatedKey != 'undefined') {
params.ExclusiveStartKey = data.LastEvaluatedKey;
data = await docClient.scan(params).promise();
items = [...items, ...data.Items];
}
let leftItems = items.length;
let group = [];
let groupNumber = 0;
console.log('Total items to be deleted', leftItems);
for (const i of items) {
// console.log(`item: ${i[PARTITION_KEY] } ${i[SORT_KEY]}`);
const deleteReq = {DeleteRequest: {Key: {},},};
deleteReq.DeleteRequest.Key[PARTITION_KEY] = i[PARTITION_KEY];
deleteReq.DeleteRequest.Key[SORT_KEY] = i[SORT_KEY];
// console.log(`DeleteRequest: ${JSON.stringify(deleteReq)}`);
group.push(deleteReq);
leftItems--;
if (group.length === 25 || leftItems < 1) {
groupNumber++;
console.log(`Batch ${groupNumber} to be deleted.`);
const params = {
RequestItems: {
[TABLE_NAME]: group,
},
};
await docClient.batchWrite(params).promise();
console.log(
`Batch ${groupNumber} processed. Left items: ${leftItems}`
);
// reset
group = [];
}
}
const response = {
statusCode: 200,
// Uncomment below to enable CORS requests
headers: {
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
Java is confusing because everything is passed by value. However for a parameter of reference type (i.e. not a parameter of primitive type) it is the reference itself which is passed by value, hence it appears to be pass-by-reference (and people often claim that it is). This is not the case, as shown by the following:
Object o = "Hello";
mutate(o)
System.out.println(o);
private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!
Will print Hello
to the console. The options if you wanted the above code to print Goodbye
are to use an explicit reference as follows:
AtomicReference<Object> ref = new AtomicReference<Object>("Hello");
mutate(ref);
System.out.println(ref.get()); //Goodbye!
private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }
a = ["A", "B", "C", "B", "A"]
b = a.select {|e| a.count(e) > 1}.uniq
c = a - b
d = b + c
Results
d
=> ["A", "B", "C"]
From Wikipedia (you can read which is correct for your OS at that article):
Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A).
My full example is here, but I will provide a summary below.
Layout
Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).
Make the swift file the xib file's owner.
Add the following code to the .swift file and hook up the outlets and actions from the .xib file.
import UIKit
class ResuableCustomView: UIView {
let nibName = "ReusableCustomView"
var contentView: UIView?
@IBOutlet weak var label: UILabel!
@IBAction func buttonTap(_ sender: UIButton) {
label.text = "Hi"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let view = loadViewFromNib() else { return }
view.frame = self.bounds
self.addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}
Use it
Use your custom view anywhere in your storyboard. Just add a UIView
and set the class name to your custom class name.
For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.
MyCustomClass.swift
MyCustomClass.xib
File's Owner
of the .xib file to be your custom class (MyCustomClass
)class
value (under the identity Inspector
) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.Assistant Editor
.
Connections Inspector
you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass
), but rather reference File's Owner
. Since File's Owner
is specified to be your custom class, the outlets will hook up and work propery. NibLoadable
protocol referenced below.
.swift
file name is different from your .xib
file name, then set the nibName
property to be the name of your .xib
file.required init?(coder aDecoder: NSCoder)
and override init(frame: CGRect)
to call setupFromNib()
like the example below.MyCustomClass
).Here is the protocol you will want to reference:
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
public static var nibName: String {
return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
}
public static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
And here is an example of MyCustomClass
that implements the protocol (with the .xib file being named MyCustomClass.xib
):
@IBDesignable
class MyCustomClass: UIView, NibLoadable {
@IBOutlet weak var myLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupFromNib()
}
}
NOTE: If you miss the Gotcha and set the class
value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS
error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder)
method which then calls Self.nib.instantiate
and calls the init
again.
I have set a php code which can help in case you want to access Instagram images without api on basis of hashtag
You can create an array of all the objects inside the dictionary and then use it as a datasource for the TableView.
NSArray *aValuesArray = [yourDict allValues];
NOSQL has no special advantages over the relational database model. NOSQL does address certain limitations of current SQL DBMSs but it doesn't imply any fundamentally new capabilities over previous data models.
NOSQL means only no SQL (or "not only SQL") but that doesn't mean the same as no relational. A relational database in principle would make a very good NOSQL solution - it's just that none of the current set of NOSQL products uses the relational model.
You can try this solution :-
To have mysql asking you for a password, you also need to specify the -p-option: (try with space between -p and password)
mysql -u root -p new_password
In the Second link someone has commented the same problem.
This should work:
start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2
The start
command interprets the first argument as a window title if it contains spaces. In this case, that means start
considers your whole argument a title and sees no command. Passing ""
(an empty title) as the first argument to start
fixes the problem.
@Andrew and @CZFox
I had the same bug and found the cause to be that parameter one is in fact: http://www.example.com?param1
and not param1
which is what one would expect.
By removing all characters before and including the question mark fixes this problem. So in essence the HttpUtility.ParseQueryString
function only requires a valid query string parameter containing only characters after the question mark as in:
HttpUtility.ParseQueryString ( "param1=good¶m2=bad" )
My workaround:
string RawUrl = "http://www.example.com?param1=good¶m2=bad";
int index = RawUrl.IndexOf ( "?" );
if ( index > 0 )
RawUrl = RawUrl.Substring ( index ).Remove ( 0, 1 );
Uri myUri = new Uri( RawUrl, UriKind.RelativeOrAbsolute);
string param1 = HttpUtility.ParseQueryString( myUri.Query ).Get( "param1" );`
Python's eager in its evaluation, so eval(input(...))
(Python 3) will evaluate the user's input as soon as it hits the eval
, regardless of what you do with the data afterwards. Therefore, this is not safe, especially when you eval
user input.
Use ast.literal_eval
.
As an example, entering this at the prompt could be very bad for you:
__import__('os').system('rm -rf /a-path-you-really-care-about')
How to tell on Ubuntu if apache2 is running:
sudo service apache2 status
/etc/init.d/apache2 status
ps aux | grep apache
If you git stash pop
(with no conflicts) it will remove the stash after it is applied. But if you git stash apply
it will apply the patch without removing it from the stash list. Then you can revert the unwanted changes with git checkout -- files...
You can do this in many ways before clicking on add items:
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.elementToBeClickable(By.id("urelementid")));// instead of id u can use cssSelector or xpath of ur element.
or
wait.until(ExpectedConditions.visibilityOfElementLocated("urelement"));
You can also wait like this. If you want to wait until invisible of previous page element:
wait.until(ExpectedConditions.invisibilityOfElementLocated("urelement"));
Here is the link where you can find all the Selenium WebDriver APIs that can be used for wait
and its documentation.
You could try:
#!/bin/bash
### $1 == the first args to this script
### usage: script.sh /path/to/dir/
for f in `find . -maxdepth 1 -mindepth 1 -type d`; do
cd "$f"
<your job here>
done
or similar...
Explanation:
find . -maxdepth 1 -mindepth 1 -type d
:
Only find directories with a maximum recursive depth of 1 (only the subdirectories of $1) and minimum depth of 1 (excludes current folder .
)
The above answers did not help so what I did was:
.modal {
-webkit-overflow-scrolling: touch;
}
My particular problem was when I increased the modal size after loading.
It's a known iOS issue, see here. Since it does not break anything else the above solution was enough for my needs.
The complete syntax depends on the database engine you're working with:
For SQL Server:
CASE case-expression
WHEN when-expression-1 THEN value-1
[ WHEN when-expression-n THEN value-n ... ]
[ ELSE else-value ]
END
or:
CASE
WHEN boolean-when-expression-1 THEN value-1
[ WHEN boolean-when-expression-n THEN value-n ... ]
[ ELSE else-value ]
END
expressions, etc:
case-expression - something that produces a value
when-expression-x - something that is compared against the case-expression
value-1 - the result of the CASE statement if:
the when-expression == case-expression
OR the boolean-when-expression == TRUE
boolean-when-exp.. - something that produces a TRUE/FALSE answer
Link: CASE (Transact-SQL)
Also note that the ordering of the WHEN statements is important. You can easily write multiple WHEN clauses that overlap, and the first one that matches is used.
Note: If no ELSE clause is specified, and no matching WHEN-condition is found, the value of the CASE expression will be NULL.
driver.switchTo().frame()
has multiple overloads.
driver.switchTo().frame(name_or_id)
Here your iframe
doesn't have id or name, so not for you.
driver.switchTo().frame(index)
This is the last option to choose, because using index is not stable enough as you could imagine. If this is your only iframe in the page, try driver.switchTo().frame(0)
driver.switchTo().frame(iframe_element)
The most common one. You locate your iframe like other elements, then pass it into the method.
Here locating it by title
attributes seems to be the best.
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));
// driver.switchTo().frame(driver.findElement(By.xpath(".//iframe[@title='Fill Quote']")));
Run the following from the command prompt:
set Path="C:\Program Files\Java\jdk1.7.0_09\bin"
or
set PATH="C:\Program Files\Java\jdk1.7.0_09\bin"
I have tried this and it works well.
Simply u can add this to jquery.validationEngine-en.js file
"onlyLetterNumberSp": {
"regex": ^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$,
"alertText": "* No special characters allowed"
},
and call it in text field as
<input type="text" class="form-control validate[required,custom[onlyLetterNumberSp]]" id="title" name="title" placeholder="Title"/>
Your question says "Internet Explorer," but for those interested in other browsers, you can now use all: unset
on buttons to unstyle them.
It doesn't work in IE, but it's well-supported everywhere else.
https://caniuse.com/#feat=css-all
Old Safari color warning: Setting the text color
of the button after using all: unset
can fail in Safari 13.1, due to a bug in WebKit. (The bug is fixed in Safari 14 and up.) "all: unset
is setting -webkit-text-fill-color
to black, and that overrides color." If you need to set text color
after using all: unset
, be sure to set both the color
and the -webkit-text-fill-color
to the same color.
Accessibility warning: For the sake of users who aren't using a mouse pointer, be sure to re-add some :focus
styling, e.g. button:focus { outline: orange auto 5px }
for keyboard accessibility.
And don't forget cursor: pointer
. all: unset
removes all styling, including the cursor: pointer
, which makes your mouse cursor look like a pointing hand when you hover over the button. You almost certainly want to bring that back.
button {
all: unset;
color: blue;
-webkit-text-fill-color: blue;
cursor: pointer;
}
button:focus {
outline: orange 5px auto;
}
_x000D_
<button>check it out</button>
_x000D_
This can also be done in later versions of handlebars using the key=value
notation:
{{> mypartial foo='bar' }}
Allowing you to pass specific values to your partial context.
Reference: Context different for partial #182
I see .btn:focus
has an outline
on it:
.btn:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
Try changing this to:
.btn:focus {
outline: none !important;
}
Basically, look for any instances of outline
on :focus
ed elements — that's what's causing it.
Update - For Bootstrap v4:
.btn:focus {
box-shadow: none;
}
In MonoTouch:
To get the Major version use:
UIDevice.CurrentDevice.SystemVersion.Split('.')[0]
For minor version use:
UIDevice.CurrentDevice.SystemVersion.Split('.')[1]
select definition from pg_views where viewname = 'my_view'
Just insert <input>
element in <td>
dynamically, on cell click. Only simple HTML and Javascript. No need for contentEditable
, jquery
, HTML5
We can run Linux containers on Windows. Docker for Windows uses Hyper-v based Linux-Kit or WSL2 as backend to facilitate Linux containers.
If any Linux distribution having this kind of setup, we can run Windows containers. Docker for Linux supports only Linux containers.
i encountered the same error but in my case i was cloning a project, the cloned project was built with Android API 22 which i did not install at the time(i had API 24 and 25 installed)........so i had to download the sdk tools for API 22
With a few tricks you can actually pass named parameters to functions, along with arrays.
The method I developed allows you to access parameters passed to a function like this:
testPassingParams() {
@var hello
l=4 @array anArrayWithFourElements
l=2 @array anotherArrayWithTwo
@var anotherSingle
@reference table # references only work in bash >=4.3
@params anArrayOfVariedSize
test "$hello" = "$1" && echo correct
#
test "${anArrayWithFourElements[0]}" = "$2" && echo correct
test "${anArrayWithFourElements[1]}" = "$3" && echo correct
test "${anArrayWithFourElements[2]}" = "$4" && echo correct
# etc...
#
test "${anotherArrayWithTwo[0]}" = "$6" && echo correct
test "${anotherArrayWithTwo[1]}" = "$7" && echo correct
#
test "$anotherSingle" = "$8" && echo correct
#
test "${table[test]}" = "works"
table[inside]="adding a new value"
#
# I'm using * just in this example:
test "${anArrayOfVariedSize[*]}" = "${*:10}" && echo correct
}
fourElements=( a1 a2 "a3 with spaces" a4 )
twoElements=( b1 b2 )
declare -A assocArray
assocArray[test]="works"
testPassingParams "first" "${fourElements[@]}" "${twoElements[@]}" "single with spaces" assocArray "and more... " "even more..."
test "${assocArray[inside]}" = "adding a new value"
In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in bash 4.3 though)! Plus, the mapped variables are all in the local scope, just as $1 (and others).
The code that makes this work is pretty light and works both in bash 3 and bash 4 (these are the only versions I've tested it with). If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below was developed for that purpose.
Function.AssignParamLocally() {
local commandWithArgs=( $1 )
local command="${commandWithArgs[0]}"
shift
if [[ "$command" == "trap" || "$command" == "l="* || "$command" == "_type="* ]]
then
paramNo+=-1
return 0
fi
if [[ "$command" != "local" ]]
then
assignNormalCodeStarted=true
fi
local varDeclaration="${commandWithArgs[1]}"
if [[ $varDeclaration == '-n' ]]
then
varDeclaration="${commandWithArgs[2]}"
fi
local varName="${varDeclaration%%=*}"
# var value is only important if making an object later on from it
local varValue="${varDeclaration#*=}"
if [[ ! -z $assignVarType ]]
then
local previousParamNo=$(expr $paramNo - 1)
if [[ "$assignVarType" == "array" ]]
then
# passing array:
execute="$assignVarName=( \"\${@:$previousParamNo:$assignArrLength}\" )"
eval "$execute"
paramNo+=$(expr $assignArrLength - 1)
unset assignArrLength
elif [[ "$assignVarType" == "params" ]]
then
execute="$assignVarName=( \"\${@:$previousParamNo}\" )"
eval "$execute"
elif [[ "$assignVarType" == "reference" ]]
then
execute="$assignVarName=\"\$$previousParamNo\""
eval "$execute"
elif [[ ! -z "${!previousParamNo}" ]]
then
execute="$assignVarName=\"\$$previousParamNo\""
eval "$execute"
fi
fi
assignVarType="$__capture_type"
assignVarName="$varName"
assignArrLength="$__capture_arrLength"
}
Function.CaptureParams() {
__capture_type="$_type"
__capture_arrLength="$l"
}
alias @trapAssign='Function.CaptureParams; trap "declare -i \"paramNo+=1\"; Function.AssignParamLocally \"\$BASH_COMMAND\" \"\$@\"; [[ \$assignNormalCodeStarted = true ]] && trap - DEBUG && unset assignVarType && unset assignVarName && unset assignNormalCodeStarted && unset paramNo" DEBUG; '
alias @param='@trapAssign local'
alias @reference='_type=reference @trapAssign local -n'
alias @var='_type=var @param'
alias @params='_type=params @param'
alias @array='_type=array @param'
This will list all jpg
files in the folder you define under url: and append them to a div
as a paragraph. Can do it with ul li
as well.
$.ajax({
url: "YOUR FOLDER",
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
// will loop through
var images = $(this).attr("href");
$('<p></p>').html(images).appendTo('a div of your choice')
});
}
});
I was having the similar issue when using VirtualBox on Ubuntu 12.04LTS. Now if anyone is using or has ever used Ubuntu, you might be aware that how things are hard sometimes when using shortcut keys in Ubuntu. For me, when i was trying to revert back the Host key, it was just not happening and the shortcut keys won't just work. I even tried the command line option to revert back the scale mode and it won't work either. Finally i found the following when all the other options fails:
Fix the Scale Mode Issue in Oracle VirtualBox in Ubuntu using the following steps:
Find your machine config files (i.e. /home/<username>/VirtualBox VMs/ANKSVM
) where ANKSVM is your VM Name and edit and change the following
in ANKSVM.vbox
and ANKSVM.vbox-prev
files:
Edit the line: <ExtraDataItem name="GUI/Scale" value="on"/>
to
<ExtraDataItem name="GUI/Scale" value="off"/>
Restart VirtualBox
You are done.
This works every time specially when all other options fails like how it happened for me.
It's funny because I'm learning Angular myself and was watching some video's from their channel on Youtube. The speaker mentions your exact problem in this video https://www.youtube.com/watch?v=ZhfUv0spHCY#t=1681 around the 28:30 minute mark.
It comes down to placing that particular piece of code in a service rather then a controller.
My guess would be to inject new popup elements into the DOM and handle them separate instead of showing and hiding the same element. This way you can have multiple popups.
The whole video is very interesting to watch as well :-)
I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6.
public class CustomObjectMapper extends ObjectMapper {
@PostConstruct
public void customConfiguration() {
// Uses Enum.toString() for serialization of an Enum
this.enable(WRITE_ENUMS_USING_TO_STRING);
// Uses Enum.toString() for deserialization of an Enum
this.enable(READ_ENUMS_USING_TO_STRING);
}
}
There are more enum-related features available, see here:
https://github.com/FasterXML/jackson-databind/wiki/Serialization-features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features
// The following method would return you timestamp after converting to milliseconds. [RETURNS STRING]
- (NSString *) timeInMiliSeconds
{
NSDate *date = [NSDate date];
NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];
return timeInMS;
}
I had this problem because a dll I was using had Sqlite as a dependency (configured in NuGet with only the Sqlite core package.). The project compiles and copies all the Sqlite dll-s except the 'SQLite.Interop.dll' (both x86 and x64 folder).
The solution was very simple: just add the System.Data.SQLite.Core package as a dependency (with NuGet) to the project you are building/running and the dll-s will be copied.
If optimizing for dev + production, you could try something like this in your config:
const dev = process.env.NODE_ENV !== 'production'
// in config
{
devtool: dev ? 'eval-cheap-module-source-map' : 'source-map',
}
I am using webpack 2.1.0-beta.19
I am installing pyfuzzy
but is is not in PyPI; it returns the message: No matching distribution found for pyfuzzy
.
I tried the accepted answer
pip install --no-index --find-links=file:///Users/victor/Downloads/pyfuzzy-0.1.0 pyfuzzy
But it does not work either and returns the following error:
Ignoring indexes: https://pypi.python.org/simple Collecting pyfuzzy Could not find a version that satisfies the requirement pyfuzzy (from versions: ) No matching distribution found for pyfuzzy
At last , I have found a simple good way there: https://pip.pypa.io/en/latest/reference/pip_install.html
Install a particular source archive file.
$ pip install ./downloads/SomePackage-1.0.4.tar.gz
$ pip install http://my.package.repo/SomePackage-1.0.4.zip
So the following command worked for me:
pip install ../pyfuzzy-0.1.0.tar.gz.
Hope it can help you.
An example with variable (ES6):
const item = document.querySelector([data-itemid="${id}"]
);
$('#abc span').text('baa baa black sheep');
$('#abc span').html('baa baa <strong>black sheep</strong>');
text()
if just text content. html()
if it contains, well, html content.
My bootstrap version was pointing to bootstap4-alpha,
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn"
crossorigin="anonymous"></script>
changed to 4-beta
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"
integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1"
crossorigin="anonymous"></script>
and it started working
For result find: Click Here
Screen is a full-screen window manager that multiplexes a physical terminal between several processes, typically interactive shells. There is a scrollback history buffer for each virtual terminal and a copy-and-paste mechanism that allows the user to move text regions between windows.
if using react:
const html = ReactDOM.findDOMNode(document.getElementsByTagName('html')[0]).outerHTML;
Here is a library that does the job well https://github.com/thellimist/SwiftRandom
public extension Int {
/// SwiftRandom extension
public static func random(lower: Int = 0, _ upper: Int = 100) -> Int {
return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}
}
public extension Double {
/// SwiftRandom extension
public static func random(lower: Double = 0, _ upper: Double = 100) -> Double {
return (Double(arc4random()) / 0xFFFFFFFF) * (upper - lower) + lower
}
}
public extension Float {
/// SwiftRandom extension
public static func random(lower: Float = 0, _ upper: Float = 100) -> Float {
return (Float(arc4random()) / 0xFFFFFFFF) * (upper - lower) + lower
}
}
public extension CGFloat {
/// SwiftRandom extension
public static func random(lower: CGFloat = 0, _ upper: CGFloat = 1) -> CGFloat {
return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (upper - lower) + lower
}
}
The Tkinter library in the Python standard library is an interactive tool which you can import. Basically, you can create buttons and boxes and popups and stuff that appear as windows which you manipulate with code.
If you use Tkinter, do not use time.sleep()
, because it will muck up your program. This happened to me. Instead, use root.after()
and replace the values for however many seconds, with a milliseconds. For example, time.sleep(1)
is equivalent to root.after(1000)
in Tkinter.
Otherwise, time.sleep()
, which many answers have pointed out, which is the way to go.
math.log2(x)
import math
log2 = math.log(x, 2.0)
log2 = math.log2(x) # python 3.3 or later
math.frexp(x)
If all you need is the integer part of log base 2 of a floating point number, extracting the exponent is pretty efficient:
log2int_slow = int(math.floor(math.log(x, 2.0)))
log2int_fast = math.frexp(x)[1] - 1
Python frexp() calls the C function frexp() which just grabs and tweaks the exponent.
Python frexp() returns a tuple (mantissa, exponent). So [1]
gets the exponent part.
For integral powers of 2 the exponent is one more than you might expect. For example 32 is stored as 0.5x26. This explains the - 1
above. Also works for 1/32 which is stored as 0.5x2?4.
Floors toward negative infinity, so log231 computed this way is 4 not 5. log2(1/17) is -5 not -4.
x.bit_length()
If both input and output are integers, this native integer method could be very efficient:
log2int_faster = x.bit_length() - 1
- 1
because 2n requires n+1 bits. Works for very large integers, e.g. 2**10000
.
Floors toward negative infinity, so log231 computed this way is 4 not 5.
You can use insert
to specify where you want to new column to be. In this case, I use 0
to place the new column at the left.
df.insert(0, 'Name', 'abc')
Name Date Open High Low Close
0 abc 01-01-2015 565 600 400 450
what about that simple way)
$(document).ready ->
$('#datepicker').datepicker( dateFormat: 'yy-mm-dd', onSelect: (dateStr) ->
alert dateStr # yy-mm-dd
#OR
alert $("#datepicker").val(); # yy-mm-dd
You should use:
URLEncoder.encode("NAME", "UTF-8");
Use schema name with period in psql command to obtain information about this schema.
Setup:
test=# create schema test_schema;
CREATE SCHEMA
test=# create table test_schema.test_table (id int);
CREATE TABLE
test=# create table test_schema.test_table_2 (id int);
CREATE TABLE
Show list of relations in test_schema
:
test=# \dt test_schema.
List of relations
Schema | Name | Type | Owner
-------------+--------------+-------+----------
test_schema | test_table | table | postgres
test_schema | test_table_2 | table | postgres
(2 rows)
Show test_schema.test_table
definition:
test=# \d test_schema.test_table
Table "test_schema.test_table"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Show all tables in test_schema
:
test=# \d test_schema.
Table "test_schema.test_table"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Table "test_schema.test_table_2"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
etc...
Outside of character classes, it is conventional not to escape hyphens. If I saw an escaped hyphen outside of a character class, that would suggest to me that it was written by someone who was not very comfortable with regexes.
Inside character classes, I don't think one way is conventional over the other; in my experience, it usually seems to be to put either first or last, as in [-._:]
or [._:-]
, to avoid the backslash; but I've also often seen it escaped instead, as in [._\-:]
, and I wouldn't call that unconventional.
You need to use javaScript's parseInt()
method to turn the strings back into numbers. Right now they are strings so adding two strings concatenates them, which is why you're getting "12".
Use while loop like this:
while IFS= read -r line || [ -n "$line" ]; do
echo "$line"
done <file
Or using grep
with while loop:
while IFS= read -r line; do
echo "$line"
done < <(grep "" file)
Using grep .
instead of grep ""
will skip the empty lines.
Note:
Using IFS=
keeps any line indentation intact.
File without a newline at the end isn't a standard unix text file.
There are a number of limitations, notably:
http://www.dotnetspider.com/tutorials/SqlServer-Tutorial-158.aspx http://www.microsoft.com/sqlserver/2008/en/us/editions.aspx
With regards to the number of databases, this MSDN article says there's no limit:
The 4 GB database size limit applies only to data files and not to log files. However, there are no limits to the number of databases that can be attached to the server.
However, as mentioned in the comments and above, the database size limit was raised to 10GB in 2008 R2 and 2012. Also, this 10GB limit only applies to relational data, and Filestream data does not count towards this limit (http://msdn.microsoft.com/en-us/library/bb895334.aspx).
The issue is that the Android User-Agent is a general User-Agent and there is no difference between tablet Android and mobile Android.
This is incorrect. Mobile Android has "Mobile" string in the User-Agent header. Tablet Android does not.
But it is worth mentioning that there are quite a few tablets that report "Mobile" Safari in the userAgent and the latter is not the only/solid way to differentiate between Mobile and Tablet.
You use a shebang line at the start of your script:
#!/usr/bin/env python
make the file executable:
chmod +x arbitraryname
and put it in a directory on your PATH (can be a symlink):
cd ~/bin/
ln -s ~/some/path/to/myscript/arbitraryname
with open('test.txt', 'r') as inf, open('test1.txt', 'w') as outf:
for line in inf:
line = line.strip()
if line:
try:
outf.write(str(int(line, 16)))
outf.write('\n')
except ValueError:
print("Could not parse '{0}'".format(line))
You can do it using heap memory (through malloc() invocation) like other answers reported here, but you must always manage the memory (use free() function everytime you call your function). You can also do it with a static array:
char* returnArrayPointer()
{
static char array[SIZE];
// do something in your array here
return array;
}
You can than use it without worrying about memory management.
int main()
{
char* myArray = returnArrayPointer();
/* use your array here */
/* don't worry to free memory here */
}
In this example you must use static keyword in array definition to set to application-long the array lifetime, so it will not destroyed after return statement. Of course, in this way you occupy SIZE bytes in your memory for the entire application life, so size it properly!
Since Facebook's Android SDK v4.0 you need to execute the following:
LoginManager.getInstance().logOut();
This is not sufficient. This will simply clear cached access token and profile so that AccessToken.getCurrentAccessToken()
and Profile.getCurrentProfile()
will now become null.
To completely logout you need to revoke permissions and then call LoginManager.getInstance().logOut();
. To revoke permission execute following graph API -
GraphRequest delPermRequest = new GraphRequest(AccessToken.getCurrentAccessToken(), "/{user-id}/permissions/", null, HttpMethod.DELETE, new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse graphResponse) {
if(graphResponse!=null){
FacebookRequestError error =graphResponse.getError();
if(error!=null){
Log.e(TAG, error.toString());
}else {
finish();
}
}
}
});
Log.d(TAG,"Executing revoke permissions with graph path" + delPermRequest.getGraphPath());
delPermRequest.executeAsync();
$str = basename($url);
In case you are as talented as me and have made the Window menu invisible, there is no way back, as the Customize and Reset Perspective are no longer available. Having good other perspectives do not help, as you only can apparently edit the current perspective only. To get out without nuking all the workspace settings, the following may work:
<persistedState key="persp.hiddenItems"
for the perspective in question. value
, which is a comma-separated list. You may look through the list and manually remove list items from this value which look like they need to be unhidden. In my case, the offending element appeared close to the beginning of the file:
<children xsi:type="advanced:Perspective" xmi:id="..." elementId="org.eclipse.cdt.ui.CPerspective" selectedElement="..." label="C/C++" iconURI="platform:/plugin/org.eclipse.cdt.ui/icons/view16/c_pers.gif">
<persistedState key="persp.hiddenItems" value="persp.hideToolbarSC:org.eclipse.jdt.ui.actions.OpenProjectWizard,...,"/>
where some parts were replaced with dots. Obviously, you need to be careful editing machine-generated files. Somebody may be able to write a script.
Now you can safely lock you out again.
Try something like this inside ThisOutlookSession
:
Private Sub Application_NewMail()
Call Your_main_macro
End Sub
My outlook vba just fired when I received an email and had that application event open.
Edit: I just tested a hello world msg box and it ran after being called in the application_newmail
event when an email was received.
The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this
Maybe not as elegant but another possibility would be to write a formula to do the check and fill it in an adjacent column. You could then filter on that column.
The following looks in cell b14 and would return true for all the file types you mention. This assumes that the file extension is by itself in the column. If it's not it would be a little more complicated but you could still do it this way.
=OR(B14=".pdf",B14=".doc",B14=".docx",B14=".xls",B14=".xlsx",B14=".rtf",B14=".txt",B14=".csv",B14=".pps")
Like I said, not as elegant as the advanced filters but options are always good.
In my case it was a simple type
$_SESSION['role' == 'ge']
I was missing the correct closing bracket
$_SESSION['role'] == 'ge'
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
select substring(your_field, CHARINDEX(';',your_field)+1 ,CHARINDEX('[',your_field)-CHARINDEX(';',your_field)-1) from your_table
Can't get the others to work. I believe you just want what is in between ';' and '[' in all cases regardless of how long the string in between is. After specifying the field in the substring function, the second argument is the starting location of what you will extract. That is, where the ';' is + 1 (fourth position - the c), because you don't want to include ';'. The next argument takes the location of the '[' (position 14) and subtracts the location of the spot after the ';' (fourth position - this is why I now subtract 1 in the query). This basically says substring(field,location I want substring to begin, how long I want substring to be). I've used this same function in other cases. If some of the fields don't have ';' and '[', you'll want to filter those out in the "where" clause, but that's a little different than the question. If your ';' was say... ';;;', you would use 3 instead of 1 in the example. Hope this helps!
By using typed arrays, you can store arrays of these types:
For example:
?var array = new Uint8Array(100);
array[42] = 10;
alert(array[42]);?
See it in action here.
Push only single file
git commit -m "Message goes here" filename
Push only two files.
git commit -m "Message goes here" file1 file2
import json
d = json.loads(j)
print d['glossary']['title']
As stated in other responses, the build tools requires the --all
flag to be installed. You also better use a -t
filter flag to avoid installing ALL the packages but there is no way to filter all the build tools.
There are already features requests for these two points in AOSP bug tracker. Feel free to vote for them, this might make them happen some day:
Update 2019.
You can now use the object-fit
css property that accepts the following values: fill | contain | cover | none | scale-down
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
As an example, you could have a container that holds an image.
<div class="container">
<img src="" class="container_img" />
</div>
.container {
height: 50px;
width: 50%;
.container_img {
height: 100%;
width: 100%;
object-fit: cover;
There might be a case where you reference everything you need to and you can even Go to Definition by pressing F12 on DbContext class which takes you to System.Data.Entity namespace but you still get this nasty compiler warning. Make sure that the Target Framework of your project and that of the Entity Framework version you are using match. Go to Project->Properties->Application Tab. Change the Target Framework(can't exactly say to which one, trial and error will help.). Just my two cents.
I will expand on the earlier answer about np.fliplr()
. Here is some code that demonstrates constructing a 1d array, transforming it into a 2d array, flipping it, then converting back into a 1d array. time.clock()
will be used to keep time, which is presented in terms of seconds.
import time
import numpy as np
start = time.clock()
x = np.array(range(3))
#transform to 2d
x = np.atleast_2d(x)
#flip array
x = np.fliplr(x)
#take first (and only) element
x = x[0]
#print x
end = time.clock()
print end-start
With print statement uncommented:
[2 1 0]
0.00203907123594
With print statement commented out:
5.59799927506e-05
So, in terms of efficiency, I think that's decent. For those of you that love to do it in one line, here is that form.
np.fliplr(np.atleast_2d(np.array(range(3))))[0]
A complete example for scripted pipepline:
stage('Build'){
withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
sh 'bash build.sh'
}
}
Because I encountered this issue just a little while ago, and the options for Rails 3.0 are a bit different, I'll provide another answer to this question.
In Rails 3.0 you want to do something like this:
class MyModel < ActiveRecord::Base
after_initialize :default_values
private
def default_values
self.name ||= "default value"
end
end
Append the line useUnicode=true&characterEncoding=UTF-8
to your jdbc url.
In your case the data is not being send using UTF-8
encoding.
Simply use Hash[*array_variable.flatten]
For example:
a1 = ['apple', 1, 'banana', 2]
h1 = Hash[*a1.flatten(1)]
puts "h1: #{h1.inspect}"
a2 = [['apple', 1], ['banana', 2]]
h2 = Hash[*a2.flatten(1)]
puts "h2: #{h2.inspect}"
Using Array#flatten(1)
limits the recursion so Array
keys and values work as expected.
Use composition:
class ClassC
{
public ClassA A { get; set; }
public ClassB B { get; set; }
public C (ClassA a, ClassB b)
{
this.A = a;
this.B = b;
}
}
Then you can call C.A.DoA()
. You also can change the properties to an interface or abstract class, like public InterfaceA A
or public AbstractClassA A
.
It turns out I was just missing DECIMAL
on the CAST()
description:
DECIMAL[(M[,D])]
Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.
Thus, the following query worked:
UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));
I have come here from another question, which has been duplicate of this question (Generating unique random number in java)
Store 1 to 100 numbers in an Array.
Generate random number between 1 to 100 as position and return array[position-1] to get the value
Once you use a number in array, mark the value as -1 ( No need to maintain another array to check if this number is already used)
If value in array is -1, get the random number again to fetch new location in array.
You can use:ls -lh
, then you will get a list of file information
To install GLIBC_2.14 or GLIBC_2.15, download package from /gnu/libc/ index at
Then follow instructions listed by Timo:
For example glibc-2.14.tar.gz in your case.
tar xvfz glibc-2.14.tar.gz
cd glibc-2.14
mkdir build
cd build
../configure --prefix=/opt/glibc-2.14
make
sudo make install
export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH
$user_ip=$_SERVER['REMOTE_ADDR'];
$check_ip = mysql_query("select userip from pageview where page='yourpage' and userip='$user_ip'");
if(mysql_num_rows($check_ip)>=1)
{
}
else
{
$insertview = mysql_query("insert into pageview values('','yourpage','$user_ip')");
$updateview = mysql_query("update totalview set totalvisit = totalvisit+1 where page='yourpage' ");
}
code from talkerscode official tutorial if you have any problem http://talkerscode.com/webtricks/create-a-simple-pageviews-counter-using-php-and-mysql.php
For people still looking a couple of years later, things have changed a bit. You can now use the queue
for .fadeIn()
as well so that it will work like this:
$('.tooltip').fadeIn({queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');
This has the benefit of working on display: none
elements so you don't need the extra two lines of code.
For me, the next worked well:
I wrapped the header and the content on a div
<div class="main-wrapper">
<div class="header">
</div>
<div class="content">
</div>
</div>
I used this reference to fill the height with flexbox. The CSS goes like this:
.main-wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.header {
flex: 1;
}
.content {
flex: 1;
}
For more info about the flexbox technique, visit the reference
Use the built-in ERRORLEVEL Variable:
echo %ERRORLEVEL%
But beware if an application has defined an environment variable named ERRORLEVEL!
I've tryied all answers of this topic, but just this below worked fine on my project.
Angular 7 and AGM Core 1.0.0-beta.7
<agm-map [latitude]="lat" [longitude]="long" [zoom]="zoom" [fitBounds]="true">
<agm-marker latitude="{{localizacao.latitude}}" longitude="{{localizacao.longitude}}" [agmFitBounds]="true"
*ngFor="let localizacao of localizacoesTec">
</agm-marker>
</agm-map>
The properties [agmFitBounds]="true"
at agm-marker
and [fitBounds]="true"
at agm-map
does the job
GCC works fine. Note that MSVC is not necessarily a valid solution because it does not support C99.
Here's a solution for you, using only one very tiny and simple image and one automatically generated span element:
span.stars, span.stars span {
display: block;
background: url(stars.png) 0 -16px repeat-x;
width: 80px;
height: 16px;
}
span.stars span {
background-position: 0 0;
}
(source: ulmanen.fi)
Note: do NOT hotlink to the above image! Copy the file to your own server and use it from there.
$.fn.stars = function() {
return $(this).each(function() {
// Get the value
var val = parseFloat($(this).html());
// Make sure that the value is in 0 - 5 range, multiply to get width
var size = Math.max(0, (Math.min(5, val))) * 16;
// Create stars holder
var $span = $('<span />').width(size);
// Replace the numerical value with stars
$(this).html($span);
});
}
If you want to restrict the stars to only half or quarter star sizes, add one of these rows before the var size
row:
val = Math.round(val * 4) / 4; /* To round to nearest quarter */
val = Math.round(val * 2) / 2; /* To round to nearest half */
<span class="stars">4.8618164</span>
<span class="stars">2.6545344</span>
<span class="stars">0.5355</span>
<span class="stars">8</span>
$(function() {
$('span.stars').stars();
});
(source: ulmanen.fi)
This will probably suit your needs. With this method you don't have to calculate any three quarter or whatnot star widths, just give it a float and it'll give you your stars.
A small explanation on how the stars are presented might be in order.
The script creates two block level span elements. Both of the spans initally get a size of 80px * 16px and a background image stars.png. The spans are nested, so that the structure of the spans looks like this:
<span class="stars">
<span></span>
</span>
The outer span gets a background-position
of 0 -16px
. That makes the gray stars in the outer span visible. As the outer span has height of 16px and repeat-x
, it will only show 5 gray stars.
The inner span on the other hand has a background-position
of 0 0
which makes only the yellow stars visible.
This would of course work with two separate imagefiles, star_yellow.png and star_gray.png. But as the stars have a fixed height, we can easily combine them into one image. This utilizes the CSS sprite technique.
Now, as the spans are nested, they are automatically overlayed over each other. In the default case, when the width of both spans is 80px, the yellow stars completely obscure the grey stars.
But when we adjust the width of the inner span, the width of the yellow stars decreases, revealing the gray stars.
Accessibility-wise, it would have been wiser to leave the float number inside the inner span and hide it with text-indent: -9999px
, so that people with CSS turned off would at least see the floating point number instead of the stars.
Hopefully that made some sense.
Now even more compact and harder to understand! Can also be squeezed down to a one liner:
$.fn.stars = function() {
return $(this).each(function() {
$(this).html($('<span />').width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * 16));
});
}
The simplest way is to edit .git/config
Here is an example file
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
[remote "origin"]
url = [email protected]:repo-name
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "test1"]
remote = origin
merge = refs/heads/test1
[branch "master"]
remote = origin
merge = refs/heads/master
Delete the line merge = refs/heads/test1
in the test1
branch section
function updateURL(url_params) {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + url_params;
window.history.replaceState({path:newurl},'',newurl);
}
}
function setActiveTab(tab) {
$('.nav-tabs li').removeClass('active');
$('.tab-content .tab-pane').removeClass('active');
$('a[href="#tab-' + tab + '"]').closest('li').addClass('active');
$('#tab-' + tab).addClass('active');
}
// Set active tab
$url_params = new URLSearchParams(window.location.search);
// Get active tab and remember it
$('a[data-toggle="tab"]')
.on('click', function() {
$href = $(this).attr('href')
$active_tab = $href.replace('#tab-', '');
$url_params.set('tab', $active_tab);
updateURL($url_params.toString());
});
if ($url_params.has('tab')) {
$tab = $url_params.get('tab');
$tab = '#tab-' + $tab;
$myTab = JSON.stringify($tab);
$thisTab = $('.nav-tabs a[href=' + $myTab +']');
$('.nav-tabs a[href=' + $myTab +']').tab('show');
}
I think the SortedMap interface enforces what you ask for and TreeMap implements that.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/SortedMap.html http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html
Simply add a margin of x amount at the bottom of an item in your RecycleView Adapter
.
onCreateViewHolder
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, 0, 0, 5);
itemView.setLayoutParams(layoutParams);
If the function you called returns null, it means your phone number is not registered in your contact list.
If instead of the phone number you just need an unique number, you may use the sim card's serial number:
TelephonyManager telemamanger = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
The reason why your X-axis plots frequencies only till 500 Hz is your command statement 'f = Fs/2*linspace(0,1,NFFT/2+1);'. Your Fs is 1000. So when you divide it by 2 & then multiply by values ranging from 0 to 1, it returns a vector of length NFFT/2+1. This vector consists of equally spaced frequency values, ranging from 0 to Fs/2 (i.e. 500 Hz). Since you plot using 'plot(f,2*abs(Y(1:NFFT/2+1)))' command, your X-axis limit is 500 Hz.
This method works fine for me:
private void alert(string message)
{
Response.Write("<script>alert('" + message + "')</script>");
}
Example:
protected void Page_Load(object sender, EventArgs e)
{
alert("Hello world!");
}
And when your page load yo will see something like this:
I'm using .NET Framework 4.5 in Firefox.
Motivation: You want to print prettify JSON response after curl command request.
Solution: json_pp - commandline tool that converts between some input and output formats (one of them is JSON). This program was copied from json_xs and modified. The default input format is json and the default output format is json with pretty option.
Synposis:
json_pp [-v] [-f from_format] [-t to_format] [-json_opt options_to_json1[,options_to_json2[,...]]]
Formula: <someCommand> | json_pp
Example:
Request
curl -X https://jsonplaceholder.typicode.com/todos/1 | json_pp
Response
{
"completed" : false,
"id" : 1,
"title" : "delectus aut autem",
"userId" : 1
}
You cannot do that but you can do the opposite:
In your jsp you can:
String name = "John Allepe";
request.setAttribute("CustomerName", name);
Access the variable in the js:
var name = "<%= request.getAttribute("CustomerName") %>";
alert(name);
Another convenient way to copy the values from src ArrayList to dest Arraylist is as follows:
ArrayList<String> src = new ArrayList<String>();
src.add("test string1");
src.add("test string2");
ArrayList<String> dest= new ArrayList<String>();
dest.addAll(src);
This is actual copying of values and not just copying of reference.
I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)
With generic method you can require that the type implements New().
Public Function CloneObject(Of T As New)(ByVal src As T) As T
Dim result As T = Nothing
Dim cloneable = TryCast(src, ICloneable)
If cloneable IsNot Nothing Then
result = cloneable.Clone()
Else
result = New T
CopySimpleProperties(src, result, Nothing, "clone")
End If
Return result
End Function
With non-generic assume the type has a default constructor and catch an exception if it doesn't.
Public Function CloneObject(ByVal src As Object) As Object
Dim result As Object = Nothing
Dim cloneable As ICloneable
Try
cloneable = TryCast(src, ICloneable)
If cloneable IsNot Nothing Then
result = cloneable.Clone()
Else
result = Activator.CreateInstance(src.GetType())
CopySimpleProperties(src, result, Nothing, "clone")
End If
Catch ex As Exception
Trace.WriteLine("!!! CloneObject(): " & ex.Message)
End Try
Return result
End Function
After you've run the Inspect by Name, select all the locations, and make use of the Apply quick fixes to all the problems drop-down, and use either (or both) of Delete unused parameter(s) and Safe Delete.
Don't forget to hit Do Refactor afterwards.
Then you'll need to run another analysis, as the refactored code will no doubt reveal more unused declarations.
Others have mentioned the relevel
command which is the best solution if you want to change the base level for all analyses on your data (or are willing to live with changing the data).
If you don't want to change the data (this is a one time change, but in the future you want the default behavior again), then you can use a combination of the C
(note uppercase) function to set contrasts and the contr.treatments
function with the base argument for choosing which level you want to be the baseline.
For example:
lm( Sepal.Width ~ C(Species,contr.treatment(3, base=2)), data=iris )
This worked for me.
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};
fetch(`${url}`, requestOptions)
.then((res) => {
return res.blob();
})
.then((blob) => {
const href = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.setAttribute('download', 'config.json'); //or any other extension
document.body.appendChild(link);
link.click();
})
.catch((err) => {
return Promise.reject({ Error: 'Something Went Wrong', err });
})
use this code
var sid = $(this);
sid.attr('checked','checked');
This isn't exactly a "solution" to the problem, but more of a workaround. It only works as written with text, but can be changed to work with other elements as needed I'm sure.
.originalContent {
font-size:0px;
transition:font-size .2s ease-in-out;
}
.show { /* class to add to content */
font-size:14px;
}
Here is an example: http://codepen.io/overthemike/pen/wzjRKa
Essentially, you set the font-size to 0 and transition that instead of the height, or max-height, or scaleY() etc. at a quick enough pace to get the height to transform to what you want. To transform the actual height with CSS to auto isn't currently possible, but transforming the content within is, hence the font-size transition.
It's just mv srcdir/* targetdir/
.
If there are too many files in srcdir
you might want to try something like the following approach:
cd srcdir
find -exec mv {} targetdir/ +
In contrast to \;
the final +
collects arguments in an xargs
like manner instead of executing mv
once for every file.
Layout changes can occur whenever any of the following events happens in a view:
a. The size of a view’s bounds rectangle changes.
b. An interface orientation change occurs, which usually triggers a change in the root view’s bounds rectangle.
c. The set of Core Animation sublayers associated with the view’s layer changes and requires layout.
d. Your application forces layout to occur by calling thesetNeedsLayout
orlayoutIfNeeded
method of a view.
e. Your application forces layout by calling thesetNeedsLayout
method of the view’s underlying layer object.
An equivalent statement would be
select * from [TableName] limit 5
The short answer is "yes". A sample ldapsearch
command to query an Active Directory server is:
ldapsearch \
-x -h ldapserver.mydomain.com \
-D "[email protected]" \
-W \
-b "cn=users,dc=mydomain,dc=com" \
-s sub "(cn=*)" cn mail sn
This would connect to an AD server at hostname ldapserver.mydomain.com
as user [email protected]
, prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com
subtree.
See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.
If you want to get a floating point value with two decimal places limited at the time of calling input,
Check this out ~
a = eval(format(float(input()), '.2f')) # if u feed 3.1415 for 'a'.
print(a) # output 3.14 will be printed.
When I'm faced with an enormous log file, I don't try to look at the whole thing, I use Free File Splitter
Admittedly this is a workaround rather than a solution, and there are times when you would need the whole file. But often I only need to see a few lines from a larger file and that seems to be your problem too. If not, maybe others would find that utility useful.
A viewer that lets you see enormous text files isn't much help if you are trying to get it loaded into Excel to use the Autofilter, for example. Since we all spend the day breaking down problems into smaller parts to be able to solve them, applying the same principle to a large file didn't strike me as contentious.
From the manual:
To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
Obviously, you should replace 95
by 10
. The large number they use is 2^64 - 1, by the way.
you can make a shell script with those commands, and then chmod +x <scriptname.sh>
, and then just run it by
./scriptname.sh
Its very simple to write a bash script
Mockup sh file:
#!/bin/sh
sudo command1
sudo command2
.
.
.
sudo commandn
I want to add that there is another difference. It is related to what Andrew posts.
It is also related to a VERY annoying to find bug in our software. See the following simplified example (I also omitted the null check).
public const int SPECIAL_NUMBER = 213;
public bool IsSpecialNumberEntered(string numberTextBoxTextValue)
{
return numberTextBoxTextValue.Equals(SPECIAL_NUMBER)
}
This will compile and always return false
. While the following will give a compile error:
public const int SPECIAL_NUMBER = 213;
public bool IsSpecialNumberEntered(string numberTextBoxTextValue)
{
return (numberTextBoxTextValue == SPECIAL_NUMBER);
}
We have had to solve a similar problem where someone compared enums of different type using Equals
. You are going to read over this MANY times before realising it is the cause of the bug. Especially if the definition of SPECIAL_NUMBER
is not near the problem area.
This is why I am really against the use of Equals in situations where is it not necessary. You lose a little bit of type-safety.
In some cases, there is no difference in file versions, but only in indentation, spacing, line ending or line numbers.
To patch despite those differences, it's possible to use the following two arguments :
--ignore-whitespace : It ignores whitespace differences (indentation, etc).
--fuzz 3 : the "--fuzz X" option sets the maximum fuzz factor to lines. This option only applies to context and unified diffs; it ignores up to X lines while looking for the place to install a hunk. Note that a larger fuzz factor increases the odds of making a faulty patch. The default fuzz factor is 2; there is no point to setting it to more than the number of lines of context in the diff, ordinarily 3.
Don't forget to user "--dry-run" : It'll try the patch without applying it.
Example :
patch --verbose --dry-run --ignore-whitespace --fuzz 3 < /path/to/patch.patch
More informations about Fuzz :
https://www.gnu.org/software/diffutils/manual/html_node/Inexact.html
Easily accomplished with a for
loop.
for (var i = 0; i < items.length; i++)
if (items[i] == 3452)
items[i] = 1010;
Lets say you want to unstage changes upto n commits,
Where commit hashes are as follows:
Then run the following command:
git reset hn
Now the HEAD will be at hn+1. Changes from h1 to hn will be unstaged.
// m specifies how many of the low bits are shown.
// Replace m with sizeof(n) below for all bits and
// remove it from the parameter list if you like.
void print_binary(unsigned long n, unsigned long m) {
static char show[3] = "01";
unsigned long mask = 1ULL << (m-1);
while(mask) {
putchar(show[!!(n&mask)]); mask >>= 1;
}
putchar('\n');
}
Just to add that using os.listdir() does not "take a lot of processing vs very simple os.walk().next()[1]". This is because os.walk() uses os.listdir() internally. In fact if you test them together:
>>>> import timeit
>>>> timeit.timeit("os.walk('.').next()[1]", "import os", number=10000)
1.1215229034423828
>>>> timeit.timeit("[ name for name in os.listdir('.') if os.path.isdir(os.path.join('.', name)) ]", "import os", number=10000)
1.0592019557952881
The filtering of os.listdir() is very slightly faster.
Try this,
window.location.href="sample.html";
Here sample.html
is a next page. It will go to the next page.
use Request.Form
to get the Data
Controller:
[HttpPost]
public ActionResult Index(int? id)
{
string jsonData= Request.Form[0]; // The data from the POST
}
I write this to try
View:
<input type="button" value="post" id="btnPost" />
<script type="text/javascript">
$(function () {
var test = {
number: 456,
name: "Ryu"
}
$("#btnPost").click(function () {
$.post('@Url.Action("Index", "Home")', JSON.stringify(test));
});
});
</script>
and write Request.Form[0]
or Request.Params[0]
in controller can get the data.
I don't write <form> tag
in view.
If you have you static path set, then just use the <link rel="icon" href="/images/favicon.ico" type="image/x-icon">
in your views. No need for anything else. Please make sure that you have your images folder inside the public folder.
Since in css3 one might set multiple background images setting "none" will only create a new layer and hide nothing.
http://www.css3.info/preview/multiple-backgrounds/ http://www.w3.org/TR/css3-background/#backgrounds
I have not found a solution yet...
SELECT "Gc_Staff_Number",
"Start_Date",
(SELECT "End_Date"
FROM "Employment_History"
WHERE "Current_Flag" != 'Y'
AND ROWNUM = 1
AND "Employee_Number" = "Employment_History"."Employee_Number"
ORDER BY "End_Date" ASC)
FROM "Employment_History"
WHERE "Current_Flag" = 'Y'
FYI, the ROWNUM = 1 gets evaluated before the ORDER BY in this case, so that inner query will sort a grand total of (at most) one record.
If you really are looking for the earliest end_date for a given employee (where current_flag <> 'Y') is this what you're looking for?
SELECT "Gc_Staff_Number",
"Start_Date",
eh.end_date
FROM "Employment_History" eh
LEFT OUTER JOIN -- in case the current record is the only record...
(SELECT "Employee_Number"
, MIN("End_Date") as end_date
FROM "Employment_History"
WHERE "Current_Flag" != 'Y'
GROUP BY "Employee_Number"
) emp_end_date
ON eh."Employee_Number" = emp_end_date."Employee_Number"
WHERE eh."Current_Flag" = 'Y'
If you have a PEM file (e.g. server.pem
) containing:
then you can import the certificate and key into a JKS keystore like this:
1) Copy the private key from the PEM file into an ascii file (e.g. server.key
)
2) Copy the cert from the PEM file into an ascii file (e.g. server.crt
)
3) Export the cert and key into a PKCS12 file:
$ openssl pkcs12 -export -in server.crt -inkey server.key \
-out server.p12 -name [some-alias] -CAfile server.pem -caname root
-CAfile
option.winpty
to the start of the command so the export password can be entered.4) Convert the PKCS12 file to a JKS keystore:
$ keytool -importkeystore -deststorepass changeit -destkeypass changeit \
-destkeystore keystore.jks -srckeystore server.p12 -srcstoretype PKCS12 \
-srcstorepass changeit
srcstorepass
password should match the export password from step 3)The man page makes it pretty clear. If you want to pass two arguments (-rpath
and .
) to the linker you can write
-Wl,-rpath,.
or alternatively
-Wl,-rpath -Wl,.
The arguments -Wl,-rpath .
you suggested do NOT make sense to my mind. How is gcc supposed to know that your second argument (.
) is supposed to be passed to the linker instead of being interpreted normally? The only way it would be able to know that is if it had insider knowledge of all possible linker arguments so it knew that -rpath
required an argument after it.
I had the same problem, and I solved it by doing:
After that, it should work.
[HttpGet]
public RedirectResult Get()
{
return RedirectPermanent("https://www.google.com");
}
Used full outer join -- But it will not show - if its not matched -
SQL> desc aaa - its a table Name Null? Type
A1 NUMBER B1 VARCHAR2(10)
SQL> desc aaav -its a view Name Null? Type
A1 NUMBER B1 VARCHAR2(10)
SQL> select a.column_name,b.column_name from dba_tab_columns a full outer join dba_tab_columns b on a.column_name=b.column_name where a.TABLE_NAME='AAA' and B.table_name='AAAV';
COLUMN_NAME COLUMN_NAME
A1 A1 B1 B1
Problem is that your folder is not identified as a Source folder.
It can be fixed by changing your theme in styles.xml from Theme.AppCompat.Light.DarkActionBar to Base.Theme.AppCompat.Light.DarkActionBar
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
to
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
and clean the project. It will surely help.
Here is how you can do it with a socket on php-fpm 7
install socat
apt-get install socat
#!/bin/sh
if echo /dev/null | socat UNIX:/var/run/php/php7.0-fpm.sock - ; then
echo "$home/run/php-fpm.sock connect OK"
else
echo "$home/run/php-fpm.sock connect ERROR"
fi
You can also check if the service is running like this.
service php7.0-fpm status | grep running
It will return
Active: active (running) since Sun 2017-04-09 12:48:09 PDT; 48s ago
Go to
https://github.com/Darkseal/bootstrap4-glyphicons
download and include in your code
<link href="bootstrap4-glyphicons/css/bootstrap-glyphicons.css" rel="stylesheet">
the strncpy is a safer version of strcpy as a matter of fact you should never use strcpy because its potential buffer overflow vulnerability which makes you system vulnerable to all sort of attacks
I prefer field access, because that way I'm not forced to provide getter/setter for each property.
A quick survey via Google suggests that field access is the majority (e.g., http://java.dzone.com/tips/12-feb-jpa-20-why-accesstype).
I believe field access is the idiom recommended by Spring, but I can't find a reference to back that up.
There's a related SO question that tried to measure performance and came to the conclusion that there's "no difference".
When the session is closed the process receives the SIGHUP signal which it is apparently not catching. You can use the nohup
command when launching the process or the bash built-in command disown -h
after starting the process to prevent this from happening:
> help disown
disown: disown [-h] [-ar] [jobspec ...]
By default, removes each JOBSPEC argument from the table of active jobs.
If the -h option is given, the job is not removed from the table, but is
marked so that SIGHUP is not sent to the job if the shell receives a
SIGHUP. The -a option, when JOBSPEC is not supplied, means to remove all
jobs from the job table; the -r option means to remove only running jobs.
You have to use the following code:
response.writeHead(302 , {
'Location' : '/view/index.html' // This is your url which you want
});
response.end();
a.txt
this is line 1
this is line 2
code:
Python 3.4.0 (default, Mar 20 2014, 22:43:40)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']
I'm on Linux, but I guess you just use \r\n
on Windows and it would also work
I agree with much that Manuel has said. In fact, his comments refer to this url...
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
... which states:
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
However, for me it would come down to tool/framework support.
If you get a clear idea of your users, and how they'll make use of your API, then that will help you decide. If you make the upload of files hard for your API users then they'll move away, of you'll spend a lot of time on supporting them.
Secondary to this would be the tool support YOU have for writing your API and how easy it is for your to accommodate one upload mechanism over the other.
First find out where do you store the environment variables-
Steps to Set up the environment variable :-
Download the jdk from JAVA
install it by double click
Now set-up environment variables in your file
a. For emacs.profile you can use this link OR see the screenshot below
b. For ZSH profile setup -
1. export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home
2. source ~/.zshrc - Restart zshrc to reflect the changes.
3. echo $JAVA_HOME - make sure path is set up properly
----> /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home
4. java -version
--> java version "1.8.0_112" Java(TM) SE Runtime Environment (build 1.8.0_112-b16)Java HotSpot(TM) 64-Bit Server VM (build 25.112-b16, mixed mode)
All set Now you can easily upgrade or degrade the JAVA version..
Use Jackson-annotations.jar will solve the problem, as it worked for me.
you can use val function to collect data from inputs:
jQuery("#myInput1").val();
Java doesn't use includes the way C does. Instead java uses a concept called the classpath, a list of resources containing java classes. The JVM can access any class on the classpath by name so if you can extend classes and refer to types simply by declaring them. The closes thing to an include statement java has is 'import'. Since classes are broken up into namespaces like foo.bar.Baz, if you're in the qux package and you want to use the Baz class without having to use its full name of foo.bar.Baz, then you need to use an import statement at the beginning of your java file like so:
import foo.bar.Baz