Simple answer:A grammar is said to be an LL(1),if the associated LL(1) parsing table has atmost one production in each table entry.
Take the simple grammar A -->Aa|b.[A is non-terminal & a,b are terminals]
then find the First and follow sets A.
First{A}={b}.
Follow{A}={$,a}.
Parsing table for Our grammar.Terminals as columns and Nonterminal S as a row element.
a b $
--------------------------------------------
S | A-->a |
| A-->Aa. |
--------------------------------------------
As [S,b] contains two Productions there is a confusion as to which rule to choose.So it is not LL(1).
Some simple checks to see whether a grammar is LL(1) or not. Check 1: The Grammar should not be left Recursive. Example: E --> E+T. is not LL(1) because it is Left recursive. Check 2: The Grammar should be Left Factored.
Left factoring is required when two or more grammar rule choices share a common prefix string. Example: S-->A+int|A.
Check 3:The Grammar should not be ambiguous.
These are some simple checks.
I was having "(...) unable to handle this request. http error 500" and found out it was from a require_once that was working locally, on a windows machine, with backslash (\) as separator for directories but when i uploaded to my server it stopped working. I changed it to forward slash (/) and now is ok.
require_once ( 'cards\cards.php' ); // **http error 500**
require_once ( 'cards/cards.php' ); // OK
This worked for me. const clear = (event) =>{event.target.value = [ ];} clear("input_id");
.list-inline class in bootstrap is a Inline Unordered List.
If you want to create a horizontal menu using ordered or unordered list you need to place all list items in a single line i.e. side by side. You can do this by simply applying the class
<div class="list-inline">
<a href="#" class="list-inline-item">First item</a>
<a href="#" class="list-inline-item">Secound item</a>
<a href="#" class="list-inline-item">Third item</a>
</div>
You can't exclude patterns with the glob
function, globs only allow for inclusion patterns. Globbing syntax is very limited (even a [!..]
character class must match a character, so it is an inclusion pattern for every character that is not in the class).
You'll have to do your own filtering; a list comprehension usually works nicely here:
files = [fn for fn in glob('somepath/*.txt')
if not os.path.basename(fn).startswith('eph')]
for me works this two commands:
git checkout commit_id
git push origin +name_of_branch
As for the inverse, the function is inv(A)
, but I won't recommend using it, since for huge matrices it is very computationally costly and unstable. Instead, you should use an approximation to the inverse, or if you want to solve Ax = b you don't really need A-1.
I have been using the following solution (with no positioning and no line height) since over a year, it works with IE 7 and 8 as well.
<style>
.outer {
font-size: 0;
width: 400px;
height: 400px;
background: orange;
text-align: center;
display: inline-block;
}
.outer .emptyDiv {
height: 100%;
background: orange;
visibility: collapse;
}
.outer .inner {
padding: 10px;
background: red;
font: bold 12px Arial;
}
.verticalCenter {
display: inline-block;
*display: inline;
zoom: 1;
vertical-align: middle;
}
</style>
<div class="outer">
<div class="emptyDiv verticalCenter"></div>
<div class="inner verticalCenter">
<p>Line 1</p>
<p>Line 2</p>
</div>
</div>
Prerequisites to execute this command -
pip (recursive acronym of Pip Installs Packages) is a package management system used to install and manage software packages written in Python. Many packages can be found in the Python Package Index (PyPI).
sudo apt-get install python-pip
Install Virtual Environment. Used to create virtual environment, to install packages and dependencies of multiple projects isolated from each other.
sudo pip install virtualenv
Install virtual environment wrapper About virtual env wrapper
sudo pip install virtualenvwrapper
After Installing prerequisites you need to bring virtual environment wrapper into action to create virtual environment. Following are the steps -
set virtual environment directory in path variable-
export WORKON_HOME=(directory you need to save envs)
source /usr/local/bin/virtualenvwrapper.sh -p $WORKON_HOME
As mentioned by @Mike, source `which virtualenvwrapper.sh` or which virtualenvwrapper.sh
can used to locate virtualenvwrapper.sh file.
It's best to put above two lines in ~/.bashrc to avoid executing the above commands every time you open new shell. That's all you need to create environment using mkvirtualenv
Points to keep in mind -
I was unable to solve this
until now. First of all you have to have system packages mentioned by Pradeep Mahdevu. Those are:
xcode-select --install (on a mac)
or
sudo apt-get install gcc make build-essential (on ubuntu)
Then I've installed node-gyp
npm install -g node-gyp
like datadracer said but npm update also suggested by him is risky. It update all modules, which can be dangerous (sometimes API changes between versions).
I suggest going into node_modules/mongodb/node_modules/bson directory and from there use
node-gyp rebuild
That solved the problem for me.
There is an easier way to find a min integer in array list:
int min = array.get(0);
for (int i : array){
min = min < i ? min : i;
}
$utfEncodedArray = array_map("utf8_encode", $inputArray );
Does the job and returns a serialized array with numeric keys (not an assoc).
Are you familiar with the DataSet
class?
The DataSet
can also load
XML documents and you may find it easier to iterate.
http://msdn.microsoft.com/en-us/library/system.data.dataset.readxml.aspx
DataSet dt = new DataSet();
dt.ReadXml(@"c:\test.xml");
You mistyped the set
command – you missed the backslash after C:
. It should be:
C:\>set path=C:\Program Files (x86)\Java\jdk1.7.0\bin
How about using os.kill? See the docs here: http://docs.python.org/library/os.html#os.kill
More recent and much cleaner: use event.key
. No more arbitrary number codes!
note.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace") {
// Do something
}
});
\mbox
is the simplest answer. Regarding the update:
TeX prefers overlong lines to adding too much space between words on a line; I think the idea is that you will notice the lines that extend into the margin (and the black boxes it inserts after such lines), and will have a chance to revise the contents, whereas if there was too much space, you might not notice it.
Use \sloppy
or \begin{sloppypar}...\end{sloppypar}
to adjust this behavior, at least a little. Another possibility is \raggedright
(or \begin{raggedright}...\end{raggedright}
).
you just need to get the absolute-path of the file, since the file you are looking for doesnt exist in the eclipse's runtime workspace you can use - getProperty() or getLocationURI() methods to get the absolute-path of the file
Try with <button type="submit">
you can perform the functionality of submitform()
by doing <form ....... onsubmit="submitform()">
The fields of your object have in turn their fields, some of which do not implement Serializable
. In your case the offending class is TransformGroup
. How to solve it?
Serializable
transient
This will do what you are looking for in C# (WebDriver/Selenium 2.0)
var browser = new FirefoxDriver();
var overallTimeout = Timespan.FromSeconds(10);
var sleepCycle = TimeSpan.FromMiliseconds(50);
var wait = new WebDriverWait(new SystemClock(), browser, overallTimeout, sleepCycle);
var hasTimedOut = wait.Until(_ => /* here goes code that looks for the map */);
And never use Thread.Sleep because it makes your tests unreliable
Constant.swift
import Foundation
let kBaseURL = NSURL(string: "http://www.example.com/")
ViewController.swift
var manager = AFHTTPRequestOperationManager(baseURL: kBaseURL)
See this answer for a non JQuery solution. Just helped me out!
Check the Initial Catalog parameter in your connection string. It may be that your code is looking in the wrong database for the Projects object.
For example, if you have database syncing setup in such a way that only a subset of the master-database's tables are transferred, you can encounter this error if Linq to SQL is expecting all tables to be in the database pointed to by the connection string.
WordPress include tags, categories and taxonomies in search results
This code is taken from http://atiblog.com/custom-search-results/
Some functions here are taken from twentynineteen theme.Because it is made on this theme.
This code example will help you to include tags, categories or any custom taxonomy in your search. And show the posts contaning these tags or categories.
You need to modify your search.php of your theme to do so.
<?php
$search=get_search_query();
$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) );
$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );
//if you have any custom taxonomy
$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );
$mcat=array();
$mtag=array();
$mcustom_taxonomy=array();
foreach($all_categories as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}
foreach($all_tags as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}
foreach($all_custom_taxonomy as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcustom_taxonomy,$all->term_id);
}
}
$matched_posts=array();
$args1= array( 'post_status' => 'publish','posts_per_page' => -1,'tax_query' =>array('relation' => 'OR',array('taxonomy' => 'category','field' => 'term_id','terms' =>$mcat),array('taxonomy' => 'post_tag','field' => 'term_id','terms' =>$mtag),array('taxonomy' => 'custom_taxonomy','field' => 'term_id','terms' =>$mcustom_taxonomy)));
$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($matched_posts,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {
}
?>
<?php
// now we will do the normal wordpress search
$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
array_push($matched_posts,get_the_id());
}
wp_reset_postdata();
} else {
}
$matched_posts= array_unique($matched_posts);
$matched_posts=array_values(array_filter($matched_posts));
//print_r($matched_posts);
?>
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );
if ( $query3->have_posts() ) {
while ( $query3->have_posts() ) {
$query3->the_post();
get_template_part( 'template-parts/content/content', 'excerpt' );
}
twentynineteen_the_posts_navigation();
wp_reset_postdata();
} else {
}
?>
On Windows : you can use FCIV utility : http://support.microsoft.com/kb/841290
On Unix/Linux : you can use md5sum : http://linux.about.com/library/cmd/blcmdl1_md5sum.htm
The problem is that your password wont match the password validation rules. You can simple follow below steps to solve your problem.
You can simply see password validation configuration matrix by typing below code.
mysql-> SHOW VARIABLES LIKE 'validate_password%';
Then in your matrix you can find below variables with corresponding values and in there you have to check validate_password_length
, validate_password_number_count
and validate_password_policy
.
Check the values used for those variables. Make sure your validate_password_length
should not be greater than 6. You can set that to 6 by using below code.
SET GLOBAL validate_password_length = 6;
And after that you need to set validate_password_number_count
to 0. Do it by using below code.
SET GLOBAL validate_password_number_count = 0;
Finally you have to set you validate_password_policy
to low
. Having that as Medium
or High
wont allow your less secure passwords. Set that to low
by below code.
SET GLOBAL validate_password_policy=LOW;
The way to do this without use of plugins is to make a subclass of google's OverlayView() method.
https://developers.google.com/maps/documentation/javascript/reference?hl=en#OverlayView
You make a custom function and apply it to the map.
function Label() {
this.setMap(g.map);
};
Now you prototype your subclass and add HTML nodes:
Label.prototype = new google.maps.OverlayView; //subclassing google's overlayView
Label.prototype.onAdd = function() {
this.MySpecialDiv = document.createElement('div');
this.MySpecialDiv.className = 'MyLabel';
this.getPanes().overlayImage.appendChild(this.MySpecialDiv); //attach it to overlay panes so it behaves like markers
}
you also have to implement remove and draw functions as stated in the API docs, or this won't work.
Label.prototype.onRemove = function() {
... // remove your stuff and its events if any
}
Label.prototype.draw = function() {
var position = this.getProjection().fromLatLngToDivPixel(this.get('position')); // translate map latLng coords into DOM px coords for css positioning
var pos = this.get('position');
$('.myLabel')
.css({
'top' : position.y + 'px',
'left' : position.x + 'px'
})
;
}
That's the gist of it, you'll have to do some more work in your specific implementation.
Since you only said render, yes you can. You could do something along the lines of this:
function render(){_x000D_
var inp = document.getElementById("box");_x000D_
var data = `_x000D_
<svg xmlns="http://www.w3.org/2000/svg" width="${inp.offsetWidth}" height="${inp.offsetHeight}">_x000D_
<foreignObject width="100%" height="100%">_x000D_
<div xmlns="http://www.w3.org/1999/xhtml" _x000D_
style="font-family:monospace;font-style: normal; font-variant: normal; font-size:13.3px;padding:2px;;">_x000D_
${inp.value} <i style="color:red">cant touch this</i>_x000D_
</div>_x000D_
</foreignObject>_x000D_
</svg>`;_x000D_
var blob = new Blob( [data], {type:'image/svg+xml'} );_x000D_
var url=URL.createObjectURL(blob);_x000D_
inp.style.backgroundImage="url("+URL.createObjectURL(blob)+")";_x000D_
}_x000D_
onload=function(){_x000D_
render();_x000D_
ro = new ResizeObserver(render);_x000D_
ro.observe(document.getElementById("box"));_x000D_
}
_x000D_
#box{_x000D_
color:transparent;_x000D_
caret-color: black;_x000D_
font-style: normal;/*must be same as in the svg for caret to align*/_x000D_
font-variant: normal; _x000D_
font-size:13.3px;_x000D_
padding:2px;_x000D_
font-family:monospace;_x000D_
}
_x000D_
<textarea id="box" oninput="render()">you can edit me!</textarea>
_x000D_
textarea
will render html!
Besides the flashing when resizing, inability to directly use classes and having to make sure that the div in the svg
has the same format as the textarea
for the caret to align correctly, it's works!
Note: It seems this is not the preferred solution because of how the extra line was being added on a Windows system. As stated in the python document:
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
Windows is one such platform where that makes a difference. While changing the line terminator as I described below may have fixed the problem, the problem could be avoided altogether by opening the file in binary mode. One might say this solution is more "elegent". "Fiddling" with the line terminator would have likely resulted in unportable code between systems in this case, where opening a file in binary mode on a unix system results in no effect. ie. it results in cross system compatible code.
From Python Docs:
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.
Original:
As part of optional paramaters for the csv.writer if you are getting extra blank lines you may have to change the lineterminator (info here). Example below adapated from the python page csv docs. Change it from '\n' to whatever it should be. As this is just a stab in the dark at the problem this may or may not work, but it's my best guess.
>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w'), lineterminator='\n')
>>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
>>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.
[Update] As mentioned by @Aftershock in the comments, util.pump
is gone and was replaced with a method on the Stream prototype called pipe
; the code below reflects this.
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
})
.listen(2000);
Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
I believe the best method with jQuery is using .scrollTop()
:
var pos = $('body').scrollTop();
You have to be careful not to insert directly into your SERIAL or sequence field, otherwise your write will fail when the sequence reaches the inserted value:
-- Table: "test"
-- DROP TABLE test;
CREATE TABLE test
(
"ID" SERIAL,
"Rank" integer NOT NULL,
"GermanHeadword" "text" [] NOT NULL,
"PartOfSpeech" "text" NOT NULL,
"ExampleSentence" "text" NOT NULL,
"EnglishGloss" "text"[] NOT NULL,
CONSTRAINT "PKey" PRIMARY KEY ("ID", "Rank")
)
WITH (
OIDS=FALSE
);
-- ALTER TABLE test OWNER TO postgres;
INSERT INTO test("Rank", "GermanHeadword", "PartOfSpeech", "ExampleSentence", "EnglishGloss")
VALUES (1, '{"der", "die", "das", "den", "dem", "des"}', 'art', 'Der Mann küsst die Frau und das Kind schaut zu', '{"the", "of the" }');
INSERT INTO test("ID", "Rank", "GermanHeadword", "PartOfSpeech", "ExampleSentence", "EnglishGloss")
VALUES (2, 1, '{"der", "die", "das"}', 'pron', 'Das ist mein Fahrrad', '{"that", "those"}');
INSERT INTO test("Rank", "GermanHeadword", "PartOfSpeech", "ExampleSentence", "EnglishGloss")
VALUES (1, '{"der", "die", "das"}', 'pron', 'Die Frau, die nebenen wohnt, heißt Renate', '{"that", "who"}');
SELECT * from test;
This function will tell you if your string contains ONLY the characters 0123456789.
private bool IsInt(string sVal)
{
foreach (char c in sVal)
{
int iN = (int)c;
if ((iN > 57) || (iN < 48))
return false;
}
return true;
}
This is different from int.TryParse() which will tell you if your string COULD BE an integer.
eg. " 123\r\n" will return TRUE from int.TryParse() but FALSE from the above function.
...Just depends on the question you need to answer.
The authenticity token is designed so that you know your form is being submitted from your website. It is generated from the machine on which it runs with a unique identifier that only your machine can know, thus helping prevent cross-site request forgery attacks.
If you are simply having difficulty with rails denying your AJAX script access, you can use
<%= form_authenticity_token %>
to generate the correct token when you are creating your form.
You can read more about it in the documentation.
It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :
Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/
You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.
The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:
For i = 1 To Len(Cells(1, 1))
Cells(2, i) = Mid(Cells(1, 1), i, 1)
Next
If you do not want the symbols like colon to be inserted put an if condition in the loop.
You can run the top
command (to run non-interactively, type top -b -n 1
). To see applications which are leaking memory, look at the following columns:
The timeout that you are looking for is the connection socket's timeout not the primary socket's, if you implement the server side. In other words, there is another timeout for the connection socket object, which is the output of socket.accept()
method. Therefore:
sock.listen(1)
connection, client_address = sock.accept()
connection.settimeout(5) # This is the one that affects recv() method.
connection.gettimeout() # This should result 5
sock.gettimeout() # This outputs None when not set previously, if I remember correctly.
If you implement the client side, it would be simple.
sock.connect(server_address)
sock.settimeout(3)
An @
symbol at the beginning of a line is used for class, function and method decorators.
Read more here:
The most common Python decorators you'll run into are:
If you see an @
in the middle of a line, that's a different thing, matrix multiplication. See this answer showing the use of @
as a binary operator.
Thanks for all the answers but none of them worked for me. Although some of them gave me some ideas on what services and stuff that needs to be running to be able "turn on" the debugging of my web app again:
I still haven't figured out what is the reason why my IIS stopped. It was working fine yesterday then today it's not. Anyways, I hope this mini checklist helps somebody else. Cheers!
List<User> findByUsernameContainingIgnoreCase(String username);
in order to ignore case issues
Static variables are common across all instances of a type.
constant variables are specific to each individual instance of a type but their values are known and fixed at compile time and it cannot be changed at runtime.
unlike constants, static variable values can be changed at runtime.
To make it easier for yourself you could also create an actionfilterattribute
public class AllowJsonGetAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
var jsonResult = filterContext.Result as JsonResult;
if (jsonResult == null)
throw new ArgumentException("Action does not return a JsonResult,
attribute AllowJsonGet is not allowed");
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
base.OnResultExecuting(filterContext);
}
}
and use it on your action
[AllowJsonGet]
public JsonResult MyAjaxAction()
{
return Json("this is my test");
}
$("#sample_id").css({ 'width' : '', 'height' : '' });
Detect:
Debug CRT
Avoid:
Smart pointers, boehm GC
I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.
Timing:
|------------|----------------|-------------------|
| | shape (10000) | shape (1,10000) |
|------------|----------------|-------------------|
| np.concat | 0.18280 | 0.17960 |
|------------|----------------|-------------------|
| np.stack | 0.21501 | 0.16465 |
|------------|----------------|-------------------|
| np.vstack | 0.21501 | 0.17181 |
|------------|----------------|-------------------|
| np.array | 0.21656 | 0.16833 |
|------------|----------------|-------------------|
As you can see I tried 2 experiments - using np.random.rand(10000)
and np.random.rand(1, 10000)
And if we use 2d arrays than np.stack
and np.array
create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.
Code:
from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
new_np = np.random.rand(10000)
l.append(new_np)
start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')
start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')
start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')
start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')
Create keystore file from command line :
Open Command line:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved
// (if you want to store keystore file at C:/ open command line with RUN AS ADMINISTRATOR)
C:\Windows\system32> keytool -genkey -v -keystore [your keystore file path]{C:/index.keystore} -alias [your_alias_name]{index} -keyalg RSA -keysize 2048 -validity 10000[in days]
Enter > It will prompt you for password > enter password (it will be invisible)
Enter keystore password:
Re-enter new password:
Enter > It will ask your detail.
What is your first and last name?
[Unknown]: {AB} // [Your Name / Name of Signer]
What is the name of your organizational unit?
[Unknown]: {Self} // [Your Unit Name]
What is the name of your organization?
[Unknown]: {Self} // [Your Organization Name]
What is the name of your City or Locality?
[Unknown]: {INDORE} // [Your City Name]
What is the name of your State or Province?
[Unknown]: {MP} //[Your State]
What is the two-letter country code for this unit?
[Unknown]: 91
Enter > Enter Y
Is CN=AB, OU=Self, O=Self, L=INDORE, ST=MP, C=91 correct?
[no]: Y
Enter > Enter password again.
Generating 2,048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 10,000 days
for: CN=AB, OU=Self, O=Self, L=INDORE, ST=MP, C=91
Enter key password for <index> (RETURN if same as keystore password):
Re-enter new password:
[ Storing C:/index.keystore ]
Export your android package to .apk with your created keystore file
Right click on Package you want to export and select export
Select Export Android Application > Next
Next
Select Use Existing Keystore > Browse .keystore file > enter password > Next
Create keystore [.keystore/.jks]
in studio...
Click Build (ALT+B) > Generate Signed APK...
Click Create new..(ALT+C)
Browse Key store path (SHIFT+ENTER) > Select Path > Enter name > OK
Fill the detail about your .jks/keystore
file
Next
Your file
Enter Studio Master Password (You can RESET if you don't know) > OK
Select *Destination Folder * > Build Type
release : for publish on app store
debug : for debugging your application
Click Finish
Done !!!
There isn't any need to write this much. Just put your desired field separator with the -F
option in the AWK command and the column number you want to print segregated as per your mentioned field separator.
echo "1: " | awk -F: '{print $1}'
1
echo "1#2" | awk -F# '{print $1}'
1
Add this single line in manifest (for permission)
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Then paste this code in your activity
private ArrayList<String> getPrimaryMailId() {
ArrayList<String> accountsList = new ArrayList<String>();
try {
Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
for (Account account : accounts) {
accountsList.add(account.name);
Log.e("GetPrimaryMailId ", account.name);
}
} catch (Exception e) {
Log.e("GetPrimaryMailId", " Exception : " + e);
}
return accountsList;
}
If you want to run a few scripts, you can use Set-executionpolicy -ExecutionPolicy Unrestricted
and then reset with Set-executionpolicy -ExecutionPolicy Default
.
Note that execution policy is only checked when you start its execution (or so it seems) and so you can run jobs in the background and reset the execution policy immediately.
# Check current setting
Get-ExecutionPolicy
# Disable policy
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
# Choose [Y]es
Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 example.com | tee ping__example.com.txt }
Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 google.com | tee ping__google.com.txt }
# Can be run immediately
Set-ExecutionPolicy -ExecutionPolicy Default
# [Y]es
This is usually what I use for counting the number of fields:
head -n 1 file.name | awk -F'|' '{print NF; exit}'
The primary role of the @Named annotation is to define a bean for the purpose of resolving EL statements within the application, usually through JSF EL resolvers. Injection can be performed using names but this was not how injection in CDI was meant to work since CDI gives us a much richer way to express injection points and the beans to be injected into them.
no idea how this happened, but i had the same problem. I had to reset my root password: http://www.jovicailic.org/2012/04/reset-forgotten-mysql-root-password-under-windows/
But after my databases that i had previously were either dropped or the new connection did not connect to them. Either way i couldn't access them via workbench. But i could use MySQL again, which was a win for me
In my experience this error is pretty common, for some reason jersey sometimes has problems parsing custom java types. Usually all you have to do is make sure that you respect the following 3 conditions:
However, I have ran into cases where this just was not enough. Then you can always wrap you custom data type in a GenericEntity and pass it as such to your ResponseBuilder:
GenericEntity<CustomDataType> entity = new GenericEntity<CustomDataType>(myObj) {};
return Response.status(httpCode).entity(entity).build();
This way you are trying to help jersey to find the proper/relevant serialization provider for you object. Well, sometimes this also is not enough. In my case I was trying to produce a text/plain from a custom data type. Theoretically jersey should have used the StringMessageProvider, but for some reason that I did not manage to discover it was giving me this error:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/plain
So what solved the problem for me was to do my own serialization with jackson's writeValueAsString(). I'm not proud of it but at the end of the day I can deliver an acceptable solution.
The answer to this may depend largely on the UUID version.
Many UUID generators use a version 4 random number. However, many of these use Pseudo a Random Number Generator to generate them.
If a poorly seeded PRNG with a small period is used to generate the UUID I would say it's not very safe at all. Some random number generators also have poor variance. i.e. favouring certain numbers more often than others. This isn't going to work well.
Therefore, it's only as safe as the algorithms used to generate it.
On the flip side, if you know the answer to these questions then I think a version 4 uuid should be very safe to use. In fact I'm using it to identify blocks on a network block file system and so far have not had a clash.
In my case, the PRNG I'm using is a mersenne twister and I'm being careful with the way it's seeded which is from multiple sources including /dev/urandom. Mersenne twister has a period of 2^19937 - 1. It's going to be a very very long time before I see a repeat uuid.
So pick a good library or generate it yourself and make sure you use a decent PRNG algorithm.
Please find in the below code which escapes the single quotes as part of the entered string using a regular expression. It validates if the user-entered string is comma-separated and at the same time it even escapes any single quote(s) entered as part of the string.
In order to escape single quotes, just enter a backward slash followed by a single quote like: \’ as part of the string. I used jQuery validator for this example, and you can use as per your convenience.
Valid String Examples:
'Hello'
'Hello', 'World'
'Hello','World'
'Hello','World',' '
'It\'s my world', 'Can\'t enjoy this without me.', 'Welcome, Guest'
HTML:
<tr>
<td>
<label class="control-label">
String Field:
</label>
<div class="inner-addon right-addon">
<input type="text" id="stringField"
name="stringField"
class="form-control"
autocomplete="off"
data-rule-required="true"
data-msg-required="Cannot be blank."
data-rule-commaSeparatedText="true"
data-msg-commaSeparatedText="Invalid comma separated value(s).">
</div>
</td>
JavaScript:
/**
*
* @param {type} param1
* @param {type} param2
* @param {type} param3
*/
jQuery.validator.addMethod('commaSeparatedText', function(value, element) {
if (value.length === 0) {
return true;
}
var expression = new RegExp("^((')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))(((,)|(,\\s))(')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))*$");
return expression.test(value);
}, 'Invalid comma separated string values.');
Try to replace 'w' for 'iw'. For example:
SELECT to_char(to_date(TRANSDATE, 'dd-mm-yyyy'), 'iw') as weeknumber from YOUR_TABLE;
If you're trying to stop someone from updating the checkbox so it appears disabled then just use JQuery
$('input[type=checkbox]').click(false);
You can then style the checkbox.
ls -I "filename1" -I "filename2" | xargs cp -rf -t destdir
The first part ls
all the files but hidden specific files with flag -I
. The output of ls
is used as standard input for the second part. xargs
build and execute command cp -rf -t destdir
from standard input. the flag -r
means copy directories recursively, -f
means copy files forcibly which will overwrite the files in the destdir
, -t
specify the destination directory copy to.
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
See my other Answer using the industry-leading java.time classes.
Normally we consider it bad form on StackOverflow.com to answer a specific question by suggesting an alternate technology. But in the case of the date, time, and calendar classes bundled with Java 7 and earlier, those classes are so notoriously bad in both design and execution that I am compelled to suggest using a 3rd-party library instead: Joda-Time.
Joda-Time works by creating immutable objects. So rather than alter the time zone of a DateTime object, we simply instantiate a new DateTime with a different time zone assigned.
Your central concern of using both local and UTC time is so very simple in Joda-Time, taking just 3 lines of code.
org.joda.time.DateTime now = new org.joda.time.DateTime();
System.out.println( "Local time in ISO 8601 format: " + now + " in zone: " + now.getZone() );
System.out.println( "UTC (Zulu) time zone: " + now.toDateTime( org.joda.time.DateTimeZone.UTC ) );
Output when run on the west coast of North America might be:
Local time in ISO 8601 format: 2013-10-15T02:45:30.801-07:00
UTC (Zulu) time zone: 2013-10-15T09:45:30.801Z
Here is a class with several examples and further comments. Using Joda-Time 2.5.
/**
* Created by Basil Bourque on 2013-10-15.
* © Basil Bourque 2013
* This source code may be used freely forever by anyone taking full responsibility for doing so.
*/
public class TimeExample {
public static void main(String[] args) {
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 8 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
// You may output to strings in other formats.
// Capture one moment in time, to be used in all the examples to follow.
org.joda.time.DateTime now = new org.joda.time.DateTime();
System.out.println( "Local time in ISO 8601 format: " + now + " in zone: " + now.getZone() );
System.out.println( "UTC (Zulu) time zone: " + now.toDateTime( org.joda.time.DateTimeZone.UTC ) );
// You may specify a time zone in either of two ways:
// • Using identifiers bundled with Joda-Time
// • Using identifiers bundled with Java via its TimeZone class
// ----| Joda-Time Zones |---------------------------------
// Time zone identifiers defined by Joda-Time…
System.out.println( "Time zones defined in Joda-Time : " + java.util.Arrays.toString( org.joda.time.DateTimeZone.getAvailableIDs().toArray() ) );
// Specify a time zone using DateTimeZone objects from Joda-Time.
// http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTimeZone.html
org.joda.time.DateTimeZone parisDateTimeZone = org.joda.time.DateTimeZone.forID( "Europe/Paris" );
System.out.println( "Paris France (Joda-Time zone): " + now.toDateTime( parisDateTimeZone ) );
// ----| Java Zones |---------------------------------
// Time zone identifiers defined by Java…
System.out.println( "Time zones defined within Java : " + java.util.Arrays.toString( java.util.TimeZone.getAvailableIDs() ) );
// Specify a time zone using TimeZone objects built into Java.
// http://docs.oracle.com/javase/8/docs/api/java/util/TimeZone.html
java.util.TimeZone parisTimeZone = java.util.TimeZone.getTimeZone( "Europe/Paris" );
System.out.println( "Paris France (Java zone): " + now.toDateTime(org.joda.time.DateTimeZone.forTimeZone( parisTimeZone ) ) );
}
}
One liner for Swift:
NSAttributedString(string: "Red Text", attributes: [.foregroundColor: UIColor.red])
You can simply call filter
multiple times:
query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
filter(User.lastname.like(searchVar2))
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Check out this plugin:
moment-countdown is a tiny moment.js plugin that integrates with Countdown.js. The file is here.
How it works?
//from then until now
moment("1982-5-25").countdown().toString(); //=> '30 years, 10 months, 14 days, 1 hour, 8 minutes, and 14 seconds'
//accepts a moment, JS Date, or anything parsable by the Date constructor
moment("1955-8-21").countdown("1982-5-25").toString(); //=> '26 years, 9 months, and 4 days'
//also works with the args flipped, like diff()
moment("1982-5-25").countdown("1955-8-21").toString(); //=> '26 years, 9 months, and 4 days'
//accepts all of countdown's options
moment().countdown("1982-5-25", countdown.MONTHS|countdown.WEEKS, NaN, 2).toString(); //=> '370 months, and 2.01 weeks'
You can do it via the constructor of your class:
public class foo {
public foo(){
Bar = "bar";
}
public string Bar {get;set;}
}
If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):
public class foo {
private foo(){
Bar = "bar";
Baz = "baz";
}
public foo(int something) : this(){
//do specialized initialization here
Baz = string.Format("{0}Baz", something);
}
public string Bar {get; set;}
public string Baz {get; set;}
}
If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.
In the solution below I used python3.4
as binary, but it's safe to use with any version or binary of python. it works fine on windows too (except the downloading pip with wget
obviously but just save the file locally and run it with python).
This is great if you have multiple versions of python installed, so you can manage external libraries per python version.
So first, I'd recommend get-pip.py
, it's great to install pip :
wget https://bootstrap.pypa.io/get-pip.py
Then you need to install pip for your version of python, I have python3.4
so for me this is the command :
python3.4 get-pip.py
Now pip is installed for python3.4
and in order to get libraries for python3.4
one need to call it within this version, like this :
python3.4 -m pip
So if you want to install numpy you would use :
python3.4 -m pip install numpy
Note that numpy
is quite the heavy library. I thought my system was hanging and failing.
But using the verbose option, you can see that the system is fine :
python3.4 -m pip install numpy -v
This may tell you that you lack python.h but you can easily get it :
On RHEL (Red hat, CentOS, Fedora) it would be something like this :
yum install python34-devel
On debian-like (Debian, Ubuntu, Kali, ...) :
apt-get install python34-dev
Then rerun this :
python3.4 -m pip install numpy -v
VMDK/VMX are VMWare file formats but you can use it with VirtualBox:
For me this worked:
buildscript {
repositories {
maven { url "http://jcenter.bintray.com"}
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
...
}
allprojects {
repositories {
mavenCentral()
jcenter{ url "http://jcenter.bintray.com/" }
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
}
I use LEd Editor with special "Filter" feature. It replaces \"{o} with ö and vice versa in its own editor, while maintaining original \"{o} in tex files. This makes text easily readable when viewed in LEd Editor and there is no need for special packages. It works with bibliography files too.
if you want your check box to keep its height and width but only be invisible:
.hiddenCheckBox{
visibility: hidden;
}
if you want your check box to be invisible without any with and height:
.hiddenCheckBox{
display: none;
}
This is the configuration file for Maven. It can be specified at two levels:
User Level. This settings.xml file provides configuration for a single user, and is normally provided in ${user.home}/.m2/settings.xml.
NOTE: This location can be overridden with the CLI option:
-s /path/to/user/settings.xml
Global Level. This settings.xml file provides configuration for all Maven users on a machine (assuming they're all using the same Maven installation). It's normally provided in ${maven.home}/conf/settings.xml.
NOTE: This location can be overridden with the CLI option:
-gs /path/to/global/settings.xml
To make the whole div act as a link, set the anchor tag as:
display: block
And set your height of the anchor tag to 100%. Then set a fixed height to your div tag. Then style your anchor tag like usual.
For example:
<html>
<head>
<title>DIV Link</title>
<style type="text/css">
.link-container {
border: 1px solid;
width: 50%;
height: 20px;
}
.link-container a {
display: block;
background: #c8c8c8;
height: 100%;
text-align: center;
}
.link-container a:hover {
background: #f8f8f8;
}
</style>
</head>
<body>
<div class="link-container">
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>
<div class="link-container">
<a href="http://www.stackoverflow.com">Stack Overflow</a>
</div>
</body> </html>
Good luck!
This gives you the root folder:
System.AppDomain.CurrentDomain.BaseDirectory
You can navigate from here using .. or ./ etc.. , Appending .. takes you to folder where .sln file can be found
For .NET framework (thanks to Adiono comment)
Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"..\\..\\"))
For .NET core here is a way to do it (thanks to nopara73 comment)
Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")) ;
It's a bit old post but I recently ran into this issue. All I did was deleted all the nuget packages from packages folder and restored it. I was able to build the solution successfully. Hopefully helpful to someone.
max_connections
You can change max_connections
while MySQL is running via SET
:
mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 5000 |
+-----------------+-------+
1 row in set (0.00 sec)
timeout
relatedI had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.
I suggest that you increase this value to 100k or disable connection pooling Pooling=false
he has two questions.
Q1 - what happens if I disable pooling
Slow down making DB connection. connection pooling
is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool
Q2 - Can the value of pooling be increased or the maximum is 100?
you can increase but I'm sure what is MAX value, maybe max_connections
in my.cnf
My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.
If you have Stress Test tool like JMeter
you can test youself.
import os
filename = C:\\Users\\Public\\Videos\\Sample Videos\\wildlife.wmv
This returns the filename
without the extension
(C:\Users\Public\Videos\Sample Videos\wildlife)
temp = os.path.splitext(filename)[0]
Now you can get just the filename
from the temp with
os.path.basename(temp) #this returns just the filename (wildlife)
Do it like this:
$foo = new stdClass();
$foo->{"bar"} = '1234';
now try:
echo $foo->bar; // should display 1234
Why not just, a=a(~~a)
or a(~a)=[]
. It's equivalent to the other approaches but certainly less key strokes.
This is my solution...
/*
this program is looking for CPU,Memory,Procs also u can look glibtop header there was a lot of usefull function have fun..
systeminfo.c
*/
#include <stdio.h>
#include <glibtop.h>
#include <glibtop/cpu.h>
#include <glibtop/mem.h>
#include <glibtop/proclist.h>
int main(){
glibtop_init();
glibtop_cpu cpu;
glibtop_mem memory;
glibtop_proclist proclist;
glibtop_get_cpu (&cpu);
glibtop_get_mem(&memory);
printf("CPU TYPE INFORMATIONS \n\n"
"Cpu Total : %ld \n"
"Cpu User : %ld \n"
"Cpu Nice : %ld \n"
"Cpu Sys : %ld \n"
"Cpu Idle : %ld \n"
"Cpu Frequences : %ld \n",
(unsigned long)cpu.total,
(unsigned long)cpu.user,
(unsigned long)cpu.nice,
(unsigned long)cpu.sys,
(unsigned long)cpu.idle,
(unsigned long)cpu.frequency);
printf("\nMEMORY USING\n\n"
"Memory Total : %ld MB\n"
"Memory Used : %ld MB\n"
"Memory Free : %ld MB\n"
"Memory Buffered : %ld MB\n"
"Memory Cached : %ld MB\n"
"Memory user : %ld MB\n"
"Memory Locked : %ld MB\n",
(unsigned long)memory.total/(1024*1024),
(unsigned long)memory.used/(1024*1024),
(unsigned long)memory.free/(1024*1024),
(unsigned long)memory.shared/(1024*1024),
(unsigned long)memory.buffer/(1024*1024),
(unsigned long)memory.cached/(1024*1024),
(unsigned long)memory.user/(1024*1024),
(unsigned long)memory.locked/(1024*1024));
int which,arg;
glibtop_get_proclist(&proclist,which,arg);
printf("%ld\n%ld\n%ld\n",
(unsigned long)proclist.number,
(unsigned long)proclist.total,
(unsigned long)proclist.size);
return 0;
}
makefile is
CC=gcc
CFLAGS=-Wall -g
CLIBS=-lgtop-2.0 -lgtop_sysdeps-2.0 -lgtop_common-2.0
cpuinfo:cpu.c
$(CC) $(CFLAGS) systeminfo.c -o systeminfo $(CLIBS)
clean:
rm -f systeminfo
The formula that you have is fine. But, after entering it, you need to hit Control + Shift + Enter in order to apply it to the range of values. Specifically:
Select the range of values in the destination sheet.
Enter into the formula panel your desired formula, e.g. =Sheet2!A1:F1
Hit Control + Shift + Enter to apply the formula to the range.
You can convert to an array and call array soring methods on it:
[...map].sort(/* etc */);
Maybe you can use Angular Augury A Google Chrome Dev Tools extension for debugging Angular 2 and above applications.
Execute this script:
SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;'
FROM v$session
where username='YOUR_USER';
It will printout sqls, which should be executed.
Try this Toggle Buttons
test_activity.xml
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="100px"
android:layout_height="50px"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="toggleclick"/>
Test.java
public class Test extends Activity {
private ToggleButton togglebutton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
}
public void toggleclick(View v){
if(togglebutton.isChecked())
Toast.makeText(TestActivity.this, "ON", Toast.LENGTH_SHORT).show();
else
Toast.makeText(TestActivity.this, "OFF", Toast.LENGTH_SHORT).show();
}
}
Besides raise Exception("message")
and raise
Python 3 introduced a new form, raise Exception("message") from e
. It's called exception chaining, it allows you to preserve the original exception (the root cause) with its traceback.
It's very similar to inner exceptions from C#.
More info: https://www.python.org/dev/peps/pep-3134/
Maybe I'm missing something here, but usually calling .SingleOrDefault()
is the way to go to return either the single element in the list, or a default value (null for reference or nullable types) if the list is empty.
It generates an exception if the list contains more than one element.
Use FirstOrDefault()
to cover the case where you could have more than one.
What worked for me (I am using TortoiseSVN v1.13.1):
1.In File Explorer, right-click on SVN project folder-name
2.Click on "SVN Commit..."
3.A "commit" window will appear
4.Right-click on the folder/file that you want to ignore
5.Click on "Add to ignore list"
6.Select the folder/file name you want to ignore
7.Commit the "property change" to SVN
After Step 3 above, click on "Show unversioned files" as follows:
You could also check to make sure the DLLs you're looking for aren't included in the GAC. I believe Visual Studio is being smart about not copying those files if it already exists in the GAC on the build machine.
I recently ran in this situation where I'd been testing an SSIS package that needed assemblies to exist in the GAC. I'd since forgotten that and was wondering why those DLLs weren't coming out during a build.
To check what's in the GAC (from a Visual Studio Developer Command Prompt):
gacutil -l
Or output to a file to make it easier to read:
gacutil -l > output.txt
notepad.exe output.txt
To remove an assembly:
gacutil -u MyProjectAssemblyName
I should also note, that once I removed the files from the GAC they were correctly output in the \bin directory after a build (Even for assemblies that were not directly referenced in the root project). This was on Visual Studio 2013 Update 5.
In Laravel 5.7 you can call specific field like this
$users = App\Book::with('author:id,name')->get();
It is important to add foreign_key
field in the selection.
Get a date object from the jquery date picker using
var myDate = $('element').datepicker('getDate')
For mysql the date needs to be in the proper format. One option which handles any timezone issues is to use moment.js
moment(myDate).format('YYYY-MM-DD HH:mm:ss')
Find an explanation below. You can check this link for more details - http://www.dotnetbull.com/2013/10/public-protected-private-internal-access-modifier-in-c.html
Private: - Private members are only accessible within the own type (Own class).
Internal: - Internal member are accessible only within the assembly by inheritance (its derived type) or by instance of class.
Reference :
In simple way we can tell below are the difference between git and git hub and VSTS.
git: - Treat git as a engine/technology to achieve source version control to our project. Unlike TFS (again a centralized source version control ) git is distributed version control technology. That means git it actually does not mandate to have any server. Through git technology we can make our own local machine as a source code repository not required to have a centralized server always(in large scale it can have Microsoft server to push and keep our project source code). But with SVN and TFS kind version control, it is mandatory that a server be associated with it.
For example if I am a free-lance developer and I directly report to my client and there is no other developer involved, I need to keep version control of my code to roll back(any version) and commit my codes and I don't have budget to get a server and I don't have time to install and use other server in my machine as TFS server and TFS client. So, the optimal way is to install git engine and use my local machine as a repository for version controlling by git.
GitHub: - as I said previously git is a technology and used with some command / shell commands , ie git only doesn't have UI. GitHub is online product or online repository which uses git technology for their process and achieve version controls along with other functionalities like bug tracking,Project management, Support ticket management ..etc. In other words Git Hub is a wrapper build on git technology with a UI and other functionalities by other third party firm, it is actually a product owned by somebody or some group based on git technology , where as git is open source, and not marketable product.
VSTS : - VSTS is a Microsoft product for online repository keeping source version control which can be treated as an alternate to git hub. Since its of Microsoft , VSTS support both git technology and TFS(TFVC-team foundation version control). Because TFS is another old Microsoft product to achieve this version control.Gradually I assume VSTS will gradually dump TFS as git is the prominent technology in this area and it is open source.
I was facing this issue recently, too. Since you can't change the browser's default behavior of showing the popup in case of a 401
(basic or digest authentication), there are two ways to fix this:
401
. Return a 200
code instead and handle this in your jQuery client.Change the method that you're using for authorization to a custom value in your header. Browsers will display the popup for Basic and Digest. You have to change this on both the client and the server.
headers : {
"Authorization" : "BasicCustom"
}
Please also take a look at this for an example of using jQuery with Basic Auth.
In WSDL, if you look at the Binding section, you will clearly see that soap binding is explicitly mentioned if the service uses soap 1.2. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="findEmployeeById">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation><operation name="create">
<soap12:operation soapAction=""/>
<input><soap12:body use="literal"/></input>
<output><soap12:body use="literal"/></output>
</operation>
</binding>
if the web service use soap 1.1, it will not explicitly define any soap version in the WSDL file under binding section. refer the below sample.
<binding name="EmployeeServiceImplPortBinding" type="tns:EmployeeServiceImpl">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
<operation name="findEmployeeById">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation><operation name="create">
<soap:operation soapAction=""/>
<input><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></input>
<output><soap:body use="literal" namespace="http://jaxb.ws.jax.samples.chathurangaonline.com/"/></output>
</operation>
</binding>
How to determine the SOAP version of the SOAP message?
but remember that this is not much recommended way to determine the soap version that your web services uses. the version of the soap message can be determined using one of following ways.
1. checking the namespace of the soap message
SOAP 1.1 namespace : http://schemas.xmlsoap.org/soap/envelope
SOAP 1.2 namespace : http://www.w3.org/2003/05/soap-envelope
2. checking the transport binding information (http header information) of the soap message
SOAP 1.1 : user text/xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: text/xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
SOAP 1.2 : user application/soap+xml for the Context-Type
POST /MyService HTTP/1.1
Content-Type: application/soap+xml; charset="utf-8"
Content-Length: xxx
SOAPAction: "urn:uuid:myaction"
3. using SOAP fault information
The structure of a SOAP fault message between the two versions are different.
The situation becomes a little bit problematic if we want to create a branch from a tag with the same name.
In this, and in similar scenarios, the important thing is to know: branches and tags are actually single-line text files in .git/refs
directory, and we can reference them explicitly using their pathes below .git
. Branches are called here "heads", to make our life more simple.
Thus, refs/heads/master
is the real, explicit name of the master
branch. And refs/tags/cica
is the exact name of the tag named cica
.
The correct command to create a branch named cica
from the tag named cica
is:
git branch cica refs/tags/cica
The thing is that AsyncTask.cancel() call only calls the onCancel function in your task. This is where you want to handle the cancel request.
Here is a small task I use to trigger an update method
private class UpdateTask extends AsyncTask<Void, Void, Void> {
private boolean running = true;
@Override
protected void onCancelled() {
running = false;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
onUpdate();
}
@Override
protected Void doInBackground(Void... params) {
while(running) {
publishProgress();
}
return null;
}
}
Change in config.php like this.
$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$base_url .= "://". @$_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $base_url;
You can achieve this with the background-size
property, which is now supported by most browsers.
To scale the background image to fit inside the div:
background-size: contain;
To scale the background image to cover the whole div:
background-size: cover;
There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.
EDITED: turns out that I had forgotten the quotes needed for $entry
in order to print correctly and not give the "no such file or directory" error. Thank you all so much for helping me!
Here is my final code:
echo "Please type in the directory you want all the files to be listed with last modified dates" #bash can't find file creation dates
read directory
for entry in "$directory"/*
do
modDate=$(stat -c %y "$entry") #%y = last modified. Qoutes are needed otherwise spaces in file name with give error of "no such file"
modDate=${modDate%% *} #%% takes off everything off the string after the date to make it look pretty
echo $entry:$modDate
Prints out like this:
/home/joanne/Dropbox/cheat sheet.docx:2012-03-14
/home/joanne/Dropbox/Comp:2013-05-05
/home/joanne/Dropbox/Comp 150 java.zip:2013-02-11
/home/joanne/Dropbox/Comp 151 Java 2.zip:2013-02-11
/home/joanne/Dropbox/Comp 162 Assembly Language.zip:2013-02-11
/home/joanne/Dropbox/Comp 262 Comp Architecture.zip:2012-12-12
/home/joanne/Dropbox/Comp 345 Image Processing.zip:2013-02-11
/home/joanne/Dropbox/Comp 362 Operating Systems:2013-05-05
/home/joanne/Dropbox/Comp 447 Societal Issues.zip:2013-02-11
Bootstrap 3 with DataTables Example: Bootstrap Docs & DataTables Docs
$(document).ready(function() {
$('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap.min.css rel=stylesheet><div class=container><h1>Bootstrap 3 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap.min.js></script>
_x000D_
Bootstrap 4 with DataTables Example: Bootstrap Docs & DataTables Docs
$(document).ready(function() {
$('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap4.min.css rel=stylesheet><div class=container><h1>Bootstrap 4 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-inverse table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tfoot><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>61<td>2011/04/25<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>63<td>2011/07/25<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>66<td>2009/01/12<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>22<td>2012/03/29<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>33<td>2008/11/28<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>61<td>2012/12/02<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>59<td>2012/08/06<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>55<td>2010/10/14<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>39<td>2009/09/15<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>23<td>2008/12/13<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>30<td>2008/12/19<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>22<td>2013/03/03<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>36<td>2008/10/16<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>43<td>2012/12/18<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>19<td>2010/03/17<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>66<td>2012/11/27<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>64<td>2010/06/09<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>59<td>2009/04/10<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>41<td>2012/10/13<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>35<td>2012/09/26<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>30<td>2011/09/03<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>40<td>2009/06/25<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>21<td>2011/12/12<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>23<td>2010/09/20<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>47<td>2009/10/09<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>42<td>2010/12/22<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>28<td>2010/11/14<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>28<td>2011/06/07<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>48<td>2010/03/11<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>20<td>2011/08/14<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>37<td>2011/06/02<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>53<td>2009/10/22<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>27<td>2011/05/07<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>22<td>2008/10/26<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>46<td>2011/03/09<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>47<td>2009/12/09<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>51<td>2008/12/16<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>41<td>2010/02/12<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>62<td>2009/02/14<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>37<td>2008/12/11<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>65<td>2008/09/26<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>64<td>2011/02/03<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>38<td>2011/05/03<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>37<td>2009/08/19<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>61<td>2013/08/11<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>47<td>2009/07/07<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>64<td>2012/04/09<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>63<td>2010/01/04<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>56<td>2012/06/01<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>43<td>2013/02/01<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>46<td>2011/12/06<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>47<td>2011/03/21<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>21<td>2009/02/27<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>30<td>2010/07/14<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>51<td>2008/11/13<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>29<td>2011/06/27<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>27<td>2011/01/25<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap4.min.js></script>
_x000D_
Bootstrap 3 with Bootstrap Table Example: Bootstrap Docs & Bootstrap Table Docs
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.css rel=stylesheet><table data-sort-name=stargazers_count data-sort-order=desc data-toggle=table data-url="https://api.github.com/users/wenzhixin/repos?type=owner&sort=full_name&direction=asc&per_page=100&page=1"><thead><tr><th data-field=name data-sortable=true>Name<th data-field=stargazers_count data-sortable=true>Stars<th data-field=forks_count data-sortable=true>Forks<th data-field=description data-sortable=true>Description</thead></table><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.js></script>
_x000D_
Bootstrap 3 with Bootstrap Sortable Example: Bootstrap Docs & Bootstrap Sortable Docs
function randomDate(t,e){return new Date(t.getTime()+Math.random()*(e.getTime()-t.getTime()))}function randomName(){return["Jack","Peter","Frank","Steven"][Math.floor(4*Math.random())]+" "+["White","Jackson","Sinatra","Spielberg"][Math.floor(4*Math.random())]}function newTableRow(){var t=moment(randomDate(new Date(2e3,0,1),new Date)).format("D.M.YYYY"),e=Math.round(Math.random()*Math.random()*100*100)/100,a=Math.round(Math.random()*Math.random()*100*100)/100,r=Math.round(Math.random()*Math.random()*100*100)/100;return"<tr><td>"+randomName()+"</td><td>"+e+"</td><td>"+a+"</td><td>"+r+"</td><td>"+Math.round(100*(e+a+r))/100+"</td><td data-dateformat='D-M-YYYY'>"+t+"</td></tr>"}function customSort(){alert("Custom sort.")}!function(t,e){"use strict";"function"==typeof define&&define.amd?define("tinysort",function(){return e}):t.tinysort=e}(this,function(){"use strict";function t(t,e){for(var a,r=t.length,o=r;o--;)e(t[a=r-o-1],a)}function e(t,e,a){for(var o in e)(a||t[o]===r)&&(t[o]=e[o]);return t}function a(t,e,a){u.push({prepare:t,sort:e,sortBy:a})}var r,o=!1,n=null,s=window,d=s.document,i=parseFloat,l=/(-?\d+\.?\d*)\s*$/g,c=/(\d+\.?\d*)\s*$/g,u=[],f=0,h=0,p=String.fromCharCode(4095),m={selector:n,order:"asc",attr:n,data:n,useVal:o,place:"org",returns:o,cases:o,natural:o,forceStrings:o,ignoreDashes:o,sortFunction:n,useFlex:o,emptyEnd:o};return s.Element&&function(t){t.matchesSelector=t.matchesSelector||t.mozMatchesSelector||t.msMatchesSelector||t.oMatchesSelector||t.webkitMatchesSelector||function(t){for(var e=this,a=(e.parentNode||e.document).querySelectorAll(t),r=-1;a[++r]&&a[r]!=e;);return!!a[r]}}(Element.prototype),e(a,{loop:t}),e(function(a,s){function v(t){var a=!!t.selector,r=a&&":"===t.selector[0],o=e(t||{},m);E.push(e({hasSelector:a,hasAttr:!(o.attr===n||""===o.attr),hasData:o.data!==n,hasFilter:r,sortReturnNumber:"asc"===o.order?1:-1},o))}function b(t,e,a){for(var r=a(t.toString()),o=a(e.toString()),n=0;r[n]&&o[n];n++)if(r[n]!==o[n]){var s=Number(r[n]),d=Number(o[n]);return s==r[n]&&d==o[n]?s-d:r[n]>o[n]?1:-1}return r.length-o.length}function g(t){for(var e,a,r=[],o=0,n=-1,s=0;e=(a=t.charAt(o++)).charCodeAt(0);){var d=46==e||e>=48&&57>=e;d!==s&&(r[++n]="",s=d),r[n]+=a}return r}function w(){return Y.forEach(function(t){F.appendChild(t.elm)}),F}function S(t){var e=t.elm,a=d.createElement("div");return t.ghost=a,e.parentNode.insertBefore(a,e),t}function y(t,e){var a=t.ghost,r=a.parentNode;r.insertBefore(e,a),r.removeChild(a),delete t.ghost}function C(t,e){var a,r=t.elm;return e.selector&&(e.hasFilter?r.matchesSelector(e.selector)||(r=n):r=r.querySelector(e.selector)),e.hasAttr?a=r.getAttribute(e.attr):e.useVal?a=r.value||r.getAttribute("value"):e.hasData?a=r.getAttribute("data-"+e.data):r&&(a=r.textContent),M(a)&&(e.cases||(a=a.toLowerCase()),a=a.replace(/\s+/g," ")),null===a&&(a=p),a}function M(t){return"string"==typeof t}M(a)&&(a=d.querySelectorAll(a)),0===a.length&&console.warn("No elements to sort");var x,N,F=d.createDocumentFragment(),D=[],Y=[],$=[],E=[],k=!0,A=a.length&&a[0].parentNode,T=A.rootNode!==document,R=a.length&&(s===r||!1!==s.useFlex)&&!T&&-1!==getComputedStyle(A,null).display.indexOf("flex");return function(){0===arguments.length?v({}):t(arguments,function(t){v(M(t)?{selector:t}:t)}),f=E.length}.apply(n,Array.prototype.slice.call(arguments,1)),t(a,function(t,e){N?N!==t.parentNode&&(k=!1):N=t.parentNode;var a=E[0],r=a.hasFilter,o=a.selector,n=!o||r&&t.matchesSelector(o)||o&&t.querySelector(o)?Y:$,s={elm:t,pos:e,posn:n.length};D.push(s),n.push(s)}),x=Y.slice(0),Y.sort(function(e,a){var n=0;for(0!==h&&(h=0);0===n&&f>h;){var s=E[h],d=s.ignoreDashes?c:l;if(t(u,function(t){var e=t.prepare;e&&e(s)}),s.sortFunction)n=s.sortFunction(e,a);else if("rand"==s.order)n=Math.random()<.5?1:-1;else{var p=o,m=C(e,s),v=C(a,s),w=""===m||m===r,S=""===v||v===r;if(m===v)n=0;else if(s.emptyEnd&&(w||S))n=w&&S?0:w?1:-1;else{if(!s.forceStrings){var y=M(m)?m&&m.match(d):o,x=M(v)?v&&v.match(d):o;y&&x&&m.substr(0,m.length-y[0].length)==v.substr(0,v.length-x[0].length)&&(p=!o,m=i(y[0]),v=i(x[0]))}n=m===r||v===r?0:s.natural&&(isNaN(m)||isNaN(v))?b(m,v,g):v>m?-1:m>v?1:0}}t(u,function(t){var e=t.sort;e&&(n=e(s,p,m,v,n))}),0==(n*=s.sortReturnNumber)&&h++}return 0===n&&(n=e.pos>a.pos?1:-1),n}),function(){var t=Y.length===D.length;if(k&&t)R?Y.forEach(function(t,e){t.elm.style.order=e}):N?N.appendChild(w()):console.warn("parentNode has been removed");else{var e=E[0].place,a="start"===e,r="end"===e,o="first"===e,n="last"===e;if("org"===e)Y.forEach(S),Y.forEach(function(t,e){y(x[e],t.elm)});else if(a||r){var s=x[a?0:x.length-1],d=s&&s.elm.parentNode,i=d&&(a&&d.firstChild||d.lastChild);i&&(i!==s.elm&&(s={elm:i}),S(s),r&&d.appendChild(s.ghost),y(s,w()))}else(o||n)&&y(S(x[o?0:x.length-1]),w())}}(),Y.map(function(t){return t.elm})},{plugin:a,defaults:m})}()),function(t,e){"function"==typeof define&&define.amd?define(["jquery","tinysort","moment"],e):e(t.jQuery,t.tinysort,t.moment||void 0)}(this,function(t,e,a){var r,o,n,s=t(document);function d(e){var s=void 0!==a;r=e.sign?e.sign:"arrow","default"==e.customSort&&(e.customSort=c),o=e.customSort||o||c,n=e.emptyEnd,t("table.sortable").each(function(){var r=t(this),o=!0===e.applyLast;r.find("span.sign").remove(),r.find("> thead [colspan]").each(function(){for(var e=parseFloat(t(this).attr("colspan")),a=1;a<e;a++)t(this).after('<th class="colspan-compensate">')}),r.find("> thead [rowspan]").each(function(){for(var e=t(this),a=parseFloat(e.attr("rowspan")),r=1;r<a;r++){var o=e.parent("tr"),n=o.next("tr"),s=o.children().index(e);n.children().eq(s).before('<th class="rowspan-compensate">')}}),r.find("> thead tr").each(function(e){t(this).find("th").each(function(a){var r=t(this);r.addClass("nosort").removeClass("up down"),r.attr("data-sortcolumn",a),r.attr("data-sortkey",a+"-"+e)})}),r.find("> thead .rowspan-compensate, .colspan-compensate").remove(),r.find("th").each(function(){var e=t(this);if(void 0!==e.attr("data-dateformat")&&s){var o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var r=t(this);r.attr("data-value",a(r.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss"))})}else if(void 0!==e.attr("data-valueprovider")){o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var a=t(this);a.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(a.text())[0])})}}),r.find("td").each(function(){var e=t(this);void 0!==e.attr("data-dateformat")&&s?e.attr("data-value",a(e.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss")):void 0!==e.attr("data-valueprovider")?e.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(e.text())[0]):void 0===e.attr("data-value")&&e.attr("data-value",e.text())});var n=l(r),d=n.bsSort;r.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var a=t(this),r=a.closest("table.sortable");a.data("sortTable",r);var s=a.attr("data-sortkey"),i=o?n.lastSort:-1;d[s]=o?d[s]:a.attr("data-defaultsort"),void 0!==d[s]&&o===(s===i)&&(d[s]="asc"===d[s]?"desc":"asc",u(a,r))})})}function i(e){var a=t(e),r=a.data("sortTable")||a.closest("table.sortable");u(a,r)}function l(e){var a=e.data("bootstrap-sortable-context");return void 0===a&&(a={bsSort:[],lastSort:void 0},e.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var r=t(this),o=r.attr("data-sortkey");a.bsSort[o]=r.attr("data-defaultsort"),void 0!==a.bsSort[o]&&(a.lastSort=o)}),e.data("bootstrap-sortable-context",a)),a}function c(t,a){e(t,a)}function u(e,a){a.trigger("before-sort");var s=parseFloat(e.attr("data-sortcolumn")),d=l(a),i=d.bsSort;if(e.attr("colspan")){var c=parseFloat(e.data("mainsort"))||0,f=parseFloat(e.data("sortkey").split("-").pop());if(a.find("> thead tr").length-1>f)return void u(a.find('[data-sortkey="'+(s+c)+"-"+(f+1)+'"]'),a);s+=c}var h=e.attr("data-defaultsign")||r;if(a.find("> thead th").each(function(){t(this).removeClass("up").removeClass("down").addClass("nosort")}),t.browser.mozilla){var p=a.find("> thead div.mozilla");void 0!==p&&(p.find(".sign").remove(),p.parent().html(p.html())),e.wrapInner('<div class="mozilla"></div>'),e.children().eq(0).append('<span class="sign '+h+'"></span>')}else a.find("> thead span.sign").remove(),e.append('<span class="sign '+h+'"></span>');var m=e.attr("data-sortkey"),v="desc"!==e.attr("data-firstsort")?"desc":"asc",b=i[m]||v;d.lastSort!==m&&void 0!==i[m]||(b="asc"===b?"desc":"asc"),i[m]=b,d.lastSort=m,"desc"===i[m]?(e.find("span.sign").addClass("up"),e.addClass("up").removeClass("down nosort")):e.addClass("down").removeClass("up nosort");var g=a.children("tbody").children("tr"),w=[];t(g.filter('[data-disablesort="true"]').get().reverse()).each(function(e,a){var r=t(a);w.push({index:g.index(r),row:r}),r.remove()});var S=g.not('[data-disablesort="true"]');if(0!=S.length){var y="asc"===i[m]&&n;o(S,{emptyEnd:y,selector:"td:nth-child("+(s+1)+")",order:i[m],data:"value"})}t(w.reverse()).each(function(t,e){0===e.index?a.children("tbody").prepend(e.row):a.children("tbody").children("tr").eq(e.index-1).after(e.row)}),a.find("> tbody > tr > td.sorted,> thead th.sorted").removeClass("sorted"),S.find("td:eq("+s+")").addClass("sorted"),e.addClass("sorted"),a.trigger("sorted")}if(t.bootstrapSortable=function(t){null==t?d({}):t.constructor===Boolean?d({applyLast:t}):void 0!==t.sortingHeader?i(t.sortingHeader):d(t)},s.on("click",'table.sortable>thead th[data-defaultsort!="disabled"]',function(t){i(this)}),!t.browser){t.browser={chrome:!1,mozilla:!1,opera:!1,msie:!1,safari:!1};var f=navigator.userAgent;t.each(t.browser,function(e){t.browser[e]=!!new RegExp(e,"i").test(f),t.browser.mozilla&&"mozilla"===e&&(t.browser.mozilla=!!new RegExp("firefox","i").test(f)),t.browser.chrome&&"safari"===e&&(t.browser.safari=!1)})}t(t.bootstrapSortable)}),function(){var t=$("table");t.append(newTableRow()),t.append(newTableRow()),$("button.add-row").on("click",function(){var e=$(this);t.append(newTableRow()),e.data("sort")?$.bootstrapSortable(!0):$.bootstrapSortable(!1)}),$("button.change-sort").on("click",function(){$(this).data("custom")?$.bootstrapSortable(!0,void 0,customSort):$.bootstrapSortable(!0,void 0,"default")}),t.on("sorted",function(){alert("Table was sorted.")}),$("#event").on("change",function(){$(this).is(":checked")?t.on("sorted",function(){alert("Table was sorted.")}):t.off("sorted")}),$("input[name=sign]:radio").change(function(){$.bootstrapSortable(!0,$(this).val())})}();
_x000D_
table.sortable span.sign { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th:after { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th.arrow:after { content: ''; } table.sortable span.arrow, span.reversed, th.arrow.down:after, th.reversedarrow.down:after, th.arrow.up:after, th.reversedarrow.up:after { border-style: solid; border-width: 5px; font-size: 0; border-color: #ccc transparent transparent transparent; line-height: 0; height: 0; width: 0; margin-top: -2px; } table.sortable span.arrow.up, th.arrow.up:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed, th.reversedarrow.down:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed.up, th.reversedarrow.up:after { border-color: #ccc transparent transparent transparent; margin-top: -2px; } table.sortable span.az:before, th.az.down:after { content: "a .. z"; } table.sortable span.az.up:before, th.az.up:after { content: "z .. a"; } table.sortable th.az.nosort:after, th.AZ.nosort:after, th._19.nosort:after, th.month.nosort:after { content: ".."; } table.sortable span.AZ:before, th.AZ.down:after { content: "A .. Z"; } table.sortable span.AZ.up:before, th.AZ.up:after { content: "Z .. A"; } table.sortable span._19:before, th._19.down:after { content: "1 .. 9"; } table.sortable span._19.up:before, th._19.up:after { content: "9 .. 1"; } table.sortable span.month:before, th.month.down:after { content: "jan .. dec"; } table.sortable span.month.up:before, th.month.up:after { content: "dec .. jan"; } table.sortable thead th:not([data-defaultsort=disabled]) { cursor: pointer; position: relative; top: 0; left: 0; } table.sortable thead th:hover:not([data-defaultsort=disabled]) { background: #efefef; } table.sortable thead th div.mozilla { position: relative; }
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css rel=stylesheet><link href=https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><div class=container><div class=hero-unit><h1>Bootstrap Sortable</h1></div><table class="sortable table table-bordered table-striped"><thead><tr><th style=width:20%;vertical-align:middle data-defaultsign=nospan class=az data-defaultsort=asc rowspan=2><i class="fa fa-fw fa-map-marker"></i>Name<th style=text-align:center colspan=4 data-mainsort=3>Results<th data-defaultsort=disabled><tr><th style=width:20% colspan=2 data-mainsort=1 data-firstsort=desc>Round 1<th style=width:20%>Round 2<th style=width:20%>Total<t
Was searching around for an answer to the same question, but think I found a better solution: http://blog.grayghostvisuals.com/compass/image-url/
Basically, you can set your image path in config.rb and you use the image-url() helper
you can use the below css styles for all browsers except Firefox 30
select {
background: url(dropdown_arw.png) no-repeat right center;
appearance: none;
-moz-appearance: none;
-webkit-appearance: none;
width: 90px;
text-indent: 0.01px;
text-overflow: "";
}
demo page - http://kvijayanand.in/jquery-plugin/test.html
Updated
here is solution for Firefox 30. little trick for custom select elements in firefox :-moz-any() css pseudo class.
As adapted from Erika Ehrli's blog, this should do it:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Save the document to a file and auto-indent the output.
using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) {
writer.Formatting = Formatting.Indented;
doc.Save(writer);
}
public class list {
public static String name(Character k){
String s="the quick brown fox jumped over the lazy dog.";
int count=0;
String l1="";
String l="";
List<Character> list=new ArrayList<Character>();
for(int i1=0;i1<s.length();i1++){
list.add(s.charAt(i1));
}
list.sort(null);
for (Character character : list) {
l+=character;
}
for (int i1=0;i1<l.length();i1++) {
if((l.charAt(i1)==k)){
count+=1;
l1=l.charAt(i1)+" "+Integer.toString(count);
if(k==' '){
l1="Space"+" "+Integer.toString(count);
}
}else{
count=0;
}
}
return l1;
}
public static void main(String[] args){
String g = name('.');
System.out.println(g);
}
}
I had the same problem recently and this helped me:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="FILENAME"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize("PATH/TO/FILE"));
ob_clean();
flush();
readfile(PATH/TO/FILE);
exit();
I found this answer here
There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0)
you are less likely to to see a difference between the two approaches.
There is no difference between the two. You can use either of them in your code.
System.String
is a class (reference type) defined the mscorlib
in the namespace System
. In other words, System.String
is a type in the CLR
.
string
is a keyword in C#
I had this code in a fragment and it was crashing if I try to come back to this fragment
if (mRootView == null) {
mRootView = inflater.inflate(R.layout.fragment_main, container, false);
}
after gathering the answers on this thread, I realised that mRootView's parent still have mRootView as child. So, this was my fix.
if (mRootView == null) {
mRootView = inflater.inflate(R.layout.fragment_main, container, false);
} else {
((ViewGroup) mRootView.getParent()).removeView(mRootView);
}
hope this helps
"Is it safe..?" is a question about the language standard and the generated code.
"Is is a good practice?" is a question about how well the statement is understood by any arbitrary human reader of the statement. If you are asking this question, it suggests that the "safe" version is less clear to future readers and writers.
Excerpt from my Blog-Note-to-myself:
Now you can import a dump file e.g. if you are migrating between machines / subversion versions. e.g. if I had created a dump file from the source repository and load it into the new repository as shown below.
Commands for Unix-like systems (from terminal):
svnadmin dump /path/to/your/old/repo > backup.dump
svnadmin load /path/to/your/new/repo < backup.dump.dmp
Commands for Microsoft Windows systems (from cmd shell):
svnadmin dump C:\path\to\your\old\repo > backup.dump
svnadmin load C:\path\to\your\old\repo < backup.dump
This may be a cause of the disk space as well, In Elasticsearch 7.5.2, by default, if disk usage is above 85% then replica shards are not assigned to any other node.
This can be fixed by setting a different threshold or by disabling it either in the .yml or via Kibana
PUT _cluster/settings
{
"persistent": {
"cluster.routing.allocation.disk.threshold_enabled": "false"
}
}
I am not seeing any JOIN approaches, which have many uses in terms of duplicates.
This approach gives you actual doubled results.
SELECT t1.* FROM my_table as t1
LEFT JOIN my_table as t2
ON t1.name=t2.name and t1.id!=t2.id
WHERE t2.id IS NOT NULL
ORDER BY t1.name
Assuming userInfoList
is a List<UserInfo>
:
var groups = userInfoList
.GroupBy(n => n.metric)
.Select(n => new
{
MetricName = n.Key,
MetricCount = n.Count()
}
)
.OrderBy(n => n.MetricName);
The lambda function for GroupBy()
, n => n.metric
means that it will get field metric
from every UserInfo
object encountered. The type of n
is depending on the context, in the first occurrence it's of type UserInfo
, because the list contains UserInfo
objects. In the second occurrence n
is of type Grouping
, because now it's a list of Grouping
objects.
Grouping
s have extension methods like .Count()
, .Key()
and pretty much anything else you would expect. Just as you would check .Lenght
on a string
, you can check .Count()
on a group.
Should just be this:
var jobject = JsonConvert.DeserializeObject<RootObject>(jsonstring);
You can paste the json string to here: http://json2csharp.com/ to check your classes are correct.
In the question above the right answer would be to use Mock
, or to be more precise create_autospec
(because it will add spec to the mock methods of the class you are mocking), the defined spec
on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some
from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch
class MyClass:
@staticmethod
def method(foo, bar):
print(foo)
def something(some_class: MyClass):
arg = 1
# Would fail becuase of wrong parameters passed to methd.
return some_class.method(arg)
def second(some_class: MyClass):
arg = 1
return some_class.unexisted_method(arg)
class TestSomethingTestCase(TestCase):
def test_something_with_autospec(self):
mock = create_autospec(MyClass)
mock.method.return_value = True
# Fails because of signature misuse.
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_something(self):
mock = Mock() # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
mock.method.return_value = True
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
class TestSecondTestCase(TestCase):
def test_second_with_autospec(self):
mock = Mock(spec=MyClass)
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second(self):
mock = Mock()
mock.unexisted_method.return_value = True
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
The test cases with defined spec used fail because methods called from something
and second
functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock
will display.
As a side note there is one more option: use patch.object to mock just the class method which is called with.
The good use cases for patch would be the case when the class is used as inner part of function:
def something():
arg = 1
return MyClass.method(arg)
Then you will want to use patch as a decorator to mock the MyClass.
To extract the audio stream without re-encoding:
ffmpeg -i input-video.avi -vn -acodec copy output-audio.aac
-vn
is no video. -acodec copy
says use the same audio stream that's already in there. Read the output to see what codec it is, to set the right filename extension.
Literally all you have to do is:
echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile
and restart your shell.
If you have multiple JDK versions installed and you want it to be a specific one, you can use the -v
flag to java_home
like so:
echo export "JAVA_HOME=\$(/usr/libexec/java_home -v 1.7)" >> ~/.bash_profile
Use String#trim()
method or String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")
for trim both the end.
For left trim:
String leftRemoved = myString.replaceAll("^\\s+", "");
For right trim:
String rightRemoved = myString.replaceAll("\\s+$", "");
If you look at the code for the component you can see that it uses the className
prop passed to it to combine with the row
class to get the resulting set of classes (<Row className="aaa bbb"...
works).Also, if you provide the id
prop like <Row id="444" ...
it will actually set the id attribute for the element.
If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?
It might not be the best way but you may type the following
=IF(sheet1!A1<>"",sheet1!A1,"")
and drag it down to the maximum number of rows you expect.
If you need the width of something that's hidden and you can't un-hide it for whatever reason, you can clone it, change the CSS so it displays off the page, make it invisible, and then measure it. The user will be none the wiser if it's hidden and deleted afterwards.
Some of the other answers here just make the visibility hidden which works, but it will take up a blank spot on your page for a fraction of a second.
Example:
$itemClone = $('.hidden-item').clone().css({
'visibility': 'hidden',
'position': 'absolute',
'z-index': '-99999',
'left': '99999999px',
'top': '0px'
}).appendTo('body');
var width = $itemClone.width();
$itemClone.remove();
MRalwasser, I'd give you a hint, cast the URL.getConnection()
to JarURLConnection
.
Then use JarURLConnection.getJarFile() and voila! You have the JarFile and you are free to access the resources inside.
The rest I leave to you.
Hope this helps!
According to Tom Hawtin
A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.
Now I'm trying to emulate the JavaScript closure example on Wikipedia, with a "straigth" translation to Java, in the hope to be useful:
//ECMAScript
var f, g;
function foo() {
var x = 0;
f = function() { return ++x; };
g = function() { return --x; };
x = 1;
print('inside foo, call to f(): ' + f()); // "2"
}
foo();
print('call to g(): ' + g()); // "1"
print('call to f(): ' + f()); // "2"
Now the java part: Function1 is "Functor" interface with arity 1 (one argument). Closure is the class implementing the Function1, a concrete Functor that acts as function (int -> int). In the main() method I just instantiate foo as a Closure object, replicating the calls from the JavaScript example. The IntBox class is just a simple container, it behave like an array of 1 int:
int a[1] = {0}
interface Function1 {
public final IntBag value = new IntBag();
public int apply();
}
class Closure implements Function1 {
private IntBag x = value;
Function1 f;
Function1 g;
@Override
public int apply() {
// print('inside foo, call to f(): ' + f()); // "2"
// inside apply, call to f.apply()
System.out.println("inside foo, call to f.apply(): " + f.apply());
return 0;
}
public Closure() {
f = new Function1() {
@Override
public int apply() {
x.add(1);
return x.get();
}
};
g = new Function1() {
@Override
public int apply() {
x.add(-1);
return x.get();
}
};
// x = 1;
x.set(1);
}
}
public class ClosureTest {
public static void main(String[] args) {
// foo()
Closure foo = new Closure();
foo.apply();
// print('call to g(): ' + g()); // "1"
System.out.println("call to foo.g.apply(): " + foo.g.apply());
// print('call to f(): ' + f()); // "2"
System.out.println("call to foo.f.apply(): " + foo.f.apply());
}
}
It prints:
inside foo, call to f.apply(): 2
call to foo.g.apply(): 1
call to foo.f.apply(): 2
Great solution, thank you! I took the AndyDBell's question and Cuong Le's answer to build an example with two diferent interface's implementation:
public interface ISample
{
int SampleId { get; set; }
}
public class Sample1 : ISample
{
public int SampleId { get; set; }
public Sample1() { }
}
public class Sample2 : ISample
{
public int SampleId { get; set; }
public String SampleName { get; set; }
public Sample2() { }
}
public class SampleGroup
{
public int GroupId { get; set; }
public IEnumerable<ISample> Samples { get; set; }
}
class Program
{
static void Main(string[] args)
{
//Sample1 instance
var sz = "{\"GroupId\":1,\"Samples\":[{\"SampleId\":1},{\"SampleId\":2}]}";
var j = JsonConvert.DeserializeObject<SampleGroup>(sz, new SampleConverter<Sample1>());
foreach (var item in j.Samples)
{
Console.WriteLine("id:{0}", item.SampleId);
}
//Sample2 instance
var sz2 = "{\"GroupId\":1,\"Samples\":[{\"SampleId\":1, \"SampleName\":\"Test1\"},{\"SampleId\":2, \"SampleName\":\"Test2\"}]}";
var j2 = JsonConvert.DeserializeObject<SampleGroup>(sz2, new SampleConverter<Sample2>());
//Print to show that the unboxing to Sample2 preserved the SampleName's values
foreach (var item in j2.Samples)
{
Console.WriteLine("id:{0} name:{1}", item.SampleId, (item as Sample2).SampleName);
}
Console.ReadKey();
}
}
And a generic version to the SampleConverter:
public class SampleConverter<T> : CustomCreationConverter<ISample> where T: new ()
{
public override ISample Create(Type objectType)
{
return ((ISample)new T());
}
}
Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.
I think this will help you better
Person p = new Person("Bruce", "Willis");
Person p1 = new Person("Tom", "Hanks");
Person p2 = new Person("Nicolas", "Cage");
Person p3 = new Person("John", "Travolta");
ArrayList<Person> list = new ArrayList<Person>();
list.add(p);
list.add(p1);
list.add(p2);
list.add(p3);
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
return p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
}
});
Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie
There's a plugin for jQuery called 'rich array' discussed in Rich Array jQuery plugin .
Shorter inline image URL, shows only down arrow, customisable arrow colour...
From https://codepen.io/jonmircha/pen/PEvqPa
Author is probably Jonathan MirCha
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='%238C98F2'><polygon points='0,0 100,0 50,50'/></svg>") no-repeat;
background-size: 12px;
background-position: calc(100% - 20px) center;
background-repeat: no-repeat;
background-color: #efefef;
}
One alternate way if file contains strings without spaces with 1string each line:
fileItemString=$(cat filename |tr "\n" " ")
fileItemArray=($fileItemString)
Check:
Print whole Array:
${fileItemArray[*]}
Length=${#fileItemArray[@]}
<View style={{flexDirection:'row'}}>
<Text style={{flex: 1, flexWrap: 'wrap'}}>
This will work
Using Heat.exe to smash face and inflict "Epic Pwnage" on painfully large installs
Expanding on Si's and
Robert-P's answers about heat.
Translation:
(Using heat to avoid typing individual files into the project by hand and for automating builds for an overall easier process.)
WiX 2.0 Heat Syntax detailed
For newer versions (not all that different from older versions but there are potentially annoying syntax changes....) go to the directory Heat is in from the cmd.exe and just type in heat but I have a example one right here for help with newer versions if needed.
Adding the following to your Build Event in visual studio 2010.
(Right Click Project->Properties ->Build Events-> Pre-Build Events)
$(WIX)bin\heat.exe" dir "$(EnviromentVariable)" -cg GroupVariable -gg -scom -sreg -sfrag -
srd -dr INSTALLLOCATION -var env.LogicPath -out "$(FragmentDir)\FileName.wxs
-gg
Generates Guids when heat is run(as in when you execute the command above)
-scom
Dont grab "COM files"
-sreg
Dont grab "Registry Files"
-sfrag
Dont grab "Fragments"
-srd
Dont grab the "root Dir"
dir
dir indicates you want Heat to look in a folder
"$(EnviromentVariable)"
The name of the variable you would add to the Preprocessor variables in the (Right click project, Go to properties) project properties->Build section where it says Define preprocessor variables (assumes visual studio 2010)
Example: EnviromentVariable=C:\Project\bin\Debug;No double quotes but end with a semicolon
-cg GroupVariable
The ComponentGroup that will be referenced from the fragment created to the main wxs file
FragmentDir
The fragment directory where the output wxs fragment will be stored
FileName.wxs
The the name of the file
Full tutorial here, So freakin helpful
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
Note that you can use as well the Descending keyword in the OrderBy (in case you need). So another possible answer is:
MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate);
Try this,
int id = getResources().getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);
This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following
imageview.setImageResource(id);
You can add a PPA that provides a relatively current version of SmartGit(as well as SmartGitHg, the predecessor of SmartGit).
To add the PPA run:
sudo add-apt-repository ppa:eugenesan/ppa
sudo apt-get update
To install smartgit
(after adding the PPA) run:
sudo apt-get install smartgit
To install smartgithg
(after adding the PPA) run:
sudo apt-get install smartgithg
This should add a menu option for you
For more information, see Eugene San PPA.
This repository contains collection of customized, updated, ported and backported packages for two last LTS releases and latest pre-LTS release
Almost 5 years later, I think my answer can reduce a little bit the hard work of many people.
Update an element in the DOM with the HTML from the one from the ajax call can be achieved that way
$('#submitform').click(function() {
$.ajax({
url: "getinfo.asp",
data: {
txtsearch: $('#appendedInputButton').val()
},
type: "GET",
dataType : "html",
success: function (data){
$('#showresults').html($('#showresults',data).html());
// similar to $(data).find('#showresults')
},
});
or with replaceWith()
// codes
success: function (data){
$('#showresults').replaceWith($('#showresults',data));
},
This code makes a window with the conditions that the user cannot change the dimensions of the Tk()
window, and also disables the maximise button.
import tkinter as tk
root = tk.Tk()
root.resizable(width=False, height=False)
root.mainloop()
Within the program you can change the window dimensions with @Carpetsmoker's answer, or by doing this:
root.geometry('{}x{}'.format(<widthpixels>, <heightpixels>))
It should be fairly easy for you to implement that into your code. :)
If you need to convert some of them to numbers and don't know in advance which ones, some additional code will be needed. Try something like this:
b = []
for x in a:
temp = []
items = x.split(",")
for item in items:
try:
n = int(item)
except ValueError:
temp.append(item)
else:
temp.append(n)
b.append(temp)
This is longer than the other answers, but it's more versatile.
There's a shortcut to delete the branch in the origin:
git push origin :<branch_name>
Which is the same as doing git push origin --delete <branch_name>
Use:
+ scale_y_continuous(labels = scales::percent)
Or, to specify formatting parameters for the percent:
+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))
(the command labels = percent
is obsolete since version 2.2.1 of ggplot2)
It is the CSS child selector. Example:
div > p
selects all paragraphs that are direct children of div.
See this
if you use sqldeveloper 18.2.0
edit %APPDATA%\sqldeveloper\18.2.0\product.conf
jdk9, jdk10, and jdk11 are not supported
change back to jdk 8
for example
SetJavaHome C:\Program Files\ojdkbuild\java-1.8.0-openjdk-1.8.0.191-1
In Eclipse it is very easy to point Tomcat to a new JVM (in this example JRE6). My problem was I couldn't find where to do it. Here is the trick:
That's all. Interesting, only steps 7-10 seem to matter, and they will change the JRE used on all servers you have previously defined to use TOMCAT v7.0. The rest of the steps are just because I can't find any other way to get to the screen except by defining a new server. Does anyone else know an easier way?
/* This code is just for convert a single uppercase character to lowercase
character & vice versa.................*/
/* This code is made without java library function, and also uses run time input...*/
import java.util.Scanner;
class CaseConvert {
char c;
void input(){
//@SuppressWarnings("resource") //only eclipse users..
Scanner in =new Scanner(System.in); //for Run time input
System.out.print("\n Enter Any Character :");
c=in.next().charAt(0); // input a single character
}
void convert(){
if(c>=65 && c<=90){
c=(char) (c+32);
System.out.print("Converted to Lowercase :"+c);
}
else if(c>=97&&c<=122){
c=(char) (c-32);
System.out.print("Converted to Uppercase :"+c);
}
else
System.out.println("invalid Character Entered :" +c);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CaseConvert obj=new CaseConvert();
obj.input();
obj.convert();
}
}
/*OUTPUT..Enter Any Character :A Converted to Lowercase :a
Enter Any Character :a Converted to Uppercase :A
Enter Any Character :+invalid Character Entered :+*/
Isn't this maybe the most elegant?
REPLACE
INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock)
VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')
Here's a special case where one of data field has semicolon (";") as part of it's data in that case most of answers above will fail.
Solution it that case will be
string[] csvRows = System.IO.File.ReadAllLines(FullyQaulifiedFileName);
string[] fields = null;
List<string> lstFields;
string field;
bool quoteStarted = false;
foreach (string csvRow in csvRows)
{
lstFields = new List<string>();
field = "";
for (int i = 0; i < csvRow.Length; i++)
{
string tmp = csvRow.ElementAt(i).ToString();
if(String.Compare(tmp,"\"")==0)
{
quoteStarted = !quoteStarted;
}
if (String.Compare(tmp, ";") == 0 && !quoteStarted)
{
lstFields.Add(field);
field = "";
}
else if (String.Compare(tmp, "\"") != 0)
{
field += tmp;
}
}
if(!string.IsNullOrEmpty(field))
{
lstFields.Add(field);
field = "";
}
// This will hold values for each column for current row under processing
fields = lstFields.ToArray();
}
Using reflection, this is the function i use :
public static bool doesPropertyExist(dynamic obj, string property)
{
return ((Type)obj.GetType()).GetProperties().Where(p => p.Name.Equals(property)).Any();
}
then..
if (doesPropertyExist(myDynamicObject, "myProperty")){
// ...
}
The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:
FileSystemWatcher watcher;
private void watch()
{
watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
//Copies file to another directory.
}
Another syntax of doing the same thing is:
rails g migration AddUserToUpload user:belongs_to
You need to put your code into ngOnInit
and use the this
keyword:
ngOnInit() {
this.booksByStoreID = this.books.filter(
book => book.store_id === this.store.id);
}
You need ngOnInit
because the input store
wouldn't be set into the constructor:
ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)
In your code, the books filtering is directly defined into the class content...
If I'm correct, this is a bug in webkit (according to this). I'm not sure if there is much you can do, sorry for the weak answer.
There is, however, a work around which you can use. If you add the title
attribute to your image (e.g. title="Image Not Found"
) it'll work.
What you claim to have "tried doing" is exactly what you wrote in the code that works "as expected" when you invoke it with curl.
The error you're getting doesn't appear to be related to any of the code you've shown us.
If you want to get the raw request, set handlers on request
for the data
and end
events (and, of course, remove any invocations of express.bodyParser()
). Note that the data
events will occur in chunks, and that unless you set an encoding for the data
event those chunks will be buffers, not strings.
There is no difference ...
So principially you could use both (one at a time !-)
But for the sake of readability and for the cleanliness of the html-code I always prefer the window.onload !o]
The WiX project I was using was hard-set in the configuration manager for x64
across the board. When making the Custom Action project for the solution, it defaulted everything to x86
within the .csproj
file. So I unloaded the project, edited it by changing all x86
to x64
, saved, reloaded, and was good to go after that.
I don't understand why I had to do this. The configuration manager was set to build as x64, but just wouldn't get set in the csproj
file :(
sudo snap install androidsdk
You can use the sdkmanager to perform the following tasks.
androidsdk --list [options]
androidsdk packages [options]
The packages argument is an SDK-style path as shown with the --list command, wrapped in quotes (for example, "build-tools;29.0.0" or "platforms;android-28"). You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.
For example, here's how to install the latest platform tools (which includes adb and fastboot) and the SDK tools for API level 28:
androidsdk "platform-tools" "platforms;android-28"
Alternatively, you can pass a text file that specifies all packages:
androidsdk --package_file=package_file [options]
The package_file argument is the location of a text file in which each line is an SDK-style path of a package to install (without quotes).
To uninstall, simply add the --uninstall flag:
androidsdk --uninstall packages [options]
androidsdk --uninstall --package_file=package_file [options]
Update all installed packages
androidsdk --update [options]
androidsdk it is snap wraper of sdkmanager all options of sdkmanager work with androidsdk
Location of installed android sdk files : /home/user/AndroidSDK
See all sdkmanager options in google documentation
You could search for:
<li><a href="#">[^\n]+
And replace with:
$0</a>
Where $0
is the whole match. The exact semantics will depend on the language are you using though.
WARNING: You should avoid parsing HTML with regex. Here's why.
Try this..
<html>
<body>
<head>
<script type="text/javascript">
function splitString()
{
var myDimen=document.getElementById("dimen").value;
var splitDimen = myDimen.split("*");
document.getElementById("myImage").width=splitDimen[0];
document.getElementById("myImage").height=splitDimen[1];
}
</script>
</head>
<h2>Norwegian Mountain Trip</h2>
<img border="0" id="myImage" src="..." alt="Pulpit rock" width="304" height="228" /><br>
<input type="text" id="dimen" name="dimension" />
<input type="submit" value="Submit" Onclick ="splitString()"/>
</body>
</html>
In the text box give the dimension as ur wish, in the format 50*60. Click submit. You will get the resized image. Give your image path in place of dots in the image tag.
I've been on different threads on the past few hours trying to find a solution for my problem, to no avail. I see that many developers share this problem, and I think people here know about this. I have multiple images inside a UIScrollView
, trying to get tap events on them.
I am not getting any events from an UIImangeView
, but I do get an event from a similar UILable
with very similar parameters I am setting to it. Under iOS 5.1.
I have already done the following:
UIImageView
.UIImageView
, didn't help any.Attaching some code below, in this code I initialize both a UIImageView
and UILabel
, the label works fine in terms of firing events. I tried keeping out irrelevant code.
UIImageView *single_view = [[UIImageView alloc]initWithFrame:CGRectMake(200, 200, 100, 100)];
single_view.image = img;
single_view.layer.zPosition = 4;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
[single_view addGestureRecognizer:singleTap];
[single_view setMultipleTouchEnabled:YES];
[single_view setUserInteractionEnabled:YES];
[self.myScrollView addSubview:single_view];
self.myScrollView.userInteractionEnabled = YES;
UILabel *testLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
testLabel.backgroundColor = [UIColor redColor];
[self.myScrollView addSubview:testLabel];
[testLabel addGestureRecognizer:singleTap];
[testLabel setMultipleTouchEnabled:YES];
[testLabel setUserInteractionEnabled:YES];
testLabel.layer.zPosition = 4;
And the method which handles the event:
- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
UIView *tappedView = [gesture.view hitTest:[gesture locationInView:gesture.view] withEvent:nil];
NSLog(@"Touch event on view: %@", [tappedView class]);
}
As said, the label tap is received.
If you are using Eclipse Neon, try this:
1) Add the maven plugin in the properties section of the POM:
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
2) Force update of project snapshot by right clicking on Project
Maven -> Update Project -> Select your Project -> Tick on the 'Force Update of Snapshots/Releases' option -> OK
Total Commander also has a binary compare option:
go to: File \\Compare by content
ps. I guess some people may alredy be using this tool and may not be aware of the built-in feature.
Well, switch
probably wasn't really meant to work like this, but you can:
AA = 'foo'
switch(AA,
foo={
# case 'foo' here...
print('foo')
},
bar={
# case 'bar' here...
print('bar')
},
{
print('default')
}
)
...each case is an expression - usually just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...
Class Row
will handle one row from your database.
Complete implementation of UpdateTask responsible for filling up UI.
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.SwingWorker;
public class JTableUpdateTask extends SwingWorker<JTable, Row> {
JTable table = null;
ResultSet resultSet = null;
public JTableUpdateTask(JTable table, ResultSet rs) {
this.table = table;
this.resultSet = rs;
}
@Override
protected JTable doInBackground() throws Exception {
List<Row> rows = new ArrayList<Row>();
Object[] values = new Object[6];
while (resultSet.next()) {
values = new Object[6];
values[0] = resultSet.getString("id");
values[1] = resultSet.getString("student_name");
values[2] = resultSet.getString("street");
values[3] = resultSet.getString("city");
values[4] = resultSet.getString("state");
values[5] = resultSet.getString("zipcode");
Row row = new Row(values);
rows.add(row);
}
process(rows);
return this.table;
}
protected void process(List<Row> chunks) {
ResultSetTableModel tableModel = (this.table.getModel() instanceof ResultSetTableModel ? (ResultSetTableModel) this.table.getModel() : null);
if (tableModel == null) {
try {
tableModel = new ResultSetTableModel(this.resultSet.getMetaData(), chunks);
} catch (SQLException e) {
e.printStackTrace();
}
this.table.setModel(tableModel);
} else {
tableModel.getRows().addAll(chunks);
}
tableModel.fireTableDataChanged();
}
}
Table Model:
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
/**
* Simple wrapper around Object[] representing a row from the ResultSet.
*/
class Row {
private final Object[] values;
public Row(Object[] values) {
this.values = values;
}
public int getSize() {
return values.length;
}
public Object getValue(int i) {
return values[i];
}
}
// TableModel implementation that will be populated by SwingWorker.
public class ResultSetTableModel extends AbstractTableModel {
private final ResultSetMetaData rsmd;
private List<Row> rows;
public ResultSetTableModel(ResultSetMetaData rsmd, List<Row> rows) {
this.rsmd = rsmd;
if (rows != null) {
this.rows = rows;
} else {
this.rows = new ArrayList<Row>();
}
}
public int getRowCount() {
return rows.size();
}
public int getColumnCount() {
try {
return rsmd.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
public Object getValue(int row, int column) {
return rows.get(row).getValue(column);
}
public String getColumnName(int col) {
try {
return rsmd.getColumnName(col + 1);
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
public Class<?> getColumnClass(int col) {
String className = "";
try {
className = rsmd.getColumnClassName(col);
} catch (SQLException e) {
e.printStackTrace();
}
return className.getClass();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(rowIndex > rows.size()){
return null;
}
return rows.get(rowIndex).getValue(columnIndex);
}
public List<Row> getRows() {
return this.rows;
}
public void setRows(List<Row> rows) {
this.rows = rows;
}
}
Main Application which builds UI and does the database connection
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
public class MainApp {
static Connection conn = null;
static void init(final ResultSet rs) {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
final JTable table = new JTable();
table.setPreferredSize(new Dimension(300,300));
table.setMinimumSize(new Dimension(300,300));
table.setMaximumSize(new Dimension(300,300));
frame.add(table, BorderLayout.CENTER);
JButton button = new JButton("Start Loading");
button.setPreferredSize(new Dimension(30,30));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JTableUpdateTask jTableUpdateTask = new JTableUpdateTask(table, rs);
jTableUpdateTask.execute();
}
});
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, userName, password);
PreparedStatement pstmt = conn.prepareStatement("Select id, student_name, street, city, state,zipcode from student");
ResultSet rs = pstmt.executeQuery();
init(rs);
} catch (Exception e) {
e.printStackTrace();
}
}
}
an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers...
Why not use a mechanism similar to Apache cron jobs? http://en.wikipedia.org/wiki/Cron
For calendar\scheduling I'd use slightly different values for "bits" to accommodate standard calendar reoccurence events - instead of [day of week (0 - 7), month (1 - 12), day of month (1 - 31), hour (0 - 23), min (0 - 59)]
-- I'd use something like [Year (repeat every N years), month (1 - 12), day of month (1 - 31), week of month (1-5), day of week (0 - 7)]
Hope this helps.
Some numpy functions for how to control the rounding: rint, floor,trunc, ceil. depending how u wish to round the floats, up, down, or to the nearest int.
>>> x = np.array([[1.0,2.3],[1.3,2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> y = np.trunc(x)
>>> y
array([[ 1., 2.],
[ 1., 2.]])
>>> z = np.ceil(x)
>>> z
array([[ 1., 3.],
[ 2., 3.]])
>>> t = np.floor(x)
>>> t
array([[ 1., 2.],
[ 1., 2.]])
>>> a = np.rint(x)
>>> a
array([[ 1., 2.],
[ 1., 3.]])
To make one of this in to int, or one of the other types in numpy, astype (as answered by BrenBern):
a.astype(int)
array([[1, 2],
[1, 3]])
>>> y.astype(int)
array([[1, 2],
[1, 2]])
When reading the strtok documentation, I see you need to pass in a NULL pointer after the first "initializing" call. Maybe you didn't do that. Just a guess of course.
The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.
When working to create Cross Browser Favicons (including touch icons) there are several things to consider.
The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->
To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon"
for IE to recognize the icon it needs the word shortcut
which is not standard. Also we wrap the .ico
favicon in a IE conditional comment because Chrome and Safari will use the .ico
file if it is present, despite other options available, not what we would like.
The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.
For the rest of the browsers we are going to use the standard way to cite a favicon:
<link rel="icon" href="path/to/favicon.png">
This icon should be 196x196 pixels in size to cover all devices that may use this icon.
To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
Using rel="apple-touch-icon-precomposed"
will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon"
. This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed"
.
As a note: Chrome for Android states:
The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).
Custom Tiles for IE 11+ on Windows 8.1+
IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.
Microsoft recommends creating a few tiles at the following size:
Small: 128 x 128
Medium: 270 x 270
Wide: 558 x 270
Large: 558 x 558
These should be transparent images as we will define a color background next.
Once these images are created you should create an xml file called browserconfig.xml
with the following code:
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square70x70logo src="images/smalltile.png"/>
<square150x150logo src="images/mediumtile.png"/>
<wide310x150logo src="images/widetile.png"/>
<square310x310logo src="images/largetile.png"/>
<TileColor>#009900</TileColor>
</tile>
</msapplication>
</browserconfig>
Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head
:
<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />
For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.
Putting it all together:
To put it all together the above code would look like this:
<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->
<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. -->
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">
Windows Phone Live Tiles
If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:
Here are detailed instructions from Microsoft but here is a synopsis:
Step 1
Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.
Step 2
Add a hidden overlay of this image. Here is example code from Microsoft:
<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
<img src="customtile.png" width="320" height="320" />
<div style='margin-top: 40px'>
Add text/graphic asking user to pin to start using the menu...
</div>
</div>
Step 3
You then can add thew following line to add a pin to start link:
<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>
Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.
Step 4
Next you add some JS to toggle the overlay visibility
<script>
function ToggleTileOverlay() {
var newVisibility = (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
document.getElementById('TileOverlay').style.visibility = newVisibility;
}
</script>
Note on Sizes
I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.
Further Reading
For those who would like more details see the links below:
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
def permutation(str)
posibilities = []
str.split('').each do |char|
if posibilities.size == 0
posibilities[0] = char.downcase
posibilities[1] = char.upcase
else
posibilities_count = posibilities.length
posibilities = posibilities + posibilities
posibilities_count.times do |i|
posibilities[i] += char.downcase
posibilities[i+posibilities_count] += char.upcase
end
end
end
posibilities
end
Here is my take on a non recursive version
After running into the issue, I found out that my WOFF file was not done properly, I sent a new TTF to FontSquirrel which gave me a proper WOFF that was smooth in Firefox without adding any extra CSS to it.
To me, @warlock's looks like the best answer here so far, but I've always used this in the past;
string baseUrl = Request.Url.GetComponents(
UriComponents.SchemeAndServer, UriFormat.UriEscaped)
Or in a WebAPI controller;
string baseUrl = Url.Request.RequestUri.GetComponents(
UriComponents.SchemeAndServer, UriFormat.Unescaped)
which is handy so you can choose what escaping format you want. I'm not clear why there are two such different implementations, and as far as I can tell, this method and @warlock's return the exact same result in this case, but it looks like GetLeftPart()
would also work for non server Uri's like mailto
tags for instance.
If you want to run the script in a linux kickstart you have to run as below .
sh /tmp/script.sh > /dev/null 2>&1 < /dev/null &
Please read and strongly consider my advice in the comments of your post. That being said, if you still have a good reason to do this, check out this list of crypto modules for Node. It has modules for dealing with both sha1 and base64.
table {
border-spacing: 10px 0px;
}
.rightborder {
border-right: 1px solid #fff;
}
Then with your code you can:
<td class="rightborder">whatever</td>
Hope that helps!
This help me a lot:
http://maestric.com/doc/mac/apache_php_mysql_snow_leopard
It also works for Mac OS X Lion :D
.:EDIT:. On my case the prefepane only allows to start and stop mysql, but after some issues i've uninstalled him. If you need a application to run queries and create DB, you could use: Sequel Pro (it's free) or Navicat
If you need start and stop mysql in ~/.bash_profile you can add these lines:
#For MySQL
alias mysql_start="/Library/StartupItems/MySQLCOM/MySQLCOM start"
alias mysql_stop="/Library/StartupItems/MySQLCOM/MySQLCOM stop"
After reloaded the console just call:
$mysql_start
or
$mysql_stop
agreding the desired action. Hope helped you.
While the other answers are correct, there is an easy way to get rid of the underline on all those pesky links:
a {
text-decoration:none;
}
This will remove the underline from EVERY SINGLE LINK on your page!
It's method overloading, not method overriding. And in Python, you do it all in one function:
class A:
def stackoverflow(self, i='some_default_value'):
print 'only method'
ob=A()
ob.stackoverflow(2)
ob.stackoverflow()
You can't have two methods with the same name in Python -- and you don't need to.
See the Default Argument Values section of the Python tutorial. See "Least Astonishment" and the Mutable Default Argument for a common mistake to avoid.
See PEP 443 for information about the new single dispatch generic functions in Python 3.4.
This answer illustrates a pre-HTML5 approach. Please take a look at Psytronic's answer for a modern solution using the placeholder
attribute.
HTML:
<input type="text" name="firstname" title="First Name" style="color:#888;"
value="First Name" onfocus="inputFocus(this)" onblur="inputBlur(this)" />
JavaScript:
function inputFocus(i) {
if (i.value == i.defaultValue) { i.value = ""; i.style.color = "#000"; }
}
function inputBlur(i) {
if (i.value == "") { i.value = i.defaultValue; i.style.color = "#888"; }
}
One simple thing you could do is abstract the test inside a function.
local function isempty(s)
return s == nil or s == ''
end
if isempty(foo) then
foo = "default value"
end
Because you have used absolute positioning, and specified a top percentage, only margin-top will affect the location of your .item object. If instead you positioned it using bottom: 50%, then you'd need margin-bottom -8px to centre it, and margin-top would have no effect.
Margin affects the boundaries of an element in terms of positioning it, either absolutely as in your case, or relative to neighbouring elements. Imagine that margin is the foundations of your element on which it sits. They are typically the same size as it, but can be made larger or smaller on any or all of the four edges.
Your CSS tells the browser to position the top of your element the margin at a point 50% of the way down the page. However, as all elements are not a single pixel, the browser needs to know which part of it to line up 50% of the way down the page. For lining up the top of the element, it uses the top margin. By default this is in line with the top of the element, but you can alter it with CSS.
In your case, top 50% would result in the top of the element starting in the middle of the page. By applying a negative top margin, the browser uses the point 8px into the element from the top (ie the line across the middle of it) as the place to position at 50%.
If you apply a positive margin to the bottom, this extends the line the browser uses to position the bottom out away from the element itself, giving a gap between it and any adjacent element below, or affecting where it is placed absolutely if positioning based on the bottom.
Just set Label AutoSize property to False. Then the text will be wrapped and you can re-size the control manually to show the text.
if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
Image = Image.FromFile(@"c:\Images\test.jpg"),
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
OR
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
ImageLocation = @"c:\Images\test.jpg",
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
i'm not sure where you put images in your folder structure but you can find the path as bellow
picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");
Depending on your platform you can use: sqlite3 file_name.db from the terminal. .tables will list the tables, .schema is full layout. SQLite commands like: select * from table_name; and such will print out the full contents. Type: ".exit" to exit. No need to download a GUI application.Use a semi-colon if you want it to execute a single command. Decent SQLite usage tutorial http://www.thegeekstuff.com/2012/09/sqlite-command-examples/
10Y (!) had passed since this was asked, and still I see no mention of MS's good, non-GPL'ed solution: IMultiLanguage2 API.
Most libraries already mentioned are based on Mozilla's UDE - and it seems reasonable that browsers have already tackled similar problems. I don't know what is chrome's solution, but since IE 5.0 MS have released theirs, and it is:
It is a native COM call, but here's some very nice work by Carsten Zeumer, that handles the interop mess for .net usage. There are some others around, but by and large this library doesn't get the attention it deserves.
if you need to close your application from main() you can use this code
int main(int argc, char *argv[]){
QApplication app(argc, argv);
...
if(!QSslSocket::supportsSsl()) return app.exit(0);
...
return app.exec();
}
The program will terminated if OpenSSL is not installed
the credit goes for my senior colleague for this:
:> filename
This will not break log files, so you can even use it on syslog, for example.
Strings in Python are immutable meaning you cannot replace parts of them.
You can however create a new string that is modified. Mind that this is not semantically equivalent since other references to the old string will not be updated.
You could for instance write a function:
def replace_str_index(text,index=0,replacement=''):
return '%s%s%s'%(text[:index],replacement,text[index+1:])
And then for instance call it with:
new_string = replace_str_index(old_string,middle)
If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.
For instance:
replace_str_index('hello?bye',5)
will return 'hellobye'
; and:
replace_str_index('hello?bye',5,'good')
will return 'hellogoodbye'
.
I also had this problem today. Mine was caused by a cyclic dependency. Project A referenced Project B and vice versa.
All scripts should be imported in order:
Bootstrap-datetimepicker requires moment.js
to be loaded before datepicker.js
.
Working snippet:
$(function() {_x000D_
$('#datetimepicker1').datetimepicker();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class='col-sm-6'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker1'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.
USE [DBName]
GO
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema]
GO
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
Found this on github...
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import pandas