Select a Random sample from a tibble type in R:
library("tibble")
a <- your_tibble[sample(1:nrow(your_tibble), 150),]
nrow takes a tibble and returns the number of rows. The first parameter passed to sample
is a range from 1 to the end of your tibble. The second parameter passed to sample, 150, is how many random samplings you want. The square bracket slicing specifies the rows of the indices returned. Variable 'a' gets the value of the random sampling.
You may like to first create a dialogue by right clicking the project in solution explorer and in the code file type
dialogue1.show()
that's all !!!
Although it is safe to declare a static ObjectMapper in terms of thread safety, you should be aware that constructing static Object variables in Java is considered bad practice. For more details, see Why are static variables considered evil? (and if you'd like, my answer)
In short, statics should be avoided because the make it difficult to write concise unit tests. For example, with a static final ObjectMapper, you can't swap out the JSON serialization for dummy code or a no-op.
In addition, a static final prevents you from ever reconfiguring ObjectMapper at runtime. You might not envision a reason for that now, but if you lock yourself into a static final pattern, nothing short of tearing down the classloader will let you re-initialize it.
In the case of ObjectMapper its fine, but in general it is bad practice and there is no advantage over using a singleton pattern or inversion-of-control to manage your long-lived objects.
Actually i tried many combinations nothing worked
but when i modified my application gradle file with following
buildTypes {
release {
minifyEnabled false
}
}
By removing the Line
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
it worked Normally :)) cheers
There are two issues I encountered with the other suggestions
The alternative that doesn't suffer from these issues is to use GetDiskFreeSpaceEx with a UNC path:
function getDiskSpaceInfoUNC($p_UNCpath, $p_unit = 1tb, $p_format = '{0:N1}')
{
# unit, one of --> 1kb, 1mb, 1gb, 1tb, 1pb
$l_typeDefinition = @'
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out ulong lpFreeBytesAvailable,
out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes);
'@
$l_type = Add-Type -MemberDefinition $l_typeDefinition -Name Win32Utils -Namespace GetDiskFreeSpaceEx -PassThru
$freeBytesAvailable = New-Object System.UInt64 # differs from totalNumberOfFreeBytes when per-user disk quotas are in place
$totalNumberOfBytes = New-Object System.UInt64
$totalNumberOfFreeBytes = New-Object System.UInt64
$l_result = $l_type::GetDiskFreeSpaceEx($p_UNCpath,([ref]$freeBytesAvailable),([ref]$totalNumberOfBytes),([ref]$totalNumberOfFreeBytes))
$totalBytes = if($l_result) { $totalNumberOfBytes /$p_unit } else { '' }
$totalFreeBytes = if($l_result) { $totalNumberOfFreeBytes/$p_unit } else { '' }
New-Object PSObject -Property @{
Success = $l_result
Path = $p_UNCpath
Total = $p_format -f $totalBytes
Free = $p_format -f $totalFreeBytes
}
}
i like this clever syntax to do async work from an entrypoint
void async function main() {
await doSomeWork()
await doMoreWork()
}()
Use:
var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
new RFCValidation(),
new DNSCheckValidation()
]);
$validator->isValid("[email protected]", $multipleValidations); //true
Everyone will have slightly different definitions, and there are often grey areas. However:
Well, you need to first get a good book on C and understand the language.
FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);
Process is to clean up and then reinstall with the following commands:
rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install )"
Notes:
curl | bash (or ruby)
commands before running themInstead of relying only on <c:out />
, an antixss library should also be used, which will not only encode but also sanitize malicious script in input. One of the best library available is OWASP Antisamy, it's highly flexible and can be configured(using xml policy files) as per requirement.
For e.g. if an application supports only text input then most generic policy file provided by OWASP can be used which sanitizes and removes most of the html tags. Similarly if application support html editors(such as tinymce) which need all kind of html tags, a more flexible policy can be use such as ebay policy file
android:focusableInTouchMode="true"
android:focusable="true"
android:clickable="true"
Add them to your ViewGroup that includes your EditTextView. It works properly to my Constraint Layout. Hope this help
Notice that in the version of 1.2.0 the viewMode
has changed to startView
.
eg:
$('#sandbox-container input').datepicker({
startView: 1,
minViewMode: 1
});
I have already replied to this question in an answer to Stack Overflow question Trouble using Google sign-in button in emulator. It only works for Android 4.2.2, but lets you use the "Intel Atom (x86)" in AVD.
I think that it is easy to make it work for other versions of Android. Just find the correct files.
Just thought I'd something that might help you in the future. To search multiple string and output line numbers and browse thru the output, type:
egrep -ne 'null|three'
will show:
2:example two null,
3:example three,
4:example four null,
egrep -ne 'null|three' | less
will display output in a less session
HTH Jun
To automate this, you can use any script or app that can send a string to a socket. I personally like nc (netcat) under cygwin. As I said before, I use it like this:
$ echo kill | nc -w 2 localhost 5554
(that means to send "kill" string to the port 5554 on localhost, and terminate netcat after 2 seconds.)
So after running brew install mcrypt php
, I had to install php-mcrypt via pecl:
pecl install mcrypt-1.0.1
At the time of writing, mcrypt does not have a stable pecl release, 1.0.1 being the current release for php 7.2 and 7.3, and brew install php
will install php 7.2.
As per bootstrap 3.0 documentation. there is no rounded corners class or id for div tag.
you can use circle behavior for image by using
<img class="img-circle">
or just use custom border-radius
css3 property in css
for only bottom rounded coner use following
border-bottom-left-radius:25%; // i use percentage u can use pix.
border-bottom-right-radius:25%;// i use percentage u can use pix.
if you want responsive circular div then try this
referred from Responsive CSS Circles
In the interest of actually putting a working solution to this question:
SELECT ... WHERE `myDateColumn` >= DATE(DATE_FORMAT(NOW(),'%Y-%m-%d'));
Obviously, you could change the NOW() function to any date or variable you want.
Use this script instead:
@taskkill/f /im test.exe >nul 2>&1
@pause
What the 2>&1
part actually does, is that it redirects the stderr
output to stdout
. I will explain it better below:
Kill the task "test.exe". Redirect stderr
to stdout
. Then, redirect stdout
to nul
.
Show the pause message Press any key to continue . . .
until someone presses a key.
NOTE: The @
symbol is hiding the prompt for each command. You can save up to 8 bytes this way.
The shortest version of your script could be:
@taskkill/f /im test.exe >nul 2>&1&pause
The &
character is used for redirection the first time, and for separating the commands the second time.
An @
character is not needed twice in a line. This code is just 40 bytes, despite the one you've posted being 49 bytes! I actually saved 9 bytes. For a cleaner code look above.
I think that without using -exec
you can simply provide /dev/null
as at least one argument in case nothing is found:
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null
Place your scripts in this order:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
You can use hidden frame, load the file in there and parse its contents.
HTML:
<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>
JavaScript:
<script type="text/javascript">
function LoadFile() {
var oFrame = document.getElementById("frmFile");
var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
while (strRawContents.indexOf("\r") >= 0)
strRawContents = strRawContents.replace("\r", "");
var arrLines = strRawContents.split("\n");
alert("File " + oFrame.src + " has " + arrLines.length + " lines");
for (var i = 0; i < arrLines.length; i++) {
var curLine = arrLines[i];
alert("Line #" + (i + 1) + " is: '" + curLine + "'");
}
}
</script>
Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-files flag. credit.
$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest
why don't you store your values in HTML5 storage objects such as sessionStorage
or localStorage
, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.
To store values for a session:
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')
or more permanently:
localStorage.getItem('label')
localStorage.setItem('label', 'value')
So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..
I was looking for an answer on what |=
does in Groovy and although answers above are right on they did not help me understand a particular piece of code I was looking at.
In particular, when applied to a boolean variable "|=" will set it to TRUE the first time it encounters a truthy expression on the right side and will HOLD its TRUE value for all |= subsequent calls. Like a latch.
Here a simplified example of this:
groovy> boolean result
groovy> //------------
groovy> println result //<-- False by default
groovy> println result |= false
groovy> println result |= true //<-- set to True and latched on to it
groovy> println result |= false
Output:
false
false
true
true
Edit: Why is this useful?
Consider a situation where you want to know if anything has changed on a variety of objects and if so notify some one of the changes. So, you would setup a hasChanges
boolean and set it to |= diff (a,b)
and then |= dif(b,c)
etc.
Here is a brief example:
groovy> boolean hasChanges, a, b, c, d
groovy> diff = {x,y -> x!=y}
groovy> hasChanges |= diff(a,b)
groovy> hasChanges |= diff(b,c)
groovy> hasChanges |= diff(true,false)
groovy> hasChanges |= diff(c,d)
groovy> hasChanges
Result: true
In memory usage and speed.
When you call jsonstr = json.dumps(mydata)
it first creates a full copy of your data in memory and only then you file.write(jsonstr)
it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.
When you call json.dump(mydata, file)
-- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.
Source: I checked the source code of json.dump()
and json.dumps()
and also tested both the variants measuring the time with time.time()
and watching the memory usage in htop.
This is just a quick review of how fPDF stands up against tcPDF in the area of performance at each libraries most basic functions.
17.0366 seconds to process 2000 PDF files using fPDF || 79.5982 seconds to process 2000 PDF files using tcPDF
788 fPDF || 1,860 tcPDF
The code used was as identical as possible and renders just a clean PDF file with no text. This is also using the latest version of each library as of June 22, 2011.
Update image field to add full URL, ignoring null fields:
UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;
Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.
They can be removed using pod spec remove SPEC_NAME
then pod setup
It may help to do pod spec remove master
then pod setup
The solution from PSL will not work in Firefox. FF accepts event only as a formal parameter. So you have to find another way to identify the selected row. My solution is something like this:
...
$('#mySelector')
.on('show.bs.modal', function(e) {
var mid;
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
mid = $(e.relatedTarget).data('id');
else
mid = $(event.target).closest('tr').data('id');
...
Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793
Check out the Python tutorial on modules and how to use them.
As for the second part of your question, Python comes with batteries included, of course:
>>> math.radians(90)
1.5707963267948966
>>> math.radians(180)
3.141592653589793
If you are using AWS CLI on Windows, you can use the Measure-Object
from PowerShell to get the total counts of files, just like wc -l
on *nix.
PS C:\> aws s3 ls s3://mybucket/ --recursive | Measure-Object
Count : 25
Average :
Sum :
Maximum :
Minimum :
Property :
Hope it helps.
Generally, the system displays an ANR if an application cannot respond to user input.
In any situation in which your app performs a potentially lengthy operation, you should not perform the work on the UI thread, but instead create a worker thread and do most of the work there. This keeps the UI thread (which drives the user interface event loop) running and prevents the system from concluding that your code has frozen.
Android applications normally run entirely on a single thread by default the "UI thread" or "main thread"). This means anything your application is doing in the UI thread that takes a long time to complete can trigger the ANR dialog because your application is not giving itself a chance to handle the input event or intent broadcasts.
Therefore, any method that runs in the UI thread should do as little work as possible on that thread. In particular, activities should do as little as possible to set up in key life-cycle methods such as onCreate() and onResume(). Potentially long running operations such as network or database operations, or computationally expensive calculations such as resizing bitmaps should be done in a worker thread (or in the case of databases operations, via an asynchronous request).
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
// Do the long-running work in here
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
// This is called each time you call publishProgress()
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// This is called when doInBackground() is finished
protected void onPostExecute(Long result) {
showNotification("Downloaded " + result + " bytes");
}
}
To execute this worker thread, simply create an instance and call execute():
new DownloadFilesTask().execute(url1, url2, url3);
http://developer.android.com/training/articles/perf-anr.html
Use a variable and call clearInterval
to stop it.
var interval;
$(document).on('ready',function()
interval = setInterval(updateDiv,3000);
});
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
$.playSound('oneday.wav');
$('.square').html('<span style="color:red">Connection problems</span>');
// I want to stop it here
clearInterval(interval);
}
});
}
Interfaces are basically a contract that all the classes implementing the Interface should follow. They looks like a class but has no implementation.
In C#
Interface names by convention is defined by Prefixing an 'I' so if you want to have an interface called shapes, you would declare it as IShapes
Improves code re-usability
Lets say you want to draw Circle
, Triangle.
You can group them together and call them Shapes
and have methods to draw Circle
and Triangle
But having concrete implementation would be a bad idea because tomorrow you might decide to have 2 more Shapes
Rectangle
& Square
. Now when you add them there is a great chance that you might break other parts of your code.
With Interface you isolate the different implementation from the Contract
Live Scenario Day 1
You were asked to create an App to Draw Circle and Triangle
interface IShapes
{
void DrawShape();
}
class Circle : IShapes
{
public void DrawShape()
{
Console.WriteLine("Implementation to Draw a Circle");
}
}
Class Triangle: IShapes
{
public void DrawShape()
{
Console.WriteLine("Implementation to draw a Triangle");
}
}
static void Main()
{
List <IShapes> shapes = new List<IShapes>();
shapes.Add(new Circle());
shapes.Add(new Triangle());
foreach(var shape in shapes)
{
shape.DrawShape();
}
}
Live Scenario Day 2
If you were asked add Square
and Rectangle
to it, all you have to do is create the implentation for it in class Square: IShapes
and in Main
add to list shapes.Add(new Square());
This answer has two main sections:
If you're only interested in the solutions, skip the first section.
To fully understand how centering works in a grid container, it's important to first understand the structure and scope of grid layout.
The HTML structure of a grid container has three levels:
Each of these levels is independent from the others, in terms of applying grid properties.
The scope of a grid container is limited to a parent-child relationship.
This means that a grid container is always the parent and a grid item is always the child. Grid properties work only within this relationship.
Descendants of a grid container beyond the children are not part of grid layout and will not accept grid properties. (At least not until the subgrid
feature has been implemented, which will allow descendants of grid items to respect the lines of the primary container.)
Here's an example of the structure and scope concepts described above.
Imagine a tic-tac-toe-like grid.
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
}
You want the X's and O's centered in each cell.
So you apply the centering at the container level:
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
justify-items: center;
}
But because of the structure and scope of grid layout, justify-items
on the container centers the grid items, not the content (at least not directly).
article {_x000D_
display: inline-grid;_x000D_
grid-template-rows: 100px 100px 100px;_x000D_
grid-template-columns: 100px 100px 100px;_x000D_
grid-gap: 3px;_x000D_
justify-items: center;_x000D_
}_x000D_
_x000D_
section {_x000D_
border: 2px solid black;_x000D_
font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
</article>
_x000D_
Same problem with align-items
: The content may be centered as a by-product, but you've lost the layout design.
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
justify-items: center;
align-items: center;
}
article {_x000D_
display: inline-grid;_x000D_
grid-template-rows: 100px 100px 100px;_x000D_
grid-template-columns: 100px 100px 100px;_x000D_
grid-gap: 3px;_x000D_
justify-items: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
section {_x000D_
border: 2px solid black;_x000D_
font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
</article>
_x000D_
To center the content you need to take a different approach. Referring again to the structure and scope of grid layout, you need to treat the grid item as the parent and the content as the child.
article {
display: inline-grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-gap: 3px;
}
section {
display: flex;
justify-content: center;
align-items: center;
border: 2px solid black;
font-size: 3em;
}
article {_x000D_
display: inline-grid;_x000D_
grid-template-rows: 100px 100px 100px;_x000D_
grid-template-columns: 100px 100px 100px;_x000D_
grid-gap: 3px;_x000D_
}_x000D_
_x000D_
section {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
border: 2px solid black;_x000D_
font-size: 3em;_x000D_
}
_x000D_
<article>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
<section>O</section>_x000D_
<section>X</section>_x000D_
</article>
_x000D_
There are multiple methods for centering grid items and their content.
Here's a basic 2x2 grid:
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
For a simple and easy way to center the content of grid items use flexbox.
More specifically, make the grid item into a flex container.
There is no conflict, spec violation or other problem with this method. It's clean and valid.
grid-item {
display: flex;
align-items: center;
justify-content: center;
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
display: flex; /* new */_x000D_
align-items: center; /* new */_x000D_
justify-content: center; /* new */_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
See this post for a complete explanation:
In the same way that a flex item can also be a flex container, a grid item can also be a grid container. This solution is similar to the flexbox solution above, except centering is done with grid, not flex, properties.
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
display: grid; /* new */_x000D_
align-items: center; /* new */_x000D_
justify-items: center; /* new */_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
auto
marginsUse margin: auto
to vertically and horizontally center grid items.
grid-item {
margin: auto;
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
margin: auto;_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
To center the content of grid items you need to make the item into a grid (or flex) container, wrap anonymous items in their own elements (since they cannot be directly targeted by CSS), and apply the margins to the new elements.
grid-item {
display: flex;
}
span, img {
margin: auto;
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
span, img {_x000D_
margin: auto;_x000D_
}_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
When considering using the following properties to align grid items, read the section on auto
margins above.
align-items
justify-items
align-self
justify-self
https://www.w3.org/TR/css-align-3/#property-index
text-align: center
To center content horizontally in a grid item, you can use the text-align
property.
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
text-align: center; /* new */_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
Note that for vertical centering, vertical-align: middle
will not work.
This is because the vertical-align
property applies only to inline and table-cell containers.
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
text-align: center; /* <--- works */_x000D_
vertical-align: middle; /* <--- fails */_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item>this text should be centered</grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
One might say that display: inline-grid
establishes an inline-level container, and that would be true. So why doesn't vertical-align
work in grid items?
The reason is that in a grid formatting context, items are treated as block-level elements.
The
display
value of a grid item is blockified: if the specifieddisplay
of an in-flow child of an element generating a grid container is an inline-level value, it computes to its block-level equivalent.
In a block formatting context, something the vertical-align
property was originally designed for, the browser doesn't expect to find a block-level element in an inline-level container. That's invalid HTML.
Lastly, there's a general CSS centering solution that also works in Grid: absolute positioning
This is a good method for centering objects that need to be removed from the document flow. For example, if you want to:
Simply set position: absolute
on the element to be centered, and position: relative
on the ancestor that will serve as the containing block (it's usually the parent). Something like this:
grid-item {
position: relative;
text-align: center;
}
span {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-auto-rows: 75px;_x000D_
grid-gap: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
position: relative;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
span, img {_x000D_
position: absolute;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
}_x000D_
_x000D_
_x000D_
/* can ignore styles below; decorative only */_x000D_
_x000D_
grid-container {_x000D_
background-color: lightyellow;_x000D_
border: 1px solid #bbb;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
grid-item {_x000D_
background-color: lightgreen;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<grid-container>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><span>this text should be centered</span></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
<grid-item><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></grid-item>_x000D_
</grid-container>
_x000D_
Here's a complete explanation for how this method works:
Here's the section on absolute positioning in the Grid spec:
Your class's constructor method should be called __construct()
, not __constructor()
:
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
I come up with this query
SELECT CASE (SELECT count(*) FROM pragma_table_info(''product'') c WHERE c.name = ''purchaseCopy'') WHEN 0 THEN ALTER TABLE product ADD purchaseCopy BLOB END
Did you dump your master gc log? So I met similar issue and I found SPARK_DRIVER_MEMORY only set the Xmx heap. The initial heap size remains 1G and the heap size never scale up to the Xmx heap.
Passing "--conf "spark.driver.extraJavaOptions=-Xms20g" resolves my issue.
ps aux | grep java and the you'll see the follow log:=
24501 30.7 1.7 41782944 2318184 pts/0 Sl+ 18:49 0:33 /usr/java/latest/bin/java -cp /opt/spark/conf/:/opt/spark/jars/* -Xmx30g -Xms20g
On OSX with Postgres installed in /Applications, I simply run the following command (change 0.20 & 9.4 according to your version)
gem install pg -v '0.20' -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config
You should have :
Building native extensions with: '--with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config' This could take a while... Successfully installed pg-0.20.
Here goes a straightforward example:
# Do something, or tell me why it failed
my_update_function <- function(x){
tryCatch(
# This is what I want to do...
{
y = x * 2
return(y)
},
# ... but if an error occurs, tell me what happened:
error=function(error_message) {
message("This is my custom message.")
message("And below is the error message from R:")
message(error_message)
return(NA)
}
)
}
If you also want to capture a "warning", just add warning=
similar to the error=
part.
Which statement is preferable? Depends on what you are doing.
Are there other performance implications? If the table is a permanent table, you can create indexes at the time of table creation which has implications for performance both negatively and positiviely. Select into does not recreate indexes that exist on current tables and thus subsequent use of the table may be slower than it needs to be.
What is a good use case for SELECT...INTO over INSERT INTO ...? Select into is used if you may not know the table structure in advance. It is faster to write than create table and an insert statement, so it is used to speed up develoment at times. It is often faster to use when you are creating a quick temp table to test things or a backup table of a specific query (maybe records you are going to delete). It should be rare to see it used in production code that will run multiple times (except for temp tables) because it will fail if the table was already in existence.
It is sometimes used inappropriately by people who don't know what they are doing. And they can cause havoc in the db as a result. I strongly feel it is inappropriate to use SELECT INTO for anything other than a throwaway table (a temporary backup, a temp table that will go away at the end of the stored proc ,etc.). Permanent tables need real thought as to their design and SELECT INTO makes it easy to avoid thinking about anything even as basic as what columns and what datatypes.
In general, I prefer the use of the create table and insert statement - you have more controls and it is better for repeatable processes. Further, if the table is a permanent table, it should be created from a separate create table script (one that is in source control) as creating permanent objects should not, in general, in code are inserts/deletes/updates or selects from a table. Object changes should be handled separately from data changes because objects have implications beyond the needs of a specific insert/update/select/delete. You need to consider the best data types, think about FK constraints, PKs and other constraints, consider auditing requirements, think about indexing, etc.
I recommend https://pypi.python.org/pypi/anytree
from anytree import Node, RenderTree
udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)
print(udo)
Node('/Udo')
print(joe)
Node('/Udo/Dan/Joe')
for pre, fill, node in RenderTree(udo):
print("%s%s" % (pre, node.name))
Udo
+-- Marc
¦ +-- Lian
+-- Dan
+-- Jet
+-- Jan
+-- Joe
print(dan.children)
(Node('/Udo/Dan/Jet'), Node('/Udo/Dan/Jan'), Node('/Udo/Dan/Joe'))
anytree has also a powerful API with:
Return false will stop the hyperlink being followed after the javascript has run. This is useful for unobtrusive javascript that degrades gracefully - for example, you could have a thumbnail image that uses javascript to open a pop-up of the full-sized image. When javascript is turned off or the image is middle-clicked (opened in a new tab) this ignores the onClick event and just opens the image as a full-sized image normally.
If return false were not specified, the image would both launch the pop-up and open the image normally. Some people instead of using return false use javascript as the href attribute, but this means that when javascript is disabled the link will do nothing.
var d = new Date();_x000D_
_x000D_
document.write('Today is: ' + d.toLocaleString());_x000D_
_x000D_
d.setDate(d.getDate() - 31);_x000D_
_x000D_
document.write('<br>5 days ago was: ' + d.toLocaleString());
_x000D_
If you are using Nodemon my guess is the PORT 3000 is set in the nodemonConfig. Check if that is the case.
You might be able to use the following for decoding, compressing and saving an image:
@Override
public void onClick(View view) {
onItemSelected1();
InputStream image_stream = null;
try {
image_stream = getContentResolver().openInputStream(myUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap image= BitmapFactory.decodeStream(image_stream );
// path to sd card
File path=Environment.getExternalStorageDirectory();
//create a file
File dir=new File(path+"/ComDec/");
dir.mkdirs();
Date date=new Date();
File file=new File(dir,date+".jpg");
OutputStream out=null;
try{
out=new FileOutputStream(file);
image.compress(format,size,out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");
image=null;
}
catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
}
});
This works
<a href="#" id="sampleApp" onclick="myFunction(); return false;">Click Here</a>
If Ruby is installed, then
ruby yourfile.rb
where yourfile.rb
is the file containing the ruby code.
Or
irb
to start the interactive Ruby environment, where you can type lines of code and see the results immediately.
ALTER TABLE mytable RENAME TO othertable
In Oracle 10g
also:
RENAME mytable TO othertable
This will work:
>>> import re
>>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE)
>>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines
>>> text="""Some varying text1
...
... AAABBBBBBCCCCCCDDDDDDD
... EEEEEEEFFFFFFFFGGGGGGG
... HHHHHHIIIIIJJJJJJJKKKK
...
... Some varying text 2
...
... LLLLLMMMMMMNNNNNNNOOOO
... PPPPPPPQQQQQQRRRRRRSSS
... TTTTTUUUUUVVVVVVWWWWWW
... """
>>> for match in rx_sequence.finditer(text):
... title, sequence = match.groups()
... title = title.strip()
... sequence = rx_blanks.sub("",sequence)
... print "Title:",title
... print "Sequence:",sequence
... print
...
Title: Some varying text1
Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK
Title: Some varying text 2
Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW
Some explanation about this regular expression might be useful: ^(.+?)\n\n((?:[A-Z]+\n)+)
^
) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).(.+?)\n\n
means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.[A-Z]+\n
means "match as many upper case letters as possible until you reach a newline. This defines what I will call a textline.((?:
textline)+)
means match one or more textlines but do not put each line in a group. Instead, put all the textlines in one group.\n
in the regular expression if you want to enforce a double newline at the end.\n
or \r
or \r\n
) then just fix the regular expression by replacing every occurrence of \n
by (?:\n|\r\n?)
.Indices imply lots of comparisons.
Typically, strings are longer than integers and collation rules may be applied for comparison, so comparing strings is usually more computationally intensive task than comparing integers.
Sometimes, though, it's faster to use a string as a primary key than to make an extra join with a string to numerical id
table.
In your httpd.conf
make sure you have:
Listen *:80
And if you are using VirtualHosts then set them as given below:
NameVirtualHost *
<VirtualHost *>
...
</VirtualHost>
You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet
of Note
s, where you need to pass in a single Note
.
You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
delete build folder projectfile\android\app\build
and run project
Use this:
String str = "testString";
char[] charArray = str.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);
It sounds to me like you're having core.autocrlf-problems. core.autocrlf=true can give problems like the ones you describe on Windows if CRLF newlines were checked into the repository. Try disabling core.autocrlf for the repository, and perform a hard-reset.
Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):
It is a little tricky though... :)
i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like
public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}
ii. This should add (using Tab-Tab) this function to your code file:
public void RaisePostBackEvent(string eventArgument) { }
iii. In your onclick event in JavaScript, write the following code:
var pageId = '<%= Page.ClientID %>';
__doPostBack(pageId, argumentString);
This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.
P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!
Option(getObject) foreach (QueueManager add)
To keep new lines:
Next:
Now, Select Replace option Extended and Replace # with \n
:) now, you have a clean ASCII file ;)
Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.
For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".
Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html
Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx
don't forget all the pleasure that occur with the shell limitation around " and '
so (in ksh)
Var=">New version of \"content' here <"
printf "%s" "${Var}" | sed "s/[&\/\\\\*\\"']/\\&/g' | read -r EscVar
echo "Here is your \"text\" to change" | sed "s/text/${EscVar}/g"
I have the same problem. After studying and googling, I have resolved my problem:
Right click on the project folder, go to Java EE Tools
, select Generate Deployment Descriptor Stub
. This will create web.xml
in the folder src/main/webapp/WEB-INF
.
Another way to do this is by using a "configure" script. If you are already using one with your makefile, you can use a combination of uname and sed to get things to work out. First, in your script, do:
UNAME=uname
Then, in order to put this in your Makefile, start out with Makefile.in which should have something like
UNAME=@@UNAME@@
in it.
Use the following sed command in your configure script after the UNAME=uname
bit.
sed -e "s|@@UNAME@@|$UNAME|" < Makefile.in > Makefile
Now your makefile should have UNAME
defined as desired. If/elif/else statements are all that's left!
If you'd like to add text at the end of each line in-place (in the same file), you can use -i
parameter, for example:
sed -i'.bak' 's/$/:80/' foo.txt
However -i
option is non-standard Unix extension and may not be available on all operating systems.
So you can consider using ex
(which is equivalent to vi -e
/vim -e
):
ex +"%s/$/:80/g" -cwq foo.txt
which will add :80
to each line, but sometimes it can append it to blank lines.
So better method is to check if the line actually contain any number, and then append it, for example:
ex +"g/[0-9]/s/$/:80/g" -cwq foo.txt
If the file has more complex format, consider using proper regex, instead of [0-9]
.
In C# you can loop through the array printing each element. Note that System.Object defines a method ToString(). Any given type that derives from System.Object() can override that.
Returns a string that represents the current object.
http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx
By default the full type name of the object will be printed, though many built-in types override that default to print a more meaningful result. You can override ToString() in your own objects to provide meaningful output.
foreach (var item in myArray)
{
Console.WriteLine(item.ToString()); // Assumes a console application
}
If you had your own class Foo, you could override ToString() like:
public class Foo
{
public override string ToString()
{
return "This is a formatted specific for the class Foo.";
}
}
I often confuse the two. Better to remember through their output:
$ touch someFile.txt
$ echo ">" > someFile.txt
$ cat someFile.txt
>
$ echo ">" > someFile.txt
$ cat someFile.txt
>
$ echo ">" > someFile.txt
$ cat someFile.txt
>
$ echo ">" >> someFile.txt
$ cat someFile.txt
>>
When you create a flex container various default flex rules come into play.
Two of these default rules are flex-direction: row
and align-items: stretch
. This means that flex items will automatically align in a single row, and each item will fill the height of the container.
If you don't want flex items to stretch – i.e., like you wrote:
make its height the minimum required for holding its content
... then simply override the default with align-items: flex-start
.
#a {_x000D_
display: flex;_x000D_
align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
background-color: red;_x000D_
padding: 5px;_x000D_
margin: 2px;_x000D_
}_x000D_
#b {_x000D_
height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
<div id="b">left</div>_x000D_
<div>_x000D_
right<br>right<br>right<br>right<br>right<br>_x000D_
</div>_x000D_
</div>
_x000D_
Here's an illustration from the flexbox spec that highlights the five values for align-items
and how they position flex items within the container. As mentioned before, stretch
is the default value.
Source: W3C
Stuart's answer provides a great explanation, but I'd like to provide another example.
I ran into this issue when attempting to perform a reduce
on a Stream containing null values (actually it was LongStream.average()
, which is a type of reduction). Since average() returns OptionalDouble
, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.
So, as the OP suggests, I added a filter like so:
list.stream()
.filter(o -> o != null)
.reduce(..);
Or as tangens pointed out below, use the predicate provided by the Java API:
list.stream()
.filter(Objects::nonNull)
.reduce(..);
From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams
You could also try dumping the table, finding the insert command and editing it:
mysqldump -umyuser -p mydatabase --skip-extended-insert mytable > outfile.sql
The --skip-extended-insert
gives you one insert command per row. You may then find the row in your favourite text editor, extract the command and alter the primary key to "default".
Here is an other solution, largely inspired by the one by @fredoverflow.
/**
* Return hexadecimal representation of the input binary sequence
*/
std::string hexitize(const std::vector<char>& input, const char* const digits = "0123456789ABCDEF")
{
std::ostringstream output;
for (unsigned char gap = 0, beg = input[gap]; gap < input.length(); beg = input[++gap])
output << digits[beg >> 4] << digits[beg & 15];
return output.str();
}
Length was required parameter in the intended usage.
$('#test').attr('checked','checked');
$('#test').removeAttr('checked');
The preferred approach should be:
Double.valueOf(d).longValue()
From the Double (Java Platform SE 7) documentation:
Double.valueOf(d)
Returns a
Double
instance representing the specifieddouble
value. If a newDouble
instance is not required, this method should generally be used in preference to the constructorDouble(double)
, as this method is likely to yield significantly better space and time performance by caching frequently requested values.
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
The syntax error is just due to a missing alias for the subquery:
select COUNT(*) from
(
select m.Company_id
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5) mySubQuery /* Alias */
I know this is an old thread... but as many people are searching for ways to undo stuff in Git, I still think it may be a good idea to continue giving tips here.
When you do a "git add" or move anything from the top left to the bottom left in git gui the content of the file is stored in a blob and the file content is possible to recover from that blob.
So it is possible to recover a file even if it was not committed but it has to have been added.
git init
echo hello >> test.txt
git add test.txt
Now the blob is created but it is referenced by the index so it will no be listed with git fsck until we reset. So we reset...
git reset --hard
git fsck
you will get a dangling blob ce013625030ba8dba906f756967f9e9ca394464a
git show ce01362
will give you the file content "hello" back
To find unreferenced commits I found a tip somewhere suggesting this.
gitk --all $(git log -g --pretty=format:%h)
I have it as a tool in git gui and it is very handy.
string filePath = HttpContext.Current.Server.MapPath("~/folderName/filename.extension");
OR
string filePath = HttpContext.Server.MapPath("~/folderName/filename.extension");
When entered as the reference of a Named range
, it refers to range on the sheet the named range is used on.
For example, create a named range MyName
refering to =SUM(!B1:!K1)
Place a formula on Sheet1
=MyName
. This will sum Sheet1!B1:K1
Now place the same formula (=MyName
) on Sheet2
. That formula will sum Sheet2!B1:K1
Note: (as pnuts commented) this and the regular SheetName!B1:K1
format are relative, so reference different cells as the =MyName
formula is entered into different cells.
mailx -a /path/to/file email@address
You might go into interactive mode (it will prompt you with "Subject: " and then a blank line), enter a subject, then enter a body and hit Ctrl+D (EOT) to finish.
There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:
With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.
Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/
Update 2019:
The size in bits of long
on Windows platforms is 32 bits (4 bytes).
You can check this using sizeof(long)
.
Here's the modern, safe one liner:
java.nio.file.Files.write(java.nio.file.Paths.get("/tmp/output.txt"), "Hello world".getBytes());
nio is a modern IO library shipped by default with the JDK 9+ so no imports or dependencies required.
I also came across this problem. In my case, I didn't know the type of the IEnumerable. So the answers given above wont work. However, I solved it like this:
public static DataTable CreateDataTable(IEnumerable source)
{
var table = new DataTable();
int index = 0;
var properties = new List<PropertyInfo>();
foreach (var obj in source)
{
if (index == 0)
{
foreach (var property in obj.GetType().GetProperties())
{
if (Nullable.GetUnderlyingType(property.PropertyType) != null)
{
continue;
}
properties.Add(property);
table.Columns.Add(new DataColumn(property.Name, property.PropertyType));
}
}
object[] values = new object[properties.Count];
for (int i = 0; i < properties.Count; i++)
{
values[i] = properties[i].GetValue(obj);
}
table.Rows.Add(values);
index++;
}
return table;
}
Keep in mind that using this method, requires at least one item in the IEnumerable. If that's not the case, the DataTable wont create any columns.
The answer is:
gcc --version
Rather than searching on forums, for any possible option you can always type:
gcc --help
haha! :)
Im posting this as a potensial Answer!
What i did to solve this was the following:
sudo rm /usr/local/mysql
sudo rm -rf /usr/local/mysql*
sudo rm -rf /Library/StartupItems/MySQLCOM
sudo rm -rf /Library/PreferencePanes/MySQL*
vim /etc/hostconfig and removed the line MYSQLCOM=-YES-
rm -rf ~/Library/PreferencePanes/MySQL*
sudo rm -rf /Library/Receipts/mysql*
sudo rm -rf /Library/Receipts/MySQL*
sudo rm -rf /var/db/receipts/com.mysql.*
Library/Application Support/appsolute
folder (MAMP application support folder)Hopefully this helps :)
I know this is a really old question.. and it appears it was answered.. But I got here with the same question but a different reason for the question, and so a slightly different answer worked for me. I have a nice reusable generic datagridview that takes the datasource supplied to it and just displays the columns in their default order. I put aliases and column order and selection at the dataset's tableadapter level in designer. However changing the select query order of columns doesn't seem to impact the columns returned through the dataset. I have found the only way to do this in the designer, is to remove all the columns selected within the tableadapter, adding them back in the order you want them selected.
Shaun F's answer will not work if Schema doesn't exist in the DB. If anyone is looking for way to create schema then just execute following script to create schema.
create schema [schema_name]
CREATE TABLE [schema_name].[table_name](
...
) ON [PRIMARY]
While adding new table, go to table design mode and press F4
to open property Window and select the schema from dropdown. Default is dbo
.
You can also change the schema of the current Table using Property window.
Refer:
First of all, your selector is overkill. I suggest using a class or ID selector like my example below. Once you've corrected your selector, simply use jQuery's .each() to iterate through the collection:
ID Selector:
$('#mytable td').each(function() {
var cellText = $(this).html();
});
Class Selector:
$('.myTableClass td').each(function() {
var cellText = $(this).html();
});
Additional Information:
Take a look at jQuery's selector docs.
From the docs:
"a UNIQUE index permits multiple NULL values for columns that can contain NULL"
This applies to all engines but BDB.
For me was not working so worked this way:
Controller:
int selectedId = 1;
ViewBag.ItemsSelect = new SelectList(db.Items, "ItemId", "ItemName",selectedId);
View:
@Html.DropDownListFor(m => m.ItemId,(SelectList)ViewBag.ItemsSelect)
JQuery:
$("document").ready(function () {
$('#ItemId').val('@Model.ItemId');
});
You need to capture the key window for a screenshot or a UIView. You can do it in Retina Resolution using UIGraphicsBeginImageContextWithOptions and set its scale parameter 0.0f. It always captures in native resolution (retina for iPhone 4 and later).
This one does a full screen screenshot (key window)
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect = [keyWindow bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];
UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
This code capture a UIView in native resolution
CGRect rect = [captureView bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[captureView.layer renderInContext:context];
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
This saves the UIImage in jpg format with 95% quality in the app's document folder if you need to do that.
NSString *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/capturedImage.jpg"]];
[UIImageJPEGRepresentation(capturedImage, 0.95) writeToFile:imagePath atomically:YES];
If the number of list items is fixed you can use the adjacent selector, e.g. if you only have three <li>
elements, you can select the last <li>
with:
#nav li+li+li {
border-bottom: 1px solid #b5b5b5;
}
Changing the 'w' (write) in this line:
output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers)
To 'wb' (write binary) fixed this problem for me:
output = csv.DictWriter(open('file3.csv','wb'), delimiter=',', fieldnames=headers)
Credit to @dandrejvv for the solution in the comment on the original post above.
Yes - just explicitly provide the path to java.exe. For instance:
c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)
c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)
The easiest way to do this for a running command shell is something like:
set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%
For example, here's a complete session showing my default JVM, then the change to the path, then the new one:
c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)
c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%
c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)
This won't change programs which explicitly use JAVA_HOME though.
Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.
I manually filled NAs by exporting the CSV then editing it and reimporting, as below.
Perhaps one of you experts might explain why this procedure worked so well
(the first file had columns with data of types char
, INT
and num
(floating point numbers)), which all became char
type after STEP 1; but at the end of STEP 3 R correctly recognized the datatype of each column).
# STEP 1:
MainOptionFile <- read.csv("XLUopt_XLUstk_v3.csv",
header=T, stringsAsFactors=FALSE)
#... STEP 2:
TestFrame <- subset(MainOptionFile, str_locate(option_symbol,"120616P00034000") > 0)
write.csv(TestFrame, file = "TestFrame2.csv")
# ...
# STEP 3:
# I made various amendments to `TestFrame2.csv`, including replacing all missing data cells with appropriate numbers. I then read that amended data frame back into R as follows:
XLU_34P_16Jun12 <- read.csv("TestFrame2_v2.csv",
header=T,stringsAsFactors=FALSE)
On arrival back in R, all columns had their correct measurement levels automatically recognized by R!
Since this is a common piece of functionality it's a good idea to write a directive for this. In fact, someone already did that and open sourced it. I used editablespan library in one of my projects and it worked perfectly, highly recommended.
Another simple way to hack it:
seq 20 | xargs -Iz echo "Hi there"
run echo 20 times.
Notice that seq 20 | xargs -Iz echo "Hi there z"
would output:
Hi there 1
Hi there 2
...
It's much easier (and faster) to get this information by only parsing the output of ver
:
@echo off
setlocal
for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j
if "%version%" == "10.0" echo Windows 10
if "%version%" == "6.3" echo Windows 8.1
if "%version%" == "6.2" echo Windows 8.
if "%version%" == "6.1" echo Windows 7.
if "%version%" == "6.0" echo Windows Vista.
rem etc etc
endlocal
This table on MSDN documents which version number corresponds to which Windows product version (this is where you get the 6.1 means Windows 7 information from).
The only drawback of this technique is that it cannot distinguish between the equivalent server and consumer versions of Windows.
You can use UNION ALL instead.
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.MainTable AS mt
Union ALL
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.OtherTable AS ot
Note that (.|\n)*
can be less efficient than (for example) [\s\S]*
(if your language's regexes support such escapes) and than finding how to specify the modifier that makes . also match newlines. Or you can go with POSIXy alternatives like [[:space:][:^space:]]*
.
TLDR: Check that you don't connect to the same table/view twice.
FooConfiguration.cs
builder.ToTable("Profiles", "dbo");
...
BarConfiguration.cs
builder.ToTable("profiles", "dbo");
For me the issue was that I was trying to add an entity that connected to the same table as some other entity that already existed.
I added a new DbSet with entity and config, thinking we don't have it in our solution yet, however after searching for table name through all solution I found another place where we already connected to it.
Switching to use existing DbSet and removing my newly added one solved the issue.
Use strtotime()
:
$time=strtotime($dateValue);
$month=date("F",$time);
$year=date("Y",$time);
I had to go through this process myself and chose a different way that I think is better in the long run.
I installed homebrew
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
then:
brew doctor
The last step gives you some warnings and errors that you have to resolve. One of those will be to download and install the Mac OS X command-line tools.
then:
brew install python3
This gave me python3
and pip3
in my path.
pieter$ which pip3 python3
/usr/local/bin/pip3
/usr/local/bin/python3
From Official Docs
Correctly configuring your shell on Windows is a matter of locating the right executable and updating the setting. Below is a list of common shell executables and their default locations.
There is also the convenience command Select Default Shell that can be accessed through the command palette which can detect and set this for you.
So you can open a command palette using ctrl+shift+p
, use the command Select Default Shell, then it displays all the available command line interfaces, select whatever you want, VS code sets that as default integrated terminal for you automatically.
If you want to set it manually find the location of executable of your cli and open user settings of vscode(ctrl+,
) then set
"terminal.integrated.shell.windows":"path/to/executable.exe"
Example for gitbash on windows7:
"terminal.integrated.shell.windows":"C:\\Users\\stldev03\\AppData\\Local\\Programs\\Git\\bin\\bash.exe",
There isn't so much a 'correct' way for the language. It's more personal preference or what the standard is for your team. I usually use the myFunction() when I'm doing my own code. Also, a style you didn't mention that you will often see in C++ is my_function() - no caps, underscores instead of spaces.
Really it is just dictated by the code your working in. Or, if it's your own project, your own personal preference then.
Bear in mind that, if you're going to be doing a lot of lookups, there are STL containers that are better for that. I don't know what your application is, but associative containers like std::map may be worth considering.
std::vector is the container of choice unless you have a reason for another, and lookups by value can be such a reason.
Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
var json = {"ListID" : "1", "ItemName":"test"};
$.ajax({
url: url,
type: 'POST',
data: username,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
console.log("Success")
},
error : function(xhr, status, error) {
console.log("error")
}
);
If the command should work with both tabs and spaces as the delimiter I would use awk
:
awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile
As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for
loop:
awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile
If you want to use cut
, you need to use the -f
option:
cut -f100-105 myfile > outfile
If the field delimiter is different from TAB
you need to specify it using -d
:
cut -d' ' -f100-105 myfile > outfile
Check the man page for more info on the cut command.
function hasSpaces(str) {
if (str.indexOf(' ') !== -1) {
return true
} else {
return false
}
}
I think the available libraries, tools, examples, and communities completely trumps the paradigm these days. For example, ML (or whatever) might be the ultimate all-purpose programming language but if you can't get any good libraries for what you are doing you're screwed.
For example, if you're making a video game, there are more good code examples and SDKs in C++, so you're probably better off with that. For a small web application, there are some great Python, PHP, and Ruby frameworks that'll get you off and running very quickly. Java is a great choice for larger projects because of the compile-time checking and enterprise libraries and platforms.
It used to be the case that the standard libraries for different languages were pretty small and easily replicated - C, C++, Assembler, ML, LISP, etc.. came with the basics, but tended to chicken out when it came to standardizing on things like network communications, encryption, graphics, data file formats (including XML), even basic data structures like balanced trees and hashtables were left out!
Modern languages like Python, PHP, Ruby, and Java now come with a far more decent standard library and have many good third party libraries you can easily use, thanks in great part to their adoption of namespaces to keep libraries from colliding with one another, and garbage collection to standardize the memory management schemes of the libraries.
Here's what I use at the top of all my batch files. I just copy/paste from my template folder.
@echo off
:: --HAS ENDING BACKSLASH
set batdir=%~dp0
:: --MISSING ENDING BACKSLASH
:: set batdir=%CD%
pushd "%batdir%"
Setting current batch file's path to %batdir% allows you to call it in subsequent stmts in current batch file, regardless of where this batch file changes to. Using PUSHD allows you to use POPD to quickly set this batch file's path to original %batdir%. Remember, if using %batdir%ExtraDir or %batdir%\ExtraDir (depending on which version used above, ending backslash or not) you will need to enclose the entire string in double quotes if path has spaces (i.e. "%batdir%ExtraDir"). You can always use PUSHD %~dp0. [https: // ss64.com/ nt/ syntax-args .html] has more on (%~) parameters.
Note that using (::) at beginning of a line makes it a comment line. More importantly, using :: allows you to include redirectors, pipes, special chars (i.e. < > | etc) in that comment.
:: ORIG STMT WAS: dir *.* | find /v "1917" > outfile.txt
Of course, Powershell does this and lots more.
Jenkins uses Cron Expressions.
You can simply schedule hourly builds by just typing@hourly
.
There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime()
and TimeUnit.NANOSECONDS
as the time unit. Why should I do this? Well, it is because System.nanoTime()
method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.
For the same reason, it is recommended to avoid the use of the System.currentTimeMillis()
method for measuring elapsed time. This method returns the wall-clock
time, which may change based on many factors. This will be negative for your measurements.
Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
So here you have one solution based on the System.nanoTime()
method, another one using Guava, and the final one Apache Commons Lang
public class TimeBenchUtil
{
public static void main(String[] args) throws InterruptedException
{
stopWatch();
stopWatchGuava();
stopWatchApacheCommons();
}
public static void stopWatch() throws InterruptedException
{
long endTime, timeElapsed, startTime = System.nanoTime();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
endTime = System.nanoTime();
// get difference of two nanoTime values
timeElapsed = endTime - startTime;
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
public static void stopWatchGuava() throws InterruptedException
{
// Creates and starts a new stopwatch
Stopwatch stopwatch = Stopwatch.createStarted();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
stopwatch.stop(); // optional
// get elapsed time, expressed in milliseconds
long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
public static void stopWatchApacheCommons() throws InterruptedException
{
StopWatch stopwatch = new StopWatch();
stopwatch.start();
/* ... the code being measured starts ... */
// sleep for 5 seconds
TimeUnit.SECONDS.sleep(5);
/* ... the code being measured ends ... */
stopwatch.stop(); // Optional
long timeElapsed = stopwatch.getNanoTime();
System.out.println("Execution time in nanoseconds : " + timeElapsed);
}
}
If your original dataframe df
is not too big, you have no memory constraints, and you only need to keep a few columns, or, if you don't know beforehand the names of all the extra columns that you do not need, then you might as well create a new dataframe with only the columns you need:
new_df = df[['spam', 'sausage']]
Another question asked specifically how to perform multiple left joins using dplyr in R . The question was marked as a duplicate of this one so I answer here, using the 3 sample data frames below:
x <- data.frame(i = c("a","b","c"), j = 1:3, stringsAsFactors=FALSE)
y <- data.frame(i = c("b","c","d"), k = 4:6, stringsAsFactors=FALSE)
z <- data.frame(i = c("c","d","a"), l = 7:9, stringsAsFactors=FALSE)
Update June 2018: I divided the answer in three sections representing three different ways to perform the merge. You probably want to use the purrr
way if you are already using the tidyverse packages. For comparison purposes below, you'll find a base R version using the same sample dataset.
1) Join them with reduce
from the purrr
package:
The purrr
package provides a reduce
function which has a concise syntax:
library(tidyverse)
list(x, y, z) %>% reduce(left_join, by = "i")
# A tibble: 3 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
You can also perform other joins, such as a full_join
or inner_join
:
list(x, y, z) %>% reduce(full_join, by = "i")
# A tibble: 4 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
# 4 d NA 6 8
list(x, y, z) %>% reduce(inner_join, by = "i")
# A tibble: 1 x 4
# i j k l
# <chr> <int> <int> <int>
# 1 c 3 5 7
2) dplyr::left_join()
with base R Reduce()
:
list(x,y,z) %>%
Reduce(function(dtf1,dtf2) left_join(dtf1,dtf2,by="i"), .)
# i j k l
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
3) Base R merge()
with base R Reduce()
:
And for comparison purposes, here is a base R version of the left join based on Charles's answer.
Reduce(function(dtf1, dtf2) merge(dtf1, dtf2, by = "i", all.x = TRUE),
list(x,y,z))
# i j k l
# 1 a 1 NA 9
# 2 b 2 4 NA
# 3 c 3 5 7
I tend to look at it from the inverse perspective which may be what you intended:
What characters do I want to allow?
This is because there could be lots of characters that make in into a string somehow that blow stuff up that you wouldn't expect.
For example this one only allows for letters and numbers removing groups of invalid characters replacing them with a hypen:
"This¢£«±Ÿ÷could&*()\/<>be!@#$%^bad".replace(/([^a-z0-9]+)/gi, '-');
//Result: "This-could-be-bad"
You can simply use the toUTCString
(or toISOString
) methods of the date object.
Example:
new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()
// Output: "Fri, 20 Jan 2012 16:51:36 GMT"
If you prefer better control of the output format, consider using a library such as date-fns or moment.js.
Also, in your question, you've actually converted the time incorrectly. When an offset is shown in a timestamp string, it means that the date and time values in the string have already been adjusted from UTC by that value. To convert back to UTC, invert the sign before applying the offset.
11:51:36 -0300 == 14:51:36Z
this works for me:
from tkinter import *
root = Tk()
l = Label(root, text="Does it work")
l.pack()
If updating cURL doesn't fix it, updating NSS should do the trick.
// This is for normal triangle
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print(" *");
}
System.out.print("\n");
}
// This is for left triangle, just removed space before printing *
for (int i = 0; i < 5; i++)
{
for (int j = 5; j > i; j--)
{
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print("*");
}
System.out.print("\n");
}
One liner with .apply()
method is following:
df['color'] = df['Set'].apply(lambda set_: 'green' if set_=='Z' else 'red')
After that, df
data frame looks like this:
>>> print(df)
Type Set color
0 A Z green
1 B Z green
2 B X red
3 C Y red
I think Peter has the right idea. I would use a regular expression for this along with the -notmatch operator.
Get-EventLog Security | ?{$_.Username -notmatch '^user1$|^.*user$'}
If i understood correct try this one
$headers = "Bcc: [email protected]";
or
$headers = "Cc: [email protected]";
To prevent monitoring a file by git
git update-index --assume-unchanged [file-path]
And to revert it back use
git update-index --no-assume-unchanged [file-path]
A repo to refer for similar use cases https://github.com/awslabs/git-secrets
change parent="android:Theme.Holo.Dark"
to parent="android:Theme.Holo"
The holo dark theme is called Holo
You are using a wrong overload of the Html.ActionLink
helper. What you think is routeValues
is actually htmlAttributes
! Just look at the generated HTML, you will see that this anchor's href property doesn't look as you expect it to look.
Here's what you are using:
@Html.ActionLink(
"Reply", // linkText
"BlogReplyCommentAdd", // actionName
"Blog", // routeValues
new { // htmlAttributes
blogPostId = blogPostId,
replyblogPostmodel = Model,
captchaValid = Model.AddNewComment.DisplayCaptcha
}
)
and here's what you should use:
@Html.ActionLink(
"Reply", // linkText
"BlogReplyCommentAdd", // actionName
"Blog", // controllerName
new { // routeValues
blogPostId = blogPostId,
replyblogPostmodel = Model,
captchaValid = Model.AddNewComment.DisplayCaptcha
},
null // htmlAttributes
)
Also there's another very serious issue with your code. The following routeValue:
replyblogPostmodel = Model
You cannot possibly pass complex objects like this in an ActionLink. So get rid of it and also remove the BlogPostModel
parameter from your controller action. You should use the blogPostId
parameter to retrieve the model from wherever this model is persisted, or if you prefer from wherever you retrieved the model in the GET action:
public ActionResult BlogReplyCommentAdd(int blogPostId, bool captchaValid)
{
BlogPostModel model = repository.Get(blogPostId);
...
}
As far as your initial problem is concerned with the wrong overload I would recommend you writing your helpers using named parameters:
@Html.ActionLink(
linkText: "Reply",
actionName: "BlogReplyCommentAdd",
controllerName: "Blog",
routeValues: new {
blogPostId = blogPostId,
captchaValid = Model.AddNewComment.DisplayCaptcha
},
htmlAttributes: null
)
Now not only that your code is more readable but you will never have confusion between the gazillions of overloads that Microsoft made for those helpers.
It means that zero or more String objects (or a single array of them) may be passed as the argument(s) for that method.
See the "Arbitrary Number of Arguments" section here: http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html#varargs
In your example, you could call it as any of the following:
myMethod(); // Likely useless, but possible
myMethod("one", "two", "three");
myMethod("solo");
myMethod(new String[]{"a", "b", "c"});
Important Note: The argument(s) passed in this way is always an array - even if there's just one. Make sure you treat it that way in the method body.
Important Note 2: The argument that gets the ...
must be the last in the method signature. So, myMethod(int i, String... strings)
is okay, but myMethod(String... strings, int i)
is not okay.
Thanks to Vash for the clarifications in his comment.
Just in case it helps: there is a way to edit a symlink with midnight commander (mc). The menu command is (in French on my mc interface):
Fichier / Éditer le lien symbolique
which may be translated to:
File / Edit symbolic link
The shortcut is C-x C-s
Maybe it internally uses the ln --force
command, I don't know.
Now, I'm trying to find a way to edit a whole lot of symlinks at once (that's how I arrived here).
In main.xml file
You can put the following attrubute to validate only alphabatics character can accept in edittext.
Do this :
android:entries="abcdefghijklmnopqrstuvwxyz"
I am probably the most novice user here, I have spent six hours just to run python in the command line in Windows 8. Once I installed the 64-bit version, then I uninstalled it and replaced it with 32-bit version. Then, I tried most suggestions here, especially by defining path in the system variables, but still it didn't work.
Then I realised when I typed in the command line: echo %path%
The path still was not directed to C:\python27. So I simply restarted the computer, and now it works.
Write bytes and Create the file if not exists:
f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()
wb
means open the file in write binary
mode.
This is technique I have used on a number of occasions. It is originally based on this fiddle with a number of modifications. It is also fluid and column widths can be fixed by adding a width style to the <th>
.
/* this is for the main container of the table, also sets the height of the fixed header row */_x000D_
.headercontainer {_x000D_
position: relative;_x000D_
border: 1px solid #222;_x000D_
padding-top: 37px;_x000D_
background: #000;_x000D_
}_x000D_
/* this is for the data area that is scrollable */_x000D_
.tablecontainer {_x000D_
overflow-y: auto;_x000D_
height: 200px;_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
/* remove default cell borders and ensures table width 100% of its container*/_x000D_
.tablecontainer table {_x000D_
border-spacing: 0;_x000D_
width:100%;_x000D_
}_x000D_
_x000D_
/* add a thin border to the left of cells, but not the first */_x000D_
.tablecontainer td + td {_x000D_
border-left:1px solid #eee; _x000D_
}_x000D_
_x000D_
/* cell padding and bottom border */_x000D_
.tablecontainer td, th {_x000D_
border-bottom:1px solid #eee;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
/* make the default header height 0 and make text invisible */_x000D_
.tablecontainer th {_x000D_
height: 0px;_x000D_
padding-top: 0;_x000D_
padding-bottom: 0;_x000D_
line-height: 0;_x000D_
visibility: hidden;_x000D_
white-space: nowrap;_x000D_
}_x000D_
_x000D_
/* reposition the divs in the header cells and place in the blank area of the headercontainer */_x000D_
.tablecontainer th div{_x000D_
visibility: visible;_x000D_
position: absolute;_x000D_
background: #000;_x000D_
color: #fff;_x000D_
padding: 9px 10px;_x000D_
top: 0;_x000D_
margin-left: -10px;_x000D_
line-height: normal;_x000D_
border-left: 1px solid #222;_x000D_
}_x000D_
/* prevent the left border from above appearing in first div header */_x000D_
th:first-child div{_x000D_
border: none;_x000D_
}_x000D_
_x000D_
/* alternate colors for rows */_x000D_
.tablecontainer tbody tr:nth-child(even){_x000D_
background-color: #ddd;_x000D_
}
_x000D_
<div class="headercontainer">_x000D_
<div class="tablecontainer">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>_x000D_
Table attribute name_x000D_
<div>Table attribute name</div>_x000D_
</th>_x000D_
<th>_x000D_
Value_x000D_
<div>Value</div>_x000D_
</th>_x000D_
<th>_x000D_
Description_x000D_
<div>Description</div>_x000D_
</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>align</td>_x000D_
<td>left, center, right</td>_x000D_
<td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the alignment of a table according to surrounding text</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>bgcolor</td>_x000D_
<td>rgb(x,x,x), #xxxxxx, colorname</td>_x000D_
<td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the background color for a table</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>border</td>_x000D_
<td>1,""</td>_x000D_
<td>Specifies whether the table cells should have borders or not</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cellpadding</td>_x000D_
<td>pixels</td>_x000D_
<td>Not supported in HTML5. Specifies the space between the cell wall and the cell content</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cellspacing</td>_x000D_
<td>pixels</td>_x000D_
<td>Not supported in HTML5. Specifies the space between cells</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>frame</td>_x000D_
<td>void, above, below, hsides, lhs, rhs, vsides, box, border</td>_x000D_
<td>Not supported in HTML5. Specifies which parts of the outside borders that should be visible</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>rules</td>_x000D_
<td>none, groups, rows, cols, all</td>_x000D_
<td>Not supported in HTML5. Specifies which parts of the inside borders that should be visible</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>summary</td>_x000D_
<td>text</td>_x000D_
<td>Not supported in HTML5. Specifies a summary of the content of a table</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>width</td>_x000D_
<td>pixels, %</td>_x000D_
<td>Not supported in HTML5. Specifies the width of a table</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
Also as a JSFiddle
Having had a similar problem with data from 1800 to now, this worked for me:
data2$date=as.character(data2$date)
lct <- Sys.getlocale("LC_TIME");
Sys.setlocale("LC_TIME","C")
data2$date<- as.Date(data2$date, format = "%Y %m %d") # and it works
Step1: Delete all instances of java from you machine
Step2: Delete all the environment variables related to java/jdk/jre
Step3: Check in programm files and program files(X86) folder, there should not be java folder.
Step4: Install java again.
Step5: Go to cmd and type "java -version" Result: it will display the java version which is installed in your machine.
Step6: now delete all the files which are in C:/User/AdminOrUserNameofYourMachine/.m2 folder
Step6: go to cmd and run "mvn -v" Result: It will display the Apache maven version installed on your machine
Step7: Now Rebuild your project.
This worked for me.
@Warren and @DCookie have covered the solution, one thing to emphasise is the use of tnsping
. You can use this to prove your TNSNames is correct before attempting to connect.
Once you have set up tnsnames correctly you could use ODBC or try TOra which will use your native oracle connection. TOra or something similar (TOAD, SQL*Plus etc) will prove invaluable in debugging and improving your SQL.
Last but not least when you eventually connect with ASP.net remember that you can use the Oracle data connection libraries. See Oracle.com for a host of resources.
An iterative function to free your list:
void freeList(struct node* head)
{
struct node* tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
What the function is doing is the follow:
check if head
is NULL, if yes the list is empty and we just return
Save the head
in a tmp
variable, and make head
point to the next node on your list (this is done in head = head->next
free(tmp)
variable, and head
just points to the rest of the list, go back to step 1 PHP sends headers automatically if set up to use internal encoding:
ini_set('default_charset', 'utf-8');
I furiously read all of this page, hoping to find a solution for:
"configure: error: C compiler cannot create executables"
In the end nothing worked, because my problem was a "typing" one, and was related to CFLAGS. In my .bash_profile file I had:
export ARM_ARCH="arm64”
export CFLAGS="-arch ${ARM_ARCH}"
As you can observe --- export ARM_ARCH="arm64” --- the last quote sign is not the same with the first quote sign. The first one ( " ) is legal while the second one ( ” ) is not.
This happended because I made the mistake to use TextEdit (I'm working under MacOS), and this is apparently a feature called SmartQuotes: the quote sign CHANGES BY ITSELF TO THE ILLEGAL STYLE whenever you edit something just next to it.
Lesson learned: use a proper text editor...
Be carefull (concerning the answer just below)...That's only true because 123 is between -5 and 256...
In [111]: q = 257
In [112]: id(q)
Out[112]: 140020248465168
In [113]: w = 257
In [114]: id(w)
Out[114]: 140020274622544
In [115]: id(257)
Out[115]: 140020274622768
In my case i had to load images on radio button click,
I just uses the regular onclick
event and it worked for me.
<input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion" onclick="return get_images(this, {{color.id}})">
<script>
function get_images(obj, color){
console.log($("input[type='radio'][name='colors']:checked").val());
}
</script>
You may want to try jQuery dialog method:
$( ".selector" ).dialog( "moveToTop" );
Declaring objects in the smallest scope improve readability.
Performance doesn't matter for today's compilers.(in this scenario)
From a maintenance perspective, 2nd option is better.
Declare and initialize variables in the same place, in the narrowest scope possible.
As Donald Ervin Knuth told:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"
i.e) situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing.
I have this code:
<html>_x000D_
<head>_x000D_
<SCRIPT type=text/javascript>_x000D_
function deshabilitarBoton() { _x000D_
document.getElementById("boton").style.display = 'none';_x000D_
document.getElementById("envio").innerHTML ="<br><img src='img/loading.gif' width='16' height='16' border='0'>Generando..."; _x000D_
return true;_x000D_
} _x000D_
</SCRIPT>_x000D_
<title>untitled</title>_x000D_
</head>_x000D_
<body>_x000D_
<form name="form" action="ok.do" method="post" >_x000D_
<table>_x000D_
<tr>_x000D_
<td>Fecha inicio:</td>_x000D_
<td><input type="TEXT" name="fecha_inicio" id="fecha_inicio" /></td>_x000D_
</tr>_x000D_
</table>_x000D_
<div id="boton">_x000D_
<input type="submit" name="event" value="Enviar" class="button" onclick="return deshabilitarBoton()" />_x000D_
</div>_x000D_
<div id="envio">_x000D_
</div>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
Today I had this same problem with another jar. I tried multiple things people said on Stackoverflow, but nothing worked. Eventually I did this:
Now it works again for me. Perhaps this solves the problem for someone else too.
this may help you.
In .cs page,
//Declare a string
public string usertypeurl = "";
//check who is the user
//place your code to check who is the user
//if it is admin
usertypeurl = "help/AdminTutorial.html";
//if it is other
usertypeurl = "help/UserTutorial.html";
In .aspx age pass this variabe
<a href='<%=usertypeurl%>'>Tutorial</a>
I think you're reading those stats incorrectly. They show that Python is up to about 400 times slower than C++ and with the exception of a single case, Python is more of a memory hog. When it comes to source size though, Python wins flat out.
My experiences with Python show the same definite trend that Python is on the order of between 10 and 100 times slower than C++ when doing any serious number crunching. There are many reasons for this, the major ones being: a) Python is interpreted, while C++ is compiled; b) Python has no primitives, everything including the builtin types (int, float, etc.) are objects; c) a Python list can hold objects of different type, so each entry has to store additional data about its type. These all severely hinder both runtime and memory consumption.
This is no reason to ignore Python though. A lot of software doesn't require much time or memory even with the 100 time slowness factor. Development cost is where Python wins with the simple and concise style. This improvement on development cost often outweighs the cost of additional cpu and memory resources. When it doesn't, however, then C++ wins.
Another option would be:
SELECT * FROM [Village] WHERE PATINDEX('foo', [CastleType]) <> 0
How about this :
@client = TinyTds::Client.new(
:adapter => 'mysql2',
:host => 'host',
:database => 'siteconfig_development',
:username => 'username',
:password => 'password'
sql = "SELECT * FROM users"
result = @client.execute(sql)
results.each do |row|
puts row[0]
end
You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record
That work fine in Ajax call back to update select from JSON object
function UpdateList() {
var lsUrl = '@Url.Action("Action", "Controller")';
$.get(lsUrl, function (opdata) {
$.each(opdata, function (key, value) {
$('#myselect').append('<option value=' + key + '>' + value + '</option>');
});
});
}
You can use the os/signal package to handle incoming signals. Ctrl+C is SIGINT, so you can use this to trap os.Interrupt
.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func(){
for sig := range c {
// sig is a ^C, handle it
}
}()
The manner in which you cause your program to terminate and print information is entirely up to you.
Use the ViewPager.onPageChangeListener
:
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
}
});
PycURL does this beautifully.
Below is a short example. It will throw a pycurl.error
if something is fishy, where you get a tuple with error code and a human readable message.
import pycurl
curl = pycurl.Curl()
curl.setopt(pycurl.CAINFO, "myFineCA.crt")
curl.setopt(pycurl.SSL_VERIFYPEER, 1)
curl.setopt(pycurl.SSL_VERIFYHOST, 2)
curl.setopt(pycurl.URL, "https://internal.stuff/")
curl.perform()
You will probably want to configure more options, like where to store the results, etc. But no need to clutter the example with non-essentials.
Example of what exceptions might be raised:
(60, 'Peer certificate cannot be authenticated with known CA certificates')
(51, "common name 'CN=something.else.stuff,O=Example Corp,C=SE' does not match 'internal.stuff'")
Some links that I found useful are the libcurl-docs for setopt and getinfo.
In Swift 4 you can set the border color and width to UIControls using below code.
let yourColor : UIColor = UIColor( red: 0.7, green: 0.3, blue:0.1, alpha: 1.0 )
yourControl.layer.masksToBounds = true
yourControl.layer.borderColor = yourColor.CGColor
yourControl.layer.borderWidth = 1.0
< Swift 4, You can set UIView's border width and border color using the below code.
yourView.layer.borderWidth = 1
yourView.layer.borderColor = UIColor.red.cgColor
One way is to get the entries array, sort it, and then create a new Map with the sorted array:
let ar = [...myMap.entries()];
sortedArray = ar.sort();
sortedMap = new Map(sortedArray);
But if you don't want to create a new object, but to work on the same one, you can do something like this:
// Get an array of the keys and sort them
let keys = [...myMap.keys()];
sortedKeys = keys.sort();
sortedKeys.forEach((key)=>{
// Delete the element and set it again at the end
const value = this.get(key);
this.delete(key);
this.set(key,value);
})
The solutions so far use ls
. Here's an all bash solution:
#!/bin/bash
shopt -s nullglob dotglob # To include hidden files
files=(/some/dir/*)
if [ ${#files[@]} -gt 0 ]; then echo "huzzah"; fi
A more general approach that will attempt to check for both integers and integers given as strings will be
def isInt(anyNumberOrString):
try:
int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
return True
except ValueError :
return False
isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True
public static void main(String[] args) {
final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
"<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
"<role>Developer</role><gen>Male</gen></Emp>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( xmlStr )) );
} catch (Exception e) {
e.printStackTrace();
}
}
Extract all gz files in current directory and its subdirectories:
find . -name "*.gz" | xargs gunzip
If the numbers you want to choose from are not consecutive, you can use random()
.
Usage:
val list = listOf(3, 1, 4, 5)
val number = list.random()
Returns one of the numbers which are in the list.
here's how:
import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()
PS C:\Users\Rack> systeminfo | findstr "System Memory"
System Boot Time: 5/5/2016, 11:10:41 PM
System Manufacturer: VMware, Inc.
System Model: VMware Virtual Platform
System Type: x64-based PC
System Directory: C:\Windows\system32
System Locale: en-us;English (United States)
Total Physical Memory: 40,959 MB
Available Physical Memory: 36,311 MB
Virtual Memory: Max Size: 45,054 MB
Virtual Memory: Available: 41,390 MB
Virtual Memory: In Use: 3,664 MB
This is what I did to fix the problem:
$sudo mkdir -p /data/db
$export PATH=/usr/local/Cellar/mongodb/3.0.7/bin:$PATH
$sudo chown -R id -u
/data/db
and then to start mongo...
$mongod
At the moment, Apple has not opened any access to the embedded NFC chip to developers as suggested by many articles such as these ones :
The list goes on. The main reason seems (like lots the other hardware features added to the iPhone in the past) that Apple wants to ensure the security of such technology before releasing any API for developers to let them do whatever they want. So at first, they will use it internally for their needs only (such as Apple Pay at launch time).
"At the moment, there isn't any open access to the NFC controller," said RapidNFC, a provider of NFC tags. "There are currently no NFC APIs in the iOS 8 GM SDK".
But eventually, I think we can all agree that they will develop such API, it's only a matter of time.
The options object can be added to the chart when the new Chart object is created.
var chart1 = new Chart(canvas, {
type: "pie",
data: data,
options: {
legend: {
display: false
},
tooltips: {
enabled: false
}
}
});
The following worked for me:
$("[id=attached_docs][value=123]")
Simple way to switch wifi on non-rooted devices is to use simple app:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager wfm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
try {
wfm.setWifiEnabled(Boolean.parseBoolean(getIntent().getStringExtra("wifi")));
} catch (Exception e) {
}
System.exit(0);
}
}
AndroidManifest.xml:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
ADB commands:
$ adb shell am start -n org.mytools.config/.MainActivity -e wifi true
$ adb shell am start -n org.mytools.config/.MainActivity -e wifi false
Please check if the python version you are using is also 64 bit. If not then that could be the issue. You would be using a 32 bit python version and would have installed a 64 bit binaries for the OPENCV library.
Here is an example :
=begin
print "Give me a number:"
number = gets.chomp.to_f
total = number * 10
puts "The total value is : #{total}"
=end
Everything you place in between =begin
and =end
will be treated as a comment regardless of how many lines of code it contains between.
Note: Make sure there is no space between =
and begin
:
=begin
= begin
just get postman from https://www.getpostman.com/docs/environments give it the file location with /test/test/1/_bulk?pretty command.
try {
query = URLEncoder.encode(query, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Just comment out the whole "User for advanced features" and "Advanced phpMyAdmin features" code blocks in config.inc.php
.
I find out a possible method by "filter" and "alias" of PowerShell, when you want use grep in pipeline output(grep file should be similar):
first define a filter:
filter Filter-Object ([string]$pattern)
{
Out-String -InputObject $_ -Stream | Select-String -Pattern "$pattern"
}
then define alias:
New-Alias -Name grep -Value Filter-Object
final, put the former filter and alias in your profile:
$Home[My ]Documents\PowerShell\Microsoft.PowerShell_profile.ps1
Restart your PS, you can use it:
alias | grep 'grep'
==================================================================
relevent Reference
alias: Set-Aliasenter link description here New-Aliasenter link description here
Filter(Special function)enter link description here
Profiles(just like .bashrc for bash):enter link description here
out-string(this is the key)enter link description here:in PowerShell Output is object-basedenter link description here,so the key is convert object to string and grep the string.
Select-Stringenter link description here:Finds text in strings and files
This code should do what you are after, I haven't generalised it for n by n, but that is straight forward. That said - I agree with MusiGenesis, using another object that is a little better suited to this (especially if you intend to do any sort of binding)
(I found the code here)
string[][] array = new string[3][];
array[0] = new string[3] { "apple", "apple", "apple" };
array[1] = new string[3] { "banana", "banana", "dog" };
array[2] = new string[3] { "cat", "hippo", "cat" };
for (int i = 0; i < 3; i++)
{
Console.WriteLine(String.Format("{0} {1} {2}", array[i][0], array[i][1], array[i][2]));
}
int j = 2;
Array.Sort(array, delegate(object[] x, object[] y)
{
return (x[j] as IComparable).CompareTo(y[ j ]);
}
);
for (int i = 0; i < 3; i++)
{
Console.WriteLine(String.Format("{0} {1} {2}", array[i][0], array[i][1], array[i][2]));
}
If you have some changes on your workspace and you want to stash them into a new branch use this command:
git stash branch branchName
It will make:
- a new branch
- move changes to this branch
- and remove latest stash (Like: git stash pop)
If the string you're pulling in happens to be a hex number such as E01, then Excel will translate it as 0 even if you use the CStr function, and even if you first deposit it in a String variable type. One way around the issue is to append ' to the beginning of the value.
For example, when pulling values out of a Word table, and bringing them to Excel:
strWr = "'" & WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:
Make a bash (shell) script version of your .bat file (like other
answers, with \
changed to /
in file paths). For example:
# File "example.command":
#!/bin/bash
java -cp ".;./supportlibraries/Framework_Core.jar; ...etc.
Then rename it to have the Mac OS file extension .command
.
That should make the script run using the Terminal app.
If the app user is going to use a bash script version of the file on Linux
or run it from the command line, they need to add executable rights
(change mode bits) using this command, in the folder that has the file:
chmod +rx [filename].sh
#or:# chmod +rx [filename].command
The forum page question:
Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.
Info from some answers after the question:
Write a shell script, and give it the extension ".command". For example:
#!/bin/bash printf "Hello World\n"
- Mar 23, 2010, Tony T1.
The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.However, OS X adds the feature that if you give the file the suffix
.command
, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]#!/bin/sh echo Hello World
- Mar 23, 2010, J D McIninch.
Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:
On mac, there is a specific extension for executing shell
scripts by double clicking them: this is.command
.
Note that with | char, you can get a warning with your IDE, for exemple I get warning with the last version of IntelliJ, So the best solution it's to use this syntax:
th:text="${'static_content - ' + you_variable}"
if you want to check the difference in a time between two dates, you can simply check if second timezone is lesser or greater from your first desired timezone and subtract or add a time.
const currTimezone = new Date().getTimezoneOffset(); // your timezone
const newDateTimezone = date.getTimezoneOffset(); // date with unknown timezone
if (currTimezone !== newDateTimezone) {
// and below you are checking if difference should be - or +. It depends on if unknown timezone is lesser or greater than yours
const newTimezone = (currTimezone - newDateTimezone) * (currTimezone > newDateTimezone ? 1 : -1);
date.setTime(date.getTime() + (newTimezone * 60 * 1000));
}
You can try this:
docker inspect --format="{{.Id}}" container_name
This approach is OS independent.
I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.
I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:
[HttpPut]
public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave)
{
if (!ModelState.IsValid)
{
return new JsonResult
{
Data = new { ErrorMessage = "Model is not valid", Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
try
{
MyDbContext db = new MyDbContext();
db.Entry(employeToSave).State = EntityState.Modified;
db.SaveChanges();
DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];
if (employeToSave.Id == user.Id)
{
user.Company = employeToSave.Company;
user.Language = employeToSave.Language;
user.Money = employeToSave.Money;
user.CostCenter = employeToSave.CostCenter;
Session["EmployeLoggin"] = user;
}
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { ErrorMessage = ex.Message, Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
return new JsonResult() { Data = new { Success = true }, };
}
Later in the ajax call I just asked for this property to know if I had an exception:
$.ajax({
url: 'UpdateEmployeeConfig',
type: 'PUT',
data: JSON.stringify(EmployeConfig),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.Success) {
//This is for the example. Please do something prettier for the user, :)
alert('All was really ok');
}
else {
alert('Oups.. we had errors: ' + data.ErrorMessage);
}
},
error: function (request, status, error) {
alert('oh, errors here. The call to the server is not working.')
}
});
Hope this helps. Happy code! :P
To use full power of scp you need to go through next steps:
Then, for example if you have this ~/.ssh/config:
Host test
User testuser
HostName test-site.com
Port 22022
Host prod
User produser
HostName production-site.com
Port 22022
you'll save yourself from password entry and simplify scp syntax like this:
scp -r prod:/path/foo /home/user/Desktop # copy to local
scp -r prod:/path/foo test:/tmp # copy from remote prod to remote test
More over, you will be able to use remote path-completion:
scp test:/var/log/ # press tab twice
Display all 151 possibilities? (y or n)
Update:
For enabling remote bash-completion you need to have bash-shell on both <source>
and <target>
hosts, and properly working bash-completion. For more information see related questions:
How to enable autocompletion for remote paths when using scp?
SCP filename tab completion
select advanced options when Write a message, and choose sound activated
this is My solution
I got it with:
import console
console.clear()
if you want to do it in your script, or if you are in the console just tap clear() and press enter. That works on Pyto on iPhone. It may depend on the console though.
Found this article on net, very relevant to this topic. So posting here.
in below code midpointsList is an ArrayList of waypoints
private String getMapsApiDirectionsUrl(GoogleMap googleMap, LatLng startLatLng, LatLng endLatLng, ArrayList<LatLng> midpointsList) {
String origin = "origin=" + startLatLng.latitude + "," + startLatLng.longitude;
String midpoints = "";
for (int mid = 0; mid < midpointsList.size(); mid++) {
midpoints += "|" + midpointsList.get(mid).latitude + "," + midpointsList.get(mid).longitude;
}
String waypoints = "waypoints=optimize:true" + midpoints + "|";
String destination = "destination=" + endLatLng.latitude + "," + endLatLng.longitude;
String key = "key=AIzaSyCV1sOa_7vASRBs6S3S6t1KofFvDhjohvI";
String sensor = "sensor=false";
String params = origin + "&" + waypoints + "&" + destination + "&" + sensor + "&" + key;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;
Log.e("url", url);
parseDirectionApidata(url, googleMap);
return url;
}
Then copy and paste this url in your browser to check And the below code is to parse the url
private void parseDirectionApidata(String url, final GoogleMap googleMap) {
final JSONObject jsonObject = new JSONObject();
try {
AppUtill.getJsonWithHTTPPost(ViewMapActivity.this, 1, new ServiceCallBack() {
@Override
public void serviceCallBack(int id, JSONObject jsonResult) throws JSONException {
if (jsonResult != null) {
Log.e("jsonRes", jsonResult.toString());
String status = jsonResult.optString("status");
if (status.equalsIgnoreCase("ok")) {
drawPath(jsonResult, googleMap);
}
} else {
Toast.makeText(ViewMapActivity.this, "Unable to parse Directions Data", Toast.LENGTH_LONG).show();
}
}
}, url, jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
}
And then pass the result to the drawPath method
public void drawPath(JSONObject jObject, GoogleMap googleMap) {
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
List<LatLng> list = null;
try {
Toast.makeText(ViewMapActivity.this, "Drawing Path...", Toast.LENGTH_SHORT).show();
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
list = decodePoly(polyline);
}
Log.e("list", list.toString());
routes.add(path);
Log.e("routes", routes.toString());
if (list != null) {
Polyline line = googleMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#FF0000"))//Google maps blue color #05b1fb
.geodesic(true)
);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
decode poly function is to decode the points(lat and long) provided by Directions API in encoded form
The previous answers assume that there is an incrementing integer ID column, so MAX(ID)
gives the last row. But sometimes the keys are of text type, not ordered in a predictable way. So in order to take the last 1 or N rows (#Nrows#) we can follow a different approach:
Select * From [#TableName#] LIMIT #Nrows# offset cast((SELECT count(*) FROM [#TableName#]) AS INT)- #Nrows#
Try This,
public View getView(final int position, View convertView,ViewGroup parent)
{
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = (LinearLayout)inflater.inflate(R.layout.YOUR_LAYOUT, null);
}
Button Button1= (Button) convertView .findViewById(R.id.BUTTON1_ID);
Button1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// Your code that you want to execute on this button click
}
});
return convertView ;
}
It may help you....
I wanted to pick up specific links within a DOM element on a page, send those users to a redirect page on a timer and then pass them onto the original clicked URL. This is how I did it using regular javascript incorporating one of the methods above.
Page with links: Head
function replaceLinks() {
var content = document.getElementById('mainContent');
var nodes = content.getElementsByTagName('a');
for (var i = 0; i < document.getElementsByTagName('a').length; i++) {
{
href = nodes[i].href;
if (href.indexOf("thisurl.com") != -1) {
nodes[i].href="http://www.thisurl.com/redirect.aspx" + "?url=" + nodes[i];
nodes[i].target="_blank";
}
}
}
}
Body
<body onload="replaceLinks()">
Redirect page Head
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
function delayer(){
window.location = getQueryVariable('url')
}
Body
<body onload="setTimeout('delayer()', 1000)">
Short answer: Yes, C does implement parameter passing by reference using pointers.
While implementing parameter passing, designers of programming languages use three different strategies (or semantic models): transfer data to the subprogram, receive data from the subprogram, or do both. These models are commonly known as in mode, out mode, and inout mode, correspondingly.
Several models have been devised by language designers to implement these three elementary parameter passing strategies:
Pass-by-Value (in mode semantics) Pass-by-Result (out mode semantics) Pass-by-Value-Result (inout mode semantics) Pass-by-Reference (inout mode semantics) Pass-by-Name (inout mode semantics)
Pass-by-reference is the second technique for inout-mode parameter passing. Instead of copying data back and forth between the main routine and the subprogram, the runtime system sends a direct access path to the data for the subprogram. In this strategy the subprogram has direct access to the data effectively sharing the data with the main routine. The main advantage with this technique is that its absolutely efficient in time and space because there is no need to duplicate space and there is no data copying operations.
Parameter passing implementation in C: C implements pass-by-value and also pass-by-reference (inout mode) semantics using pointers as parameters. The pointer is send to the subprogram and no actual data is copied at all. However, because a pointer is an access path to the data of the main routine, the subprogram may change the data in the main routine. C adopted this method from ALGOL68.
Parameter passing implementation in C++: C++ also implements pass-by-reference (inout mode) semantics using pointers and also using a special kind of pointer, called reference type. Reference type pointers are implicitly dereferenced inside the subprogram but their semantics are also pass-by-reference.
So the key concept here is that pass-by-reference implements an access path to the data instead of copying the data into the subprogram. Data access paths can be explicitly dereferenced pointers or auto dereferenced pointers (reference type).
For more info please refer to the book Concepts of Programming Languages by Robert Sebesta, 10th Ed., Chapter 9.
Try:
CREATE TABLE foo SELECT * FROM bar LIMIT 0
Or:
CREATE TABLE foo SELECT * FROM bar WHERE 1=0
In the CMakeLists.txt file, create a cache variable, as documented here:
SET(FAB "po" CACHE STRING "Some user-specified option")
Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set
Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:
cmake -DFAB:STRING=po
Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue
Modify your cache variable to a boolean if, in fact, your option is boolean.
Here's a version to convert each value in a hex string to it's two's complement version.
In [5159]: twoscomplement('f0079debdd9abe0fdb8adca9dbc89a807b707f')
Out[5159]: '10097325337652013586346735487680959091'
def twoscomplement(hm):
twoscomplement=''
for x in range(0,len(hm)):
value = int(hm[x],16)
if value % 2 == 1:
twoscomplement+=hex(value ^ 14)[2:]
else:
twoscomplement+=hex(((value-1)^15)&0xf)[2:]
return twoscomplement
-Contains
is actually a collection operator. It is true if the collection contains the object. It is not limited to strings.
-match
and -imatch
are regular expression string matchers, and set automatic variables to use with captures.
-like
, -ilike
are SQL-like matchers.
Assuming a modern release, find -newermt
is powerful:
find -newermt '10 minutes ago' ## other units work too, see `Date input formats`
or, if you want to specify a time_t
(seconds since epoch):
find -newermt @1568670245
For reference, -newermt
is not directly listed in the man page for find. Instead, it is shown as -newerXY
, where XY
are placeholders for mt
. Other replacements are legal, but not applicable for this solution.
From man find -newerXY
:
Time specifications are interpreted as for the argument to the -d option of GNU date.
So the following are equivalent to the initial example:
find -newermt "$(date '+%Y-%m-%d %H:%M:%S' -d '10 minutes ago')" ## long form using 'date'
find -newermt "@$(date +%s -d '10 minutes ago')" ## short form using 'date' -- notice '@'
The date -d
(and find -newermt
) arguments are quite flexible, but the documentation is obscure. Here's one source that seems to be on point: Date input formats
You can create a custom loading screen instead of splash screen. if you show a splash screen for 10 sec, it's not a good idea for user experience. So it's better to add a custom loading screen. For a custom loading screen you may need some different images to make that feel like a gif. after that add the images in the res
folder and make a class like this :-
public class LoadingScreen {private ImageView loading;
LoadingScreen(ImageView loading) {
this.loading = loading;
}
public void setLoadScreen(){
final Integer[] loadingImages = {R.mipmap.loading_1, R.mipmap.loading_2, R.mipmap.loading_3, R.mipmap.loading_4};
final Handler loadingHandler = new Handler();
Runnable runnable = new Runnable() {
int loadingImgIndex = 0;
public void run() {
loading.setImageResource(loadingImages[loadingImgIndex]);
loadingImgIndex++;
if (loadingImgIndex >= loadingImages.length)
loadingImgIndex = 0;
loadingHandler.postDelayed(this, 500);
}
};
loadingHandler.postDelayed(runnable, 500);
}}
In your MainActivity, you can pass a to the LoadingScreen class like this :-
private ImageView loadingImage;
Don't forget to add an ImageView in activity_main. After that call the LoadingScreen class like this;
LoadingScreen loadingscreen = new LoadingScreen(loadingImage);
loadingscreen.setLoadScreen();
I hope this will help you
layout_weight
tells Android how to distribute your View
s in a LinearLayout
. Android then first calculates the total proportion required for all View
s that have a weight specified and places each View
according to what fraction of the screen it has specified it needs. In the following example, Android sees that the TextView
s have a layout_weight
of 0
(this is the default) and the EditText
s have a layout_weight
of 2
each, while the Button
has a weight of 1
. So Android allocates 'just enough' space to display tvUsername
and tvPassword
and then divides the remainder of the screen width into 5 equal parts, two of which are allocated to etUsername
, two to etPassword
and the last part to bLogin
:
<LinearLayout android:orientation="horizontal" ...>
<TextView android:id="@+id/tvUsername"
android:text="Username"
android:layout_width="wrap_content" ... />
<EditText android:id="@+id/etUsername"
android:layout_width="0dp"
android:layout_weight="2" ... />
<TextView android:id="@+id/tvPassword"
android:text="Password"
android:layout_width="wrap_content" />
<EditText android:id="@+id/etPassword"
android:layout_width="0dp"
android:layout_weight="2" ... />
<Button android:id="@+id/bLogin"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Login"... />
</LinearLayout>
It looks like:
and