SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks
DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.
SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.
source: https://wiki.qt.io/MinGW-64-bit
If by configure release/build, you mean you only need one config per makefile, then it is simply a matter and decoupling CC and CFLAGS:
CFLAGS=-DDEBUG
#CFLAGS=-O2 -DNDEBUG
CC=g++ -g3 -gdwarf2 $(CFLAGS)
Depending on whether you can use gnu makefile, you can use conditional to make this a bit fancier, and control it from the command line:
DEBUG ?= 1
ifeq ($(DEBUG), 1)
CFLAGS =-DDEBUG
else
CFLAGS=-DNDEBUG
endif
.o: .c
$(CC) -c $< -o $@ $(CFLAGS)
and then use:
make DEBUG=0
make DEBUG=1
If you need to control both configurations at the same time, I think it is better to have build directories, and one build directory / config.
First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:
if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
return false;
}
Make sure you only fetch the headers, not the body content:
@curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY , true); // we don't need body
For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):
As a whole:
$url = 'http://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo 'HTTP code: ' . $httpcode;
Just append a hash with an ID of an element to the URL. E.g.
<div id="about"></div>
and
http://mysite.com/#about
So the link would look like:
<a href="http://mysite.com/#about">About</a>
or just
<a href="#about">About</a>
If you absolutely must use HTML to give your text color, you have to use the (deprecated) <font>
-tag:
<h2><font color="#006699">Process Report</font></h2>
But otherwise, I strongly recommend you to do as rekire said: use CSS.
You should check your designer file. Open Form1.Designer.cs and
find this line: windows Form Designer Generated Code.
Expand this and you will see a lot of code. So check Whether this line is there inside datagridview1 controls if not place it.
this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
I hope it helps.
Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to
find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
Just to sum up!
What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.
To do this after half day searching did it using:
docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb
This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.
To login in mysql after that can use:
mysql -u root -proot -h 127.0.0.1 -P3301
Used sources are:
The answer of Iarks in this article /using -it -d was the key :) /
how-to-install-and-use-docker-on-ubuntu-16-04
installing-and-using-mariadb-via-docker
mariadb-and-docker-use-cases-part-1
Good luck all!
By default, the below code will NOT generate a checked Check Box as model properties override the html attributes:
@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });
Instead, in your GET Action method, the following needs to be done:
model.SomeBooleanProperty = true;
The above will preserve your selection(If you uncheck the box) even if model is not valid(i.e. some error occurs on posting the form).
However, the following code will certainly generate a checked checkbox, but will not preserve your uncheck responses, instead make the checkbox checked every time on errors in form.
@Html.CheckBox("SomeBooleanProperty", new { @checked = "checked" });
UPDATE
//Get Method
public ActionResult CreateUser(int id)
{
model.SomeBooleanProperty = true;
}
Above code would generate a checked check Box at starting and will also preserve your selection even on errors in form.
Looking at the JDK, innermost constructor for Calendar.getInstance()
has this:
public GregorianCalendar(TimeZone zone, Locale aLocale) {
super(zone, aLocale);
gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);
setTimeInMillis(System.currentTimeMillis());
}
so it already automatically does what you suggest. Date's default constructor holds this:
public Date() {
this(System.currentTimeMillis());
}
So there really isn't need to get system time specifically unless you want to do some math with it before creating your Calendar/Date object with it. Also I do have to recommend joda-time to use as replacement for Java's own calendar/date classes if your purpose is to work with date calculations a lot.
$dob = $this->dateOfBirth; //Datetime
$currentDate = new \DateTime();
$dateDiff = $dob->diff($currentDate);
$years = $dateDiff->y;
$months = $dateDiff->m;
$days = $dateDiff->d;
$age = $years .' Year(s)';
if($years === 0) {
$age = $months .' Month(s)';
if($months === 0) {
$age = $days .' Day(s)';
}
}
return $age;
Sairam With the samples given above, I have tried & came out with the script which I wanted. The position parameters mentioned in other example gave different results. I wanted to create one Batch file to take the Oracle data backup (export data) on daily basis, preserving distinct DMP files with date & time as part of file name. Here is the script which worked well:
cls
set dt=%date:~0,2%%date:~3,2%%date:~6,4%-%time:~0,2%%time:~3,2%
set fn=backup-%dt%.DMP
echo %fn%
pause A
exp user/password file=D:\DATA_DMP\%fn%
See §6.7.9 Initialization:
21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
So, yes both of them work. Note that in C99 a new way of initialization, called designated initialization can be used too:
myStruct _m1 = {.c2 = 0, .c1 = 1};
In VB code, when trying to submit an INSERT
query, you must submit a double query in the same 'executenonquery' like this:
sqlQuery = "SET IDENTITY_INSERT dbo.TheTable ON; INSERT INTO dbo.TheTable (Col1, COl2) VALUES (Val1, Val2); SET IDENTITY_INSERT dbo.TheTable OFF;"
I used a ;
separator instead of a GO.
Works for me. Late but efficient!
He drinks rice (wrong semantic- meaningless, right syntax- grammar)
Hi drink water (right semantic- has meaning, wrong syntax- grammar)
You want to use os.path.expanduser.
This will ensure it works on all platforms:
from os.path import expanduser
home = expanduser("~")
If you're on Python 3.5+ you can use pathlib.Path.home():
from pathlib import Path
home = str(Path.home())
You can easily check for the Imagick class in PHP.
if( class_exists("Imagick") )
{
//Imagick is installed
}
To avoid the limitation of the file size , which can cause the Exception java.lang.OutOfMemoryError
to be thrown when creating an array of the file size byte[] bytes = new byte[(int) length];
, instead we could do
byte[] bytearray = new byte[1024*16];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
OutputStream output= socket.getOututStream();
BufferedInputStream bis = new BufferedInputStream(fis);
int readLength = -1;
while ((readLength = bis.read(bytearray)) > 0) {
output.write(bytearray, 0, readLength);
}
bis.close();
output.close();
}
catch(Exception ex ){
ex.printStackTrace();
} //Excuse the poor exception handling...
Try this:
Dim s = "RAJAN"
Dim firstChar = s(0)
You can even do this:
Dim firstChar = "RAJAN"(0)
You could use List inside the method and transform it to an array at the end. But i think if we talk about an max-value of 20, your code is faster.
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
List<InputProperty> ip = new List<InputProperty>();
for (int i = 0; i < nvPairs.Length; i++)
{
if (nvPairs[i] == null) break;
ip[i] = new InputProperty();
ip[i].Name = "udf:" + nvPairs[i].Name;
ip[i].Val = nvPairs[i].Value;
}
update.Items = ip.ToArray();
return update;
}
A URL that starts with the URL scheme and scheme specific part (http://
, https://
, ftp://
, etc.) is an absolute URL.
Any other URL is a relative URL and needs a base URL the relative URL is resolved from (and thus depend on) that is the URL of the resource the reference is used in if not declared otherwise.
Take a look at RFC 2396 – Appendix C for examples of resolving relative URLs.
In addition to the accepted answer. You can use a lambda
instead of regex
:
from bs4 import BeautifulSoup
html = """<p>test python</p>"""
soup = BeautifulSoup(html, "html.parser")
print(soup(text="python"))
print(soup(text=lambda t: "python" in t))
Output:
[]
['test python']
Use the @RequestParam to pass a parameter to the controller handler method.
In the jsp your form should have an input field with name = "id"
like the following:
<input type="text" name="id" />
<input type="submit" />
Then in your controller, your handler method should be like the following:
@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
Person person = personService.getCurrentlyAuthenticatedUser();
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
return "note";
}
Please also refer to these answers and tutorial:
unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.
So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.
Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.
result = bytes.fromhex(some_hex_string)
From here:
ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.
In terms of performance Array and ArrayList provides similar performance in terms of constant time for adding or getting element if you know index. Though automatic resize of ArrayList may slow down insertion a bit Both Array and ArrayList is core concept of Java and any serious Java programmer must be familiar with these differences between Array and ArrayList or in more general Array vs List.
The >
is a child selector. So if your HTML looks like this:
<h1 class="hc-reform">
title
<p>stuff here</p>
</h1>
... then that's your ticket.
But if your HTML looks like this:
<h1 class="hc-reform">
title
</h1>
<p>stuff here</p>
Then you want the adjacent selector:
h1.hc-reform + p{
clear:both;
}
Well, ["Title", "Ramones"]
is an array of strings. But [{"01":"Title", "02", "Ramones"}]
is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue;
in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[]
, so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({})
, or myArray.push({""})
.
This will push an empty object into myArray
which will have an index number 0
, so your exact object is now myArray[0]
Then push property
and value
into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
There is one repo that provides the jar. In SBT add a resolver similar to this: "oracle driver repo" at "http://dist.codehaus.org/mule/dependencies/maven2"
and a dependency: "oracle" % "ojdbc14" % "10.2.0.2"
You can do the same with maven. pom.xml and jar are available (http://dist.codehaus.org/mule/dependencies/maven2/oracle/ojdbc14/10.2.0.2/).
If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.
If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.
you can try this:
adb install -r -d -f your_Apk_path
The same as @Nix with a small change to be strongly typed:
If you don't want to query for it just create an entity, and then delete it.
Customer customer = new Customer () { Id = id };
context.Customers.Attach(customer);
context.Customers.DeleteObject(customer);
context.SaveChanges();
This can be done simply by using from_records of pandas DataFrame
import numpy as np
import pandas as pd
# Creating a numpy array
x = np.arange(1,10,1).reshape(-1,1)
dataframe = pd.DataFrame.from_records(x)
WhatsApp does not have a API available for public use. As you put it, it's a closed system.
However, they provide several other ways in which your iPhone application can interact with WhatsApp: through custom URL schemes, share extension and through the Document Interaction API.
Example:
driver.execute_script("arguments[0].scrollIntoView();", driver.find_element_by_css_selector(.your_css_selector))
This one always works for me for any type of selectors. There is also the Actions class, but for this case, it is not so reliable.
Peer to SamGoody and Lego Stormtroopr comments.
If you are looking for a PHP algorithm to rank search results based on proximity/relevance of multiple words here comes a quick and easy way of generating search results with PHP only:
Issues with the other boolean search methods such as strpos()
, preg_match()
, strstr()
or stristr()
PHP method based on Vector Space Model and tf-idf (term frequency–inverse document frequency):
It sounds difficult but is surprisingly easy.
If we want to search for multiple words in a string the core problem is how we assign a weight to each one of them?
If we could weight the terms in a string based on how representative they are of the string as a whole, we could order our results by the ones that best match the query.
This is the idea of the vector space model, not far from how SQL full-text search works:
function get_corpus_index($corpus = array(), $separator=' ') {
$dictionary = array();
$doc_count = array();
foreach($corpus as $doc_id => $doc) {
$terms = explode($separator, $doc);
$doc_count[$doc_id] = count($terms);
// tf–idf, short for term frequency–inverse document frequency,
// according to wikipedia is a numerical statistic that is intended to reflect
// how important a word is to a document in a corpus
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$doc_id])) {
$dictionary[$term]['document_frequency']++;
$dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
}
$dictionary[$term]['postings'][$doc_id]['term_frequency']++;
}
//from http://phpir.com/simple-search-the-vector-space-model/
}
return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}
function get_similar_documents($query='', $corpus=array(), $separator=' '){
$similar_documents=array();
if($query!=''&&!empty($corpus)){
$words=explode($separator,$query);
$corpus=get_corpus_index($corpus, $separator);
$doc_count=count($corpus['doc_count']);
foreach($words as $word) {
if(isset($corpus['dictionary'][$word])){
$entry = $corpus['dictionary'][$word];
foreach($entry['postings'] as $doc_id => $posting) {
//get term frequency–inverse document frequency
$score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);
if(isset($similar_documents[$doc_id])){
$similar_documents[$doc_id]+=$score;
}
else{
$similar_documents[$doc_id]=$score;
}
}
}
}
// length normalise
foreach($similar_documents as $doc_id => $score) {
$similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
}
// sort from high to low
arsort($similar_documents);
}
return $similar_documents;
}
CASE 1
$query = 'are';
$corpus = array(
1 => 'How are you?',
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULT
Array
(
[1] => 0.52832083357372
)
CASE 2
$query = 'are';
$corpus = array(
1 => 'how are you today?',
2 => 'how do you do',
3 => 'here you are! how are you? Are we done yet?'
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[1] => 0.54248125036058
[3] => 0.21699250014423
)
CASE 3
$query = 'we are done';
$corpus = array(
1 => 'how are you today?',
2 => 'how do you do',
3 => 'here you are! how are you? Are we done yet?'
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[3] => 0.6813781191217
[1] => 0.54248125036058
)
There are plenty of improvements to be made
but the model provides a way of getting good results from natural queries,
which don't have boolean operators such as strpos()
, preg_match()
, strstr()
or stristr()
.
NOTA BENE
Optionally eliminating redundancy prior to search the words
thereby reducing index size and resulting in less storage requirement
less disk I/O
faster indexing and a consequently faster search.
1. Normalisation
2. Stopword elimination
3. Dictionary substitution
Replace words with others which have an identical or similar meaning. (ex:replace instances of 'hungrily' and 'hungry' with 'hunger')
Further algorithmic measures (snowball) may be performed to further reduce words to their essential meaning.
The replacement of colour names with their hexadecimal equivalents
The reduction of numeric values by reducing precision are other ways of normalising the text.
RESOURCES
You can add listener all video events nicluding ended, loadedmetadata, timeupdate
where ended
function gets called when video ends
$("#myVideo").on("ended", function() {_x000D_
//TO DO: Your code goes here..._x000D_
alert("Video Finished");_x000D_
});_x000D_
_x000D_
$("#myVideo").on("loadedmetadata", function() {_x000D_
alert("Video loaded");_x000D_
this.currentTime = 50;//50 seconds_x000D_
//TO DO: Your code goes here..._x000D_
});_x000D_
_x000D_
_x000D_
$("#myVideo").on("timeupdate", function() {_x000D_
var cTime=this.currentTime;_x000D_
if(cTime>0 && cTime % 2 == 0)//Alerts every 2 minutes once_x000D_
alert("Video played "+cTime+" minutes");_x000D_
//TO DO: Your code goes here..._x000D_
var perc=cTime * 100 / this.duration;_x000D_
if(perc % 10 == 0)//Alerts when every 10% watched_x000D_
alert("Video played "+ perc +"%");_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<video id="myVideo" controls="controls">_x000D_
<source src="your_video_file.mp4" type="video/mp4">_x000D_
<source src="your_video_file.mp4" type="video/ogg">_x000D_
Your browser does not support HTML5 video._x000D_
</video>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
What does the trick for me is:
1) Right click on wwwroot > Add > Client Side Library
2) Typed "bootstrap" on the search box
3) Select "Choose specific files"
4) Scroll down and select a folder. In my case I chose "twitter-bootstrap"
5) Check "css" and "js"
6) Click "Install".
A few seconds later I have all of them wwwroot folder. Do the same for all client side packages that you want to add.
The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.
The HTML would look like this:
<th><a href="mypage.php?sort=type">Type:</a></th>
<th><a href="mypage.php?sort=desc">Description:</a></th>
<th><a href="mypage.php?sort=recorded">Recorded Date:</a></th>
<th><a href="mypage.php?sort=added">Added Date:</a></th>
And in the php code, do something like this:
<?php
$sql = "SELECT * FROM MyTable";
if ($_GET['sort'] == 'type')
{
$sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
$sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
$sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
$sql .= " ORDER BY DateAdded";
}
$>
Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;
Walltearer's solution is excellent, particularly if enclosed in a 'pre' tag:
<pre>
<?php debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); ?>
</pre>
- which sets out the calls on separate lines, neatly numbered
I've yet another answer that builds upon all previous ones that describe npm install @types/node
and including node
in tsconfig.json / compilerOptions / types
.
In my case, I have a base tsConfig.json
and a separate one in the Angular application that extends this one:
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": []
},
My problem was the empty types
in this tsconfi.app.json
- it clobbers the one in the base configuration.
C# and the CLR should support static methods in interfaces as Java does. The static modifier is part of a contract definition and does have meaning, specifically that the behavior and return value do not vary base on instance although it may still vary from call to call.
That said, I recommend that when you want to use a static method in an interface and cannot, use an annotation instead. You will get the functionality you are looking for.
In my mind @slugslog had it, but I would change one thing. I would use replace instead so you don't have to set it back.
$scope.scrollTo = function(id) {
var old = $location.hash();
$location.hash(id).replace();
$anchorScroll();
};
Docs Search for "Replace method"
One line code for Done button:-
[yourTextField setReturnKeyType:UIReturnKeyDone];
And add action method on valueChanged of TextField and add this line-
[yourTextField resignFirstResponder];
function wait(time)
local duration = os.time() + time
while os.time() < duration do end
end
This is probably one of the easiest ways to add a wait/sleep function to your script
There is very sophisticated way you can validate whether any of the radio buttons are checked with ECMA6 and method .some()
.
Html:
<input type="radio" name="status" id="marriedId" value="Married" />
<input type="radio" name="status" id="divorcedId" value="Divorced" />
And javascript:
let htmlNodes = document.getElementsByName('status');
let radioButtonsArray = Array.from(htmlNodes);
let isAnyRadioButtonChecked = radioButtonsArray.some(element => element.checked);
isAnyRadioButtonChecked
will be true
if some of the radio buttons are checked and false
if neither of them are checked.
Using TortoiseSVN worked easily on Windows for me.
Right click file -> TortoiseSVN menu -> Repo-browser -> right click file in repository -> rename -> press Enter -> click Ok
Using SVN 1.8.8 TortoiseSVN version 1.8.5
A simple change in Num2 class like this:
super().__init__(num)
It works in python3.
class Num:
def __init__(self,num):
self.n1 = num
class Num2(Num):
def __init__(self,num):
super().__init__(num)
self.n2 = num*2
def show(self):
print (self.n1,self.n2)
mynumber = Num2(8)
mynumber.show()
Java's Primitive Data Types
boolean: 1-bit. May take on the values true and false only.
byte: 1 signed byte (two's complement). Covers values from -128 to 127.
short: 2 bytes, signed (two's complement), -32,768 to 32,767
int: 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647.
long: 8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.
float: 4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).
double: 8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).
char: 2 bytes, unsigned, Unicode, 0 to 65,535
For SQL server mgmt. studio:
Right click database: Properties -> Options -> Restrict Access : Set to "Single User" and perform the drop afterwards
Yes, s
stands for string. The json.loads
function does not take the file path, but the file contents as a string. Look at the documentation at https://docs.python.org/2/library/json.html!
In most cases it could be better to pad the columns only on the right so just the spacing between the columns gets padded, and the first column is still aligned with the table.
CSS:
.padding-table-columns td
{
padding:0 5px 0 0; /* Only right padding*/
}
HTML:
<table className="padding-table-columns">
<tr>
<td>Cell one</td>
<!-- There will be a 5px space here-->
<td>Cell two</td>
<!-- There will be an invisible 5px space here-->
</tr>
</table>
Just use the *args
parameter, which allows you to pass as many arguments as you want after your a,b,c
. You would have to add some logic to map args
->c,d,e,f
but its a "way" of overloading.
def myfunc(a,b, *args, **kwargs):
for ar in args:
print ar
myfunc(a,b,c,d,e,f)
And it will print values of c,d,e,f
Similarly you could use the kwargs
argument and then you could name your parameters.
def myfunc(a,b, *args, **kwargs):
c = kwargs.get('c', None)
d = kwargs.get('d', None)
#etc
myfunc(a,b, c='nick', d='dog', ...)
And then kwargs
would have a dictionary of all the parameters that are key valued after a,b
To access the mysql
command in Windows without manually changing directories, do this:
Append the path to your MySQL installation to the end of the exisiting 'Variable value'. Example:
%systemDrive%\xampp\mysql\bin\
or, if you prefer
c:\xampp\mysql\bin\
Finally, open a new command prompt to make this change take effect.
Note that MySQL's documentation on Setting Environment Variables has little to say about handling this in Windows.
A DTO is a dumb object - it just holds properties and has getters and setters, but no other logic of any significance (other than maybe a compare()
or equals()
implementation).
Typically model classes in MVC (assuming .net MVC here) are DTOs, or collections/aggregates of DTOs
You need to compile with the link flag -lm
, like this:
gcc fib.c -lm -o fibo
This will tell gcc to link your code against the math lib. Just be sure to put the flag after the objects you want to link.
You have to inherit nusoap.php
class and put it in your project directory, you can download it from the Internet.
Use this code:
require_once('nusoap.php');
Schleis' variant does not work for me (Ubuntu 12.04), so let me propose my (clear and shiny :) variants:
Variant 1 (I would prefer this option):
git for-each-ref --format='%(refname:short) %(upstream)' refs/heads/ | awk '$2 !~/^refs\/remotes/' | xargs git branch -D
Variant 2:
a. Dry-run:
comm -23 <( git branch | grep -v "/" | grep -v "*" | sort ) <( git br -r | awk -F '/' '{print $2}' | sort ) | awk '{print "git branch -D " $1}'
b. Remove branches:
comm -23 <( git branch | grep -v "/" | grep -v "*" | sort ) <( git br -r | awk -F '/' '{print $2}' | sort ) | xargs git branch -D
Try this:
var classname = ("" + obj.constructor).split("function ")[1].split("(")[0];
View more detail from my previous answer I have created an nuget package Nuget
Code on Github
sample : you can use :
string login = "";
string domain = "";
string password = "";
using (UserImpersonation user = new UserImpersonation(login, domain, password))
{
if (user.ImpersonateValidUser())
{
File.WriteAllText("test.txt", "your text");
Console.WriteLine("File writed");
}
else
{
Console.WriteLine("User not connected");
}
}
Vieuw the full code :
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
/// <summary>
/// Object to change the user authticated
/// </summary>
public class UserImpersonation : IDisposable
{
/// <summary>
/// Logon method (check athetification) from advapi32.dll
/// </summary>
/// <param name="lpszUserName"></param>
/// <param name="lpszDomain"></param>
/// <param name="lpszPassword"></param>
/// <param name="dwLogonType"></param>
/// <param name="dwLogonProvider"></param>
/// <param name="phToken"></param>
/// <returns></returns>
[DllImport("advapi32.dll")]
private static extern bool LogonUser(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
/// <summary>
/// Close
/// </summary>
/// <param name="handle"></param>
/// <returns></returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
private WindowsImpersonationContext _windowsImpersonationContext;
private IntPtr _tokenHandle;
private string _userName;
private string _domain;
private string _passWord;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
/// <summary>
/// Initialize a UserImpersonation
/// </summary>
/// <param name="userName"></param>
/// <param name="domain"></param>
/// <param name="passWord"></param>
public UserImpersonation(string userName, string domain, string passWord)
{
_userName = userName;
_domain = domain;
_passWord = passWord;
}
/// <summary>
/// Valiate the user inforamtion
/// </summary>
/// <returns></returns>
public bool ImpersonateValidUser()
{
bool returnValue = LogonUser(_userName, _domain, _passWord,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref _tokenHandle);
if (false == returnValue)
{
return false;
}
WindowsIdentity newId = new WindowsIdentity(_tokenHandle);
_windowsImpersonationContext = newId.Impersonate();
return true;
}
#region IDisposable Members
/// <summary>
/// Dispose the UserImpersonation connection
/// </summary>
public void Dispose()
{
if (_windowsImpersonationContext != null)
_windowsImpersonationContext.Undo();
if (_tokenHandle != IntPtr.Zero)
CloseHandle(_tokenHandle);
}
#endregion
}
Well to obtain all different values in a Dataframe
you can use distinct. As you can see in the documentation that method returns another DataFrame
. After that you can create a UDF
in order to transform each record.
For example:
val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")
// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct
// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)
// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))
Just pass the object as is. Note you can create the object as follows
var data0 = {numberId: "1", companyId : "531"};
$.ajax({
type: "POST",
url: "TelephoneNumbers.aspx/DeleteNumber",
data: dataO,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('In Ajax');
}
});
UPDATE seems an odd issue with the serializer, maybe it is expecting a string, out of interest can you try the following.
data: "{'numberId':'1', 'companyId ':'531'}",
update VersionedFields
set Value = replace(replace(value,'<iframe','<a>iframe'), '> </iframe>','</a>')
and you do it in a single pass.
@Entity
is useful with model classes to denote that this is the entity or table
@Table
is used to provide any specific name to your table if you want to provide any different name
Note: if you don't use @Table
then hibernate consider that @Entity
is your table name by default and @Entity
must
@Entity
@Table(name = "emp")
public class Employee implements java.io.Serializable
{
}
If you are using Mac(OSX)
Based on the current tab, to select the file on project is : FN + OPTION + F1
Then in the popup you can Select in: Project View > Select In: Project
For SQL Server version 9.0 (2005), you can use the code below:
select *
from
syscomments c
inner join sys.procedures p on p.object_id = c.id
where
p.name like '%usp_ConnectionsCount%';
I think SELECT CAST( CAST([field] AS VARBINARY(120)) AS varchar(120)) for your update
I haven't had to do this, so take this with a grain of salt and a big helping of "test, test, test".
What happens if (in a safe controlled test environment) you directly modify the Host
column in the mysql.user
and probably mysql.db
tables? (E.g., with an update
statement.) I don't think MySQL uses the user's host as part of the password encoding (the PASSWORD
function doesn't suggest it does), but you'll have to try it to be sure. You may need to issue a FLUSH PRIVILEGES
command (or stop and restart the server).
For some storage engines (MyISAM, for instance), you may also need to check/modify the .frm
file any views that user has created. The .frm
file stores the definer, including the definer's host. (I have had to do this, when moving databases between hosts where there had been a misconfiguration causing the wrong host to be recorded...)
This is not an answer to the original question "What are the differences between .gitignore and .gitkeep?" but posting here to help people to keep track of empty dir in a simple fashion. To track empty directory and knowling that .gitkeep
is not official part of git,
just add a empty (with no content) .gitignore
file in it.
So for e.g. if you have /project/content/posts
and sometimes posts
directory might be empty then create empty file /project/content/posts/.gitignore
with no content to track that directory and its future files in git.
Notice that you're using Observable#map to convert the raw Response
object your base Observable emits to a parsed representation of the JSON response.
If I understood you correctly, you want to map
again. But this time, converting that raw JSON to instances of your Model
. So you would do something like:
http.get('api/people.json')
.map(res => res.json())
.map(peopleData => peopleData.map(personData => new Person(personData)))
So, you started with an Observable that emits a Response
object, turned that into an observable that emits an object of the parsed JSON of that response, and then turned that into yet another observable that turned that raw JSON into an array of your models.
Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.
I am sure this code will surely resolve your issues...This is working fine for me...\
try {
File mountFile = new File("/proc/mounts");
usbFoundCount=0;
sdcardFoundCount=0;
if(mountFile.exists())
{
Scanner usbscanner = new Scanner(mountFile);
while (usbscanner.hasNext()) {
String line = usbscanner.nextLine();
if (line.startsWith("/dev/fuse /storage/usbcard1")) {
usbFoundCount=1;
Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/usbcard1" );
}
}
}
if(mountFile.exists()){
Scanner sdcardscanner = new Scanner(mountFile);
while (sdcardscanner.hasNext()) {
String line = sdcardscanner.nextLine();
if (line.startsWith("/dev/fuse /storage/sdcard1")) {
sdcardFoundCount=1;
Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/sdcard1" );
}
}
}
if(usbFoundCount==1)
{
Toast.makeText(context,"USB Connected and properly mounted", 7000).show();
Log.i("-----USB--------","USB Connected and properly mounted" );
}
else
{
Toast.makeText(context,"USB not found!!!!", 7000).show();
Log.i("-----USB--------","USB not found!!!!" );
}
if(sdcardFoundCount==1)
{
Toast.makeText(context,"SDCard Connected and properly mounted", 7000).show();
Log.i("-----SDCard--------","SDCard Connected and properly mounted" );
}
else
{
Toast.makeText(context,"SDCard not found!!!!", 7000).show();
Log.i("-----SDCard--------","SDCard not found!!!!" );
}
}catch (Exception e) {
e.printStackTrace();
}
<pre><form name="myform" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
Note: before using the code above you have to add the gen_validatorv31.js
file.
At my company they didn't configure the server to provide a list of repositories, so svn list
worked for a specific repository but not at a higher level to list all repositories.
However they installed FishEye which gives you a GUI listing the repositories https://www.atlassian.com/software/fisheye
It's a paid option, so it's not for everyone, but the functionality is nice.
Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below
CREATE TABLE `table1` (
`col1` VARCHAR(50) NULL DEFAULT NULL
)
Now if you want to insert number from 1 to 50 in that table then use following stored procedure
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
DECLARE a INT Default 1 ;
simple_loop: LOOP
insert into table1 values(a);
SET a=a+1;
IF a=51 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
To call that stored procedure use
CALL `ABC`()
var findObjectByLabel = function(objs, label) {
if(objs.label === label) {
return objs;
}
else{
if(objs.subs){
for(var i in objs.subs){
let found = findObjectByLabel(objs.subs[i],label)
if(found) return found
}
}
}
};
findObjectByLabel(cars, "Ford");
When you make the input, set it to be readonly.
<input type="text" name="datepicker" id="datepicker" readonly="readonly" />
Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.
I'm not really too clear what you are asking, but using the -f
command line option just specifies a file - it doesn't tell make to change directories. If you want to do the work in another directory, you need to cd
to the directory:
clean:
cd gtest-1.4.0 && $(MAKE) clean
Note that each line in Makefile
runs in a separate shell, so there is no need to change the directory back.
In Swift:
Changing the label text color is quite different than changing it for a UIButton
. To change the text color for a UIButton
use this method:
self.headingButton.setTitleColor(UIColor(red: 107.0/255.0, green: 199.0/255.0, blue: 217.0/255.0), forState: UIControlState.Normal)
Apart from Thread.join()
suggested by others, java 5 introduced the executor framework. There you don't work with Thread
objects. Instead, you submit your Callable
or Runnable
objects to an executor. There's a special executor that is meant to execute multiple tasks and return their results out of order. That's the ExecutorCompletionService
:
ExecutorCompletionService executor;
for (..) {
executor.submit(Executors.callable(yourRunnable));
}
Then you can repeatedly call take()
until there are no more Future<?>
objects to return, which means all of them are completed.
Another thing that may be relevant, depending on your scenario is CyclicBarrier
.
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
First of all there are functions for this. But if you prefer vars then your task can be done like this:
$ cmd=ls
$ $cmd # works
file file2 test
$ cmd='ls | grep file'
$ $cmd # not works
ls: cannot access '|': No such file or directory
ls: cannot access 'grep': No such file or directory
file
$ bash -c $cmd # works
file file2 test
$ bash -c "$cmd" # also works
file
file2
$ bash <<< $cmd
file
file2
$ bash <<< "$cmd"
file
file2
Or via tmp file
$ tmp=$(mktemp)
$ echo "$cmd" > "$tmp"
$ chmod +x "$tmp"
$ "$tmp"
file
file2
$ rm "$tmp"
You can index into a tuple:
(falseValue, trueValue)[test]
test
needs to return True or False.
It might be safer to always implement it as:
(falseValue, trueValue)[test == True]
or you can use the built-in bool()
to assure a Boolean value:
(falseValue, trueValue)[bool(<expression>)]
I had the same error message and, like you mentioned, it was due to different versions of the Newtonsoft.Json.dll being referenced.
Some projects in my MVC solution used the NuGet package for version 4 of that dll.
I then added a NuGet package (for Salesforce in my case) that brought Newtonsoft.Json version 6 with it as a dependency to one of the projects. That was what triggered the problem for me.
To clean things up, I used the Updates section in the NuGet Package Manager for the solution (off Tools menu or solution right-click) to update the Json.Net package throughout the solution so it was the same version for all projects.
After that I just checked the App Config files to ensure any binding redirect lines were going to my chosen version as below.
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
PHP was not designed to explicitly give you a pure REST (GET, POST, PUT, PATCH, DELETE) like interface for handling HTTP requests.
However, the $_SERVER
, $_COOKIE
, $_POST
, $_GET
, and $_FILES
superglobals, and the function filter_input_array()
are very useful for the average person's / layman's needs.
The number one hidden advantage of $_POST
(and $_GET
) is that your input data is url-decoded automatically by PHP. You never even think about having to do it, especially for query string parameters within a standard GET
request, or HTTP body data submitted with a POST
request.
Those studying the underlying HTTP protocol and its various request methods come to understand that there are many HTTP request methods, including the often referenced PUT
, PATCH
(not used in Google's Apigee), and DELETE
.
In PHP, there are no superglobals or input filter functions for getting HTTP request body data when POST
is not used. What are disciples of Roy Fielding to do? ;-)
That being said, as you advance in your PHP programming knowledge and want to use JavaScript's XmlHttpRequest
object (jQuery for some), you come to see the limitation of this scheme.
$_POST
limits you to the use of two media types in the HTTP Content-Type
header:
application/x-www-form-urlencoded
, andmultipart/form-data
Thus, if you want to send data values to PHP on the server, and have it show up in the $_POST
superglobal, then you must urlencode it on the client-side and send said data as key/value pairs--an inconvenient step for novices (especially when trying to figure out if different parts of the URL require different forms of urlencoding: normal, raw, etc..).
For all you jQuery users, the $.ajax()
method is converting your JSON to URL encoded key/value pairs before transmitting them to the server. You can override this behavior by setting processData: false
. Just read the $.ajax() documentation, and don't forget to send the correct media type in the Content-Type header.
Even if you use php://input
instead of $_POST
for your HTTP POST
request body data, it will not work with an HTTP Content-Type
of multipart/form-data
This is the content type that you use on an HTML form when you want to allow file uploads!
<form enctype="multipart/form-data" accept-charset="utf-8" action="post">
<input type="file" name="resume">
</form>
Therefore, in traditional PHP, to deal with a diversity of content types from an HTTP POST
request, you will learn to use $_POST
or filter_input_array(POST)
, $_FILES
, and php://input
. There is no way to just use one, universal input source for HTTP POST
requests in PHP.
You cannot get files through $_POST
, filter_input_array(POST), or php://input
, and you cannot get JSON/XML/YAML in either filter_input_array(POST)
or $_POST
.
php://input is a read-only stream that allows you to read raw data from the request body...php://input is not available with enctype="multipart/form-data".
PHP frameworks like Codeigniter 4 and Laravel use a facade to provide a cleaner interface (IncomingRequest
or Request
objects) to the above. This is why professional PHP developers use frameworks instead of raw PHP.
Of course, if you like to program, you can devise your own facade object to provide what frameworks do. It is because I have taken time to investigate this issue that I am able to write this answer.
Typically, if you are doing a normal, synchronous (when the entire page redraws) HTTP requests with an HTML form, the user-agent (web browser) will urlencode your form data for you. If you want to do an asynchronous HTTP requests using the XmlHttpRequest
object, then you must fashion a urlencoded string and send it, if you want that data to show up in the $_POST
superglobal.
Converting from a JavaScript array or object to a urlencoded string bothers many developers (even with new APIs like Form Data). They would much rather just be able to send JSON, and it would be more efficient for the client code to do so.
Remember (wink, wink), the average web developer does not learn to use the XmlHttpRequest
object directly, global functions, string functions, array functions, and regular expressions like you and I ;-). Urlencoding for them is a nightmare. ;-)
PHP's lack of intuitive XML and JSON handling turns many people off. You would think it would be part of PHP by now (sigh).
XML, JSON, and YAML all have media types that can be put into an HTTP Content-Type
header.
Look how many media-types (formerly, MIME types) are defined by IANA.
Look how many HTTP headers there are.
Using the php://input
stream allows you to circumvent the baby-sitting / hand holding level of abstraction that PHP has forced on the world. :-) With great power comes great responsibility!
Now, before you deal with data values streamed through php://input
, you should / must do a few things.
AH, HA! Yes, you might want the data stream being sent into your application to be UTF-8 encoded, but how can you know if it is or not?
php://input
.Are you going to attempt to handle stream data without knowing how much is there first? That is a terrible idea. You cannot rely exclusively on the HTTP Content-Length
header for guidance on the size of streamed input because it can be spoofed.
You are going to need a:
Are you going to attempt to convert stream data to UTF-8 without knowing the current encoding of the stream? How? The iconv stream filter (iconv stream filter example) seems to want a starting and ending encoding, like this.
'convert.iconv.ISO-8859-1/UTF-8'
Thus, if you are conscientious, you will need:
(Update: 'convert.iconv.UTF-8/UTF-8'
will force everything to UTF-8, but you still have to account for characters that the iconv library might not know how to translate. In other words, you have to some how define what action to take when a character cannot be translated: 1) Insert a dummy character, 2) Fail / throw and exception).
You cannot rely exclusively on the HTTP Content-Encoding
header, as this might indicate something like compression as in the following. This is not what you want to make a decision off of in regards to iconv.
Content-Encoding: gzip
Part I: HTTP Request Related
Part II: Stream Data Related
Part III: Data Type Related
(Remember, the data can still be a URL encoded string which you must then parse and URL decode).
Part IV: Data Value Related
Filter input data.
Validate input data.
The $_POST
superglobal, along with php.ini settings for limits on input, are simpler for the layman. However, dealing with character encoding is much more intuitive and efficient when using streams because there is no need to loop through superglobals (or arrays, generally) to check input values for the proper encoding.
IMO, you should call it. If your superclass is object
, you should not, but in other cases I think it is exceptional not to call it. As already answered by others, it is very convenient if your class doesn't even have to override __init__
itself, for example when it has no (additional) internal state to initialize.
I would do something like this but i bet there is a simpler way. i think the sql from linqtosql would use a select from person Where NOT EXIST(select from your exclusion list)
static class Program
{
public class Person
{
public string Key { get; set; }
public Person(string key)
{
Key = key;
}
}
public class NotPerson
{
public string Key { get; set; }
public NotPerson(string key)
{
Key = key;
}
}
static void Main()
{
List<Person> persons = new List<Person>()
{
new Person ("1"),
new Person ("2"),
new Person ("3"),
new Person ("4")
};
List<NotPerson> notpersons = new List<NotPerson>()
{
new NotPerson ("3"),
new NotPerson ("4")
};
var filteredResults = from n in persons
where !notpersons.Any(y => n.Key == y.Key)
select n;
foreach (var item in filteredResults)
{
Console.WriteLine(item.Key);
}
}
}
Use the clip property along with opacity, z-index, absolute positioning, and some browser filters to place the file input over the desired button:
http://en.wikibooks.org/wiki/Cascading_Style_Sheets/Clipping
I forgot to mention. This should also accept whitespace.
You could use:
/^[-@.\/#&+\w\s]*$/
Note how this makes use of the character classes \w
and \s
.
EDIT:- Added \ to escape /
As while developing react native apps, we play with the terminal so much
so I added a script in the scripts in the package.json file
"menu": "adb shell input keyevent 82"
and I hit $ yarn menu
for the menu to appear on the emulator it will forward the keycode 82 to the emulator via ADB not the optimal way but I like it and felt to share it.
If the list of conditions is not known at compile time and is instead built at run time, you don't have to worry about whether you have one or more than one condition. You can generate them all like:
and <condition>
and concatenate them all together. With the 1=1
at the start, the initial and
has something to associate with.
I've never seen this used for any kind of injection protection, as you say it doesn't seem like it would help much. I have seen it used as an implementation convenience. The SQL query engine will end up ignoring the 1=1
so it should have no performance impact.
it's very strange that I met this problem because I forgot specify the 'type' parameter. e.g.:
add_column :cms_push_msgs, :android_title
which should be:
add_column :cms_push_msgs, :android_content, :string
If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp
num = input("number")
power = 0
num = int(num)
while num > 10:
num = num / 10
power += 1
print(str(round(num, 2)) + "^" + str(power))
May this help to someone if they have the same requirement.
This will read a file that contains the Jenkins Job name and run them iteratively from one single job.
Please change below code accordingly in your Jenkins.
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
git branch: 'Your Branch name', credentialsId: 'Your crendiatails', url: ' Your BitBucket Repo URL '
##To read file from workspace which will contain the Jenkins Job Name ###
def filePath = readFile "${WORKSPACE}/ Your File Location"
##To read file line by line ###
def lines = filePath.readLines()
##To iterate and run Jenkins Jobs one by one ####
for (line in lines) {
build(job: "$line/branchName",
parameters:
[string(name: 'vertical', value: "${params.vert}"),
string(name: 'environment', value: "${params.env}"),
string(name: 'branch', value: "${params.branch}"),
string(name: 'project', value: "${params.project}")
]
)
}
}
}
}
}
}
_x000D_
I took the answer from PirateApp and made it reusable. If you include this script it will transform all selects with the class '.dropdown' to searchable dropdowns.
$('.dropdown').each(function(index, dropdown) {
//Find the input search box
let search = $(dropdown).find('.search');
//Find every item inside the dropdown
let items = $(dropdown).find('.dropdown-item');
//Capture the event when user types into the search box
$(search).on('input', function() {
filter($(search).val().trim().toLowerCase())
});
//For every word entered by the user, check if the symbol starts with that word
//If it does show the symbol, else hide it
function filter(word) {
let length = items.length
let collection = []
let hidden = 0
for (let i = 0; i < length; i++) {
if (items[i].value.toString().toLowerCase().includes(word)) {
$(items[i]).show()
} else {
$(items[i]).hide()
hidden++
}
}
//If all items are hidden, show the empty view
if (hidden === length) {
$(dropdown).find('.dropdown_empty').show();
} else {
$(dropdown).find('.dropdown_empty').hide();
}
}
//If the user clicks on any item, set the title of the button as the text of the item
$(dropdown).find('.dropdown-menu').find('.menuItems').on('click', '.dropdown-item', function() {
$(dropdown).find('.dropdown-toggle').text($(this)[0].value);
$(dropdown).find('.dropdown-toggle').dropdown('toggle');
})
});
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<div class="dropdown">
<button class="btn btn-sm btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Benutzer
</button>
<div class="dropdown-menu" aria-labelledby="dropdown_user">
<form class="px-4 py-2">
<input type="search" class="form-control search" placeholder="Suche.." autofocus="autofocus">
</form>
<div class="menuItems">
<input type="button" class="dropdown-item" type="button" value="Test1" />
<input type="button" class="dropdown-item" type="button" value="Test2" />
<input type="button" class="dropdown-item" type="button" value="Test3" />
</div>
<div style="display:none;" class="dropdown-header dropdown_empty">No entry found</div>
</div>
</div>
_x000D_
For those who ignored that the initial error message displaying is the following one:
The name org.freedesktop.secrets was not provided by any .service files
Make sure to install gnome-keyring using the following
sudo apt install gnome-keyring
Unfortunately the answers given so far (including the most voted) are either "just" common sense, plain wrong or confusing at best. None of crucial keywords1 pop up!
I wrote 3 answers:
To understand the role of the html elements discussed here you have to know that some of them section the document. Each and every html document can be sectioned according to the HTML5 outline algorithm for the purpose of creating an outline—or—table of contents (TOC). The outline is not generally visible (these days), but authors should use html in such a way that the resulting outline reflects their intentions.
You can create sections with exactly these elements and nothing else:
<section>
sections<article>
sections<nav>
sections<aside>
sections<h*>
2 (not all do this, see below)Sections can be named:
<h*>
created sections name themselves<section|article|nav|aside>
sections will be named by the first <h*>
if there is one
<h*>
are the only ones which don’t create sections themselvesThere is one more thing to sections: the following contexts (i.e. elements) create "outline boundaries". Whatever sections they contain is private to them:
<body>
<td>
<blockquote>
<details>
, <dialog>
, <fieldset>
, and <figure>
example HTML
<body>
<h3>if you want siblings
at top level...</h3>
<h3>...you have to use untyped
sections with <h*>...</h3>
<article>
<h1>...as any other section
will descent</h1>
</article>
<nav>
<ul>
<li><a href=...>...</a></li>
</ul>
</nav>
</body>
has this outline
1. if you want siblings
at top level...
2. ...you have to use untyped
sections with <h*>...
2.1. ...as any other section
will descent
2.2. (unnamed navigation)
This raises two questions:
What is the difference between <article>
and <section>
?
<section>
s are like book chapters
<article>
, at least on the lowest level
<article>
and its comment <article>
s could also be wrapped with an <article>
<section>
s in an <article>
are like chapters in a book<article>
s in a <section>
are like poems in a volume (within a series)How do <header>
, <footer>
and <main>
fit in?
<header>
and <footer>
<header>
<footer>
<header>
<main>
<body>
that is)<main>
can even “hide” in some subsections of the document, while document’s <header>
and <footer>
can’t (that markup would mark header/footer of that subsection then)
<article>
sections31 to mind comes: outline, algorithm, implicit sectioning
2 I use <h*>
as shorthand for <h1>
, <h2>
, <h3>
, <h4>
, <h5>
and <h6>
3 neither is <main>
allowed in <aside>
or <nav>
, but that is of no surprise. – In effect: <main>
can only hide in (nested) descending <section>
sections or appear at top level, namely <body>
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
if you want the object on the stack, try this:
MyClass myclass;
myclass.DoSomething();
If you need a pointer to that object:
MyClass* myclassptr = &myclass;
myclassptr->DoSomething();
If you want to select town and total user count, you can use this query below:
SELECT Town, (SELECT Count(*) FROM User) `Count` FROM user GROUP BY Town;
I have exactly the same question and have done the same things as you with no success.
I found an entries in my log of
HM: HMR3Init: Falling back to raw-mode: VT-x is not available
VMSetError: F:\tinderbox\win-5.2\src\VBox\VMM\VMMR3\VM.cpp(361) int __cdecl
VMR3Create(unsigned int,const struct VMM2USERMETHODS *,void (__cdecl *)(struct UVM *,void *,int,const char *,unsigned int,const char *,const char *,char *),void *,int (__cdecl *)(struct UVM *,struct VM *,void *),void *,struct VM **,struct UVM **); rc=VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT
00:00:05.088846
VMSetError: Raw-mode is unavailable courtesy of Hyper-V. 00:00:05.089946
ERROR [COM]: aRC=E_FAIL (0x80004005) aIID={872da645-4a9b-1727-bee2-5585105b9eed} aComponent={ConsoleWrap} aText={Raw-mode is unavailable courtesy of Hyper-V. (VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT)}, preserve=false aResultDetail=0 00:00:05.090271 Console: Machine state changed to 'PoweredOff'
My chip says it has VT-x and is on in the Bios but the log says not
HM: HMR3Init: Falling back to raw-mode: VT-x is not available
I have a 6 month old Lenovo Yoga with 2.7-GHz Intel Core i7-7500U
I have tried the following, but it didn't work for me.
From this thread https://forums.virtualbox.org/viewtopic.php?t=77120#p383348 I tried disabling Device Guard but Windows wouldn't shut down so I reenabled it.
I used this path .... On the host operating system, click Start > Run, type gpedit.msc, and click Ok. The Local group Policy Editor opens. Go to Local Computer Policy > Computer Configuration > Administrative Templates > System > Device Guard > Turn on Virtualization Based Security. Select Disabled.
What worked for me besides restarting eclipse is:
After removing all filters, logcat was filled with text again Hope this will be helpful to someone else
Just using plain JavaScript, this has been answered already: remove objects from array by object property.
Using underscore.js, you could combine .findWhere
with .without
:
var arr = [{_x000D_
id: 1,_x000D_
name: 'a'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'b'_x000D_
}, {_x000D_
id: 3,_x000D_
name: 'c'_x000D_
}];_x000D_
_x000D_
//substract third_x000D_
arr = _.without(arr, _.findWhere(arr, {_x000D_
id: 3_x000D_
}));_x000D_
console.log(arr);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
Although, since you are creating a new array in this case anyway, you could simply use _.filter
or the native Array.prototype.filter
function (just like shown in the other question). Then you would only iterate over array once instead of potentially twice like here.
If you want to modify the array in-place, you have to use .splice
. This is also shown in the other question and undescore doesn't seem to provide any useful function for that.
I would just use a value in the querystring to pass the required information to the next page.
You can get the total number of rows containing a specific name using:
SELECT COUNT(*) FROM tbl_foo WHERE name = 'sarmen'
Given the count, you can now get the nth row using:
SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT (n - 1), 1
Where 1 <= n <= COUNT(*) from the first query.
Example:
getting the 3rd row
SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT 2, 1
While the accepted and most upvoted answer is great, I additionally find it useful trying to explain the difference only by words:
merge
rebase
summary: When possible, rebase is almost always better. Making re-integration into the main branch easier.
Because? ? your feature work can be presented as one big ‘patch file’ (aka diff) in respect to the main branch, not having to ‘explain’ multiple parents: At least two, coming from one merge, but likely many more, if there were several merges. Unlike merges, multiple rebases do not add up. (another big plus)
As of Django 1.8, there's the from_db
method, as Serge mentions. In fact, the Django docs include this specific use case as an example:
https://docs.djangoproject.com/en/dev/ref/models/instances/#customizing-model-loading
Below is an example showing how to record the initial values of fields that are loaded from the database
write parenthesis next to return not in next line.
Incorrect
return
(
statement1
statement2
.......
.......
)
Correct
return(
statement1
statement2
.........
.........
)
If the file contains only parameter assignments, you can use the following loop in place of sourcing it:
# Instead of source file.txt
while IFS="=" read name value; do
declare "$name=$value"
done < file.txt
This saves you having to quote anything in the file, and is also more secure, as you don't risk executing arbitrary code from file.txt
.
This problem happens because you are referencing the same object more than once. This is not a limitation of EF, but rather a safety feature to ensure you are not inserting the same object with two different IDs. So to achieve what you are trying to do, is simply create a new object and add the newly created object to the database.
** This issue often happens inside loops. If you are using a while or foreach loop, make sure to have the New Created Object INSIDE the loop body.
try this:
Contact contact = dbContext.Contacts.Single(c => c.contactTypeId == 1234);
contact.contactTypeId = 4;
dbContext.AddObject(contact);
dbContext.SaveChanges();
Note from 2017: File::Slurp is not recommended due to design mistakes and unmaintained errors. Use File::Slurper or Path::Tiny instead.
extending on your answer
use File::Slurp ();
my $value = File::Slurp::slurp($filename);
$value =~ s/\R*//g;
File::Slurp abstracts away the File IO stuff and just returns a string for you.
NOTE
Important to note the addition of /g
, without it, given a multi-line string, it will only replace the first offending character.
Also, the removal of $
, which is redundant for this purpose, as we want to strip all line breaks, not just line-breaks before whatever is meant by $
on this OS.
In a multi-line string, $
matches the end of the string and that would be problematic ).
Point 3 means that point 2 is made with the assumption that you'd also want to use /m
otherwise '$' would be basically meaningless for anything practical in a string with >1 lines, or, doing single line processing, an OS which actually understands $
and manages to find the \R*
that proceed the $
Examples
while( my $line = <$foo> ){
$line =~ $regex;
}
Given the above notation, an OS which does not understand whatever your files '\n' or '\r' delimiters, in the default scenario with the OS's default delimiter set for $/
will result in reading your whole file as one contiguous string ( unless your string has the $OS's delimiters in it, where it will delimit by that )
So in this case all of these regex are useless:
/\R*$//
: Will only erase the last sequence of \R
in the file /\R*//
: Will only erase the first sequence of \R
in the file /\012?\015?//
: When will only erase the first 012\015
, \012
, or \015
sequence, \015\012
will result in either \012
or \015
being emitted.
/\R*$//
: If there happens to be no byte sequences of '\015$OSDELIMITER' in the file, then then NO linebreaks will be removed except for the OS's own ones.
It would appear nobody gets what I'm talking about, so here is example code, that is tested to NOT remove line feeds. Run it, you'll see that it leaves the linefeeds in.
#!/usr/bin/perl
use strict;
use warnings;
my $fn = 'TestFile.txt';
my $LF = "\012";
my $CR = "\015";
my $UnixNL = $LF;
my $DOSNL = $CR . $LF;
my $MacNL = $CR;
sub generate {
my $filename = shift;
my $lineDelimiter = shift;
open my $fh, '>', $filename;
for ( 0 .. 10 )
{
print $fh "{0}";
print $fh join "", map { chr( int( rand(26) + 60 ) ) } 0 .. 20;
print $fh "{1}";
print $fh $lineDelimiter->();
print $fh "{2}";
}
close $fh;
}
sub parse {
my $filename = shift;
my $osDelimiter = shift;
my $message = shift;
print "Parsing $message File $filename : \n";
local $/ = $osDelimiter;
open my $fh, '<', $filename;
while ( my $line = <$fh> )
{
$line =~ s/\R*$//;
print ">|" . $line . "|<";
}
print "Done.\n\n";
}
my @all = ( $DOSNL,$MacNL,$UnixNL);
generate 'Windows.txt' , sub { $DOSNL };
generate 'Mac.txt' , sub { $MacNL };
generate 'Unix.txt', sub { $UnixNL };
generate 'Mixed.txt', sub {
return @all[ int(rand(2)) ];
};
for my $os ( ["$MacNL", "On Mac"], ["$DOSNL", "On Windows"], ["$UnixNL", "On Unix"]){
for ( qw( Windows Mac Unix Mixed ) ){
parse $_ . ".txt", @{ $os };
}
}
For the CLEARLY Unprocessed output, see here: http://pastebin.com/f2c063d74
Note there are certain combinations that of course work, but they are likely the ones you yourself naívely tested.
Note that in this output, all results must be of the form >|$string|<>|$string|<
with NO LINE FEEDS to be considered valid output.
and $string
is of the general form {0}$data{1}$delimiter{2}
where in all output sources, there should be either :
{1}
and {2}
|<>|
between {1}
and {2}
If you installed pip like this:
- sudo apt install python-pip
- sudo apt install python3-pip
Uninstall them like this:
- sudo apt remove python-pip
- sudo apt remove python3-pip
Set "dateTime="
For /F %%A In ('powershell get-date -format "{yyyyMMdd_HHmm}"') Do Set "dateTime=%%A"
echo %dateTime%
pause
Official Microsoft docs for for
command
I think the wait/notify/notifyAll methods don't belong on the Object class as it pollutes all objects with methods that are rarely used. They make much more sense on a dedicated Lock class. So from this point of view, perhaps it's better to use a tool that is explicitly designed for the job at hand - ie ReentrantLock.
The IV that your using for decryption is incorrect. Replace this code
//Decrypt cipher
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());
decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);
With this code
//Decrypt cipher
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(encryptCipher.getIV());
decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);
And that should solve your problem.
Below includes an example of a simple AES class in Java. I do not recommend using this class in production environments, as it may not account for all of the specific needs of your application.
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AES
{
public static byte[] encrypt(final byte[] keyBytes, final byte[] ivBytes, final byte[] messageBytes) throws InvalidKeyException, InvalidAlgorithmParameterException
{
return AES.transform(Cipher.ENCRYPT_MODE, keyBytes, ivBytes, messageBytes);
}
public static byte[] decrypt(final byte[] keyBytes, final byte[] ivBytes, final byte[] messageBytes) throws InvalidKeyException, InvalidAlgorithmParameterException
{
return AES.transform(Cipher.DECRYPT_MODE, keyBytes, ivBytes, messageBytes);
}
private static byte[] transform(final int mode, final byte[] keyBytes, final byte[] ivBytes, final byte[] messageBytes) throws InvalidKeyException, InvalidAlgorithmParameterException
{
final SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
final IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
byte[] transformedBytes = null;
try
{
final Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(mode, keySpec, ivSpec);
transformedBytes = cipher.doFinal(messageBytes);
}
catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e)
{
e.printStackTrace();
}
return transformedBytes;
}
public static void main(final String[] args) throws InvalidKeyException, InvalidAlgorithmParameterException
{
//Retrieved from a protected local file.
//Do not hard-code and do not version control.
final String base64Key = "ABEiM0RVZneImaq7zN3u/w==";
//Retrieved from a protected database.
//Do not hard-code and do not version control.
final String shadowEntry = "AAECAwQFBgcICQoLDA0ODw==:ZtrkahwcMzTu7e/WuJ3AZmF09DE=";
//Extract the iv and the ciphertext from the shadow entry.
final String[] shadowData = shadowEntry.split(":");
final String base64Iv = shadowData[0];
final String base64Ciphertext = shadowData[1];
//Convert to raw bytes.
final byte[] keyBytes = Base64.getDecoder().decode(base64Key);
final byte[] ivBytes = Base64.getDecoder().decode(base64Iv);
final byte[] encryptedBytes = Base64.getDecoder().decode(base64Ciphertext);
//Decrypt data and do something with it.
final byte[] decryptedBytes = AES.decrypt(keyBytes, ivBytes, encryptedBytes);
//Use non-blocking SecureRandom implementation for the new IV.
final SecureRandom secureRandom = new SecureRandom();
//Generate a new IV.
secureRandom.nextBytes(ivBytes);
//At this point instead of printing to the screen,
//one should replace the old shadow entry with the new one.
System.out.println("Old Shadow Entry = " + shadowEntry);
System.out.println("Decrytped Shadow Data = " + new String(decryptedBytes, StandardCharsets.UTF_8));
System.out.println("New Shadow Entry = " + Base64.getEncoder().encodeToString(ivBytes) + ":" + Base64.getEncoder().encodeToString(AES.encrypt(keyBytes, ivBytes, decryptedBytes)));
}
}
Note that AES has nothing to do with encoding, which is why I chose to handle it separately and without the need of any third party libraries.
It is very important that you don't include bin in your JAVA_HOME path. It should be like,
C:\Program Files\Java\jdk-11.0.3
you'll need to cast it to an HtmlControl in order to access the Style property.
HtmlControl control = (HtmlControl)Page.FindControl("portlet_tab1"); control.Style.Add("display","none");
There are two features of null we should understand:
You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value.
example:-
let a = null;
console.log(a); //null
This is because in line
graph(x**3+2*x-4, range(-10, 11))
x is not defined.
The easiest way is to pass the function you want to plot as a string and use eval
to evaluate it as an expression.
So your code with minimal modifications will be
import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
x = np.array(x_range)
y = eval(formula)
plt.plot(x, y)
plt.show()
and you can call it as
graph('x**3+2*x-4', range(-10, 11))
This has happened to me after I "updated" into 5.0 SDK and wanted to create a new application with support library
In both Projects (project.properties
file) in the one you want to use support library and the support library itself it has to be set the same target
e.g. for my case it worked
android-support-v7-appcompat
Change
project.properties
into target=android-21
android-support-v7-appcompat
In my project (where I desire support
library) project.properties
into target=android-21
and android.library.reference.1=../android-support-v7-appcompat
(or add support library in project properties)Edit your app at www.facebook.com/developers/ and set the "Site URL" to "http://localhost/myapppath".
When done - change it back.
The file is just a file, you need to create an image like so:
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
var objectUrl = _URL.createObjectURL(file);
img.onload = function () {
alert(this.width + " " + this.height);
_URL.revokeObjectURL(objectUrl);
};
img.src = objectUrl;
}
});
Demo: http://jsfiddle.net/4N6D9/1/
I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.
P.S. The URL.createObjectURL()
method has been removed from the MediaStream
interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.srcObject
. The old method was removed because it is less safe, requiring a call to URL.revokeOjbectURL()
to end the stream. Other user agents have either deprecated (Firefox) or removed (Safari) this feature feature.
For more information, please refer here.
The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[]
with an index read from stream. Try vector::at()
instead of vector::operator[]
. This won't solve your problem, but will show which assignment to the vector causes error.
I concur with the other answers. UUIDs are safe enough for nearly all practical purposes1, and certainly for yours.
But suppose (hypothetically) that they aren't.
Is there a better system or a pattern of some type to alleviate this issue?
Here are a couple of approaches:
Use a bigger UUID. For instance, instead of a 128 random bits, use 256 or 512 or ... Each bit you add to a type-4 style UUID will reduce the probability of a collision by a half, assuming that you have a reliable source of entropy2.
Build a centralized or distributed service that generates UUIDs and records each and every one it has ever issued. Each time it generates a new one, it checks that the UUID has never been issued before. Such a service would be technically straight-forward to implement (I think) if we assumed that the people running the service were absolutely trustworthy, incorruptible, etcetera. Unfortunately, they aren't ... especially when there is the possibility of governments' security organizations interfering. So, this approach is probably impractical, and may be3 impossible in the real world.
1 - If uniqueness of UUIDs determined whether nuclear missiles got launched at your country's capital city, a lot of your fellow citizens would not be convinced by "the probability is extremely low". Hence my "nearly all" qualification.
2 - And here's a philosophical question for you. Is anything ever truly random? How would we know if it wasn't? Is the universe as we know it a simulation? Is there a God who might conceivably "tweak" the laws of physics to alter an outcome?
3 - If anyone knows of any research papers on this problem, please comment.
As mentioned by Santosh, I think this query is suitably fast, while not querying all the table.
To return integer result of number of data records, for a specific tablename in a particular database:
select TABLE_ROWS from information_schema.TABLES where TABLE_SCHEMA = 'database'
AND table_name='tablename';
You can use the round function.
round(80.23456, 3)
will give you an answer of 80.234
In your case, use
answer = str(round(answer, 2))
For Python3
html = """\\u003Cdiv id=\\u0022contenedor\\u0022\\u003E \\u003Ch2 class=\\u0022text-left m-b-2\\u0022\\u003EInformaci\\u00f3n del veh\\u00edculo de patente AA345AA\\u003C\\/h2\\u003E\\n\\n\\n\\n \\u003Cdiv class=\\u0022panel panel-default panel-disabled m-b-2\\u0022\\u003E\\n \\u003Cdiv class=\\u0022panel-body\\u0022\\u003E\\n \\u003Ch2 class=\\u0022table_title m-b-2\\u0022\\u003EInformaci\\u00f3n del Registro Automotor\\u003C\\/h2\\u003E\\n \\u003Cdiv class=\\u0022col-md-6\\u0022\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003ERegistro Seccional\\u003C\\/label\\u003E\\n \\u003Cp\\u003ESAN MIGUEL N\\u00b0 1\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EDirecci\\u00f3n\\u003C\\/label\\u003E\\n \\u003Cp\\u003EMAESTRO ANGEL D\\u0027ELIA 766\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EPiso\\u003C\\/label\\u003E\\n \\u003Cp\\u003EPB\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EDepartamento\\u003C\\/label\\u003E\\n \\u003Cp\\u003E-\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EC\\u00f3digo postal\\u003C\\/label\\u003E\\n \\u003Cp\\u003E1663\\u003C\\/p\\u003E\\n \\u003C\\/div\\u003E\\n \\u003Cdiv class=\\u0022col-md-6\\u0022\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003ELocalidad\\u003C\\/label\\u003E\\n \\u003Cp\\u003ESAN MIGUEL\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EProvincia\\u003C\\/label\\u003E\\n \\u003Cp\\u003EBUENOS AIRES\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003ETel\\u00e9fono\\u003C\\/label\\u003E\\n \\u003Cp\\u003E(11)46646647\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EHorario\\u003C\\/label\\u003E\\n \\u003Cp\\u003E08:30 a 12:30\\u003C\\/p\\u003E\\n \\u003C\\/div\\u003E\\n \\u003C\\/div\\u003E\\n\\u003C\\/div\\u003E \\n\\n\\u003Cp class=\\u0022text-center m-t-3 m-b-1 hidden-print\\u0022\\u003E\\n \\u003Ca href=\\u0022javascript:window.print();\\u0022 class=\\u0022btn btn-default\\u0022\\u003EImprim\\u00ed la consulta\\u003C\\/a\\u003E \\u0026nbsp; \\u0026nbsp;\\n \\u003Ca href=\\u0022\\u0022 class=\\u0022btn use-ajax btn-primary\\u0022\\u003EHacer otra consulta\\u003C\\/a\\u003E\\n\\u003C\\/p\\u003E\\n\\u003C\\/div\\u003E"""
print(html.replace("\\/", "/").encode().decode('unicode_escape'))
I'd suggest you do two things:
>>
in your shell script to append contents to particular file. The filename can be fixed or using some pattern.You can move your files to other folder and then pull whole folder.
adb shell mkdir /sdcard/tmp adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end) adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back adb shell rmdir /sdcard/tmp # remove temporary directory
I also had same problem. Purposely my build output path was "..\bin" and it works for me when I set the build output path as "\bin".
Deleting and restoring the entire solution from the repository resolved the issue for me. I didn't find this solution listed in any of the other answers, so thought it might help someone.
We use it as a temporary storage area for uploaded csv files. Once uploaded, an ajax method processes and deletes the file.
With the nuget package System.Resources.ResourceManager
(v4.3.0) the ResourceSet
and ResourceManager.GetResourceSet
are not available.
Using the ResourceReader
, as this post suggest: "C# - Cannot getting a string from ResourceManager (from satellite assembly)"
It's still possible to read the key/values of the resource file.
System.Reflection.Assembly resourceAssembly = System.Reflection.Assembly.Load(new System.Reflection.AssemblyName("YourAssemblyName"));
String[] manifests = resourceAssembly.GetManifestResourceNames();
using (ResourceReader reader = new ResourceReader(resourceAssembly.GetManifestResourceStream(manifests[0])))
{
System.Collections.IDictionaryEnumerator dict = reader.GetEnumerator();
while (dict.MoveNext())
{
String key = dict.Key as String;
String value = dict.Value as String;
}
}
let originalString = "http://www.ihtc.cc?name=htc&title=iOS?????"
1. encodingQuery:
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
result:
"http://www.ihtc.cc?name=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
2. encodingURL:
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
result:
"http:%2F%2Fwww.ihtc.cc%3Fname=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
We can change the item by value, here is the trick:
radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2
Given this route
app.get('/hi/:param1', function(req,res){} );
and given this URL
http://www.google.com/hi/there?qs1=you&qs2=tube
You will have:
req.query
{
qs1: 'you',
qs2: 'tube'
}
req.params
{
param1: 'there'
}
rgba
value for the backgroundColor
.For example,
backgroundColor: 'rgba(52, 52, 52, 0.8)'
This sets it to a grey color with 80% opacity, which is derived from the opacity decimal, 0.8
. This value can be anything from 0.0
to 1.0
.
you can easily disable any process running on port 80 and then run this command
flask run --host 0.0.0.0 --port 80
or if u prefer running it within the .py file
if __name__ == "__main__":
app.run(host=0.0.0.0, port=80)
Use this code, Working properly
CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT
AS
Begin
DECLARE @cnt int;
DECLARE @status int =0;
SET NOCOUNT OFF
SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
if(@cnt = 1)
Begin
return @status;
End
else
Begin
SET @status =1;
return @status;
End
END
Execute SP
DECLARE @statuss bit;
EXECUTE [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;
I don't see this answer already posted, so I'll throw this one into the mix too. This is similar to Jeff's answer with the half-width Hangul space.
var a = 1;_x000D_
var a = 2;_x000D_
var ? = 3;_x000D_
if(a == 1 && a == 2 && ? == 3) {_x000D_
console.log("Why hello there!")_x000D_
}
_x000D_
You might notice a slight discrepancy with the second one, but the first and third are identical to the naked eye. All 3 are distinct characters:
a
- Latin lower case A
a
- Full Width Latin lower case A
?
- Cyrillic lower case A
The generic term for this is "homoglyphs": different unicode characters that look the same. Typically hard to get three that are utterly indistinguishable, but in some cases you can get lucky. A, ?, ?, and ? would work better (Latin-A, Greek Alpha, Cyrillic-A, and Cherokee-A respectively; unfortunately the Greek and Cherokee lower-case letters are too different from the Latin a
: a
,?
, and so doesn't help with the above snippet).
There's an entire class of Homoglyph Attacks out there, most commonly in fake domain names (eg. wikipedi?.org
(Cyrillic) vs wikipedia.org
(Latin)), but it can show up in code as well; typically referred to as being underhanded (as mentioned in a comment, [underhanded] questions are now off-topic on PPCG, but used to be a type of challenge where these sorts of things would show up). I used this website to find the homoglyphs used for this answer.
You can load a local Javascript file (in the tree below your file:/
source page) using the source tag:
<script src="my_data.js"></script>
If you encode your input into Javascript, like in this case:
mydata.js:
$xsl_text = "<xsl:stylesheet version="1.0" + ....
(this is easier for json) then you have your 'data' in a Javascript global variable to use as you wish.
Perhaps you're asking about keeping such things going...
Of course you'll invoke a full table scan for the queries and if the table containing the scores that need to be tallied (aggregations) is large you might want a better performing solution, you can create a secondary table and use rules, such as on insert
- you might look into it.
Not all RDBMS engines have rules, though!
Set the GET query parameters as managed properties in faces-config.xml
so that you don't need to gather them manually:
<managed-bean>
<managed-bean-name>forward</managed-bean-name>
<managed-bean-class>com.example.ForwardBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>action</property-name>
<value>#{param.action}</value>
</managed-property>
<managed-property>
<property-name>actionParam</property-name>
<value>#{param.actionParam}</value>
</managed-property>
</managed-bean>
This way the request forward.jsf?action=outcome1&actionParam=123
will let JSF set the action
and actionParam
parameters as action
and actionParam
properties of the ForwardBean
.
Create a small view forward.xhtml
(so small that it fits in default response buffer (often 2KB) so that it can be resetted by the navigationhandler, otherwise you've to increase the response buffer in the servletcontainer's configuration), which invokes a bean method on beforePhase
of the f:view
:
<!DOCTYPE html>
<html xmlns:f="http://java.sun.com/jsf/core">
<f:view beforePhase="#{forward.navigate}" />
</html>
The ForwardBean
can look like this:
public class ForwardBean {
private String action;
private String actionParam;
public void navigate(PhaseEvent event) {
FacesContext facesContext = FacesContext.getCurrentInstance();
String outcome = action; // Do your thing?
facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);
}
// Add/generate the usual boilerplate.
}
The navigation-rule
speaks for itself (note the <redirect />
entries which would do ExternalContext#redirect()
instead of ExternalContext#dispatch()
under the covers):
<navigation-rule>
<navigation-case>
<from-outcome>outcome1</from-outcome>
<to-view-id>/outcome1.xhtml</to-view-id>
<redirect />
</navigation-case>
<navigation-case>
<from-outcome>outcome2</from-outcome>
<to-view-id>/outcome2.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
An alternative is to use forward.xhtml
as
<!DOCTYPE html>
<html>#{forward}</html>
and update the navigate()
method to be invoked on @PostConstruct
(which will be invoked after bean's construction and all managed property setting):
@PostConstruct
public void navigate() {
// ...
}
It has the same effect, however the view side is not really self-documenting. All it basically does is printing ForwardBean#toString()
(and hereby implicitly constructing the bean if not present yet).
Note for the JSF2 users, there is a cleaner way of passing parameters with <f:viewParam>
and more robust way of handling the redirect/navigation by <f:event type="preRenderView">
. See also among others:
document.body.style.cursor = 'cursorurl';
origin
is not the remote repository name. It is rather a local alias set as a key in place of the remote repository URL.
It avoids the user having to type the whole remote URL when prompting a push.
This name is set by default and for convention by Git when cloning from a remote for the first time.
This alias name is not hard coded and could be changed using following command prompt:
git remote rename origin mynewalias
Take a look at http://git-scm.com/docs/git-remote for further clarifications.
Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.
The variable Random
is only "in scope" inside the main
method. It's not accessible to any methods called by main
. When you return from main
, the variable disappears (it's part of the stack frame).
If you want all of the methods of your class to use the same Random
instance, declare a member variable:
class MyObj {
private final Random random = new Random();
public void compTurn() {
while (true) {
int a = random.nextInt(10);
if (possibles[a] == 1)
break;
}
}
}
This regexp prevents duplicate domain names like [email protected], it will allow only domain two time like [email protected]. It also does not allow statring from number like [email protected]
regexp: /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\@(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/,
All The Best !!!!!
Here's one possible method.
function isMouseInBox(e) {
var textbox = document.getElementById('textbox');
// Box position & sizes
var boxX = textbox.offsetLeft;
var boxY = textbox.offsetTop;
var boxWidth = textbox.offsetWidth;
var boxHeight = textbox.offsetHeight;
// Mouse position comes from the 'mousemove' event
var mouseX = e.pageX;
var mouseY = e.pageY;
if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
if(mouseY>=boxY && mouseY<=boxY+boxHeight){
// Mouse is in the box
return true;
}
}
}
document.addEventListener('mousemove', function(e){
isMouseInBox(e);
})
Often classes are used to enclose methods and following is the extension for answers above with default method in case the method is not found.
class P:
def p1(self):
print('Start')
def p2(self):
print('Help')
def ps(self):
print('Settings')
def d(self):
print('Default function')
myDict = {
"start": p1,
"help": p2,
"settings": ps
}
def call_it(self):
name = 'start'
f = lambda self, x : self.myDict.get(x, lambda x : self.d())(self)
f(self, name)
p = P()
p.call_it()
Pretty much down to personal choice. It may make sense to use an extension based on the database scheme you are storing; treat your database schema as a file format, with SQLite simply being an encoding used for that file format. So, you might use .bookmarks
if it's storing bookmarks, or .index
if it's being used as an index.
If you want to use a generic extension, I'd use .sqlite3
since that is most descriptive of what version of SQLite is needed to work with the database.
I came across same old issue and found below code more understandable which is in a way per above solutions.
std::set<int*>::iterator beginIt = listOfInts.begin();
while(beginIt != listOfInts.end())
{
// Use your member
std::cout<<(*beginIt)<<std::endl;
// delete the object
delete (*beginIt);
// erase item from vector
listOfInts.erase(beginIt );
// re-calculate the begin
beginIt = listOfInts.begin();
}
Basic and primary difference is, ASP.NET web service is designed to exchange SOAP messages over HTTP only while WCF Service can exchange message using any format (SOAP is default) over any transport protocol i.e. HTTP, TCP, MSMQ or NamedPipes etc.
I met this issue due to operation system, simple to different platform about JRE implementation.
new SecureRandom(key.getBytes())
will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.
Coarse-grained granularity does not always mean bigger components, if you go by literally meaning of the word coarse, it means harsh, or not appropriate. e.g. In software projects management, if you breakdown a small system into few components, which are equal in size, but varies in complexities and features, this could lead to a coarse-grained granularity. In reverse, for a fine-grained breakdown, you would divide the components based on their cohesiveness of the functionalities each component is providing.
File imageToUpload = new File(new URI(androidURI.toString())); works if this is a file u have created in the external storage.
For example file:///storage/emulated/0/(some directory and file name)
I notice you have some C++ questions in your profile. If you understand the concept of multiple-inheritance from C++ (referring to classes that inherit characteristics from more than one other class), Java does not allow this, but it does have keyword interface
, which is sort of like a pure virtual class in C++. As mentioned by lots of people, you extend
a class (and you can only extend from one), and you implement
an interface -- but your class can implement as many interfaces as you like.
Ie, these keywords and the rules governing their use delineate the possibilities for multiple-inheritance in Java (you can only have one super class, but you can implement multiple interfaces).
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case "DbConnectionString")
Delete All Records
#for all records
db.session.query(Model).delete()
db.session.commit()
Deleted Single Row
here DB is the object Flask-SQLAlchemy class. It will delete all records from it and if you want to delete specific records then try filter
clause in the query.
ex.
#for specific value
db.session.query(Model).filter(Model.id==123).delete()
db.session.commit()
Delete Single Record by Object
record_obj = db.session.query(Model).filter(Model.id==123).first()
db.session.delete(record_obj)
db.session.commit()
https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records
Add this dependency to your pom.xml
file:
http://mvnrepository.com/artifact/junit/junit-dep/4.8.2
<!-- https://mvnrepository.com/artifact/junit/junit-dep -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>4.8.2</version>
</dependency>
To calculate distance on Google Maps, you can use Directions API. That will be one of the easiest way to do it. To get data from Google Server, you can use Retrofit or Volley. Both has their own advantage. Take a look at following code where I have used retrofit to implement it:
private void build_retrofit_and_get_response(String type) {
String url = "https://maps.googleapis.com/maps/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitMaps service = retrofit.create(RetrofitMaps.class);
Call<Example> call = service.getDistanceDuration("metric", origin.latitude + "," + origin.longitude,dest.latitude + "," + dest.longitude, type);
call.enqueue(new Callback<Example>() {
@Override
public void onResponse(Response<Example> response, Retrofit retrofit) {
try {
//Remove previous line from map
if (line != null) {
line.remove();
}
// This loop will go through all the results and add marker on each location.
for (int i = 0; i < response.body().getRoutes().size(); i++) {
String distance = response.body().getRoutes().get(i).getLegs().get(i).getDistance().getText();
String time = response.body().getRoutes().get(i).getLegs().get(i).getDuration().getText();
ShowDistanceDuration.setText("Distance:" + distance + ", Duration:" + time);
String encodedString = response.body().getRoutes().get(0).getOverviewPolyline().getPoints();
List<LatLng> list = decodePoly(encodedString);
line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(20)
.color(Color.RED)
.geodesic(true)
);
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
Above is the code of function build_retrofit_and_get_response for calculating distance. Below is corresponding Retrofit Interface:
package com.androidtutorialpoint.googlemapsdistancecalculator;
import com.androidtutorialpoint.googlemapsdistancecalculator.POJO.Example;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;
public interface RetrofitMaps {
/*
* Retrofit get annotation with our URL
* And our method that will return us details of student.
*/
@GET("api/directions/json?key=AIzaSyC22GfkHu9FdgT9SwdCWMwKX1a4aohGifM")
Call<Example> getDistanceDuration(@Query("units") String units, @Query("origin") String origin, @Query("destination") String destination, @Query("mode") String mode);
}
I hope this explains your query. All the best :)
Source: Google Maps Distance Calculator
You can handle custom cell in uicollection view see below code.
- (void)viewDidLoad
{
UINib *nib2 = [UINib nibWithNibName:@"YourCustomCell" bundle:nil];
[CollectionVW registerNib:nib2 forCellWithReuseIdentifier:@"YourCustomCell"];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(200, 230)];
flowLayout.minimumInteritemSpacing = 0;
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[CollectionVW setCollectionViewLayout:flowLayout];
[CollectionVW reloadData];
}
#pragma mark - COLLECTIONVIEW
#pragma mark Collection View CODE
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return Array.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"YourCustomCell";
YourCustomCell *cell = (YourCustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.MainIMG.image=[UIImage imageNamed:[Array objectAtIndex:indexPath.row]];
return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}
#pragma mark Collection view layout things
// Layout: Set cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize mElementSize;
mElementSize=CGSizeMake(kScreenWidth/3.4, 150);
return mElementSize;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 5.0;
}
// Layout: Set Edges
- (UIEdgeInsets)collectionView: (UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
if (isIphone5 || isiPhone4)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
else if (isIphone6)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
else if (isIphone6P)
{
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
return UIEdgeInsetsMake(15,15,5,15); // top, left, bottom, right
}
you could use this
curl_setopt($curl->curl, CURLOPT_SSL_VERIFYPEER, false);
In Jboss you can perform the following
nohup $JBOSS_HOME/bin/run.sh -c yourinstancename $JBOSS_OPTS >> console-$(date +%Y%m%d).out 2>&1 < /dev/null &
kill -3 <java_pid>
This will redirect your output/threadump to the file console specified in the above command.
git stash
did the job,
It restored the files that I had deleted using rm
instead of git rm
.
I did first a checkout of the last hash, but I do not believe it is required.
The syntax is wrong. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class:
class A {
public:
int f();
int (A::*x)(); // <- declare by saying what class it is a pointer to
};
int A::f() {
return 1;
}
int main() {
A a;
a.x = &A::f; // use the :: syntax
printf("%d\n",(a.*(a.x))()); // use together with an object of its class
}
a.x
does not yet say on what object the function is to be called on. It just says that you want to use the pointer stored in the object a
. Prepending a
another time as the left operand to the .*
operator will tell the compiler on what object to call the function on.
You can convert your .ui files to an executable python file using the below command..
pyuic4 -x form1.ui > form1.py
Now you can straightaway execute the python file as
python3(whatever version) form1.py
You can import this file and you can use it.
XRegExp has an escape function:
XRegExp.escape('Escaped? <.>');
// -> 'Escaped\?\ <\.>'
More on: http://xregexp.com/api/#escape
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(int i, char *c[]) {
if (i != 2)
fprintf(stderr, "Usage: perror errno\n");
else {
errno = atoi(c[1]);
perror("");
}
exit(0);
}
Works on Solaris.
cc perror.c -o perror
<< use this line to compile it
Use sonar.coverage.exclusions property.
mvn clean install -Dsonar.coverage.exclusions=**/*ToBeExcluded.java
This should exclude the classes from coverage calculation.
f = Character.toUpperCase(f);
l = Character.toUpperCase(l);
From Java 7 (API Description) onwards you can do:
new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
Where filePath is a String representing the file you want to load.
This error usually comes when the Windows user account is expired and he is already logged in with old password. Just ask the user to restart his machine and check if the password is expired or he has changed the password. Hope this helps!!!!!
While this is an old post, I recently came across it when I was looking for a solution to the same issue. While the above solutions do prevent charts from plotting data (when source cells are #N/A or made to look blank), it doesn't resolve the issue of the chart data labels themselves still showing a zero label.
I had searched and searched and almost given up, when I came across the solution posted online @ https://www.extendoffice.com/documents/excel/2031-excel-hide-zero-data-labels.html
It worked liked a charm. Attached is an image showing an example of how the data (labels) displayed before, Chart#1, and how it displays using this tip chart#2.
you can use the weight value specified in the Google Fonts.
body{
font-family: 'Heebo', sans-serif;
font-weight: 100;
}
simple answer for Angular 8.*
constructor(private route:ActivatedRoute) {
console.log(route);
}
new
, you are responsible for calling delete
. When you create an object with make_shared
, the resulting shared_ptr
is responsible for keeping count and calling delete
when the use count goes to zero.new
(i.e. it is a stack object).new
.See below. This code works with spring-boot and spring-boot + apache CXF/SOAP.
// in your class RequestUtil
private static final String[] IP_HEADER_NAMES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR"
};
public static String getRemoteIP(RequestAttributes requestAttributes)
{
if (requestAttributes == null)
{
return "0.0.0.0";
}
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
String ip = Arrays.asList(IP_HEADER_NAMES)
.stream()
.map(request::getHeader)
.filter(h -> h != null && h.length() != 0 && !"unknown".equalsIgnoreCase(h))
.map(h -> h.split(",")[0])
.reduce("", (h1, h2) -> h1 + ":" + h2);
return ip + request.getRemoteAddr();
}
//... in service class:
String remoteAddress = RequestUtil.getRemoteIP(RequestContextHolder.currentRequestAttributes());
:)
To rehash a couple of old jokes:
for (;;) {}
" — it makes the statement cry.#define EVER ;;
".Try this:
find . -name .svn -exec rm -v {} \;
Read more about the find command at developerWorks.
If are using jQuery, grep may be useful:
var arr = [ a, b, c, , e, f, , g, h ];
arr = jQuery.grep(arr, function(n){ return (n); });
arr
is now [ a, b, c, d, e, f, g];
It is possible to use "flex-start" and to add the margins manually. It requires some math-hacking but is definitely easy to do and make it easy to use with a CSS preprocessor like LESS.
See for example this LESS mixin:
.flexboxGridMixin(@columnNumber,@spacingPercent) {
@contentPercent: 100% - @spacingPercent;
@sideMargin: @spacingPercent/(@columnNumber*2);
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
> * {
box-sizing: border-box;
width: @contentPercent/@columnNumber;
margin-left: @sideMargin;
margin-right: @sideMargin;
}
}
And then it can easily be used to display a responsive grid layout:
ul {
list-style: none;
padding: 0;
@spacing: 10%;
@media only screen and (max-width: 499px) { .flexboxGridMixin(1,@spacing); }
@media only screen and (min-width: 500px) { .flexboxGridMixin(2,@spacing); }
@media only screen and (min-width: 700px) { .flexboxGridMixin(3,@spacing); }
@media only screen and (min-width: 900px) { .flexboxGridMixin(4,@spacing); }
@media only screen and (min-width: 1100px) { .flexboxGridMixin(5,@spacing); }
}
li {
background: pink;
height: 100px;
margin-top: 20px;
}
Here is an example of
Here is an answer by way of example:
In order to make sure data loggers are online a cron
script runs every 15 minutes that looks like this:
#!/bin/bash
#
if ! ping -c 1 SOLAR &>/dev/null
then
echo "SUBJECT: SOLAR is not responding to ping" | ssmtp [email protected]
echo "SOLAR is not responding to ping" | ssmtp [email protected]
else
echo "SOLAR is up"
fi
#
if ! ping -c 1 OUTSIDE &>/dev/null
then
echo "SUBJECT: OUTSIDE is not responding to ping" | ssmtp [email protected]
echo "OUTSIDE is not responding to ping" | ssmtp [email protected]
else
echo "OUTSIDE is up"
fi
#
...and so on for each data logger that you can see in the montage at http://www.SDsolarBlog.com/montage
FYI, using &>/dev/null
redirects all output from the command, including errors, to /dev/null
(The conditional only requires the exit status
of the ping
command)
Also FYI, note that since cron
jobs run as root
there is no need to use sudo ping
in a cron
script.
If you have to get gradients and background images working together in IE 9 (HTML 5 & HTML 4.01 Strict), add the following attribute declaration to your css class and it should do the trick:
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr='#000000', endColorstr='#ff00ff'), progid:DXImageTransform.Microsoft.AlphaImageLoader(src='[IMAGE_URL]', sizingMethod='crop');
Notice that you use the filter
attribute and that there are two instances of progid:[val]
separated by a comma before you close the attribute value with a semicolon. Here's the fiddle. Also notice that when you look at the fiddle the gradient extends beyond the rounded corners. I don't have a fix for that other not using rounded corners. Also note that when using a relative path in the src [IMAGE_URL] attribute, the path is relative to the document page and not the css file (See source).
This article (http://coding.smashingmagazine.com/2010/04/28/css3-solutions-for-internet-explorer/) is what lead me to this solution. It's pretty helpful for IE-specific CSS3.
If you don't need to change something onMeasure - there's absolutely no need for you to override it.
Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).
You can check the onMeasure method here :
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
Overriding SDK code to be replaced with the exact same code makes no sense.
This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.
You're out of memory. Try adding -Xmx256m
to your java command line. The 256m
is the amount of memory to give to the JVM (256 megabytes). It usually defaults to 64m
.
This should do it for you:
Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'
Select ProductName,
IsNull([1],0) as 'Week 1',
IsNull([2],0) as 'Week 2',
IsNull([3],0) as 'Week 3',
IsNull([4],0) as 'Week 4',
IsNull([5], 0) as 'Week 5'
From
(
Select ProductName,
DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, InputDate), 0), InputDate) +1 as [Weeks],
Sale as 'Sale'
From dbo.YourTable
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, InputDate)= DatePart(Month, @DatePeriod)
)p
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv
It will calculate the week number relative to the month. So instead of week 20 for the year it will be week 2. The @DatePeriod
variable is used to fetch only rows relative to the month (in this example only for the month of May)
Output using my sample data:
If you are running a nginx + uwsgi setup vagrant then the main problem is the Virtual box bug with send file as mentioned in some of the answers. However to resolve it you have to disable sendfile in both nginx and uwsgi.
In nginx.conf sendfile off
uwsgi application / config --disable-sendfile
The problem here is very simple. If you want to display value in JSP, you have to use <%= %> tag instead of <% %>, here is the solved code:
<tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getString("SKILL") %></td>
</tr>
Try using a format like %d.%02d
int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);
Another approach is to type cast it to double before printing it using %f like this:
printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);
My 2 cents :)
Okay I just detached and reattach to the screen session and I am back to normal screen I wanted
Use the Below Code for that
UPDATE Table1 SET Column1 = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(Column1, CHAR(9), ''), CHAR(10), ''), CHAR(13), '')))`
Class is only meaningful in the context of software engineering. In the context of data structures and algorithms, class and struct are not that different. There's no any rule restricted that class's member must be referenced.
When developing large project with tons of people without class, you may finally get complicated coupled code because everybody use whatever functions and data they want. class provides permission controls and inherents to enhance decoupling and reusing codes.
If you read some software engineering principles, you'll find most standards can not be implemented easily without class. for example: http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29
BTW, When a struct allocates a crunch of memory and includes several variables, value type variables indicates that values are embbeded in where struct is allocated. In contrast, reference type variable's values are external and reference by a pointer which is also embedded in where struct is allocated.
None of the provided examples here work for the generic case, which are N dimensional matrices. Anything using "rows" assumes theres columns and rows only, a 4 dimensional matrix might have more.
Here is some example code copying a non-continuous N-dimensional matrix into a continuous memory stream - then converts it back into a Cv::Mat
#include <iostream>
#include <cstdint>
#include <cstring>
#include <opencv2/opencv.hpp>
int main(int argc, char**argv)
{
if ( argc != 2 )
{
std::cerr << "Usage: " << argv[0] << " <Image_Path>\n";
return -1;
}
cv::Mat origSource = cv::imread(argv[1],1);
if (!origSource.data) {
std::cerr << "Can't read image";
return -1;
}
// this will select a subsection of the original source image - WITHOUT copying the data
// (the header will point to a region of interest, adjusting data pointers and row step sizes)
cv::Mat sourceMat = origSource(cv::Range(origSource.size[0]/4,(3*origSource.size[0])/4),cv::Range(origSource.size[1]/4,(3*origSource.size[1])/4));
// correctly copy the contents of an N dimensional cv::Mat
// works just as fast as copying a 2D mat, but has much more difficult to read code :)
// see http://stackoverflow.com/questions/18882242/how-do-i-get-the-size-of-a-multi-dimensional-cvmat-mat-or-matnd
// copy this code in your own cvMat_To_Char_Array() function which really OpenCV should provide somehow...
// keep in mind that even Mat::clone() aligns each row at a 4 byte boundary, so uneven sized images always have stepgaps
size_t totalsize = sourceMat.step[sourceMat.dims-1];
const size_t rowsize = sourceMat.step[sourceMat.dims-1] * sourceMat.size[sourceMat.dims-1];
size_t coordinates[sourceMat.dims-1] = {0};
std::cout << "Image dimensions: ";
for (int t=0;t<sourceMat.dims;t++)
{
// calculate total size of multi dimensional matrix by multiplying dimensions
totalsize*=sourceMat.size[t];
std::cout << (t>0?" X ":"") << sourceMat.size[t];
}
// Allocate destination image buffer
uint8_t * imagebuffer = new uint8_t[totalsize];
size_t srcptr=0,dptr=0;
std::cout << std::endl;
std::cout << "One pixel in image has " << sourceMat.step[sourceMat.dims-1] << " bytes" <<std::endl;
std::cout << "Copying data in blocks of " << rowsize << " bytes" << std::endl ;
std::cout << "Total size is " << totalsize << " bytes" << std::endl;
while (dptr<totalsize) {
// we copy entire rows at once, so lowest iterator is always [dims-2]
// this is legal since OpenCV does not use 1 dimensional matrices internally (a 1D matrix is a 2d matrix with only 1 row)
std::memcpy(&imagebuffer[dptr],&(((uint8_t*)sourceMat.data)[srcptr]),rowsize);
// destination matrix has no gaps so rows follow each other directly
dptr += rowsize;
// src matrix can have gaps so we need to calculate the address of the start of the next row the hard way
// see *brief* text in opencv2/core/mat.hpp for address calculation
coordinates[sourceMat.dims-2]++;
srcptr = 0;
for (int t=sourceMat.dims-2;t>=0;t--) {
if (coordinates[t]>=sourceMat.size[t]) {
if (t==0) break;
coordinates[t]=0;
coordinates[t-1]++;
}
srcptr += sourceMat.step[t]*coordinates[t];
}
}
// this constructor assumes that imagebuffer is gap-less (if not, a complete array of step sizes must be given, too)
cv::Mat destination=cv::Mat(sourceMat.dims, sourceMat.size, sourceMat.type(), (void*)imagebuffer);
// and just to proof that sourceImage points to the same memory as origSource, we strike it through
cv::line(sourceMat,cv::Point(0,0),cv::Point(sourceMat.size[1],sourceMat.size[0]),CV_RGB(255,0,0),3);
cv::imshow("original image",origSource);
cv::imshow("partial image",sourceMat);
cv::imshow("copied image",destination);
while (cv::waitKey(60)!='q');
}
There are two kinds of cell reference, and it's really valuable to understand them well.
One is relative reference, which is what you get when you just type the cell: A5
. This reference will be adjusted when you paste or fill the formula into other cells.
The other is absolute reference, and you get this by adding dollar signs to the cell reference: $A$5
. This cell reference will not change when pasted or filled.
A cool but rarely used feature is that row and column within a single cell reference may be independent: $A5
and A$5
. This comes in handy for producing things like multiplication tables from a single formula.
I agree with Brian Rasmussen, the unxutils port is the easiest way to do this. In the Batch Files section of his Scripting Pages Rob van der Woude provides a wealth of information on the use MS-DOS and CMD commands. I thought he might have a native solution to your problem and after digging around there I found TEE.BAT, which appears to be just that, an MS-DOS batch language implementation of tee. It is a pretty complex-looking batch file and my inclination would still be to use the unxutils port.
You need to modify the Starter-Application class as shown below.
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages="com.nice.application")
@EnableJpaRepositories("com.spring.app.repository")
public class InventoryApp extends SpringBootServletInitializer {..........
And update the Controller, Service and Repository packages structure as I mentioned below.
Example: REST-Controller
package com.nice.controller;
--> It has to be modified as
package com.nice.application.controller;
You need to follow proper package structure for all packages which are in Spring Boot MVC flow.
So, If you modify your project bundle package structures correctly then your spring boot app will work correctly.
you can add toggle class or toggle state on click
class Test extends Component(){
state={
active:false,
}
toggleClass() {
console.log(this.state.active)
this.setState=({
active:true,
})
}
render() {
<div>
<div onClick={this.toggleClass.bind(this)}>
<p>1</p>
</div>
</div>
}
}
I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.
You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.
public class ImageButton extends Parent {
private static final Image NORMAL_IMAGE = ...;
private static final Image PRESSED_IMAGE = ...;
private final ImageView iv;
public ImageButton() {
this.iv = new ImageView(NORMAL_IMAGE);
this.getChildren().add(this.iv);
this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(PRESSED_IMAGE);
}
});
// TODO other event handlers like mouse up
}
}
I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).
A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.
Do like this:
create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;
Definitely a matter of style. I prefer constructors with default parameters, so long as the parameters make sense. Classes in the standard use them as well, which speaks in their favor.
One thing to watch out for is if you have defaults for all but one parameter, your class can be implicitly converted from that parameter type. Check out this thread for more info.