You could split on all commas that do have an even number of quotes following them.
You would also like to view at the specf
for CSV format about handling comma's.
Useful Link : C# Regex Split - commas outside quotes
$this->load->library('excel');
$file_name = 'Demo';
$arrHeader = array('Name', 'Mobile');
$arrRows = array(0=>array('Name'=>'Jayant','Mobile'=>54545), 1=>array('Name'=>'Jayant1', 'Mobile'=>44454), 2=>array('Name'=>'Jayant2','Mobile'=>111222), 3=>array('Name'=>'Jayant3', 'Mobile'=>99999));
$this->excel->getActiveSheet()->fromArray($arrHeader,'','A1');
$this->excel->getActiveSheet()->fromArray($arrRows);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$file_name.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');
You can use normal file operation to create an error log. Just refer this and input this link: PHP File Handling
There might be many causes to this problem. The key is to use
export QT_DEBUG_PLUGINS=1
before you run your Qt application. Then, inspect the output, which will point you to the direction of the error. In my case it was:
Cannot load library /opt/nao/plugins/platforms/libqxcb.so: (/opt/nao/bin/../lib/libz.so.1: version `ZLIB_1.2.9' not found (required by /usr/lib/x86_64-linux-gnu/libpng16.so.16))
But that is solved in different threads. See for instance https://stackoverflow.com/a/50097275/2408964.
Why not use
$iframe.load(function () {
var $body = $('body', $iframe.get(0).contentWindow.document);
$body.html(contentDiv);
});
instead of timer ?
iOS textTransform support has been added to react-native in 0.56 version. Android textTransform support has been added in 0.59 version. It accepts one of these options:
The actual iOS commit, Android commit and documentation
Example:
<View>
<Text style={{ textTransform: 'uppercase'}}>
This text should be uppercased.
</Text>
<Text style={{ textTransform: 'capitalize'}}>
Mixed:{' '}
<Text style={{ textTransform: 'lowercase'}}>
lowercase{' '}
</Text>
</Text>
</View>
Your mistake is the parameters to Substring. The first parameter should be the start index and the second should be the length or offset from the startindex.
string newString = url.Substring(18, 7);
If the length of the substring can vary you need to calculate the length.
Something in the direction of (url.Length - 18) - 4
(or url.Length - 22
)
In the end it will look something like this
string newString = url.Substring(18, url.Length - 22);
In my case there was another directory within my workspace, having the same jar file as the one in my project. I hadn't created that directory or anything in it. It was created by Eclipse I believe. I just erased that directory and it just runs ok.
Try this
$("#postcontent").submit(function() {
return false;
};
$('#postsubmit').click(function(){
// your ajax request here
});
I had these choices:
-----------------------------------------------
* 1 /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java
+ 2 /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
3 /home/ec2-user/local/java/jre1.7.0_25/bin/java
When I chose 3, it didn't work. When I chose 2, it did work.
Deleting duplicates on MySQL tables is a common issue, that's genarally the result of a missing constraint to avoid those duplicates before hand. But this common issue usually comes with specific needs... that do require specific approaches. The approach should be different depending on, for example, the size of the data, the duplicated entry that should be kept (generally the first or the last one), whether there are indexes to be kept, or whether we want to perform any additional action on the duplicated data.
There are also some specificities on MySQL itself, such as not being able to reference the same table on a FROM cause when performing a table UPDATE (it'll raise MySQL error #1093). This limitation can be overcome by using an inner query with a temporary table (as suggested on some approaches above). But this inner query won't perform specially well when dealing with big data sources.
However, a better approach does exist to remove duplicates, that's both efficient and reliable, and that can be easily adapted to different needs.
The general idea is to create a new temporary table, usually adding a unique constraint to avoid further duplicates, and to INSERT the data from your former table into the new one, while taking care of the duplicates. This approach relies on simple MySQL INSERT queries, creates a new constraint to avoid further duplicates, and skips the need of using an inner query to search for duplicates and a temporary table that should be kept in memory (thus fitting big data sources too).
This is how it can be achieved. Given we have a table employee, with the following columns:
employee (id, first_name, last_name, start_date, ssn)
In order to delete the rows with a duplicate ssn column, and keeping only the first entry found, the following process can be followed:
-- create a new tmp_eployee table
CREATE TABLE tmp_employee LIKE employee;
-- add a unique constraint
ALTER TABLE tmp_employee ADD UNIQUE(ssn);
-- scan over the employee table to insert employee entries
INSERT IGNORE INTO tmp_employee SELECT * FROM employee ORDER BY id;
-- rename tables
RENAME TABLE employee TO backup_employee, tmp_employee TO employee;
? Using this approach, 1.6M registers were converted into 6k in less than 200s.
Chetan, following this process, you could fast and easily remove all your duplicates and create a UNIQUE constraint by running:
CREATE TABLE tmp_jobs LIKE jobs;
ALTER TABLE tmp_jobs ADD UNIQUE(site_id, title, company);
INSERT IGNORE INTO tmp_jobs SELECT * FROM jobs ORDER BY id;
RENAME TABLE jobs TO backup_jobs, tmp_jobs TO jobs;
Of course, this process can be further modified to adapt it for different needs when deleting duplicates. Some examples follow.
Sometimes we need to keep the last duplicated entry instead of the first one.
CREATE TABLE tmp_employee LIKE employee;
ALTER TABLE tmp_employee ADD UNIQUE(ssn);
INSERT IGNORE INTO tmp_employee SELECT * FROM employee ORDER BY id DESC;
RENAME TABLE employee TO backup_employee, tmp_employee TO employee;
Sometimes we need to perform some further processing on the duplicated entries that are found (such as keeping a count of the duplicates).
CREATE TABLE tmp_employee LIKE employee;
ALTER TABLE tmp_employee ADD UNIQUE(ssn);
ALTER TABLE tmp_employee ADD COLUMN n_duplicates INT DEFAULT 0;
INSERT INTO tmp_employee SELECT * FROM employee ORDER BY id ON DUPLICATE KEY UPDATE n_duplicates=n_duplicates+1;
RENAME TABLE employee TO backup_employee, tmp_employee TO employee;
Sometimes we use an auto-incremental field and, in order the keep the index as compact as possible, we can take advantage of the deletion of the duplicates to regenerate the auto-incremental field in the new temporary table.
CREATE TABLE tmp_employee LIKE employee;
ALTER TABLE tmp_employee ADD UNIQUE(ssn);
INSERT IGNORE INTO tmp_employee SELECT (first_name, last_name, start_date, ssn) FROM employee ORDER BY id;
RENAME TABLE employee TO backup_employee, tmp_employee TO employee;
Many further modifications are also doable depending on the desired behavior. As an example, the following queries will use a second temporary table to, besides 1) keep the last entry instead of the first one; and 2) increase a counter on the duplicates found; also 3) regenerate the auto-incremental field id while keeping the entry order as it was on the former data.
CREATE TABLE tmp_employee LIKE employee;
ALTER TABLE tmp_employee ADD UNIQUE(ssn);
ALTER TABLE tmp_employee ADD COLUMN n_duplicates INT DEFAULT 0;
INSERT INTO tmp_employee SELECT * FROM employee ORDER BY id DESC ON DUPLICATE KEY UPDATE n_duplicates=n_duplicates+1;
CREATE TABLE tmp_employee2 LIKE tmp_employee;
INSERT INTO tmp_employee2 SELECT (first_name, last_name, start_date, ssn) FROM tmp_employee ORDER BY id;
DROP TABLE tmp_employee;
RENAME TABLE employee TO backup_employee, tmp_employee2 TO employee;
net use f: \\\VFServer"\HQ Publications" /persistent:yes
Note that the first quotation mark
goes before the leading \
and the second goes after the end of the folder name.
The most common way would be to put a simple text file (XML/JSON would be better) on your webserver with the last build version. The application will then download this file, check the version and start the updater. A typical file would look like this:
Application Update File (A unique string that will let your application recognize the file type)
version: 1.0.0 (Latest Assembly Version)
download: http://yourserver.com/... (A link to the download version)
redirect: http://yournewserver.com/... (I used this field in case of a change in the server address.)
This would let the client know that they need to be looking at a new address.
You can also add other important details.
No, the String.isEmpty()
method looks as following:
public boolean isEmpty() {
return this.value.length == 0;
}
as you can see it checks the length of the string so you definitely have to check if the string is null before.
This is how I implemented my URL builder. I have created one Service class to provide the params for the URL
public interface ParamsProvider {
String queryProvider(List<BasicNameValuePair> params);
String bodyProvider(List<BasicNameValuePair> params);
}
The Implementation of methods are below
@Component
public class ParamsProviderImp implements ParamsProvider {
@Override
public String queryProvider(List<BasicNameValuePair> params) {
StringBuilder query = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
query.append("?");
query.append(basicNameValuePair.toString());
first.set(false);
} else {
query.append("&");
query.append(basicNameValuePair.toString());
}
});
return query.toString();
}
@Override
public String bodyProvider(List<BasicNameValuePair> params) {
StringBuilder body = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
body.append(basicNameValuePair.toString());
first.set(false);
} else {
body.append("&");
body.append(basicNameValuePair.toString());
}
});
return body.toString();
}
}
When we need the query params for our URL, I simply call the service and build it. Example for that is below.
Class Mock{
@Autowired
ParamsProvider paramsProvider;
String url ="http://www.google.lk";
// For the query params price,type
List<BasicNameValuePair> queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("price", 100));
queryParameters.add(new BasicNameValuePair("type", "L"));
url = url+paramsProvider.queryProvider(queryParameters);
// You can use it in similar way to send the body params using the bodyProvider
}
The strategy of the accepted answer is correct, but here's a generalized example that works with the current version of React and Material-UI.
The flow of data should be one-way:
TextArea
s are populated from this initial statestate
via the handleChange
callback.state
is accessed from the onClick
callback---right now it just writes to the console. If you want to add validation it could go there.import * as React from "react";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
const initialState = {
error: null, // you could put error messages here if you wanted
person: {
firstname: "",
lastname: ""
}
};
export class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = initialState;
// make sure the "this" variable keeps its scope
this.handleChange = this.handleChange.bind(this);
this.onClick = this.onClick.bind(this);
}
render() {
return (
<div>
<div>{this.state.error}</div>
<div>
<TextField
name="firstname"
value={this.state.person.firstname}
floatingLabelText="First Name"
onChange={this.handleChange}/>
<TextField
name="lastname"
value={this.state.person.lastname}
floatingLabelText="Last Name"
onChange={this.handleChange}/>
</div>
<div>
<RaisedButton onClick={this.onClick} label="Submit!" />
</div>
</div>
);
}
onClick() {
console.log("when clicking, the form data is:");
console.log(this.state.person);
}
handleChange(event, newValue): void {
event.persist(); // allow native event access (see: https://facebook.github.io/react/docs/events.html)
// give react a function to set the state asynchronously.
// here it's using the "name" value set on the TextField
// to set state.person.[firstname|lastname].
this.setState((state) => state.person[event.target.name] = newValue);
}
}
React.render(<MyForm />, document.getElementById('app'));
(Note: You may want to write one handleChange
callback per MUI Component to eliminate that ugly event.persist()
call.)
The best way is to:
wget http://dl.fedoraproject.org/pub/epel/6/x86_64/php-mcrypt-5.3.3-3.el6.x86_64.rpm
yum localinstall php-mcrypt-5.3.3-3.el6.x86_64.rpm
wget http://dl.fedoraproject.org/pub/epel/6/x86_64/libmcrypt-2.5.8-9.el6.x86_64.rpm
yum localinstall libmcrypt-2.5.8-9.el6.x86_64.rpm
or go to: http://dl.fedoraproject.org/pub/epel/6/x86_64/ to match your version check from your info.php that is ok -- done!
A framework or other similar schema will run/interpret a script to do a task. A program is compiled and run by a machine to do a task
Perhaps this is over-simplistic...
Create a Windows Form project...
Then: Project Properties -> Application -> Output Type -> Console Application
Then can have Console and Forms running together, works for me
You can leverage Conditional Formatting
as follows.
H8
select Format > Conditional Formatting...=I8="Elementary"
Format...
and select the color you want etc.Add>>
and repeat steps 1 to 4Note that you can only have (in excel 2003) three separate conditions so you will only be able to have different formatting for three items in the drop down menu. If the idea is to make them visually distinct then (maybe) having no color for one of the selections is not a problem?
If the cell is never blank, you can use format (not conditional) to get 4 distinct visuals.
In VS - project properties - in the Build tab - platform target =X86
--USER and SCHEMA
The both words user and schema are interchangeble,thats why most people get confusion on this words below i explained the difference between them
--User User is a account to connect database(Server). we can create user by using CREATE USER user_name IDENTIFIED BY password .
--Schema
Actually Oracle Database contain logical and physical strucutre to process the data.The Schema Also Logical Structure to process the data in Database(Memory Component). Its Created automatically by oracle when user created.It Contains All Objects created by the user associated to that schema.For Example if i created a user with name santhosh then oracle createts a schema called santhosh,oracle stores all objects created by user santhosh in santhosh schema.
We can create schema by CREATE SCHEMA statement ,but Oracle Automatically create a user for that schema.
We can Drop the schema by using DROP SCHEMA schama_name RESTRICT statement but it can not delete scehema contains objects,so to drop schema it must be empty.here the restrict word forcely specify that schema with out objects.
If we try to drop a user contain objects in his schema we must specify CASCADE word because oracle does not allow you to delete user contain objects. DROP USER user_name CASCADE so oracle deletes the objects in schema and then it drops the user automatically,Objects refered to this schema objects from other schema like views and private synonyms goes to invalid state.
I hope now you got the difference between them,if you have any doubts on this topic,please feel free to ask.
Thank you.
With java-8, you can also use Stream.generate
.
import static java.util.stream.Collectors.joining;
...
String repeated = Stream.generate(() -> "abc").limit(3).collect(joining()); //"abcabcabc"
and you can wrap it in a simple utility method if needed:
public static String repeat(String str, int times) {
return Stream.generate(() -> str).limit(times).collect(joining());
}
var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
var imgsrc = jQuery('.MulImage')[i];
var CurrentImgSrc = imgsrc.src;
img = jQuery('<img class="dynamic" style="width:100%;">');
img.attr('src', CurrentImgSrc);
jQuery('.YourDivClass').append(img);
}
Here is how I have done it:
Canvas g = new Canvas( compass );
Paint p = new Paint( Paint.ANTI_ALIAS_FLAG );
float rotation = display.getOrientation() * 90;
g.translate( -box.left, -box.top );
g.rotate( -bearing - rotation, box.exactCenterX(), box.exactCenterY() );
drawCompass( g, p );
drawNeedle( g, p );
As mentioned in other answers, all of the following will work for the standard string-based syntax.
WAITFOR DELAY '02:00' --Two hours
WAITFOR DELAY '00:02' --Two minutes
WAITFOR DELAY '00:00:02' --Two seconds
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds
There is also an alternative method of passing it a DATETIME
value. You might think I'm confusing this with WAITFOR TIME
, but it also works for WAITFOR DELAY
.
Considerations for passing DATETIME
:
'1900-01-01'
).DATETIME
than to properly format a VARCHAR
.How to wait for 2 seconds:
--Example 1
DECLARE @Delay1 DATETIME
SELECT @Delay1 = '1900-01-01 00:00:02.000'
WAITFOR DELAY @Delay1
--Example 2
DECLARE @Delay2 DATETIME
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0))
WAITFOR DELAY @Delay2
A note on waiting for TIME
vs DELAY
:
Have you ever noticed that if you accidentally pass WAITFOR TIME
a date that already passed, even by just a second, it will never return? Check it out:
--Example 3
DECLARE @Time1 DATETIME
SELECT @Time1 = getdate()
WAITFOR DELAY '00:00:01'
WAITFOR TIME @Time1 --WILL HANG FOREVER
Unfortunately, WAITFOR DELAY
will do the same thing if you pass it a negative DATETIME
value (yes, that's a thing).
--Example 4
DECLARE @Delay3 DATETIME
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0))
WAITFOR DELAY @Delay3 --WILL HANG FOREVER
However, I would still recommend using WAITFOR DELAY
over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR
statement.
var valKeyDown;
var valKeyUp;
function integerOnly(e) {
e = e || window.event;
var code = e.which || e.keyCode;
if (!e.ctrlKey) {
var arrIntCodes1 = new Array(96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 8, 9, 116); // 96 TO 105 - 0 TO 9 (Numpad)
if (!e.shiftKey) { //48 to 57 - 0 to 9
arrIntCodes1.push(48); //These keys will be allowed only if shift key is NOT pressed
arrIntCodes1.push(49); //Because, with shift key (48 to 57) events will print chars like @,#,$,%,^, etc.
arrIntCodes1.push(50);
arrIntCodes1.push(51);
arrIntCodes1.push(52);
arrIntCodes1.push(53);
arrIntCodes1.push(54);
arrIntCodes1.push(55);
arrIntCodes1.push(56);
arrIntCodes1.push(57);
}
var arrIntCodes2 = new Array(35, 36, 37, 38, 39, 40, 46);
if ($.inArray(e.keyCode, arrIntCodes2) != -1) {
arrIntCodes1.push(e.keyCode);
}
if ($.inArray(code, arrIntCodes1) == -1) {
return false;
}
}
return true;
}
$('.integerOnly').keydown(function (event) {
valKeyDown = this.value;
return integerOnly(event);
});
$('.integerOnly').keyup(function (event) { //This is to protect if user copy-pastes some character value ,..
valKeyUp = this.value; //In that case, pasted text is replaced with old value,
if (!new RegExp('^[0-9]*$').test(valKeyUp)) { //which is stored in 'valKeyDown' at keydown event.
$(this).val(valKeyDown); //It is not possible to check this inside 'integerOnly' function as,
} //one cannot get the text printed by keydown event
}); //(that's why, this is checked on keyup)
$('.integerOnly').bind('input propertychange', function(e) { //if user copy-pastes some character value using mouse
valKeyUp = this.value;
if (!new RegExp('^[0-9]*$').test(valKeyUp)) {
$(this).val(valKeyDown);
}
});
To get Only Incoming Call history , the beneath code will help u:)
private void getCallDetailsAgil() {
StringBuffer sb = new StringBuffer();
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, null, null, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details :");
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " + callDayTime + " \nCall duration in sec :--- " + callDuration);
sb.append("\n----------------------------------");
miss_cal.setText(sb);
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
}
managedCursor.close();
}
I use this comparable
function to produce copies of my objects that are JSON comparable:
var comparable = o => (typeof o != 'object' || !o)? o :_x000D_
Object.keys(o).sort().reduce((c, key) => (c[key] = comparable(o[key]), c), {});_x000D_
_x000D_
// Demo:_x000D_
_x000D_
var a = { a: 1, c: 4, b: [2, 3], d: { e: '5', f: null } };_x000D_
var b = { b: [2, 3], c: 4, d: { f: null, e: '5' }, a: 1 };_x000D_
_x000D_
console.log(JSON.stringify(comparable(a)));_x000D_
console.log(JSON.stringify(comparable(b)));_x000D_
console.log(JSON.stringify(comparable(a)) == JSON.stringify(comparable(b)));
_x000D_
<div id="div"></div>
_x000D_
Comes in handy in tests (most test frameworks have an is
function). E.g.
is(JSON.stringify(comparable(x)), JSON.stringify(comparable(y)), 'x must match y');
If a difference is caught, strings get logged, making differences spottable:
x must match y
got {"a":1,"b":{"0":2,"1":3},"c":7,"d":{"e":"5","f":null}},
expected {"a":1,"b":{"0":2,"1":3},"c":4,"d":{"e":"5","f":null}}.
Glad there are tons of answers, I hope you find this one to be clear, concise, and fast.
Thank you
import math
def merge_array(ar1, ar2):
c, i, j= [], 0, 0
while i < len(ar1) and j < len(ar2):
if ar1[i] < ar2[j]:
c.append(ar1[i])
i+=1
else:
c.append(ar2[j])
j+=1
return c + ar1[i:] + ar2[j:]
def mergesort(array):
n = len(array)
if n == 1:
return array
half_n = math.floor(n/2)
ar1, ar2 = mergesort(array[:half_n]), mergesort(array[half_n:])
return merge_array(ar1, ar2)
Alternatively, when you want to save individual R objects, I recommend using saveRDS
.
You can save R objects using saveRDS
, then load them into R with a new variable name using readRDS
.
Example:
# Save the city object
saveRDS(city, "city.rds")
# ...
# Load the city object as city
city <- readRDS("city.rds")
# Or with a different name
city2 <- readRDS("city.rds")
But when you want to save many/all your objects in your workspace, use Manetheran's answer.
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
ABOVE CODE TO SELECT IMAGE FROM GALLERY
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String filePath = getPath(selectedImage);
String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
image_name_tv.setText(filePath);
try {
if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
//FINE
} else {
//NOT IN REQUIRED FORMAT
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaColumns.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
NOW POST THE DATA USING MULTIPART FORM DATA
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");
Multipart FORM DATA
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
File file = new File(filePath);
Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
mpEntity.addPart("avatar", new FileBody(file, "application/octet"));
}
FINALLY POST DATA TO SERVER
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.
You just need to re-open the image with IrfanView after changing the view color to white.
To change the viewing color in Irfanview go to:
Options > Properties/Settings > Viewing > Main window color
Valid answer from this thread was the right answer for my special case. Specify the ORM folder path for datanucleus certainly reduce the java path compile.
This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:
String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454
Date.getTime()
returns the epoch time in milliseconds.
Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element
or null
. Properties without can return any other kind of node.
console.log(document.body.parentNode, "is body's parent node"); // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>
var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null
The SSL certificates are going to be bound to hostname rather than IP if they are setup in the standard way. Hence why it works at one site rather than the other.
Even if the servers share the same hostname they may well have two different certificates and hence WebSphere will have a certificate trust issue as it won't be able to recognise the certificate on the second server as it is different to the first.
I suggest you to look at this highly rated blog post which manages to give a solution to the problem you're facing :
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emulator.html
His code is based on the current Android APIs and should work in your case given that you are using a recent Android API.
it can be installed separated, and it's not included in framwork, choose tab list "extensions" and it exists there are and more other libs, all is ok not needed to used old libs etc, exists old 20 30 and 4001
You could use a library such as node-uuid for this to make sure you get unique ids.
Install using:
npm install node-uuid --save
Then in your react component add the following:
import {default as UUID} from "node-uuid";
import {default as React} from "react";
export default class MyComponent extends React.Component {
componentWillMount() {
this.id = UUID.v4();
},
render() {
return (
<div>
<label htmlFor={this.id}>My label</label>
<input id={this.id} type="text"/>
</div>
);
}
}
A Singleton candidate must satisfy three requirements:
If your proposed Singleton has only one or two of these requirements, a redesign is almost always the correct option.
For example, a printer spooler is unlikely to be called from more than one place (the Print menu), so you can use mutexes to solve the concurrent access problem.
A simple logger is the most obvious example of a possibly-valid Singleton, but this can change with more complex logging schemes.
Select all text afected by this issue:
Window -> Character, click the icon next to hide the Character Window, Middle Western Features and select Left-to-right character direction.
in the div
style="text-align:center; line-height:200px"
I've had this exact same problem a few days ago. I eventually managed to solve it. I'm not quite sure how, but I'll tell you what I did anyway. Maybe it'll help you.
I started by downloading RVM. If you aren't using it yet, I highly recommend doing so. It basically creates a sandbox for a new separate installation of Ruby, RoR and RubyGems. In fact, you can have multiple installations simultaneously and instantly switch to one other. It works like a charm.
Why is this useful? Because you shouldn't mess with the default Ruby installation in OS X. The system depends on it. It's best to just leave the default Ruby and RoR installation alone and create a new one using RVM that you can use for your own development.
Once I created my separate Ruby installation, I just installed RoR, RubyGems and mysql, and it worked. For the exact steps I took, see my question: Installing Rails, MySQL, etc. everything goes wrong
Again: I don't know for certain this will solve your problem. But it certainly did the trick for me, and in any case using RVM is highly recommendable.
Below is Brian's modified code which copies files from source location to destination location.
public class CopyFiles {
public static void copyFiles(File sourceLocation , File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
File[] files = sourceLocation.listFiles();
for(File file:files){
InputStream in = new FileInputStream(file);
OutputStream out = new FileOutputStream(targetLocation+"/"+file.getName());
// Copy the bits from input stream to output stream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
Having two primary keys at the same time, is not possible. But (assuming that you have not messed the case up with composite key), may be what you might need is to make one attribute unique.
CREATE t1(
c1 int NOT NULL,
c2 int NOT NULL UNIQUE,
...,
PRIMARY KEY (c1)
);
However note that in relational database a 'super key' is a subset of attributes which uniquely identify a tuple or row in a table. A 'key' is a 'super key' that has an additional property that removing any attribute from the key, makes that key no more a 'super key'(or simply a 'key' is a minimal super key). If there are more keys, all of them are candidate keys. We select one of the candidate keys as a primary key. That's why talking about multiple primary keys for a one relation or table is being a conflict.
I made some changes in above code to look for a location fix by both GPS and Network for about 5sec and give me the best known location out of it.
public class LocationService implements LocationListener {
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
final static long MIN_TIME_INTERVAL = 60 * 1000L;
Location location;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
protected LocationManager locationManager;
private CountDownTimer timer = new CountDownTimer(5 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
stopUsingGPS();
}
};
public LocationService() {
super(R.id.gps_service_id);
}
public void start() {
if (Utils.isNetworkAvailable(context)) {
try {
timer.start();
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
Location tempLocation = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (tempLocation != null
&& isBetterLocation(tempLocation,
location))
location = tempLocation;
}
}
if (isGPSEnabled) {
locationManager.requestSingleUpdate(
LocationManager.GPS_PROVIDER, this, null);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
Location tempLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (tempLocation != null
&& isBetterLocation(tempLocation,
location))
location = tempLocation;
}
}
} catch (Exception e) {
onTaskError(e.getMessage());
e.printStackTrace();
}
} else {
onOfflineResponse(requestData);
}
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(LocationService.this);
}
}
public boolean canGetLocation() {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return isGPSEnabled || isNetworkEnabled;
}
@Override
public void onLocationChanged(Location location) {
if (location != null
&& isBetterLocation(location, this.location)) {
this.location = location;
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public Object getResponseObject(Object location) {
return location;
}
public static boolean isBetterLocation(Location location,
Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > MIN_TIME_INTERVAL;
boolean isSignificantlyOlder = timeDelta < -MIN_TIME_INTERVAL;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location,
// use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must
// be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate
&& isFromSameProvider) {
return true;
}
return false;
}
}
In the above class, I am registering a location listener for both GPS and network, so an onLocationChanged
call back can be called by either or both of them multiple times and we just compare the new location fix with the one we already have and keep the best one.
If you use numpy.multiply
S = [22, 33, 45.6, 21.6, 51.8]
P = 2.45
multiply(S, P)
It gives you as a result
array([53.9 , 80.85, 111.72, 52.92, 126.91])
Instead of typedef struct { ... } pos;
you should be doing struct pos { ... };
. The issue here is that you are using the pos
type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.
Further, the typedef struct { ... } name;
pattern is a C-ism, and doesn't have much place in C++.
To answer your question about inline
, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline
, the compiler effectively ignores it because the method is already declared inline.
(inline
methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)
Or more complex, but makes life easy is to use more constants in boot. So subclasses can be defined freely, and a single method to show view. Also selected constants can be passed to javascript in the header.
<?php
/*
* extends codeigniter main controller
*/
class CH_Controller extends CI_Controller {
protected $viewdata;
public function __construct() {
parent::__construct();
//hard code / override and transfer only required constants (for security) server constants
//such as domain name to client - this is for code porting and no passwords or database details
//should be used - ajax is for this
$this->viewdata = array(
"constants_js" => array(
"TOP_DOMAIN"=>TOP_DOMAIN,
"C_UROOT" => C_UROOT,
"UROOT" => UROOT,
"DOMAIN"=> DOMAIN
)
);
}
public function show($viewloc) {
$this->load->view('templates/header', $this->viewdata);
$this->load->view($viewloc, $this->viewdata);
$this->load->view('templates/footer', $this->viewdata);
}
//loads custom class objects if not already loaded
public function loadplugin($newclass) {
if (!class_exists("PL_" . $newclass)) {
require(CI_PLUGIN . "PL_" . $newclass . ".php");
}
}
then simply:
$this->show("<path>/views/viewname/whatever_V.php");
will load header, view and footer.
FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other. You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by assigning gravity to each child, using the
android:layout_gravity
attribute.Child views are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child (plus padding), visible or not (if the FrameLayout's parent permits).
A RelativeLayout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. If you find yourself using several nested LinearLayout groups, you may be able to replace them with a single RelativeLayout.
(Current docs here)
A TableLayout consists of a number of
TableRow
objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.The width of a column is defined by the row with the widest cell in that column.
Note: Absolute Layout is deprecated.
One thing to also keep in mind if .gitignore
does not seem to be ignoring untracked files is that you should not have comments on the same line as the ignores. So this is okay
# ignore all foo.txt, foo.markdown, foo.dat, etc.
foo*
But this will not work:
foo* # ignore all foo.txt, foo.markdown, foo.dat, etc.
.gitignore
interprets the latter case as "ignore files named "foo* # ignore all foo.txt, foo.markdown, foo.dat, etc."
, which, of course, you don't have.
Don't use:
'data' => 'Default value'
Read here: https://symfony.com/doc/current/reference/forms/types/form.html#data
"The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overriden when the form edits an already persisted object, causing it to lose its persisted value when the form is submitted."
Use the following:
Lets say, for this example, you have an Entity Foo, and there is a field "active" (in this example is CheckBoxType, but process is the same to every other type), which you want to be checked by default
In your FooFormType class add:
...
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
...
public function buildForm( FormBuilderInterface $builder, array $options )
{
...
$builder->add('active', CheckboxType::class, array(
'label' => 'Active',
));
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event){
$foo = $event->getData();
// Set Active to true (checked) if form is "create new" ($foo->active = null)
if(is_null($foo->getActive())) $foo->setActive(true);
}
);
}
public function configureOptions( OptionsResolver $resolver )
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle:Foo',
));
}
In my case I had duplicated a class file! Found it by using the bottom search field at the right side bar of Xcode, so to solve it remove reference of one of them
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.testpoc.controller"/>
<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="ViewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Everybody seems to be suggesting that adding
using System.Configuration;
which is true.
But might I suggest that you think about installing ReSharper's Visual Studio extension?
With it installed, instead of seeing an error that a class isn't defined, you'll see a prompt that tells you which assembly it is in, asking you if you want it to add the needed using statement.
There is no need to use angular http, you can get with js native functions
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
// on the first then you will return blob from response_x000D_
return await fetch(url).then(r => r.blob())_x000D_
.then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
_x000D_
return new File([blob], fileName+'.'+ blob.type.split('/')[1]) ;_x000D_
});_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
// with file reader you will transform the file in a data url file;_x000D_
var reader = new FileReader();_x000D_
reader.readAsDataURL(file);_x000D_
reader.onloadend = () => {_x000D_
_x000D_
// just putting the data url to img element_x000D_
document.querySelector('#image').src = reader.result ;_x000D_
}_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
You can set enable/disable bounce or scrolling the tableview by selecting/deselecting these in the Scroll View area
All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.
You can use Math.round(double)
function or simply do :
(int)(yourDoubleValue + 0.5d)
This one is great:
<style type="text/css">
textarea.test
{
width: 100%;
height: 100%;
border-color: Transparent;
}
</style>
<textarea class="test"></textarea>
Alternatively, if you want to get the IP address of whichever interface is used to connect to the network without having to know its name, you can use this:
import socket
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
I know it's a little different than your question, but others may arrive here and find this one more useful. You do not have to have a route to 8.8.8.8 to use this. All it is doing is opening a socket, but not sending any data.
Here is a regex based solution to this problem...
private XmlDocument RemoveNS(XmlDocument doc)
{
var xml = doc.OuterXml;
var newxml = Regex.Replace(xml, @"xmlns[:xsi|:xsd]*="".*?""","");
var newdoc = new XmlDocument();
newdoc.LoadXml(newxml);
return newdoc;
}
With mockito you can use withSettings(), for example if the CounterService required 2 dependencies, you can pass them as a mock:
UserService userService = Mockito.mock(UserService.class);
SearchService searchService = Mockito.mock(SearchService.class);
CounterService counterService = Mockito.mock(CounterService.class,
withSettings().useConstructor(userService, searchService));
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
</body>
</html>
I guess the issues happens at the encode strings. I solved same issues. Please try adding trim() at last of the encode string.
If you are that particular to pass elements to viewmodel You can use
CommandParameter="{Binding ElementName=ManualParcelScanScreen}"
I encountered a similar problem, with a syntax error that I knew should not be a syntax error. In my case it turned out that a Python 2 interpreter was trying to run Python 3 code, or vice versa; I think that my shell had a PYTHONPATH with a mixture of Python 2 and Python 3.
If all you are doing is adding css to the page, then I would suggest you use the Stylish addon, and write a user style instead of a user script, because a user style is more efficient and appropriate.
See this page with information on how to create a user style
Comparison sorts (i.e. ones based on comparing elements) cannot possibly be faster than n log n
. It doesn't matter what the underlying data structure is. See Wikipedia.
Other kinds of sort that take advantage of there being lots of identical elements in the list (such as the counting sort), or some expected distribution of elements in the list, are faster, though I can't think of any that work particularly well on a linked list.
To Find the problem label(s) in a large storyboard, follow my steps below.
Next, reveal your storyboard as source file.
Search. You should be able to tell what label it is from here quite easily by looking at the content.
Once you find the label the solution that worked for me was to set the "preferred width" to 0.
BTW, you can always quickly get the id of an interface item by selecting the item and looking under the identify inspector. Very handy.
You might want to look here and here.
A Little code example from the first link:
<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
print "Error: ". $fault;
}
else if ($price == -1) {
print "The book is not in the database.";
} else {
// otherwise output the result
print "The price of book number ". $param[isbn] ." is $". $price;
}
// kill object
unset($client);
?>
Principally; you can assign a value to a static readonly field to a non-constant value at runtime, whereas a const has to be assigned a constant value.
What about element.tagName
?
See also tagName
docs on MDN.
One more trick, search photos by hashtags:
GET https://www.instagram.com/graphql/query/?query_hash=3e7706b09c6184d5eafd8b032dbcf487&variables={"tag_name":"nature","first":25,"after":""}
Where:
query_hash
- permanent value(i belive its hash of 17888483320059182, can be changed in future)
tag_name
- the title speaks for itself
first
- amount of items to get (I do not know why, but this value does not work as expected. The actual number of returned photos is slightly larger than the value multiplied by 4.5 (about 110 for the value 25, and about 460 for the value 100))
after
- id of the last item if you want to get items from that id. Value of end_cursor
from JSON response can be used here.
ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
ini_set('max_execution_time', '0'); // for infinite time of execution
Place this at the top of your PHP script and let your script loose!
Taken from Increase PHP Script Execution Time Limit Using ini_set()
Another one I've found useful: "Numbers" allows encoding-settings when saving as CSV.
These values vary from person to person, especially for people who are colorblind.
You can use T-SQL's built in format function:
declare @number int = 1
select format (@number, '0#')
I'd suggest following a few debugging steps.
First run the query directly against the DB. Confirm it is bringing results back. Even with something as simple as this you can find you've made a mistake, or the table is empty, or somesuch oddity.
If the above is ok, then try looping and echoing out the contents of $row just directly into the HTML to see what you've getting back in the mysql_query - see if it matches what you got directly in the DB.
If your data is output onto the page, then look at what's going wrong in your HTML formatting.
However, if nothing is output from $row
, then figure out why the mysql_query isn't working e.g. does the user have permission to query that DB, do you have an open DB connection, can the webserver connect to the DB etc [something on these lines can often be a gotcha]
Changing your query slightly to
$sql = mysql_query("SELECT username FROM users") or die(mysql_error());
may help to highlight any errors: php manual
The correct value for the content
attribute should include initial-scale
instead:
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
^^^^^^^^^^^^^^^
_x000D_
Try This Once...
*{_x000D_
padding:0;_x000D_
margin:0;_x000D_
}_x000D_
.parent_div{_x000D_
overflow:hidden;_x000D_
clear:both;_x000D_
color:#fff;_x000D_
text-align:center;_x000D_
}_x000D_
_x000D_
.left_div {_x000D_
float: left;_x000D_
height: 100vh;_x000D_
width: 50%;_x000D_
background-color: blue;_x000D_
_x000D_
}_x000D_
_x000D_
.right_div {_x000D_
float: right;_x000D_
height: 100vh;_x000D_
width: 50%;_x000D_
background-color: green;_x000D_
_x000D_
}
_x000D_
<div class=" parent_div">_x000D_
<div class="left_div">Left</div>_x000D_
<div class="right_div">Right</div>_x000D_
</div>
_x000D_
This worked for me in Swift 5.0. Set the Storyboard Id in the identity inspector as "destinationVC".
@IBAction func buttonTapped(_ sender: Any) {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let destVC = storyboard.instantiateViewController(withIdentifier: "destinationVC") as! MyViewController
destVC.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
destVC.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
self.present(destVC, animated: true, completion: nil)
}
Here's a video that will show you, step-by-step, how to export data to Excel. It's a great solution for 'one-off' problems where you need to export to Excel:
Ad-Hoc Reporting
We basically use user controls when we have to use similar functionality on different locations of an app. Like we use master pages for consistent look and feel of app, similarly to avoid repeating the same functionality and UI all over the app, we use usercontrols. There might me much more usage too, but I know this one only...
For example, let's say your site has 4 levels of users and for each user there are different pages under different directories with different access mechanisms. Say you are requesting address info for all users, then creating address fields like Street, City, State, Zip, etc on each page. That would be a repetitive job. Instead you can create it as an ascx file (ext for user control) and in this control put the necessary UI and business code for add/update/delete/select the address role wise and then simply reference it all required page.
So, thought user controls, one can avoid code repetition for each role and UI creation for each role.
The Pattern.quote(String s)
sort of does what you want. However it leaves a little left to be desired; it doesn't actually escape the individual characters, just wraps the string with \Q...\E
.
There is not a method that does exactly what you are looking for, but the good news is that it is actually fairly simple to escape all of the special characters in a Java regular expression:
regex.replaceAll("[\\W]", "\\\\$0")
Why does this work? Well, the documentation for Pattern
specifically says that its permissible to escape non-alphabetic characters that don't necessarily have to be escaped:
It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
For example, ;
is not a special character in a regular expression. However, if you escape it, Pattern
will still interpret \;
as ;
. Here are a few more examples:
>
becomes \>
which is equivalent to >
[
becomes \[
which is the escaped form of [
8
is still 8
.\)
becomes \\\)
which is the escaped forms of \
and (
concatenated. Note: The key is is the definition of "non-alphabetic", which in the documentation really means "non-word" characters, or characters outside the character set [a-zA-Z_0-9]
.
There are some cases during development when there is no service yet but you want to simulate it and keep the container alive.
It is very easy to write a bash placeholder that simulates a running service:
while true; do
sleep 100
done
You replace this by something more serious as the development progress.
Here is how I would write it.
String[] fruit = "apple banana orange".split(" ");
System.out.println(fruit[1]);
Modifying styles directly in range or cells did not work for me. But the idea to:
Style
property of the range, given in MSDN How to: Programmatically Apply Styles to Ranges in Workbooks did the job.
For example:
var range = worksheet.Range[string.Format("A{0}:C{0}", rowIndex++)];
range.Merge();
range.Value = "some value";
var style = workbook.AddStyle();
style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
range.Style = style.Name;
The Do/While solution is more elegant, but if you do use just the While solution posted above, without the moveToPosition(-1) you will miss the first element (at least on the Contact query).
I suggest:
if (cursor.getCount() > 0) {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
<do stuff>
}
}
Make sure that you have given constraints to the table. I hadn't and faced the similar issue of having an unexplained padding at the bottom of table.
Made a Grunt build with the Bootstrap 3.3.5 grid only:
https://github.com/horgen/grunt-builds/tree/master/bootstrap-grid
~10KB minimized.
If you need some other parts from Bootstrap just include them in /src/less/bootstrap.less.
The difference between
import java.util.*;
and
import java.util.*;
import java.util.List;
import java.util.Arrays;
becomes apparent when the code refers to some other List
or Arrays
(for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays
declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays
will be used.
You may find it easier to loop over your array and build a new array out of the items you want to keep from the array than by trying to loop and splice as has been suggested, since modifying the length of the array while it is being looped over can introduce problems.
You could do something like this:
function removeFalsyElementsFromArray(someArray) {
var newArray = [];
for(var index = 0; index < someArray.length; index++) {
if(someArray[index]) {
newArray.push(someArray[index]);
}
}
return newArray;
}
Actually here is a more generic solution:
function removeElementsFromArray(someArray, filter) {
var newArray = [];
for(var index = 0; index < someArray.length; index++) {
if(filter(someArray[index]) == false) {
newArray.push(someArray[index]);
}
}
return newArray;
}
// then provide one or more filter functions that will
// filter out the elements based on some condition:
function isNullOrUndefined(item) {
return (item == null || typeof(item) == "undefined");
}
// then call the function like this:
var myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,];
var results = removeElementsFromArray(myArray, isNullOrUndefined);
// results == [1,2,3,3,4,4,5,6]
You get the idea - you could then have other types of filter functions. Probably more than you need, but I was feeling generous... ;)
In html
$('#raisepay_id').attr("readonly", true)
$("#raisepay_id").prop("readonly",true);
in bootstrap
$('#raisepay_id').attr("disabled", true)
$("#raisepay_id").prop("disabled",true);
JQuery is a changing library and sometimes they make regular improvements. .attr() is used to get attributes from the HTML tags, and while it is perfectly functional .prop() was added later to be more semantic and it works better with value-less attributes like 'checked' and 'selected'.
It is advised that if you are using a later version of JQuery you should use .prop() whenever possible.
A work Around :
Collections.reverse(stringList).forEach(str -> ...);
Or with guava :
Lists.reverse(stringList).forEach(str -> ...);
On Windows, using Total Commander all you have to do is select the folder click shift + delete . Don't forget about the shift key.
var ids = [];
$(document).ready(function($) {
$(".color_cell").bind('click', function() {
alert('Test');
ids.push(this.id);
});
});
In my case, I had an Object-C file which was also in the same Target Membership. I fixed by adding #import "YourObjectCFileHeader.h"
inside file Bridging-Header.h
I've found only this actually works.
**/node_modules/*
!**/node_modules/keep-dir
I am late, but here's another gotcha : Google shows the API as enabled, but in fact they are not. Disable then re-enable it.
PHP has its own inbuilt class that can be used to unzip or extracts contents from a zip file. The class is ZipArchive. Below is the simple and basic PHP code that will extract a zip file and place it in a specific directory:
<?php
$zip_obj = new ZipArchive;
$zip_obj->open('dummy.zip');
$zip_obj->extractTo('directory_name/sub_dir');
?>
If you want some advance features then below is the improved code that will check if the zip file exists or not:
<?php
$zip_obj = new ZipArchive;
if ($zip_obj->open('dummy.zip') === TRUE) {
$zip_obj->extractTo('directory/sub_dir');
echo "Zip exists and successfully extracted";
}
else {
echo "This zip file does not exists";
}
?>
Have a look at json_encode() in PHP. You can get $.ajax to recognize this with the dataType: "json" parameter.
The date function would be defined something like this:
function date($format, $timestamp = null)
{
if ($timestamp === null) {
$timestamp = time();
}
// Format the timestamp according to $format
}
Usually, you would put the default value like this:
function foo($required, $optional = 42)
{
// This function can be passed one or more arguments
}
However, only literals are valid default arguments, which is why I used null
as default argument in the first example, not $timestamp = time()
, and combined it with a null check. Literals include arrays (array()
or []
), booleans, numbers, strings, and null
.
Json.NET probably serializes C# dictionaries adequately now, but when the OP originally posted this question, many MVC developers may have been using the JavaScriptSerializer class because that was the default option out of the box.
If you're working on a legacy project (MVC 1 or MVC 2), and you can't use Json.NET, I recommend that you use a List<KeyValuePair<K,V>>
instead of a Dictionary<K,V>>
. The legacy JavaScriptSerializer class will serialize this type just fine, but it will have problems with a dictionary.
Documentation: Serializing Collections with Json.NET
If the variable required to be final, cannot be then you can assign the value of the variable to another variable and make THAT final so you can use it instead.
2020 Update: Concatenation by String Interpolation
RFC 2795 issued 2019-10-27: Suggests support for implicit arguments to do what many people would know as "string interpolation" -- a way of embedding arguments within a string to concatenate them.
RFC: https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
Latest issue status can be found here: https://github.com/rust-lang/rust/issues/67984
At the time of this writing (2020-9-24), I believe this feature should be available in the Rust Nightly build.
This will allow you to concatenate via the following shorthand:
format_args!("hello {person}")
It is equivalent to this:
format_args!("hello {person}", person=person)
There is also the "ifmt" crate, which provides its own kind of string interpolation:
Another way to think about Return-Path
vs Reply-To
is to compare it to snail mail.
When you send an envelope in the mail, you specify a return address. If the recipient does not exist or refuses your mail, the postmaster returns the envelope back to the return address. For email, the return address is the Return-Path
.
Inside of the envelope might be a letter and inside of the letter it may direct the recipient to "Send correspondence to example address". For email, the example address is the Reply-To
.
In essence, a Postage Return Address is comparable to SMTP's Return-Path
header and SMTP's Reply-To
header is similar to the replying instructions contained in a letter.
raw_input
returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3
is "ABABAB"
; how much is "L" * 3.14
? Please do not reply "LLL|"
). You need to parse the string to a numerical value.
You might want to try:
salesAmount = float(raw_input("Insert sale amount here\n"))
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
In my opinion the answer is wrong! He asked for event.preventDefault();
when you simply return false; it calls event.preventDefault();
AND event.stopPropagation();
as well!
You can solve it by this:
<a href="#" onclick="callmymethod(event, 24)">Call</a>
function callmymethod(e, myVal){
//doing custom things with myVal
//here I want to prevent default
e = e || window.event;
e.preventDefault();
}
I had this issue recently and I resolved it by simply rolling IE8 back to IE7.
My guess is that IE7 had these files as a wrapper for working on Windows XP, but IE8 was likely made to work with Vista/7 so it removed the files because the later editions just don't use the shim.
Taken from this comment on the PHP manual, you could use this:
function gen_uuid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
// 16 bits for "time_mid"
mt_rand( 0, 0xffff ),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand( 0, 0x0fff ) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand( 0, 0x3fff ) | 0x8000,
// 48 bits for "node"
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
def test():
....
return r1, r2, r3, ....
>> ret_val = test()
>> print ret_val
(r1, r2, r3, ....)
now you can do everything you like with your tuple.
You can use the status command in MySQL client.
mysql> status;
--------------
mysql Ver 14.14 Distrib 5.5.8, for Win32 (x86)
Connection id: 1
Current database: test
Current user: ODBC@localhost
SSL: Not in use
Using delimiter: ;
Server version: 5.5.8 MySQL Community Server (GPL)
Protocol version: 10
Connection: localhost via TCP/IP
Server characterset: latin1
Db characterset: latin1
Client characterset: gbk
Conn. characterset: gbk
TCP port: 3306
Uptime: 7 min 16 sec
Threads: 1 Questions: 21 Slow queries: 0 Opens: 33 Flush tables: 1 Open tables: 26 Queries per second avg: 0.48
--------------
mysql>
It should be put in the HTTP Authorization header. The spec is here https://tools.ietf.org/html/rfc7235
If you want to add a bounding box, use a rectangle:
ax = plt.gca()
r = matplotlib.patches.Rectangle((.5, .5), .25, .1, fill=False)
ax.add_artist(r)
If you are looking for readability, I believe that this is that code:
print '%(kg).2f kg = %(lb).2f lb = %(gal).2f gal = %(l).2f l' % {
'kg': var1,
'lb': var2,
'gal': var3,
'l': var4,
}
You should read the documentation about DesiredCapabilities. There is also a different page for the ChromeDriver. Javadoc from Capabilities
:
Capabilities: Describes a series of key/value pairs that encapsulate aspects of a browser.
Basically, the DesiredCapabilities
help to set properties for the WebDriver. A typical usecase would be to set the path for the FirefoxDriver
if your local installation doesn't correspond to the default settings.
The id of your private channel is the XXXXXX part (between the "p=c" and the underscore). To use it, just add "-100" in front of it. So if "XXXXXX" is "4785444554" your private channel id id "-1004785444554".
In my case I have a sequence called PS_LOG_SEQ
which had a LAST_NUMBER = 3920
.
I then imported some data from PROD
to my local machine and inserted into the PS_LOG
table. Production data had more than 20000
rows with the latest LOG_ID (primary key) being 20070. After importing I tried to insert new rows in this table but when saving I got an exception like this one:
ORA-00001: unique constraint (LOG.PS_LOG_PK) violated
Surely this has to do with the Sequence PS_LOG_SEQ
associated with the PS_LOG
table. The LAST_NUMBER
was colliding with data I imported which had already used the next ID value from the PS_LOG_SEQ
.
To solve that I used this command to update the sequence to the latest \ max(LOG_ID)
+ 1:
alter sequence PS_LOG_SEQ restart start with 20071;
This command reset the LAST_NUMBER
value and I could then insert new rows into the table. No more collision. :)
Note: this alter sequence
command is new in Oracle 12c.
Note: this blog post
documents the ALTER SEQUENCE RESTART option does exist, but as of 18c, is not documented. Its apparently intended for internal Oracle use.
First make your template into a jQuery object:
var template = $("<li><div class='bar'>bla</div></li>");
Then set the attributes and append it to the DOM.
template.find('li').attr('id','1234');
$(document.body).append(template);
Note that it however makes no sense at all to add a li directly to the DOM since li should always be children of ul or ol. Also it is better to not make jQuery parse raw HTML. Instead create a li, set its attributes. Create a div and set it's attributes. Insert the div into the li and then append the li to the DOM.
import time
year = time.strftime("%Y") # or "%y"
I do tend to use static classes for factories. For example, this is the logging class in one of my projects:
public static class Log
{
private static readonly ILoggerFactory _loggerFactory =
IoC.Resolve<ILoggerFactory>();
public static ILogger For<T>(T instance)
{
return For(typeof(T));
}
public static ILogger For(Type type)
{
return _loggerFactory.GetLoggerFor(type);
}
}
You might have even noticed that IoC is called with a static accessor. Most of the time for me, if you can call static methods on a class, that's all you can do so I mark the class as static for extra clarity.
Your first CSS selector—social.h2
—is looking for the "social" element in the "h2", class, e.g.:
<social class="h2">
Class selectors are proceeded with a dot (.
). Also, use a space () to indicate that one element is inside of another. To find an
<h2>
descendant of an element in the social
class, try something like:
.social h2 {
color: pink;
font-size: 14px;
}
To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.
I would not expect that to work
try instead
window.frames["printf"].focus();
window.frames["printf"].print();
and use
<iframe id="printf" name="printf"></iframe>
Alternatively try good old
var newWin = window.frames["printf"];
newWin.document.write('<body onload="window.print()">dddd</body>');
newWin.document.close();
if jQuery cannot hack it
Add buttonTint in your xml
<CheckBox
android:id="@+id/chk_remember_signup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="@android:color/white"
android:text="@string/hint_chk_remember_me" />
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}
The easiest and the most correct (and legal) way is to use graph api.
Just perform the request: http://graph.facebook.com/4
which returns
{
"id": "4",
"name": "Mark Zuckerberg",
"first_name": "Mark",
"last_name": "Zuckerberg",
"link": "http://www.facebook.com/zuck",
"username": "zuck",
"gender": "male",
"locale": "en_US"
}
and take the link
key.
You can also reduce the traffic by using fields
parameter: http://graph.facebook.com/4?fields=link to get only what you need:
{
"link": "http://www.facebook.com/zuck",
"id": "4"
}
What is the len
of the equivalent nested list?
len([[2,3,1,0], [2,3,1,0], [3,2,1,1]])
With the more general concept of shape
, numpy
developers choose to implement __len__
as the first dimension. Python maps len(obj)
onto obj.__len__
.
X.shape
returns a tuple, which does have a len
- which is the number of dimensions, X.ndim
. X.shape[i]
selects the ith
dimension (a straight forward application of tuple indexing).
Just an addition to nicktea's answer. This code loads the content of a remote page (without redirecting there), and also cleans up when closing it.
<script type="text/javascript">
function showDialog() {
$('<div>').dialog({
modal: true,
open: function () {
$(this).load('AccessRightsConfig.htm');
},
close: function(event, ui) {
$(this).remove();
},
height: 400,
width: 600,
title: 'Ajax Page'
});
return false;
}
</script>
If you have control over the entity that's returning true
/false
, one option is to have it return 1
/0
instead of true
/false
, then:
boolean_response = bool(int(response))
The extra cast to int
handles responses from a network, which are always string.
Update 2021: "which are always string" -- this is a naive observation. It depends on the serialization protocol used by the library. Default serialization of high-level libraries (the ones used by most web devs) is typically to convert to string before being serialized to bytes. And then on the other side, it's deserialized from bytes to string, so you've lost any type information.
IF...ELSE... is pretty much what we've got in T-SQL. There is nothing like structured programming's CASE statement. If you have an extended set of ...ELSE IF...s to deal with, be sure to include BEGIN...END for each block to keep things clear, and always remember, consistent indentation is your friend!
I have made a bash script related to the same to check if the certificate is expired or not. You can use the same if required.
Script
https://github.com/zeeshanjamal16/usefulScripts/blob/master/sslCertificateExpireCheck.sh
ReadMe
https://github.com/zeeshanjamal16/usefulScripts/blob/master/README.md
you can check by putting these code in php file.
<?php
if(in_array ('curl', get_loaded_extensions())) {
echo "CURL is available on your web server";
}
else{
echo "CURL is not available on your web server";
}
OR
var_dump(extension_loaded('curl'));
Use a regular expression for .replace()
.:
messagetoSend = messagetoSend.replace(/\n/g, "<br />");
If those linebreaks were made by windows-encoding, you will also have to replace the carriage return
.
messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");
Lots of things here:
\r\n
, not \n\r
.\n
without the \r
(or even in unusual cases, possibly just the \r
)Given the last point, you may find preg_split()
using all the possible variants will give you a more reliable way of splitting the data than explode()
. But alternatively you could use explode()
with just \n
, and then use trim()
to remove any \r
characters that are left hanging around.
You need to add the following line:
using FootballLeagueSystem;
into your all your classes (MainMenu.cs, programme.cs, etc.) that use Login
.
At the moment the compiler can't find the Login
class.
I would like to thank the person who posted the answer, but he has deleted the post. We can do it like this.
$("#yourElem").uploadify({
'uploader': ...,
'script': ...
'fileExt' : '*.jpg;*.gif;', //add allowed extensions
.....,
'onSelect': function(e, q, f) {
var validExtensions = ['jpg','gif']; //array of valid extensions
var fileName = f.name;
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
if ($.inArray(fileNameExt, validExtensions) == -1){
alert("Invalid file type");
$("#yourElem").uploadifyCancel(q);
return false;
}
}
});
Thanks for the answer, it really worked...
You can use the substring method:
String aString = "This.is.a.great.place.too.work.";
String aSubstring = "work";
String endString = aString.substring(aString.length() -
(aSubstring.length() + 1),aString.length() - 1);
if ( endString.equals(aSubstring) )
System.out.println("Equal " + aString + " " + aSubstring);
else
System.out.println("NOT equal " + aString + " " + aSubstring);
As long as you clearly reference the other commit from the empty commit it should be fine. Something like:
Commit message errata for [commit sha1]
[new commit message]
As others have pointed out, this is often preferable to force pushing a corrected commit.
Here is another simpler way to slice last elements
var tags = [1, 2, 3, "foo", "bar", "foobar", "barfoo"];
var lastObj = tags.slice(-1);
lastObj
is now ["barfoo"]
.
Python does this the same way and when I tried using JS it worked out. I am guessing string manipulation in scripting languages work the same way.
Similarly, if you want the last two objects in a array,
var lastTwoObj = tags.slice(-2)
will give you ["foobar", "barfoo"]
and so on.
I think your issue is that Range("H18")
doesn't contain a formula. Also, you could make your code more efficient by eliminating x
. Instead, change your code to
Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")
I had the same problem. I solved it by removing the line break from the xml file. I did
<operationBindings>
<OperationBinding>
<operationType>update</operationType>
<operationId>makePdf</operationId>
<serverObject>
<className>com.myclass</className>
<lookupStyle>new</lookupStyle>
</serverObject>
<serverMethod>makePdf</serverMethod>
</OperationBinding>
</operationBindings>
instead of ...
<serverObject>
<className>com.myclass
</className>
<lookupStyle>new</lookupStyle>
</serverObject>
When it comes to memory usage, x86 is limited to circa 3 / 3,5 Gb, while x64 works fine with 4 Gb and more.
Moreover, when it comes to Windows, x86 will run on both X86 and x64 processors, while x64 requires x64 processor only.
May be the easy one to see the source:
In Android studio 2.3, Build -> Analyze APK -> Select the apk that you want to decompile
.
You will see it's source code.
Link for reference:
https://medium.com/google-developers/making-the-most-of-the-apk-analyzer-c066cb871ea2
Apart from following the optimizations mentioned in existing answers (not much helpful, was still painfully slow), doing below did the trick for me.
HP Notebook with 6 GM RAM and i5 processor I have, still android studio was terribly slow. After checking task manager for memory usage, noticed that there is a software called "HP Touchpoint Analytics Client" that was taking more than 1 GB memory. Found that it's a spyware installed by HP in Windows 10 after searching about it in Google.
Uninstalled a bunch of HP software which does nothing and slows down the system. Now, Android studio is considerably fast - Gradle build completes in less than 30 seconds when compared to more than 2 minutes before. Every keystroke would take 5 seconds to respond, now it is real time and performance is comparable with Eclipse.
This might be true for Laptops from other vendors as well like Dell, etc. HP really messed up the user experience with their spyware for Windows 10 users. Uninstall them, it will help Android studio and improves the overall laptop experience as well.
Hope this helps someone. Thanks.
Consider TextArea
People finding this via Google and looking for a better way to manage the display of their snippets should also consider <textarea>
which gives a lot of control over width/height, scrolling etc. Noting that @vsync mentioned the deprecated tag <xmp>
, I find <textarea readonly>
is an excellent substitute for displaying HTML without the need to escape anything inside it (except where </textarea>
might appear within).
For example, to display a single line with controlled line wrapping, consider <textarea rows=1 cols=100 readonly>
your html or etc with any characters including tabs and CrLf's </textarea>
.
<textarea rows=5 cols=100 readonly>Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>displayed</b>._x000D_
However, note that & still acts as an escape char.._x000D_
Eg: <u>(text)</u>_x000D_
</textarea>
_x000D_
To compare all...
<h2>Compared: TEXTAREA, XMP, PRE, SAMP, CODE</h2>_x000D_
<p>Note that CSS can be used to override default fixed space fonts in each or all these.</p>_x000D_
_x000D_
_x000D_
<textarea rows=5 cols=100 readonly>TEXTAREA: Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>displayed natively</b>._x000D_
However, note that & still acts as an escape char.._x000D_
Eg: <u>(text)</u></textarea>_x000D_
_x000D_
<xmp>XMP: Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>displayed natively</b>._x000D_
However, note that & (&) will not act as an escape char.._x000D_
Eg: <u>(text)</u>_x000D_
</xmp>_x000D_
_x000D_
<pre>PRE: Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>are interpreted, not displayed</b>._x000D_
However, note that & still acts as an escape char.._x000D_
Eg: <u>(text)</u>_x000D_
</pre>_x000D_
_x000D_
<samp>SAMP: Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>are interpreted, not displayed</b>._x000D_
However, note that & still acts as an escape char.._x000D_
Eg: <u>(text)</u>_x000D_
</samp>_x000D_
_x000D_
<code>CODE: Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>are interpreted, not displayed</b>._x000D_
However, note that & still acts as an escape char.._x000D_
Eg: <u>(text)</u>_x000D_
</code>
_x000D_
When creating an application where I needed to generate 30,000 unique numbers within a larger range, I was able to cut down processing time from 25 seconds to 1.5 seconds using this method.
The idea is that PHP is much faster at generating random numbers than it is at checking the existence of items in an array - that is why using a while(in_array) loop can be slow.
$count = 0;
$collectNumbers = [];
while ($count < 30000) {
for ($i = 0; $i < 60000; $i++) {
$rand = mt_rand(1, 100000);
$collectNumbers[] = $rand;
}
$unique = array_unique($collectNumbers);
$count = count($unique);
}
$finalArray = array_slice($unique, 0, 30000);
This will return 30,000 unique numbers extremely quickly. Using an iteration value that is double the amount of numbers you need to generate can increase the likelihood of unique numbers the first iteration... but regardless of how many iterations it takes, this will produce a result faster than checking your array for repeated numbers in a loop.
TLDR; The formula is n(n-1)/2
where n
is the number of items in the set.
To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA)
, you can calculate the summation of 1 + 2 + ... + (n-1)
where n
is the number of items in the set.
The reasoning is as follows, say you have 4 items:
A
B
C
D
The number of items that can be paired with A
is 3, or n-1
:
AB
AC
AD
It follows that the number of items that can be paired with B
is n-2
(because B
has already been paired with A
):
BC
BD
and so on...
(n-1) + (n-2) + ... + (n-(n-1))
which is the same as
1 + 2 + ... + (n-1)
or
n(n-1)/2
The format is %lu
.
Please check about the various other datatypes and their usage in printf here
I like the simplicity of tabulary
package:
\usepackage{tabulary}
...
\begin{tabulary}{\linewidth}{LCL}
\hline
Short sentences & \# & Long sentences \\
\hline
This is short. & 173 & This is much loooooooonger, because there are many more words. \\
This is not shorter. & 317 & This is still loooooooonger, because there are many more words. \\
\hline
\end{tabulary}
In the example, you arrange the whole width of the table with respect to \textwidth. E.g 0.4 of it. Then the rest is automatically done by the package.
Most of the example is taken from http://en.wikibooks.org/wiki/LaTeX/Tables .
Here is a good example of array_keys
from PHP.js library:
function array_keys (input, search_value, argStrict) {
// Return just the keys from the input array, optionally only for the specified search_value
var search = typeof search_value !== 'undefined',
tmp_arr = [],
strict = !!argStrict,
include = true,
key = '';
for (key in input) {
if (input.hasOwnProperty(key)) {
include = true;
if (search) {
if (strict && input[key] !== search_value) {
include = false;
}
else if (input[key] != search_value) {
include = false;
}
}
if (include) {
tmp_arr[tmp_arr.length] = key;
}
}
}
return tmp_arr;
}
The same goes for array_values
(from the same PHP.js library):
function array_values (input) {
// Return just the values from the input array
var tmp_arr = [],
key = '';
for (key in input) {
tmp_arr[tmp_arr.length] = input[key];
}
return tmp_arr;
}
EDIT: Removed unnecessary clauses from the code.
Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.
Sometimes using image = array(img).reshape(a,b,c,d)
will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is
np.expand_dims(img, axis=0)
It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.
res.json()
returns a promise. Try ...
res.json().then(body => console.log(body));
While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...
To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop
command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).
Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."
Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop
.
Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage
It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.
Good to know:
It's also worth referencing this Bluebird promises library wiki page that shows how to manage the arguments
object into array in a way that makes the function optimizable under V8 JavaScript engine:
function doesntLeakArguments() {
var args = new Array(arguments.length);
for(var i = 0; i < args.length; ++i) {
args[i] = arguments[i];
}
return args;
}
This method is used in favor of var args = [].slice.call(arguments);
. The author also shows how a build step can help reduce the verbosity.
I'm finding that it's kind of tricky to get pip3 (v9.0.1, as installed by Ubuntu 18.04's package manager) to actually install the thing I tell it to install. I'm posting this answer to save anyone's time who runs into this problem.
Putting this into a requirements.txt file failed:
git+git://github.com/myname/myrepo.git@my-branch#egg=eggname
By "failed" I mean that while it downloaded the code from Git, it ended up installing the original version of the code, as found on PyPi, instead of the code in the repo on that branch.
However, installing the commmit instead of the branch name works:
git+git://github.com/myname/myrepo.git@d27d07c9e862feb939e56d0df19d5733ea7b4f4d#egg=eggname
Solution without using loops and recursion.
Use the required pattern in compile method and enter the desired occurrence in variable 'n' and the last statement will print the starting index of the nth occurrence of the pattern in the given string. Here the result of finditer i.e. iterator is being converted to list and directly accessing the nth index.
import re
n=2
sampleString="this is history"
pattern=re.compile("is")
matches=pattern.finditer(sampleString)
print(list(matches)[n].span()[0])
You can switch on string!
switch(name)
{
case "Dave":
return true;
case "Bob":
return false;
default:
throw new ApplicationException();
}
Very handy! and a lot cleaner than a bunch of if-else statements
For sub-objects, ReadSubtree()
gives you an xml-reader limited to the sub-objects, but I really think that you are doing this the hard way. Unless you have very specific requirements for handling unusual / unpredicatable xml, use XmlSerializer
(perhaps coupled with sgen.exe
if you really want).
XmlReader
is... tricky. Contrast to:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
public class ApplicationPool {
private readonly List<Account> accounts = new List<Account>();
public List<Account> Accounts {get{return accounts;}}
}
public class Account {
public string NameOfKin {get;set;}
private readonly List<Statement> statements = new List<Statement>();
public List<Statement> StatementsAvailable {get{return statements;}}
}
public class Statement {}
static class Program {
static void Main() {
XmlSerializer ser = new XmlSerializer(typeof(ApplicationPool));
ser.Serialize(Console.Out, new ApplicationPool {
Accounts = { new Account { NameOfKin = "Fred",
StatementsAvailable = { new Statement {}, new Statement {}}}}
});
}
}
Downloading Wget is not necessary; the .NET Framework has web client classes built in.
$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")
Just get the millisecond timestamp and add 20 minutes to it:
twentyMinutesLater = new Date(currentDate.getTime() + (20*60*1000))
You can do that in this way:
ORDER BY `products`.`product_category_id` DESC ,`naam` ASC
Have a look at ORDER BY
Optimization
Just have a look on my solution,[1] that I verbatim copied from my project, so there a German is API doc included. My goal was to combine flexibility and safety within my actual needs:[2]
0x
prefix added: caller may decidelong long
#include <string>
#include <sstream>
#include <iomanip>
/// Vertextet einen Ganzzahlwert val im Hexadezimalformat.
/// Auf die Minimal-Breite width wird mit führenden Nullen aufgefüllt;
/// falls nicht angegeben, wird diese Breite aus dem Typ des Arguments
/// abgeleitet. Funktion geeignet von char bis long long.
/// Zeiger, Fließkommazahlen u.ä. werden nicht unterstützt, ihre
/// Übergabe führt zu einem (beabsichtigten!) Compilerfehler.
/// Grundlagen aus: http://stackoverflow.com/a/5100745/2932052
template <typename T>
inline std::string int_to_hex(T val, size_t width=sizeof(T)*2)
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(width) << std::hex << (val|0);
return ss.str();
}
[1] based on the answer by Kornel Kisielewicz
[2] Translated into the language of CppTest, this is how it reads:
TEST_ASSERT(int_to_hex(char(0x12)) == "12");
TEST_ASSERT(int_to_hex(short(0x1234)) == "1234");
TEST_ASSERT(int_to_hex(long(0x12345678)) == "12345678");
TEST_ASSERT(int_to_hex((long long)(0x123456789abcdef0)) == "123456789abcdef0");
TEST_ASSERT(int_to_hex(0x123, 1) == "123");
TEST_ASSERT(int_to_hex(0x123, 8) == "00000123");
// with deduction test as suggested by Lightness Races in Orbit:
TEST_ASSERT(int_to_hex(short(0x12)) == "0012");
UI-Router is a project that can help: https://github.com/angular-ui/ui-router One of it's features is Multiple Named Views
UI-Router has many features and i recommend you using it if you're working on an advanced app.
Check documentation of Multiple Named Views here.
There's probably a more direct way using regular expressions. With luck, somebody else will provide it. But here's what I'd do without needing to go to the manuals.
Create a PLSQL function to receive your input string and return a varchar2.
In the PLSQL function, do an asciistr() of your input. The PLSQL is because that may return a string longer than 4000 and you have 32K available for varchar2 in PLSQL.
That function converts the non-ASCII characters to \xxxx notation. So you can use regular expressions to find and remove those. Then return the result.
Anything that is static
is in the class level. You don't have to create instance to access static fields/method. Static variable will be created once when class is loaded.
Instance variables are the variable associated with the object which means that instance variables are created for each object you create. All objects will have separate copy of instance variable for themselves.
In your case, when you declared it as static final
, that is only one copy of variable. If you change it from multiple instance, the same variable would be updated (however, you have final
variable so it cannot be updated).
In second case, the final int a
is also constant , however it is created every time you create an instance of the class where that variable is declared.
Have a look on this Java tutorial for better understanding ,
You have to look to official ReactiveX documentation: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md.
This is a good article about piping in RxJS: https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44.
In short .pipe() allows chaining multiple pipeable operators.
Starting in version 5.5 RxJS has shipped "pipeable operators" and renamed some operators:
do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize
I've recently found even more interesting way to create any ValueNode
or ContainerNode
(Jackson v2.3).
ObjectNode node = JsonNodeFactory.instance.objectNode();
In a nutshell, the syntax for Bower version numbers (and NPM's) is called SemVer, which is short for 'Semantic Versioning'. You can find documentation for the detailed syntax of SemVer as used in Bower and NPM on the API for the semver parser within Node/npm. You can learn more about the underlying spec (which does not mention ~
or other syntax details) at semver.org.
There's a super-handy visual semver calculator you can play with, making all of this much easier to grok and test.
SemVer isn't just a syntax! It has some pretty interesting things to say about the right ways to publish API's, which will help to understand what the syntax means. Crucially:
Once you identify your public API, you communicate changes to it with specific increments to your version number. Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version.
So, your specific question about ~
relates to that Major.Minor.Patch schema. (As does the related caret operator ^
.) You can use ~
to narrow the range of versions you're willing to accept to either:
For example: to indicate you'll take any subsequent patch-level changes on the 1.2.x tree, starting with 1.2.0, but less than 1.3.0, you could use:
"angular": "~1.2"
or:
"angular": "~1.2.0"
This also gets you the same results as using the .x
syntax:
"angular": "1.2.x"
But, you can use the tilde/~
syntax to be even more specific: if you're only willing to accept patch-level changes starting with 1.2.4, but still less than 1.3.0, you'd use:
"angular": "~1.2.4"
Moving left, towards the major version, if you use...
"angular": "~1"
... it's the same as...
"angular": "1.x"
or:
"angular": "^1.0.0"
...and matches any minor- or patch-level changes above 1.0.0, and less than 2.0:
Note that last variation above: it's called a 'caret range'. The caret looks an awful lot like a >
, so you'd be excused for thinking it means "any version greater than 1.0.0". (I've certainly slipped on that.) Nope!
Caret ranges are basically used to say that you care only about the left-most significant digit - usually the major version - and that you'll permit any minor- or patch-level changes that don't affect that left-most digit. Yet, unlike a tilde range that specifies a major version, caret ranges let you specify a precise minor/patch starting point. So, while ^1.0.0 === ~1
, a caret range such as ^1.2.3
lets you say you'll take any changes >=1.2.3 && <2.0.0
. You couldn't do that with a tilde range.
That all seems confusing at first, when you look at it up-close. But zoom out for a sec, and think about it this way: the caret simply lets you say that you're most concerned about whatever significant digit is left-most. The tilde lets you say you're most concerned about whichever digit is right-most. The rest is detail.
It's the expressive power of the tilde and the caret that explains why people use them much more than the simpler .x
syntax: they simply let you do more. That's why you'll see the tilde used often even where .x
would serve. As an example, see npm itself: its own package.json file includes lots of dependencies in ~2.4.0
format, rather than the 2.4.x
format it could use. By sticking to ~
, the syntax is consistent all the way down a list of 70+ versioned dependencies, regardless of which beginning patch number is acceptable.
Anyway, there's still more to SemVer, but I won't try to detail it all here. Check it out on the node semver package's readme. And be sure to use the semantic versioning calculator while you're practicing and trying to get your head around how SemVer works.
RE: Non-Consecutive Version Numbers: OP's final question seems to be about specifying non-consecutive version numbers/ranges (if I have edited it fairly). Yes, you can do that, using the common double-pipe "or" operator: ||
. Like so:
"angular": "1.2 <= 1.2.9 || >2.0.0"
C:\Users\username\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm-android.exe
check this location in windows
dirname(__FILE__)
will give the absolute route of the current file from which you are demanding the route, the route of your server directory.
example files :
www/http/html/index.php ; if you place this code inside your index.php it will return:
<?php
echo dirname(__FILE__); // this will return: www/http/html/
www/http/html/class/myclass.php ; if you place this code inside your myclass.php it will return:
<?php
echo dirname(__FILE__); // this will return: www/http/html/class/
var datep = $('#datepicker').val();
if(Date.parse(datep)-Date.parse(new Date())<0)
{
// do something
}
I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.
package local.test.servlet;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;
@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
// /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
System.out.println(templateFileUrl.getPath());
String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
String outputFileDir = "MasatoExcelHorizontalOutput";
ReportProcessor reportProcessor = new ReportProcessor();
ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);
ReportSheet outputSheet = new ReportSheet("MySheet");
outputBook.addReportSheet(outputSheet);
reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
System.out.println("wtf???");
reportProcessor.process(outputBook);
System.out.println("done!!");
}
catch(Exception e) {
System.out.println(e);
}
} //end doGet()
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}//end class
class OutputStreamExporter extends ReportBookExporter {
private HttpServletResponse response;
public OutputStreamExporter(HttpServletResponse response) {
this.response = response;
}
@Override
public String getExtention() {
return null;
}
@Override
public String getFormatType() {
return ExcelExporter.FORMAT_TYPE;
}
@Override
public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {
System.out.println(book.getFirstVisibleTab());
System.out.println(book.getSheetName(0));
//TODO write to stream
try {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
book.write(response.getOutputStream());
response.getOutputStream().close();
System.out.println("booya!!");
}
catch(Exception e) {
System.out.println(e);
}
}
}//end class
Make the files immutable. Not even root will be allowed to delete them.
chattr +i textfile.txt backup.tar.gz script.php database.sql info.txt
rm *
All other files have been deleted.
Eventually you can reset them mutable.
chattr -i *
delete build folder projectfile\android\app\build
and run project
Traditionally whenever I've wanted to commit and empty directory structure, I create the structure and then in the leaf directories place an empty file called empty.txt
.
Then when I put stuff in that's ready to commit, I can simply remove the empty.txt
file and commit the real files.
i.e.
There are a couple of different ways to approach the problem:
Each approach has its own quirks. You will need to setup SSH keys to enable password-less logins if you are wrapping system commands like "ssh", "scp" or "rsync." You can embed a password in a script using Paramiko or some other library, but you might find the lack of documentation frustrating, especially if you are not familiar with the basics of the SSH connection (eg - key exchanges, agents, etc). It probably goes without saying that SSH keys are almost always a better idea than passwords for this sort of stuff.
NOTE: its hard to beat rsync if you plan on transferring files via SSH, especially if the alternative is plain old scp.
I've used Paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity. You might be different. I gave Conch the once-over some time ago but it didn't appeal to me.
If opting for the system-call path, Python offers an array of options such as os.system or the commands/subprocess modules. I'd go with the subprocess module if using version 2.4+.
If the indices match then:
df['B'] = df1['E']
should work otherwise:
df['B'] = df1['E'].values
will work so long as the length of the elements matches
Here is an example of reading and taking at face value a chardet
encoding prediction, reading n_lines
from the file in the event it is large.
chardet
also gives you a probability (i.e. confidence
) of it's encoding prediction (haven't looked how they come up with that), which is returned with its prediction from chardet.predict()
, so you could work that in somehow if you like.
def predict_encoding(file_path, n_lines=20):
'''Predict a file's encoding using chardet'''
import chardet
# Open the file as binary data
with open(file_path, 'rb') as f:
# Join binary lines for specified number of lines
rawdata = b''.join([f.readline() for _ in range(n_lines)])
return chardet.detect(rawdata)['encoding']
Hackbod's is one of the best answers on Stack Overflow. It throws light on a very obscure subject. It helped me a lot.
Another really helpful resource is this must-see video: Google I/O 2011: Memory management for Android Apps
UPDATE:
Process Stats, a service to discover how your app manages memory explained at the blog post Process Stats: Understanding How Your App Uses RAM by Dianne Hackborn:
I don't see any mention of flexbox in here, so I will illustrate:
HTML
<div class="wrapper">
<div class="main">top</div>
<div class="footer">bottom</div>
</div>
CSS
.wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.main {
flex: 1;
}
.footer {
flex: 0;
}
By using regular expression: $string = preg_replace('/\s+By.*$/', '', $string)
Define these variables in the class:
int PICK_IMAGE_MULTIPLE = 1;
String imageEncoded;
List<String> imagesEncodedList;
Let's Assume that onClick on a button it should open gallery to select images
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);
Then you should override onActivityResult Method
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri=data.getData();
// Get the cursor
Cursor cursor = getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
super.onActivityResult(requestCode, resultCode, data);
}
NOTE THAT: the gallery doesn't give you the ability to select multi-images so we here open all images studio that you can select multi-images from them. and don't forget to add the permissions to your manifest
VERY IMPORTANT: getData(); to get one single image and I've stored it here in imageEncoded String if the user select multi-images then they should be stored in the list
So you have to check which is null to use the other
Wish you have a nice try and to others
My preferred solution to remove <ul> indentation is a simple CSS one-liner:
ul { padding-left: 1.2em; }
_x000D_
<p>A leading line of paragraph text</p>_x000D_
<ul>_x000D_
<li>Bullet points align with paragraph text above.</li>_x000D_
<li>Long list items wrap around correctly. Long list items wrap around correctly. Long list items wrap around correctly. Long list items wrap around correctly. Long list items wrap around correctly. </li>_x000D_
<li>List item 3</li>_x000D_
</ul>_x000D_
<p>A trailing line of paragraph text</p>
_x000D_
This solution is not only lightweight, but has multiple advantages:
Legacy info:
For IE versions 8 and below you must use margin-left instead:
ul { margin-left: 1.2em; }
Look at this link. In that method you can jump to your line code, when you double click on LogCat's row.
Also you can use this code to get line number:
public static int getLineNumber()
{
int lineNumber = 0;
StackTraceElement[] stackTraceElement = Thread.currentThread()
.getStackTrace();
int currentIndex = -1;
for (int i = 0; i < stackTraceElement.length; i++) {
if (stackTraceElement[i].getMethodName().compareTo("getLineNumber") == 0)
{
currentIndex = i + 1;
break;
}
}
lineNumber = stackTraceElement[currentIndex].getLineNumber();
return lineNumber;
}
When g++ says cannot find -l<nameOfTheLibrary>
, it means that g++ looked for the file lib{nameOfTheLibrary}.so
, but it couldn't find it in the shared library search path, which by default points to /usr/lib
and /usr/local/lib
and somewhere else maybe.
To resolve this problem, you should either provide the library file (lib{nameOfTheLibrary}.so
) in those search paths or use -L
command option. -L{path}
tells the g++ (actually ld
) to find library files in path {path}
in addition to default paths.
Example: Assuming you have a library at /home/taylor/libswift.so
, and you want to link your app to this library. In this case you should supply the g++ with the following options:
g++ main.cpp -o main -L/home/taylor -lswift
Note 1: -l
option gets the library name without lib
and .so
at its beginning and end.
Note 2: In some cases, the library file name is followed by its version, for instance libswift.so.1.2
. In these cases, g++ also cannot find the library file. A simple workaround to fix this is creating a symbolic link to libswift.so.1.2
called libswift.so
.
When you link your app to a shared library, it's required that library stays available whenever you run the app. In runtime your app (actually dynamic linker) looks for its libraries in LD_LIBRARY_PATH
. It's an environment variable which stores a list of paths.
Example: In case of our libswift.so
example, dynamic linker cannot find libswift.so
in LD_LIBRARY_PATH
(which points to default search paths). To fix the problem you should append that variable with the path libswift.so
is in.
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/taylor
According to the spec RFC 2045 #Syntax of the Content-Type Header Field application/myappname
is not allowed, but application/x-myappname
is allowed and sounds most appropriate for you're application to me.
For me in Xcode 5.1, I was getting The entitlements specified in your application’s Code Signing Entitlements file do not match those specified in your provisioning profile.
when trying to test the app on my device. Device Development Certificate has to expire Feb 2015.
Issue was resolved:
Selected Target->Capabilities
, under GameCenter, here I was getting error on GameCenter entitlement as it was not added to project, although first version of application was released via same XCode 5.1 but there were no errors like this before.
Below, a button was given with title Fix Issue
. When clicked it added the GameCenter entitlement and issue was resolved.
After wards the screen looks like:
For me, there was nothing to do with certificate or bundle identifier. App now runs successfully on the device.
Have you looked into rasdial?
Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network
ie
rasdial "VPN NETWORK NAME" "Username" *
it will then prompt for a password, else you can use "username" "password", this is however less secure
http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265
Try like this
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= '2013-12-04'
Wrote one up myself:
let regex = /([\w+]+\:\/\/)?([\w\d-]+\.)*[\w-]+[\.\:]\w+([\/\?\=\&\#\.]?[\w-]+)*\/?/gm
It works on ALL of the following domains:
https://www.facebook.com
https://app-1.number123.com
http://facebook.com
ftp://facebook.com
http://localhost:3000
localhost:3000/
unitedkingdomurl.co.uk
this.is.a.url.com/its/still=going?wow
shop.facebook.org
app.number123.com
app1.number123.com
app-1.numbEr123.com
app.dashes-dash.com
www.facebook.com
facebook.com
fb.com/hello_123
fb.com/hel-lo
fb.com/hello/goodbye
fb.com/hello/goodbye?okay
fb.com/hello/goodbye?okay=alright
Hello www.google.com World http://yahoo.com
https://www.google.com.tr/admin/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
https://google.com.tr/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
http://google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
ftp://google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
www.google.com.tr/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
www.google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
drive.google.com/test/subPage?qs1=sss1&qs2=sss2&qs3=sss3#Services
https://www.example.pl
http://www.example.com
www.example.pl
example.com
http://blog.example.com
http://www.example.com/product
http://www.example.com/products?id=1&page=2
http://www.example.com#up
http://255.255.255.255
255.255.255.255
shop.facebook.org/derf.html
You can see how it performs here on regex101 and adjust as needed