Here's a solution with flexbox
for images with variable width and height:
.container {
display: flex;
flex-wrap: no-wrap;
overflow-x: auto;
margin: 20px;
}
img {
flex: 0 0 auto;
width: auto;
height: 100px;
max-width: 100%;
margin-right: 10px;
}
Example: JsFiddle
Importing .cer
certificate file downloaded from browser (open the url and dig for details) into cacerts keystore in java_home\jre\lib\security
worked for me, as opposed to attemps to generate and use my own keystore.
java_home\jre\lib\security
cmd
and CTRL+SHIFT+ENTERyourAliasName
and path\to\certificate.cer
respectively) ..\..\bin\keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias yourAliasName -file path\to\certificate.cer
This way you don't have to specify any additional JVM options and the certificate should be recognized by the JRE.
You could also use =COUNTA(A1:A200)
which requires no conditions.
From Google Support:
COUNTA counts all values in a dataset, including those which appear more than once and text values (including zero-length strings and whitespace). To count unique values, use COUNTUNIQUE.
In mysql, use:
SHOW TABLES;
After selecting the DB with:
USE db_name
There can be any number of different screen sizes due to Android having no set standard size so as a guide you can use the minimum screen sizes, which are provided by Google.
According to Google's statistics the majority of ldpi displays are small screens and the majority of mdpi, hdpi, xhdpi and xxhdpi displays are normal sized screens.
You can view the statistics on the relative sizes of devices on Google's dashboard which is available here.
More information on multiple screens can be found here.
The best solution is to create a nine-patch image so that the image's border can stretch to fit the size of the screen without affecting the static area of the image.
http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch
For the OpenSuse comrades out there:
sudo zypper install python3-devel
One way would be to inherit a new class,EntryWithSet
, and defining set
method that makes use of delete
and insert
methods of the Entry
class objects:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
class EntryWithSet(tk.Entry):
"""
A subclass to Entry that has a set method for setting its text to
a given string, much like a Variable class.
"""
def __init__(self, master, *args, **kwargs):
tk.Entry.__init__(self, master, *args, **kwargs)
def set(self, text_string):
"""
Sets the object's text to text_string.
"""
self.delete('0', 'end')
self.insert('0', text_string)
def on_button_click():
import random, string
rand_str = ''.join(random.choice(string.ascii_letters) for _ in range(19))
entry.set(rand_str)
if __name__ == '__main__':
root = tk.Tk()
entry = EntryWithSet(root)
entry.pack()
tk.Button(root, text="Set", command=on_button_click).pack()
tk.mainloop()
As @Vlad from Moscow says,
Take into account that value_type
for std::map
is defined the following way:
typedef pair<const Key, T> value_type
This then means that if you wish to replace the keyword auto
with a more explicit type specifier, then you could this;
for ( const pair<const string, int> &p : table ) {
std::cout << p.first << '\t' << p.second << std::endl;
}
Just for understanding what auto
will translate to in this case.
This is actually super simple with just a little bit of added javascript. The link's href is used as the ajax content source. Note that for Bootstrap 3.* we set data-remote="false"
to disable the deprecated Bootstrap load function.
JavaScript:
// Fill modal with content from link href
$("#myModal").on("show.bs.modal", function(e) {
var link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
Html (based on the official example):
<!-- Link trigger modal -->
<a href="remoteContent.html" data-remote="false" data-toggle="modal" data-target="#myModal" class="btn btn-default">
Launch Modal
</a>
<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Try it yourself: https://jsfiddle.net/ednon5d1/
You can use chars as is as single byte integers.
So this is long after the initial question, and technically it isn't a direct answer to how to use Ajax call to populate exterior variable as the question asks. However in research and responses it's been found to be extremely difficult to do this without disabling asynchronous functions within the call, or by descending into what seems like the potential for callback hell. My solution for this has been to use Axios. Using this has dramatically simplified my usages of asynchronous calls getting in the way of getting at data.
For example if I were trying to access session variables in PHP, like the User ID, via a call from JS this might be a problem. Doing something like this..
async function getSession() {
'use strict';
const getSession = await axios("http:" + url + "auth/" + "getSession");
log(getSession.data);//test
return getSession.data;
}
Which calls a PHP function that looks like this.
public function getSession() {
$session = new SessionController();
$session->Session();
$sessionObj = new \stdClass();
$sessionObj->user_id = $_SESSION["user_id"];
echo json_encode($sessionObj);
}
To invoke this using Axios do something like this.
getSession().then(function (res) {
log(res);//test
anyVariable = res;
anyFunction(res);//set any variable or populate another function waiting for the data
});
The result would be, in this case a Json object from PHP.
{"user_id":"1111111-1111-1111-1111-111111111111"}
Which you can either use in a function directly in the response section of the Axios call or set a variable or invoke another function.
Proper syntax for the Axios call would actually look like this.
getSession().then(function (res) {
log(res);//test
anyVariable = res;
anyFunction(res);//set any variable or populate another function waiting for the data
}).catch(function (error) {
console.log(error);
});
For proper error handling.
I hope this helps anyone having these issues. And yes I am aware this technically is not a direct answer to the question but given the answers supplied already I felt the need to provide this alternative solution which dramatically simplified my code on the client and server sides.
What you use instead of the b
element depends on the semantics of that element's content.
b
and strong
have co-existed for a long time by now. In HTML 4.01, which has been superseded by HTML5, strong
was meant to be used for "strong emphasis", i.e. stronger emphasis than the em
element (which just indicated emphasis). In HTML 5.2, strong
"represents strong importance, seriousness, or urgency for its contents"; the aspects of "seriousness" and "urgency" are new in the specification compared to HTML 4.01. So if you used b
to represent content that was important, serious or urgent, it is recommended that you use strong
instead. If you want, you can differentiate between these different semantics by adding meaningful class attributes, e.g. <strong class="urgent">...</strong>
and <strong class="warning">...</strong>
and use appropriate CSS selectors to style these types of "emphasis" different, e.g. using different colours and font sizes (e.g. in your CSS file: strong.warning { color: red; background-color: transparent; border: 2px solid red; }
.).
b
is the em
element, which in HTML 5.2 "represents stress emphasis of its contents". Note that this element is usually rendered in italics (and has therefore often been recommended as a replacement for the i
element).
<strong class="bold">...</strong>
. Firstly, the class attribute doesn't mean anything in non-visual contexts (listening to an ePub book, text to speech generally, screen readers, Braille); secondly, people maintaining the code will need to read the actual content to figure out why something was bolded.b
for entire paragraphs or headings (as opposed to shorter spans of texts, which is the use case in the previous bullet point), I would replace it with appropriate class
attributes or, if applicable, WAI-ARIA roles such as alert
for a live region "with important, and usually time-sensitive, information". As mentioned above, you should use "semantic" class
attribute values, so that people maintaining the code (including your future self) can figure out why something was bolded.b
may represent something semantic. For example, when you are converting printed documents into HTML, text may be bolded for reasons that have nothing to do with emphasis or importance but as a visual guide. For example, the headwords in dictionaries aren't any more "serious", "urgent" than the other content, so you may keep the b
element and optionallly add a meaningful class attribute, e.g. <b class="headword">
or replace the tag with <span class="headword">
based on the argument that b
has no meaning in non-visual contexts.In your CSS file (instead of using style
attributes, as some of the other answers have recommended), you have several options for styling the "bold" or important text:
font-weight
property, which allows more values than just normal
and bold
, namely normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
,Note that support for numeric font-weight values has not always been great.
According to documentation:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Basically, it picks k unique random elements, a sample, from a sequence:
>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]
random.sample
works also directly from a range:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
However, random.sample
doesn't work with arbitrary iterators:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
This will surely work:
UPDATE table1
SET table1.price=(SELECT table2.price
FROM table2
WHERE table2.id=table1.id AND table2.item=table1.item);
This is exactly what I wanted to do. I was not sure of the previous command git cherry-pick C
, it sounds nice but it seems you do this to get changes from another branch but not on same branch, has anyone tried it?
So I did something else which also worked : I got the files I wanted back from the old commit file by file
git checkout <commit-hash> <filename>
ex :
git checkout 08a6497b76ad098a5f7eda3e4ec89e8032a4da51 file.css
-> this takes the files as they were from the old commit
Then I did my changes. And I committed again.
git status (to check which files were modified)
git diff (to check the changes you made)
git add .
git commit -m "my message"
I checked my history with git log
, and I still have my history along with my new changes made from the old files. And I could push too.
Note that to go back to the state you want you need to put the hash of the commit before the unwanted changes. Also make sure you don't have uncommitted changes before you do that.
in my case i click on recent apps shortcut on my cell phone and close all apps. This solution always work for me, because this error not related to code.
You can use the redirect URL to controller:
Class Ctrlr1 extends CI_Controller{
public void my_fct1(){
redirect('Ctrlr2 /my_fct2', 'refresh');
}
}
Class Ctrlr2 extends CI_Controller{
public void my_fct2(){
$this->load->view('view1');
}
}
You can actually set this up in your migrations:
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
Source: http://laravel.com/docs/5.1/migrations#foreign-key-constraints
You may also specify the desired action for the "on delete" and "on update" properties of the constraint:
$table->foreign('user_id') ->references('id')->on('users') ->onDelete('cascade');
you can use Simple Contact Form in HTML with PHP mailer. It's easy to implement in you website. You can try the demo from following link: Simple Contact/Feedback Form in HTML-PHP mailer
Otherwise you can watch the demo video in following link: Youtube: Simple Contact/Feedback Form in HTML-PHP mailer
When you are running in localhost, you may get following error:
You can check in this link for more detailed information: Simple Contact/Feedback Form in HTML with php (HTML-PHP mailer) And this is the screenshot of HTML form:
And this is the main PHP coding:
<?php
if($_POST["submit"]) {
$recipient="[email protected]"; //Enter your mail address
$subject="Contact from Website"; //Subject
$sender=$_POST["name"];
$senderEmail=$_POST["email"];
$message=$_POST["comments"];
$mailBody="Name: $sender\nEmail Address: $senderEmail\n\nMessage: $message";
mail($recipient, $subject, $mailBody);
sleep(1);
header("Location:http://blog.antonyraphel.in/sample/"); // Set here redirect page or destination page
}
?>
Fixed it. I needed to run libtoolize
in the directory, then re-run:
aclocal
autoheader
I was getting following error on a fedora 18 box:
1. /usr/include/gnu/stubs.h:7:27: fatal error: gnu/stubs-32.h: No such file or directory compilation terminated.
I Installed glibc.i686 and glibc-devel.i686, then compilation failed with following error:
2. /usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-redhat-linux/4.7.2/libgcc_s.so when searching for -lgcc_s /usr/bin/ld: cannot find -lgcc_s collect2: error: ld returned 1 exit status
Solution:
I installed (yum install) glibc.i686 glibc-devel.i386 and libgcc.i686 to get rid of the compilation issue.
Now compilation for 32 bit (-m32) works fine.
Try innerText property:
var content = document.getElementById("one").innerText;
alert(content);
See also this fiddle http://fiddle.jshell.net/4g8vb/
Using scanf
removing any blank spaces before the string is typed and limiting the amount of characters to be read:
#define SIZE 100
....
char str[SIZE];
scanf(" %99[^\n]", str);
/* Or even you can do it like this */
scanf(" %99[a-zA-Z0-9 ]", str);
If you do not limit the amount of characters to be read with scanf
it can be as dangerous as gets
While the accepted answer is correct, I'll add a more elegant version (in my opinion):
boolean idExists = tabPane.getTabs().stream()
.map(Tab::getId)
.anyMatch(idToCheck::equals);
Don't neglect using Stream#map() which allows to flatten the data structure before applying the Predicate
.
Please read the whole answer before attempting to run with sudo
Try running sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme
The sudo command executes the commands which follow it with 'superuser' or 'root' privileges. This should allow you to execute almost anything from the command line. That said, DON'T DO THIS! If you are running a script on your computer and don't need it to access core components of your operating system (I'm guessing you're not since you are invoking the script on something inside your home directory (~/)), then it should be running from your home directory, ie:
~/dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme
Move it to ~/ or a sub directory and execute from there. You should never have permission issues there and there wont be a risk of it accessing or modifying anything critical to your OS.
If you are still having problems you can check the permissions on the file by running ls -l
while in the same directory as the ruby script. You will get something like this:
$ ls -l
total 13
drwxr-xr-x 4 or019268 Administ 12288 Apr 10 18:14 TestWizard
drwxr-xr-x 4 or019268 Administ 4096 Aug 27 12:41 Wizard.Controls
drwxr-xr-x 5 or019268 Administ 8192 Sep 5 00:03 Wizard.UI
-rw-r--r-- 1 or019268 Administ 1375 Sep 5 00:03 readme.txt
You will notice that the readme.txt file says -rw-r--r--
on the left. This shows the permissions for that file. The 9 characters from the right can be split into groups of 3 characters of 'rwx' (read, write, execute). If I want to add execute rights to this file I would execute chmod 755 readme.txt
and that permissions portion would become rwxr-xr-x
. I can now execute this file if I want to by running ./readme.txt
(./ tells the bash to look in the current directory for the intended command rather that search the $PATH variable).
schluchc alludes to looking at the man page for chmod, do this by running man chmod
. This is the best way to get documentation on a given command, man <command>
If your app is meant to run on the device, make sure you are not trying to run in it on the simulator. May sound obvious, but check anyway.
try this
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();
Consider taking advantage of the double tilde: ~~
.
Take in the number. Multiply by significant digits after the decimal so that you can truncate to zero places with ~~
. Divide that multiplier back out. Profit.
function truncator(numToTruncate, intDecimalPlaces) {
var numPower = Math.pow(10, intDecimalPlaces); // "numPowerConverter" might be better
return ~~(numToTruncate * numPower)/numPower;
}
I'm trying to resist wrapping the ~~
call in parens; order of operations should make that work correctly, I believe.
alert(truncator(5.1231231, 1)); // is 5.1
alert(truncator(-5.73, 1)); // is -5.7
alert(truncator(-5.73, 0)); // is -5
EDIT: Looking back over, I've unintentionally also handled cases to round off left of the decimal as well.
alert(truncator(4343.123, -2)); // gives 4300.
The logic's a little wacky looking for that usage, and may benefit from a quick refactor. But it still works. Better lucky than good.
This is because you have not compiled it. Click 'Project > compile'. Then, either click 'start debugging', or 'start without debugging'.
let phone = "tel://\("1234567890")";
let url:NSURL = NSURL(string:phone)!;
UIApplication.sharedApplication().openURL(url);
While creating the object for the progressbar check the following.
This fails:
dialog = new ProgressDialog(getApplicationContext());
While adding the activities context works..
dialog = new ProgressDialog(MainActivity.this);
You can use += to concatenate strings, for example:
declare @test nvarchar(max)
set @test = ''
select @test += name from names
if you select @test, it will give you all names concatenated
To determine whether a string contains another string you can use the PHP function strpos().
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
<?php
$haystack = 'how are you';
$needle = 'are';
if (strpos($haystack,$needle) !== false) {
echo "$haystack contains $needle";
}
?>
CAUTION:
If the needle you are searching for is at the beginning of the haystack it will return position 0, if you do a ==
compare that will not work, you will need to do a ===
A ==
sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.
A ===
sign is a comparison to see whether two variables / expresions / constants are equal AND
have the same type - i.e. both are strings or both are integers.
In the hexadecimal it can't get a negative value. So it shows it like ffffffff.
The advantage to using the unsigned version (when you know the values contained will be non-negative) is that sometimes the computer will spot errors for you (the program will "crash" when a negative value is assigned to the variable).
You could set like this
button.setAllCaps(false);
programmatically
I think you should convert to utf8
--set utf8 for connection
SET collation_connection = 'utf8_general_ci'
--change CHARACTER SET of DB to utf8
ALTER DATABASE dbName CHARACTER SET utf8 COLLATE utf8_general_ci
--change CHARACTER SET of table to utf8
ALTER TABLE tableName CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci
Use isset()
$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';
EDIT: This is added for the completeness sake. $_GET in php is a reserved variable that is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.
$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';
XML comments start with <!--
and end with -->
.
For example:
<!-- This is a comment. -->
I think the most logical answer in this regard is to set the system clock to the relevant feature.
[HttpPost]
public ActionResult Yeni(tblKategori kategori)
{
kategori.CREATEDDATE = DateTime.Now;
var ctx = new MvcDbStokEntities();
ctx.tblKategori.Add(kategori);
ctx.SaveChanges();
return RedirectToAction("Index");//listele sayfasina yönlendir.
}
this is the full source code to direct use,
public class CardDBDAO {
protected SQLiteDatabase database;
private DataBaseHelper dbHelper;
private Context mContext;
public CardDBDAO(Context context) {
this.mContext = context;
dbHelper = DataBaseHelper.getHelper(mContext);
open();
}
public void open() throws SQLException {
if(dbHelper == null)
dbHelper = DataBaseHelper.getHelper(mContext);
database = dbHelper.getWritableDatabase();
}
}
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydbnamedb";
private static final int DATABASE_VERSION = 1;
public static final String CARDS_TABLE = "tbl_cards";
public static final String POICATEGORIES_TABLE = "tbl_poicategories";
public static final String POILANGS_TABLE = "tbl_poilangs";
public static final String ID_COLUMN = "id";
public static final String POI_ID = "poi_id";
public static final String POICATEGORIES_COLUMN = "poi_categories";
public static final String POILANGS_COLUMN = "poi_langs";
public static final String CARDS = "cards";
public static final String CARD_ID = "card_id";
public static final String CARDS_PCAT_ID = "pcat_id";
public static final String CREATE_PLANG_TABLE = "CREATE TABLE "
+ POILANGS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
+ POILANGS_COLUMN + " TEXT, " + POI_ID + " TEXT)";
public static final String CREATE_PCAT_TABLE = "CREATE TABLE "
+ POICATEGORIES_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
+ POICATEGORIES_COLUMN + " TEXT, " + POI_ID + " TEXT)";
public static final String CREATE_CARDS_TABLE = "CREATE TABLE "
+ CARDS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY," + CARD_ID
+ " TEXT, " + CARDS_PCAT_ID + " TEXT, " + CARDS + " TEXT)";
private static DataBaseHelper instance;
public static synchronized DataBaseHelper getHelper(Context context) {
if (instance == null)
instance = new DataBaseHelper(context);
return instance;
}
private DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
// db.execSQL("PRAGMA foreign_keys=ON;");
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_PCAT_TABLE);
db.execSQL(CREATE_PLANG_TABLE);
db.execSQL(CREATE_CARDS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public class PoiLangDAO extends CardDBDAO {
private static final String WHERE_ID_EQUALS = DataBaseHelper.ID_COLUMN
+ " =?";
public PoiLangDAO(Context context) {
super(context);
}
public long save(PLang plang_data) {
ContentValues values = new ContentValues();
values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());
return database
.insert(DataBaseHelper.POILANGS_TABLE, null, values);
}
public long update(PLang plang_data) {
ContentValues values = new ContentValues();
values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());
long result = database.update(DataBaseHelper.POILANGS_TABLE,
values, WHERE_ID_EQUALS,
new String[] { String.valueOf(plang_data.getId()) });
Log.d("Update Result:", "=" + result);
return result;
}
public int deleteDept(PLang plang_data) {
return database.delete(DataBaseHelper.POILANGS_TABLE,
WHERE_ID_EQUALS, new String[] { plang_data.getId() + "" });
}
public List<PLang> getPLangs1() {
List<PLang> plang_list = new ArrayList<PLang>();
Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
DataBaseHelper.POILANGS_COLUMN }, null, null, null,
null, null);
while (cursor.moveToNext()) {
PLang plang_bin = new PLang();
plang_bin.setId(cursor.getInt(0));
plang_bin.setPoi_id(cursor.getString(1));
plang_bin.setLangarr(cursor.getString(2));
plang_list.add(plang_bin);
}
return plang_list;
}
public List<PLang> getPLangs(String pid) {
List<PLang> plang_list = new ArrayList<PLang>();
String selection = DataBaseHelper.POI_ID + "=?";
String[] selectionArgs = { pid };
Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
DataBaseHelper.POILANGS_COLUMN }, selection,
selectionArgs, null, null, null);
while (cursor.moveToNext()) {
PLang plang_bin = new PLang();
plang_bin.setId(cursor.getInt(0));
plang_bin.setPoi_id(cursor.getString(1));
plang_bin.setLangarr(cursor.getString(2));
plang_list.add(plang_bin);
}
return plang_list;
}
public void loadPLangs(String poi_id, String langarrs) {
PLang plangbin = new PLang(poi_id, langarrs);
List<PLang> plang_arr = new ArrayList<PLang>();
plang_arr.add(plangbin);
for (PLang dept : plang_arr) {
ContentValues values = new ContentValues();
values.put(DataBaseHelper.POI_ID, dept.getPoi_id());
values.put(DataBaseHelper.POILANGS_COLUMN, dept.getLangarr());
database.insert(DataBaseHelper.POILANGS_TABLE, null, values);
}
}
}
public class PLang {
public PLang() {
super();
}
public PLang(String poi_id, String langarrs) {
// TODO Auto-generated constructor stub
this.poi_id = poi_id;
this.langarr = langarrs;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPoi_id() {
return poi_id;
}
public void setPoi_id(String poi_id) {
this.poi_id = poi_id;
}
public String getLangarr() {
return langarr;
}
public void setLangarr(String langarr) {
this.langarr = langarr;
}
private int id;
private String poi_id;
private String langarr;
}
Notwithstanding what Pavel Shved said - that it is probably more advisable to get used to Escaping Insert mode - here is an example set of mappings for quick navigation within Insert mode:
" provide hjkl movements in Insert mode via the <Alt> modifier key
inoremap <A-h> <C-o>h
inoremap <A-j> <C-o>j
inoremap <A-k> <C-o>k
inoremap <A-l> <C-o>l
This will make Alt+h in Insert mode go one character left, Alt+j down and so on, analogously to hjkl in Normal mode.
You have to copy that code into your vimrc file to have it loaded every time you start vim (you can open that by typing :new $myvimrc
starting in Normal mode).
Since the Alt modifier key is not mapped (to something important) by default, you can in the same fashion pull other (or all) functionality from Normal mode to Insert mode. E.g.:
Moving to the beginning of the current word with Alt+b:
inoremap <A-b> <C-o>b
inoremap <A-w> <C-o>w
It is worth mentioning that there may be better uses for the Alt key than replicating Normal mode behaviour: e.g. here are mappings for copying from an adjacent line the portion from the current column till the end of the line:
" Insert the rest of the line below the cursor.
" Mnemonic: Elevate characters from below line
inoremap <A-e>
\<Esc>
\jl
\y$
\hk
\p
\a
" Insert the rest of the line above the cursor.
" Mnemonic: Y depicts a funnel, through which the above line's characters pour onto the current line.
inoremap <A-y>
\<Esc>
\kl
\y$
\hj
\p
\a
(I used \
line continuation and indentation to increase clarity. The commands are interpreted as if written on a single line.)
CTRL-H delete the character in front of the cursor (same as <Backspace>)
CTRL-W delete the word in front of the cursor
CTRL-U delete all characters in front of the cursor (influenced by the 'backspace' option)
(There are no notable built-in hotkeys for movement in Insert mode.)
Reference: :help insert-index
This set of mappings makes the upper Alt+hjkl movements available in the Command-line:
" provide hjkl movements in Command-line mode via the <Alt> modifier key
cnoremap <A-h> <Left>
cnoremap <A-j> <Down>
cnoremap <A-k> <Up>
cnoremap <A-l> <Right>
Alternatively, these mappings add the movements both to Insert mode and Command-line mode in one go:
" provide hjkl movements in Insert mode and Command-line mode via the <Alt> modifier key
noremap! <A-h> <Left>
noremap! <A-j> <Down>
noremap! <A-k> <Up>
noremap! <A-l> <Right>
The mapping commands for pulling Normal mode commands to Command-line mode look a bit different from the Insert mode mapping commands (because Command-line mode lacks Insert mode's Ctrl+O):
" Normal mode command(s) go… --v <-- here
cnoremap <expr> <A-h> &cedit. 'h' .'<C-c>'
cnoremap <expr> <A-j> &cedit. 'j' .'<C-c>'
cnoremap <expr> <A-k> &cedit. 'k' .'<C-c>'
cnoremap <expr> <A-l> &cedit. 'l' .'<C-c>'
cnoremap <expr> <A-b> &cedit. 'b' .'<C-c>'
cnoremap <expr> <A-w> &cedit. 'w' .'<C-c>'
CTRL-B cursor to beginning of command-line
CTRL-E cursor to end of command-line
CTRL-F opens the command-line window (unless a different key is specified in 'cedit')
CTRL-H delete the character in front of the cursor (same as <Backspace>)
CTRL-W delete the word in front of the cursor
CTRL-U delete all characters in front of the cursor
CTRL-P recall previous command-line from history (that matches pattern in front of the cursor)
CTRL-N recall next command-line from history (that matches pattern in front of the cursor)
<Up> recall previous command-line from history (that matches pattern in front of the cursor)
<Down> recall next command-line from history (that matches pattern in front of the cursor)
<S-Up> recall previous command-line from history
<S-Down> recall next command-line from history
<PageUp> recall previous command-line from history
<PageDown> recall next command-line from history
<S-Left> cursor one word left
<C-Left> cursor one word left
<S-Right> cursor one word right
<C-Right> cursor one word right
<LeftMouse> cursor at mouse click
Reference: :help ex-edit-index
You should take care with readLines(...)
and big files. Reading all lines at memory can be risky. Below is a example of how to read file and process just one line at time:
processFile = function(filepath) {
con = file(filepath, "r")
while ( TRUE ) {
line = readLines(con, n = 1)
if ( length(line) == 0 ) {
break
}
print(line)
}
close(con)
}
Understand the risk of reading a line at memory too. Big files without line breaks can fill your memory too.
There are multiple methods for handling this problem.
My advice is to use the powerful Windows freeware console application SendEmail.
sendEmail.exe -f [email protected] -o message-file=body.txt -u subject message -t [email protected] -a attachment.zip -s smtp.gmail.com:446 -xu gmail.login -xp gmail.password
I think the simplest way to achieve your goal is this:
var str = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);
I'm unable to reproduce your problem but have you tried converting it to an integer first?
image_name_data['id'] = image_name_data['id'].astype(int).astype('str')
Then, regarding your more general question you could use map
(as in this answer). In your case:
image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)
Instead of turn off the csrf protection, it's better to add the following line of code into the form
<%= tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) %>
and if you're using form_for or form_tag to generate the form, then it will automatically add the above line of code in the form
For the date part:(month is 0-indexed while days are 1-indexed)
var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear());
for the time you'll want to create a function to test different situations and convert.
uh, how about just:
function IsString(obj) {
return obj !== undefined && obj != null && obj.toLowerCase !== undefined;
}
After further review many months later, this only guarantees obj
is an object that has the method or property name toLowerCase
defined. I am ashamed of my answer. Please see top-voted typeof
one.
http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.
It is nor php nor html it sounds like specific xml tag.
there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD')
and heredoc(<<<EOD)
strings
you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.
nowdoc strings will not expand variables just like single quotes.
ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
Using a single function with the possibility of custom unit of measure or formatted. Each time the function is called without parameters we restarted the initial time.
@ECHO OFF
ECHO.
ECHO DEMO timer function
ECHO --------------------
SET DELAY=4
:: First we call the function without any parameters to set the starting time
CALL:timer
:: We put some code we want to measure
ECHO.
ECHO Making some delay, please wait...
ECHO.
ping -n %DELAY% -w 1 127.0.0.1 >NUL
:: Now we call the function again with the desired parameters
CALL:timer elapsed_time
ECHO by Default : %elapsed_time%
CALL:timer elapsed_time "s"
ECHO in Seconds : %elapsed_time%
CALL:timer elapsed_time "anything"
ECHO Formatted : %elapsed_time% (HH:MM:SS.CS)
ECHO.
PAUSE
:: Elapsed Time Function
:: -----------------------------------------------------------------------
:: The returned value is in centiseconds, unless you enter the parameters
:: to be in another unit of measure or with formatted
::
:: Parameters:
:: <return> the returned value
:: [formatted] s (for seconds), m (for minutes), h (for hours)
:: anything else for formatted output
:: -----------------------------------------------------------------------
:timer <return> [formatted]
SetLocal EnableExtensions EnableDelayedExpansion
SET _t=%time%
SET _t=%_t::0=: %
SET _t=%_t:,0=, %
SET _t=%_t:.0=. %
SET _t=%_t:~0,2% * 360000 + %_t:~3,2% * 6000 + %_t:~6,2% * 100 + %_t:~9,2%
SET /A _t=%_t%
:: If we call the function without parameters is defined initial time
SET _r=%~1
IF NOT DEFINED _r (
EndLocal & SET TIMER_START_TIME=%_t% & GOTO :EOF
)
SET /A _t=%_t% - %TIMER_START_TIME%
:: In the case of wanting a formatted output
SET _f=%~2
IF DEFINED _f (
IF "%_f%" == "s" (
SET /A "_t=%_t% / 100"
) ELSE (
IF "%_f%" == "m" (
SET /A "_t=%_t% / 6000"
) ELSE (
IF "%_f%" == "h" (
SET /A "_t=%_t% / 360000"
) ELSE (
SET /A "_h=%_t% / 360000"
SET /A "_m=(%_t% - !_h! * 360000) / 6000"
SET /A "_s=(%_t% - !_h! * 360000 - !_m! * 6000) / 100"
SET /A "_cs=(%_t% - !_h! * 360000 - !_m! * 6000 - !_s! * 100)"
IF !_h! LSS 10 SET "_h=0!_h!"
IF !_m! LSS 10 SET "_m=0!_m!"
IF !_s! LSS 10 SET "_s=0!_s!"
IF !_cs! LSS 10 SET "_cs=0!_cs!"
SET "_t=!_h!:!_m!:!_s!.!_cs!"
SET "_t=!_t:00:=!"
)
)
)
)
EndLocal & SET %~1=%_t%
goto :EOF
A test with a delay of 94 sec
DEMO timer function
--------------------
Making some delay, please wait...
by Default : 9404
in Seconds : 94
Formatted : 01:34.05 (HH:MM:SS.CS)
Presione una tecla para continuar . . .
You can also use like below code.
<button style="position: absolute; right: 0;">Button</button>
Yes, cmake and make are different programs. cmake
is (on Linux) a Makefile generator (and Makefile-s are the files driving the make
utility). There are other Makefile generators (in particular configure and autoconf etc...). And you can find other build automation programs (e.g. ninja).
Enable Offline Work
Improve Gradle Performance by adding following code in gradle.properties
org.gradle.daemon=true
org.gradle.parallel=true
Step by step guide:http://www.viralandroid.com/2015/08/how-to-make-android-studio-fast.html
You can pass an ArrayList<E>
the same way, if the E
type is Serializable
.
You would call the putExtra (String name, Serializable value)
of Intent
to store, and getSerializableExtra (String name)
for retrieval.
Example:
ArrayList<String> myList = new ArrayList<String>();
intent.putExtra("mylist", myList);
In the other Activity:
ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("mylist");
simple is the best and works in every version.
if a>10:
value="b"
else:
value="c"
Hashtables/Dictionaries are O(1) performance, meaning that performance is not a function of size. That's important to know.
EDIT: In practice, the average time complexity for Hashtable/Dictionary<> lookups is O(1).
To elaborate on GoZoner's answer:
Your real issue here is that you are recursively calling your getter.
var x:Int
{
set
{
x = newValue * 2 // This isn't a problem
}
get {
return x / 2 // Here is your real issue, you are recursively calling
// your x property's getter
}
}
Like the code comment suggests above, you are infinitely calling the x property's getter, which will continue to execute until you get a EXC_BAD_ACCESS code (you can see the spinner in the bottom right corner of your Xcode's playground environment).
Consider the example from the Swift documentation:
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
Notice how the center computed property never modifies or returns itself in the variable's declaration.
simplest way without any intermediate list using list.index():
z = ['a', 'b', 'a', 'c', 'b', 'a', ]
[z[i] for i in range(len(z)) if i == z.index(z[i])]
>>>['a', 'b', 'c']
and you can also list the duplicates itself (may contain duplicates again as in the example):
[z[i] for i in range(len(z)) if not i == z.index(z[i])]
>>>['a', 'b', 'a']
or their index:
[i for i in range(len(z)) if not i == z.index(z[i])]
>>>[2, 4, 5]
or the duplicates as a list of 2-tuples of their index (referenced to their first occurrence only), what is the answer to the original question!!!:
[(i,z.index(z[i])) for i in range(len(z)) if not i == z.index(z[i])]
>>>[(2, 0), (4, 1), (5, 0)]
or this together with the item itself:
[(i,z.index(z[i]),z[i]) for i in range(len(z)) if not i == z.index(z[i])]
>>>[(2, 0, 'a'), (4, 1, 'b'), (5, 0, 'a')]
or any other combination of elements and indices....
Don't forget nullability.
ALTER TABLE <schemaName>.<tableName>
ALTER COLUMN <columnName> nvarchar(200) [NULL|NOT NULL]
Here is how I solved it, based on the answers here:
Connection conn = ConnectToDB(); //ConnectToDB establishes a connection to the database.
String sql = "INSERT INTO \"TableName\"" +
"(\"Column1\", \"Column2\",\"Column3\",\"Column4\")" +
"VALUES ('value1',value2, 'value3', 'value4') RETURNING
\"TableName\".\"TableId\"";
PreparedStatement prpState = conn.prepareStatement(sql);
ResultSet rs = prpState.executeQuery();
if(rs.next()){
System.out.println(rs.getInt(1));
}
In two way ssl the client asks for servers digital certificate and server ask for the same from the client. It is more secured as it is both ways, although its bit slow. Generally we dont follow it as the server doesnt care about the identity of the client, but a client needs to make sure about the integrity of server it is connecting to.
To aid in what has already been mentioned there is a very good overview of the Linux graphics stack at this blog: http://blog.mecheye.net/2012/06/the-linux-graphics-stack/
This explains X11/Wayland etc and how it all fits together. In addition to what has already been mentioned I think it's worth adding a bit about the following API's you can use for graphics in Linux:
Mesa - "Mesa is many things, but one of the major things it provides that it is most famous for is its OpenGL implementation. It is an open-source implementation of the OpenGL API."
Cairo - "cairo is a drawing library used either by applications like Firefox directly, or through libraries like GTK+, to draw vector shapes."
DRM (Direct Rendering Manager) - I understand this the least but its basically the kernel drivers that let you write graphics directly to framebuffer without going through X
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
Other than your IDE giving you hints when you pass null
to methods that expect the argument to not be null, there are further advantages:
This can help your code be more maintainable (since you do not need null
checks) and less error-prone.
This is more of an example where TABLOCK did not work for me and TABLOCKX did.
I have 2 sessions, that both use the default (READ COMMITTED) isolation level:
Session 1 is an explicit transaction that will copy data from a linked server to a set of tables in a database, and takes a few seconds to run. [Example, it deletes Questions] Session 2 is an insert statement, that simply inserts rows into a table that Session 1 doesn't make changes to. [Example, it inserts Answers].
(In practice there are multiple sessions inserting multiple records into the table, simultaneously, while Session 1 is running its transaction).
Session 1 has to query the table Session 2 inserts into because it can't delete records that depend on entries that were added by Session 2. [Example: Delete questions that have not been answered].
So, while Session 1 is executing and Session 2 tries to insert, Session 2 loses in a deadlock every time.
So, a delete statement in Session 1 might look something like this: DELETE tblA FROM tblQ LEFT JOIN tblX on ... LEFT JOIN tblA a ON tblQ.Qid = tblA.Qid WHERE ... a.QId IS NULL and ...
The deadlock seems to be caused from contention between querying tblA while Session 2, [3, 4, 5, ..., n] try to insert into tblA.
In my case I could change the isolation level of Session 1's transaction to be SERIALIZABLE. When I did this: The transaction manager has disabled its support for remote/network transactions.
So, I could follow instructions in the accepted answer here to get around it: The transaction manager has disabled its support for remote/network transactions
But a) I wasn't comfortable with changing the isolation level to SERIALIZABLE in the first place- supposedly it degrades performance and may have other consequences I haven't considered, b) didn't understand why doing this suddenly caused the transaction to have a problem working across linked servers, and c) don't know what possible holes I might be opening up by enabling network access.
There seemed to be just 6 queries within a very large transaction that are causing the trouble.
So, I read about TABLOCK and TabLOCKX.
I wasn't crystal clear on the differences, and didn't know if either would work. But it seemed like it would. First I tried TABLOCK and it didn't seem to make any difference. The competing sessions generated the same deadlocks. Then I tried TABLOCKX, and no more deadlocks.
So, in six places, all I needed to do was add a WITH (TABLOCKX).
So, a delete statement in Session 1 might look something like this: DELETE tblA FROM tblQ q LEFT JOIN tblX x on ... LEFT JOIN tblA a WITH (TABLOCKX) ON tblQ.Qid = tblA.Qid WHERE ... a.QId IS NULL and ...
Viewgroup inherits properties of views and does more with other views and viewgroup.
See the Android API: http://developer.android.com/reference/android/view/ViewGroup.html
You should set the src
attribute after the onload
event, f.ex:
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM before attaching the onload
event:
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
The function I used to perform the task, joining the upgrade made by schnaader is:
mysql_real_escape_string(
preg_replace_callback("/&#?[a-z0-9]+;/i", function($m) {
return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
}, strip_tags($row['cuerpo'])))
This function removes every html tag and html symbol, converted in UTF-8 ready to save in MySQL
Creating a project description should not be complicated.
I say:
Apache Camel is messaging technology glue with routing. It joins together messaging start and end points allowing the transference of messages from different sources to different destinations. For example: JMS -> JSON, HTTP -> JMS or funneling FTP -> JMS, HTTP -> JMS, JSON -> JMS
Wikipedia says:
Apache Camel is a rule-based routing and mediation engine which provides a Java object based implementation of the Enterprise Integration Patterns using an API (or declarative Java Domain Specific Language) to configure routing and mediation rules. The domain specific language means that Apache Camel can support type-safe smart completion of routing rules in your IDE using regular Java code without huge amounts of XML configuration files; though XML configuration inside Spring is also supported.
See? That wasn't hard was it?
If ASP.NET 4.0 is not registered with IIS
*****Use this step if u cant access using run command*****
Go to
C Drive
-->>windows
-->>Microsoft.Net
-->>Framework
-->>v4.0.30319
(Choose whatever framework to register with IIS me selecting Framework 4)-->>aspnet_regiis
(Double-click or right click & choose run as administrator)
This will actually be the correct answer:
function scrolled(event) {
const container = event.target.body
const {clientHeight, scrollHeight, scrollY: scrollTop} = container
if (clientHeight + scrollY >= scrollHeight) {
scrolledToBottom(event);
}
}
The reason for using the event
is up-to-date data, if you'll use a direct reference to the div you'll get outdated scrollY
and will fail to detect the position correctly.
additional way is to wrap it in a setTimeout
and wait till the data updates.
To set ANDROID_HOME environment on ubuntu 20.04 visit Ubuntu's snap store and install Android studio and then open
vim $HOME/.bashrc
And set the environment variables as follows:
export ANDROID_HOME=${HOME}/Android/Sdk
export PATH=${ANDROID_HOME}/tools:${PATH}
export PATH=${ANDROID_HOME}/emulator:${PATH}
export PATH=${ANDROID_HOME}/platform-tools:${PATH}
With recent versions of Android studio replace ANDROID_HOME with ANDROID_SDK_ROOT otherwise builds will complain that ANDROID_HOME is deprecated.
In my case, putting space after colon was wrong.
# Not work
curl -H Content-Type: application/json ~
# OK
curl -H Content-Type:application/json ~
Simple. Use splitlines()
L = open("myFile.txt", "r").read().splitlines();
for line in L:
process(line) # this 'line' will not have '\n' character at the end
My workarounds:
git fetch --depth=1
git checkout <branch_name>
if you don't have a local clone:
git clone --depth 1 -b <branch_name> <repo_url>
The problem with many answers here is that "\r\n\r\n"
can legitimately appear in the body of the html, so you can't be sure that you're splitting headers correctly.
It seems that the only way to store headers separately with one call to curl_exec
is to use a callback as is suggested above in https://stackoverflow.com/a/25118032/3326494
And then to (reliably) get just the body of the request, you would need to pass the value of the Content-Length
header to substr()
as a negative start value.
Two methods:
<div>
that is position: absolute;
before #main
and the same height as #main
, then apply the background-image and opacity: 0.2; filter: alpha(opacity=20);
.If the images are generated via an ASP Response.Write()
, make sure you don't call Response.Close();
. Chrome doesn't like it.
I was facing the problem in passing string value to string parameters in Ajax. After so much googling, i have come up with a custom solution as below.
var bar = 'xyz';
var calibri = 'no$libri';
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "http://nakolesah.ru/",
data: '{ foo: \'' + bar + '\', zoo: \'' + calibri + '\'}',
success: function(msg){
alert('wow'+msg);
},
});
Here, bar and calibri are two string variables and you can pass whatever string value to respective string parameters in web method.
On Xcode 6, you can just use \n even inside a string when using word wrap. It will work. So for example:
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, screenRect.size.width, 50)];
label.textAlignment = NSTextAlignmentCenter;
label.text = @"This will be on the first line\nfollowed by a line under it.";
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
You might want to consider refactoring that query instead of adding an arbitrarily long list of ids... You could use a range if the ids indeed follow the pattern in your example:
SELECT * FROM user WHERE id >= minValue AND id <= maxValue;
Another option is to add an inner select:
SELECT *
FROM user
WHERE id IN (
SELECT userId
FROM ForumThreads ft
WHERE ft.id = X
);
I had the same error, because I was trying to manipulate session variables inside a custom Session class.
I had to pass the current context (system.web.httpcontext.current) into the class, and then everything worked out fine.
MA
If you want to know if the user is accessing your app from facebook page tab or canvas check for the Signed Request. If you don't get it, probably the user is not accessing from facebook. To make sure confirm the signed_request fields structure and fields content.
With the php-sdk you can get the Signed Request like this:
$signed_request = $facebook->getSignedRequest();
You can read more about Signed Request here:
https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest/
and here:
https://developers.facebook.com/docs/reference/login/signed-request/
How about this. using the modulo operator
if(a%b==0)
{
System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
System.out.println("b is NOT a factor of a");
}
On input type=file add an event onchange="preview()"
For the function preview()
type:
thumb.src=URL.createObjectURL(event.target.files[0]);
Live example:
function preview() {
thumb.src=URL.createObjectURL(event.target.files[0]);
}
_x000D_
<form>
<input type="file" onchange="preview()">
<img id="thumb" src="" width="150px"/>
</form>
_x000D_
I ran into this problem and fixed it by closing the input and output streams before closing the socket. Now I can disconnect and connect again with no issues.
https://stackoverflow.com/a/3039807/5688612
In Kotlin:
fun disconnect() {
bluetoothSocket.inputStream.close()
bluetoothSocket.outputStream.close()
bluetoothSocket.close()
}
i dont know whether it is relevant to your issue, i got similar issue which i got solved by
1) In eclipse right click server and clean
if it still didnt work
2) export the project and delete the project create the project with same name and import the project and add the project to server and run.
In case you just need the existence of it you could also throw it off the screen with display: fixed; right: -1000px;
. It is useful when you need an input for copying to clipboard. :)
It means something like this:
std::vector<Movie *> movies;
Then you add to the vector as you read lines:
movies.push_back(new Movie(...));
Remember to delete all of the Movie*
objects once you are done with the vector.
To add to Blender's answer, you can disable SSL certificate validation for all requests using Session.verify = False
import requests
session = requests.Session()
session.verify = False
session.post(url='https://example.com', data={'bar':'baz'})
Note that urllib3
, (which Requests uses), strongly discourages making unverified HTTPS requests and will raise an InsecureRequestWarning
.
React Router v4 is fundamentally different from v3 (and earlier) and you cannot do browserHistory.push()
like you used to.
This discussion seems related if you want more info:
- Creating a new
browserHistory
won't work because<BrowserRouter>
creates its own history instance, and listens for changes on that. So a different instance will change the url but not update the<BrowserRouter>
.browserHistory
is not exposed by react-router in v4, only in v2.
Instead you have a few options to do this:
withRouter
high-order componentInstead you should use the withRouter
high order component, and wrap that to the component that will push to history. For example:
import React from "react";
import { withRouter } from "react-router-dom";
class MyComponent extends React.Component {
...
myFunction() {
this.props.history.push("/some/Path");
}
...
}
export default withRouter(MyComponent);
Check out the official documentation for more info:
You can get access to the
history
object’s properties and the closest<Route>
'smatch
via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as<Route>
render props:{ match, location, history }
.
context
APIUsing the context might be one of the easiest solutions, but being an experimental API it is unstable and unsupported. Use it only when everything else fails. Here's an example:
import React from "react";
import PropTypes from "prop-types";
class MyComponent extends React.Component {
static contextTypes = {
router: PropTypes.object
}
constructor(props, context) {
super(props, context);
}
...
myFunction() {
this.context.router.history.push("/some/Path");
}
...
}
Have a look at the official documentation on context:
If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.
If you insist on using context despite these warnings, try to isolate your use of context to a small area and avoid using the context API directly when possible so that it's easier to upgrade when the API changes.
If you know the white space is only due to spaces, you can use:
$string = str_replace(' ','',$string);
But if it could be due to space, tab...you can use:
$string = preg_replace('/\s+/','',$string);
You can take the first string, replace all the @
with vs
using str_replace
, then explode on vs
or vice versa.
.c1 {
height: unset;
}
The unset
value added in CSS3 also solves this problem and it's even more universal method than auto
or initial
because it sets to every CSS property its default value and additionally its default behawior relative to its parent.
Note that initial
value breaks aforementioned behavior.
From MDN:
Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not.
Probably working Perl solution, if the string is on one line:
my $NesteD ;
$NesteD = qr/ \{( [^{}] | (??{ $NesteD }) )* \} /x ;
if ( $Stringy =~ m/\b( \w+$NesteD )/x ) {
print "Found: $1\n" ;
}
HTH
EDIT: check:
And one more thing by Torsten Marek (who had pointed out correctly, that it's not a regex anymore):
IMO using the C++ reference for std::string
is a quick and short local optimization, while using passing by value could be (or not) a better global optimization.
So the answer is: it depends on circumstances:
const std::string &
. std::string
copy constructor behavior.If you have created the migrations, you could execute them in the Startup.cs as follows.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
}
...
This will create the database and the tables using your added migrations.
If you're not using Entity Framework Migrations, and instead just need your DbContext model created exactly as it is in your context class at first run, then you can use:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.EnsureCreated();
}
...
Instead.
If you need to delete your database prior to making sure it's created, call:
context.Database.EnsureDeleted();
Just before you call EnsureCreated()
Adapted from: http://docs.identityserver.io/en/latest/quickstarts/7_entity_framework.html?highlight=entity
map
, applymap
and ap
ply
: Context MattersFirst major difference: DEFINITION
map
is defined on Series ONLYapplymap
is defined on DataFrames ONLYapply
is defined on BOTHSecond major difference: INPUT ARGUMENT
map
accepts dict
s, Series
, or callableapplymap
and apply
accept callables onlyThird major difference: BEHAVIOR
map
is elementwise for Seriesapplymap
is elementwise for DataFramesapply
also works elementwise but is suited to more complex operations and aggregation. The behaviour and return value depends on the function.Fourth major difference (the most important one): USE CASE
map
is meant for mapping values from one domain to another, so is optimised for performance (e.g., df['A'].map({1:'a', 2:'b', 3:'c'})
)applymap
is good for elementwise transformations across multiple rows/columns (e.g., df[['A', 'B', 'C']].applymap(str.strip)
)apply
is for applying any function that cannot be vectorised (e.g., df['sentences'].apply(nltk.sent_tokenize)
)Footnotes
map
when passed a dictionary/Series will map elements based on the keys in that dictionary/Series. Missing values will be recorded as NaN in the output.
applymap
in more recent versions has been optimised for some operations. You will findapplymap
slightly faster thanapply
in some cases. My suggestion is to test them both and use whatever works better.
map
is optimised for elementwise mappings and transformation. Operations that involve dictionaries or Series will enable pandas to use faster code paths for better performance.Series.apply
returns a scalar for aggregating operations, Series otherwise. Similarly forDataFrame.apply
. Note thatapply
also has fastpaths when called with certain NumPy functions such asmean
,sum
, etc.
Use scipy:
import scipy;
a=[1,2,4];
print(scipy.mean(a));
Using curl:
curl -v \
-F "r=releases" \
-F "g=com.acme.widgets" \
-F "a=widget" \
-F "v=0.1-1" \
-F "p=tar.gz" \
-F "file=@./widget-0.1-1.tar.gz" \
-u myuser:mypassword \
http://localhost:8081/nexus/service/local/artifact/maven/content
You can see what the parameters mean here: https://support.sonatype.com/entries/22189106-How-can-I-programatically-upload-an-artifact-into-Nexus-
To make the permissions for this work, I created a new role in the admin GUI and I added two privileges to that role: Artifact Download and Artifact Upload. The standard "Repo: All Maven Repositories (Full Control)"-role is not enough. You won't find this in the REST API documentation that comes bundled with the Nexus server, so these parameters might change in the future.
On a Sonatype JIRA issue, it was mentioned that they "are going to overhaul the REST API (and the way it's documentation is generated) in an upcoming release, most likely later this year".
The maximum values do not depend on Eclipse, it depends on your OS (and obviously on the physical memory available).
You may want to take a look at this question: Max amount of memory per java process in Windows?
"abcdefgh..".IndexOf("d")
returns 3
In general returns first occurrence index, if not present returns -1
For dynamic values!
<div class="col-md-4" ng-repeat="(k, v) in tiposAcesso">
<label class="control-label">
<input type="radio" name="tipoAcesso" ng-model="userLogin.tipoAcesso" value="{{k}}" ng-change="changeTipoAcesso(k)" />
<span ng-bind="v"></span>
</label>
</div>
in controller
$scope.changeTipoAcesso = function(value) {
console.log(value);
};
Just a side note for similar problem (If we don't want to loop through):
How to lookup a dictionary using a variable key within Jinja template?
Here is an example:
{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}
It might be obvious. But we don't need curly braces within curly braces. Straight python syntax works. (I am posting because I was confusing to me...)
Alternatively, you can simply do
{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}
But it will spit an error when no key is found. So better to use get
in Jinja.
I figured out that in my case, my database was in different subnet than the subnet from where i was trying to access the db.
I prefer to use an extension method to get the scripts object:
public static IJavaScriptExecutor Scripts(this IWebDriver driver)
{
return (IJavaScriptExecutor)driver;
}
Used as this:
driver.Scripts().ExecuteScript("some script");
Well, you may try this '.*[0-9]'
If you use RecycleView, first you need more efford to setup. You need to give more time to setup simple Item onclick, border, touch event and other simple thing. But end product will be perfect.
So decision is yours. I suggest, if you design simple app like phonebook loading, where simple click of item is enough, you can implement listview. But if you design like social media home page with unlimited scrolling. Several different decoration between item, much control of individual item than use recycle view.
The port that the Admin button references is configurable. In the XAMPP install folder there is a xampp-control.ini
file. Changing the Apache entry under [ServicePorts]
will affect the url the Admin button opens.
[ServicePorts]
Apache=8080
I did a dynamic cell height of collection view. Here is git hub repo.
And, dig out why preferredLayoutAttributesFittingAttributes is called more than once. Actually, it will be called at least 3 times.
1st preferredLayoutAttributesFittingAttributes:
(lldb) po layoutAttributes
<UICollectionViewLayoutAttributes: 0x7fa405c290e0> index path: (<NSIndexPath: 0xc000000000000016>
{length = 2, path = 0 - 0}); frame = (15 12; 384 57.5);
(lldb) po self.collectionView
<UICollectionView: 0x7fa40606c800; frame = (0 57.6667; 384 0);
The layoutAttributes.frame.size.height is current status 57.5.
2nd preferredLayoutAttributesFittingAttributes:
(lldb) po layoutAttributes
<UICollectionViewLayoutAttributes: 0x7fa405c16370> index path: (<NSIndexPath: 0xc000000000000016>
{length = 2, path = 0 - 0}); frame = (15 12; 384 534.5);
(lldb) po self.collectionView
<UICollectionView: 0x7fa40606c800; frame = (0 57.6667; 384 0);
The cell frame height changed to 534.5 as our expected. But, the collection view still zero height.
3rd preferredLayoutAttributesFittingAttributes:
(lldb) po layoutAttributes
<UICollectionViewLayoutAttributes: 0x7fa403d516a0> index path: (<NSIndexPath: 0xc000000000000016>
{length = 2, path = 0 - 0}); frame = (15 12; 384 534.5);
(lldb) po self.collectionView
<UICollectionView: 0x7fa40606c800; frame = (0 57.6667; 384 477);
You can see the collection view height was changed from 0 to 477.
The behavior is similar to handle scroll:
1. Before self-sizing cell
2. Validated self-sizing cell again after other cells recalculated.
3. Did changed self-sizing cell
At beginning, I thought this method only call once. So I coded as the following:
CGRect frame = layoutAttributes.frame;
frame.size.height = frame.size.height + self.collectionView.contentSize.height;
UICollectionViewLayoutAttributes* newAttributes = [layoutAttributes copy];
newAttributes.frame = frame;
return newAttributes;
This line:
frame.size.height = frame.size.height + self.collectionView.contentSize.height;
will cause system call infinite loop and App crash.
Any size changed, it will validate all cells' preferredLayoutAttributesFittingAttributes again and again until every cells' positions (i.e frames) are no more change.
SQL>
SELECT interview.qtrcode QTR, interview.companyname "Company Name", interview.division Division
FROM interview
JOIN jobsdev.employer
ON (interview.companyname = employer.companyname AND employer.zipcode like '100%')
GROUP BY interview.qtrcode, interview.companyname, interview.division
ORDER BY interview.qtrcode;
If the you know the times will be less than an hour, you could just use the date()
or $date->format()
functions.
$minsandsecs = date('i:s',$numberofsecs);
This works because the system epoch time begins at midnight (on 1 Jan 1970, but that's not important for you).
If it's an hour or more but less than a day, you could output it in hours:mins:secs format with `
$hoursminsandsecs = date('H:i:s',$numberofsecs);
For more than a day, you'll need to use modulus to calculate the number of days, as this is where the start date of the epoch would become relevant.
Hope that helps.
A string can be converted to an array of characters by calling the ToCharArray
string's method.
var characters = stringValue.ToCharArray();
An object of type string[]
is not a string, but an array of strings. You cannot convert an array of strings to an array of characters by just calling a method like ToCharArray
. To be more correct there isn't any method in the .NET framework that does this thing. You could however declare an extension method to do this, but this is another discussion.
If your intention is to build an array of the characters that make up the strings you have in your array, you could do so by calling the ToCharArray
method on each string of your array.
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
I had the same problem, and resolved it. In my case it was error due to the non-proper format. Please check the first and last coordinates array in geometry coordinates they must be same then and only then it will work. Hope it may help you!
Drag and drop a Python file in the Ipython notebooks "home" notebooks table, click upload. This will create a new notebook with only one cell containing your .py file content
Else copy/paste from your favorite editor ;)
Alternate way: Dismount the drive (from settings/storage) and re-mount the sdcard also fixes the problem. (verify by moving a file from internal storage to sdcard) In any case, this simple method saved my butt this time :)
In this particular example, you can use:
#container:hover #cube {
background-color: yellow;
}
This example only works since cube
is a child of container
. For more complicated scenarios, you'd need to use different CSS, or use JavaScript.
Since the Grid solution hasn't been presented yet, here it is, with just two declarations for the parent element, if we take the height: 100%
and margin: 0
for granted:
html, body {height: 100%}_x000D_
_x000D_
body {_x000D_
display: grid; /* generates a block-level grid */_x000D_
align-content: space-between; /* places an even amount of space between each grid item, with no space at the far ends */_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
.content {_x000D_
background: lightgreen;_x000D_
/* demo / for default snippet window */_x000D_
height: 1em;_x000D_
animation: height 2.5s linear alternate infinite;_x000D_
}_x000D_
_x000D_
footer {background: lightblue}_x000D_
_x000D_
@keyframes height {to {height: 250px}}
_x000D_
<div class="content">Content</div>_x000D_
<footer>Footer</footer>
_x000D_
The items are evenly distributed within the alignment container along the cross axis. The spacing between each pair of adjacent items is the same. The first item is flush with the main-start edge, and the last item is flush with the main-end edge.
It just happened to me that different projects were referencing different copies of the same dll. I made sure all referenced the same file on disk, and the error disappeared as I expected.
Perhaps to late to the party, but you could just do the following:
const set = new Set(['a', 'b']);
const values = set.values();
const array = Array.from(values);
This should work without problems in browsers that have support for ES6 or if you have a shim that correctly polyfills the above functionality.
Edit: Today you can just use what @c69 suggests:
const set = new Set(['a', 'b']);
const array = [...set]; // or Array.from(set)
SELECT id FROM tbl
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.
IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).
A Double
in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double
object.
Locate the following file
C:\Users\
[your name]\.android\adb_usb.ini
And make the following changes:
# ANDROID 3RD PARTY USB VENDOR ID LIST -- DO NOT EDIT.
# USE 'android update adb' TO GENERATE.
# 1 USB VENDOR ID PER LINE.
0x2207
I added 0x2207
to the file. This number is part of the hardware id, which can be found under the device's hardware information.
Mine was:
USB\VID_2207&PID_0010&MI_01
(I tried executing android update adb
, but it did nothing.)
Even though this is fairly an old question, I have my 2 cents to share.
Like the zipball
link pointed by various answers here, There is a tarball
link as well which downloads the content of the git repository in tar.gz
format.
curl -L http://github.com/zoul/Finch/tarball/master/
Git also provides a different URL pattern where you can simply append the type of file you want to download at the end of url. This way is better if you want to process these urls in a batch or bash script.
curl -L http://github.com/zoul/Finch/archive/master.zip
curl -L http://github.com/zoul/Finch/archive/master.tar.gz
Replace master
with the commit-hash
or the branch-name
in the above urls like below.
curl -L http://github.com/zoul/Finch/archive/cfeb671ac55f6b1aba6ed28b9bc9b246e0e.zip
curl -L http://github.com/zoul/Finch/archive/cfeb671ac55f6b1aba6ed28b9bc9b246e0e.tar.gz
curl -L http://github.com/zoul/Finch/archive/your-branch-name.zip
curl -L http://github.com/zoul/Finch/archive/your-branch-name.tar.gz
function showstuff(boxid){
document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />
This will help you, I think.
This is what a constant expression in Java looks like:
package com.mycompany.mypackage;
public class MyLinks {
// constant expression
public static final String GUESTBOOK_URL = "/guestbook";
}
You can use it with annotations as following:
import com.mycompany.mypackage.MyLinks;
@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
// ...
}
If you import the module (.py) file you are creating now from another python script it will not execute the code within
if __name__ == '__main__':
...
If you run the script directly from the console, it will be executed.
Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.
This is expanded upon a little more at python.berkely.edu
You can actually still use ".css" and apply css transitions to the div being affected. So continue using ".css" and add the below styles to your stylesheet for "#hfont1". Since ".css" allows for a lot more properties than ".animate", this is always my preferred method.
#hfont1 {
-webkit-transition: width 0.4s;
transition: width 0.4s;
}
use as at end of query
Select * into #temp (select * from table1,table2) as temp_table
Excel 2003, doesn't included 1M row features, Introduced in 2007 onwards.
In Excel2007, save as "normal" Excel file, not a backwards compatible one.
You may have to close and re-open Excel to get the full 1M rows
Thilip
Changed to:
SELECT FORMAT(SA.[RequestStartDate],'dd/MM/yyyy') as 'Service Start Date', SA.[RequestEndDate] as 'Service End Date', FROM (......)SA WHERE......
Have no idea which SQL engine you are using, for other SQL engine, CONVERT can be used in SELECT statement to change the format in the form you needed.
None of these did exactly what I needed, to force 2 d.p. and round up as 0.005 -> 0.01
Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p.
then rounding to ensure we do not have more than 2 d.p.
Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)
6.665m.ToString() -> "6.67"
6.6m.ToString() -> "6.60"
It should be noted that the documentation recommends using a Layout
rather than Canvas.drawText
directly. My full answer about using a StaticLayout
is here, but I will provide a summary below.
String text = "This is some text.";
TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);
int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);
Here is a fuller example in the context of a custom view:
public class MyView extends View {
String mText = "This is some text.";
TextPaint mTextPaint;
StaticLayout mStaticLayout;
// use this constructor if creating MyView programmatically
public MyView(Context context) {
super(context);
initLabelView();
}
// this constructor is used when created from xml
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initLabelView();
}
private void initLabelView() {
mTextPaint = new TextPaint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
mTextPaint.setColor(0xFF000000);
// default to a single line of text
int width = (int) mTextPaint.measureText(mText);
mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
// New API alternate
//
// StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
// .setAlignment(Layout.Alignment.ALIGN_NORMAL)
// .setLineSpacing(1, 0) // multiplier, add
// .setIncludePad(false);
// mStaticLayout = builder.build();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Tell the parent layout how big this view would like to be
// but still respect any requirements (measure specs) that are passed down.
// determine the width
int width;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
width = widthRequirement;
} else {
width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
if (widthMode == MeasureSpec.AT_MOST) {
if (width > widthRequirement) {
width = widthRequirement;
// too long for a single line so relayout as multiline
mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
}
}
}
// determine the height
int height;
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
if (heightMode == MeasureSpec.EXACTLY) {
height = heightRequirement;
} else {
height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(height, heightRequirement);
}
}
// Required call: set width and height
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// do as little as possible inside onDraw to improve performance
// draw the text on the canvas after adjusting for padding
canvas.save();
canvas.translate(getPaddingLeft(), getPaddingTop());
mStaticLayout.draw(canvas);
canvas.restore();
}
}
Adding to Chris Gong's answer about VS2017/2019 above (I don't yet have comments permission).
If VS 2019 Build Tools are installed rather than the full Visual Studio then file paths are slightly different. VCTargetsPath should then be
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\
Also note the terminating backslash - required at least in my case (TFS2017, VS2019 Build tools). Corresponding change to the PATH entry as well.
This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs
SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.
And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.
This is the fix we did
<listener>
<listener-class>
net.sf.ehcache.constructs.web.ShutdownListener
</listener-class>
</listener>
So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.
Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html
There is an Android library called Android Design Support Library that's a handy library where you can find of all of those Material fancy design things that the Material documentation presents without telling you how to do them.
It's well presented in this Android Blog post. The "Collapsing Toolbar" in particular is what you're looking for.
One thing that wasn't mentioned completely (although @BlooB kinda mentioned it) is that map returns a map object NOT a list. This is a big difference when it comes to time performance on initialization and iteration. Consider these two tests.
import time
def test1(iterable):
a = time.clock()
map(str, iterable)
a = time.clock() - a
b = time.clock()
[ str(x) for x in iterable ]
b = time.clock() - b
print(a,b)
def test2(iterable):
a = time.clock()
[ x for x in map(str, iterable)]
a = time.clock() - a
b = time.clock()
[ str(x) for x in iterable ]
b = time.clock() - b
print(a,b)
test1(range(2000000)) # Prints ~1.7e-5s ~8s
test2(range(2000000)) # Prints ~9s ~8s
As you can see initializing the map function takes almost no time at all. However iterating through the map object takes longer than simply iterating through the iterable. This means that the function passed to map() is not applied to each element until the element is reached in the iteration. If you want a list use list comprehension. If you plan to iterate through in a for loop and will break at some point, then use map.
the easiest way in my opinion, this: you edit you main postgres config file: pg_hba.conf there you have to add the following line:
host <you_db_name> <you_db_owner> 127.0.0.1/32 trust
and after this you need start you cron thus:
pg_dump -h 127.0.0.1 -U <you_db_user> <you_db_name> | gzip > /backup/db/$(date +%Y-%m-%d).psql.gz
and it worked without password
On windows 10
If you wanna close it open command prompt with work with admin. Write NET STOP MySQL80
. Its done. If you wanna open again so you must write NET START MySQL80
If you do not want it to be turned on automatically when not in use, it automatically runs when the computer is turned on and consumes some ram.
Open services.msc find Mysql80 , look at properties and turn start type manuel or otomaticly again as you wish.
This worked fine with me url:http://example.com/rest/muqsith/get-file?filePath=C:\Users\I066807\Desktop\test.xml
@GET
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
@Path("/get-file")
public Response getFile(@Context HttpServletRequest request){
String filePath = request.getParameter("filePath");
if(filePath != null && !"".equals(filePath)){
File file = new File(filePath);
StreamingOutput stream = null;
try {
final InputStream in = new FileInputStream(file);
stream = new StreamingOutput() {
public void write(OutputStream out) throws IOException, WebApplicationException {
try {
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
};
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return Response.ok(stream).header("content-disposition","attachment; filename = "+file.getName()).build();
}
return Response.ok("file path null").build();
}
On Unix you can use valgrind
to find issues. It's free and powerful. If you'd rather do it yourself you can overload the new
and delete
operators to set up a configuration where you have 1 byte with 0xDEADBEEF
before and after each new object. Then track what happens at each iteration. This can fail to catch everything (you aren't guaranteed to even touch those bytes) but it has worked for me in the past on a Windows platform.
The answer by Pomber is acceptable, however I'm not a big fan of creating new objects repeatedly. The best solutions are always the ones that try to mitigate memory hog. Yes, there is auto garbage collection but memory conservation in a mobile device falls within the confines of best practice. The code below updates a TextView in a service.
TextViewUpdater textViewUpdater = new TextViewUpdater();
Handler textViewUpdaterHandler = new Handler(Looper.getMainLooper());
private class TextViewUpdater implements Runnable{
private String txt;
@Override
public void run() {
searchResultTextView.setText(txt);
}
public void setText(String txt){
this.txt = txt;
}
}
It can be used from anywhere like this:
textViewUpdater.setText("Hello");
textViewUpdaterHandler.post(textViewUpdater);
Just to add to the answer for people trying to find class names within inline SVG elements.
Change the hasCLass()
function to:
function hasClass(element, cls) {
return (' ' + element.getAttribute('class') + ' ').indexOf(' ' + cls + ' ') > -1;
}
Instead of using the className
property you'll need to use the getAttribute()
method to grab the class name.
I was developing for .NET core 2.1 using log4net 2.0.8 and found NealWalters code moans about 0 arguments for XmlConfigurator.Configure(). I found a solution by Matt Watson here
log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
To remove an element from an array, just do:
array.splice(index, 1);
In your case:
removePeople(e) {
var array = [...this.state.people]; // make a separate copy of the array
var index = array.indexOf(e.target.value)
if (index !== -1) {
array.splice(index, 1);
this.setState({people: array});
}
},
Works for me:
List<Item> list = Task.Run(() => manager.GetList()).Result;
in this way it is not necessary to mark the method with async in the call.
In my case port 8080 are already use by my local xampp server during oracle installation software check un used port like pop window appear for me
so for me url is http://127.0.0.1:8081/apex/f?p=4950:1:4076881202565564
Here is a simple approach based on @benmcdonald and others, more than one line though...
let K = [];_x000D_
for (i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {_x000D_
K.push(String.fromCharCode(i))_x000D_
};_x000D_
console.log(K);
_x000D_
Note: your text must be larger than the container box for the following to marquee:
android:ellipsize="marquee"
You have to change from wb to w:
def __init__(self):
self.myCsv = csv.writer(open('Item.csv', 'wb'))
self.myCsv.writerow(['title', 'link'])
to
def __init__(self):
self.myCsv = csv.writer(open('Item.csv', 'w'))
self.myCsv.writerow(['title', 'link'])
After changing this, the error disappears, but you can't write to the file (in my case). So after all, I don't have an answer?
Source: How to remove ^M
Changing to 'rb' brings me the other error: io.UnsupportedOperation: write
<video width="320" height="240" autoplay="autoplay">
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
You could use a recursive scalar function:-
set nocount on
create table location (
id int,
name varchar(50),
parent int
)
insert into location values
(1,'france',null),
(2,'paris',1),
(3,'belleville',2),
(4,'lyon',1),
(5,'vaise',4),
(6,'united kingdom',null),
(7,'england',6),
(8,'manchester',7),
(9,'fallowfield',8),
(10,'withington',8)
go
create function dbo.breadcrumb(@child int)
returns varchar(1024)
as begin
declare @returnValue varchar(1024)=''
declare @parent int
select @returnValue+=' > '+name,@parent=parent
from location
where id=@child
if @parent is not null
set @returnValue=dbo.breadcrumb(@parent)+@returnValue
return @returnValue
end
go
declare @location int=1
while @location<=10 begin
print dbo.breadcrumb(@location)+' >'
set @location+=1
end
produces:-
> france >
> france > paris >
> france > paris > belleville >
> france > lyon >
> france > lyon > vaise >
> united kingdom >
> united kingdom > england >
> united kingdom > england > manchester >
> united kingdom > england > manchester > fallowfield >
> united kingdom > england > manchester > withington >
Go to the Preferences menu command under menu Settings, and select Language Menu/Tab Settings, depending on your version. Earlier versions use Tab Settings. Later versions use Language. Click the Replace with space check box. Set the size to 4.
See documentation: http://docs.notepad-plus-plus.org/index.php/Built-in_Languages#Tab_settings
var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
if (c.hasOwnProperty(i)) count++;
}
alert(count);
There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.
In manifest.xml, select activity which u wanna start e set this informations:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:
In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75
Doing some rough math:
75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB
So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.
If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.
The problem is in the Eclipse Maven support, the related question is here.
Under Eclipse, the java.home
variable is set to the JRE that was used to start Eclipse, not the build JRE. The default system JRE from C:\Program Files
doesn't include the JDK so tools.jar
is not being found.
To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to eclipse.ini
(before -vmargs
!):
-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll
Then refresh the Maven dependencies (Alt-F5) (Just refreshing the project isn't sufficient).
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
When you select a radio button and click on a submit button, you need to handle the submission of any selected values in your php code using $_POST[]
For example:
if your radio button is:
<input type="radio" name="rdb" value="male"/>
then in your php code you need to use:
$rdb_value = $_POST['rdb'];
The problem is that if you try to write a <table>
or a <tr>
or <td>
tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.
Instead of writing your table line by line, concatenate your table into a variable and insert it once created:
<script language="javascript" type="text/javascript">
<!--
var myArray = new Array();
myArray[0] = 1;
myArray[1] = 2.218;
myArray[2] = 33;
myArray[3] = 114.94;
myArray[4] = 5;
myArray[5] = 33;
myArray[6] = 114.980;
myArray[7] = 5;
var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";
myTable+="<tr><td style='width: 100px; '>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td></tr>";
for (var i=0; i<8; i++) {
myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
myArray[i] = myArray[i].toFixed(3);
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
}
myTable+="</table>";
document.write( myTable);
//-->
</script>
If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:
<div id="tablePrint"> </div>
And in JS instead of document.write(myTable)
use the following code:
document.getElementById('tablePrint').innerHTML = myTable;
Try this it will work --
if($('#EventStartTimeMin').val() === " ") {
alert("Please enter start time!");
}
if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter secondary_y=True
, like this:
df.A.plot(label="Points", legend=True)
df.B.plot(secondary_y=True, label="Comments", legend=True)
This would look something like below:
You can do few more things as well. Take a look at Pandas plotting doc.
I guess you forgot .btn-primary:focus
property and comma after .btn-primary
You also can use less and redefine some colors in variables.less file
With this in mind your code will be look like this:
.btn-primary,_x000D_
.btn-primary:hover,_x000D_
.btn-primary:active,_x000D_
.btn-primary:visited,_x000D_
.btn-primary:focus {_x000D_
background-color: #8064A2;_x000D_
border-color: #8064A2;_x000D_
}
_x000D_
The Bitwise complement operator(~) is a unary operator.
It works as per the following methods
First it converts the given decimal number to its corresponding binary value.That is in case of 2 it first convert 2 to 0000 0010 (to 8 bit binary number).
Then it converts all the 1 in the number to 0,and all the zeros to 1;then the number will become 1111 1101.
that is the 2's complement representation of -3.
In order to find the unsigned value using complement,i.e. simply to convert 1111 1101 to decimal (=4294967293) we can simply use the %u during printing.
z-index
property enables you to take your control at front. the bigger number you set the upper your element you get.
position
property should be relative
because position of html-element
should be position relatively against other controls in all dimensions.
element.style {
position:relative;
z-index:1000; //change your number as per elements lies on your page.
}
just to add a detail to what Tamlyn wrote,
instead of
$('form').get(0).setAttribute('action', 'baz'); //this works
$('form')[0].setAttribute('action', 'baz');
works equally well
The following script uses PsExec to connect to another Windows Session so it works even when connected via Remote Desktop Service.
I wrote a small batch script for Java 8 (using PsExec
and jcmd
) named jvmdump.bat
, which dumps the threads, heap, system properties, and JVM args.
:: set the paths for your environment
set PsExec=C:\Apps\SysInternals\PsExec.exe
set JAVA_HOME=C:\Apps\Java\jdk1.8.0_121
set DUMP_DIR=C:\temp
@echo off
set PID=%1
if "%PID%"=="" (
echo usage: jvmdump.bat {pid}
exit /b
)
for /f "tokens=2,3,4 delims=/ " %%f in ('date /t') do set timestamp_d=%%h%%g%%f
for /f "tokens=1,2 delims=: " %%f in ('time /t') do set timestamp_t=%%f%%g
set timestamp=%timestamp_d%%timestamp_t%
echo datetime is: %timestamp%
echo ### Version >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
%PsExec% -s %JAVA_HOME%\bin\jcmd.exe %PID% VM.version >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
echo. >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
echo ### Uptime >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
%PsExec% -s %JAVA_HOME%\bin\jcmd.exe %PID% VM.uptime >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
echo. >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
echo ### Command >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
%PsExec% -s %JAVA_HOME%\bin\jcmd.exe %PID% VM.command_line >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
echo. >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
echo ### Flags >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
%PsExec% -s %JAVA_HOME%\bin\jcmd.exe %PID% VM.flags >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
echo. >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
echo ### Properties >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
%PsExec% -s %JAVA_HOME%\bin\jcmd.exe %PID% VM.system_properties >>"%DUMP_DIR%\%PID%-%timestamp%-jvm.log"
%PsExec% -s %JAVA_HOME%\bin\jcmd.exe %PID% Thread.print -l >"%DUMP_DIR%\%PID%-%timestamp%-threads.log"
%PsExec% -s %JAVA_HOME%\bin\jcmd.exe %PID% GC.heap_dump "%DUMP_DIR%\%PID%-%timestamp%-heap.hprof"
echo Dumped to %DUMP_DIR%
It must be run in the same Windows session of the user that started the JVM, so if you connect through Remote Desktop you might need to launch a command prompt in Session 0
and run it from there. e.g.
%PsExec% -s -h -d -i 0 cmd.exe
This will prompt you (click the taskbar icon at the bottom) to View the message
in the interactive session, which will take you to the new console in the other session from which you can run the jvmdump.bat
script.
In HPUX ( hp UNIX)
Please install the md5sum package on your UNIX machine for example, if there is a file called a.txt
shell > md5sum a.txt
System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();
Substitute the right encoding above: e.g.
System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();
When you select a column with type ZEROFILL
it pads the displayed value of the field with zeros up to the display width specified in the column definition. Values longer than the display width are not truncated. Note that usage of ZEROFILL
also implies UNSIGNED
.
Using ZEROFILL
and a display width has no effect on how the data is stored. It affects only how it is displayed.
Here is some example SQL that demonstrates the use of ZEROFILL
:
CREATE TABLE yourtable (x INT(8) ZEROFILL NOT NULL, y INT(8) NOT NULL);
INSERT INTO yourtable (x,y) VALUES
(1, 1),
(12, 12),
(123, 123),
(123456789, 123456789);
SELECT x, y FROM yourtable;
Result:
x y
00000001 1
00000012 12
00000123 123
123456789 123456789
In my case I needed a list of prefixes
colsToScale=["production", "test", "development"]
dc[dc.columns[dc.columns.str.startswith(tuple(colsToScale))]]
profilage bas� sur l'analyse de l'esprit
(french)
should be translated as:
profilage basé sur l'analyse de l'esprit
so, in this case �
= é
Date and time formats are well described below
SimpleDateFormat (Java Platform SE 7) - Date and Time Patterns
There could be n
Number of formats you can possibly make. ex - dd/MM/yyyy
or YYYY-'W'ww-u
or you can mix and match the letters to achieve your required pattern. Pattern letters are as follow.
G
- Era designator (AD)y
- Year (1996; 96)Y
- Week Year (2009; 09)M
- Month in year (July; Jul; 07)w
- Week in year (27)W
- Week in month (2)D
- Day in year (189)d
- Day in month (10)F
- Day of week in month (2)E
- Day name in week (Tuesday; Tue)u
- Day number of week (1 = Monday, ..., 7 = Sunday)a
- AM/PM markerH
- Hour in day (0-23)k
- Hour in day (1-24)K
- Hour in am/pm (0-11)h
- Hour in am/pm (1-12)m
- Minute in hour (30)s
- Second in minute (55)S
- Millisecond (978)z
- General time zone (Pacific Standard Time; PST; GMT-08:00)Z
- RFC 822 time zone (-0800)X
- ISO 8601 time zone (-08; -0800; -08:00)To parse:
2000-01-23T04:56:07.000+0000
Use:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
It worked for me to add a class name to the input and then apply CSS rules to that:
<input type="text" name="product" class="product" />
<style>
input[value=""].product {
display: none;
}
</style>
I wanted to clarify some more use between the ;
and the /
In SQLPLUS:
;
means "terminate the current statement, execute it and store it to the SQLPLUS buffer"<newline>
after a D.M.L. (SELECT, UPDATE, INSERT,...) statement or some types of D.D.L (Creating Tables and Views) statements (that contain no ;
), it means, store the statement to the buffer but do not run it./
after entering a statement into the buffer (with a blank <newline>
) means "run the D.M.L. or D.D.L. or PL/SQL in the buffer.RUN
or R
is a sqlsplus command to show/output the SQL in the buffer and run it. It will not terminate a SQL Statement./
during the entering of a D.M.L. or D.D.L. or PL/SQL means "terminate the current statement, execute it and store it to the SQLPLUS buffer"NOTE: Because ;
are used for PL/SQL to end a statement ;
cannot be used by SQLPLUS to mean "terminate the current statement, execute it and store it to the SQLPLUS buffer" because we want the whole PL/SQL block to be completely in the buffer, then execute it. PL/SQL blocks must end with:
END;
/
I recommend OTRS, its very easily customizable, and we also use it for hundreds of employees (University).
Add the separator to the li
background and make sure the link doesn't expand to cover the separator, which means the separator won't be click-able.
Do not access or modify the collection in the Comparator
. The comparator should be used only to determine which object is comes before another. The two objects that are to be compared are supplied as arguments.
Date
itself is comparable, so, using generics:
class MovieComparator implements Comparator<Movie> {
public int compare(Movie m1, Movie m2) {
//possibly check for nulls to avoid NullPointerException
return m1.getDate().compareTo(m2.getDate());
}
}
And do not instantiate the comparator on each sort. Use:
private static final MovieComparator comparator = new MovieComparator();
Please stop all services MySQL with following command /etc/init.d/mysqld stop After it use this
mysqld_safe --skip-grant-tables
its may work properly
You seem to be asking, "If I can rewrite a RIGHT OUTER JOIN
using LEFT OUTER JOIN
syntax then why have a RIGHT OUTER JOIN
syntax at all?" I think the answer to this question is, because the designers of the language didn't want to place such a restriction on users (and I think they would have been criticized if they did), which would force users to change the order of tables in the FROM
clause in some circumstances when merely changing the join type.
I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is very slightly more accurate, I wish I could come up with a better way to generate "months ago" that didn't seem too over-engineered.
I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected).
For the below code PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago) returns the relative time message (e.g. "yesterday").
public class RelativeTimeRange : IComparable
{
public TimeSpan UpperBound { get; set; }
public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta);
public RelativeTimeTextDelegate MessageCreator { get; set; }
public int CompareTo(object obj)
{
if (!(obj is RelativeTimeRange))
{
return 1;
}
// note that this sorts in reverse order to the way you'd expect,
// this saves having to reverse a list later
return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound);
}
}
public class PrintRelativeTime
{
private static List<RelativeTimeRange> timeRanges;
static PrintRelativeTime()
{
timeRanges = new List<RelativeTimeRange>{
new RelativeTimeRange
{
UpperBound = TimeSpan.FromSeconds(1),
MessageCreator = (delta) =>
{ return "one second ago"; }
},
new RelativeTimeRange
{
UpperBound = TimeSpan.FromSeconds(60),
MessageCreator = (delta) =>
{ return delta.Seconds + " seconds ago"; }
},
new RelativeTimeRange
{
UpperBound = TimeSpan.FromMinutes(2),
MessageCreator = (delta) =>
{ return "one minute ago"; }
},
new RelativeTimeRange
{
UpperBound = TimeSpan.FromMinutes(60),
MessageCreator = (delta) =>
{ return delta.Minutes + " minutes ago"; }
},
new RelativeTimeRange
{
UpperBound = TimeSpan.FromHours(2),
MessageCreator = (delta) =>
{ return "one hour ago"; }
},
new RelativeTimeRange
{
UpperBound = TimeSpan.FromHours(24),
MessageCreator = (delta) =>
{ return delta.Hours + " hours ago"; }
},
new RelativeTimeRange
{
UpperBound = TimeSpan.FromDays(2),
MessageCreator = (delta) =>
{ return "yesterday"; }
},
new RelativeTimeRange
{
UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)),
MessageCreator = (delta) =>
{ return delta.Days + " days ago"; }
},
new RelativeTimeRange
{
UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)),
MessageCreator = (delta) =>
{ return "one month ago"; }
},
new RelativeTimeRange
{
UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)),
MessageCreator = (delta) =>
{ return (int)Math.Floor(delta.TotalDays / 30) + " months ago"; }
},
new RelativeTimeRange
{
UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)),
MessageCreator = (delta) =>
{ return "one year ago"; }
},
new RelativeTimeRange
{
UpperBound = TimeSpan.MaxValue,
MessageCreator = (delta) =>
{ return (int)Math.Floor(delta.TotalDays / 365.24D) + " years ago"; }
}
};
timeRanges.Sort();
}
public static string GetRelativeTimeMessage(TimeSpan ago)
{
RelativeTimeRange postRelativeDateRange = timeRanges[0];
foreach (var timeRange in timeRanges)
{
if (ago.CompareTo(timeRange.UpperBound) <= 0)
{
postRelativeDateRange = timeRange;
}
}
return postRelativeDateRange.MessageCreator(ago);
}
}
Precision, Scale, and Length in the SQL Server 2000 documentation reads:
Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.
The rubocop gem contributors propose in their Ruby Style Guide:
Prefer alias when aliasing methods in lexical class scope as the resolution of self in this context is also lexical, and it communicates clearly to the user that the indirection of your alias will not be altered at runtime or by any subclass unless made explicit.
class Westerner
def first_name
@names.first
end
alias given_name first_name
end
Always use alias_method when aliasing methods of modules, classes, or singleton classes at runtime, as the lexical scope of alias leads to unpredictability in these cases
module Mononymous
def self.included(other)
other.class_eval { alias_method :full_name, :given_name }
end
end
class Sting < Westerner
include Mononymous
end
If you want to check any/all of multiple columns for a value, you can do:
df[(df[['HomeTeam', 'AwayTeam']] == 'Fulham').any(axis=1)]
In my case I had a float value expected where xml had a null value so be sure to search for float and int data type in your xsd map
Alternatively, you could use the jQuery 1.2 inArray function, which should work across browsers:
jQuery.inArray( value, array [, fromIndex ] )
In Java you can use GET
which shows requested data on URL.But POST
method cannot , because POST
has body but GET
donot have body.
If using XML configuration you can use
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security">
<security:http>
<security:headers>
<security:frame-options disabled="true"></security:frame-options>
</security:headers>
</security:http>
</beans>
You can create an XML file in the drawable folder. Call it, for example, shape.xml
In shape.xml
:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid
android:color="#888888" >
</solid>
<stroke
android:width="2dp"
android:color="#C4CDE0" >
</stroke>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" >
</padding>
<corners
android:radius="11dp" >
</corners>
</shape>
The <corner>
tag is for your specific question.
Make changes as required.
And in your whatever_layout_name.xml
:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="5dp"
android:background="@drawable/shape" >
</LinearLayout>
This is what I usually do in my apps. Hope this helps....
SELECT Subject, CONVERT(varchar(10),DeliveryDate) as DeliveryDate
from Email_Administration
where MerchantId =@ MerchantID
The choosen answer has a bug.
Following is the correct code:
def addressInNetwork(ip, net_n_bits):
ipaddr = struct.unpack('<L', socket.inet_aton(ip))[0]
net, bits = net_n_bits.split('/')
netaddr = struct.unpack('<L', socket.inet_aton(net))[0]
netmask = ((1L << int(bits)) - 1)
return ipaddr & netmask == netaddr & netmask
Note: ipaddr & netmask == netaddr & netmask
instead of ipaddr & netmask == netmask
.
I also replace ((2L<<int(bits)-1) - 1)
with ((1L << int(bits)) - 1)
, as the latter seems more understandable.
In Bootstrap 4, there is a new utility known as .mx-auto
. You just need to specify the width of the centered element.
Ref: http://v4-alpha.getbootstrap.com/utilities/spacing/#horizontal-centering
Diffferent from Bass Jobsen's answer, which is a relative center to the elements on both ends, the following example is absolute centered.
Here's the HTML:
<nav class="navbar bg-faded">
<div class="container">
<ul class="nav navbar-nav pull-sm-left">
<li class="nav-item">
<a class="nav-link" href="#">Link 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 3</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 4</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-logo mx-auto">
<li class="nav-item">
<a class="nav-link" href="#">Brand</a>
</li>
</ul>
<ul class="nav navbar-nav pull-sm-right">
<li class="nav-item">
<a class="nav-link" href="#">Link 5</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link 6</a>
</li>
</ul>
</div>
</nav>
And CSS:
.navbar-logo {
width: 90px;
}