The best way is to use mpack!
mpack -s "Subject" -d "./body.txt" "././image.png" mailadress
mpack - subject - body - attachment - mailadress
On debian where bsd-mailx
is installed by default, the -r
option does not work. However you can use mailx -s subject [email protected] -- -f [email protected]
instead. According to man page, you can specify sendmail options after --
.
I had successfully used the following on Arch Linux (where the -a
flag is used for attachments) for several years:
mailx -s "The Subject $( echo -e "\nContent-Type: text/html" [email protected] < email.html
This appended the Content-Type header to the subject header, which worked great until a recent update. Now the new line is filtered out of the -s
subject. Presumably, this was done to improve security.
Instead of relying on hacking the subject line, I now use a bash subshell:
(
echo -e "Content-Type: text/html\n"
cat mail.html
) | mail -s "The Subject" -t [email protected]
And since we are really only using mailx
's subject flag, it seems there is no reason not to switch to sendmail
as suggested by @dogbane:
(
echo "To: [email protected]"
echo "Subject: The Subject"
echo "Content-Type: text/html"
echo
cat mail.html
) | sendmail -t
The use of bash subshells avoids having to create a temporary file.
Here you are :
echo "Body" | mailx -r "FROM_EMAIL" -s "SUBJECT" "To_EMAIL"
PS. Body and subject should be kept within double quotes.
Remove quotes from FROM_EMAIL
and To_EMAIL
while substituting email addresses.
$('#demoTable td').contents().each(function() {
if (this.nodeType === 3) {
this.textContent
? this.textContent = 'The text has been '
: this.innerText = 'The text has been '
} else {
this.innerHTML = 'changed';
return false;
}
})
It's possible to use a udev rule to let the system decide on the scheduler based on some characteristics of the hw.
An example udev rule for SSDs and other non-rotational drives might look like
# set noop scheduler for non-rotating disks
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="noop"
inside a new udev rules file (e.g., /etc/udev/rules.d/60-ssd-scheduler.rules
). This answer is based on the debian wiki
To check whether ssd disks would use the rule, it's possible to check for the trigger attribute in advance:
for f in /sys/block/sd?/queue/rotational; do printf "$f "; cat $f; done
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
__filename
is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js
)__dirname
is the directory name of the current module. (ex:/home/kyle/some/dir
)It is possible. Here is some step by step:
In $PROJECT_DIR/jni/Application.mk:
APP_STL := stlport_static
I tried using stlport_shared, but no luck. Same with libstdc++.
In $PROJECT_DIR/jni/Android.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.cpp
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)
Nothing special here, but make sure your files are .cpp.
In $PROJECT_DIR/jni/hello-jni.cpp:
#include <string.h>
#include <jni.h>
#include <android/log.h>
#include <iostream>
#include <vector>
#define LOG_TAG "hellojni"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#ifdef __cplusplus
extern "C" {
#endif
// Comments omitted.
void
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
jobject thiz )
{
std::vector<std::string> vec;
// Go ahead and do some stuff with this vector of strings now.
}
#ifdef __cplusplus
}
#endif
The only thing that bite me here was #ifdef __cplusplus.
Watch the directories.
To compile, use ndk-build clean && ndk-build
.
I've extended String with two substring methods. You can call substring with a from/to range or from/length like so:
var bcd = "abcdef".substring(1,to:3)
var cde = "abcdef".substring(2,to:-2)
var cde = "abcdef".substring(2,length:3)
extension String {
public func substring(from:Int = 0, var to:Int = -1) -> String {
if to < 0 {
to = self.length + to
}
return self.substringWithRange(Range<String.Index>(
start:self.startIndex.advancedBy(from),
end:self.startIndex.advancedBy(to+1)))
}
public func substring(from:Int = 0, length:Int) -> String {
return self.substringWithRange(Range<String.Index>(
start:self.startIndex.advancedBy(from),
end:self.startIndex.advancedBy(from+length)))
}
}
Just to add on to what @Zaph says in the comments.
I have the same problem as you, as to know, the array of String
is not saved. Even though Apple bridges types such as String and NSString, I wasn't able to save an array of [String]
neither of [AnyObject]
.
However an array of [NSString]
works for me.
So your code could look like that :
var key = "keySave"
var array1: [NSString] = [NSString]()
array1.append("value 1")
array1.append("value 2")
//save
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(array1, forKey: key)
defaults.synchronize()
//read
if let testArray : AnyObject? = defaults.objectForKey(key) {
var readArray : [NSString] = testArray! as [NSString]
}
Note that I created an array of NSString and not a dictionary. I didn't check if it works with a dictionary, but probably you will have to define the things as [NSString : NSString]
to have it working.
EDIT
Re-reading your question and your title, you are talking of array of array
. I think that as long as you stay with NSString
, an array of array will work. However, if you think my answer is irrelevant, just let me know in the comments and I will remove it.
After a long time fighting with this problem, I think I have found a better solution.
The combination of two functions makes it possible to escape a string to use as HTML.
One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.
Solution:
mysql_real_escape_string(htmlspecialchars($string))
Solve:
echo 'onclick="javascript_function(\'' . mysql_real_escape_string(htmlspecialchars($string))"
The answers mentioning adding @Transactional
are correct, but for simplicity you could just have your test class extends AbstractTransactionalJUnit4SpringContextTests
.
You have set #slider
as absolute
, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content
div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.
You can read about CSS positioning here
If you set both to relative
, the divs will be one after the other, as shown here:
#slider {
position:relative;
left:0;
height:400px;
border-style:solid;
border-width:5px;
}
#slider img {
width:100%;
}
#content {
position:relative;
}
#content #text {
position:relative;
width:950px;
height:215px;
color:red;
}
There are a few efficient ways to implement this. Let's start with required imports:
from pyspark.sql.functions import col, expr, when
You can use Hive IF
function inside expr:
new_column_1 = expr(
"""IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)
or when
+ otherwise
:
new_column_2 = when(
col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)
Finally you could use following trick:
from pyspark.sql.functions import coalesce, lit
new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))
With example data:
df = sc.parallelize([
("orange", "apple"), ("kiwi", None), (None, "banana"),
("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])
you can use this as follows:
(df
.withColumn("new_column_1", new_column_1)
.withColumn("new_column_2", new_column_2)
.withColumn("new_column_3", new_column_3))
and the result is:
+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple| 0| 0| 0|
| kiwi| null| 3| 3| 3|
| null|banana| 3| 3| 3|
| mango| mango| 1| 1| 1|
| null| null| 3| 3| 3|
+------+------+------------+------------+------------+
Adding to Gisheri's answer
Following code worked for me
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON
]
},
markerOptions: {
icon: 'images/beachflag.png'
},
circleOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
//console.log(polygon.overlay.latLngs.j[0].j);return false;
$.each(polygon.overlay.latLngs.j[0].j, function(key, LatLongsObject){
var LatLongs = LatLongsObject;
var lat = LatLongs.k;
var lon = LatLongs.B;
console.log("Lat is: "+lat+" Long is: "+lon); //do something with the coordinates
});
I faced this issue, and that is when a Bean (@Bean) was not instantiated properly as it was not given the correct parameters in my test class.
#/bin/bash
# $1 is the file name
# usage: this_script <filename>
IP_address="xx.xxx.xx.xx"
username="username"
domain=my.ftp.domain
password=password
echo "
verbose
open $IP_address
USER $username $password
put $1
bye
" | ftp -n > ftp_$$.log
I would use bash's [[
:
if [[ ! ("$#" == 1 && $1 =~ ^[0-9]+$ && -d $1) ]]; then
echo 'Please pass a number that corresponds to a directory'
exit 1
fi
I found this faq to be a good source of information.
In Tensorflow V2, Print value of tensor using: tf.keras.backend.print_tensor(x, message='')
# will get you the current local (session based) state.
SHOW Variables WHERE Variable_name='foreign_key_checks';
If you didn't SET GLOBAL, only your session was affected.
You only can have one unique ID per page. Change those IDs to classes, and change the jQuery selectors as well.
Also, move the .on() outside of the .click() function, as you only need to set it once.
http://jsfiddle.net/samliew/3AJcj/2/
$(document).ready(function(){
$(".addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
You can do that using FileInfo
class:
FileInfo fi = new FileInfo("path");
var created = fi.CreationTime;
var lastmodified = fi.LastWriteTime;
For some fun with linq and string interpolation:
public string ByteArrayToString(byte[] bytes)
{
if ( bytes == null ) return "null";
string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
return $"new byte[] {{ {joinedBytes} }}";
}
Test cases:
byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();
Output:
new byte[] { 1, 2, 3, 4 }
null
new byte[] { }
If you can't affect your parents elements (like in a nested components situation) you can use height: 100vh
which will make it a full window (=view) height;
Taken from
span() returns both start and end indexes in a single tuple. Since the match method only checks if the RE matches at the start of a string, start() will always be zero. However, the search method of RegexObject instances scans through the string, so the match may not start at zero in that case.
>>> p = re.compile('[a-z]+')
>>> print p.match('::: message')
None
>>> m = p.search('::: message') ; print m
<re.MatchObject instance at 80c9650>
>>> m.group()
'message'
>>> m.span()
(4, 11)
Combine that with:
In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator.
>>> p = re.compile( ... )
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable-iterator object at 0x401833ac>
>>> for match in iterator:
... print match.span()
...
(0, 2)
(22, 24)
(29, 31)
you should be able to do something on the order of
for match in re.finditer(r'[a-z]', 'a1b2c3d4'):
print match.span()
In case if you are using WPF application using PRISM framework then configuration should exist in your start up project (i.e. in the project where your bootstrapper resides.)
Try this:
@Html.DropDownList(
"country",
new[] {
new SelectListItem() { Value = "IN", Text = "India" },
new SelectListItem() { Value = "US", Text = "United States" }
},
"Country",
new { @class = "form-control",@selected = Model.Country}
)
First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter
to your simple format and convert it back to a String.
Swift 3
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")
The printed result is: Dateobj: 10-22-2015
When require is given the path of a folder, it'll look for an index.js file in that folder; if there is one, it uses that, and if there isn't, it fails.
It would probably make most sense (if you have control over the folder) to create an index.js file and then assign all the "modules" and then simply require that.
yourfile.js
var routes = require("./routes");
index.js
exports.something = require("./routes/something.js");
exports.others = require("./routes/others.js");
If you don't know the filenames you should write some kind of loader.
Working example of a loader:
var normalizedPath = require("path").join(__dirname, "routes");
require("fs").readdirSync(normalizedPath).forEach(function(file) {
require("./routes/" + file);
});
// Continue application logic here
You can use Hyperlink instead of Button, like this:
<TextBlock>
<Hyperlink TextDecorations="{x:Null}">
<Image Width="16"
Height="16"
Margin="3"
Source="/YourProjectName;component/Images/close-small.png" />
</Hyperlink>
</TextBlock>
You are getting the error because you might not have run the command npm install
first.
i.e.
First, run npm install
and then npm run dev
I make this method and work fine. (tested in android 6.0.1)
public void notifyThis(String title, String message) {
NotificationCompat.Builder b = new NotificationCompat.Builder(this.context);
b.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.favicon32)
.setTicker("{your tiny message}")
.setContentTitle(title)
.setContentText(message)
.setContentInfo("INFO");
NotificationManager nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, b.build());
}
It's all about the key bindings which one can simply achieve from .vimrc configurations.
As far as clipboard is concerned you can use :set clipboard unnamed
and the yank from vim will go to system clipboard.
Anyways, whichever one you end up using I suggest using this vimrc config
, it contains a whole lot of plugins and bindings which will make your experience smooth.
The Basics:
String
is an immutable class, it can't be changed.
StringBuilder
is a mutable class that can be appended to, characters replaced or removed and ultimately converted to a String
StringBuffer
is the original synchronized version of StringBuilder
You should prefer StringBuilder
in all cases where you have only a single thread accessing your object.
The Details:
Also note that StringBuilder/Buffers
aren't magic, they just use an Array as a backing object and that Array has to be re-allocated when ever it gets full. Be sure and create your StringBuilder/Buffer
objects large enough originally where they don't have to be constantly re-sized every time .append()
gets called.
The re-sizing can get very degenerate. It basically re-sizes the backing Array to 2 times its current size every time it needs to be expanded. This can result in large amounts of RAM getting allocated and not used when StringBuilder/Buffer
classes start to grow large.
In Java String x = "A" + "B";
uses a StringBuilder
behind the scenes. So for simple cases there is no benefit of declaring your own. But if you are building String
objects that are large, say less than 4k, then declaring StringBuilder sb = StringBuilder(4096);
is much more efficient than concatenation or using the default constructor which is only 16 characters. If your String
is going to be less than 10k then initialize it with the constructor to 10k to be safe. But if it is initialize to 10k then you write 1 character more than 10k, it will get re-allocated and copied to a 20k array. So initializing high is better than to low.
In the auto re-size case, at the 17th character the backing Array gets re-allocated and copied to 32 characters, at the 33th character this happens again and you get to re-allocated and copy the Array into 64 characters. You can see how this degenerates to lots of re-allocations and copies which is what you really are trying to avoid using StringBuilder/Buffer
in the first place.
This is from the JDK 6 Source code for AbstractStringBuilder
void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}
A best practice is to initialize the StringBuilder/Buffer
a little bit larger than you think you are going to need if you don't know right off hand how big the String
will be but you can guess. One allocation of slightly more memory than you need is going to be better than lots of re-allocations and copies.
Also beware of initializing a StringBuilder/Buffer
with a String
as that will only allocated the size of the String + 16 characters, which in most cases will just start the degenerate re-allocation and copy cycle that you are trying to avoid. The following is straight from the Java 6 source code.
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
If you by chance do end up with an instance of StringBuilder/Buffer
that you didn't create and can't control the constructor that is called, there is a way to avoid the degenerate re-allocate and copy behavior. Call .ensureCapacity()
with the size you want to ensure your resulting String
will fit into.
The Alternatives:
Just as a note, if you are doing really heavy String
building and manipulation, there is a much more performance oriented alternative called Ropes.
Another alternative, is to create a StringList
implemenation by sub-classing ArrayList<String>
, and adding counters to track the number of characters on every .append()
and other mutation operations of the list, then override .toString()
to create a StringBuilder
of the exact size you need and loop through the list and build the output, you can even make that StringBuilder
an instance variable and 'cache' the results of .toString()
and only have to re-generate it when something changes.
Also don't forget about String.format()
when building fixed formatted output, which can be optimized by the compiler as they make it better.
it should look like this:
void cstringcpy(char *src, char * dest)
{
while (*src) {
*(dest++) = *(src++);
}
*dest = '\0';
}
.....
char src[6] = "Hello";
char dest[6];
cstringcpy(src, dest);
I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page.
function insertUrlParam(key, value) {
if (history.pushState) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
window.history.pushState({path: newurl}, '', newurl);
}
}
This is a simple example for adding the background image in a JFrame:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
{
JButton b1;
JLabel l1;
public BackgroundImageJFrame()
{
setTitle("Background Color for JFrame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
One way
-----------------
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
*/
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
add(l1);
add(b1);
// Just for refresh :) Not optional!
setSize(399,399);
setSize(400,400);
}
public static void main(String args[])
{
new BackgroundImageJFrame();
}
}
try this: (you missed the single quotes)
var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';
The answer I was looking for is at https://unix.stackexchange.com/a/9557/114862.
Using the
-c
flag when the local file is of greater or equal size to the server version will avoid re-downloading.
/**
* Save and get ArrayList in SharedPreference
*/
JAVA:
public void saveArrayList(ArrayList<String> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
Kotlin
fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
val editor: Editor = prefs.edit()
val gson = Gson()
val json: String = gson.toJson(list)
editor.putString(key, json)
editor.apply()
}
fun getArrayList(key: String?): java.util.ArrayList<String?>? {
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
val gson = Gson()
val json: String = prefs.getString(key, null)
val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()
return gson.fromJson(json, type)
}
I tried @NorthCat answer using pdfkit.
It required wkhtmltopdf to be installed. The install can be downloaded from here. https://wkhtmltopdf.org/downloads.html
Install the executable file. Then write a line to indicate where wkhtmltopdf is, like below. (referenced from Can't create pdf using python PDFKIT Error : " No wkhtmltopdf executable found:"
import pdfkit
path_wkthmltopdf = "C:\\Folder\\where\\wkhtmltopdf.exe"
config = pdfkit.configuration(wkhtmltopdf = path_wkthmltopdf)
pdfkit.from_url("http://google.com", "out.pdf", configuration=config)
I use npm-check
to achieve this.
npm i -g npm npm-check
npm-check -ug #to update globals
npm-check -u #to update locals
Another useful command list which will keep exact version numbers in package.json
npm cache clean
rm -rf node_modules/
npm i -g npm npm-check-updates
ncu -g #update globals
ncu -ua #update locals
npm i
Your meta tag should look like this:
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
And it has to be placed on the page you want to share (this is unclear in your question).
If you have shared the page before the image (or the meta tag) was present, then it is possible, that facebook has the page in its "memory" without an image. In this case simply enter the URL of your page in the debug tool http://developers.facebook.com/tools/debug. After that, the image should be present when the page is shared the next time.
This worked for me -
from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime('2011-08-15 12:00:00', '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime('2012-02-15', '%Y-%m-%d')
r = relativedelta.relativedelta(date2, date1)
r.months + (12*r.years)
I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:
if ($_POST['action'] == 'addRunner')
I used the :not() on the selection to stop it from clearing the hidden field.
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You probably want to use an ExpandableListView, a special ListView that allows you to open and close groups.
$(.surrounding_div_class).on( 'click', '.test', function () {
alert( 'WORKS!' );
});
Will only work if the DIV with the class .surrounding_div_class is the immediate parent to the object .test
If there is another object in the div that will be filled it wont work.
<?php
phpinfo();
?>
Look under Configuration in the apache2handler in the Loaded Modules row.
This is simple and works.
<?php foreach( apache_get_modules() as $module ) echo "$module<br />"; ?>
This code has been tested and works on Android 4.4
Spinner spinner = (Spinner) activity.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_spinner_dropdown_item) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
if (position == getCount()) {
((TextView)v.findViewById(android.R.id.text1)).setText("");
((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
}
return v;
}
@Override
public int getCount() {
return super.getCount()-1; // you dont display last item. It is used as hint.
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Daily");
adapter.add("Two Days");
adapter.add("Weekly");
adapter.add("Monthly");
adapter.add("Three Months");
adapter.add("HINT_TEXT_HERE"); //This is the text that will be displayed as hint.
spinner.setAdapter(adapter);
spinner.setSelection(adapter.getCount()); //set the hint the default selection so it appears on launch.
spinner.setOnItemSelectedListener(this);
Look before you leap (LBYL):
if idx < len(array):
array[idx]
else:
# handle this
Easier to ask forgiveness than permission (EAFP):
try:
array[idx]
except IndexError:
# handle this
In Python, EAFP seems to be the popular and preferred style. It is generally more reliable, and avoids an entire class of bugs (time of check vs. time of use). All other things being equal, the try
/except
version is recommended - don't see it as a "last resort".
This excerpt is from the official docs linked above, endorsing using try/except for flow control:
This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.
Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName
. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
if (foo = bar)
by accident.Therefore I prefer
if (foo == NULL)
{
// null case
}
else
{
// non null case
}
or
if (foo != NULL)
{
// non null case
}
else
{
// null case
}
However, if I were writing a set of style guidelines I would not be putting things like this in it, I would be putting things like:
Make sure you do a null check on the pointer.
I usually use this workaround:
try:
from .mymodule import myclass
except Exception: #ImportError
from mymodule import myclass
Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.
I'm surprised nobody has mentioned it before, but FindBin::libs will always find your libs as it searches in all reasonable places relative to the location of your script.
#!/usr/bin/perl
use FindBin::libs;
use <your lib>;
jars used to be in the lib/ folder, now they're in libs/ If you use lib, you can move your jars from lib to libs, and remove the dependencies from project properties/java build path because Android will now find them automatically.
The reason of why your code throws an UnboundLocalError
is already well explained in other answers.
But it seems to me that you're trying to build something that works like itertools.count()
.
So why don't you try it out, and see if it suits your case:
>>> from itertools import count
>>> counter = count(0)
>>> counter
count(0)
>>> next(counter)
0
>>> counter
count(1)
>>> next(counter)
1
>>> counter
count(2)
This is just a possible scenario which happened to me. Well if it helps someone then great: I wrote a complicated app which somewhere along the code I used a function to clear all textboxes values before showing them. Sometime later I tried to set a textbox value using jquery val('value') but I did'nt notice that right after that I invoked the ClearAllInputs method.. so, this could also happen.
Compilr is an online java compiler. It provides syntax highlighting and reports any errors back to you. It's a project I'm working on, so if you have any feedback please leave a comment!
For those of you struggling with getting this done trying every possible answer you can find on SO. Here's what worked for me on a VPS running Windows 2012 R2 :
Place your sql file wherever the bin is for me it is located at C:\Program Files\MySQL\MySQL Server 8.0\bin
Open windows command prompt (cmd)
C:\Program Files\MySQL\MySQL Server 8.0\bin > mysql -u [username] -p
use [database_name]
;C://Program Files//MySQL//MySQL Server 8.0//bin//mydatabasename.sql
It did it for me as everything else had failed. It might help you too.
This worked for me:
let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
...
The key was adding in the URLSessionDataTask
type declaration.
I find jackson fasterxml
is one good choice to serializing/deserializing
bean with XML.
The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html
Similar to solution of mark
with some checking of variables. Also I prefer not to use $variable
but rather the same string I saved it under
save your folder/directory using save dir sdir myproject
and go back to that folder using goto dir gdir myproject
in addition checkout the workings of native pushd and popd
they will save the current folder and this is handy for going back and forth. In this case you can also use popd
after gdir myproject
and go back again
# Save the current folder using sdir yourhandle to a variable you can later access the same folder fast using gdir yourhandle
function sdir {
[[ ! -z "$1" ]] && export __d__$1="`pwd`";
}
function gdir {
[[ ! -z "$1" ]] && cd "${!1}";
}
another handy trick is to combine the two pushd/popd and sdir and gdir wher you replace the cd in the goto dir function in pushd. This enables you to also fly back to your previous folder when making the jump to the saved folder.
# Save the current folder using sdir yourhandle to a variable you can later access the same folder fast using gdir yourhandle
function sdir {
[[ ! -z "$1" ]] && export __d__$1="`pwd`";
}
function gdir {
[[ ! -z "$1" ]] && pushd "${!1}";
}
This is a pretty common proof. One way to prove this is to use mathematical induction. Here is a link: http://zimmer.csufresno.edu/~larryc/proofs/proofs.mathinduction.html
I had a lot of trouble to fix this, there are two things to do :
update file /etc/mysql/my.cnf
with local-infile =1
at two locations after [mysql]
paragraphs (this allows to use LOCAL INFILE sql command).
update via sudo gedit /etc/apparmor.d/usr.sbin.mysqld
so apparmor will allow you to write into the special files of /var/www/
by adding the lines:
/name of your directory/ r,
/name of your directory/* rw,
The name of your directory can be as /var/www/toto/
(this allows to use the directory where your files are located).
Since value is the last entry, you can do:
metrics.sort_by(&:last)
All of the above are correct, but try this straight one-liner:
{{session()->has('message') ? session()->get('message') : ''}}
gcc
and g++
are compiler-drivers of the GNU Compiler Collection (which was once upon a time just the GNU C Compiler).
Even though they automatically determine which backends (cc1
cc1plus
...) to call depending on the file-type, unless overridden with -x language
, they have some differences.
The probably most important difference in their defaults is which libraries they link against automatically.
According to GCC's online documentation link options and how g++ is invoked, g++
is equivalent to gcc -xc++ -lstdc++ -shared-libgcc
(the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the -v
option (it displays the backend toolchain commands being run).
Google has ended support for eclipse plugin. If you prefer to use eclipse still you can download Eclipse Android Development Tool from
To filter for specific file extensions:
wget -A pdf,jpg -m -p -E -k -K -np http://site/path/
Or, if you prefer long option names:
wget --accept pdf,jpg --mirror --page-requisites --adjust-extension --convert-links --backup-converted --no-parent http://site/path/
This will mirror the site, but the files without jpg
or pdf
extension will be automatically removed.
I have done the json parser in simplest way, here it is
package com.inzane.shoapp.activity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
System.out.println(line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
System.out.println("error on parse data in jsonparser.java");
}
// return JSON String
return jObj;
}
}
this class returns the json object from the url
and when you want the json object you just call this class and the method in your Activity class
my code is here
String url = "your url";
JSONParser jsonParser = new JSONParser();
JSONObject object = jsonParser.getJSONFromUrl(url);
String content=object.getString("json key");
here the "json key" is denoted that the key in your json file
this is a simple json file example
{
"json":"hi"
}
Here "json" is key and "hi" is value
This will get your json value to string content.
Based on LukeP's answer, and add some methods to setup timeout
and requireSSL
cooperated with Web.config
.
1, Set timeout
based on Web.Config
. The FormsAuthentication.Timeout will get the timeout value, which is defined in web.config. I wrapped the followings to be a function, which return a ticket
back.
int version = 1;
DateTime now = DateTime.Now;
// respect to the `timeout` in Web.config.
TimeSpan timeout = FormsAuthentication.Timeout;
DateTime expire = now.Add(timeout);
bool isPersist = false;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
version,
name,
now,
expire,
isPersist,
userData);
2, Configure the cookie to be secure or not, based on the RequireSSL
configuration.
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
// respect to `RequreSSL` in `Web.Config`
bool bSSL = FormsAuthentication.RequireSSL;
faCookie.Secure = bSSL;
SQL Server 2012 and up support LAG / LEAD functions to access the previous or subsequent row. SQL Server 2005 does not support this (in SQL2005 you need a join or something else).
A SQL 2012 example on this data
/* Prepare */
select * into #tmp
from
(
select 2 as rowint, 23 as Value
union select 3, 45
union select 17, 10
union select 9, 0
) x
/* The SQL 2012 query */
select rowInt, Value, LEAD(value) over (order by rowInt) - Value
from #tmp
LEAD(value) will return the value of the next row in respect to the given order in "over" clause.
import sys
try:
print("stuff")
except:
sys.exit(1) # exiing with a non zero value is better for returning from an error
The Spring reference manual explains how circular dependencies are resolved. The beans are instantiated first, then injected into each other.
Consider this class:
package mypackage;
public class A {
public A() {
System.out.println("Creating instance of A");
}
private B b;
public void setB(B b) {
System.out.println("Setting property b of A instance");
this.b = b;
}
}
And a similar class B
:
package mypackage;
public class B {
public B() {
System.out.println("Creating instance of B");
}
private A a;
public void setA(A a) {
System.out.println("Setting property a of B instance");
this.a = a;
}
}
If you then had this configuration file:
<bean id="a" class="mypackage.A">
<property name="b" ref="b" />
</bean>
<bean id="b" class="mypackage.B">
<property name="a" ref="a" />
</bean>
You would see the following output when creating a context using this configuration:
Creating instance of A
Creating instance of B
Setting property a of B instance
Setting property b of A instance
Note that when a
is injected into b
, a
is not yet fully initialised.
An alternative way to do this could be select distinct PersonId
and group join with persons
:
var result =
from id in persons.Select(x => x.PersonId).Distinct()
join p2 in persons on id equals p2.PersonId into gr // apply group join here
select new
{
PersonId = id,
Cars = gr.Select(x => x.Car).ToList(),
};
Or the same with fluent API syntax:
var result = persons.Select(x => x.PersonId).Distinct()
.GroupJoin(persons, id => id, p => p.PersonId, (id, gr) => new
{
PersonId = id,
Cars = gr.Select(x => x.Car).ToList(),
});
GroupJoin produces a list of entries in the first list ( list of PersonId
in our case), each with a group of joined entries in the second list (list of persons
).
Extract the package to C:\ from here and install it
Copy the path C:\MinGW\bin
which contains gcc.exe.
go to Control Panel->System->Advanced>Environment variables
, and add or modify PATH. (just concatenate with ';')
Then, open a cmd.exe command prompt
(Windows + R and type cmd, if already opened, please close and open a new one, to get the path change)
change the folder to your file path by cd D:\c code Path
type gcc main.c -o helloworld.o
. It will compile the code. for C++ use g++
7 type ./helloworld
to run the program.
If zlib1.dll is missing, download from here
For MS IE 10 you'll probably find you need to do the following:
-ms-overflow-style: none
See the following:
https://msdn.microsoft.com/en-us/library/hh771902(v=vs.85).aspx
You should create a ModelForm
(docs), which has a field that uses the PasswordInput
widget from the forms library.
It would look like this:
from django import models
class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
from django import forms
class UserForm(forms.ModelForm):
class Meta:
model = User
widgets = {
'password': forms.PasswordInput(),
}
For more about using forms in a view, see this section of the docs.
I documented the perfect detailed solution here - https://amprandom.blogspot.com/2016/12/blogger-whatsapp-rich-link-preview.html There are seven steps to be done to get the perfect preview.
Title : Add Keyword rich title to your webpage with maximum of 65 characters.
Meta Description : Describe your web page in a maximum of 155 characters.
og:title : Maximum 35 characters.
og:url : Full link to your webpage address.
og:description : Maximum 65 characters.
og:image : Image(JPG or PNG) of size less than 300KB and minimum dimension of 300 x 200 pixel is advised.
favicon : A small icon of dimensions 32 x 32 pixels.
In the above page, you have the required specifications, the character limit and sample tags. Do upvote once you find it satisfactory.
You could try using json-lib's JSONAssert class:
JSONAssert.assertEquals(
"{foo: 'bar', baz: 'qux'}",
JSONObject.fromObject("{foo: 'bar', baz: 'xyzzy'}")
);
Gives:
junit.framework.ComparisonFailure: objects differed at key [baz]; expected:<[qux]> but was:<[xyzzy]>
For version 9.5 I use, it would be like this:
COPY products_273 TO '/tmp/products_199.csv' WITH (FORMAT CSV, HEADER);
Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.
var width = 960,_x000D_
height = 500,_x000D_
json = {_x000D_
"nodes": [{_x000D_
"x": 100,_x000D_
"r": 20,_x000D_
"label": "Node 1",_x000D_
"color": "red"_x000D_
}, {_x000D_
"x": 200,_x000D_
"r": 25,_x000D_
"label": "Node 2",_x000D_
"color": "blue"_x000D_
}, {_x000D_
"x": 300,_x000D_
"r": 30,_x000D_
"label": "Node 3",_x000D_
"color": "green"_x000D_
}]_x000D_
};_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
.attr("width", width)_x000D_
.attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
.append("pattern")_x000D_
.attr({_x000D_
"id": "stripes",_x000D_
"width": "8",_x000D_
"height": "8",_x000D_
"fill": "red",_x000D_
"patternUnits": "userSpaceOnUse",_x000D_
"patternTransform": "rotate(60)"_x000D_
})_x000D_
.append("rect")_x000D_
.attr({_x000D_
"width": "4",_x000D_
"height": "8",_x000D_
"transform": "translate(0,0)",_x000D_
"fill": "grey"_x000D_
});_x000D_
_x000D_
function plotChart(json) {_x000D_
/* Define the data for the circles */_x000D_
var elem = svg.selectAll("g myCircleText")_x000D_
.data(json.nodes)_x000D_
_x000D_
/*Create and place the "blocks" containing the circle and the text */_x000D_
var elemEnter = elem.enter()_x000D_
.append("g")_x000D_
.attr("class", "node-group")_x000D_
.attr("transform", function(d) {_x000D_
return "translate(" + d.x + ",80)"_x000D_
})_x000D_
_x000D_
/*Create the circle for each block */_x000D_
var circleInner = elemEnter.append("circle")_x000D_
.attr("r", function(d) {_x000D_
return d.r_x000D_
})_x000D_
.attr("stroke", function(d) {_x000D_
return d.color;_x000D_
})_x000D_
.attr("fill", function(d) {_x000D_
return d.color;_x000D_
});_x000D_
_x000D_
var circleOuter = elemEnter.append("circle")_x000D_
.attr("r", function(d) {_x000D_
return d.r_x000D_
})_x000D_
.attr("stroke", function(d) {_x000D_
return d.color;_x000D_
})_x000D_
.attr("fill", "url(#stripes)");_x000D_
_x000D_
/* Create the text for each block */_x000D_
elemEnter.append("text")_x000D_
.text(function(d) {_x000D_
return d.label_x000D_
})_x000D_
.attr({_x000D_
"text-anchor": "middle",_x000D_
"font-size": function(d) {_x000D_
return d.r / ((d.r * 10) / 100);_x000D_
},_x000D_
"dy": function(d) {_x000D_
return d.r / ((d.r * 25) / 100);_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
Output:
Below is the link to codepen
also:
Thanks, Manish Kumar
Same problem but @Angelo answer didn't work for me, because I'm using same server with different credentials. I used the approach below and tested it on Windows 10.
cmdkey /add:server01 /user:<username> /pass:<password>
Then used mstsc /v:server01
to connect to the server.
The point is to use names instead of ip addresses to avoid conflict between credentials. If you don't have a DNS server locally accessible try c:\windows\system32\drivers\etc\hosts
file.
Use jquery validator in your script tag DEMO
<script src="js/jquery.validate.min.js"></script>
and validate your element by like this
<form name="enquiry_form" method="post" id="enquiry_form">
Full Name *
<input class="input-style" name="name" id="name" type="text"/>
<br>
Email *
<input class="input-style" name="email" id="email" type="email"><br>
Phone *
<input id="mobile" name="mobile" id="mobile"></input><br>
<input type="submit" value="SUBMIT" id="enq_submit">
</form>
$('#enquiry_form').validate({
rules:{
name:"required",
email:{
required:true,
email:true
},
mobile:{
required:true,
minlength:9,
maxlength:10,
}
},
messages:{
name:"Please enter your username..!",
email:"Please enter your email..!",
mobile:"Enter your mobile no"
},
submitHandler: function(form) {
alert("working");
//write your success code here
}
});
There is no conversion between InputStream/OutputStream and the bytes they are working with. They are made for binary data, and just read (or write) the bytes one by one as is.
A conversion needs to happen when you want to go from byte to char. Then you need to convert using a character set. This happens when you make String or Reader from bytes, which are made for character data.
This is because Keypress
event is fired before the new character is added. Use 'keyup' event instead,which will work perfectly in your situation.
$(document).ready(function() {
$("#dSuggest").keyup(function() {
var dInput = $('input:text[name=dSuggest]').val();
console.log(dInput);
$(".dDimension:contains('" + dInput + "')").css("display","block");
});
});
I want to add to this, if you have many textboxes and you have to do the same thing on their keyup event you can simply give them a common css class(eg commoncss) and apply keyup event like this.
$(document).ready(function() {
$(".commoncss").keyup(function() {
//your code
});
});
this will greatly reduce you code as you don't have to apply keyup event by id for each textboxes.
Can't you just set left
to 50%
and then have margin-left
set to -25px
to account for it's width: http://jsfiddle.net/9AbYc/
.hero:after {
content:'';
position: absolute;
top: 100%;
left: 50%;
margin-left: -50px;
width: 0;
height: 0;
border-top: solid 50px #e15915;
border-left: solid 50px transparent;
border-right: solid 50px transparent;
}
or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/
.hero:after {
content:'';
position: absolute;
top: 100%;
left: 0;
right: 0;
margin: 0 auto;
width: 0;
height: 0;
border-top: solid 50px #e15915;
border-left: solid 50px transparent;
border-right: solid 50px transparent;
}
Use tr:first-child
to take the first tr
:
.category_table tr:first-child td {
vertical-align: top;
}
If you have nested tables, and you don't want to apply styles to the inner rows, add some child selectors so only the top-level td
s in the first top-level tr
get the styles:
.category_table > tbody > tr:first-child > td {
vertical-align: top;
}
To be more semantically correct and answer the OPs orginal question about aligning them side by side I would use this:
HTML
<div class="items">
<figure>
<img src="hello.png" width="100px" height="100px">
<figcaption>Caption 1</figcaption>
</figure>
<figure>
<img src="hi.png" width="100px" height="100px">
<figcaption>Caption 2</figcaption>
</figure></div>
CSS
.items{
text-align:center;
margin:50px auto;}
.items figure{
margin:0px 20px;
display:inline-block;
text-decoration:none;
color:black;}
The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or @Override in sub class (as public), then Mockito can mock it correctly.
public class BaseService{
public boolean foo(){
return true;
}
}
public ChildService extends BaseService{
}
@Test
@Mock ChildService childService;
public void testSave() {
Mockito.when(childService.foo()).thenReturn(false);
// When
assertFalse(childService.foo());
}
Groovy maps can be used with the property
property, so you can just do:
def x = mymap.likes
If the key you are looking for (for example 'likes.key'
) contains a dot itself, then you can use the syntax:
def x = mymap.'likes.key'
Go to "Run" and execute this:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
NOTE: run as administrator.
The problem is somewhere else in your code, because this works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (size_t i = 0; i < strs.size(); i++)
cout << strs[i] << endl;
and testing your approach, which uses a vector iterator also works:
string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));
cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
cout << *it << endl;
}
Again, your problem is somewhere else. Maybe what you think is a \t
character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.
Output:
* size of the vector: 3
test
test2
test3
I think this question needs an updated answer, because both PostgreSQL and SQLDeveloper have been updated several times since it was originally asked.
I've got a PostgreSQL instance running in Azure, with SSLMODE=Require. While I've been using DBeaverCE to access that instance and generate an ER Diagram, I've gotten really familiar with SQLDeveloper, which is now at v19.4.
The instructions about downloading the latest PostgreSQL JDBC driver and where to place it are correct. What has changed, though, is where to configure your DB access.
You'll find a file $HOME/.sqldeveloper/system19.4.0.354.1759/o.jdeveloper.db.connection.19.3.0.354.1759/connections.json
:
{
"connections": [
{
"name": "connection-name-goes-here",
"type": "jdbc",
"info": {
"customUrl": "jdbc:postgresql://your-postgresql-host:5432/DBNAME?sslmode=require",
"hostname": "your-postgresql-host",
"driver": "org.postgresql.Driver",
"subtype": "SDPostgreSQL",
"port": "5432",
"SavePassword": "false",
"RaptorConnectionType": "SDPostgreSQL",
"user": "your_admin_user",
"sslmode": "require"
}
}
]
}
You can use this connection with both Data Modeller and the admin functionality of SQLDeveloper. Specifying all the port, dbname and sslmode in the customUrl are required because SQLDeveloper isn't including the sslmode in what it sends via JDBC, so you have to construct it by hand.
Have a look at config.sample.inc.php: you will find examples of the configuration directives that you should copy to your config.inc.php (copy the missing ones). Then, have a look at examples/create_tables.sql which will help you create the missing tables.
The complete documentation for this is available at http://docs.phpmyadmin.net/en/latest/setup.html#phpmyadmin-configuration-storage.
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
You can change background of a page by simply using:
function changeBodyBg(color){
document.body.style.background = color;
}
Read more @ Changing the Background Color
There are three issues here that need to be fixed:
First is that you are expecting synchronous behavior while using stdout asynchronously. All of the calls in your run_cmd
function are asynchronous, so it will spawn the child process and return immediately regardless of whether some, all, or none of the data has been read off of stdout. As such, when you run
console.log(foo.stdout);
you get whatever happens to be stored in foo.stdout at the moment, and there's no guarantee what that will be because your child process might still be running.
Second is that stdout is a readable stream, so 1) the data event can be called multiple times, and 2) the callback is given a buffer, not a string. Easy to remedy; just change
foo = new run_cmd(
'netstat.exe', ['-an'], function (me, data){me.stdout=data;}
);
into
foo = new run_cmd(
'netstat.exe', ['-an'], function (me, buffer){me.stdout+=buffer.toString();}
);
so that we convert our buffer into a string and append that string to our stdout variable.
Third is that you can only know you've received all output when you get the 'end' event, which means we need another listener and callback:
function run_cmd(cmd, args, cb, end) {
// ...
child.stdout.on('end', end);
}
So, your final result is this:
function run_cmd(cmd, args, cb, end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
child.stdout.on('data', function (buffer) { cb(me, buffer) });
child.stdout.on('end', end);
}
// Run C:\Windows\System32\netstat.exe -an
var foo = new run_cmd(
'netstat.exe', ['-an'],
function (me, buffer) { me.stdout += buffer.toString() },
function () { console.log(foo.stdout) }
);
In core_test.py, do the following:
import sys
sys.path.append('../components')
from core import GameLoopEvents
I assume that you are looking to do something interactive when the textbox changes (i.e. retrieve some data via ajax). I was looking for this same functionality. I know using a global isn't the most robust or elegant solution, but that is what I went with. Here is an example:
var searchValue = $('#Search').val();
$(function () {
setTimeout(checkSearchChanged, 0.1);
});
function checkSearchChanged() {
var currentValue = $('#Search').val();
if ((currentValue) && currentValue != searchValue && currentValue != '') {
searchValue = $('#Search').val();
$('#submit').click();
}
else {
setTimeout(checkSearchChanged, 0.1);
}
}
One key thing to note here is that I am using setTimeout and not setInterval since I don't want to send multiple requests at the same time. This ensures that the timer "stops" when the form is submitted and "starts" when the request is complete. I do this by calling checkSearchChanged when my ajax call completes. Obviously you could expand this to check for minimum length, etc.
In my case, I am using ASP.Net MVC so you can see how to tie this in with MVC Ajax as well in the following post:
One way you can achieve this is setting display: inline-block;
on the div
. It is by default a block
element, which will always fill the width it can fill (unless specifying width
of course).
inline-block
's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline
elements, but there are hacks to solve this problem.
There are other options you have, you can either float
it, or set position: absolute
on it, but these also have other effects on layout, you need to decide which one fits your situation better.
Since the answer for me was buried in the comments. For SQL Server 2012 and beyond, you can use the following:
BACKUP LOG Database TO DISK='NUL:'
DBCC SHRINKFILE (Database_Log, 1)
A total different approach to convert hex color code to RGB without regex
It handles both #FFF
and #FFFFFF
format on the base of length of string. It removes #
from beginning of string and divides each character of string and converts it to base10 and add it to respective index on the base of it's position.
//Algorithm of hex to rgb conversion in ES5_x000D_
function hex2rgbSimple(str){_x000D_
str = str.replace('#', '');_x000D_
return str.split('').reduce(function(result, char, index, array){_x000D_
var j = parseInt(index * 3/array.length);_x000D_
var number = parseInt(char, 16);_x000D_
result[j] = (array.length == 3? number : result[j]) * 16 + number;_x000D_
return result;_x000D_
},[0,0,0]);_x000D_
}_x000D_
_x000D_
//Same code in ES6_x000D_
hex2rgb = str => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]);_x000D_
_x000D_
//hex to RGBA conversion_x000D_
hex2rgba = (str, a) => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0,a||1]);_x000D_
_x000D_
//hex to standard RGB conversion_x000D_
hex2rgbStandard = str => `RGB(${str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]).join(',')})`;_x000D_
_x000D_
_x000D_
console.log(hex2rgb('#aebece'));_x000D_
console.log(hex2rgbSimple('#aebece'));_x000D_
_x000D_
console.log(hex2rgb('#aabbcc'));_x000D_
_x000D_
console.log(hex2rgb('#abc'));_x000D_
_x000D_
console.log(hex2rgba('#abc', 0.7));_x000D_
_x000D_
console.log(hex2rgbStandard('#abc'));
_x000D_
php artisan dump-autoload
was deprecated on Laravel 5, so you need to use composer dump-autoload
Go to Behavior > Site Content > All Pages and put your URI into the search box.
To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 tr
from rule one and add it to rule two.
table.rule1 tr td {
background-color: #ff0000;
}
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.
You can use the IGNORE
keyword too, example:
update IGNORE table set primary_field = 'value'...............
Have you tried simply selecting by Id?
$("#header").focus();
Seeing as Ids should be unique, there's no need to have a more specific selector.
If you're sick of messing with java you can just send it to db2 as part of your query:
select date1, date2, days(date1) - days(date2) from table
will return date1, date2 and the difference in days between the two.
I just ran into this problem while trying to use pprint to output a list of tuples of floats. Nested comprehensions might be a bad idea, but here's what I did:
tups = [
(12.0, 9.75, 23.54),
(12.5, 2.6, 13.85),
(14.77, 3.56, 23.23),
(12.0, 5.5, 23.5)
]
pprint([['{0:0.02f}'.format(num) for num in tup] for tup in tups])
I used generator expressions at first, but pprint just repred the generator...
Continued discussion & other solutions covered at How to sort an (associative) array by value? with the best solution (for my case) being by saml (quoted below).
Arrays can only have numeric indexes. You'd need to rewrite this as either an Object, or an Array of Objects.
var status = new Array();
status.push({name: 'BOB', val: 10});
status.push({name: 'TOM', val: 3});
status.push({name: 'ROB', val: 22});
status.push({name: 'JON', val: 7});
If you like the status.push
method, you can sort it with:
status.sort(function(a,b) {
return a.val - b.val;
});
If anyone came here from python-graphql client looking for a solution to pass an object as variable here's what I used:
query = """
{{
pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
id
txCount
reserveUSD
trackedReserveETH
volumeUSD
}}
}}
""".format(block=''.join(['{number: ', str(block), '}']))
query = gql(query)
Make sure to escape all curly braces like I did: "{{", "}}"
If you want to build on top of ScriptControl
, you can add a few helper method to get at the required information. The JScriptTypeInfo
object is a bit unfortunate: it contains all the relevant information (as you can see in the Watch window) but it seems impossible to get at it with VBA. However, the Javascript engine can help us:
Option Explicit
Private ScriptEngine As ScriptControl
Public Sub InitScriptEngine()
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"
ScriptEngine.AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "
ScriptEngine.AddCode "function getKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj) { keys.push(i); } return keys; } "
End Sub
Public Function DecodeJsonString(ByVal JsonString As String)
Set DecodeJsonString = ScriptEngine.Eval("(" + JsonString + ")")
End Function
Public Function GetProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Variant
GetProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function
Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
Set GetObjectProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
End Function
Public Function GetKeys(ByVal JsonObject As Object) As String()
Dim Length As Integer
Dim KeysArray() As String
Dim KeysObject As Object
Dim Index As Integer
Dim Key As Variant
Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
Length = GetProperty(KeysObject, "length")
ReDim KeysArray(Length - 1)
Index = 0
For Each Key In KeysObject
KeysArray(Index) = Key
Index = Index + 1
Next
GetKeys = KeysArray
End Function
Public Sub TestJsonAccess()
Dim JsonString As String
Dim JsonObject As Object
Dim Keys() As String
Dim Value As Variant
Dim j As Variant
InitScriptEngine
JsonString = "{""key1"": ""val1"", ""key2"": { ""key3"": ""val3"" } }"
Set JsonObject = DecodeJsonString(CStr(JsonString))
Keys = GetKeys(JsonObject)
Value = GetProperty(JsonObject, "key1")
Set Value = GetObjectProperty(JsonObject, "key2")
End Sub
A few notes:
JScriptTypeInfo
instance refers to a Javascript object, For Each ... Next
won't work. However, it does work if it refers to a Javascript array (see GetKeys
function).GetProperty
and GetObjectProperty
.length
, 0
, Item 0
, 1
, Item 1
etc. With the VBA dot notation (jsonObject.property
), only the length property is accessible and only if you declare a variable called length
with all lowercase letters. Otherwise the case doesn't match and it won't find it. The other properties are not valid in VBA. So better use the GetProperty
function.InitScriptEngine
once before using the other functions to do some basic initialization.Had the same exception when tried to compile an Angular 5 application.
Unexpected value 'undefined' imported by the module 'DemoAppModule'
In my case it turned out it was a circular dependency which I found by using a tool madge. Found the files containing circular dependency by running
npx madge --circular --extensions ts src/
NSDate.init
with timeIntervalSinceNow
:
Ex:
let dateAfterMin = NSDate.init(timeIntervalSinceNow: (minutes * 60.0))
As data type in JAVA I strongly recommend to use java.util.Date. I ran into pretty nasty timezone problems when using Calendar. See this Thread.
For setting the timestamps I would recommend using either an AOP approach or you could simply use Triggers on the table (actually this is the only thing that I ever find the use of triggers acceptable).
In case you have NA's:
sapply(data, mean, na.rm = T) # Returns a vector (with names)
lapply(data, mean, na.rm = T) # Returns a list
Remember that "mean" needs numeric data. If you have mixed class data, then use:
numdata<-data[sapply(data, is.numeric)]
sapply(numdata, mean, na.rm = T) # Returns a vector
lapply(numdata, mean, na.rm = T) # Returns a list
You could use a dict
object's get()
method, as others have already suggested. Alternatively, depending on exactly what you're doing, you might be able use a try/except
suite like this:
try:
<to do something with d[key]>
except KeyError:
<deal with it not being there>
Which is considered to be a very "Pythonic" approach to handling the case.
Probably not the case of everybody but I had the same problem. I was using the last, in my case, the error was because I was using jfrog manage from the company where I am working.
npm config list
The result was
; cli configs
metrics-registry = "https://COMPANYNAME.jfrog.io/COMPANYNAM/api/npm/npm/"
scope = ""
user-agent = "npm/6.3.0 node/v8.11.2 win32 x64"
; userconfig C:\Users\USER\.npmrc
always-auth = true
email = "XXXXXXXXX"
registry = "https://COMPANYNAME.jfrog.io/COMPANYNAME/api/npm/npm/"
; builtin config undefined
prefix = "C:\\Users\\XXXXX\\AppData\\Roaming\\npm"
; node bin location = C:\Program Files\nodejs\node.exe
; cwd = C:\WINDOWS\system32
; HOME = C:\Users\XXXXXX
; "npm config ls -l" to show all defaults.
I solve the problem by using the global metrics.
The other answers to this question seem to hit it spot on. Now how would you figure this out for yourself without stack overflow? Check out IPython, an interactive Python shell that has tab auto-complete.
> ipython
import Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
Type "copyright", "credits" or "license" for more information.
IPython 0.8.2.svn.r2750 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import datetime
In [2]: now=datetime.datetime.now()
In [3]: now.
press tab a few times and you'll be prompted with the members of the "now" object:
now.__add__ now.__gt__ now.__radd__ now.__sub__ now.fromordinal now.microsecond now.second now.toordinal now.weekday
now.__class__ now.__hash__ now.__reduce__ now.astimezone now.fromtimestamp now.min now.strftime now.tzinfo now.year
now.__delattr__ now.__init__ now.__reduce_ex__ now.combine now.hour now.minute now.strptime now.tzname
now.__doc__ now.__le__ now.__repr__ now.ctime now.isocalendar now.month now.time now.utcfromtimestamp
now.__eq__ now.__lt__ now.__rsub__ now.date now.isoformat now.now now.timetuple now.utcnow
now.__ge__ now.__ne__ now.__setattr__ now.day now.isoweekday now.replace now.timetz now.utcoffset
now.__getattribute__ now.__new__ now.__str__ now.dst now.max now.resolution now.today now.utctimetuple
and you'll see that now.year is a member of the "now" object.
@bsimmons
git fsck --lost-found | grep commit
Then create a branch for each one:
$ git fsck --lost-found | grep commit
Checking object directories: 100% (256/256), done.
dangling commit 2806a32af04d1bbd7803fb899071fcf247a2b9b0
dangling commit 6d0e49efd0c1a4b5bea1235c6286f0b64c4c8de1
dangling commit 91ca9b2482a96b20dc31d2af4818d69606a229d4
$ git branch branch_2806a3 2806a3
$ git branch branch_6d0e49 6d0e49
$ git branch branch_91ca9b 91ca9b
Now many tools will show you a graphical visualization of those lost commits.
Have a look at this Stack Overflow answer.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
You can use the method to animate:
I.e.:
var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
If you use a Datetime format see http://php.net/manual/en/datetime.format.php
You can do this :
$date = new \DateTime();
echo date_format($date, 'Y-m-d H:i:s');
#output: 2012-03-24 17:45:12
echo date_format($date, 'G:ia');
#output: 05:45pm
There are a couple of potential problems with this approach, though in a lot of circumstances (such as your example) it will work well.
In particular you should be careful when dealing with anything that deals with the GUI
that requires a Context
. For example, if you pass the application Context into the LayoutInflater
you will get an Exception. Generally speaking, your approach is excellent: it's good practice to use an Activity's
Context
within that Activity
, and the Application Context
when passing a context beyond the scope of an Activity
to avoid memory leaks.
Also, as an alternative to your pattern you can use the shortcut of calling getApplicationContext()
on a Context
object (such as an Activity) to get the Application Context.
There are plenty of libraries out there. It all depends on how complicated your data structure is (e.g. consider deeply nested keys)
We like object-fields as it also works with deeply nested hierarchies (build for api fields parameter). Here is a simple code example
// const objectFields = require('object-fields');
const array = [ { bad: 'something', good: 'something' }, { bad: 'something', good: 'something' } ];
const retain = objectFields.Retainer(['good']);
retain(array);
console.log(array);
// => [ { good: 'something' }, { good: 'something' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-fields
The less complicated answer is to use .contents()
to get at the iframe. Interestingly, though, it returns a different value from what I get using the code in my original answer, due to the padding on the body, I believe.
$('iframe').contents().height() + 'is the height'
This is how I've done it for cross-domain communication, so I'm afraid it's maybe unnecessarily complicated. First, I would put jQuery inside the iFrame's document; this will consume more memory, but it shouldn't increase load time as the script only needs to be loaded once.
Use the iFrame's jQuery to measure the height of your iframe's body as early as possible (onDOMReady) and then set the URL hash to that height. And in the parent document, add an onload
event to the iFrame tag that will look at the location of the iframe and extract the value you need. Because onDOMReady will always occur before the document's load event, you can be fairly certain the value will get communicated correctly without a race condition complicating things.
In other words:
...in Help.php:
var getDocumentHeight = function() {
if (location.hash === '') { // EDIT: this should prevent the retriggering of onDOMReady
location.hash = $('body').height();
// at this point the document address will be something like help.php#1552
}
};
$(getDocumentHeight);
...and in the parent document:
var getIFrameHeight = function() {
var iFrame = $('iframe')[0]; // this will return the DOM element
var strHash = iFrame.contentDocument.location.hash;
alert(strHash); // will return something like '#1552'
};
$('iframe').bind('load', getIFrameHeight );
@Art L. Richards 's solution didn't work out. now in bootstrap.css, original code has become like this.
.carousel .item > img {
display: block;
line-height: 1;
}
@rnaka530 's code would break the fluid feature of bootstrap.
I don't have a good solution but I did fix it. I observed the bootstrap's carousel example very carefully http://twitter.github.com/bootstrap/javascript.html#carousel.
I find out that img width has to be larger than the grid width. In span9
, width is up to 870px, so you have to prepare a image larger than 870px. If you have more container outside the img, as all the container has border or margin something, you can use image with smaller width.
This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.
This is for the following query:
data = Leaderboard.objects.filter(id=custom_user.id).values(
'value1',
'value2',
'value3')
In template:
{% for dictionary in data %}
{% for key, value in dictionary.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}
{% endfor %}
The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.
It's not only a Python bug with * actually, it can also happen when you pass a string as a part of your regular expression to be compiled, like ;
import re
input_line = "string from any input source"
processed_line= "text to be edited with {}".format(input_line)
target = "text to be searched"
re.search(processed_line, target)
this will cause an error if processed line contained some "(+)" for example, like you can find in chemical formulae, or such chains of characters. the solution is to escape but when you do it on the fly, it can happen that you fail to do it properly...
Using dialog methods:
$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');
Or directly, hacky though:
$("span.ui-dialog-title").text('My New Title');
For future reference, you can skip google with jQuery. The jQuery API will answer your questions most of the time. In this case, the Dialog API page. For the main library: http://api.jquery.com
I might be wrong on this but I think you need to implement your own com.android.volley.toolbox.HttpStack
for this because the default ones (HurlStack
if version > Gingerbread or HttpClientStack
) don't deal with multipart/form-data
.
Edit:
And indeed I was wrong. I was able to do it using MultipartEntity
in Request like this:
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "file";
private static final String STRING_PART_NAME = "text";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final String mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file, String stringPart)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
mStringPart = stringPart;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
try
{
entity.addPart(STRING_PART_NAME, new StringBody(mStringPart));
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
@Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
return Response.success("Uploaded", getCacheEntry());
}
@Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
}
It's pretty raw but I tried it with an image and a simple string and it works. The response is a placeholder, doesn't make much sense to return a Response String in this case. I had problems using apache httpmime to use MultipartEntity so I used this https://code.google.com/p/httpclientandroidlib/ don't know if there's a better way. Hope it helps.
Edit
You can use httpmime without using httpclientandroidlib, the only dependency is httpcore.
var counter = 15;
var interval = setTimeout(function(){
// your interval code here
window.counter = dynamicValue;
interval();
}, counter);
the issue happened with me, I resolved by removing the scope tag only and built successfully.
C++11 (Source: Iterator Invalidation Rules (C++0x))
Sequence containers
vector
: all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.3.6.5/1]deque
: all iterators and references are invalidated, unless the inserted member is at an end (front or back) of the deque (in which case all iterators are invalidated, but references to elements are unaffected) [23.3.3.4/1]list
: all iterators and references unaffected [23.3.5.4/1]forward_list
: all iterators and references unaffected (applies to insert_after
) [23.3.4.5/1]array
: (n/a)Associative containers
[multi]{set,map}
: all iterators and references unaffected [23.2.4/9]Unsorted associative containers
unordered_[multi]{set,map}
: all iterators invalidated when rehashing occurs, but references unaffected [23.2.5/8]. Rehashing does not occur if the insertion does not cause the container's size to exceed z * B
where z
is the maximum load factor and B
the current number of buckets. [23.2.5/14]Container adaptors
stack
: inherited from underlying containerqueue
: inherited from underlying containerpriority_queue
: inherited from underlying containerSequence containers
vector
: every iterator and reference at or after the point of erase is invalidated [23.3.6.5/3]deque
: erasing the last element invalidates only iterators and references to the erased elements and the past-the-end iterator; erasing the first element invalidates only iterators and references to the erased elements; erasing any other elements invalidates all iterators and references (including the past-the-end iterator) [23.3.3.4/4]list
: only the iterators and references to the erased element is invalidated [23.3.5.4/3]forward_list
: only the iterators and references to the erased element is invalidated (applies to erase_after
) [23.3.4.5/1]array
: (n/a)Associative containers
[multi]{set,map}
: only iterators and references to the erased elements are invalidated [23.2.4/9]Unordered associative containers
unordered_[multi]{set,map}
: only iterators and references to the erased elements are invalidated [23.2.5/13]Container adaptors
stack
: inherited from underlying containerqueue
: inherited from underlying containerpriority_queue
: inherited from underlying containervector
: as per insert/erase [23.3.6.5/12]deque
: as per insert/erase [23.3.3.3/3]list
: as per insert/erase [23.3.5.3/1]forward_list
: as per insert/erase [23.3.4.5/25]array
: (n/a)Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container. [23.2.1/11]
no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ] [23.2.1/10]
Other than the above caveat regarding swap()
, it's not clear whether "end" iterators are subject to the above listed per-container rules; you should assume, anyway, that they are.
vector
and all unordered associative containers support reserve(n)
which guarantees that no automatic resizing will occur at least until the size of the container grows to n
. Caution should be taken with unordered associative containers because a future proposal will allow the specification of a minimum load factor, which would allow rehashing to occur on insert
after enough erase
operations reduce the container size below the minimum; the guarantee should be considered potentially void after an erase
.
Make a bat file with the following in it:
copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt
However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:
C:\temp\test.bat > C:\temp\test.log
(assuming the first bat file was called test.bat and was located in that directory)
As to why this still exists - MS doesn't consider it a priority, and values backwards compatibility over advancing their OS (at least in this instance).
A workaround I use is to use the "short names" for the directories in the path, instead of their standard, human-readable versions. So e.g. for C:\Program Files\
I would use C:\PROGRA~1\
You can find the short name equivalents using dir /x
.
This can be used in to solve this problem
<div id='scrol'></div>
in javascript use this
jQuery("div#scrol").scrollTop(jQuery("div#scrol")[0].scrollHeight);
I often find it useful to write a function to handle error messages so the code is cleaner overall.
# Usage: die [exit_code] [error message]
die() {
local code=$? now=$(date +%T.%N)
if [ "$1" -ge 0 ] 2>/dev/null; then # assume $1 is an error code if numeric
code="$1"
shift
fi
echo "$0: ERROR at ${now%???}${1:+: $*}" >&2
exit $code
}
This takes the error code from the previous command and uses it as the default error code when exiting the whole script. It also notes the time, with microseconds where supported (GNU date's %N
is nanoseconds, which we truncate to microseconds later).
If the first option is zero or a positive integer, it becomes the exit code and we remove it from the list of options. We then report the message to standard error, with the name of the script, the word "ERROR", and the time (we use parameter expansion to truncate nanoseconds to microseconds, or for non-GNU times, to truncate e.g. 12:34:56.%N
to 12:34:56
). A colon and space are added after the word ERROR, but only when there is a provided error message. Finally, we exit the script using the previously determined exit code, triggering any traps as normal.
Some examples (assume the code lives in script.sh
):
if [ condition ]; then die 123 "condition not met"; fi
# exit code 123, message "script.sh: ERROR at 14:58:01.234564: condition not met"
$command |grep -q condition || die 1 "'$command' lacked 'condition'"
# exit code 1, "script.sh: ERROR at 14:58:55.825626: 'foo' lacked 'condition'"
$command || die
# exit code comes from command's, message "script.sh: ERROR at 14:59:15.575089"
There's of course the rather obvious:
Data[...,0] + 1j * Data[...,1]
Try adding ?wmode=opaque
to the URL or &wmode=opaque
if there already is a parameter.
If it doesn't work try this instead, &wmode=transparent
which will work in IE browser as well.
Well, it doesn't get much better than that. Officially, you should use
dataGridView1.DataSource = typeof(List);
dataGridView1.DataSource = itemStates;
It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.
var str = 'Hello World',
i = 3,
result = str.substr(0, i-1)+str.substring(i);
alert(result);
Value of i
should not be less then 1
.
Works for primitives and immutable classes like String
, Wrapper classes Character, Byte.
int i=0,j=2
String s1,s2
s1 = s2 = "java rocks"
For mutable classes
Reference r1 = Reference r2 = Reference r3 = new Object();`
Three references + one object are created. All references point to the same object and your program will misbehave.
It looks like you are trying to parse each line. You've been shown by another answer how to use getline
in a loop to seperate each line. The other tool you are going to want is istringstream
, to seperate each token.
std::string line;
while(std::getline(file, line))
{
std::istringstream iss(line);
std::string token;
while (iss >> token)
{
// do something with token
}
}
You should be looking at adding a like like this:
<identity impersonate="true" userName="domain\user" password="****" />
Into your web.config.
Swift 3
If you have an array of generic objects and you want to sum some object property then:
class A: NSObject {
var value = 0
init(value: Int) {
self.value = value
}
}
let array = [A(value: 2), A(value: 4)]
let sum = array.reduce(0, { $0 + $1.value })
// ^ ^
// $0=result $1=next A object
print(sum) // 6
Despite of the shorter form, many times you may prefer the classic for-cycle:
let array = [A(value: 2), A(value: 4)]
var sum = 0
array.forEach({ sum += $0.value})
// or
for element in array {
sum += element.value
}
I am using Visual Studio 2012. After installing the Visual Studio 2013 web express, when I want to run or open any project in Visual Studio 2012 it shows me the following error:
"no exports were found that match the constraint contract name".
I also tried the above solution for clearing the ComponentModelCache, but I did not find the folder. I solves my problem just by: Repair Visual Studio 2012
For the Express versions of the software, the folder you need is in a slightly different place(s): For Express 2012 for Web it is C:\Users\XXXXXXXX\AppData\Local\Microsoft\VWDExpress
- not in the Visual Studio folder.
You can use split
method for it. And if you should take string from specific pattern you can use split
with req. exp.:
var string = "sometext-20202";
console.log(string.split(/-(.*)/)[1])
_x000D_
DecimalFormat df=new DecimalFormat("0.00");
Use this code to get exact two decimal points. Even if the value is 0.0 it will give u 0.00 as output.
Instead if you use:
DecimalFormat df=new DecimalFormat("#.00");
It wont convert 0.2659 into 0.27. You will get an answer like .27.
Also adding insert option, as not mentioned yet.
std::string str("Hello World");
char ch;
str.push_back(ch); //ch is the character to be added
OR
str.append(sizeof(ch),ch);
OR
str.insert(str.length(),sizeof(ch),ch) //not mentioned above
zxing does not (only) provide a web API; really, that is Google providing the API, from source code that was later open-sourced in the project.
As Rob says here you can use the Java source code for the QR code encoder to create a raw barcode and then render it as a Bitmap.
I can offer an easier way still. You can call Barcode Scanner by Intent to encode a barcode. You need just a few lines of code, and two classes from the project, under android-integration
. The main one is IntentIntegrator. Just call shareText()
.
If you are using WL 10 use the following:
org.hibernate.dialect.Oracle10gDialect
window.location.href = "URL2"
inside a JS block on the page or in an included file; that's assuming you really want to do it on the client. Usually, the server sends the redirect via a 300-series response.
A regular expression for words would give you the most control. You would want to carefully consider how to deal with words with dashes or apostrophes, like "I'm".
To add to what Jonathan said: use the -print0
option for find
in conjunction with xargs
as follows:
find test/* -type d -print0 | xargs -0 command
That will execute the command command
with the proper arguments; directories with spaces in them will be properly quoted (i.e. they'll be passed in as one argument).
Same problem with Chrome : I had in my html page the following code :
<body>
...
<script src="http://myserver/lib/load.js"></script>
...
</body>
But the load.js
was always in status pending
when looking in the Network pannel.
I found a workaround using asynchronous load of load.js
:
<body>
...
<script>
setTimeout(function(){
var head, script;
head = document.getElementsByTagName("head")[0];
script = document.createElement("script");
script.src = "http://myserver/lib/load.js";
head.appendChild(script);
}, 1);
</script>
...
</body>
Now its working fine.
My approach:
define a default constraint on the ModDate
column with a value of GETDATE()
- this handles the INSERT
case
have a AFTER UPDATE
trigger to update the ModDate
column
Something like:
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
The orderBy
method requires either two strings or an Expr\OrderBy
object. If you want to add multiple order declarations, the correct thing is to use addOrderBy
method, or instantiate an OrderBy
object and populate it accordingly:
# Inside a Repository method:
$myResults = $this->createQueryBuilder('a')
->addOrderBy('a.column1', 'ASC')
->addOrderBy('a.column2', 'ASC')
->addOrderBy('a.column3', 'DESC')
;
# Or, using a OrderBy object:
$orderBy = new OrderBy('a.column1', 'ASC');
$orderBy->add('a.column2', 'ASC');
$orderBy->add('a.column3', 'DESC');
$myResults = $this->createQueryBuilder('a')
->orderBy($orderBy)
;
/*
*The Options Menu (the one that pops up on pressing the menu button on the emulator)
* can be customized to change the background of the menu
*@primalpop
*/
package com.pop.menu;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.LayoutInflater.Factory;
public class Options_Menu extends Activity {
private static final String TAG = "DEBUG";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/* Invoked when the menu button is pressed */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater inflater = new MenuInflater(getApplicationContext());
inflater.inflate(R.menu.options_menu, menu);
setMenuBackground();
return true;
}
/*IconMenuItemView is the class that creates and controls the options menu
* which is derived from basic View class. So We can use a LayoutInflater
* object to create a view and apply the background.
*/
protected void setMenuBackground(){
Log.d(TAG, "Enterting setMenuBackGround");
getLayoutInflater().setFactory( new Factory() {
@Override
public View onCreateView ( String name, Context context, AttributeSet attrs ) {
if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {
try { // Ask our inflater to create the view
LayoutInflater f = getLayoutInflater();
final View view = f.createView( name, null, attrs );
/*
* The background gets refreshed each time a new item is added the options menu.
* So each time Android applies the default background we need to set our own
* background. This is done using a thread giving the background change as runnable
* object
*/
new Handler().post( new Runnable() {
public void run () {
view.setBackgroundResource( R.drawable.background);
}
} );
return view;
}
catch ( InflateException e ) {}
catch ( ClassNotFoundException e ) {}
}
return null;
}
});
}
}
That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character
You can do that nowadays with FormData
and URLSearchParams
without the need to loop over anything.
const formData = new FormData(form);
const searchParams = new URLSearchParams(formData);
const queryString = searchParams.toString();
Older browsers will need a polyfill, though.
As others have said, there is no universally correct block size; what is optimal for one situation or one piece of hardware may be terribly inefficient for another. Also, depending on the health of the disks it may be preferable to use a different block size than what is "optimal".
One thing that is pretty reliable on modern hardware is that the default block size of 512 bytes tends to be almost an order of magnitude slower than a more optimal alternative. When in doubt, I've found that 64K is a pretty solid modern default. Though 64K usually isn't THE optimal block size, in my experience it tends to be a lot more efficient than the default. 64K also has a pretty solid history of being reliably performant: You can find a message from the Eug-Lug mailing list, circa 2002, recommending a block size of 64K here: http://www.mail-archive.com/[email protected]/msg12073.html
For determining THE optimal output block size, I've written the following script that tests writing a 128M test file with dd at a range of different block sizes, from the default of 512 bytes to a maximum of 64M. Be warned, this script uses dd internally, so use with caution.
dd_obs_test.sh:
#!/bin/bash
# Since we're dealing with dd, abort if any errors occur
set -e
TEST_FILE=${1:-dd_obs_testfile}
TEST_FILE_EXISTS=0
if [ -e "$TEST_FILE" ]; then TEST_FILE_EXISTS=1; fi
TEST_FILE_SIZE=134217728
if [ $EUID -ne 0 ]; then
echo "NOTE: Kernel cache will not be cleared between tests without sudo. This will likely cause inaccurate results." 1>&2
fi
# Header
PRINTF_FORMAT="%8s : %s\n"
printf "$PRINTF_FORMAT" 'block size' 'transfer rate'
# Block sizes of 512b 1K 2K 4K 8K 16K 32K 64K 128K 256K 512K 1M 2M 4M 8M 16M 32M 64M
for BLOCK_SIZE in 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864
do
# Calculate number of segments required to copy
COUNT=$(($TEST_FILE_SIZE / $BLOCK_SIZE))
if [ $COUNT -le 0 ]; then
echo "Block size of $BLOCK_SIZE estimated to require $COUNT blocks, aborting further tests."
break
fi
# Clear kernel cache to ensure more accurate test
[ $EUID -eq 0 ] && [ -e /proc/sys/vm/drop_caches ] && echo 3 > /proc/sys/vm/drop_caches
# Create a test file with the specified block size
DD_RESULT=$(dd if=/dev/zero of=$TEST_FILE bs=$BLOCK_SIZE count=$COUNT conv=fsync 2>&1 1>/dev/null)
# Extract the transfer rate from dd's STDERR output
TRANSFER_RATE=$(echo $DD_RESULT | \grep --only-matching -E '[0-9.]+ ([MGk]?B|bytes)/s(ec)?')
# Clean up the test file if we created one
if [ $TEST_FILE_EXISTS -ne 0 ]; then rm $TEST_FILE; fi
# Output the result
printf "$PRINTF_FORMAT" "$BLOCK_SIZE" "$TRANSFER_RATE"
done
I've only tested this script on a Debian (Ubuntu) system and on OSX Yosemite, so it will probably take some tweaking to make work on other Unix flavors.
By default the command will create a test file named dd_obs_testfile in the current directory. Alternatively, you can provide a path to a custom test file by providing a path after the script name:
$ ./dd_obs_test.sh /path/to/disk/test_file
The output of the script is a list of the tested block sizes and their respective transfer rates like so:
$ ./dd_obs_test.sh
block size : transfer rate
512 : 11.3 MB/s
1024 : 22.1 MB/s
2048 : 42.3 MB/s
4096 : 75.2 MB/s
8192 : 90.7 MB/s
16384 : 101 MB/s
32768 : 104 MB/s
65536 : 108 MB/s
131072 : 113 MB/s
262144 : 112 MB/s
524288 : 133 MB/s
1048576 : 125 MB/s
2097152 : 113 MB/s
4194304 : 106 MB/s
8388608 : 107 MB/s
16777216 : 110 MB/s
33554432 : 119 MB/s
67108864 : 134 MB/s
(Note: The unit of the transfer rates will vary by OS)
To test optimal read block size, you could use more or less the same process, but instead of reading from /dev/zero and writing to the disk, you'd read from the disk and write to /dev/null. A script to do this might look like so:
dd_ibs_test.sh:
#!/bin/bash
# Since we're dealing with dd, abort if any errors occur
set -e
TEST_FILE=${1:-dd_ibs_testfile}
if [ -e "$TEST_FILE" ]; then TEST_FILE_EXISTS=$?; fi
TEST_FILE_SIZE=134217728
# Exit if file exists
if [ -e $TEST_FILE ]; then
echo "Test file $TEST_FILE exists, aborting."
exit 1
fi
TEST_FILE_EXISTS=1
if [ $EUID -ne 0 ]; then
echo "NOTE: Kernel cache will not be cleared between tests without sudo. This will likely cause inaccurate results." 1>&2
fi
# Create test file
echo 'Generating test file...'
BLOCK_SIZE=65536
COUNT=$(($TEST_FILE_SIZE / $BLOCK_SIZE))
dd if=/dev/urandom of=$TEST_FILE bs=$BLOCK_SIZE count=$COUNT conv=fsync > /dev/null 2>&1
# Header
PRINTF_FORMAT="%8s : %s\n"
printf "$PRINTF_FORMAT" 'block size' 'transfer rate'
# Block sizes of 512b 1K 2K 4K 8K 16K 32K 64K 128K 256K 512K 1M 2M 4M 8M 16M 32M 64M
for BLOCK_SIZE in 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864
do
# Clear kernel cache to ensure more accurate test
[ $EUID -eq 0 ] && [ -e /proc/sys/vm/drop_caches ] && echo 3 > /proc/sys/vm/drop_caches
# Read test file out to /dev/null with specified block size
DD_RESULT=$(dd if=$TEST_FILE of=/dev/null bs=$BLOCK_SIZE 2>&1 1>/dev/null)
# Extract transfer rate
TRANSFER_RATE=$(echo $DD_RESULT | \grep --only-matching -E '[0-9.]+ ([MGk]?B|bytes)/s(ec)?')
printf "$PRINTF_FORMAT" "$BLOCK_SIZE" "$TRANSFER_RATE"
done
# Clean up the test file if we created one
if [ $TEST_FILE_EXISTS -ne 0 ]; then rm $TEST_FILE; fi
An important difference in this case is that the test file is a file that is written by the script. Do not point this command at an existing file or the existing file will be overwritten with zeroes!
For my particular hardware I found that 128K was the most optimal input block size on a HDD and 32K was most optimal on a SSD.
Though this answer covers most of my findings, I've run into this situation enough times that I wrote a blog post about it: http://blog.tdg5.com/tuning-dd-block-size/ You can find more specifics on the tests I performed there.
In case you came here looking for a way to modify logging of any (possibly deeply nested) module, use logging.Logger.manager.loggerDict
to get a dictionary of all of the logger objects. The returned names can then be used as the argument to logging.getLogger
:
import requests
import logging
for key in logging.Logger.manager.loggerDict:
print(key)
# requests.packages.urllib3.connectionpool
# requests.packages.urllib3.util
# requests.packages
# requests.packages.urllib3
# requests.packages.urllib3.util.retry
# PYREADLINE
# requests
# requests.packages.urllib3.poolmanager
logging.getLogger('requests').setLevel(logging.CRITICAL)
# Could also use the dictionary directly:
# logging.Logger.manager.loggerDict['requests'].setLevel(logging.CRITICAL)
Per user136036 in a comment, be aware that this method only shows you the loggers that exist at the time you run the above snippet. If, for example, a module creates a new logger when you instantiate a class, then you must put this snippet after creating the class in order to print its name.
First of all, you should never use the money datatype. If you do any calculations you will get truncated results. Run the following to see what I mean
DECLARE
@mon1 MONEY,
@mon2 MONEY,
@mon3 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)
SELECT
@mon1 = 100, @mon2 = 339, @mon3 = 10000,
@num1 = 100, @num2 = 339, @num3 = 10000
SET @mon4 = @mon1/@mon2*@mon3
SET @num4 = @num1/@num2*@num3
SELECT @mon4 AS moneyresult,
@num4 AS numericresult
Output: 2949.0000 2949.8525
Now to answer your question (it was a little vague), the money datatype always has two places after the decimal point. Use the integer datatype if you don't want the fractional part or convert to int.
Perhaps you want to use the decimal or numeric datatype?
Thanks to G_money and other suggestions for this excellent solution to input-text with inline dropdown... here's another great solution.
<form class="form-inline" role="form" id="yourformID-form" action="" method="post">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-male"></i></span>
<div class="form-group">
<input size="50" maxlength="50" class="form-control" name="q" type="text">
</div>
<div class="form-group">
<select class="form-control" name="category">
<option value=""></option>
<option value="0">select1</option>
<option value="1">select2</option>
<option value="2">select3</option>
</select>
</div>
</div>
</form>
This works with Bootstrap 3: allowing input-text inline with a select dropdown. Here's what it looks like below...
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function
, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList
not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join()
, I prefer list comprehensions and generators over map()
so I would probably use the following:
print '\n'.join(str(p) for p in myList)
A Covering Index is a Non-Clustered
index. Both Clustered and Non-Clustered indexes use B-Tree data structure to improve the search for data, the difference is that in the leaves of a Clustered Index a whole record (i.e. row) is stored physically right there!, but this is not the case for Non-Clustered indexes. The following examples illustrate it:
Example: I have a table with three columns: ID, Fname and Lname.
However, for a Non-Clustered index, there are two possibilities: either the table already has a Clustered index or it doesn't:
As the two diagrams show, such Non-Clustered indexes do not provide a good performance, because they cannot find the favorite value (i.e. Lname) solely from the B-Tree. Instead they have to do an extra Look Up step (either Key or RID look up) to find the value of Lname. And, this is where covered index comes to the screen. Here, the Non-Clustered index on ID coveres the value of Lname right next to it in the leaves of the B-Tree and there is no need for any type of look up anymore.
Yes, you can put arrays in sessions, example:
$_SESSION['name_here'] = $your_array;
Now you can use the $_SESSION['name_here']
on any page you want but make sure that you put the session_start()
line before using any session functions, so you code should look something like this:
session_start();
$_SESSION['name_here'] = $your_array;
Possible Example:
session_start();
$_SESSION['name_here'] = $_POST;
Now you can get field values on any page like this:
echo $_SESSION['name_here']['field_name'];
As for the second part of your question, the session variables remain there unless you assign different array data:
$_SESSION['name_here'] = $your_array;
Session life time is set into php.ini file.
This worked for me.
I created a folder then changed into the folder using CD option from command prompt.
Then executed the jar from there.
d:\LS\afterchange>jar xvf ..\mywar.war
I use below simple solution:
This is your workbook and sheet:
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("YOUR Workshhet");
then add data to your sheet with columns and rows. Once done with adding data to sheet write following code to autoSizeColumn
width.
for (int columnIndex = 0; columnIndex < 15; columnIndex++) {
sheet.autoSizeColumn(columnIndex);
}
Here, instead 15, you add the number of columns in your sheet.
Hope someone helps this.
Place your springbootapplication class in root package for example if your service,controller is in springBoot.xyz package then your main class should be in springBoot package otherwise it will not scan below packages
In your concrete example the problem is that you don't use this construct correctly:
@JsonSubTypes({ @JsonSubTypes.Type(value = MyAbstractClass.class, name = "MyAbstractClass") })
@JsonSubTypes.Type
should contain the actual non-abstract subtypes of your abstract class.
Therefore if you have:
abstract class Parent
and the concrete subclasses
Ch1 extends Parent
and
Ch2 extends Parent
Then your annotation should look like:
@JsonSubTypes({
@JsonSubTypes.Type(value = Ch1.class, name = "ch1"),
@JsonSubTypes.Type(value = Ch2.class, name = "ch2")
})
Here name
should match the value of your 'discriminator':
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT,
property = "type")
in the property
field, here it is equal to type
. So type
will be the key and the value you set in name
will be the value.
Therefore, when the json string comes if it has this form:
{
"type": "ch1",
"other":"fields"
}
Jackson will automatically convert this to a Ch1
class.
If you send this:
{
"type": "ch2",
"other":"fields"
}
You would get a Ch2
instance.
Simply look at:
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#ROUND_HALF_UP
and:
setScale(int precision, int roundingMode)
Or if using Java 6, then
http://download.oracle.com/javase/6/docs/api/java/math/RoundingMode.html#HALF_UP
http://download.oracle.com/javase/6/docs/api/java/math/MathContext.html
and either:
setScale(int precision, RoundingMode mode);
round(MathContext mc);
I had a similar problem and was able to solve it by addressing my mysql with 127.0.0.1
instead of localhost
.
This probably means I've got something wrong in my hosts setup, but this quick fix get's me going for right now.
I'd say
chunks = [data[x:x+100] for x in range(0, len(data), 100)]
If you are using python 2.x instead of 3.x, you can be more memory-efficient by using xrange()
, changing the above code to:
chunks = [data[x:x+100] for x in xrange(0, len(data), 100)]
In 1.20
ALT+SHIFT+0 PC (Windows, Linux)
?+?+0 Mac
Pre-1.20
ALT+SHIFT+1 PC (Windows, Linux)
?+?+1 Mac
Changes editor split layout from horizontal to vertical
In 1.25 you can split editor into Grid
layout. Check View
=>Editor Layout
It is nicely presented in Release notes v1.25: VS Code grid editor layout
On Fedora 28, just pay attention to the line
security.useSystemPropertiesFile=true
of the java.security
file, found at:
$(dirname $(readlink -f $(which java)))/../lib/security/java.security
Fedora 28 introduced external file of disabledAlgorithms control at
/etc/crypto-policies/back-ends/java.config
You can edit this external file or you can exclude it from java.security
by setting
security.useSystemPropertiesFile=false
If you don't want to alter the list:
List<Integer> list = Arrays.asList(array)
But if you want to modify it then you can use this:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(ints));
Or just use java8 like the following:
List<Integer> list = Arrays.stream(ints).collect(Collectors.toList());
Java9 has introduced this method:
List<Integer> list = List.of(ints);
However, this will return an immutable list that you can't add to.
You need to do the following to make it mutable:
List<Integer> list = new ArrayList<Integer>(List.of(ints));
I have writen a single file AJAX tester. Enjoy it!!! Just because I have had problems with my hosting provider
<?php /*
Author: Luis Siquot
Purpose: Check ajax performance and errors
License: GPL
site5: Please don't drop json requests (nor delay)!!!!
*/
$r = (int)$_GET['r'];
$w = (int)$_GET['w'];
if($r) {
sleep($w);
echo json_encode($_GET);
die ();
} //else
?><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var _settimer;
var _timer;
var _waiting;
$(function(){
clearTable();
$('#boton').bind('click', donow);
})
function donow(){
var w;
var estim = 0;
_waiting = $('#total')[0].value * 1;
clearTable();
for(var r=1;r<=_waiting;r++){
w = Math.floor(Math.random()*6)+2;
estim += w;
dodebug({r:r, w:w});
$.ajax({url: '<?php echo $_SERVER['SCRIPT_NAME']; ?>',
data: {r:r, w:w},
dataType: 'json', // 'html',
type: 'GET',
success: function(CBdata, status) {
CBdebug(CBdata);
}
});
}
doStat(estim);
timer(estim+10);
}
function doStat(what){
$('#stat').replaceWith(
'<table border="0" id="stat"><tr><td>Request Time Sum=<th>'+what+
'<td> /2=<th>'+Math.ceil(what/2)+
'<td> /3=<th>'+Math.ceil(what/3)+
'<td> /4=<th>'+Math.ceil(what/4)+
'<td> /6=<th>'+Math.ceil(what/6)+
'<td> /8=<th>'+Math.ceil(what/8)+
'<td> (seconds)</table>'
);
}
function timer(what){
if(what) {_timer = 0; _settimer = what;}
if(_waiting==0) {
$('#showTimer')[0].innerHTML = 'completed in <b>' + _timer + ' seconds</b> (aprox)';
return ;
}
if(_timer<_settimer){
$('#showTimer')[0].innerHTML = _timer;
setTimeout("timer()",1000);
_timer++;
return;
}
$('#showTimer')[0].innerHTML = '<b>don\'t wait any more!!!</b>';
}
function CBdebug(what){
_waiting--;
$('#req'+what.r)[0].innerHTML = 'x';
}
function dodebug(what){
var tt = '<tr><td>' + what.r + '<td>' + what.w + '<td id=req' + what.r + '> '
$('#debug').append(tt);
}
function clearTable(){
$('#debug').replaceWith('<table border="1" id="debug"><tr><td>Request #<td>Wait Time<td>Done</table>');
}
</script>
</head>
<body>
<center>
<input type="button" value="start" id="boton">
<input type="text" value="80" id="total" size="2"> concurrent json requests
<table id="stat"><tr><td> </table>
Elapsed Time: <span id="showTimer"></span>
<table id="debug"></table>
</center>
</body>
Edit:
r means row and w waiting time.
When you initially press start button 80 (or any other number) of concurrent ajax request are launched by javascript, but as is known they are spooled by the browser. Also they are requested to the server in parallel (limited to certain number, this is the fact of this question). Here the requests are solved server side with a random delay (established by w). At start time all the time needed to solve all ajax calls is calculated. When test is finished, you can see if it took half, took third, took a quarter, etc of the total time, deducting which was the parallelism on the calls to the server. This is not strict, nor precise, but is nice to see in real time how ajaxs calls are completed (seeing the incoming cross). And is a very simple self contained script to show ajax basics.
Of course, this assumes, that server side is not introducing any extra limit.
Preferably use in conjunction with firebug net panel (or your browser's equivalent)
In your readLine
function, you return a pointer to the line
array (Strictly speaking, a pointer to its first character, but the difference is irrelevant here). Since it's an automatic variable (i.e., it's “on the stack”), the memory is reclaimed when the function returns. You see gibberish because printf
has put its own stuff on the stack.
You need to return a dynamically allocated buffer from the function. You already have one, it's lineBuffer
; all you have to do is truncate it to the desired length.
lineBuffer[count] = '\0';
realloc(lineBuffer, count + 1);
return lineBuffer;
}
ADDED (response to follow-up question in comment): readLine
returns a pointer to the characters that make up the line. This pointer is what you need to work with the contents of the line. It's also what you must pass to free
when you've finished using the memory taken by these characters. Here's how you might use the readLine
function:
char *line = readLine(file);
printf("LOG: read a line: %s\n", line);
if (strchr(line, 'a')) { puts("The line contains an a"); }
/* etc. */
free(line);
/* After this point, the memory allocated for the line has been reclaimed.
You can't use the value of `line` again (though you can assign a new value
to the `line` variable if you want). */
margin: auto;
The standard way to import AAR file in an application is given in https://developer.android.com/studio/projects/android-library.html#AddDependency
Click File > New > New Module. Click Import .JAR/.AAR Package then click Next. Enter the location of the compiled AAR or JAR file then click Finish.
Please refer the link above for next steps.
There is an easy way if you want simple code formatting.
Then content mixer add will open automatically and you can copy paste your code in there and click on "Insert" to insert it in word doc.
Sooner or later you will have property with special character. You can either use index or combination of index and property.
dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use
You need to write following code on controller suppose test is model, and Name, Address are field of this model.
public ActionResult MyMethod()
{
Test test=new Test();
var test.Name="John";
return View(test);
}
now use like like this on your view to give set value of hidden variable.
@model YourApplicationName.Model.Test
@Html.HiddenFor(m=>m.Name,new{id="hdnFlag"})
This will automatically set hidden value=john.
Well if you are getting into a linux machine you can use the package manager of that linux distro.
If you are using Ubuntu just use apt-get search python, check the list and do apt-get install python2.7 (not sure if python2.7 or python-2.7, check the list)
You could use yum in fedora and do the same.
if you want to install it on your windows machine i dont know any package manager, i would download the wget for windows, donwload the package from python.org and install it
This may be helpful for all using tools for GIT
Command
Switch branch - it will move your changes to new-branch. Then you can commit changes.
$ git checkout -b <new-branch>
TortoiseGIT
Right-click on your repository and then use TortoiseGit->Switch/Checkout
SourceTree
Use the "Checkout" button to switch branch. You will see the "checkout" button at the top after clicking on a branch. Changes from the current branch will be applied automatically. Then you can commit them.
I like my bars tight and dynamic. This is for CSS 3 & HTML 5
First, setting the Width to 100px is limiting. Don't do it.
Second, setting the container's width to 100% will work ok, until were talking about it being a header/footer bar for the whole app, like a navigation or credits/copyright bar. Use right: 0;
instead for that scenario.
You are using id's (hash #container
, #left
, etc) instead of classes (.container
, .left
, etc), which is fine, unless you want to repeat your style pattern elsewhere in your code. I'd consider using classes instead.
For HTML, no need to swap order for: left, center, & right. display: inline-block;
fixes this, returning your code to something cleaner and logically in order again.
Lastly, you need to clear the floats all up so that it doesn't mess with future <div>
. You do this with the clear: both;
To summarize:
HTML:
<div class="container">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
<div class="clear"></div>
</div>
CSS:
.container {right: 0; text-align: center;}
.container .left, .container .center, .container .right { display: inline-block; }
.container .left { float: left; }
.container .center { margin: 0 auto; }
.container .right { float: right; }
.clear { clear: both; }
Bonus point if using HAML and SASS ;)
HAML:
.container
.left
.center
.right
.clear
SASS:
.container {
right: 0;
text-align: center;
.left, .center, .right { display: inline-block; }
.left { float: left; }
.center { margin: 0 auto; }
.right { float: right; }
.clear { clear: both; }
}
This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7
You may also check Unsupported major.minor version 51.0
IE 9 : If you want that the user takes a look at image before he posts it to the server : The user should ADD the website to "trusted Website list".
setting aria-hidden to false and toggling it on element.show() worked for me.
e.g
<span aria-hidden="true">aria text</span>
$(span).attr('aria-hidden', 'false');
$(span).show();
and when hiding back
$(span).attr('aria-hidden', 'true');
$(span).hide();
textarea {
border: 0;
overflow: auto; }
less CSS ^ you can't align the text to the bottom unfortunately.
Not exactly the answer to the question, but I needed to scroll down as soon as an EditText got the focus. However the accepted answer would make the ET also lose focus right away (to the ScrollView I assume).
My workaround was the following:
emailEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
Toast.makeText(getActivity(), "got the focus", Toast.LENGTH_LONG).show();
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
}, 200);
}else {
Toast.makeText(getActivity(), "lost the focus", Toast.LENGTH_LONG).show();
}
}
});
See at the bottom of this page at Python wiki, there are at least 2 options to "unescape" html.
GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back.
They're optional though.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
TTFB is something that happens behind the scenes. Your browser knows nothing about what happens behind the scenes.
You need to look into what queries are being run and how the website connects to the server.
This article might help understand TTFB, but otherwise you need to dig deeper into your application.
You can try something like this. Here on click of image button I toggle the imageview.
holder.imgitem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if(!onclick){
mSparseBooleanArray.put((Integer) view.getTag(), true);
holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_delete_overlay_com);
onclick=true;}
else if(onclick)
{
mSparseBooleanArray.put((Integer) view.getTag(), false);
holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_selection_com);
onclick=false;
}
}
});
Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string.
The thing is: think carefully about what your app must do and can accept. Build something robust.
If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'.
As an example of something that will explode if you follow some advices here not carefully.
var getLastChar = function (str) {
if (str.length > 0)
return str.charAt(str.length - 1)
}
getLastChar('hello')
=> "o"
getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'
So, I'd stick with
if (myVar === '')
...
Actually, this has nothing to do with the usual Windows / Unix \r\n
vs \n
issue. The TELNET procotol itself defines \r\n
as the end-of-line sequence, independently of the operating system. See RFC854.
Copy the global variable to a variable in the scope in your controller.
function MyCtrl($scope) {
$scope.variable1 = variable1;
}
Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).
But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.