The abstract.xml.gz
dump sounds like the one you want.
I just tried using this code and @psynnott's answer was correct though I needed to know it would work repeatedly, seems to work with jquery 1.7.1 >
I modified the jfiddle to the following http://jsfiddle.net/Rjj9v/109/
$('#mytext').text('');
This is not a new answer @psynnott is correct I am just providing a more concise example that shows the textarea is still working after the clear because if you use .val("") the text area stops working
change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:
data['label'] = data['label'].astype(np.uint8)
here is mine
echo Math+
ECHO First num:
SET /P a=
ECHO Second num:
SET /P b=
set /a s=%a%+%b%
echo Result: %s%
html link example:
<!-- boostrap button + fontawesome icon -->
<a class="btn btn-primary" id="BT_Download" target="_blank" href="DownloadDoc?Id=32">
<i class="icon-file-text icon-large"></i>
Download Document
</a>
use this in jQuery
$('#BT_Download').attr('disabled',true);
add this to css :
a[disabled="disabled"] {
pointer-events: none;
}
If you have downloaded pio-3.17 On eclipse: right click on the project folder -> build path -> configure build path -> libraries -> add external jars -> add all the commons jar file from the "lib". It's worked for me.
Login to virtual machine use below command to check ip address. (anyone will work)
If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1
If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
I don't have IE8 to test this out, but I'm pretty sure it should work:
<div class="screen">
<!-- code -->
<div class="innerdiv">
text or other content
</div>
</div>
and the css:
.screen{
position: relative;
}
.innerdiv {
position: absolute;
bottom: 0;
right: 0;
}
This should place the .innerdiv in the bottom-right corner of the .screen class. I hope this helps :)
It should run properly at cron also. Please check below things.
1- You are editing proper file to set cron.
2- You have given proper permission(execute permission) to script mean your script is executable.
As of 2017, it's just brew install r
. See @Andrew's answer below.
As of 2014 (using an Yosemite), the method is the following:
brew tap homebrew/science
brew install Caskroom/cask/xquartz
brew install r
The gcc
package (will be installed automatically as a required dependency) in the homebrew/science
tap already contains the latest fortran compiler (gfortran
), and most of all: the whole package is precompiled so it saves you a lot of compilation time.
This answer will also work for El Capitan and Mac OS Sierra.
In case you don't have XCode Command Line Tools (CLT), run from terminal:
xcode-select --install
Of course! jQuery is just a library that utilizes javascript after all.
You can use document.getElementById to get the element in question, then change its height accordingly, through element.style.height.
elementToChange = document.getElementById('collapseableEl');
elementToChange.style.height = '100%';
Wrap that up in a neat little function that caters for toggling back and forth and you have yourself a solution.
**Production build with
- Angular Rc5
- Gulp
- typescripts
- systemjs**
1)con-cat all js files and css files include on index.html using "gulp-concat".
- styles.css (all css concat in this files)
- shims.js(all js concat in this files)
2)copy all images and fonts as well as html files with gulp task to "/dist".
3)Bundling -minify angular libraries and app components mentioned in systemjs.config.js file.
Using gulp 'systemjs-builder'
SystemBuilder = require('systemjs-builder'),
gulp.task('system-build', ['tsc'], function () {
var builder = new SystemBuilder();
return builder.loadConfig('systemjs.config.js')
.then(function () {
builder.buildStatic('assets', 'dist/app/app_libs_bundle.js')
})
.then(function () {
del('temp')
})
});
4)Minify bundles using 'gulp-uglify'
jsMinify = require('gulp-uglify'),
gulp.task('minify', function () {
var options = {
mangle: false
};
var js = gulp.src('dist/app/shims.js')
.pipe(jsMinify())
.pipe(gulp.dest('dist/app/'));
var js1 = gulp.src('dist/app/app_libs_bundle.js')
.pipe(jsMinify(options))
.pipe(gulp.dest('dist/app/'));
var css = gulp.src('dist/css/styles.min.css');
return merge(js,js1, css);
});
5) In index.html for production
<html>
<head>
<title>Hello</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8" />
<link rel="stylesheet" href="app/css/styles.min.css" />
<script type="text/javascript" src="app/shims.js"></script>
<base href="/">
</head>
<body>
<my-app>Loading...</my-app>
<script type="text/javascript" src="app/app_libs_bundle.js"></script>
</body>
</html>
6) Now just copy your dist folder to '/www' in wamp server node need to copy node_modules in www.
You can use nonzero function. it returns the nonzero indices of the given input.
Easy Way
>>> (e > 15).nonzero()
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
to see the indices more cleaner, use transpose
method:
>>> numpy.transpose((e>15).nonzero())
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Not Bad Way
>>> numpy.nonzero(e > 15)
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
or the clean way:
>>> numpy.transpose(numpy.nonzero(e > 15))
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
For those using npm to install packages, you can install jquery via npm install jquery
and then use elixir to compile jquery and your other npm packages into one file (e.g. vendor.js). Here's a sample gulpfile.js
var elixir = require('laravel-elixir');
elixir(function(mix) {
mix
.scripts([
'jquery/dist/jquery.min.js',
// list your other npm packages here
],
'public/js/vendor.js', // 2nd param is the output file
'node_modules') // 3rd param is saying "look in /node_modules/ for these scripts"
.scripts([
'scripts.js' // your custom js file located in default location: /resources/assets/js/
], 'public/js/app.js') // looks in default location since there's no 3rd param
.version([ // optionally append versioning string to filename
'js/vendor.js', // compiled files will be in /public/build/js/
'js/app.js'
]);
});
Can refer to here: https://ss64.com/nt/start.html
start "" /D F:\- Big Packets -\kitterengine\Common\ /W Template.bat
Go to Eclipse Menu --> Window ==> Show View ==> Variables
This should bring back your variables window in eclipse
Find the Run button present on the top of the Eclipse, then select Run Configuration -> Arguments, in VM arguments section just mention the heap size you want to extend as below:
-Xmx1024m
vfork()
is an obsolete optimization. Before good memory management, fork()
made a full copy of the parent's memory, so it was pretty expensive. since in many cases a fork()
was followed by exec()
, which discards the current memory map and creates a new one, it was a needless expense. Nowadays, fork()
doesn't copy the memory; it's simply set as "copy on write", so fork()
+exec()
is just as efficient as vfork()
+exec()
.
clone()
is the syscall used by fork()
. with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.
"background-size: cover;" causes a lot of issues on all mobile browsers except Firefox!
This fixed my issue:
/* Mobile first */
body{
background-image: url(bg_mobile.jpg);
background-attachment: fixed;
background-repeat: no-repeat;
}
/* Then tablets, laptops and desktops (768px and up) */
@media screen and (min-width:768px) {
body{
background-image: url(bg.jpg);
background-size: cover;
}
}
Try this formula:
=SUBSTITUTE(TEXT(A1/B1,"?/?"),"/",":")
Result:
A B C
33 11 3:1
25 5 5:1
6 4 3:2
Explanation:
This doesn't require any special toolkits or macros. The only downside might be that the result is considered text--not a number--so you can easily use it for further calculations.
Note: as @Robin Day suggested, increase the number of question marks (?) as desired to reduce rounding (thanks Robin!).
Use either of the Map
implementations bundled with Java 6 and later that implement NavigableMap
(the successor to SortedMap
):
TreeMap
if running single-threaded, or if the map is to be read-only across threads after first being populated. ConcurrentSkipListMap
if manipulating the map across threads.NavigableMap
FYI, the SortedMap
interface was succeeded by the NavigableMap
interface.
You would only need to use SortedMap
if using 3rd-party implementations that have not yet declared their support of NavigableMap
. Of the maps bundled with Java, both of the implementations that implement SortedMap
also implement NavigableMap
.
s SortedMap the best answer? TreeMap?
As others mentioned, SortedMap
is an interface while TreeMap
is one of multiple implementations of that interface (and of the more recent NavigableMap
.
Having an interface allows you to write code that uses the map without breaking if you later decide to switch between implementations.
NavigableMap< Employee , Project > currentAssignments = new TreeSet<>() ;
currentAssignments.put( alice , writeAdCopyProject ) ;
currentAssignments.put( bob , setUpNewVendorsProject ) ;
This code still works if later change implementations. Perhaps you later need a map that supports concurrency for use across threads. Change that declaration to:
NavigableMap< Employee , Project > currentAssignments = new ConcurrentSkipListMap<>() ;
…and the rest of your code using that map continues to work.
There are ten implementations of Map
bundled with Java 11. And more implementations provided by 3rd parties such as Google Guava.
Here is a graphic table I made highlighting the various features of each. Notice that two of the bundled implementations keep the keys in sorted order by examining the key’s content. Also, EnumMap
keeps its keys in the order of the objects defined on that enum. Lastly, the LinkedHashMap
remembers original insertion order.
Use this :
<div style="width:700px; background:#F2F2F2">
<table style="width:100%;padding: 25px; margin: 0 auto; font-family:'Open Sans', 'Helvetica', 'Arial';">
<tr align="center" style="margin: 0; padding: 0;">
<td>
<table style="width:100%;border-style:solid; border-width:2px; border-color: #c3d2d9;" cellspacing="0">
<tr style="background-color: white;">
<td style=" padding: 10px 15px 10px 15px; color: #000000;">
<p>Some content here</p>
<span style="font-weight: bold;">My Signature</span><br/>
My Title<br/>
My Company<br/>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
I have also faced this problem in my project. AVD is not able to reload assets,lib,res and etc folder contexts.
problem :
Dex Loader] Unable to execute dex: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl
.
Then,I created new projects and copied MainActivity.java
,activity_main.xml
, drawable context.
Then delete old project from package explore,restart your Eclipse and AVD.
My project is now working properly.... :)
I hope this steps will help u little bit folks..!!
Microsoft says the SQL Server 2005 it's not compatible with Windows 8, but I've run it without problems (only using SP3) except the installation.
After you run the install file SQLExpr.exe
look for a hidden folder recently created in the C drive. Copy the contents to another folder and cancel the installer (or use WinRar to open the file and extract the contents to a temp folder)
After that, find the file sqlncli_x64.msi
in the setup folder, and run it.
Now you are ready the run the setup.exe
file and install SQL server 2005 without errors
The command line tool ExifTool by Phil Harvey works with dozens of images formats - including plenty of proprietary RAW formats - and can manipulate a variety of metadata formats including EXIF, GPS, IPTC, XMP, JFIF.
Very easy to use, lightweight, impressive application.
To do links, you can do
.social h2 a:link {
color: pink;
font-size: 14px;
}
You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.
If you want to use Unix shell commands on Windows, you can use Windows Powershell, which includes both Windows and Unix commands as aliases. You can find more info on it in the documentation.
PowerShell supports aliases to refer to commands by alternate names. Aliasing allows users with experience in other shells to use common command names that they already know for similar operations in PowerShell.
The PowerShell equivalents may not produce identical results. However, the results are close enough that users can do work without knowing the PowerShell command name.
Update: I took your saying "click" literally, which was a bit dumb of me. You can substitute focus
for click
in all of the below if you also want the action to happen when the user tabs to the input, which seems likely.
Update 2: My guess is that you're looking to do placeholders; see note and example at the end.
Original answer:
You can do this:
$("selector_for_the_input").click(function() {
this.value = '';
});
...but that will clear the text regardless of what it is. If you only want to clear it if it's a specific value:
$("selector_for_the_input").click(function() {
if (this.value === "TEXT") {
this.value = '';
}
});
So for example, if the input has an id
, you could do:
$("#theId").click(function() {
if (this.value === "TEXT") {
this.value = '';
}
});
Or if it's in a form with an id
(say, "myForm") and you want to do this for every form field:
$("#myForm input").click(function() {
if (this.value === "TEXT") {
this.value = '';
}
});
You may also be able to do it with delegation:
$("#myForm").delegate("input", "click", function() {
if (this.value === "TEXT") {
this.value = '';
}
});
That uses delegate
to hook up a handler on the form but apply it to the inputs on the form, rather than hooking up a handler to each individual input.
If you're trying to do placeholders, there's more to it than that and you may want to find a good plug-in to do it. But here's the basics:
HTML:
<form id='theForm'>
<label>Field 1:
<input type='text' value='provide a value for field 1'>
</label>
<br><label>Field 2:
<input type='text' value='provide a value for field 2'>
</label>
<br><label>Field 3:
<input type='text' value='provide a value for field 3'>
</label>
</form>
JavaScript using jQuery:
jQuery(function($) {
// Save the initial values of the inputs as placeholder text
$('#theForm input').attr("data-placeholdertext", function() {
return this.value;
});
// Hook up a handler to delete the placeholder text on focus,
// and put it back on blur
$('#theForm')
.delegate('input', 'focus', function() {
if (this.value === $(this).attr("data-placeholdertext")) {
this.value = '';
}
})
.delegate('input', 'blur', function() {
if (this.value.length == 0) {
this.value = $(this).attr("data-placeholdertext");
}
});
});
Of course, you can also use the new placeholder
attribute from HTML5 and only do the above if your code is running on a browser that doesn't support it, in which case you want to invert the logic I used above:
HTML:
<form id='theForm'>
<label>Field 1:
<input type='text' placeholder='provide a value for field 1'>
</label>
<br><label>Field 2:
<input type='text' placeholder='provide a value for field 2'>
</label>
<br><label>Field 3:
<input type='text' placeholder='provide a value for field 3'>
</label>
</form>
JavaScript with jQuery:
jQuery(function($) {
// Is placeholder supported?
if ('placeholder' in document.createElement('input')) {
// Yes, no need for us to do it
display("This browser supports automatic placeholders");
}
else {
// No, do it manually
display("Manual placeholders");
// Set the initial values of the inputs as placeholder text
$('#theForm input').val(function() {
if (this.value.length == 0) {
return $(this).attr('placeholder');
}
});
// Hook up a handler to delete the placeholder text on focus,
// and put it back on blur
$('#theForm')
.delegate('input', 'focus', function() {
if (this.value === $(this).attr("placeholder")) {
this.value = '';
}
})
.delegate('input', 'blur', function() {
if (this.value.length == 0) {
this.value = $(this).attr("placeholder");
}
});
}
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
(Kudos to diveintohtml5.ep.io for the placholder
feature-detection code.)
try this:
public int getIndexOfMin(List<Float> data) {
float min = Float.MAX_VALUE;
int index = -1;
for (int i = 0; i < data.size(); i++) {
Float f = data.get(i);
if (Float.compare(f.floatValue(), min) < 0) {
min = f.floatValue();
index = i;
}
}
return index;
}
Thread.currentThread().isInterrupted() is superbly working. but this code is only pause the timer.
This code is stop and reset the thread timer. h1 is handler name. This code is add on inside your button click listener. w_h =minutes w_m =milli sec i=counter
i=0;
w_h = 0;
w_m = 0;
textView.setText(String.format("%02d", w_h) + ":" + String.format("%02d", w_m));
hl.removeCallbacksAndMessages(null);
Thread.currentThread().isInterrupted();
}
});
}`
You can use the #Requires
statement (supports modules from PowerShell 3.0).
The #Requires statement prevents a script from running unless the PowerShell version, modules, snap-ins, and module and snap-in version prerequisites are met.
So At the top of the script, simply add #Requires -Module <ModuleName>
If the required modules are not in the current session, PowerShell imports them.
If the modules cannot be imported, PowerShell throws a terminating error.
Also you can do something like:
scp foo@bar:"\"apath/with spaces in it/\""
The first level of quotes will be interpreted by scp and then the second level of quotes will preserve the spaces.
This works fine in bash
:
END=5
i=1 ; while [[ $i -le $END ]] ; do
echo $i
((i = i + 1))
done
file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.
See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins
Problem:
Your View
cannot be found in default locations.
Explanation:
Views should be in the same folder named as the Controller
or in the Shared
folder.
Solution:
Either move your View
to the MyAccount
folder or create a HomeController
.
Alternatives:
If you don't want to move your View
or create a new Controller
you can check at this link.
There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).
Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.
Now write down the new SA password.
No posters have mentioned the contraction of floating expressions yet (ISO C standard, 6.5p8 and 7.12.2). If the FP_CONTRACT
pragma is set to ON
, the compiler is allowed to regard an expression such as a*a*a*a*a*a
as a single operation, as if evaluated exactly with a single rounding. For instance, a compiler may replace it by an internal power function that is both faster and more accurate. This is particularly interesting as the behavior is partly controlled by the programmer directly in the source code, while compiler options provided by the end user may sometimes be used incorrectly.
The default state of the FP_CONTRACT
pragma is implementation-defined, so that a compiler is allowed to do such optimizations by default. Thus portable code that needs to strictly follow the IEEE 754 rules should explicitly set it to OFF
.
If a compiler doesn't support this pragma, it must be conservative by avoiding any such optimization, in case the developer has chosen to set it to OFF
.
GCC doesn't support this pragma, but with the default options, it assumes it to be ON
; thus for targets with a hardware FMA, if one wants to prevent the transformation a*b+c
to fma(a,b,c), one needs to provide an option such as -ffp-contract=off
(to explicitly set the pragma to OFF
) or -std=c99
(to tell GCC to conform to some C standard version, here C99, thus follow the above paragraph). In the past, the latter option was not preventing the transformation, meaning that GCC was not conforming on this point: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=37845
The key elements include:
class="nav nav-tabs"
and data-tabs="tabs"
of ul
data-toggle="tab"
and href="#orange"
of the a
class="tab-content"
of the div
of the contentclass="tab-pane"
and id
of the div of the itemsThe complete code is as below:
<ul class="nav nav-tabs" data-tabs="tabs">
<li class="active"><a data-toggle="tab" href="#red">Red</a></li>
<li><a data-toggle="tab" href="#orange">Orange</a></li>
<li><a data-toggle="tab" href="#yellow">Yellow</a></li>
<li><a data-toggle="tab" href="#green">Green</a></li>
<li><a data-toggle="tab" href="#blue">Blue</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="red">
<h1>Red</h1>
<p>red red red red red red</p>
</div>
<div class="tab-pane" id="orange">
<h1>Orange</h1>
<p>orange orange orange orange orange</p>
</div>
<div class="tab-pane" id="yellow">
<h1>Yellow</h1>
<p>yellow yellow yellow yellow yellow</p>
</div>
<div class="tab-pane" id="green">
<h1>Green</h1>
<p>green green green green green</p>
</div>
<div class="tab-pane" id="blue">
<h1>Blue</h1>
<p>blue blue blue blue blue</p>
</div>
</div>
use DataTable object instead:
private void doMore(DataTable dt)
{
foreach(DataColumn dc in dt.Columns)
{
MessageBox.Show(dc.ColumnName);
}
}
You can define your Comparator with your own logic like this;
private static final Comparator<UserResource> sortByLastLogin = (c1, c2) -> {
if (Objects.isNull(c1.getLastLoggedin())) {
return -1;
} else if (Objects.isNull(c2.getLastLoggedin())) {
return 1;
}
return c1.getLastLoggedin().compareTo(c2.getLastLoggedin());
};
And use it inside foreach as:
list.stream()
.sorted(sortCredentialsByLastLogin.reversed())
.collect(Collectors.toList());
First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables.
Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)
Of course, there are many, but the most popular that I've seen in wild are:
Complete list is at http://wiki.python.org/moin/GuiProgramming
Single executable (all platforms)
PyQt
)Single executable (Windows)
Single executable (Linux)
Single executable (Mac)
Here's another way through the GUI that does exactly what your script does even though it goes through Indexes (not Constraints) in the object explorer.
Just an information: let us all remember that the Image
class is actually an abstract class and referencing a variable of this with a BufferedImage only stores or returns any Object's memory adress.
Also, wherefore, static java.awt.image.imageIO
's read()
method returns a BufferedImage
object, therefore no doubt that using operator/expression instanceof BufferedImage
on that object will return true
.
In fact, being abstract, Image
class has such method signatures as:
public abstract Graphics getGraphics()
public abstract ImageProducer getSource()
among others.
I emphasize, an actual Image
variable only holds memory adress of a concrete Image-subclass object, almost like pointers in C, C++, Ada, etc.
If you're introduced or advanced in those languages, and also of Java interface instances like Runnable
, javax.sound.Clip
, AWT's Shape
, etc.. . Take note that Image
has: public abstract Image getScaledInstance(...)
- you get the point. (Of course, scaling in 2D Graphics programming is interchangeable to resizing, for which precision is desirable).
But in an impossible case when herein ImageIO method return ! (instanceof BufferedImage)
just create a new BufferedImage
object with this ImgObjNotInstncfBufImg
apassed to one of its constructor argument. Then, at (rational) will manipulate this in the logic of your code.
Anyways, the Affine Transform class is appropriate for transforming Shapes and Images to thier scaled, rotated, relocated, etc forms, so I recommend you to study about using an "affine transform".
Take note that you can manipulate the actual pixels in such Image's Raster - well another technical 2D Graphics jargon which must be referenced from a technical glossary - which perhaps a excercised skill in Java ways of binary blitwise operations will be needed, in types of Image buffers that store individual color attributes in a compact in of 32-bytes - 7-bits each for the alpha and RGB values.
I suspect your gonna use it in layering images. So, FINALLY, the rational is that you only reference BufferedImage
with the abstract Image, and if ever your Image
object isn't a BufferedImage
one yet, then you can just make an image out of this related-but-non-BufferedImage-instance without having to worry about any conversion, casting, autoboxing or whatever; manipulating a BufferedImage really means manipulating also the underlying root Image data-bearing object that it points to.
Okay, finished; I think I certainly extracted and splintered out what deadlock you may have thought you are facing to. As I have said abstract classes in java, and also interfaces, are very much the equivaleng of the low-level, more-close-to-hardware operators called pointers in other languages.
MSDN has an easy way to perform sorting on columns with up/down glyphs. The example isn't complete, though - they don't explain how to use the data templates for the glyphs. Below is what I got to work with my ListView. This works on .Net 4.
In your ListView, you have to specify an event handler to fire for a click on the GridViewColumnHeader. My ListView looks like this:
<ListView Name="results" GridViewColumnHeader.Click="results_Click">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=ContactName}">
<GridViewColumn.Header>
<GridViewColumnHeader Content="Contact Name" Padding="5,0,0,0" HorizontalContentAlignment="Left" MinWidth="150" Name="ContactName" />
</GridViewColumn.Header>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=PrimaryPhone}">
<GridViewColumn.Header>
<GridViewColumnHeader Content="Contact Number" Padding="5,0,0,0" HorizontalContentAlignment="Left" MinWidth="150" Name="PrimaryPhone"/>
</GridViewColumn.Header>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
In your code behind, set up the code to handle the sorting:
// Global objects
BindingListCollectionView blcv;
GridViewColumnHeader _lastHeaderClicked = null;
ListSortDirection _lastDirection = ListSortDirection.Ascending;
// Header click event
void results_Click(object sender, RoutedEventArgs e)
{
GridViewColumnHeader headerClicked =
e.OriginalSource as GridViewColumnHeader;
ListSortDirection direction;
if (headerClicked != null)
{
if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
{
if (headerClicked != _lastHeaderClicked)
{
direction = ListSortDirection.Ascending;
}
else
{
if (_lastDirection == ListSortDirection.Ascending)
{
direction = ListSortDirection.Descending;
}
else
{
direction = ListSortDirection.Ascending;
}
}
string header = headerClicked.Column.Header as string;
Sort(header, direction);
if (direction == ListSortDirection.Ascending)
{
headerClicked.Column.HeaderTemplate =
Resources["HeaderTemplateArrowUp"] as DataTemplate;
}
else
{
headerClicked.Column.HeaderTemplate =
Resources["HeaderTemplateArrowDown"] as DataTemplate;
}
// Remove arrow from previously sorted header
if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
{
_lastHeaderClicked.Column.HeaderTemplate = null;
}
_lastHeaderClicked = headerClicked;
_lastDirection = direction;
}
}
// Sort code
private void Sort(string sortBy, ListSortDirection direction)
{
blcv.SortDescriptions.Clear();
SortDescription sd = new SortDescription(sortBy, direction);
blcv.SortDescriptions.Add(sd);
blcv.Refresh();
}
And then in your XAML, you need to add two DataTemplates that you specified in the sorting method:
<DataTemplate x:Key="HeaderTemplateArrowUp">
<DockPanel LastChildFill="True" Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewColumnHeader}}}">
<Path x:Name="arrowUp" StrokeThickness="1" Fill="Gray" Data="M 5,10 L 15,10 L 10,5 L 5,10" DockPanel.Dock="Right" Width="20" HorizontalAlignment="Right" Margin="5,0,5,0" SnapsToDevicePixels="True"/>
<TextBlock Text="{Binding }" />
</DockPanel>
</DataTemplate>
<DataTemplate x:Key="HeaderTemplateArrowDown">
<DockPanel LastChildFill="True" Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewColumnHeader}}}">
<Path x:Name="arrowDown" StrokeThickness="1" Fill="Gray" Data="M 5,5 L 10,10 L 15,5 L 5,5" DockPanel.Dock="Right" Width="20" HorizontalAlignment="Right" Margin="5,0,5,0" SnapsToDevicePixels="True"/>
<TextBlock Text="{Binding }" />
</DockPanel>
</DataTemplate>
Using the DockPanel
with LastChildFill
set to true will keep the glyph on the right of the header and let the label fill the rest of the space. I bound the DockPanel
width to the ActualWidth
of the GridViewColumnHeader
because my columns have no width, which lets them autofit to the content. I did set MinWidth
s on the columns, though, so that the glyph doesn't cover up the column title. The TextBlock Text
is set to an empty binding which displays the column name specified in the header.
If you just want a very quick way to debug the result:
$ch = curl_init();
curl_exec($ch);
$curl_error = curl_error($ch);
echo "<script>console.log($curl_error);</script>"
strcat
concats str2
onto str1
You'll get runtime errors because str1
is not being properly allocated for concatenation
Yes. Java doubles will hold their precision better than your given epsilon of 0.00001.
Any rounding error that occurs due to the storage of floating point values will occur smaller than 0.00001. I regularly use 1E-6
or 0.000001 for a double epsilon in Java with no trouble.
On a related note, I like the format of epsilon = 1E-5;
because I feel it is more readable (1E-5 in Java = 1 x 10^-5). 1E-6 is easy to distinguish from 1E-5 when reading code whereas 0.00001 and 0.000001 look so similar when glancing at code I think they are the same value.
You can save it using the Save As dialog using ".something".
I personally made this python code to change the color of a whole image opened or created with openCV . I am sorry if it's not good enough , I am beginner .
def OpenCvImgColorChanger(img,blue = 0,green = 0,red = 0):
line = 1
ImgColumn = int(img.shape[0])-2
ImgRaw = int(img.shape[1])-2
for j in range(ImgColumn):
for i in range(ImgRaw):
if i == ImgRaw-1:
line +=1
img[line][i][2] = int(red)
img[line][i][1] = int(green)
img[line][i][0] = int(blue)
$("#chk0") is refering to an element with the id chk0. You might try adding id's to the elements. Ids are unique even though the names are the same so that in jQuery you can access a single element by it's id.
Tested on Ubuntu:
sudo apt install git-extras
git-show-tree
This produces an effect similar to the 2 most upvoted answers here.
Source: http://manpages.ubuntu.com/manpages/bionic/man1/git-show-tree.1.html
Also, if you have arcanist installed (correction: Uber's fork of arcanist installed--see the bottom of this answer here for installation instructions), arc flow
shows a beautiful dependency tree of upstream dependencies (ie: which were set previously via arc flow new_branch
or manually via git branch --set-upstream-to=upstream_branch
).
git branch
you are on too!"I am an operating system that only allocates you memory in 10mb partitions.
Internal Fragmentation
Fulfilling this request has just led to 3mb of internal fragmentation.
External Fragmentation
Fulfilling this request has just led to external fragmentation
There is another open-source tool that allows you to save all console.log
output in a file on your server - JS LogFlush (plug!).
JS LogFlush is an integrated JavaScript logging solution which include:
- cross-browser UI-less replacement of console.log - on client side.
- log storage system - on server side.
Probably you are requesting for an external resource, this case IE needs the XDomain object. See the sample code below for how to make ajax request for all browsers with cross domains:
Tork.post = function (url,data,callBack,callBackParameter){
if (url.indexOf("?")>0){
data = url.substring(url.indexOf("?")+1)+"&"+ data;
url = url.substring(0,url.indexOf("?"));
}
data += "&randomNumberG=" + Math.random() + (Tork.debug?"&debug=1":"");
var xmlhttp;
if (window.XDomainRequest)
{
xmlhttp=new XDomainRequest();
xmlhttp.onload = function(){callBack(xmlhttp.responseText)};
}
else if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
Tork.msg("Response:"+xmlhttp.responseText);
callBack(xmlhttp.responseText,callBackParameter);
Tork.showLoadingScreen(false);
}
}
xmlhttp.open("POST",Tork.baseURL+url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
In case someone needs a CSS background with different color repeating horizontal stripes, here is how I managed to achieve this:
body {_x000D_
font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;_x000D_
font-size: 13px;_x000D_
}_x000D_
_x000D_
.css-stripes {_x000D_
margin: 0 auto;_x000D_
width: 200px;_x000D_
padding: 100px;_x000D_
text-align: center;_x000D_
/* For browsers that do not support gradients */_x000D_
background-color: #F691FF;_x000D_
/* Safari 5.1 to 6.0 */_x000D_
background: -webkit-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Opera 11.1 to 12.0 */_x000D_
background: -o-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Firefox 3.6 to 15 */_x000D_
background: -moz-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Standard syntax */_x000D_
background-image: repeating-linear-gradient(to top, #F691FF, #EC72A8);_x000D_
background-size: 1px 2px;_x000D_
}
_x000D_
<div class="css-stripes">Hello World!</div>
_x000D_
I'm using a popup to show the map in a new window. I'm using the following url
https://www.google.com/maps?z=15&daddr=LATITUDE,LONGITUDE
HTML snippet
<a target='_blank' href='https://www.google.com/maps?z=15&daddr=${location.latitude},${location.longitude}'>Calculate route</a>
import numpy as np
ImportError: No module named numpy
I got this even though I knew numpy was installed and unsuccessfully tried all the advice above. The fix for me was to remove the as np and directly refer to modules . (python 3.4.8 on Centos) .
import numpy
DataTwo=numpy.stack((OutputListUnixTwo))...
Your bat file could be like:
CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319
msbuild C:\Users\mmaratt\Desktop\BladeTortoise\build\ALL_BUILD.vcxproj
PAUSE
EXIT
This work crossbrowser for me (IE11, EDGE, CHROME, FIREFOX, OPERA), use https://www.icoconverter.com/ to create .ico file
<link data-senna-track="temporary" href="${favicon_url}" rel="Shortcut Icon" />
<link rel="icon" href="${favicon_url}" type="image/x-icon" />
<link rel="shortcut icon" href="${favicon_url}" type="image/x-icon" />
Use the axis
argument:
>> numpy.sum(a, axis=0)
array([18, 22, 26])
CGRect
Can be simply created using an instance of a CGPoint
or CGSize
, thats given below.
let rect = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 100, height: 100))
// Or
let rect = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
Or if we want to specify each value in CGFloat
or Double
or Int
, we can use this method.
let rect = CGRect(x: 0, y: 0, width: 100, height: 100) // CGFloat, Double, Int
CGPoint
Can be created like this.
let point = CGPoint(x: 0,y :0) // CGFloat, Double, Int
CGSize
Can be created like this.
let size = CGSize(width: 100, height: 100) // CGFloat, Double, Int
Also size and point with 0 as the values, it can be done like this.
let size = CGSize.zero // width = 0, height = 0
let point = CGPoint.zero // x = 0, y = 0, equal to CGPointZero
let rect = CGRect.zero // equal to CGRectZero
CGRectZero
& CGPointZero
replaced with CGRect.zero
& CGPoint.zero
in Swift 3.0
.
Here's an improvement, grabbing just the directory to stdout:
java -XshowSettings:properties -version 2>&1 \
| sed '/^[[:space:]]*java\.home/!d;s/^[[:space:]]*java\.home[[:space:]]*=[[:space:]]*//'
Actually I found out that the container of the image tag need to have a height in order to keep the ratio of the image. for example>
.container{display:flex; height:100%;} img{width:100%;height:auto;}
then in your html your container will wrap the tag image
<div class="container"><img src="image.jpg" alt="image" /></div>
this work for IE and other browsers
In case of Windows, if you can't find setenv.bat, in the 2nd line of catalina.bat (after @echo off) add this:
SET APP_MASTER_PASSWORD=foo
May not be the best approach, but works
Use String#replace()
.
To replace them with spaces (as per your question title):
System.out.println("I don't like these \"double\" quotes".replace("\"", " "));
The above can also be done with characters:
System.out.println("I don't like these \"double\" quotes".replace('"', ' '));
To remove them (as per your example):
System.out.println("I don't like these \"double\" quotes".replace("\"", ""));
I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary
)
var result = new JsonResult()
{
Data = new
{
partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
}
};
I get what's expected:
{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}
Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult
action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting
Here's a simple actionresult JsonNetResult
http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
You'll see the difference (and can make sure you're using the right one) when serializing a date:
Microsoft way:
{"wireTime":"\/Date(1355627201572)\/"}
JSON.NET way:
{"wireTime":"2012-12-15T19:07:03.5247384-08:00"}
This might be just a requirement of PyMySql in Python, but I found that I had to name the exact table that I wanted the ID for:
In:
cnx = pymysql.connect(host='host',
database='db',
user='user',
password='pass')
cursor = cnx.cursor()
update_batch = """insert into batch set type = "%s" , records = %i, started = NOW(); """
second_query = (update_batch % ( "Batch 1", 22 ))
cursor.execute(second_query)
cnx.commit()
batch_id = cursor.execute('select last_insert_id() from batch')
cursor.close()
batch_id
Out:
5
... or whatever the correct Batch_ID value actually is
Sure. Just list the files:
$ svn ci -m "Fixed all those horrible crashes" foo bar baz graphics/logo.png
I'm not aware of a way to tell it to ignore a certain set of files. Of course, if the files you do want to commit are easily listed by the shell, you can use that:
$ svn ci -m "No longer sets printer on fire" printer-driver/*.c
You can also have the svn command read the list of files to commit from a file:
$ svn ci -m "Now works" --targets fix4711.txt
I ran this test before stumbling upon the discussion here. However, having run it I thought I'd at least post my results.
I stole and bastardized the example in Jeff Friedl's "Mastering Regular Expressions". This is on a macbook running OSX 10.6 (2Ghz intel core 2 duo, 4GB ram). Python version is 2.6.1.
Run 1 - using re.compile
import re
import time
import fpformat
Regex1 = re.compile('^(a|b|c|d|e|f|g)+$')
Regex2 = re.compile('^[a-g]+$')
TimesToDo = 1000
TestString = ""
for i in range(1000):
TestString += "abababdedfg"
StartTime = time.time()
for i in range(TimesToDo):
Regex1.search(TestString)
Seconds = time.time() - StartTime
print "Alternation takes " + fpformat.fix(Seconds,3) + " seconds"
StartTime = time.time()
for i in range(TimesToDo):
Regex2.search(TestString)
Seconds = time.time() - StartTime
print "Character Class takes " + fpformat.fix(Seconds,3) + " seconds"
Alternation takes 2.299 seconds
Character Class takes 0.107 seconds
Run 2 - Not using re.compile
import re
import time
import fpformat
TimesToDo = 1000
TestString = ""
for i in range(1000):
TestString += "abababdedfg"
StartTime = time.time()
for i in range(TimesToDo):
re.search('^(a|b|c|d|e|f|g)+$',TestString)
Seconds = time.time() - StartTime
print "Alternation takes " + fpformat.fix(Seconds,3) + " seconds"
StartTime = time.time()
for i in range(TimesToDo):
re.search('^[a-g]+$',TestString)
Seconds = time.time() - StartTime
print "Character Class takes " + fpformat.fix(Seconds,3) + " seconds"
Alternation takes 2.508 seconds
Character Class takes 0.109 seconds
So i tried all the suggested solutions to no avail. All i did was to set run the app from the server and it displayed the error in full, this should have worked when i set customErrors mode to false but it didn't. The moment i browsed the API form the server i was able to see the problem.
Just remember that modifying the padding or margins on any bootstrap grid elements is likely to create overflowing elements at some point at lower screen-widths.
If that happens just remember to use CSS media queries and only include the margins at screen-widths that can handle it.
In keeping with the mobile-first approach of the framework you are working within (bootstrap) it is better to add the padding at widths which can handle it, rather than excluding it at widths which can't.
@media (min-width: 992px){
.navbar li {
margin-left : 1em;
margin-right : 1em;
}
}
Got stupid error. So post here, if anyone find it useful
[-\._]
- means hyphen, dot and underscore[\.-_]
- means all signs in range from dot to underscoreIt is possible to horisontally center the div this way:
html:
<div class="container">
<div class="inner">content</div>
</div>
css:
.container {
left: 0;
right: 0;
bottom: 0; /* or top: 0, or any needed value */
position: fixed;
z-index: 1000; /* or even higher to prevent guarantee overlapping */
}
.inner {
max-width: 600px; /* just for example */
margin: 0 auto;
}
Using this way you will have always your inner block centered, in addition it can be easily turned to true responsive (in the example it will be just fluid on smaller screens), therefore no limitation in as in the question example and in the chosen answer.
The below code worked for me.
declare @Today date
Set @Today=getdate() --date will equal today
Select *
FROM table_name
WHERE created <= @Today
There's a good answer here:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
or in ES6:
var text = "foo bar loo zoo moo";
text = text.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
You can use np.concatenate()
specifying which axis
to append, using np.newaxis
:
import numpy as np
movie = np.concatenate((img1[:,np.newaxis], img2[:,np.newaxis]), axis=3)
If you are reading from many files:
import glob
movie = np.concatenate([cv2.imread(p)[:,np.newaxis] for p in glob.glob('*.jpg')], axis=3)
userCookie.Expires.AddDays(365);
This line of code doesn't do anything. It is the equivalent of:
DateTime temp = userCookie.Expires.AddDays(365);
//do nothing with temp
You probably want
userCookie.Expires = DateTime.Now.AddDays(365);
There are several things wrong with your script.
Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).
It's good practice to surround your variable references with curly braces, too. Your code might look like:
#!/bin/sh
command="/bin/date -u" #...Example Only
safeRunCommand() {
cmnd="$@" #...insure whitespace passed and preserved
$cmnd
ERROR_CODE=$? #...so we have it for the command we want
if [ ${ERROR_CODE} != 0 ]; then
printf "Error when executing command: '${command}'\n"
exit ${ERROR_CODE} #...consider 'return()' here
fi
}
safeRunCommand $command
command="cp"
safeRunCommand $command
I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890
. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
d
is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
class FileReadWriteService {
private var context:Context? = ContextHolder.instance.appContext
fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
val file = File(context?.filesDir, "files")
try {
if (!file.exists()) {
file.mkdir()
}
val fileToWrite = File(file, fileKey)
val writer = FileWriter(fileToWrite)
writer.append(sBody)
writer.flush()
writer.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
}
fun readFileOnInternalStorage(fileKey: String): String {
val file = File(context?.filesDir, "files")
var ret = ""
try {
if (!file.exists()) {
return ret
}
val fileToRead = File(file, fileKey)
val reader = FileReader(fileToRead)
ret = reader.readText()
reader.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
return ret
}
}
Streams are good for dealing with large amounts of data. When it's impractical to load all the data into memory at the same time, you can open it as a stream and work with small chunks of it.
Don't use the alias (P
) in your WHERE
clause directly.
You can either use the same REPLACE
logic again in the WHERE
clause:
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
Or use an aliased sub query as described in Nick's answers.
jQuery can handle JSONP, just pass an url formatted with the callback=? parameter to the $.getJSON
method, for example:
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
console.log(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
This example is of a really simple JSONP service implemented on with api.ipify.org
.
If you aren't looking for a cross-domain solution the script can be simplified even more, since you don't need the callback parameter, and you return pure JSON.
If the range of the numbers is limited (there can be only mod 2 8 digit numbers, or only 10 different 8 digit numbers for example), then you could write an optimized sorting algorithm. But if you want to sort all possible 8 digit numbers, this is not possible with that low amount of memory.
The top voted solution does actually more than requested:
git checkout <sha>
git checkout -b <branch>
or
git checkout -b <branch> <sha>
move you to the new branch together with all recent changes you might have forgot to commit. This may not be your intention, especially when in the "panic mode" after losing the branch.
A cleaner (and simpler) solution seems to be the one-liner (after you found the <sha>
with git reflog
):
git branch <branch> <sha>
Now neither your current branch nor uncommited changes are affected. Instead only a new branch will be created all the way up to the <sha>
.
If it is not the tip, it'll still work and you get a shorter branch, then you can retry with new <sha>
and new branch name until you get it right.
Finally you can rename the successfully restored branch into what it was named or anything else:
git branch -m <restored branch> <final branch>
Needless to say, the key to success was to find the right commit <sha>
, so name your commits wisely :)
You can use:
$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);
Update. And yes current documentation is not so good but if you are okay using older versions you can refer legacy documentation.
Here is my approach:
labels = [0, 0, 1, 1]
from collections import Counter
from scipy import stats
stats.entropy(list(Counter(labels).values()), base=2)
Matlab doesn't provide a mechanism for this, but you can construct one in userland code that's terser than inputParser or "if nargin < 1..." sequences.
function varargout = getargs(args, defaults)
%GETARGS Parse function arguments, with defaults
%
% args is varargin from the caller. By convention, a [] means "use default".
% defaults (optional) is a cell vector of corresponding default values
if nargin < 2; defaults = {}; end
varargout = cell(1, nargout);
for i = 1:nargout
if numel(args) >= i && ~isequal(args{i}, [])
varargout{i} = args{i};
elseif numel(defaults) >= i
varargout{i} = defaults{i};
end
end
Then you can call it in your functions like this:
function y = foo(varargin)
%FOO
%
% y = foo(a, b, c, d, e, f, g)
[a, b, c, d, e, f, g] = getargs(varargin,...
{1, 14, 'dfltc'});
The formatting is a convention that lets you read down from parameter names to their default values. You can extend your getargs() with optional parameter type specifications (for error detection or implicit conversion) and argument count ranges.
There are two drawbacks to this approach. First, it's slow, so you don't want to use it for functions that are called in loops. Second, Matlab's function help - the autocompletion hints on the command line - don't work for varargin functions. But it is pretty convenient.
Popen.communicate()
documentation:
Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.
Replacing os.popen*
pipe = os.popen(cmd, 'w', bufsize)
# ==>
pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
Warning Use communicate() rather than stdin.write(), stdout.read() or stderr.read() to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
So your example could be written as follows:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print(grep_stdout.decode())
# -> four
# -> five
# ->
On Python 3.5+ (3.6+ for encoding
), you could use subprocess.run
, to pass input as a string to an external command and get its exit status, and its output as a string back in one call:
#!/usr/bin/env python3
from subprocess import run, PIPE
p = run(['grep', 'f'], stdout=PIPE,
input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii')
print(p.returncode)
# -> 0
print(p.stdout)
# -> four
# -> five
# ->
You need to set the responseType
to arraybuffer
if you would like to create a blob
from your response data:
$http.post('/fetchBlobURL',{myParams}, {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
more information: Sending_and_Receiving_Binary_Data
Enjoy it...
int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);
You can use the following code snippet:
myTextBox.SelectionStart = myTextBox.Text.Length;
myTextBox.ScrollToCaret();
which will automatically scroll to the end.
[explanations in my “main answer”]
line 7. section around the whole website? Or only a div?
Neither. For styling: use the <body>
, it’s already there. For sectioning/semantics: as detailed in my example HTML its effect is contrary to usefulness. Extra wrappers to already wrapped content is no improvement, but noise.
line 8. Each section start with a header?
No, it is the author’s choice where to put content typically summarized as “header”. And if that header-content is clearly recognizable without extra marking, it may perfectly stay without <header>
. This is also the author’s choice.
line 23. Is this div right? or must this be a section?
The <div>
is probably wrong. It depends on the intentions: is it for styling only it could be right. If it’s for semantic purposes it is wrong: it should be an <article>
instead as shown in my other answer. <article>
is also right if it is for both styling and sectioning combined.
<section>
looks wrong here, as there are no similar sections before or after this one, like chapters in a book. (This is the purpose of <section>
).
line 24. Split left/right column with a div.
No. Why?
line 25. Right place for the article tag?
Yes, makes sense.
line 26. Is it required to put your h1-tag in the header-tag?
No. A lone <h*>
element probably never needs to go in a <header>
(but it can if you want to) as it is already clear that it’s the heading of what is about to come. – It would make sense if that <header>
also encompassed a tagline (marked with <p>
), for example.
line 43. The content is not related to the main article, so I decided this is a section and not an aside.
It is a misunderstanding that an <aside>
has to be “tangentially related” to the content around. The point is: use an <aside>
if the content is only “tangentially related” or not at all!
Nevertheless, apart from <aside>
being a decent choice, <article>
might still be better than a <section>
as “hot items” and “new items” are not to be read like two chapters in a book. You can perfectly go for one of them and not the other like an alternative sorting of something, not like two parts of a whole.
line 44. H2 without header
Is great.
line 53. section without header
Well, there is no <header>
, but the <h2>
-heading leaves pretty clear which part in this section is the header.
line 63. Div with all (non-related) news items
<article>
or <aside>
might be better.
line 64. header with h2
Discussed already.
line 65. Hmm, div or section? Or remove this div and only use the article-tag
Exactly! Remove the <div>
.
line 105. Footer :-)
Very reasonable.
Each type of integer has a different range of storage capacity
Type Capacity
Int16 -- (-32,768 to +32,767)
Int32 -- (-2,147,483,648 to +2,147,483,647)
Int64 -- (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)
As stated by James Sutherland in his answer:
int
andInt32
are indeed synonymous;int
will be a little more familiar looking,Int32
makes the 32-bitness more explicit to those reading your code. I would be inclined to use int where I just need 'an integer',Int32
where the size is important (cryptographic code, structures) so future maintainers will know it's safe to enlarge anint
if appropriate, but should take care changingInt32
variables in the same way.The resulting code will be identical: the difference is purely one of readability or code appearance.
I had the same problem. I called my own custom logger in the log4j.properties file from code when using log4j api directly. If you are using the slf4j api calls, you are probably using the default root logger so you must configure that to be associated with an appender in the log4j.properties:
# Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG, A1 # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender
You said you copied files from another computer. After you copied them, did you 'Unblock' them? Specifically the .snk file should be checked to make sure it is not marked as unsafe.
setup.py can be used in two scenarios , First, you want to install a Python package. Second, you want to create your own Python package. Usually standard Python package has couple of important files like setup.py, setup.cfg and Manifest.in. When you are creating the Python package, these three files will determine the (content in PKG-INFO under egg-info folder) name, version, description, other required installations (usually in .txt file) and few other parameters. setup.cfg is read by setup.py while package is created (could be tar.gz ). Manifest.in is where you can define what should be included in your package. Anyways you can do bunch of stuff using setup.py like
python setup.py build
python setup.py install
python setup.py sdist <distname> upload [-r urltorepo] (to upload package to pypi or local repo)
There are bunch of other commands which could be used with setup.py . for help
python setup.py --help-commands
You can simply extract the existing zip files also by using "unzip". It will work for any size files and you need to add it as a dependency from npm.
fs.createReadStream(filePath).pipe(unzip.Extract({path:moveIntoFolder})).on('close', function(){_x000D_
//To do after unzip_x000D_
callback();_x000D_
});
_x000D_
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] { 1, 24, 4, 4, 345 };
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);
If any of the parent containers RowDefinition
Height set to "Auto"
also stoppers for scrollbars
Alternatively you may set Height "*"
Which happened in my case.
Easy mode for complex object storage with using Gson google library [1]
public static void setComplexObject(Context ctx, ComplexObject obj){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("COMPLEX_OBJECT",new Gson().toJson(obj));
editor.commit();
}
public static ComplexObject getComplexObject (Context ctx){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
String sobj = preferences.getString("COMPLEX_OBJECT", "");
if(sobj.equals(""))return null;
else return new Gson().fromJson(sobj, ComplexObject.class);
}
I use Github Desktop for Windows and I wanted to move location of a repository. No problem if you move your directory and choose the new location in the software. But if you set a bad directory, you get a fatal error and no second chance to make a relocation to the good one. So to repair that. You must copy project files in the bad directory, make its reconize by Github Desktop, after that, you can move again your project in another folder and make a relocate in the software. No need to close Github Desktop for that, it will check folders in live.
Hoping this will help someone.
When working with Swift, you can use the enum
UIUserInterfaceIdiom
, defined as:
enum UIUserInterfaceIdiom : Int {
case unspecified
case phone // iPhone and iPod touch style UI
case pad // iPad style UI (also includes macOS Catalyst)
}
So you can use it as:
UIDevice.current.userInterfaceIdiom == .pad
UIDevice.current.userInterfaceIdiom == .phone
UIDevice.current.userInterfaceIdiom == .unspecified
Or with a Switch statement:
switch UIDevice.current.userInterfaceIdiom {
case .phone:
// It's an iPhone
case .pad:
// It's an iPad (or macOS Catalyst)
@unknown default:
// Uh, oh! What could it be?
}
UI_USER_INTERFACE_IDIOM()
is an Objective-C macro, which is defined as:
#define UI_USER_INTERFACE_IDIOM() \ ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? \ [[UIDevice currentDevice] userInterfaceIdiom] : \ UIUserInterfaceIdiomPhone)
Also, note that even when working with Objective-C, the UI_USER_INTERFACE_IDIOM()
macro is only required when targeting iOS 3.2 and below. When deploying to iOS 3.2 and up, you can use [UIDevice userInterfaceIdiom]
directly.
I have the following nginx virtual host (static content) for local development work to disable all browser caching:
server {
listen 8080;
server_name localhost;
location / {
root /your/site/public;
index index.html;
# kill cache
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
if_modified_since off;
expires off;
etag off;
}
}
No cache headers sent:
$ curl -I http://localhost:8080
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Mon, 24 Jul 2017 16:19:30 GMT
Content-Type: text/html
Content-Length: 2076
Connection: keep-alive
Last-Modified: Monday, 24-Jul-2017 16:19:30 GMT
Cache-Control: no-store
Accept-Ranges: bytes
Last-Modified
is always current time.
In addition to what Dario stated about the Delegates you could execute a delegate with several parameters:
Predefine your delegate:
Private Delegate Sub TestThreadDelegate(ByRef goodList As List(Of String), ByVal coolvalue As Integer)
Get a handle to the delegate, create parameters in an array, DynamicInvoke on the Delegate:
Dim tester As TestThreadDelegate = AddressOf Me.testthread
Dim params(1) As Object
params(0) = New List(Of String)
params(1) = 0
tester.DynamicInvoke(params)
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
What parts of Boost do you need? A lot of stuff is part of TR1 which is shipped with Visual Studio, so you could simply say, for example:
#include <tr1/memory>
using std::tr1::shared_ptr;
According to James, this should also work (in C++0x):
#include <memory>
using std::shared_ptr;
I think this should help.
import java.util.*;
public class StringSwap{
public static void main(String ar[]){
Scanner in = new Scanner(System.in);
String s = in.next();
System.out.println(new StringBuffer(s.substring(0,2)).reverse().toString().concat(s.substring(2)));
}
}
// SQL: SELECT * FROM table LIMIT start, maxRows;
Query q = session.createQuery("FROM table");
q.setFirstResult(start);
q.setMaxResults(maxRows);
Following can be used for display only which uses the property of String ..
double value = 123.456789;
String.Format("{0:0.00}", value);
If Right Ctrl (Host Key) + C does not work (there have been some issues on Ubuntu), do the following:
1) File > Preferences > Input on the Virtual Machine which is stuck in Scale Mode
2) Change or Reset the Host Key. There's no need to even save after changing the settings
3) Re-open the Virtual Machine and it should be reset!
This is a pretty way to do that:
function time_converter($sec_time, $format='h:m:s'){
$hour = intval($sec_time / 3600) >= 10 ? intval($sec_time / 3600) : '0'.intval($sec_time / 3600);
$minute = intval(($sec_time % 3600) / 60) >= 10 ? intval(($sec_time % 3600) / 60) : '0'.intval(($sec_time % 3600) / 60);
$sec = intval(($sec_time % 3600) % 60) >= 10 ? intval(($sec_time % 3600) % 60) : '0'.intval(($sec_time % 3600) % 60);
$format = str_replace('h', $hour, $format);
$format = str_replace('m', $minute, $format);
$format = str_replace('s', $sec, $format);
return $format;
}
This is a fairly old thread, but since I was reinstalling my Visual Studio 2015 Community today, I thought I might add some info on what to use on VS2015, or what might work in general.
To see which instances were installed by default, type sqllocaldb info
inside a command prompt. On my machine, I get two instances, the first one named MSSQLLocalDB
.
C:\>sqllocaldb info
MSSQLLocalDB
ProjectsV13
You can also create a new instance if you wish, using sqllocaldb create "some_instance_name"
, but the default one will work just fine:
// if not using a verbatim string literal, don't forget to escape backslashes
@"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;"
Updated answer for a .NET Core Web Api project...
Right-click on your project, select "Properties," go to "Debug" and untick the "Launch browser" checkbox (enabled by default).
Check out www.connectionstrings.com for a ton of samples of proper connection strings.
In your case, use this:
Server=localhost;Database=employeedetails;Integrated Security=SSPI
Update: obviously, the service account used to run ASP.NET web apps doesn't have access to SQL Server, and judging from that error message, you're probably using "anonymous authentication" on your web site.
So you either need to add this account IIS APPPOOL\ASP.NET V4.0
as a SQL Server login and give that login access to your database, or you need to switch to using "Windows authentication" on your ASP.NET web site so that the calling Windows account will be passed through to SQL Server and used as a login on SQL Server.
Sorry to rouse a really old thread, but I've been using jemdoc for a couple of years and it is really excellent.
You're looking for the SyndicationFeed
class, which does exactly that.
What about thinking the following way:
So when you have an abstract class Mammals, a subclass Human, and an interface Driving, then you can say
My suggestion is that the book knowledge phrase indicates that he wanted to hear the semantic difference between both (like others here already suggested).
Think of (char *) as string.begin(). The essential difference is that (char *) is an iterator and std::string is a container. If you stick to basic strings a (char *) will give you what std::string::iterator does. You could use (char *) when you want the benefit of an iterator and also compatibility with C, but that's the exception and not the rule. As always, be careful of iterator invalidation. When people say (char *) isn't safe this is what they mean. It's as safe as any other C++ iterator.
Date and time input is accepted in almost any reasonable format, including ISO 8601, SQL-compatible, traditional POSTGRES, and others. For some formats, ordering of month, day, and year in date input is ambiguous and there is support for specifying the expected ordering of these fields.
In other words: just write anything and it will work.
Or check this table with all the unambiguous formats.
Following will return true when checkbox is checked and false when not.
$(this).is(":checked")
Replace $(this) with the variable you want to check.
And used in a condition:
if ($(this).is(":checked")) {
// do something
}
Create unique constraint that two numbers together CANNOT together be repeated:
ALTER TABLE someTable
ADD UNIQUE (col1, col2)
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
Before you extract values from $_POST
, you should check if they exist. You could use the isset
function for this (http://php.net/manual/en/function.isset.php)
This looks a bit strange, but...
stringName == null || "".equals(stringName)
Never had any issues doing it this way, plus it's a safer way to check while avoiding potential null point exceptions.
The child process environment is lost in the moment it ceases to exist, and moving the environment content from there to the parent is somewhat tricky.
You probably need to spawn a shell script (you can generate one dynamically to /tmp) which will output the virtualenv environment variables to a file, which you then read in the parent Python process and put in os.environ.
Or you simply parse the activate script in using for the line in open("bin/activate"), manually extract stuff, and put in os.environ. It is tricky, but not impossible.
There's no need to check the exit code explicitly. Try
if getent passwd $1 > /dev/null 2>&1; then
echo "yes the user exists"
else
echo "No, the user does not exist"
fi
If that doesn't work, there is something wrong with your getent
, or you have more users defined than you think.
Since @Jonathan's answer still consisted of some bugs, I made an improved version. I overwrote the toString()
method for debugging purposes, be sure to change it accordingly to your data.
import java.util.ArrayList;
import java.util.List;
/**
* Provides an easy way to create a parent-->child tree while preserving their depth/history.
* Original Author: Jonathan, https://stackoverflow.com/a/22419453/14720622
*/
public class TreeNode<T> {
private final List<TreeNode<T>> children;
private TreeNode<T> parent;
private T data;
private int depth;
public TreeNode(T data) {
// a fresh node, without a parent reference
this.children = new ArrayList<>();
this.parent = null;
this.data = data;
this.depth = 0; // 0 is the base level (only the root should be on there)
}
public TreeNode(T data, TreeNode<T> parent) {
// new node with a given parent
this.children = new ArrayList<>();
this.data = data;
this.parent = parent;
this.depth = (parent.getDepth() + 1);
parent.addChild(this);
}
public int getDepth() {
return this.depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
public List<TreeNode<T>> getChildren() {
return children;
}
public void setParent(TreeNode<T> parent) {
this.setDepth(parent.getDepth() + 1);
parent.addChild(this);
this.parent = parent;
}
public TreeNode<T> getParent() {
return this.parent;
}
public void addChild(T data) {
TreeNode<T> child = new TreeNode<>(data);
this.children.add(child);
}
public void addChild(TreeNode<T> child) {
this.children.add(child);
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public boolean isRootNode() {
return (this.parent == null);
}
public boolean isLeafNode() {
return (this.children.size() == 0);
}
public void removeParent() {
this.parent = null;
}
@Override
public String toString() {
String out = "";
out += "Node: " + this.getData().toString() + " | Depth: " + this.depth + " | Parent: " + (this.getParent() == null ? "None" : this.parent.getData().toString()) + " | Children: " + (this.getChildren().size() == 0 ? "None" : "");
for(TreeNode<T> child : this.getChildren()) {
out += "\n\t" + child.getData().toString() + " | Parent: " + (child.getParent() == null ? "None" : child.getParent().getData());
}
return out;
}
}
And for the visualization:
import model.TreeNode;
/**
* Entrypoint
*/
public class Main {
public static void main(String[] args) {
TreeNode<String> rootNode = new TreeNode<>("Root");
TreeNode<String> firstNode = new TreeNode<>("Child 1 (under Root)", rootNode);
TreeNode<String> secondNode = new TreeNode<>("Child 2 (under Root)", rootNode);
TreeNode<String> thirdNode = new TreeNode<>("Child 3 (under Child 2)", secondNode);
TreeNode<String> fourthNode = new TreeNode<>("Child 4 (under Child 3)", thirdNode);
TreeNode<String> fifthNode = new TreeNode<>("Child 5 (under Root, but with a later call)");
fifthNode.setParent(rootNode);
System.out.println(rootNode.toString());
System.out.println(firstNode.toString());
System.out.println(secondNode.toString());
System.out.println(thirdNode.toString());
System.out.println(fourthNode.toString());
System.out.println(fifthNode.toString());
System.out.println("Is rootNode a root node? - " + rootNode.isRootNode());
System.out.println("Is firstNode a root node? - " + firstNode.isRootNode());
System.out.println("Is thirdNode a leaf node? - " + thirdNode.isLeafNode());
System.out.println("Is fifthNode a leaf node? - " + fifthNode.isLeafNode());
}
}
Example output:
Node: Root | Depth: 0 | Parent: None | Children:
Child 1 (under Root) | Parent: Root
Child 2 (under Root) | Parent: Root
Child 5 (under Root, but with a later call) | Parent: Root
Node: Child 1 (under Root) | Depth: 1 | Parent: Root | Children: None
Node: Child 2 (under Root) | Depth: 1 | Parent: Root | Children:
Child 3 (under Child 2) | Parent: Child 2 (under Root)
Node: Child 3 (under Child 2) | Depth: 2 | Parent: Child 2 (under Root) | Children:
Child 4 (under Child 3) | Parent: Child 3 (under Child 2)
Node: Child 4 (under Child 3) | Depth: 3 | Parent: Child 3 (under Child 2) | Children: None
Node: Child 5 (under Root, but with a later call) | Depth: 1 | Parent: Root | Children: None
Is rootNode a root node? - true
Is firstNode a root node? - false
Is thirdNode a leaf node? - false
Is fifthNode a leaf node? - true
Some additional informations: Do not use addChildren()
and setParent()
together. You'll end up having two references as setParent()
already updates the children=>parent relationship.
for set empty all input such textarea select and input run this code:
$('#message').val('').change();
The fastest code for counting files with ANY attributes in folder %FOLDER%
and its subfolders is the following. The code is for script in a command script (batch) file.
@for /f %%a in ('2^>nul dir "%FOLDER%" /a-d/b/-o/-p/s^|find /v /c ""') do set n=%%a
@echo Total files: %n%.
Here are two quickie approaches I know of:
In base
AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1
Not in base
library(qdap)
NAer(airquality)
PS P.S. Does my command above create a new dataframe called AQ1?
Look at AQ1 and see
function convert() {
dom = document.getElementById('divname');
var script,
$this = this,
options = this.options,
runH2c = function(){
try {
var canvas = window.html2canvas([ document.getElementById('divname') ], {
onrendered: function( canvas ) {
window.open(canvas.toDataURL());
}
});
} catch( e ) {
$this.h2cDone = true;
log("Error in html2canvas: " + e.message);
}
};
if ( window.html2canvas === undefined && script === undefined ) {
} else {.
// html2canvas already loaded, just run it then
runH2c();
}
}
Now only I came across this situation and found some more interesting features around GROUP_CONCAT
. I hope these details will make you feel interesting.
simple GROUP_CONCAT
SELECT GROUP_CONCAT(TaskName)
FROM Tasks;
Result:
+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName) |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+
GROUP_CONCAT with DISTINCT
SELECT GROUP_CONCAT(TaskName)
FROM Tasks;
Result:
+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName) |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+
GROUP_CONCAT with DISTINCT and ORDER BY
SELECT GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC)
FROM Tasks;
Result:
+--------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) |
+--------------------------------------------------------+
| Take dog for walk,Relax,Paint roof,Feed cats,Do garden |
+--------------------------------------------------------+
GROUP_CONCAT with DISTINCT and SEPARATOR
SELECT GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ')
FROM Tasks;
Result:
+----------------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ') |
+----------------------------------------------------------------+
| Do garden + Feed cats + Paint roof + Relax + Take dog for walk |
+----------------------------------------------------------------+
GROUP_CONCAT and Combining Columns
SELECT GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ')
FROM Tasks;
Result:
+------------------------------------------------------------------------------------+
| GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ') |
+------------------------------------------------------------------------------------+
| 1) Do garden 2) Feed cats 3) Paint roof 4) Take dog for walk 5) Relax 6) Feed cats |
+------------------------------------------------------------------------------------+
GROUP_CONCAT and Grouped Results
Assume that the following are the results before using GROUP_CONCAT
+------------------------+--------------------------+
| ArtistName | AlbumName |
+------------------------+--------------------------+
| Iron Maiden | Powerslave |
| AC/DC | Powerage |
| Jim Reeves | Singing Down the Lane |
| Devin Townsend | Ziltoid the Omniscient |
| Devin Townsend | Casualties of Cool |
| Devin Townsend | Epicloud |
| Iron Maiden | Somewhere in Time |
| Iron Maiden | Piece of Mind |
| Iron Maiden | Killers |
| Iron Maiden | No Prayer for the Dying |
| The Script | No Sound Without Silence |
| Buddy Rich | Big Swing Face |
| Michael Learns to Rock | Blue Night |
| Michael Learns to Rock | Eternity |
| Michael Learns to Rock | Scandinavia |
| Tom Jones | Long Lost Suitcase |
| Tom Jones | Praise and Blame |
| Tom Jones | Along Came Jones |
| Allan Holdsworth | All Night Wrong |
| Allan Holdsworth | The Sixteen Men of Tain |
+------------------------+--------------------------+
USE Music;
SELECT ar.ArtistName,
GROUP_CONCAT(al.AlbumName)
FROM Artists ar
INNER JOIN Albums al
ON ar.ArtistId = al.ArtistId
GROUP BY ArtistName;
Result:
+------------------------+----------------------------------------------------------------------------+
| ArtistName | GROUP_CONCAT(al.AlbumName) |
+------------------------+----------------------------------------------------------------------------+
| AC/DC | Powerage |
| Allan Holdsworth | All Night Wrong,The Sixteen Men of Tain |
| Buddy Rich | Big Swing Face |
| Devin Townsend | Epicloud,Ziltoid the Omniscient,Casualties of Cool |
| Iron Maiden | Somewhere in Time,Piece of Mind,Powerslave,Killers,No Prayer for the Dying |
| Jim Reeves | Singing Down the Lane |
| Michael Learns to Rock | Eternity,Scandinavia,Blue Night |
| The Script | No Sound Without Silence |
| Tom Jones | Long Lost Suitcase,Praise and Blame,Along Came Jones |
+------------------------+----------------------------------------------------------------------------+
sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php
and set:
$cfg['Lang'] = 'en-utf-8';
Use the Distinct operator:
var idList = yourList.Select(x=> x.ID).Distinct();
The timeouts()
methods are not implemented in some drivers and are very unreliable in general.
I use a separate thread for the timeouts (passing the url to access as the thread name):
Thread t = new Thread(new Runnable() {
public void run() {
driver.get(Thread.currentThread().getName());
}
}, url);
t.start();
try {
t.join(YOUR_TIMEOUT_HERE_IN_MS);
} catch (InterruptedException e) { // ignore
}
if (t.isAlive()) { // Thread still alive, we need to abort
logger.warning("Timeout on loading page " + url);
t.interrupt();
}
This seems to work most of the time, however it might happen that the driver is really stuck and any subsequent call to driver will be blocked (I experience that with Chrome driver on Windows). Even something as innocuous as a driver.findElements() call could end up being blocked. Unfortunately I have no solutions for blocked drivers.
Firstly, of all I recommend that the pictures are in the same folder as the workbook. You need to enter some codes in the Worksheet_Change procedure of the worksheet. For example, we can enter the following codes to add the image that with the same name as the value of cell in column A to the cell in column D:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim pic As Picture
If Intersect(Target, [A:A]) Is Nothing Then Exit Sub
On Error GoTo son
For Each pic In ActiveSheet.Pictures
If Not Application.Intersect(pic.TopLeftCell, Range(Target.Offset(0, 3).Address)) Is Nothing Then
pic.Delete
End If
Next pic
ActiveSheet.Pictures.Insert(ThisWorkbook.Path & "\" & Target.Value & ".jpg").Select
Selection.Top = Target.Offset(0, 2).Top
Selection.Left = Target.Offset(0, 3).Left
Selection.ShapeRange.LockAspectRatio = msoFalse
Selection.ShapeRange.Height = Target.Offset(0, 2).Height
Selection.ShapeRange.Width = Target.Offset(0, 3).Width
son:
End Sub
With the codes above, the picture is sized according to the cell it is added to.
Details and sample file here : Vba Insert image to cell
I have issue with itextsharp and itextsharp.xmlworker dlls for exception-from-hresult-0x80131040 so I have removed those both dlls from references and downloaded new dlls directly from nuget packages, which resolved my issue.
May be this method can be useful to resolved the issue to other people.
As JERC said, make sure you have an updated version of git. If you are only using the default settings, when you try to install git you will get version 1.7.1. Other than manually downloading and installing the latest version of get, you can also accomplish this by adding a new repository to yum.
From tecadmin.net:
Download and install the rpmforge repository:
# use this for 64-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm'
# use this for 32-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.i686.rpm'
# then run this in either case
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
Then you need to enable the rpmforge-extras. Edit /etc/yum.repos.d/rpmforge.repo
and change enabled = 0
to enabled = 1
under [rpmforge-extras]
. The file looks like this:
### Name: RPMforge RPM Repository for RHEL 6 - dag
### URL: http://rpmforge.net/
[rpmforge]
name = RHEL $releasever - RPMforge.net - dag
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/rpmforge
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge
enabled = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
[rpmforge-extras]
name = RHEL $releasever - RPMforge.net - extras
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/extras
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-extras
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-extras
enabled = 0 ####### CHANGE THIS LINE TO "enabled = 1" #############
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
[rpmforge-testing]
name = RHEL $releasever - RPMforge.net - testing
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/testing
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-testing
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-testing
enabled = 0
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
Once you've done this, then you can update git with
yum update git
I'm not sure why, but they then suggest disabling rpmforge-extras (change back to enabled = 0
) and then running yum clean all
.
Most likely you'll need to use sudo
for these commands.
If you are looking for a library to carry out client-side image compression, you can check this out:compress.js. This will basically help you compress multiple images purely with JavaScript and convert them to base64 string. You can optionally set the maximum size in MB and also the preferred image quality.
Maybe this can help:
echo off
@prompt set date=$d$_ set time=$t$h$h$h
echo some log >> %date% %time%.log
exit
or
echo off
set v=%date%.log
echo some log >> %v%
res_list = [x[0] for x in rows]
c.f. http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
For a discussion on why to prefer comprehensions over higher-order functions such as map
, go to http://www.artima.com/weblogs/viewpost.jsp?thread=98196.
You can use an infinite loop to achieve this:
while true
do
read -p "Enter password" passwd
case "$passwd" in
<some good condition> ) break;;
esac
done
You can take this trick to use only qplot. Use inner variable $mapping
. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.
cpu_metric2 <- qplot(y=Y2,x=X1)
cpu_metric1 <- qplot(y=Y1,
x=X1,
xlab="Time", ylab="%")
combined_cpu_plot <- cpu_metric1 +
geom_line() +
geom_point(mapping=cpu_metric2$mapping)+
geom_line(mapping=cpu_metric2$mapping)
I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().
If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.
There are a number of different solutions for finding running median from streamed data, I will briefly talk about them at the very end of the answer.
The question is about the details of the a specific solution (max heap/min heap solution), and how heap based solution works is explained below:
For the first two elements add smaller one to the maxHeap on the left, and bigger one to the minHeap on the right. Then process stream data one by one,
Step 1: Add next item to one of the heaps
if next item is smaller than maxHeap root add it to maxHeap,
else add it to minHeap
Step 2: Balance the heaps (after this step heaps will be either balanced or
one of them will contain 1 more item)
if number of elements in one of the heaps is greater than the other by
more than 1, remove the root element from the one containing more elements and
add to the other one
Then at any given time you can calculate median like this:
If the heaps contain equal amount of elements;
median = (root of maxHeap + root of minHeap)/2
Else
median = root of the heap with more elements
Now I will talk about the problem in general as promised in the beginning of the answer. Finding running median from a stream of data is a tough problem, and finding an exact solution with memory constraints efficiently is probably impossible for the general case. On the other hand, if the data has some characteristics we can exploit, we can develop efficient specialized solutions. For example, if we know that the data is an integral type, then we can use counting sort, which can give you a constant memory constant time algorithm. Heap based solution is a more general solution because it can be used for other data types (doubles) as well. And finally, if the exact median is not required and an approximation is enough, you can just try to estimate a probability density function for the data and estimate median using that.
To avoid check on every digest cycle, we can change the height of the div when the window height gets changed.
http://jsfiddle.net/zbjLh/709/
<div ng-app="miniapp" resize>
Testing
</div>
.
var app = angular.module('miniapp', []);
app.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
var changeHeight = function() {element.css('height', (w.height() -20) + 'px' );};
w.bind('resize', function () {
changeHeight(); // when window size gets changed
});
changeHeight(); // when page loads
}
})
In case of using NUnit, try this:
Assert.That(() =>
{
Your_Method_To_Test();
}, Throws.TypeOf<Your_Specific_Exception>().With.Message.EqualTo("Your_Specific_Message"));
The easiest way I found (just I use eval() to convert string gotten from input to tuple to read again for form instance or other place)
This trick works very well
#model.py
class ClassName(models.Model):
field_name = models.CharField(max_length=100)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.field_name:
self.field_name= eval(self.field_name)
#form.py
CHOICES = [('pi', 'PI'), ('ci', 'CI')]
class ClassNameForm(forms.ModelForm):
field_name = forms.MultipleChoiceField(choices=CHOICES)
class Meta:
model = ClassName
fields = ['field_name',]
Mockito [3.4.0] can mock static methods!
Replace mockito-core
dependency with mockito-inline:3.4.0
.
Class with static method:
class Buddy {
static String name() {
return "John";
}
}
Use new method Mockito.mockStatic()
:
@Test
void lookMomICanMockStaticMethods() {
assertThat(Buddy.name()).isEqualTo("John");
try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
theMock.when(Buddy::name).thenReturn("Rafael");
assertThat(Buddy.name()).isEqualTo("Rafael");
}
assertThat(Buddy.name()).isEqualTo("John");
}
Mockito replaces the static method within the try
block only.
Just for completeness, this error can happen also in a different situation: when you declare an array in an outer scope, but declare another variable with the same name in an inner scope, shadowing the array. Then, when you try to index the array, you are actually accessing the variable in the inner scope, which might not even be an array, or it might be an array with fewer dimensions.
Example:
int a[10]; // a global scope
void f(int a) // a declared in local scope, overshadows a in global scope
{
printf("%d", a[0]); // you trying to access the array a, but actually addressing local argument a
}
Yes include the first file into the second. That's all.
See an example below,
File1.php :
<?php
function first($int, $string){ //function parameters, two variables.
return $string; //returns the second argument passed into the function
}
?>
Now Using include
(http://php.net/include) to include the File1.php
to make its content available for use in the second file:
File2.php :
<?php
include 'File1.php';
echo first(1,"omg lol"); //returns omg lol;
?>
string[][] table = { ... };
I have scopes for this, hope it help somebody. https://laravel.com/docs/master/eloquent#local-scopes
public function scopeWhereLike($query, $column, $value)
{
return $query->where($column, 'like', '%'.$value.'%');
}
public function scopeOrWhereLike($query, $column, $value)
{
return $query->orWhere($column, 'like', '%'.$value.'%');
}
Usage:
$result = BookingDates::whereLike('email', $email)->orWhereLike('name', $name)->get();
A python class that acts like dict
Why add slots? A builtin dict
instance doesn't have arbitrary attributes:
>>> d = dict()
>>> d.foo = 'bar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'foo'
If we create a subclass the way most are doing it here on this answer, we see we don't get the same behavior, because we'll have a __dict__
attribute, causing our dicts to take up to potentially twice the space:
my_dict(dict):
"""my subclass of dict"""
md = my_dict()
md.foo = 'bar'
Since there's no error created by the above, the above class doesn't actually act, "like dict
."
We can make it act like dict by giving it empty slots:
class my_dict(dict):
__slots__ = ()
md = my_dict()
So now attempting to use arbitrary attributes will fail:
>>> md.foo = 'bar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'my_dict' object has no attribute 'foo'
And this Python class acts more like a dict
.
For more on how and why to use slots, see this Q&A: Usage of __slots__?
I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format
<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here
I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o
file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!
Deduping is rarely simple. That's because the records to be dedupped often have slightly different values is some of the fields. Therefore choose which record to keep can be problematic. Further, dups are often people records and it is hard to identify if the two John Smith's are two people or one person who is duplicated. So spend a lot (50% or more of the whole project) of your time defining what constitutes a dup and how to handle the differences and child records.
How do you know which is the correct value? Further dedupping requires that you handle all child records not orphaning any. What happens when you find that by changing the id on the child record you are suddenly violating one of the unique indexes or constraints - this will happen eventually and your process needs to handle it. If you have chosen foolishly to apply all your constraints only thorough the application, you may not even know the constraints are violated. When you have 10,000 records to dedup, you aren't going to go through the application to dedup one at a time. If the constraint isn't in the database, lots of luck in maintaining data integrity when you dedup.
A further complication is that dups don't always match exactly on the name or address. For instance a salesrep named Joan Martin may be a dup of a sales rep names Joan Martin-Jones especially if they have the same address and email. OR you could have John or Johnny in the name. Or the same street address except one record abbreveiated ST. and one spelled out Street. In SQL server you can use SSIS and fuzzy grouping to also identify near matches. These are often the most common dups as the fact that weren't exact matches is why they got put in as dups in the first place.
For some types of dedupping, you may need a user interface, so that the person doing the dedupping can choose which of two values to use for a particular field. This is especially true if the person who is being dedupped is in two or more roles. It could be that the data for a particular role is usually better than the data for another role. Or it could be that only the users will know for sure which is the correct value or they may need to contact people to find out if they are genuinely dups or simply two people with the same name.
Try this:
<div id="mainTable" style="width:100px; height:200px;"></div>
$(document).ready(function() {
$("#mainTable").width(100).height(200);
}) ;
you can use the shell(bash for example)
$ string="12 BBQ ,45 rofl, 89 lol"
$ echo ${string% rofl*}
12 BBQ ,45
$ string=${string% rofl*}
$ echo ${string##*,}
45
Open port 9418 on your firewall - it's a custom port that Git uses to communicate on and it's often not open on a corporate or private firewall.
Great question and great idea, but in SQL you'll need to do this:
For data type datetime, something like this-
declare @BeginDate datetime = '1/1/2016',
@EndDate datetime = '12/1/2016'
create table #months (dates datetime)
declare @var datetime = @BeginDate
while @var < dateadd(MONTH, +1, @EndDate)
Begin
insert into #months Values(@var)
set @var = Dateadd(MONTH, +1, @var)
end
If all you really want is numbers, do this-
create table #numbas (digit int)
declare @var int = 1 --your starting digit
while @var <= 12 --your ending digit
begin
insert into #numbas Values(@var)
set @var = @var +1
end
For those working with AngularJS front-end, it does not use the Ajax header laravel is expecting. (Read more)
Use Request::wantsJson() for AngularJS:
if(Request::wantsJson()) {
// Client wants JSON returned
}
git branch --set-upstream <<origin/branch>>
is officially not supported anymore and is replaced by git branch --set-upstream-to <<origin/branch>>
For oracle I use self-written java programm oracle-ddl2svn for auto track changes of oracle DDL scheme in SVN
Using the createElement
function provided in this answer, which is necessary due to IE's brokenness with the name attribute on elements created normally with document.createElement
:
function postToURL(url, values) {
values = values || {};
var form = createElement("form", {action: url,
method: "POST",
style: "display: none"});
for (var property in values) {
if (values.hasOwnProperty(property)) {
var value = values[property];
if (value instanceof Array) {
for (var i = 0, l = value.length; i < l; i++) {
form.appendChild(createElement("input", {type: "hidden",
name: property,
value: value[i]}));
}
}
else {
form.appendChild(createElement("input", {type: "hidden",
name: property,
value: value}));
}
}
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
__str__
is only called when a string representation is required of an object.
For example str(uno)
, print "%s" % uno
or print uno
However, there is another magic method called __repr__
this is the representation of an object. When you don't explicitly convert the object to a string, then the representation is used.
If you do this uno.neighbors.append([[str(due),4],[str(tri),5]])
it will do what you expect.
Use QString::fromUtf16((ushort *)Data.data())
, as shown in the following code example:
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// QByteArray to QString
// =====================
const char c_test[10] = {'t', '\0', 'e', '\0', 's', '\0', 't', '\0', '\0', '\0'};
QByteArray qba_test(QByteArray::fromRawData(c_test, 10));
qDebug().nospace().noquote() << "qba_test[" << qba_test << "]"; // Should see: qba_test[t
QString qstr_test = QString::fromUtf16((ushort *)qba_test.data());
qDebug().nospace().noquote() << "qstr_test[" << qstr_test << "]"; // Should see: qstr_test[test]
return a.exec();
}
This is an alternative solution to the one using QTextCodec. The code has been tested using Qt 5.4.
I had the pleasure of experiencing this random problem in Visual Studio 2017 Enterprise.
I tried every solution here, and it didn't work, including the Visual Studio repair (which takes a while). Several hours in, I thought maybe I should actually check the ActivityLog.xml file.
I uninstalled the offending extension from the 'Developer Command Prompt for VS2017' as an administrator since Visual Studio just freezed after open and nothing could be clicked.
Steps to uninstall - courtesy of jessehouwing.net
vsixinstaller /u:Microsoft.VisualStudio.LiveShare
to remove the extension.As shown in the latest edit, the password is valid until 1970, which means it's currently invalid. This explains the error message which is the same as if the password was incorrect.
Reset the validity with:
ALTER USER postgres VALID UNTIL 'infinity';
In a recent question, another user had the same problem with user accounts and PG-9.2:
PostgreSQL - Password authentication fail after adding group roles
So apparently there is a way to unintentionally set a bogus password validity to the Unix epoch (1st Jan, 1970, the minimum possible value for the abstime
type). Possibly, there's a bug in PG itself or in some client tool that would create this situation.
EDIT: it turns out to be a pgadmin bug. See https://dba.stackexchange.com/questions/36137/
There is better way. I'm using it in pages where I'm using kendo angularJS directives and grids has'nt IDs...
change: function (e) {
var selectedDataItem = e != null ? e.sender.dataItem(e.sender.select()) : null;
}
Use gradle dependencies to get the Gson in your project. Your application build.gradle should look like this-
dependencies {
implementation 'com.google.code.gson:gson:2.8.2'
}
I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog
Non-uniformly distributed data can be plotted in excel in
Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.
1- Add the center point to your data series
+---------------+-------+------+
| Time | Time | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 | 12 |
| 09:00 - 10:00 | 09:30 | 13 |
| 10:00 - 11:00 | 10:30 | 10 |
| 13:00 - 14:00 | 13:30 | 5 |
| 14:00 - 15:00 | 14:30 | 14 |
+---------------+-------+------+
2- Create a Scatter Plot
3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:
Alternative Display:
To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.
1- You're going to need to add several rows where we draw the line and disjoint the data
+-------+------+
| Time | Freq |
+-------+------+
| 08:30 | 0 |
| 08:30 | 12 |
| | |
| 09:30 | 0 |
| 09:30 | 13 |
| | |
| 10:30 | 0 |
| 10:30 | 10 |
| | |
| 13:30 | 0 |
| 13:30 | 5 |
| | |
| 14:30 | 0 |
| 14:30 | 14 |
+-------+------+
2- Plot an X Y (Scatter) Chart with Lines.
3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.
Solution in Swift 3.1, After connecting your textfields IBOutlets set your textfields delegate in viewDidLoad, And then navigate your action in textFieldShouldReturn
class YourViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.passwordTextField.delegate = self
self.phoneTextField.delegate = self
// Set your return type
self.phoneTextField.returnKeyType = .next
self.passwordTextField.returnKeyType = .done
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool{
if textField == self.phoneTextField {
self.passwordTextField.becomeFirstResponder()
}else if textField == self.passwordTextField{
// Call login api
self.login()
}
return true
}
}
In current versions of Matplotlib, you can do axis.set_xticklabels(labels, fontsize='small')
.
Output on Windows 7 (64-bit)
SpecialFolder.CommonApplicationData: C:\ProgramData
SpecialFolder.CommonDesktopDirectory: C:\Users\Public\Desktop
SpecialFolder.CommonStartMenu: C:\ProgramData\Microsoft\Windows\Start Menu
SpecialFolder.CommonPrograms: C:\ProgramData\Microsoft\Windows\Start Menu\Programs
SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files
SpecialFolder.CommonProgramFilesX86: C:\Program Files (x86)\Common Files
SpecialFolder.CommonStartup: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
SpecialFolder.ProgramFiles: C:\Program Files
SpecialFolder.ProgramFilesX86: C:\Program Files (x86)
SpecialFolder.System: C:\Windows\system32
SpecialFolder.SystemX86: C:\Windows\SysWOW64
Output on Windows XP
SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data
SpecialFolder.CommonDesktopDirectory: C:\Documents and Settings\All Users\Desktop
SpecialFolder.CommonPrograms: C:\Documents and Settings\All Users\Start Menu\Programs
SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files
SpecialFolder.CommonProgramFilesX86:
SpecialFolder.CommonStartMenu: C:\Documents and Settings\All Users\Start Menu
SpecialFolder.CommonStartup: C:\Documents and Settings\All Users\Start Menu\Programs\Startup
SpecialFolder.ProgramFiles: C:\Program Files
SpecialFolder.ProgramFilesX86:
SpecialFolder.System: C:\WINDOWS\system32
SpecialFolder.SystemX86: C:\WINDOWS\system32
I would get the part before and after what you want to replace and put them either side.
Like:
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
var matches = str.match(regex);
var result = matches[1] + "1" + matches[2];
// With ES6:
var result = `${matches[1]}1${matches[2]}`;
It's possible to do this cleanly using a lambda in C++11 (tested in G++ 4.8.2).
Given this reusable typedef
:
template<typename T>
using deleted_unique_ptr = std::unique_ptr<T,std::function<void(T*)>>;
You can write:
deleted_unique_ptr<Foo> foo(new Foo(), [](Foo* f) { customdeleter(f); });
For example, with a FILE*
:
deleted_unique_ptr<FILE> file(
fopen("file.txt", "r"),
[](FILE* f) { fclose(f); });
With this you get the benefits of exception-safe cleanup using RAII, without needing try/catch noise.
Events onunload or onbeforeunload you can't use directly - they do not differ between window close, page refresh, form submit, link click or url change.
The only working solution is How to capture the browser window close event?
Quick way to print something is:
select '** Place your mesage here' AS '** DEBUG:';
Alright so after trying every solution out there to solve this exact issues on a wordpress blog, I might have done something either really stupid or genius... With no idea why there's an increase in Mysql connections, I used the php script below in my header to kill all sleeping processes..
So every visitor to my site helps in killing the sleeping processes..
<?php
$result = mysql_query("SHOW processlist");
while ($myrow = mysql_fetch_assoc($result)) {
if ($myrow['Command'] == "Sleep") {
mysql_query("KILL {$myrow['Id']}");}
}
?>
Edit:
As some folks needs help in Unlocking device after locking programmatically, I came through post Android screen lock/ unlock programatically, please have look, may help you.
Original Answer was:
You need to get Admin permission and you can lock phone screen
please check below simple tutorial to achive this one
Lock Phone Screen Programmtically
also here is the code example..
LockScreenActivity.java
public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
MyAdmin.java
public class MyAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
@Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
@Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
@Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
@Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
@Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
The general rule I follow is not to include any header file unless I have to. So unless I am storing the object of a class as a member variable of my class I won't include it, I'll just use the forward declaration.
let myArr = [_x000D_
{ name: "john", age: 23 },_x000D_
{ name: "john", age: 43 },_x000D_
{ name: "jim", age: 101 },_x000D_
{ name: "bob", age: 67 },_x000D_
];_x000D_
_x000D_
// this will return old object (myArr) with items named 'john'_x000D_
let list = _.filter(myArr, item => item.name === 'jhon');_x000D_
_x000D_
// this will return new object referenc (new Object) with items named 'john' _x000D_
let list = _.map(myArr, item => item.name === 'jhon').filter(item => item.name);
_x000D_
You can use option -A (after) and -B (before) in your grep command try grep -nri -A 5 -B 5 .
C++ supplies a string
class that can be used like this:
#include <string>
#include <iostream>
int main() {
std::string Something = "Some text";
std::cout << Something << std::endl;
}
How to design table like this in mongodb?
First, to clarify some naming conventions. MongoDB uses collections
instead of tables
.
I think there are no foreign keys!
Take the following model:
student
{
_id: ObjectId(...),
name: 'Jane',
courses: [
{ course: 'bio101', mark: 85 },
{ course: 'chem101', mark: 89 }
]
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
Clearly Jane's course list points to some specific courses. The database does not apply any constraints to the system (i.e.: foreign key constraints), so there are no "cascading deletes" or "cascading updates". However, the database does contain the correct information.
In addition, MongoDB has a DBRef standard that helps standardize the creation of these references. In fact, if you take a look at that link, it has a similar example.
How can I solve this task?
To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.
You can try following code using Jsoup
String latestVersion = doc.getElementsContainingOwnText("Current Version").parents().first().getAllElements().last().text();
To search google using API you should use Google Custom Search, scraping web page is not allowed
In java you can use CustomSearch API Client Library for Java
The maven dependency is:
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-customsearch</artifactId>
<version>v1-rev57-1.23.0</version>
</dependency>
Example code searching using Google CustomSearch API Client Library
public static void main(String[] args) throws GeneralSecurityException, IOException {
String searchQuery = "test"; //The query to search
String cx = "002845322276752338984:vxqzfa86nqc"; //Your search engine
//Instance Customsearch
Customsearch cs = new Customsearch.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), null)
.setApplicationName("MyApplication")
.setGoogleClientRequestInitializer(new CustomsearchRequestInitializer("your api key"))
.build();
//Set search parameter
Customsearch.Cse.List list = cs.cse().list(searchQuery).setCx(cx);
//Execute search
Search result = list.execute();
if (result.getItems()!=null){
for (Result ri : result.getItems()) {
//Get title, link, body etc. from search
System.out.println(ri.getTitle() + ", " + ri.getLink());
}
}
}
As you can see you will need to request an api key and setup an own search engine id, cx.
Note that you can search the whole web by selecting "Search entire web" on basic tab settings during setup of cx, but results will not be exactly the same as a normal browser google search.
Currently (date of answer) you get 100 api calls per day for free, then google like to share your profit.
I have resolved this problem by adding the reference to System.Web.
Example:
git tag -a v1.2 9fceb02 -m "Message here"
Where 9fceb02
is the beginning part of the commit id.
You can then push the tag using git push origin v1.2
.
You can do git log
to show all the commit id's in your current branch.
There is also a good chapter on tagging in the Pro Git book.
Warning: This creates tags with the current date (and that value is what will show on a GitHub releases page, for example). If you want the tag to be dated with the commit date, please look at another answer.
the mobile solution suggested by Sumit works perfectly for AS3 Air:
html.location = "http://m.facebook.com/logout.php?confirm=1&next=http://yoursitename.com"
Well, the message is pretty much self-explanatory. You did not tell git what your name and email address is.
Open a command line and type:
git config --global user.email "[email protected]"
git config --global user.name "Your Name"
Of course you should enter your real name and email. Afterwards git knows who you are and is able to insert this information in your commits.
Seems like smartgit does not add the git binary to your path. You have to add its path to the PATH environment variable or first change to the corresponding directory. You can find a screencast here: http://blog.dragndream.com/?p=97
I know this is an old post but try using an extension method:
public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
{
return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
}
and use it like this
var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));
Feel free to choose your own dates, you don't have to restrict yourself to January 2000.
I think your question is a bit more general than I originally thought. type()
with one argument returns the type
or class
of the object. So if you have a = 'abc'
and use type(a)
this returns str
because the variable a
is a string. If b = 10
, type(b)
returns int
.
See also python documentation on type().
If you want a comparison you could use: if type(v) == h5py.h5r.Reference
(to check if it is a h5py.h5r.Reference
instance).
But it is recommended that one uses if isinstance(v, h5py.h5r.Reference)
but then also subclasses will evaluate to True
.
If you want to print the class use print v.__class__.__name__
.
More generally: You can compare if two instances have the same class by using type(v) is type(other_v)
or isinstance(v, other_v.__class__)
.
Working code snippet using GetDiskFreeSpaceEx
from link by RichardOD.
// Pinvoke for API function
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out ulong lpFreeBytesAvailable,
out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes);
public static bool DriveFreeBytes(string folderName, out ulong freespace)
{
freespace = 0;
if (string.IsNullOrEmpty(folderName))
{
throw new ArgumentNullException("folderName");
}
if (!folderName.EndsWith("\\"))
{
folderName += '\\';
}
ulong free = 0, dummy1 = 0, dummy2 = 0;
if (GetDiskFreeSpaceEx(folderName, out free, out dummy1, out dummy2))
{
freespace = free;
return true;
}
else
{
return false;
}
}
You should definitely avoid using <jsp:...>
tags. They're relics from the past and should always be avoided now.
Use the JSTL.
Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a
public SomeType getQuestionPaperID() {
//...
}
method in your bean.
Once you have that, you can display the value of this property using this code :
<c:out value="${Questions.questionPaperID}" />
or, to specifically target the session scoped attributes (in case of conflicts between scopes) :
<c:out value="${sessionScope.Questions.questionPaperID}" />
Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
Define the range between the numbers:
r = range(1,10)
Then use it:
if num in r:
print("All right!")