It should be
r.append("\n");
But I recommend you to do as below,
r.append(System.getProperty("line.separator"));
System.getProperty("line.separator")
gives you system-dependent newline in java. Also from Java 7 there's a method that returns the value directly: System.lineSeparator()
This happens when PDO::ATTR_EMULATE_PREPARES
is set to true
on the connection.
Careful though, setting it to false
disallows the use of parameters more than once. I believe it also affects the quality of the error messages coming back.
2011-01-15
= 2011-16
= 1995
. This is then being implicitly converted from an integer to a date, giving you the 1995th day, starting from 1st Jan 1900.
You need to use SET @test = '2011-02-15'
You have to set the height
for the parents (container and child) explicitly, here is another work-around (if you don't want to set that height explicitly):
.child {
width: 30px;
background-color: red;
display: table-cell;
vertical-align: top;
position:relative;
}
.content {
position:absolute;
top:0;
bottom:0;
width:100%;
background-color: blue;
}
I didn't mean to copy the same answer, that is why I didn't accept my own answer.
Actually when I add use DateTime
in top of the controller solves this problem.
If you want to understand AutoResetEvent and ManualResetEvent you need to understand not threading but interrupts!
.NET wants to conjure up low-level programming the most distant possible.
An interrupts is something used in low-level programming which equals to a signal that from low became high (or viceversa). When this happens the program interrupt its normal execution and move the execution pointer to the function that handles this event.
The first thing to do when an interrupt happend is to reset its state, becosa the hardware works in this way:
This is the difference between ManualResetEvent and AutoResetEvent.
If a ManualResetEvent happen and I do not reset it, the next time it happens I will not be able to listen it.
I did this:
php -r "echo json_encode(array_combine(DateTimeZone::listIdentifiers(DateTimeZone::ALL), DateTimeZone::listIdentifiers(DateTimeZone::ALL)));" > list-of-timezones.json
public string SendFile(string filePath)
{
WebResponse response = null;
try
{
string sWebAddress = "Https://www.address.com";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(sWebAddress);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream stream = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
stream.Write(boundarybytes, 0, boundarybytes.Length);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(filePath);
stream.Write(formitembytes, 0, formitembytes.Length);
stream.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "file", Path.GetFileName(filePath), Path.GetExtension(filePath));
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
stream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
stream.Write(buffer, 0, bytesRead);
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
stream.Write(trailer, 0, trailer.Length);
stream.Close();
response = wr.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string responseData = streamReader.ReadToEnd();
return responseData;
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
if (response != null)
response.Close();
}
}
A margin-top of -8px means it will be 8px higher than if it had 0 margin.
A margin-bottom of 8px means that the thing below it will be 8px further down that if it had 0 margin.
You can use .map().
Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.
As the return value is a jQuery object, which contains an array, it's very common to call .get()
on the result to work with a basic array.
Use
var arr = $('input[name="pname[]"]').map(function () {
return this.value; // $(this).val()
}).get();
Applying the full_extent()
function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox()
which gives a little tighter bounding box
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox
def full_extent(ax, pad=0.0):
"""Get the full extent of an axes, including axes labels, tick labels, and
titles."""
# For text objects, we need to draw the figure first, otherwise the extents
# are undefined.
ax.figure.canvas.draw()
items = ax.get_xticklabels() + ax.get_yticklabels()
# items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
items += [ax, ax.title]
bbox = Bbox.union([item.get_window_extent() for item in items])
return bbox.expanded(1.0 + pad, 1.0 + pad)
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
I'd post a pic but I lack the reputation points
Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming
Update March 2013
Git 1.8.2 added the possibility to track branches.
"
git submodule
" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).
# add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".
Also see Vogella's tutorial on submodules for general information on submodules.
Note:
git submodule add -b . [URL to Git repo];
^^^
A special value of
.
is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.
See commit b928922727d6691a3bdc28160f93f25712c565f6:
submodule add
: If --branch
is given, record it in .gitmodules
This allows you to easily record a
submodule.<name>.branch
option in.gitmodules
when you add a new submodule. With this patch,
$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>
reduces to
$ git submodule add -b <branch> <repository> [<path>]
This means that future calls to
$ git submodule update --remote ...
will get updates from the same branch that you used to initialize the submodule, which is usually what you want.
Signed-off-by: W. Trevor King [email protected]
Original answer (February 2012):
A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log
within that submodule.
So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:
gitslave (that you already looked at) seems to be the best fit, including for the commit operation.
It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).
Other alternatives are detailed here.
pre-made code attached here. you can use it by just copying and pasting in your code:
https://gist.github.com/umairidrees/8952054#file-php-save-db-table-as-csv
Sometimes it is Skype or another application "Holding" on to port 80. Jusct close Skype
Something like this:
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
target: self
selector: @selector(handleTimer:)
userInfo: nil
repeats: YES];
--version
is a valid option from JDK 9 and it is not a valid option until JDK 8 hence you get the below:
Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
You can try installing JDK 9 or any version later and check for java --version
it will work.
Alternately, from the installed JDK 9 or later versions you can see from java -help
the below two options will be available:
-version print product version to the error stream and exit
--version print product version to the output stream and exit
where as in JDK 8 you will only have below when you execute java -help
-version print product version and exit
I hope it answers your question.
A (MySQLdb/PyMySQL-specific) difference worth noting when using a DictCursor
is that list(cursor)
will always give you a list, while cursor.fetchall()
gives you a list unless the result set is empty, in which case it gives you an empty tuple. This was the case in MySQLdb and remains the case in the newer PyMySQL, where it will not be fixed for backwards-compatibility reasons. While this isn't a violation of Python Database API Specification, it's still surprising and can easily lead to a type error caused by wrongly assuming that the result is a list, rather than just a sequence.
Given the above, I suggest always favouring list(cursor)
over cursor.fetchall()
, to avoid ever getting caught out by a mysterious type error in the edge case where your result set is empty.
If you are still in your development environment, I would drop the entire db and start over with your new schema.
From the command line
? mongo
use dbName;
db.dropDatabase();
exit
One more variant using extension
and argument name range
This extension uses Range
and ClosedRange
extension Array {
subscript (range r: Range<Int>) -> Array {
return Array(self[r])
}
subscript (range r: ClosedRange<Int>) -> Array {
return Array(self[r])
}
}
Tests:
func testArraySubscriptRange() {
//given
let arr = ["1", "2", "3"]
//when
let result = arr[range: 1..<arr.count] as Array
//then
XCTAssertEqual(["2", "3"], result)
}
func testArraySubscriptClosedRange() {
//given
let arr = ["1", "2", "3"]
//when
let result = arr[range: 1...arr.count - 1] as Array
//then
XCTAssertEqual(["2", "3"], result)
}
Along the lines of Sainath S.R's comment above, I was able to set a js object property name from a variable in Google Apps Script (which does not support ES6 yet) by defining the object then defining another key/value outside of the object:
var salesperson = ...
var mailchimpInterests = {
"aGroupId": true,
};
mailchimpInterests[salesperson] = true;
If you want check only displayed objects(C#):
public bool TextPresent(string text, int expectedNumberOfOccurrences)
{
var elements = Driver.FindElements(By.XPath(".//*[text()[contains(.,'" + text + "')]]"));
var dispayedElements = 0;
foreach (var webElement in elements)
{
if (webElement.Displayed)
{
dispayedElements++;
}
}
var allExpectedElementsDisplayed = dispayedElements == expectedNumberOfOccurrences;
return allExpectedElementsDisplayed;
}
When I used above code.It show me translated text as question mark like (???????).Then I convert from WebClient to HttpClient then I got a accurate result.So you can used code like this.
public static string TranslateText( string input, string languagePair)
{
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
HttpClient httpClient = new HttpClient();
string result = httpClient.GetStringAsync(url).Result;
result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
result = result.Substring(result.IndexOf(">") + 1);
result = result.Substring(0, result.IndexOf("</span>"));
return result.Trim();
}
Then you Call a function like.You put first two letter of any language pair.
From English(en) To Urdu(ur).
TranslateText(line, "en|ur")
The same reason there isn't an int.Empty
. Containers can be empty, scalar values cannot. If you mean 0 (which is not empty), then use '\0'
. If you mean null
, then use null
:)
An idea would be that display:flex;
with flex-direction: row;
is filling the container
div with .flex-1
and .flex-2
, but that does not mean that .flex-2
has a default height:100%;
, even if it is extended to full height.
And to have a child element (.flex-2-child
) with height:100%;
, you'll need to set the parent to height:100%;
or use display:flex;
with flex-direction: row;
on the .flex-2
div too.
From what I know, display:flex
will not extend all your child elements height to 100%.
A small demo, removed the height from .flex-2-child
and used display:flex;
on .flex-2
:
http://jsfiddle.net/2ZDuE/3/
I know that this is an old question but I wanted to write my answer for visual learners. I couldn't find any diagrams explaining output buffering on the worldwide-web so I made a diagram myself in Windows mspaint.exe
.
If output buffering is turned off, then echo
will send data immediately to the Browser.
If output buffering is turned on, then an echo
will send data to the output buffer before sending it to the Browser.
phpinfo
To see whether Output buffering is turned on / off please refer to phpinfo at the core section. The output_buffering
directive will tell you if Output buffering is on/off.
In this case the output_buffering
value is 4096 which means that the buffer size is 4 KB. It also means that Output buffering is turned on, on the Web server.
php.ini
It's possible to turn on/off and change buffer size by changing the value of the output_buffering
directive. Just find it in php.ini
, change it to the setting of your choice, and restart the Web server. You can find a sample of my php.ini
below.
; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
; functions.
; Possible Values:
; On = Enabled and buffer is unlimited. (Use with caution)
; Off = Disabled
; Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096
The directive output_buffering
is not the only configurable directive regarding Output buffering. You can find other configurable Output buffering directives here: http://php.net/manual/en/outcontrol.configuration.php
Example: ob_get_clean()
Below you can see how to capture an echo
and manipulate it before sending it to the browser.
// Turn on output buffering
ob_start();
echo 'Hello World'; // save to output buffer
$output = ob_get_clean(); // Get content from the output buffer, and discard the output buffer ...
$output = strtoupper($output); // manipulate the output
echo $output; // send to output stream / Browser
// OUTPUT:
HELLO WORLD
Examples: Hackingwithphp.com
More info about Output buffer with examples can be found here:
I use http://wiltgen.net/objecty/, it helps to embed media content and avoid the IE "click to activate" problem.
This error is gone for me by remove the AVD and create a new one.
after some compile and clean, the error was gone away.
This is a very good article: http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/
In summary, for great performance, you should:
For example, to reduce the access to disk, you can use a large buffer. The article describes various approaches.
I wanted to answer to the following question which is a little bit different than this:
Best way to print messages on multiple lines
He wanted to show lines from repeated characters too. He wanted this output:
----------------------------------------
# Operator Micro-benchmarks
# Run_mode: short
# Num_repeats: 5
# Num_runs: 1000
----------------------------------------
You can create those lines inside f-strings with a multiplication, like this:
run_mode, num_repeats, num_runs = 'short', 5, 1000
s = f"""
{'-'*40}
# Operator Micro-benchmarks
# Run_mode: {run_mode}
# Num_repeats: {num_repeats}
# Num_runs: {num_runs}
{'-'*40}
"""
print(s)
def NewFileName(fichier):
cpt = 0
fic , *ext = fichier.split('.')
ext = '.'.join(ext)
while os.path.isfile(fichier):
cpt += 1
fichier = '{0}-({1}).{2}'.format(fic, cpt, ext)
return fichier
Try this:
printf '\n%s\n' 'I want this on a new line!'
That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.
quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f %s\n' "$quantity" "$price" "$description"
38 142.15 advanced widget
Instead of instantiating the FileUpload
in your code behind file, just declare it in your markup file (.aspx file):
<asp:FileUpload ID="fileUpload" runat="server" />
Then you will be able to access all of the properties of the control, such as HasFile
.
<?php
// ------------------------------------------------------
function curl_get_contents($url) {
$timeout = 5;
$useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
// ------------------------------------------------------
function fetch_meta_tags($url) {
$html = curl_get_contents($url);
$mdata = array();
$doc = new DOMDocument();
$doc->loadHTML($html);
$titlenode = $doc->getElementsByTagName('title');
$title = $titlenode->item(0)->nodeValue;
$metanodes = $doc->getElementsByTagName('meta');
foreach($metanodes as $node) {
$key = $node->getAttribute('name');
$val = $node->getAttribute('content');
if (!empty($key)) { $mdata[$key] = $val; }
}
$res = array($url, $title, $mdata);
return $res;
}
// ------------------------------------------------------
?>
SELECT *
INTO #Temp
FROM
(SELECT
Received,
Total,
Answer,
(CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) AS application
FROM
FirstTable
WHERE
Recieved = 1 AND
application = 'MORESTUFF'
GROUP BY
CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) data
WHERE
application LIKE
isNull(
'%MORESTUFF%',
'%')
It's more convenient to use a session, this way you don't have to remember to set headers each time:
session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})
session.get('https://httpbin.org/headers')
By default, session also manages cookies for you. In case you want to disable that, see this question.
For Query parameters like domain.com/test?format=json&type=mini
format, then you can easily receive it via - req.query.
app.get('/test', function(req, res){
var format = req.query.format,
type = req.query.type;
});
xmllint support formatting in-place:
for f in *.xml; do xmllint -o $f --format $f; done
As Daniel Veillard has written:
I think
xmllint -o tst.xml --format tst.xml
should be safe as the parser will fully load the input into a tree before opening the output to serialize it.
Indent level is controlled by XMLLINT_INDENT
environment variable which is by default 2 spaces. Example how to change indent to 4 spaces:
XMLLINT_INDENT=' ' xmllint -o out.xml --format in.xml
You may have lack with --recover
option when you XML documents are broken. Or try weak HTML parser with strict XML output:
xmllint --html --xmlout <in.xml >out.xml
--nsclean
, --nonet
, --nocdata
, --noblanks
etc may be useful. Read man page.
apt-get install libxml2-utils
apt-cyg install libxml2
brew install libxml2
import re
htmlString = '</dd><dt> Fine, thank you. </dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'
SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'
Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)
print Result.groups()
Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.
I'm a beginner too and I faced that issue a couple of times myself.
I am encounted this problem when I am using Admob JUST because I forgot to write my Ad Unit ID into @string
.
Use chown
to change ownership and chmod
to change rights.
use the -R
option to apply the rights for all files inside of a directory too.
Note that both these commands just work for directories too. The -R
option makes them also change the permissions for all files and directories inside of the directory.
For example
sudo chown -R username:group directory
will change ownership (both user and group) of all files and directories inside of directory and directory itself.
sudo chown username:group directory
will only change the permission of the folder directory but will leave the files and folders inside the directory alone.
you need to use sudo to change the ownership from root to yourself.
Edit:
Note that if you use chown user: file
(Note the left-out group), it will use the default group for that user.
Also You can change the group ownership of a file or directory with the command:
chgrp group_name file/directory_name
You must be a member of the group to which you are changing ownership to.
You can find group of file as follows
# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file
# chown sujit:friends file
User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.
What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.
But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.
Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.
I faced with the problem like this.
The problem was that I added the public key without '-----BEGIN PUBLIC KEY-----' at the beginning and without '-----END PUBLIC KEY-----'.
So it causes the error.
Initially, my public key was like this:
-----BEGIN PUBLIC KEY-----
WnsbGUXbb0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2wKKyRdcROK7ZTSCSMsJpAFOY
-----END PUBLIC KEY-----
But I used just this part:
WnsbGUXb+b0GbJSCwCBAhrzT0s2KMRyqqS7QBiIG7t3H2Qtmde6UoUIcTTPJgv71
......
oNLcaK2w+KKyRdcROK7ZTSCSMsJpAFOY
In Selenium IDE you can do:
Command | clickAndWait Target | //input[@value='Next' and @title='next']
It should work fine.
First you need to start karma server with
karma start
Then, you can use grep to filter a specific test or describe block:
karma run -- --grep=testDescriptionFilter
We don't need to access the canvas context.
Implementing hednek in pure JS you would get canvas.setAttribute('style', 'background-color:#00F8')
. But my preferred method requires converting the kabab-case to camelCase.
canvas.style.backgroundColor = '#00F8'
This should give what you want:
FLOOR(RAND() * 401) + 100
Generically, FLOOR(RAND() * (<max> - <min> + 1)) + <min>
generates a number between <min
> and <max>
inclusive.
Update
This full statement should work:
SELECT name, address, FLOOR(RAND() * 401) + 100 AS `random_number`
FROM users
I've always found it easier to invert the test against the list in situations like this. For instance...
SELECT
field0, field1, field2
FROM
my_table
WHERE
',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%'
This means that there is no complicated mish-mash required for the values that you are looking for.
As an example, if our list was ('1,2,3')
, then we add a comma to the start and end of our list like so: ',' + @mysearchlist + ','
.
We also do the same for the field value we're looking for and add wildcards: '%,' + CAST(field3 AS VARCHAR) + ',%'
(notice the %
and the ,
characters).
Finally we test the two using the LIKE
operator: ',' + @mysearchlist + ',' LIKE '%,' + CAST(field3 AS VARCHAR) + ',%'
.
Is Button1
visible? I mean, from the server side. Make sure Button1.Visible is true.
Controls that aren't Visible
won't be rendered in HTML, so although they are assigned a ClientID
, they don't actually exist on the client side.
You forgot to reset the position of the memory stream:
private void Test()
{
System.IO.MemoryStream data = new System.IO.MemoryStream();
System.IO.Stream str = TestStream();
str.CopyTo(data);
// Reset memory stream
data.Seek(0, SeekOrigin.Begin);
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
}
Update:
There is one more thing to note: It usually pays not to ignore the return values of methods. A more robust implementation should check how many bytes have been read after the call returns:
private void Test()
{
using(MemoryStream data = new MemoryStream())
{
using(Stream str = TestStream())
{
str.CopyTo(data);
}
// Reset memory stream
data.Seek(0, SeekOrigin.Begin);
byte[] buf = new byte[data.Length];
int bytesRead = data.Read(buf, 0, buf.Length);
Debug.Assert(bytesRead == data.Length,
String.Format("Expected to read {0} bytes, but read {1}.",
data.Length, bytesRead));
}
}
Core jQuery doesn't have anything special for touch events, but you can easily build your own using the following events
For example, the touchmove
document.addEventListener('touchmove', function(e) {
e.preventDefault();
var touch = e.touches[0];
alert(touch.pageX + " - " + touch.pageY);
}, false);
This works in most WebKit based browsers (incl. Android).
If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.
You can however drop this web.config in the root of the folder or site where you want to set it:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>
</system.webServer>
</configuration>
That will inform the client to cache content for 7 days in that folder and all subfolders.
You can also do this by editing the IIS7 metabase via appcmd.exe
, like so:
\Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMode:UseMaxAge \Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMaxAge:"7.00:00:00"
<div class="container-fluid">
<div class="row">
<h3 class="one">Text</h3>
<button class="btn btn-secondary ml-auto">Button</button>
</div>
</div>
.ml-auto
is Bootstraph 4's non-flexbox way of aligning things.
CSV is a standard format, outlined in RFC 4180 (in 2005), so there IS no lack of a standard. https://www.ietf.org/rfc/rfc4180.txt
And even before that, the C in CSV has always stood for Comma, not for semiColon :(
It's a pity Microsoft keeps ignoring that and is still sticking to the monstrosity they turned it into decades ago (yes, I admit, that was before the RFC was created).
Only if text is enclosed in double quotation marks, such quotations marks in the text escaped by doubling. These examples represent the same three fields:
1,"this text contains ""quotation marks""",3
1,this text contains "quotation marks",3
The standard does not cover date and time values, personally I try to stick to ISO 8601 format to avoid day/month/year -- month/day/year confusion.
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
It is simple for me i downloaded the apk file in my computer and drag that file to emulator it install the google play for me Hope it help some one
Not forgetting
.equalsIgnoreCase(String)
if you're not worried about that sort of thing...
Simple Solution:
df['date_only'] = df['date_time_column'].dt.date
This flexbox principle also works horizontally
During calculations of flex bases and flexible lengths, auto margins
are treated as 0.
Prior to alignment via justify-content and
align-self, any positive free space is distributed to auto margins in
that dimension.
Setting an automatic left margin for the Last Item will do the work.
.last-item {
margin-left: auto;
}
Code Example:
.container {_x000D_
display: flex;_x000D_
width: 400px;_x000D_
outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
margin: 5px;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<p></p>_x000D_
<p></p>_x000D_
<p></p>_x000D_
<p class="last-item"></p>_x000D_
</div>
_x000D_
This can be very useful for Desktop Footers.
As Envato did here with the company logo.
DON'T change the interpreter path.
Change the project structure instead:
File -> Settings -> Project -> Project structure -> Add content root
Try this:
$("#datepicker").datepicker({ minDate: 0 });
Remove the quotes from 0
.
In my case, the problem was another. I was trying convert lists of lists of int to array. The problem was that there was one list with a different length than others. If you want to prove it, you must do:
print([i for i,x in enumerate(list) if len(x) != 560])
In my case, the length reference was 560.
Just make top,bottom, left and right to 0.
<html>
<head>
<style>
<div>
{
position: absolute;
margin: auto;
background-color: lightblue;
width: 100px;
height :100px;
padding: 25px;
top :0;
right :0;
bottom:0;
left:0;
}
</style>
</head>
<body>
<div> I am in the middle</div>
</body>
</html>
I was able to center a view using
android:layout_centerHorizontal="true"
and
android:layout_centerVertical="true"
params.
Spring Data
is a convenience library on top of JPA
that abstracts away many things and brings Spring magic (like it or not) to the persistence store access. It is primarily used for working with relational databases. In short, it allows you to declare interfaces that have methods like findByNameOrderByAge(String name);
that will be parsed in runtime and converted into appropriate JPA
queries.
Its placement atop of JPA
makes its use tempting for:
Rookie developers who don't know SQL
or know it badly. This is a
recipe for disaster but they can get away with it if the project is trivial.
Experienced engineers who know what they do and want to spindle up things fast. This might be a viable strategy (but read further).
From my experience with Spring Data
, its magic is too much (this is applicable to Spring
in general). I started to use it heavily in one project and eventually hit several corner cases where I couldn't get the library out of my way and ended up with ugly workarounds. Later I read other users' complaints and realized that these issues are typical for Spring Data
. For example, check this issue that led to hours of investigation/swearing:
public TourAccommodationRate createTourAccommodationRate(
@RequestBody TourAccommodationRate tourAccommodationRate
) {
if (tourAccommodationRate.getId() != null) {
throw new BadRequestException("id MUST NOT be specified in a body during entry creation");
}
// This is an ugly hack required for the Room slim model to work. The problem stems from the fact that
// when we send a child entity having the many-to-many (M:N) relation to the containing entity, its
// information is not fetched. As a result, we get NPEs when trying to access all but its Id in the
// code creating the corresponding slim model. By detaching the entity from the persistence context we
// force the ORM to re-fetch it from the database instead of taking it from the cache
tourAccommodationRateRepository.save(tourAccommodationRate);
entityManager.detach(tourAccommodationRate);
return tourAccommodationRateRepository.findOne(tourAccommodationRate.getId());
}
I ended up going lower level and started using JDBI
- a nice library with just enough "magic" to save you from the boilerplate. With it, you have complete control over SQL queries and almost never have to fight the library.
None of the above worked for me. I SOLVED my problem by saving my source data (save as) Excel file as a single xls Worksheet Excel 5.0/95 and imported without column headings. Also, I created the table in advance and mapped manually instead of letting SQL create the table.
1
$("ul.rootlist > target-element")
2 $("ul.rootlist").find(target-element).eq(0) (only one instance)
3 $("ul.rootlist").children(target-element)
there are probably many other ways
I was using express server with nodemon on NodeJS. I got the following message and it seems an error:
$ node ./bin/www
Port 3000 is already in use
There is a general solution that if you terminate all node server connections, you can add this code in your package.json file:
"scripts": {
"start": "node ./bin/www",
"stop": "taskkill -f -im node.exe"
},
In addition, I've found several solutions windows command and bash on Win 10 x64.
All my notes are here:
# Terminate all NodeJS Server Connections
$ taskkill -f -im node.exe
SUCCESS: The process "node.exe" with PID 14380 has been terminated.
SUCCESS: The process "node.exe" with PID 18364 has been terminated.
SUCCESS: The process "node.exe" with PID 18656 has been terminated.
# Example: Open the Windows Task Manager and see "node.exe" PID number on Windows
>> Command Line
$ netstat /?
$ netstat -a -n -o
$ netstat -ano
# Kill a process in Windows by Port Number (Example)
For Help:
$ taskkill /?
$ tskill /?
Code 1:
$ taskkill -pid 14228
ERROR: The process with PID 14228 could not be terminated.
Reason: This process can only be terminated forcefully (with /F option).
Code 2:
$ taskkill -f -pid 14228
SUCCESS: The process with PID 14228 has been terminated.
Code 3:
$ tskill 14228
# Command line for looking at specific port
in cmd:
$ netstat -ano | find "14228"
in bash:
$ netstat -ano | grep "14228" or $ netstat -ano | grep 14228
# Find node.exe using "tasklist" command
in cmd:
$ tasklist | find "node"
in bash:
$ tasklist | grep node
$ tasklist | grep node.exe
node.exe 14228 Console 2 48,156 K
node.exe 15236 Console 2 24,776 K
node.exe 19364 Console 2 24,428 K
awk -F " " '($1=="A1") {print $NF}' FILE | tail -n 1
Use awk
with field separator -F set to a space " ".
Use the pattern $1=="A1"
and action {print $NF}
, this will print the last field in every record where the first field is "A1". Pipe the result into tail and use the -n 1
option to only show the last line.
If you right-click on your "Computer" (or "My Computer") icon and select "Manage" from the pop-up menu, that'll take you to the Computer Management console.
In there, under System Tools\Shared Folders, you'll find "Open Files". This is probably close to what you want, but if the file is on a network share then you'd need to do the same thing on the server on which the file lives.
The size member function.
myList.size();
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
You can install pidof
with Homebrew:
brew install pidof
pidof <process_name>
I found that "@RequestMapping produces=" and other configuration changes didn't help me. By the time you do resp.getWriter(), it is also too late to set the encoding on the writer.
Adding a header to the HttpServletResponse works.
@RequestMapping(value="/test", method=RequestMethod.POST)
public void test(HttpServletResponse resp) {
try {
resp.addHeader("content-type", "application/json; charset=utf-8");
PrintWriter w = resp.getWriter();
w.write("{\"name\" : \"µr µicron\"}");
w.flush();
w.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Fluid layout in Bootstrap 3.
Unlike Boostrap 2, Bootstrap 3 doesn't have a .container-fluid mixin to make a fluid container. The .container is a fixed width responsive grid layout. In a large screen, there are excessive white spaces in both sides of one's Web page content.
container-fluid
is added back in Bootstrap 3.1
A fluid grid layout uses all screen width and works better in large screen. It turns out that it is easy to create a fluid grid layout using Bootstrap 3 mixins. The following line makes a fluid responsive grid layout:
.container-fixed;
The .container-fixed mixin sets the content to the center of the screen and add paddings. It doesn't specifies a fixed page width.
Another approach is to use Eric Flowers' CSS style
.my-fluid-container {
padding-left: 15px;
padding-right: 15px;
margin-left: auto;
margin-right: auto;
}
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
GitHub Flavored Markdown doesn't support footnotes, but you can manually fake it¹ with Unicode characters or superscript tags, e.g. <sup>1</sup>
.
¹Of course this isn't ideal, as you are now responsible for maintaining the numbering of your footnotes. It works reasonably well if you only have one or two, though.
I typically use triggers to handle timestamps but I think this may work.
$data = array(
'name' => $name,
'email' => $email
);
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
You can use FileInfo object to get all information of your file.
FileInfo f = new FileInfo(@"C:\Hello\AnotherFolder\The File Name.PDF");
MessageBox.Show(f.Name);
MessageBox.Show(f.FullName);
MessageBox.Show(f.Extension );
MessageBox.Show(f.DirectoryName);
If you want to create the popup window through jQuery then you'll need to use a plugin. This one seems like it will do what you want:
http://rip747.github.com/popupwindow/
Alternately, you can always use JavaScript's window.open function.
Note that with either approach, the new window must be opened in response to user input/action (so for instance, a click on a link or button). Otherwise the browser's popup blocker will just block the popup.
There are several ways that you can transform data from multiple rows into columns.
PIVOT
In SQL Server you can use the PIVOT
function to transform the data from rows to columns:
select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
select value, columnname
from yourtable
) d
pivot
(
max(value)
for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;
See Demo.
columnnames
If you have an unknown number of columnnames
that you want to transpose, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName)
from yourtable
group by ColumnName, id
order by id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select value, ColumnName
from yourtable
) x
pivot
(
max(value)
for ColumnName in (' + @cols + N')
) p '
exec sp_executesql @query;
See Demo.
If you do not want to use the PIVOT
function, then you can use an aggregate function with a CASE
expression:
select
max(case when columnname = 'FirstName' then value end) Firstname,
max(case when columnname = 'Amount' then value end) Amount,
max(case when columnname = 'PostalCode' then value end) PostalCode,
max(case when columnname = 'LastName' then value end) LastName,
max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable
See Demo.
This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:
select fn.value as FirstName,
a.value as Amount,
pc.value as PostalCode,
ln.value as LastName,
an.value as AccountNumber
from yourtable fn
left join yourtable a
on fn.somecol = a.somecol
and a.columnname = 'Amount'
left join yourtable pc
on fn.somecol = pc.somecol
and pc.columnname = 'PostalCode'
left join yourtable ln
on fn.somecol = ln.somecol
and ln.columnname = 'LastName'
left join yourtable an
on fn.somecol = an.somecol
and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'
ALTER TABLE <tablename> CHANGE COLUMN <colname> <colname> VARCHAR(65536);
You have to list the column name twice, even if you aren't changing its name.
Note that after you make this change, the data type of the column will be MEDIUMTEXT
.
Miky D is correct, the MODIFY
command can do this more concisely.
Re the MEDIUMTEXT
thing: a MySQL row can be only 65535 bytes (not counting BLOB/TEXT columns). If you try to change a column to be too large, making the total size of the row 65536 or greater, you may get an error. If you try to declare a column of VARCHAR(65536)
then it's too large even if it's the only column in that table, so MySQL automatically converts it to a MEDIUMTEXT
data type.
mysql> create table foo (str varchar(300));
mysql> alter table foo modify str varchar(65536);
mysql> show create table foo;
CREATE TABLE `foo` (
`str` mediumtext
) ENGINE=MyISAM DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
I misread your original question, you want VARCHAR(65353)
, which MySQL can do, as long as that column size summed with the other columns in the table doesn't exceed 65535.
mysql> create table foo (str1 varchar(300), str2 varchar(300));
mysql> alter table foo modify str2 varchar(65353);
ERROR 1118 (42000): Row size too large.
The maximum row size for the used table type, not counting BLOBs, is 65535.
You have to change some columns to TEXT or BLOBs
the context.xml configuration didn't work for me. Tomcat 6.0.29 complains about the docBase being inside the appBase: ... For Tomcat 5 this did actually work.
So one solution is to put the application in the ROOT folder.
Another very simple solution is to put an index.jsp to ROOT that redirects to my application like this: response.sendRedirect("/MyApplicationXy");
Best Regards, Jan
This looks like you have to enable .htaccess
by adding this to your vhost:
<Directory /var/www/html/public/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
If that doesn't work, make sure you have mod_rewrite enabled.
Don't forget to restart apache after making the changes! (service apache2 restart
)
Give 0777 to all files and directories starting from the current path :
chmod -R 0777 ./
In addition to installing the repository and the SDK packages one should be aware that the version number changes periodically. A simple solution at this point is to replace the specific version number with a plus (+) symbol.
compile 'com.google.android.gms:play-services:+'
Google instructions indicate that one should be sure to upgrade the version numbers, however adding the plus deals with the changes in versioning. Also note that when building in Android Studio a message will appear in the status line when a new version is available.
One can view the available versions of play services by drilling down on the correct repository path:
References
This site also has instructions for Eclipse, and other IDE's.
I prefer this
if(in_array($id,$user_access_arr) == false)
respective
if (in_array(search_value, array) == false)
// value is not in array
Another way to look at this. Check out the details of the exception:
In [49]: try:
...: open('file.DNE.txt')
...: except Exception as e:
...: print(dir(e))
...:
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']
There are lots of "things" to access using the 'as e' syntax.
This code was solely meant to show the details of this instance.
Ideally you need to have .d.ts
file for typings to let Linting
work.
But It seems that d3gauge
doesn't have one, you can Ask the developers to provide and hope they will listen.
Alternatively, you can solve this specific issue by doing this
declare var drawGauge: any;
import '../../../../js/d3gauge.js';
export class MemMonComponent {
createMemGauge() {
new drawGauge(this.opt); //drawGauge() is a function inside d3gauge.js
}
}
If you use it in multiple files, you can create a d3gauage.d.ts
file with the content below
declare var drawGauge: any;
and reference it in your boot.ts
(bootstrap) file at the top, like this
///<reference path="../path/to/d3gauage.d.ts"/>
For me the issue was that I used the connection string
generated by ADO.Net
Model (.edmx). Changing the connection string solved my issue.
I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.
//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
"ln": {c.ln},
"ip": {c.ip},
"ua": {c.ua}})
//okay, moving on...
if err != nil {
//handle postform error
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
//handle read response error
}
fmt.Printf("%s\n", string(body))
The most recent and in my opinion preferred approach is the f-string
:
''.join(f'{i:02x}' for i in [1, 15, 255])
The old format style was the %
-syntax:
['%02x'%i for i in [1, 15, 255]]
The more modern approach is the .format
method:
['{:02x}'.format(i) for i in [1, 15, 255]]
More recently, from python 3.6 upwards we were treated to the f-string
syntax:
[f'{i:02x}' for i in [1, 15, 255]]
Note that the f'{i:02x}'
works as follows.
:
is the input or variable to format. x
indicates that the string should be hex. f'{100:02x}'
is '64'
and f'{100:02d}'
is '1001'
.02
indicates that the string should be left-filled with 0
's to length 2
. f'{100:02x}'
is '64'
and f'{100:30x}'
is ' 64'
.Have you tried using a icon font like http://fortawesome.github.io/Font-Awesome/
Bootstrap comes with their own library, but it doesn't have as many icons as Font Awesome.
Normally when querying a database with SQL and then fill a data-table with its results, it will never be a null Data table. You have the column headers filled with column information even if you returned 0 records.When one tried to process a data table with 0 records but with column information it will throw exception.To check the datatable before processing one could check like this.
if (DetailTable != null && DetailTable.Rows.Count>0)
I ran into the same problem and found that the documentation has example for this type of scenario (where we write STDERR TO STDOUT and always exit successfully with return code 0) without causing/catching an exception.
output = subprocess.check_output("ping -c 2 -W 2 1.1.1.1; exit 0", stderr=subprocess.STDOUT, shell=True)
Now, you can use standard string function find
to check the output string output
.
For Idea 2017.1 + Gradle, the plugin is somehow buggy. Tried all synchronize, invalidate + restart, nothing worked. According to https://github.com/gradle/gradle/issues/2315, this worked for me: 1. Close Idea 2. Type gradle idea in command line (should generate 3 files: .iml, .ipr, .iws) 3. Run idea and open the created file .ipr, this should import your project from scratch, with hard-wired dependencies in those 3 files
In boto 3, the 'Key.set_contents_from_' methods were replaced by
For example:
import boto3
some_binary_data = b'Here we have some data'
more_binary_data = b'Here we have some more data'
# Method 1: Object.put()
s3 = boto3.resource('s3')
object = s3.Object('my_bucket_name', 'my/key/including/filename.txt')
object.put(Body=some_binary_data)
# Method 2: Client.put_object()
client = boto3.client('s3')
client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')
Alternatively, the binary data can come from reading a file, as described in the official docs comparing boto 2 and boto 3:
Storing Data
Storing data from a file, stream, or string is easy:
# Boto 2.x from boto.s3.key import Key key = Key('hello.txt') key.set_contents_from_file('/tmp/hello.txt') # Boto 3 s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))
You can use:
adb shell monkey -p com.package.name -c android.intent.category.LAUNCHER 1
This will start the LAUNCHER Activity of the application using monkeyrunner test tool.
There are a couple of other applications that i've seen recommended, you'll find them here:
Wrapping can be done in various ways. I'll mention 2 of them:
1.) text wrapping - using white-space property http://www.w3schools.com/cssref/pr_text_white-space.asp
2.) word wrapping - using word-wrap property http://webdesignerwall.com/tutorials/word-wrap-force-text-to-wrap
By the way, in order to work using these 2 approaches, I believe you need to set the "display" property to block of the corresponding span element.
However, as Kirill already mentioned, it's a good idea to think about it for a moment. You're talking about forcing the text into a paragraph. PARAGRAPH. That should ring some bells in your head, shouldn't it? ;)
You cannot guarantee that the automatically-generated WSDL will match the WSDL from which you create the service interface.
In your scenario, you should place the WSDL file on your web site somewhere, and have consumers use that URL. You should disable the Documentation
protocol in the web.config so that "?wsdl" does not return a WSDL. See <protocols>
Element.
Also, note the first paragraph of that article:
This topic is specific to a legacy technology. XML Web services and XML Web service clients should now be created using Windows Communication Foundation (WCF).
>>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
>>> import itertools
>>> k.sort()
>>> list(k for k,_ in itertools.groupby(k))
[[1, 2], [3], [4], [5, 6, 2]]
itertools
often offers the fastest and most powerful solutions to this kind of problems, and is well worth getting intimately familiar with!-)
Edit: as I mention in a comment, normal optimization efforts are focused on large inputs (the big-O approach) because it's so much easier that it offers good returns on efforts. But sometimes (essentially for "tragically crucial bottlenecks" in deep inner loops of code that's pushing the boundaries of performance limits) one may need to go into much more detail, providing probability distributions, deciding which performance measures to optimize (maybe the upper bound or the 90th centile is more important than an average or median, depending on one's apps), performing possibly-heuristic checks at the start to pick different algorithms depending on input data characteristics, and so forth.
Careful measurements of "point" performance (code A vs code B for a specific input) are a part of this extremely costly process, and standard library module timeit
helps here. However, it's easier to use it at a shell prompt. For example, here's a short module to showcase the general approach for this problem, save it as nodup.py
:
import itertools
k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
def doset(k, map=map, list=list, set=set, tuple=tuple):
return map(list, set(map(tuple, k)))
def dosort(k, sorted=sorted, xrange=xrange, len=len):
ks = sorted(k)
return [ks[i] for i in xrange(len(ks)) if i == 0 or ks[i] != ks[i-1]]
def dogroupby(k, sorted=sorted, groupby=itertools.groupby, list=list):
ks = sorted(k)
return [i for i, _ in itertools.groupby(ks)]
def donewk(k):
newk = []
for i in k:
if i not in newk:
newk.append(i)
return newk
# sanity check that all functions compute the same result and don't alter k
if __name__ == '__main__':
savek = list(k)
for f in doset, dosort, dogroupby, donewk:
resk = f(k)
assert k == savek
print '%10s %s' % (f.__name__, sorted(resk))
Note the sanity check (performed when you just do python nodup.py
) and the basic hoisting technique (make constant global names local to each function for speed) to put things on equal footing.
Now we can run checks on the tiny example list:
$ python -mtimeit -s'import nodup' 'nodup.doset(nodup.k)'
100000 loops, best of 3: 11.7 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dosort(nodup.k)'
100000 loops, best of 3: 9.68 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dogroupby(nodup.k)'
100000 loops, best of 3: 8.74 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.donewk(nodup.k)'
100000 loops, best of 3: 4.44 usec per loop
confirming that the quadratic approach has small-enough constants to make it attractive for tiny lists with few duplicated values. With a short list without duplicates:
$ python -mtimeit -s'import nodup' 'nodup.donewk([[i] for i in range(12)])'
10000 loops, best of 3: 25.4 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dogroupby([[i] for i in range(12)])'
10000 loops, best of 3: 23.7 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.doset([[i] for i in range(12)])'
10000 loops, best of 3: 31.3 usec per loop
$ python -mtimeit -s'import nodup' 'nodup.dosort([[i] for i in range(12)])'
10000 loops, best of 3: 25 usec per loop
the quadratic approach isn't bad, but the sort and groupby ones are better. Etc, etc.
If (as the obsession with performance suggests) this operation is at a core inner loop of your pushing-the-boundaries application, it's worth trying the same set of tests on other representative input samples, possibly detecting some simple measure that could heuristically let you pick one or the other approach (but the measure must be fast, of course).
It's also well worth considering keeping a different representation for k
-- why does it have to be a list of lists rather than a set of tuples in the first place? If the duplicate removal task is frequent, and profiling shows it to be the program's performance bottleneck, keeping a set of tuples all the time and getting a list of lists from it only if and where needed, might be faster overall, for example.
This is how Oauth 2.0 works, well explained in this article
I wrote this helper function:
def is_module_available(module_name):
if sys.version_info < (3, 0):
# python 2
import importlib
torch_loader = importlib.find_loader(module_name)
elif sys.version_info <= (3, 3):
# python 3.0 to 3.3
import pkgutil
torch_loader = pkgutil.find_loader(module_name)
elif sys.version_info >= (3, 4):
# python 3.4 and above
import importlib
torch_loader = importlib.util.find_spec(module_name)
return torch_loader is not None
In MainViewController.m inside: - (void)viewWillAppear:(BOOL)animated
add this:
//Lower screen 20px on ios 7
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
CGRect viewBounds = [self.webView bounds];
viewBounds.origin.y = 18;
viewBounds.size.height = viewBounds.size.height - 18;
self.webView.frame = viewBounds;
}
so the end function will look like this:
- (void)viewWillAppear:(BOOL)animated
{
// View defaults to full size. If you want to customize the view's size, or its subviews (e.g. webView),
// you can do so here.
//Lower screen 20px on ios 7
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
CGRect viewBounds = [self.webView bounds];
viewBounds.origin.y = 18;
viewBounds.size.height = viewBounds.size.height - 18;
self.webView.frame = viewBounds;
}
[super viewWillAppear:animated];
}
You can try jQuery treegrid (http://maxazan.github.io/jquery-treegrid/) or jQuery treetable (http://ludo.cubicphuse.nl/jquery-treetable/)
Both are using HTML <table>
tag format and styled the as tree.
The jQuery treetable is using data-tt-id
and data-tt-parent-id
for determining the parent and child of the tree. Usage example:
<table id="tree">
<tr data-tt-id="1">
<td>Parent</td>
</tr>
<tr data-tt-id="2" data-tt-parent-id="1">
<td>Child</td>
</tr>
</table>
$("#tree").treetable({ expandable: true });
Meanwhile, jQuery treegrid is using only class for styling the tree. Usage example:
<table class="tree">
<tr class="treegrid-1">
<td>Root node</td><td>Additional info</td>
</tr>
<tr class="treegrid-2 treegrid-parent-1">
<td>Node 1-1</td><td>Additional info</td>
</tr>
<tr class="treegrid-3 treegrid-parent-1">
<td>Node 1-2</td><td>Additional info</td>
</tr>
<tr class="treegrid-4 treegrid-parent-3">
<td>Node 1-2-1</td><td>Additional info</td>
</tr>
</table>
<script type="text/javascript">
$('.tree').treegrid();
</script>
It seems that for full page reload $window.location.href
is the preferred way.
It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.
Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.
<telerik:RadScriptBlock ID="radSript1" runat="server">
<script type="text/javascript">
//Your javascript
</script>
</telerik>
Regards Örvar
The standard approach suggested by Nate Kohl, just using vector, sort + unique:
sort( vec.begin(), vec.end() );
vec.erase( unique( vec.begin(), vec.end() ), vec.end() );
doesn't work for a vector of pointers.
Look carefully at this example on cplusplus.com.
In their example, the "so called duplicates" moved to the end are actually shown as ? (undefined values), because those "so called duplicates" are SOMETIMES "extra elements" and SOMETIMES there are "missing elements" that were in the original vector.
A problem occurs when using std::unique()
on a vector of pointers to objects (memory leaks, bad read of data from HEAP, duplicate frees, which cause segmentation faults, etc).
Here's my solution to the problem: replace std::unique()
with ptgi::unique()
.
See the file ptgi_unique.hpp below:
// ptgi::unique()
//
// Fix a problem in std::unique(), such that none of the original elts in the collection are lost or duplicate.
// ptgi::unique() has the same interface as std::unique()
//
// There is the 2 argument version which calls the default operator== to compare elements.
//
// There is the 3 argument version, which you can pass a user defined functor for specialized comparison.
//
// ptgi::unique() is an improved version of std::unique() which doesn't looose any of the original data
// in the collection, nor does it create duplicates.
//
// After ptgi::unique(), every old element in the original collection is still present in the re-ordered collection,
// except that duplicates have been moved to a contiguous range [dupPosition, last) at the end.
//
// Thus on output:
// [begin, dupPosition) range are unique elements.
// [dupPosition, last) range are duplicates which can be removed.
// where:
// [] means inclusive, and
// () means exclusive.
//
// In the original std::unique() non-duplicates at end are moved downward toward beginning.
// In the improved ptgi:unique(), non-duplicates at end are swapped with duplicates near beginning.
//
// In addition if you have a collection of ptrs to objects, the regular std::unique() will loose memory,
// and can possibly delete the same pointer multiple times (leading to SEGMENTATION VIOLATION on Linux machines)
// but ptgi::unique() won't. Use valgrind(1) to find such memory leak problems!!!
//
// NOTE: IF you have a vector of pointers, that is, std::vector<Object*>, then upon return from ptgi::unique()
// you would normally do the following to get rid of the duplicate objects in the HEAP:
//
// // delete objects from HEAP
// std::vector<Object*> objects;
// for (iter = dupPosition; iter != objects.end(); ++iter)
// {
// delete (*iter);
// }
//
// // shrink the vector. But Object * pointers are NOT followed for duplicate deletes, this shrinks the vector.size())
// objects.erase(dupPosition, objects.end));
//
// NOTE: But if you have a vector of objects, that is: std::vector<Object>, then upon return from ptgi::unique(), it
// suffices to just call vector:erase(, as erase will automatically call delete on each object in the
// [dupPosition, end) range for you:
//
// std::vector<Object> objects;
// objects.erase(dupPosition, last);
//
//==========================================================================================================
// Example of differences between std::unique() vs ptgi::unique().
//
// Given:
// int data[] = {10, 11, 21};
//
// Given this functor: ArrayOfIntegersEqualByTen:
// A functor which compares two integers a[i] and a[j] in an int a[] array, after division by 10:
//
// // given an int data[] array, remove consecutive duplicates from it.
// // functor used for std::unique (BUGGY) or ptgi::unique(IMPROVED)
//
// // Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
// // Hence 50..59 are equal, 60..69 are equal, etc.
// struct ArrayOfIntegersEqualByTen: public std::equal_to<int>
// {
// bool operator() (const int& arg1, const int& arg2) const
// {
// return ((arg1/10) == (arg2/10));
// }
// };
//
// Now, if we call (problematic) std::unique( data, data+3, ArrayOfIntegersEqualByTen() );
//
// TEST1: BEFORE UNIQ: 10,11,21
// TEST1: AFTER UNIQ: 10,21,21
// DUP_INX=2
//
// PROBLEM: 11 is lost, and extra 21 has been added.
//
// More complicated example:
//
// TEST2: BEFORE UNIQ: 10,20,21,22,30,31,23,24,11
// TEST2: AFTER UNIQ: 10,20,30,23,11,31,23,24,11
// DUP_INX=5
//
// Problem: 21 and 22 are deleted.
// Problem: 11 and 23 are duplicated.
//
//
// NOW if ptgi::unique is called instead of std::unique, both problems go away:
//
// DEBUG: TEST1: NEW_WAY=1
// TEST1: BEFORE UNIQ: 10,11,21
// TEST1: AFTER UNIQ: 10,21,11
// DUP_INX=2
//
// DEBUG: TEST2: NEW_WAY=1
// TEST2: BEFORE UNIQ: 10,20,21,22,30,31,23,24,11
// TEST2: AFTER UNIQ: 10,20,30,23,11,31,22,24,21
// DUP_INX=5
//
// @SEE: look at the "case study" below to understand which the last "AFTER UNIQ" results with that order:
// TEST2: AFTER UNIQ: 10,20,30,23,11,31,22,24,21
//
//==========================================================================================================
// Case Study: how ptgi::unique() works:
// Remember we "remove adjacent duplicates".
// In this example, the input is NOT fully sorted when ptgi:unique() is called.
//
// I put | separatators, BEFORE UNIQ to illustrate this
// 10 | 20,21,22 | 30,31 | 23,24 | 11
//
// In example above, 20, 21, 22 are "same" since dividing by 10 gives 2 quotient.
// And 30,31 are "same", since /10 quotient is 3.
// And 23, 24 are same, since /10 quotient is 2.
// And 11 is "group of one" by itself.
// So there are 5 groups, but the 4th group (23, 24) happens to be equal to group 2 (20, 21, 22)
// So there are 5 groups, and the 5th group (11) is equal to group 1 (10)
//
// R = result
// F = first
//
// 10, 20, 21, 22, 30, 31, 23, 24, 11
// R F
//
// 10 is result, and first points to 20, and R != F (10 != 20) so bump R:
// R
// F
//
// Now we hits the "optimized out swap logic".
// (avoid swap because R == F)
//
// // now bump F until R != F (integer division by 10)
// 10, 20, 21, 22, 30, 31, 23, 24, 11
// R F // 20 == 21 in 10x
// R F // 20 == 22 in 10x
// R F // 20 != 30, so we do a swap of ++R and F
// (Now first hits 21, 22, then finally 30, which is different than R, so we swap bump R to 21 and swap with 30)
// 10, 20, 30, 22, 21, 31, 23, 24, 11 // after R & F swap (21 and 30)
// R F
//
// 10, 20, 30, 22, 21, 31, 23, 24, 11
// R F // bump F to 31, but R and F are same (30 vs 31)
// R F // bump F to 23, R != F, so swap ++R with F
// 10, 20, 30, 22, 21, 31, 23, 24, 11
// R F // bump R to 22
// 10, 20, 30, 23, 21, 31, 22, 24, 11 // after the R & F swap (22 & 23 swap)
// R F // will swap 22 and 23
// R F // bump F to 24, but R and F are same in 10x
// R F // bump F, R != F, so swap ++R with F
// R F // R and F are diff, so swap ++R with F (21 and 11)
// 10, 20, 30, 23, 11, 31, 22, 24, 21
// R F // aftter swap of old 21 and 11
// R F // F now at last(), so loop terminates
// R F // bump R by 1 to point to dupPostion (first duplicate in range)
//
// return R which now points to 31
//==========================================================================================================
// NOTES:
// 1) the #ifdef IMPROVED_STD_UNIQUE_ALGORITHM documents how we have modified the original std::unique().
// 2) I've heavily unit tested this code, including using valgrind(1), and it is *believed* to be 100% defect-free.
//
//==========================================================================================================
// History:
// 130201 dpb [email protected] created
//==========================================================================================================
#ifndef PTGI_UNIQUE_HPP
#define PTGI_UNIQUE_HPP
// Created to solve memory leak problems when calling std::unique() on a vector<Route*>.
// Memory leaks discovered with valgrind and unitTesting.
#include <algorithm> // std::swap
// instead of std::myUnique, call this instead, where arg3 is a function ptr
//
// like std::unique, it puts the dups at the end, but it uses swapping to preserve original
// vector contents, to avoid memory leaks and duplicate pointers in vector<Object*>.
#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
#error the #ifdef for IMPROVED_STD_UNIQUE_ALGORITHM was defined previously.. Something is wrong.
#endif
#undef IMPROVED_STD_UNIQUE_ALGORITHM
#define IMPROVED_STD_UNIQUE_ALGORITHM
// similar to std::unique, except that this version swaps elements, to avoid
// memory leaks, when vector contains pointers.
//
// Normally the input is sorted.
// Normal std::unique:
// 10 20 20 20 30 30 20 20 10
// a b c d e f g h i
//
// 10 20 30 20 10 | 30 20 20 10
// a b e g i f g h i
//
// Now GONE: c, d.
// Now DUPS: g, i.
// This causes memory leaks and segmenation faults due to duplicate deletes of same pointer!
namespace ptgi {
// Return the position of the first in range of duplicates moved to end of vector.
//
// uses operator== of class for comparison
//
// @param [first, last) is a range to find duplicates within.
//
// @return the dupPosition position, such that [dupPosition, end) are contiguous
// duplicate elements.
// IF all items are unique, then it would return last.
//
template <class ForwardIterator>
ForwardIterator unique( ForwardIterator first, ForwardIterator last)
{
// compare iterators, not values
if (first == last)
return last;
// remember the current item that we are looking at for uniqueness
ForwardIterator result = first;
// result is slow ptr where to store next unique item
// first is fast ptr which is looking at all elts
// the first iterator moves over all elements [begin+1, end).
// while the current item (result) is the same as all elts
// to the right, (first) keeps going, until you find a different
// element pointed to by *first. At that time, we swap them.
while (++first != last)
{
if (!(*result == *first))
{
#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
// inc result, then swap *result and *first
// THIS IS WHAT WE WANT TO DO.
// BUT THIS COULD SWAP AN ELEMENT WITH ITSELF, UNCECESSARILY!!!
// std::swap( *first, *(++result));
// BUT avoid swapping with itself when both iterators are the same
++result;
if (result != first)
std::swap( *first, *result);
#else
// original code found in std::unique()
// copies unique down
*(++result) = *first;
#endif
}
}
return ++result;
}
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique( ForwardIterator first, ForwardIterator last, BinaryPredicate pred)
{
if (first == last)
return last;
// remember the current item that we are looking at for uniqueness
ForwardIterator result = first;
while (++first != last)
{
if (!pred(*result,*first))
{
#ifdef IMPROVED_STD_UNIQUE_ALGORITHM
// inc result, then swap *result and *first
// THIS COULD SWAP WITH ITSELF UNCECESSARILY
// std::swap( *first, *(++result));
//
// BUT avoid swapping with itself when both iterators are the same
++result;
if (result != first)
std::swap( *first, *result);
#else
// original code found in std::unique()
// copies unique down
// causes memory leaks, and duplicate ptrs
// and uncessarily moves in place!
*(++result) = *first;
#endif
}
}
return ++result;
}
// from now on, the #define is no longer needed, so get rid of it
#undef IMPROVED_STD_UNIQUE_ALGORITHM
} // end ptgi:: namespace
#endif
And here is the UNIT Test program that I used to test it:
// QUESTION: in test2, I had trouble getting one line to compile,which was caused by the declaration of operator()
// in the equal_to Predicate. I'm not sure how to correctly resolve that issue.
// Look for //OUT lines
//
// Make sure that NOTES in ptgi_unique.hpp are correct, in how we should "cleanup" duplicates
// from both a vector<Integer> (test1()) and vector<Integer*> (test2).
// Run this with valgrind(1).
//
// In test2(), IF we use the call to std::unique(), we get this problem:
//
// [dbednar@ipeng8 TestSortRoutes]$ ./Main7
// TEST2: ORIG nums before UNIQUE: 10, 20, 21, 22, 30, 31, 23, 24, 11
// TEST2: modified nums AFTER UNIQUE: 10, 20, 30, 23, 11, 31, 23, 24, 11
// INFO: dupInx=5
// TEST2: uniq = 10
// TEST2: uniq = 20
// TEST2: uniq = 30
// TEST2: uniq = 33427744
// TEST2: uniq = 33427808
// Segmentation fault (core dumped)
//
// And if we run valgrind we seen various error about "read errors", "mismatched free", "definitely lost", etc.
//
// valgrind --leak-check=full ./Main7
// ==359== Memcheck, a memory error detector
// ==359== Command: ./Main7
// ==359== Invalid read of size 4
// ==359== Invalid free() / delete / delete[]
// ==359== HEAP SUMMARY:
// ==359== in use at exit: 8 bytes in 2 blocks
// ==359== LEAK SUMMARY:
// ==359== definitely lost: 8 bytes in 2 blocks
// But once we replace the call in test2() to use ptgi::unique(), all valgrind() error messages disappear.
//
// 130212 dpb [email protected] created
// =========================================================================================================
#include <iostream> // std::cout, std::cerr
#include <string>
#include <vector> // std::vector
#include <sstream> // std::ostringstream
#include <algorithm> // std::unique()
#include <functional> // std::equal_to(), std::binary_function()
#include <cassert> // assert() MACRO
#include "ptgi_unique.hpp" // ptgi::unique()
// Integer is small "wrapper class" around a primitive int.
// There is no SETTER, so Integer's are IMMUTABLE, just like in JAVA.
class Integer
{
private:
int num;
public:
// default CTOR: "Integer zero;"
// COMPRENSIVE CTOR: "Integer five(5);"
Integer( int num = 0 ) :
num(num)
{
}
// COPY CTOR
Integer( const Integer& rhs) :
num(rhs.num)
{
}
// assignment, operator=, needs nothing special... since all data members are primitives
// GETTER for 'num' data member
// GETTER' are *always* const
int getNum() const
{
return num;
}
// NO SETTER, because IMMUTABLE (similar to Java's Integer class)
// @return "num"
// NB: toString() should *always* be a const method
//
// NOTE: it is probably more efficient to call getNum() intead
// of toString() when printing a number:
//
// BETTER to do this:
// Integer five(5);
// std::cout << five.getNum() << "\n"
// than this:
// std::cout << five.toString() << "\n"
std::string toString() const
{
std::ostringstream oss;
oss << num;
return oss.str();
}
};
// convenience typedef's for iterating over std::vector<Integer>
typedef std::vector<Integer>::iterator IntegerVectorIterator;
typedef std::vector<Integer>::const_iterator ConstIntegerVectorIterator;
// convenience typedef's for iterating over std::vector<Integer*>
typedef std::vector<Integer*>::iterator IntegerStarVectorIterator;
typedef std::vector<Integer*>::const_iterator ConstIntegerStarVectorIterator;
// functor used for std::unique or ptgi::unique() on a std::vector<Integer>
// Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
// Hence 50..59 are equal, 60..69 are equal, etc.
struct IntegerEqualByTen: public std::equal_to<Integer>
{
bool operator() (const Integer& arg1, const Integer& arg2) const
{
return ((arg1.getNum()/10) == (arg2.getNum()/10));
}
};
// functor used for std::unique or ptgi::unique on a std::vector<Integer*>
// Two numbers equal if, when divided by 10 (integer division), the quotients are the same.
// Hence 50..59 are equal, 60..69 are equal, etc.
struct IntegerEqualByTenPointer: public std::equal_to<Integer*>
{
// NB: the Integer*& looks funny to me!
// TECHNICAL PROBLEM ELSEWHERE so had to remove the & from *&
//OUT bool operator() (const Integer*& arg1, const Integer*& arg2) const
//
bool operator() (const Integer* arg1, const Integer* arg2) const
{
return ((arg1->getNum()/10) == (arg2->getNum()/10));
}
};
void test1();
void test2();
void printIntegerStarVector( const std::string& msg, const std::vector<Integer*>& nums );
int main()
{
test1();
test2();
return 0;
}
// test1() uses a vector<Object> (namely vector<Integer>), so there is no problem with memory loss
void test1()
{
int data[] = { 10, 20, 21, 22, 30, 31, 23, 24, 11};
// turn C array into C++ vector
std::vector<Integer> nums(data, data+9);
// arg3 is a functor
IntegerVectorIterator dupPosition = ptgi::unique( nums.begin(), nums.end(), IntegerEqualByTen() );
nums.erase(dupPosition, nums.end());
nums.erase(nums.begin(), dupPosition);
}
//==================================================================================
// test2() uses a vector<Integer*>, so after ptgi:unique(), we have to be careful in
// how we eliminate the duplicate Integer objects stored in the heap.
//==================================================================================
void test2()
{
int data[] = { 10, 20, 21, 22, 30, 31, 23, 24, 11};
// turn C array into C++ vector of Integer* pointers
std::vector<Integer*> nums;
// put data[] integers into equivalent Integer* objects in HEAP
for (int inx = 0; inx < 9; ++inx)
{
nums.push_back( new Integer(data[inx]) );
}
// print the vector<Integer*> to stdout
printIntegerStarVector( "TEST2: ORIG nums before UNIQUE", nums );
// arg3 is a functor
#if 1
// corrected version which fixes SEGMENTATION FAULT and all memory leaks reported by valgrind(1)
// I THINK we want to use new C++11 cbegin() and cend(),since the equal_to predicate is passed "Integer *&"
// DID NOT COMPILE
//OUT IntegerStarVectorIterator dupPosition = ptgi::unique( const_cast<ConstIntegerStarVectorIterator>(nums.begin()), const_cast<ConstIntegerStarVectorIterator>(nums.end()), IntegerEqualByTenPointer() );
// DID NOT COMPILE when equal_to predicate declared "Integer*& arg1, Integer*& arg2"
//OUT IntegerStarVectorIterator dupPosition = ptgi::unique( const_cast<nums::const_iterator>(nums.begin()), const_cast<nums::const_iterator>(nums.end()), IntegerEqualByTenPointer() );
// okay when equal_to predicate declared "Integer* arg1, Integer* arg2"
IntegerStarVectorIterator dupPosition = ptgi::unique(nums.begin(), nums.end(), IntegerEqualByTenPointer() );
#else
// BUGGY version that causes SEGMENTATION FAULT and valgrind(1) errors
IntegerStarVectorIterator dupPosition = std::unique( nums.begin(), nums.end(), IntegerEqualByTenPointer() );
#endif
printIntegerStarVector( "TEST2: modified nums AFTER UNIQUE", nums );
int dupInx = dupPosition - nums.begin();
std::cout << "INFO: dupInx=" << dupInx <<"\n";
// delete the dup Integer* objects in the [dupPosition, end] range
for (IntegerStarVectorIterator iter = dupPosition; iter != nums.end(); ++iter)
{
delete (*iter);
}
// shrink the vector
// NB: the Integer* ptrs are NOT followed by vector::erase()
nums.erase(dupPosition, nums.end());
// print the uniques, by following the iter to the Integer* pointer
for (IntegerStarVectorIterator iter = nums.begin(); iter != nums.end(); ++iter)
{
std::cout << "TEST2: uniq = " << (*iter)->getNum() << "\n";
}
// remove the unique objects from heap
for (IntegerStarVectorIterator iter = nums.begin(); iter != nums.end(); ++iter)
{
delete (*iter);
}
// shrink the vector
nums.erase(nums.begin(), nums.end());
// the vector should now be completely empty
assert( nums.size() == 0);
}
//@ print to stdout the string: "info_msg: num1, num2, .... numN\n"
void printIntegerStarVector( const std::string& msg, const std::vector<Integer*>& nums )
{
std::cout << msg << ": ";
int inx = 0;
ConstIntegerStarVectorIterator iter;
// use const iterator and const range!
// NB: cbegin() and cend() not supported until LATER (c++11)
for (iter = nums.begin(), inx = 0; iter != nums.end(); ++iter, ++inx)
{
// output a comma seperator *AFTER* first
if (inx > 0)
std::cout << ", ";
// call Integer::toString()
std::cout << (*iter)->getNum(); // send int to stdout
// std::cout << (*iter)->toString(); // also works, but is probably slower
}
// in conclusion, add newline
std::cout << "\n";
}
I have solved it with Dov Benjamin's help like that:
<ul>
<li v-for="(n,index) in 2">{{ object.price }}</li>
</ul>
And another method, for both V1.x and 2.x of vue.js
Vue 1:
<p v-for="item in items | limitBy 10">{{ item }}</p>
Vue2:
// Via slice method in computed prop
<p v-for="item in filteredItems">{{ item }}</p>
computed: {
filteredItems: function () {
return this.items.slice(0, 10)
}
}
The classic example, Dogs and cats are animals, animals have the method makeNoise. I can iterate through an array of animals calling makeNoise on them and expect that they would do there respective implementation.
The calling code does not have to know what specific animal they are.
Thats what I think of as polymorphism.
Also you can:
IMHO a little bit hidden and cumbersome...
I came here because I wanted to see if there was a more elegant solution to this problem than using unset($arr[$i]). To my disappointment these answers are either wrong or do not cover every edge case.
Here is why array_diff() does not work. Keys are unique in the array, while elements are not always unique.
$arr = [1,2,2,3];
foreach($arr as $i => $n){
$b = array_diff($arr,[$n]);
echo "\n".json_encode($b);
}
Results...
[2,2,3]
[1,3]
[1,2,2]
If two elements are the same they will be remove. This also applies for array_search() and array_flip().
I saw a lot of answers with array_slice() and array_splice(), but these functions only work with numeric arrays. All the answers I am aware if here does not answer the question, and so here is a solution that will work.
$arr = [1,2,3];
foreach($arr as $i => $n){
$b = array_merge(array_slice($arr,0,$i),array_slice($arr,$i+1));
echo "\n".json_encode($b);
}
Results...
[2,3];
[1,3];
[1,2];
Since unset($arr[$i]) will work on both associative array and numeric arrays this still does not answer the question.
This solution is to compare the keys and with a tool that will handle both numeric and associative arrays. I use array_diff_uassoc() for this. This function compares the keys in a call back function.
$arr = [1,2,2,3];
//$arr = ['a'=>'z','b'=>'y','c'=>'x','d'=>'w'];
foreach($arr as $key => $n){
$b = array_diff_uassoc($arr, [$key=>$n], function($a,$b) {
if($a != $b){
return 1;
}
});
echo "\n".json_encode($b);
}
Results.....
[2,2,3];
[1,2,3];
[1,2,2];
['b'=>'y','c'=>'x','d'=>'w'];
['a'=>'z','c'=>'x','d'=>'w'];
['a'=>'z','b'=>'y','d'=>'w'];
['a'=>'z','b'=>'y','c'=>'x'];
Sheet.getPhysicalNumberOfRows()
does not involve some empty rows.
If you want to loop for all rows, do not use this to know the loop size.
Controller not supposed to be called from view. That's the whole idea of MVC - clear separation of concerns.
If you need to call controller from View - you are doing something wrong. Time for refactoring.
use this class inside nav tag
class="navbar navbar-expand-lg navbar-light bg-light sticky-top"
For bootstrap 4
Because you need parentheses around the value your looking for.
So here : document.querySelector('a[data-a="1"]')
If you don't know in advance the value but is looking for it via variable you can use template literals :
Say we have divs with data-price
<div data-price="99">My okay price</div>
<div data-price="100">My too expensive price</div>
We want to find an element but with the number that someone chose (so we don't know it):
// User chose 99
let chosenNumber = 99
document.querySelector(`[data-price="${chosenNumber}"`]
You'll probably have to use an external API, most of which cost money.
I did find this though, seems to be free: http://hostip.info/use.html
Visual Studio 2003 - 2008 (Visual C++ 7.1 - 9) don't claim to be C99 compatible. (Thanks to rdentato for his comment.)
Method1: Getting Current Date and Time from system datetime
The datetime module supplies classes for manipulating dates and times.
Code
from datetime import datetime,date
print("Date: "+str(date.today().year)+"-"+str(date.today().month)+"-"+str(date.today().day))
print("Year: "+str(date.today().year))
print("Month: "+str(date.today().month))
print("Day: "+str(date.today().day)+"\n")
print("Time: "+str(datetime.today().hour)+":"+str(datetime.today().minute)+":"+str(datetime.today().second))
print("Hour: "+str(datetime.today().hour))
print("Minute: "+str(datetime.today().minute))
print("Second: "+str(datetime.today().second))
print("MilliSecond: "+str(datetime.today().microsecond))
Output will be like
Date: 2020-4-18
Year: 2020
Month: 4
Day: 18
Time: 19:30:5
Hour: 19
Minute: 30
Second: 5
MilliSecond: 836071
Method2: Getting Current Date and Time if Network is available
urllib package helps us to handle the url's that means webpages. Here we collects data from the webpage http://just-the-time.appspot.com/ and parses dateime from the webpage using the package dateparser.
Code
from urllib.request import urlopen
import dateparser
time_url = urlopen(u'http://just-the-time.appspot.com/')
datetime = time_url.read().decode("utf-8", errors="ignore").split(' ')[:-1]
date = datetime[0]
time = datetime[1]
print("Date: "+str(date))
print("Year: "+str(date.split('-')[0]))
print("Month: "+str(date.split('-')[1]))
print("Day: "+str(date.split('-')[2])+'\n')
print("Time: "+str(time))
print("Hour: "+str(time.split(':')[0]))
print("Minute: "+str(time.split(':')[1]))
print("Second: "+str(time.split(':')[2]))
Output will be like
Date: 2020-04-18
Year: 2020
Month: 04
Day: 18
Time: 14:17:10
Hour: 14
Minute: 17
Second: 10
Method3: Getting Current Date and Time from Local Time of the Machine
Python's time module provides a function for getting local time from the number of seconds elapsed since the epoch called localtime(). ctime() function takes seconds passed since epoch as an argument and returns a string representing local time.
Code
from time import time, ctime
datetime = ctime(time()).split(' ')
print("Date: "+str(datetime[4])+"-"+str(datetime[1])+"-"+str(datetime[2]))
print("Year: "+str(datetime[4]))
print("Month: "+str(datetime[1]))
print("Day: "+str(datetime[2]))
print("Week Day: "+str(datetime[0])+'\n')
print("Time: "+str(datetime[3]))
print("Hour: "+str(datetime[3]).split(':')[0])
print("Minute: "+str(datetime[3]).split(':')[1])
print("Second: "+str(datetime[3]).split(':')[2])
Output will be like
Date: 2020-Apr-18
Year: 2020
Month: Apr
Day: 18
Week Day: Sat
Time: 19:30:20
Hour: 19
Minute: 30
Second: 20
You have to be a little careful with using kdiff3
as while git mergetool
can be configured to save a .orig
file during merging, the default behaviour for kdiff3
is to also save a .orig
backup file independently of git mergetool
.
You have to make sure that mergetool
backup is off:
git config --global mergetool.keepBackup false
and also that kdiff3's settings are set to not create a backup:
Configure/Options => Directory Merge => Backup Files (*.orig)
In the meantime (while you were updating your project), other commits have been made to the 'master' branch. Therefore, you must pull those changes first to be able to push your changes.
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!! Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
I'm afraid I don't think there's a shortcut to do this - if only someone would write a linq wrapper for VB6!
You could write a function that does it by looping through the array and checking each entry - I don't think you'll get cleaner than that.
There's an example article that provides some details here: http://www.vb6.us/tutorials/searching-arrays-visual-basic-6
This can now be done in Angular 5.1 using the onSameUrlNavigation
property of the Router config.
I have added a blog explaining how here but the gist of it is as follows
In your router config enable onSameUrlNavigation
option, setting it to 'reload'
. This causes the Router to fire an events cycle when you try to navigate to a route that is active already.
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
exports: [RouterModule],
})
In your route definitions, set runGuardsAndResolvers
to always
. This will tell the router to always kick off the guards and resolvers cycles, firing associated events.
export const routes: Routes = [
{
path: 'invites',
component: InviteComponent,
children: [
{
path: '',
loadChildren: './pages/invites/invites.module#InvitesModule',
},
],
canActivate: [AuthenticationGuard],
runGuardsAndResolvers: 'always',
}
]
Finally, in each component that you would like to enable reloading, you need to handle the events. This can be done by importing the router, binding onto the events and invoking an initialisation method that resets the state of your component and re-fetches data if required.
export class InviteComponent implements OnInit, OnDestroy {
navigationSubscription;
constructor(
// … your declarations here
private router: Router,
) {
// subscribe to the router events. Store the subscription so we can
// unsubscribe later.
this.navigationSubscription = this.router.events.subscribe((e: any) => {
// If it is a NavigationEnd event re-initalise the component
if (e instanceof NavigationEnd) {
this.initialiseInvites();
}
});
}
initialiseInvites() {
// Set default values and re-fetch any data you need.
}
ngOnDestroy() {
if (this.navigationSubscription) {
this.navigationSubscription.unsubscribe();
}
}
}
With all of these steps in place, you should have route reloading enabled.
EDIT : As of 2020, THIS is working. Most previous answers are outdated.
All you have to do is open your file:
Then, go into your web inspector (for Chrome, Cmd-Shift-I
or Ctrl-Shift-I
depending on your OS) and get the link. Paste that link into your browser and it will redirect to another link. Copy the new URL. Done!
It seems that if you use the first link, it can only be accessed when signed in to your Google account. Not very helpful for other people. The second, redirected link, however, does not need you to be signed in. That's the rationale behind it.
I deleted the original file shown in the images, but I have another working example here.
I've actually checked back on my example link that I posted in my edit about a week ago, but it no longer seems to be working. I guess these links only work temporarily, so don't use them for any kind of production environment.
You may want to use WildcardPattern
from System.Management.Automation
assembly. See my answer here.
The best is QSpinBox
.
And for a double value use QDoubleSpinBox
.
QSpinBox myInt;
myInt.setMinimum(-5);
myInt.setMaximum(5);
myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
myInt.setValue(2);// Default/begining value
myInt.value();// Get the current value
//connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));
The logarithm is your friend:
int n = 1000;
int length = (int)(Math.log10(n)+1);
NB: only valid for n > 0.
in normal time, checkboxes return an on/off value.
you can verify it with this code:
<form action method="POST">
<input type="checkbox" name="hello"/>
</form>
<?php
if(isset($_POST['hello'])) echo('<p>'.$_POST['hello'].'</p>');
?>
this will return
<p>off</p>
or
<p>on</p>
You want style image and Nav with float to each other then use like this
ol.widgets ul
{
list-style-image:url('some-img.gif');
}
ol.widgets ul li
{
float:left;
}
Like this:
import operator
l = [...]
sorted_list = sorted(l, key=operator.itemgetter(desired_item_index))
Try this :
var htmlEntities = "<script>alert('hello');</script>";_x000D_
var htmlDecode =$.parseHTML(htmlEntities)[0]['wholeText'];_x000D_
console.log(htmlDecode);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
parseHTML is a Function in Jquery library and it will return an array that includes some details about the given String..
in some cases the String is being big, so the function will separate the content to many indexes..
and to get all the indexes data you should go to any index, then access to the index called "wholeText".
I chose index 0 because it's will work in all cases (small String or big string).
If you are using sass you can simply set below mentioned variables to use icons provided by other fonts,
$slick-font-family:FontAwesome;
$slick-prev-character: "\f053";
$slick-next-character: "\f054";
These will change the font family used by slick's theme css and also the unicode for prev and next button. This example will use FontAwesome's chevron-left and chevron-right icons.
Other sass variables which can be configured are given in Slick Github page
As I recognize, at the moment, in JUnit, the syntax is like this:
AssertTrue(Long.parseLong(previousTokenValues[1]) > Long.parseLong(currentTokenValues[1]), "your fail message ");
Means that, the condition is in front of the message.
The -e and -t parameter does not work together. i tried some expressions and the result was the following code snippet :
QMESSAGE="SHOULD I DO YES OR NO"
YMESSAGE="I DO"
NMESSAGE="I DO NOT"
FMESSAGE="PLEASE ENTER Y or N"
COUNTDOWN=2
DEFAULTVALUE=n
#----------------------------------------------------------------#
function REQUEST ()
{
read -n1 -t$COUNTDOWN -p "$QMESSAGE ? Y/N " INPUT
INPUT=${INPUT:-$DEFAULTVALUE}
if [ "$INPUT" = "y" -o "$INPUT" = "Y" ] ;then
echo -e "\n$YMESSAGE\n"
#COMMANDEXECUTION
elif [ "$INPUT" = "n" -o "$INPUT" = "N" ] ;then
echo -e "\n$NMESSAGE\n"
#COMMANDEXECUTION
else
echo -e "\n$FMESSAGE\n"
REQUEST
fi
}
REQUEST
Regex.Replace
does not modify its first argument (recall that strings are immutable in .NET) so the call
Regex.Replace(LastName, @"\s+", "");
leaves the LastName
string unchanged. You need to call it like this:
LastName = Regex.Replace(LastName, @"\s+", "");
All three of your regular expressions would have worked. However, the first regex would remove all plus characters as well, which I imagine would be unintentional.
You will find the siblings() and parent() methods useful here.
// assuming A1 is clicked
$('div a').click(function(e) {
$(this); // A1
$(this).parent(); // the div containing A1
$(this).siblings(); // A2 and A3
});
Combining those methods with andSelf() will let you manipulate any combination of those elements you want.
Edit: The comment left by Mark regarding event delegation on Shog9's answer is a very good one. The easiest way to accomplish this in jQuery would be by using the live() method.
// assuming A1 is clicked
$('div a').live('click', function(e) {
$(this); // A1
$(this).parent(); // the div containing A1
$(this).siblings(); // A2 and A3
});
I think it actually binds the event to the root element, but the effect is that same. Not only is it more flexible, it also improves performance in a lot of cases. Just be sure to read the documentation to avoid any gotchas.
In bootstrap 4, they have designed a bigger input file.
A simple solution to increase the size input file is to use font-size
:
Add you style, for example:
input[type="file"] {
font-size:35px
}
Otherwise, you can make one custom class and add to input control.
To answer TJJ: But is it also possible to do this without copying the whole file? So, just to somehow create an additional vmdk-metafile, that references the raw dd-image.
Yes, it's possible. Here's how to use a flat disk image in VirtualBox:
First you create an image with dd in the usual way:
dd bs=512 count=60000 if=/dev/zero of=usbdrv.img
Then you can create a file for VirtualBox that references this image:
VBoxManage internalcommands createrawvmdk -filename "usbdrv.vmdk" -rawdisk "usbdrv.img"
You can use this image in VirtualBox as is, but depending on the guest OS it might not be visible immediately. For example, I experimented on using this method with a Windows guest OS and I had to do the following to give it a drive letter:
You might want to access your files on Linux. First dismount it from the guest OS to be sure and remove it from the virtual machine. Now we need to create a virtual device that references the partition.
sfdisk -d usbdrv.img
Response:
label: dos
label-id: 0xd367a714
device: usbdrv.img
unit: sectors
usbdrv.img1 : start= 63, size= 48132, type=4
Take note of the start position of the partition: 63. In the command below I used loop4 because it was the first available loop device in my case.
sudo losetup -o $((63*512)) loop4 usbdrv.img
mkdir usbdrv
sudo mount /dev/loop4 usbdrv
ls usbdrv -l
Response:
total 0
-rwxr-xr-x. 1 root root 0 Apr 5 17:13 'Test file.txt'
Yay!
Try "vash" - asp.net mvc like razor syntax for node.js
https://github.com/kirbysayshi/Vash
also checkout: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
// sample
var tmpl = vash.compile('<hr/>@model.a,@model.b<hr/>');
var html = tmpl({"a": "hello", "b": "world"});
res.write(html);
CREATE FUNCTION dbo.ConvertUnixToDateTime(@Datetime BIGINT)
RETURNS DATETIME
AS
BEGIN
RETURN (SELECT DATEADD(second,@Datetime, CAST('1970-01-01' AS datetime)))
END;
GO
If you don't want to show controls then try this code
<audio autoplay>
<source src="song.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
You could also use Regular Expressions:
SELECT * FROM TABLE WHERE REGEXP_LIKE (TABLE.NAME,'IgNoReCaSe','i');
For Linux let me introduce a shell script that will show the mac address and allows to change it (MAC sniffing).
ifconfig eth0 | grep HWaddr |cut -dH -f2|cut -d\ -f2
00:26:6c:df:c3:95
Cut arguements may dffer (I am not an expert) try:
ifconfig etho | grep HWaddr
eth0 Link encap:Ethernet HWaddr 00:26:6c:df:c3:95
To change MAC we may do:
ifconfig eth0 down
ifconfig eth0 hw ether 00:80:48:BA:d1:30
ifconfig eth0 up
will change mac address to 00:80:48:BA:d1:30 (temporarily, will restore to actual one upon reboot).
This is actually really easy:
@article = user.articles.build(:title => "MainTitle")
@article.save
Just pass the list to np.array
:
a = np.array(a)
You can also take this opportunity to set the dtype
if the default is not what you desire.
a = np.array(a, dtype=...)
Linking to local resources is disabled in all modern browsers due to security restrictions.
For Firefox:
For security purposes, Mozilla applications block links to local files (and directories) from remote files. This includes linking to files on your hard drive, on mapped network drives, and accessible via Uniform Naming Convention (UNC) paths. This prevents a number of unpleasant possibilities, including:
- Allowing sites to detect your operating system by checking default installation paths
- Allowing sites to exploit system vulnerabilities (e.g., C:\con\con in Windows 95/98)
- Allowing sites to detect browser preferences or read sensitive data
for IE:
Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.
for Opera (in the context of a security advisory, I'm sure there is a more canonical link for this):
As a security precaution, Opera does not allow Web pages to link to files on the user's local disk
If you want to generate your email bodies in razor, you can use Mailzory. Also, you can download the nuget package from here.
// template path
var viewPath = Path.Combine("Views/Emails", "hello.cshtml");
// read the content of template and pass it to the Email constructor
var template = File.ReadAllText(viewPath);
var email = new Email(template);
// set ViewBag properties
email.ViewBag.Name = "Johnny";
email.ViewBag.Content = "Mailzory Is Funny";
// send email
var task = email.SendAsync("[email protected]", "subject");
task.Wait()
<kdb></kdb>
is required when we have a space in Alias Name like
SELECT employee_id,department_id AS "Department ID"
FROM employees
order by department
In CurrentGame
component you need to change initial state because you are trying use loop for participants
but this property is undefined
that's why you get error.,
getInitialState: function(){
return {
data: {
participants: []
}
};
},
also, as player
in .map
is Object
you should get properties from it
this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
// -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})
You have to check if the argument is undefined:
function func(a, b) {
if (a === undefined) a = "default value";
if (b === undefined) b = "default value";
}
Try the following, no extra headers
wget -qO- www.google.com
Note the trailing -
. This is part of the normal command argument for -O
to cat out to a file, but since we don't use >
to direct to a file, it goes out to the shell. You can use -qO-
or -qO -
.
You can also do like this:
template <typename T>
class make_vector {
public:
typedef make_vector<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
And use it like this:
std::vector<int> v = make_vector<int>() << 1 << 2 << 3;
I have used jQuery AJAX to make AJAX requests.
Check the following code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#call').click(function ()
{
$.ajax({
type: "post",
url: "testme", //this is my servlet
data: "input=" +$('#ip').val()+"&output="+$('#op').val(),
success: function(msg){
$('#output').append(msg);
}
});
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
input:<input id="ip" type="text" name="" value="" /><br></br>
output:<input id="op" type="text" name="" value="" /><br></br>
<input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
<div id="output"></div>
</body>
Use like below:
yourFunc(input: any):Observable<string> {
var requestHeader = { headers: new HttpHeaders({ 'Content-Type': 'text/plain', 'No-Auth': 'False' })};
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post<string>(this.yourBaseApi+ '/do-api', input, { headers, responseType: 'text' as 'json' });
}
Here's how to do this:
(type file1.txt && more +1 file2.txt) > out.txt
I had the same problem with venv in PyCharm. But It is not big problem! Just do:
kinda dumb, but I had a weird character (é) in my password. After omitting it, I no longer got the error.
use
startDate: '-0d'
Like
$("#datepicker").datepicker({
startDate: '-0d',
changeMonth: true
});
Encryption and hash algorithms work in similar ways. In each case, there is a need to create confusion and diffusion amongst the bits. Boiled down, confusion is creating a complex relationship between the key and the ciphertext, and diffusion is spreading the information of each bit around.
Many hash functions actually use encryption algorithms (or primitives of encryption algorithms. For example, the SHA-3 candidate Skein uses Threefish as the underlying method to process each block. The difference is that instead of keeping each block of ciphertext, they are destructively, deterministically merged together to a fixed length
gcc has a so-called "case range" extension:
http://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Case-Ranges.html#Case-Ranges
I used to use this when I was only using gcc. Not much to say about it really -- it does sort of what you want, though only for ranges of values.
The biggest problem with this is that only gcc supports it; this may or may not be a problem for you.
(I suspect that for your example an if
statement would be a more natural fit.)
Here you go. This solution uses a DataInputStream
to scan for the position of the string you want replaced and uses a FileChannel
to replace the text at that exact position. It only replaces the first occurrence of the string that it finds. This solution doesn't store a copy of the entire file somewhere, (either the RAM or a temp file), it just edits the portion of the file that it finds.
public static long scanForString(String text, File file) throws IOException {
if (text.isEmpty())
return file.exists() ? 0 : -1;
// First of all, get a byte array off of this string:
byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);
// Next, search the file for the byte array.
try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
List<Integer> matches = new LinkedList<>();
for (long pos = 0; pos < file.length(); pos++) {
byte bite = dis.readByte();
for (int i = 0; i < matches.size(); i++) {
Integer m = matches.get(i);
if (bytes[m] != bite)
matches.remove(i--);
else if (++m == bytes.length)
return pos - m + 1;
else
matches.set(i, m);
}
if (bytes[0] == bite)
matches.add(1);
}
}
return -1;
}
public static void replaceText(String text, String replacement, File file) throws IOException {
// Open a FileChannel with writing ability. You don't really need the read
// ability for this specific case, but there it is in case you need it for
// something else.
try (FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ)) {
long scanForString = scanForString(text, file);
if (scanForString == -1) {
System.out.println("String not found.");
return;
}
channel.position(scanForString);
channel.write(ByteBuffer.wrap(replacement.getBytes(/* StandardCharsets.your_charset */)));
}
}
Input: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Method Call:
replaceText("QRS", "000", new File("path/to/file");
Resulting File: ABCDEFGHIJKLMNOP000TUVWXYZ
You can try:
df[0] = df[0].str.strip()
or more specifically for all string columns
non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())
Here is my suggested validation:
var isValid = false;
// Check whether this entered value is numeric.
function checkNumeric() {
var numericVal = document.getElementById("txt_numeric").value;
if(isNaN(numericVal) || numericVal == "" || numericVal == null || numericVal.indexOf(' ') >= 0) {
alert("Please, enter a numeric value!");
isValid = false;
} else {
isValid = true;
}
}
@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU
system, they can do this:
tar cvf - folderToCompress | gzip > compressFileName
To expand the archive:
zcat compressFileName | tar xvf -
The other answers here are very much correct, and valuable. But sometimes you just want simple: to get a plain old parsed value at directive instantiation, without needing updates, and without messing with isolate scope. For instance, it can be handy to provide a declarative payload into your directive as an array or hash-object in the form:
my-directive-name="['string1', 'string2']"
In that case, you can cut to the chase and just use a nice basic angular.$eval(attr.attrName)
.
element.val("value = "+angular.$eval(attr.value));
Working Fiddle.
c_str() converts a C++ string into a C-style string which is essentially a null terminated array of bytes. You use it when you want to pass a C++ string into a function that expects a C-style string (e.g. a lot of the Win32 API, POSIX style functions, etc).
from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))
You can run loop for each column but this is the simplest way to convert string column into integer.
@John, Earlz and Nathan. The way I learned it at uni is: functions return values, methods don't. In some languages the syntax is/was actually different. Example (no specific language):
Method SetY(int y) ...
Function CalculateY(int x) As Integer ...
Most languages now use the same syntax for both versions, using void as a return type to say there actually isn't a return type. I assume it's because the syntax is more consistent and easier to change from method to function, and vice versa.
just for modifying certain property from object collection you could directly use forEach with a collection as follows
collection.forEach(c -> c.setXyz(c.getXyz + "a"))
You also can use graceful restart the apache server with service apache2 reload
or apachectl -k graceful
.
As the apache doc says:
The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.
You can try U2U Query Builder http://www.u2u.net/res/Tools/CamlQueryBuilder.aspx you can use their API U2U.SharePoint.CAML.Server.dll and U2U.SharePoint.CAML.Client.dll
I didn't use them but I'm sure it will help you achieving your task.
Actually, the built-in function is named master.dbo.fn_varbintohexstr.
So, for example:
SELECT 100, master.dbo.fn_varbintohexstr(100)
Gives you
100 0x00000064
What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.
Perhaps you could use something like this?
package com.example;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Serializer {
public static byte[] serialize(Object obj) throws IOException {
try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
try(ObjectOutputStream o = new ObjectOutputStream(b)){
o.writeObject(obj);
}
return b.toByteArray();
}
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
try(ObjectInputStream o = new ObjectInputStream(b)){
return o.readObject();
}
}
}
}
There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.
Note that "Only objects that support the java.io.Serializable
interface can be written to streams" (see java.io.ObjectOutputStream
).
Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream
might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.
For serialization of objects that do not implement the Serializable
interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream
and the get*/put* methods of java.nio.ByteBuffer
perhaps together with reflection, or pull in a third party dependency.
This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.
Both
-Djavax.net.ssl.trustStore=path/to/trustStore.jks
and
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore
in javax.net.ssl.trustStore.
My solution is quite simple.
In my login window. the xaml is like this.
<DockPanel HorizontalAlignment="Center" VerticalAlignment="Center" Height="80" Width="300" LastChildFill="True">
<Button Margin="5,0,0,0" Click="login_Click" DockPanel.Dock="Right" VerticalAlignment="Center" ToolTip="Login to system">
Login
</Button>
<StackPanel>
<TextBox x:Name="userNameWatermarked" Height="25" Foreground="Gray" Text="UserName" GotFocus="userNameWatermarked_GotFocus"></TextBox>
<TextBox x:Name="userName" Height="25" TextChanged="loginElement_TextChanged" Visibility="Collapsed" LostFocus="userName_LostFocus" ></TextBox>
<TextBox x:Name="passwordWatermarked" Height="25" Foreground="Gray" Text="Password" Margin="0,5,0,5" GotFocus="passwordWatermarked_GotFocus"></TextBox>
<PasswordBox x:Name="password" Height="25" PasswordChanged="password_PasswordChanged" KeyUp="password_KeyUp" LostFocus="password_LostFocus" Margin="0,5,0,5" Visibility="Collapsed"></PasswordBox>
<TextBlock x:Name="loginError" Visibility="Hidden" Foreground="Red" FontSize="12"></TextBlock>
</StackPanel>
</DockPanel>
the code is like this.
private void userNameWatermarked_GotFocus(object sender, RoutedEventArgs e)
{
userNameWatermarked.Visibility = System.Windows.Visibility.Collapsed;
userName.Visibility = System.Windows.Visibility.Visible;
userName.Focus();
}
private void userName_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(this.userName.Text))
{
userName.Visibility = System.Windows.Visibility.Collapsed;
userNameWatermarked.Visibility = System.Windows.Visibility.Visible;
}
}
private void passwordWatermarked_GotFocus(object sender, RoutedEventArgs e)
{
passwordWatermarked.Visibility = System.Windows.Visibility.Collapsed;
password.Visibility = System.Windows.Visibility.Visible;
password.Focus();
}
private void password_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(this.password.Password))
{
password.Visibility = System.Windows.Visibility.Collapsed;
passwordWatermarked.Visibility = System.Windows.Visibility.Visible;
}
}
Just decide to hide or show the watermark textbox is enough. Though not beautiful,but work well.
Super Duper Old I know but I would add my piece on using Linq and continuation lambdas on methods with using C# 7. I try to use named tuples as replacements for DTOs and anonymous projections when reused in a class. Yes for mocking and testing you still need classes but doing things inline and passing around in a class is nice to have this newer option IMHO. You can instantiate them from
- Direct Instantiation
var items = new List<(int Id, string Name)> { (1, "Me"), (2, "You")};
- Off of an existing collection, and now you can return well typed tuples similar to how anonymous projections used to be done.
public class Hold
{
public int Id { get; set; }
public string Name { get; set; }
}
//In some method or main console app:
var holds = new List<Hold> { new Hold { Id = 1, Name = "Me" }, new Hold { Id = 2, Name = "You" } };
var anonymousProjections = holds.Select(x => new { SomeNewId = x.Id, SomeNewName = x.Name });
var namedTuples = holds.Select(x => (TupleId: x.Id, TupleName: x.Name));
- Reuse the tuples later with grouping methods or use a method to construct them inline in other logic:
//Assuming holder class above making 'holds' object
public (int Id, string Name) ReturnNamedTuple(int id, string name) => (id, name);
public static List<(int Id, string Name)> ReturnNamedTuplesFromHolder(List<Hold> holds) => holds.Select(x => (x.Id, x.Name)).ToList();
public static void DoSomethingWithNamedTuplesInput(List<(int id, string name)> inputs) => inputs.ForEach(x => Console.WriteLine($"Doing work with {x.id} for {x.name}"));
var namedTuples2 = holds.Select(x => ReturnNamedTuple(x.Id, x.Name));
var namedTuples3 = ReturnNamedTuplesFromHolder(holds);
DoSomethingWithNamedTuplesInput(namedTuples.ToList());
Use this line of codes inside the Column.
For wrap_content : mainAxisSize: MainAxisSize.min
For match_parent : mainAxisSize: MainAxisSize.max
To view the file, run:
xxd filename | less
To use Vim as a hex editor:
:%!xxd
(transform buffer to hex):%!xxd -r
(reverse transformation)we can disable using this technique.
<select class="form-control" name="option_select">
<option selected="true" disabled="disabled">Select option </option>
<option value="Option A">Option A</option>
<option value="Option B">Option B</option>
<option value="Option C">Option C</option>
</select>
If this didn't work:
<ImageView
android:layout_gravity="center_horizontal"
android:paddingTop="10px"
android:paddingBottom="5px"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:src="@android:drawable/divider_horizontal_bright" />
Try this raw View:
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#000000" />
All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static
and I used the same STATIC_URL in my dev settings.py file.
This causes a silent failure in django/conf/urls/static.py.
The test elif not settings.DEBUG or '://' in prefix:
picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.
It would be thoughtful if Django spit out an error message stating you can't use a http(s)://
with DEBUG = True
I had to change STATIC_URL to be '/static/'
>>>import json
>>>json_string = json.dumps("??? ????")
>>>json_string.encode('ascii').decode('unicode-escape')
'"??? ????"'
>>>s = '? ?a? ???'
>>>print('unicode: ' + s.encode('unicode-escape').decode('utf-8'))
unicode: \u6f22 \u03c7\u03b1\u03bd \u0445\u0430\u043d
>>>u = s.encode('unicode-escape').decode('utf-8')
>>>print('original: ' + u.encode("utf-8").decode('unicode-escape'))
original: ? ?a? ???
original resource:https://blog.csdn.net/chuatony/article/details/72628868
This link contains a good checklist why core dumps are not generated:
exit()
instead of using the core dump handler.Adding the all
remote gets a bit tedious as you have to setup on each machine that you use.
Also, the bash
and git
aliases provided all assume that you have will push to all remotes.
(Ex: I have a fork of sshag
that I maintain on GitHub and GitLab. I have the upstream remote added, but I don't have permission to push to it.)
Here is a git
alias that only pushes to remotes with a push URL that includes @
.
psall = "!f() { \
for R in $(git remote -v | awk '/@.*push/ { print $1 }'); do \
git push $R $1; \
done \
}; f"
This problems occurs because you have the same project in some other project folder.As in eclipse we have many project folder, So if you have a project in one folder and you want to import it in other project folder, then this problem occurs. So first of all DELETE the project from other folder and then import in into your current one project FOLDER.
If you are not giving export default then it throws an error. check if you have given module.exports = Speaker; //spelling mistake here you have written exoprts and check in all the modules whether you have exported correct.
Following up on David W's answer from Oct '13, if using expr
this might be better
test_var=`expr $am_i_numeric \* 0` >/dev/null 2>&1
if [ "$test_var" = "" ]
then
......
If numeric, multiplied by 1 gives you the same value, (including negative numbers). Otherwise you get null
which you can test for
After a full day working on this feature finally able to get the right answer.
First, create the following classes:
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by hoshyar on 1/19/17.
*/
public class SwipeDetector implements View.OnTouchListener {
public static enum Action {
LR, // Left to Right
RL, // Right to Left
TB, // Top to bottom
BT, // Bottom to Top
None // when no action was detected
}
private static final String logTag = "Swipe";
private static final int MIN_DISTANCE = 100;
private float downX, downY, upX, upY;
private Action mSwipeDetected = Action.None;
public boolean swipeDetected() {
return mSwipeDetected != Action.None;
}
public Action getAction() {
return mSwipeDetected;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = event.getX();
downY = event.getY();
mSwipeDetected = Action.None;
return false;
case MotionEvent.ACTION_MOVE:
upX = event.getX();
upY = event.getY();
float deltaX = downX - upX;
float deltaY = downY - upY;
Log.i(logTag,String.valueOf(deltaX));
Log.i(logTag,String.valueOf(deltaX));
if (deltaY>0 && deltaY<10 && deltaX<0 || deltaY==0 && deltaX>-15 && deltaX<0){
Log.i(logTag,"to right");
}if (deltaY>=0 && deltaY<10 && deltaX>0 || deltaY<0 && deltaX>15 && deltaX<40){
Log.i(logTag,"to left");
}
if (Math.abs(deltaX) > MIN_DISTANCE) {
// left or right
if (deltaX < 0) {
mSwipeDetected = Action.LR;
return false;
}
if (deltaX > 0) {
mSwipeDetected = Action.RL;
return false;
}
} else if (Math.abs(deltaY) > MIN_DISTANCE) {
if (deltaY < 0) {
Log.i(logTag,"to bottom");
mSwipeDetected = Action.TB;
return false;
}
if (deltaY > 0) {
Log.i(logTag,"to up");
mSwipeDetected = Action.BT;
return false;
}
}
return true;
}
return false;
}
}
Finally on the object that you want to apply. My example:
SwipeDetector swipeDetector = new SwipeDetector();
listView.setOnTouchListener(swipeDetector);
Good luck .
Check out java.io.ByteArrayInputStream
It is possible by dumping, editing and reimporting the table.
This script will do it for you (Adapt the values at the start of the script to your needs):
#!/bin/bash
DB=/tmp/synapse/homeserver.db
TABLE="public_room_list_stream"
FIELD=visibility
OLD="BOOLEAN NOT NULL"
NEW="INTEGER NOT NULL"
TMP=/tmp/sqlite_$TABLE.sql
echo "### create dump"
echo ".dump '$TABLE'" | sqlite3 "$DB" >$TMP
echo "### editing the create statement"
sed -i "s|$FIELD $OLD|$FIELD $NEW|g" $TMP
read -rsp $'Press any key to continue deleting and recreating the table $TABLE ...\n' -n1 key
echo "### rename the original to '$TABLE"_backup"'"
sqlite3 "$DB" "PRAGMA busy_timeout=20000; ALTER TABLE '$TABLE' RENAME TO '$TABLE"_backup"'"
echo "### delete the old indexes"
for idx in $(echo "SELECT name FROM sqlite_master WHERE type == 'index' AND tbl_name LIKE '$TABLE""%';" | sqlite3 $DB); do
echo "DROP INDEX '$idx';" | sqlite3 $DB
done
echo "### reinserting the edited table"
cat $TMP | sqlite3 $DB
SELECT column1 FROM table WHERE column1 not like '%[0-9]%'
Removing the '^' did it for me. I'm looking at a varchar field and when I included the ^ it excluded all of my non-numerics which is exactly what I didn't want. So, by removing ^ I only got non-numeric values back.
As an alternative option you could install OpenSSH http://www.mls-software.com/opensshd.html and then simply ssh user@host -pw password -m command_run
Edit: After a response from user2687375 when installing, select client only. Once this is done you should be able to initiate SSH from command.
Then you can create an ssh batch script such as
ECHO OFF
CLS
:MENU
ECHO.
ECHO ........................
ECHO SSH servers
ECHO ........................
ECHO.
ECHO 1 - Web Server 1
ECHO 2 - Web Server 2
ECHO E - EXIT
ECHO.
SET /P M=Type 1 - 2 then press ENTER:
IF %M%==1 GOTO WEB1
IF %M%==2 GOTO WEB2
IF %M%==E GOTO EOF
REM ------------------------------
REM SSH Server details
REM ------------------------------
:WEB1
CLS
call ssh [email protected]
cmd /k
:WEB2
CLS
call ssh [email protected]
cmd /k
I liked to answer this question.
Their are many places where we have css & javascript files, like in css folder which is outside the protected folder, css & js files of extension & widgets which we need to include externally sometime when use ajax a lot, js & css files of core framework which also we need to include externally sometime. So their are some ways to do this.
Include core js files of framework like jquery.js, jquery.ui.js
<?php
Yii::app()->clientScript->registerCoreScript('jquery');
Yii::app()->clientScript->registerCoreScript('jquery.ui');
?>
Include files from css folder outside of protected folder.
<?php
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/example.css');
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/css/example.js');
?>
Include css & js files from extension or widgets.
Here fancybox is an extension which is placed under protected folder. Files we including has path : /protected/extensions/fancybox/assets/
<?php
// Fancybox stuff.
$assetUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.fancybox.assets'));
Yii::app()->clientScript->registerScriptFile($assetUrl.'/jquery.fancybox-1.3.4.pack.js');
Yii::app()->clientScript->registerScriptFile($assetUrl.'/jquery.mousewheel-3.0.4.pack.js');
?>
Also we can include core framework files: Example : I am including CListView js file.
<?php
$baseScriptUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets'));
Yii::app()->clientScript->registerScriptFile($baseScriptUrl.'/listview/jquery.yiilistview.js',CClientScript::POS_END);
?>
For more detail Look at my blog article
If other solutions doesn't work for you, just try (as root) this:
amportal restart
Hope it helps ;-)
Bozo sort is a related algorithm that checks if the list is sorted and, if not, swaps two items at random. It has the same best and worst case performances, but I would intuitively expect the average case to be longer than Bogosort. It's hard to find (or produce) any data on performance of this algorithm.
To modify the value in a cell at the intersection of row "r" (in column "A") and column "C"
retrieve the index of the row "r" in column "A"
i = df[ df['A']=='r' ].index.values[0]
modify the value in the desired column "C"
df.loc[i,"C"]="newValue"
Note: before, be sure to reset the index of rows ...to have a nice index list!
df=df.reset_index(drop=True)