In java synchronization,if a thread want to enter into synchronization method it will acquire lock on all synchronized methods of that object not just on one synchronized method that thread is using. So a thread executing addA() will acquire lock on addA() and addB() as both are synchronized.So other threads with same object cannot execute addB().
You should really think about your intentions: If you need the information now when debugging to fix the test, you will need it next week again when the tests break.
This means that you will need the information always when the test fails - and adding a var_dump
to find the cause is just too much work. Rather put the data into your assertions.
If your code is too complex for that, split it up until you reach a level where one assertion (with a custom message) tells you enough to know where it broke, why and how to fix the code.
Also you should note that if your project is consist of several modules which are dependent on each other, you should use "install" instead of "package", otherwise your build will fail, cause when you use install command, module A will be packaged and deployed to local repository and then if module B needs module A as a dependency, it can access it from local repository.
It seems that you need to pass a flag "-l, --log-file"
https://github.com/elastic/kibana/issues/3407
Usage: kibana [options]
Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.
Options:
-h, --help output usage information
-V, --version output the version number
-e, --elasticsearch <uri> Elasticsearch instance
-c, --config <path> Path to the config file
-p, --port <port> The port to bind to
-q, --quiet Turns off logging
-H, --host <host> The host to bind to
-l, --log-file <path> The file to log to
--plugins <path> Path to scan for plugins
If you use the init script to run as a service, maybe you will need to customize it.
There are many way to skin a cat.
The most simple way is to use the pydoc
function directly from the shell with:
pydoc modules
But for more information use the tool called pip-date that also tell you the installation dates.
pip install pip-date
The case-insensitive marker, (?i)
can be incorporated directly into the regex pattern:
>>> import re
>>> s = 'This is one Test, another TEST, and another test.'
>>> re.findall('(?i)test', s)
['Test', 'TEST', 'test']
I got the error 'AdBrixRM framework not found'. I checked the AdBrixRM.framework. I noticed that 'AdBrixRM' excution file is missed. I copied this file into the framework folder and the issue was gone.
You can use C style string formatting:
"%d:%d:d" % (hours, minutes, seconds)
See here, especially: https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html
I had the same issue with gcc "gnat1" and it was due to the path being wrong. Gnat1 was on version 4.6 but I was executing version 4.8.1, which I had installed. As a temporary solution, I copied gnat1 from 4.6 and pasted under the 4.8.1 folder.
The path to gcc on my computer is /usr/lib/gcc/i686-linux-gnu/
You can find the path by using the find command:
find /usr -name "gnat1"
In your case you would look for cc1plus:
find /usr -name "cc1plus"
Of course, this is a quick solution and a more solid answer would be fixing the broken path.
It's possible, but you have to add some JVM flags when you start your application.
You have to add remote debug configuration: Edit configuration -> Remote.
Then you'lll find in displayed dialog window parametrs that you have to add to program execution, like:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
Then when your application is launched you can attach your debugger. If you want your application to wait until debugger is connected just change suspend flag to y (suspend=y
)
Use the textchange
event via customized jQuery shim for cross-browser input
compatibility. http://benalpert.com/2013/06/18/a-near-perfect-oninput-shim-for-ie-8-and-9.html (most recently forked github: https://github.com/pandell/jquery-splendid-textchange/blob/master/jquery.splendid.textchange.js)
This handles all input tags including <textarea>content</textarea>
, which does not always work with change
keyup
etc. (!) Only jQuery on("input propertychange")
handles <textarea>
tags consistently, and the above is a shim for all browsers that don't understand input
event.
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/pandell/jquery-splendid-textchange/master/jquery.splendid.textchange.js"></script>
<meta charset=utf-8 />
<title>splendid textchange test</title>
<script> // this is all you have to do. using splendid.textchange.js
$('textarea').on("textchange",function(){
yourFunctionHere($(this).val()); });
</script>
</head>
<body>
<textarea style="height:3em;width:90%"></textarea>
</body>
</html>
This also handles paste, delete, and doesn't duplicate effort on keyup.
If not using a shim, use jQuery on("input propertychange")
events.
// works with most recent browsers (use this if not using src="...splendid.textchange.js")
$('textarea').on("input propertychange",function(){
yourFunctionHere($(this).val());
});
Because these days ASP.NET is open source, you can find it on GitHub: AspNet.Identity 3.0 and AspNet.Identity 2.0.
From the comments:
/* =======================
* HASHED PASSWORD FORMATS
* =======================
*
* Version 2:
* PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
* (See also: SDL crypto guidelines v5.1, Part III)
* Format: { 0x00, salt, subkey }
*
* Version 3:
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
* (All UInt32s are stored big-endian.)
*/
Command to install GCC and Development Tools on a CentOS / RHEL 7 server
Type the following yum command as root user:
OR
If above command failed, try:
The most important part about $ is that it has the lowest operator precedence.
If you type info you'll see this:
?> :info ($)
($) :: (a -> b) -> a -> b
-- Defined in ‘GHC.Base’
infixr 0 $
This tells us it is an infix operator with right-associativity that has the lowest possible precedence. Normal function application is left-associative and has highest precedence (10). So $ is something of the opposite.
So then we use it where normal function application or using () doesn't work.
So, for example, this works:
?> head . sort $ "example"
?> e
but this does not:
?> head . sort "example"
because . has lower precedence than sort and the type of (sort "example") is [Char]
?> :type (sort "example")
(sort "example") :: [Char]
But . expects two functions and there isn't a nice short way to do this because of the order of operations of sort and .
Two ways out of possible solutions to achieve this are:
1. Create a .htaccess
file in root folder as under (just replace example.com and my_dir with your corresponding values):
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/my_dir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /my_dir/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ my_dir/index.php [L]
</IfModule>
Use RedirectMatch to only redirect the root URL “/” to another folder or URL,
RedirectMatch ^/$ http://www.example.com/my_dir
Following the documentation of fopen
:
``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.
So if you pFile2=fopen("myfile2.txt", "a");
the stream is positioned at the end to append automatically. just do:
FILE *pFile;
FILE *pFile2;
char buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
perror("Error opening file.");
}
else {
while(fgets(buffer, sizeof(buffer), pFile)) {
fprintf(pFile2, "%s", buffer);
}
}
fclose(pFile);
fclose(pFile2);
Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.
$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'
& $app $arg1 $arg2 $arg3
In Java, you cannot set a value in ArrayList by assigning to it, there's a set()
method to call:
String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)
@sdbrain's answer in Swift 3:
let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")!)
webView.loadRequest(NSURLRequest.init(url: url) as URLRequest)
I realize this may be a bit late, but I stumbled upon this and was wondering how to handle situations with multiple identical values, but different keys (as per bigbearzhu's comment).
So I modified Stephan Muller's answer slightly:
A datalist with non-unique values:
<input list="answers" name="answer" id="answerInput">
<datalist id="answers">
<option value="42">The answer</option>
<option value="43">The answer</option>
<option value="44">Another Answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
When the user selects an option, the browser replaces input.value
with the value
of the datalist
option instead of the innerText
.
The following code then checks for an option
with that value
, pushes that into the hidden field and replaces the input.value
with the innerText
.
document.querySelector('#answerInput').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option[value="'+input.value+'"]'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden');
if (options.length > 0) {
hiddenInput.value = input.value;
input.value = options[0].innerText;
}
});
As a consequence the user sees whatever the option's innerText
says, but the unique id from option.value
is available upon form submit.
Demo jsFiddle
Simple two line code solution using pandas
import pandas as pd
read_file = pd.read_csv ('File name.csv')
read_file.to_excel ('File name.xlsx', index = None, header=True)
This is possible in KeyDB which is a Fork of Redis. Because it's a Fork its fully compatible with Redis and works as a drop in replacement.
Just use the EXPIREMEMBER command. It works with sets, hashes, and sorted sets.
EXPIREMEMBER keyname subkey [time]
You can also use TTL and PTTL to see the expiration
TTL keyname subkey
More documentation is available here: https://docs.keydb.dev/docs/commands/#expiremember
You need to use a regular expression, so that you can specify the global (g) flag:
var s = 'some+multi+word+string'.replace(/\+/g, ' ');
(I removed the $()
around the string, as replace
is not a jQuery method, so that won't work at all.)
You can save old color and then use it to restore the original value. Here is an example:
ColorStateList oldColors = textView.getTextColors(); //save original colors
textView.setTextColor(Color.RED);
....
textView.setTextColor(oldColors);//restore original colors
But in general default TextView
text color is determined from current Theme applied to your Activity
.
I'll assume that you're asking how to push a dependency out to a "well-known repository," and not simply asking how to update your POM.
If yes, then this is what you want to read.
And for anyone looking to set up an internal repository server, look here (half of the problem with using Maven 2 is finding the docs)
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
XCOPY /S folder1\data.zip copy_of_folder1
XCOPY /S folder1\info.txt copy_of_folder1
EDIT: If you want to preserve the empty folders (which, on rereading your post, you seem to) use /E instead of /S.
Instead of choosing Restore Database..., select Restore Files and Filegroups...
Then enter a database name, select your .bak file path as the source, check the restore checkbox, and click Ok. If the .bak file is valid, it will work.
(The SQL Server restore option names are not intuitive for what should a very simple task.)
I had my Apache service not start same as MySQL one. Please follow these steps if none of above tips works :
Note: Ports 80 and 443 must be unused by any program.
If it is in use . Just edit ports. There is a lot of tutorials about that .
We actually just upgraded a .NET web service to 4.6 to allow TLS 1.2.
What Artem is saying were the first steps we've done. We recompiled the framework of the web service to 4.6 and we tried change the registry key to enable TLS 1.2, although this didn't work: the connection was still in TLS 1.0. Also, we didn't want to disallow SLL 3.0, TLS 1.0 or TLS 1.1 on the machine: other web services could be using this; we rolled-back our changes on the registry.
We actually changed the Web.Config files to tell IIS: "hey, run me in 4.6 please".
Here's the changes we added in the web.config + recompilation in .NET 4.6:
<system.web>
<compilation targetFramework="4.6"/> <!-- Changed framework 4.0 to 4.6 -->
<!--Added this httpRuntime -->
<httpRuntime targetFramework="4.6" />
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
And the connection changed to TLS 1.2, because IIS is now running the web service in 4.6 (told explicitly) and 4.6 is using TLS 1.2 by default.
You need to insert the character code that Excel uses, which IIRC is 10 (ten).
EDIT: OK, here's some code. Note that I was able to confirm that the character-code used is indeed 10, by creating a cell containing:
A
B
...and then selecting it and executing this in the VBA immediate window:
?Asc(Mid(Activecell.Value,2,1))
So, the code you need to insert that value into another cell in VBA would be:
ActiveCell.Value = "A" & vbLf & "B"
(since vbLf is character code 10).
I know you're using C# but I find it's much easier to figure out what to do if you first do it in VBA, since you can try it out "interactively" without having to compile anything. Whatever you do in C# is just replicating what you do in VBA so there's rarely any difference. (Remember that the C# interop stuff is just using the same underlying COM libraries as VBA).
Anyway, the C# for this would be:
oCell.Value = "A\nB";
Spot the difference :-)
EDIT 2: Aaaargh! I just re-read the post and saw that you're using the Aspose library. Sorry, in that case I've no idea.
Here's the NoCache
attribute proposed by mattytommo, simplified by using the information from Chris Moschini's answer:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : OutputCacheAttribute
{
public NoCacheAttribute()
{
this.Duration = 0;
}
}
Use formula =row(b2)-x, where x will adjust the entries so that the first S/No is marked as 1 and will increment with the rows.
I'd like to add something that no one has yet mentioned: ng2-input-autocomplete
NPM: https://www.npmjs.com/package/ng2-input-autocomplete
GitHub: https://github.com/liuy97/ng2-input-autocomplete#readme
You should call this function from the controller.
angular.module('App', [])
.controller('CinemaCtrl', ['$scope', function($scope) {
myFunction();
}]);
Even with normal javascript/html your function won't run on page load as all your are doing is defining the function, you never call it. This is really nothing to do with angular, but since you're using angular the above would be the "angular way" to invoke the function.
Obviously better still declare the function in the controller too.
Edit: Actually I see your "onload" - that won't get called as angular injects the HTML into the DOM. The html is never "loaded" (or the page is only loaded once).
If Image folder location is public/assets/img/default.jpg.
You can try in view
<img src="{{ URL::to('/assets/img/default.jpg') }}">
i have same problem what i did i just downloaded 32-bit dll and added it to my bin folder this is solved my problem
I think :hover
was missing in above answers. So following would do the needful.(if css was required)
#myDiv:hover
{
cursor: pointer;
}
First go through this tutorial for getting familiar with Android Google Maps and this for API 2.
To retrive the current location of device see this answer or this another answer and for API 2
Then you can get places near by your location using Google Place API and for use of Place Api see this blog.
After getting Placemarks of near by location use this blog with source code to show markers on map with balloon overlay with API 2.
You also have great sample to draw route between two points on map look here in these links Link1 and Link2 and this Great Answer.
After following these steps you will be easily able to do your application. The only condition is, you will have to read it and understand it, because like magic its not going to be complete in a click.
Concluding from above answers, Here is the exact difference between full/strictly, complete and perfect binary trees
Full/Strictly binary tree :- Every node except the leaf nodes have two children
Complete binary tree :- Every level except the last level is completely filled and all the nodes are left justified.
Perfect binary tree :- Every node except the leaf nodes have two children and every level (last level too) is completely filled.
MIME type of the CSV is text/csv according to RFC 4180.
Note : Use it if calculating / adding days from current date.
Be aware: this answer has issues (see comments)
var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);
It should be like
var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));
I have encountered this with Maven projects too. This is what I had to do to get around the problem:
First update your web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Servlet 3.0 Web Application</display-name>
Then right click on your project and select Properties -> Project Facets In there you will see the version of your Dynamic Web Module. This needs to change from version 2.3 or whatever to version 2.5 or above (I chose 3.0).
However to do this I had to uncheck the tick box for Dynamic Web Module -> Apply, then do a Maven Update on the project. Go back into the Project Facets window and it should already match your web.xml configuration - 3.0 in my case. You should be able to change it if not.
If this does not work for you then try right-clicking on the Dynamic Web Module Facet and select change version (and ensure it is not locked).
Or you can follow this steps:
don't forget to update your project
Hope that works!
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
Sometimes you can refactor your @Component
to use constructor or setter based injection to setup your testcase (you can and still rely on @Autowired
). Now, you can create your test entirely without a mocking framework by implementing test stubs instead (e.g. Martin Fowler's MailServiceStub):
@Component
public class MyLauncher {
private MyService myService;
@Autowired
MyLauncher(MyService myService) {
this.myService = myService;
}
// other methods
}
public class MyServiceStub implements MyService {
// ...
}
public class MyLauncherTest
private MyLauncher myLauncher;
private MyServiceStub myServiceStub;
@Before
public void setUp() {
myServiceStub = new MyServiceStub();
myLauncher = new MyLauncher(myServiceStub);
}
@Test
public void someTest() {
}
}
This technique especially useful if the test and the class under test is located in the same package because then you can use the default, package-private access modifier to prevent other classes from accessing it. Note that you can still have your production code in src/main/java
but your tests in src/main/test
directories.
If you like Mockito then you will appreciate the MockitoJUnitRunner. It allows you to do "magic" things like @Manuel showed you:
@RunWith(MockitoJUnitRunner.class)
public class MyLauncherTest
@InjectMocks
private MyLauncher myLauncher; // no need to call the constructor
@Mock
private MyService myService;
@Test
public void someTest() {
}
}
Alternatively, you can use the default JUnit runner and call the MockitoAnnotations.initMocks() in a setUp()
method to let Mockito initialize the annotated values. You can find more information in the javadoc of @InjectMocks and in a blog post that I have written.
AngularJS form elements look for the required
attribute to perform validation functions. ng-required
allows you to set the required
attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)
As an example, <input required>
and <input ng-required="true">
are essentially the same thing
If you are wondering why this is this way, (and not just make <input required="true">
or <input required="false">
), it is due to the limitations of HTML - the required
attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false"
would be invalid HTML)
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace()
is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g
(global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
Read these answered questions to understand the difference between Cygwin and MinGW.
Question #1: I want to create an application that I write source code once, compile it once and run it in any platforms (e.g. Windows, Linux and Mac OS X…).
Answer #1: Write your source code in JAVA. Compile the source code once and run it anywhere.
Question #2: I want to create an application that I write source code once but there is no problem that I compile the source code for any platforms separately (e.g. Windows, Linux and Mac OS X …).
Answer #2: Write your source code in C or C++. Use standard header files only. Use a suitable compiler for any platform (e.g. Visual Studio for Windows, GCC for Linux and XCode for Mac). Note that you should not use any advanced programming features to compile your source code in all platforms successfully. If you use none C or C++ standard classes or functions, your source code does not compile in other platforms.
Question #3: In answer of question #2, it is difficult using different compiler for each platform, is there any cross platform compiler?
Answer #3: Yes, Use GCC compiler. It is a cross platform compiler. To compile your source code in Windows use MinGW that provides GCC compiler for Windows and compiles your source code to native Windows program. Do not use any advanced programming features (like Windows API) to compile your source code in all platforms successfully. If you use Windows API functions, your source code does not compile in other platforms.
Question #4: C or C++ standard header files do not provide any advanced programming features like multi-threading. What can I do?
Answer #4: You should use POSIX (Portable Operating System Interface [for UNIX]) standard. It provides many advanced programming features and tools. Many operating systems fully or partly POSIX compatible (like Mac OS X, Solaris, BSD/OS and ...). Some operating systems while not officially certified as POSIX compatible, conform in large part (like Linux, FreeBSD, OpenSolaris and ...). Cygwin provides a largely POSIX-compliant development and run-time environment for Microsoft Windows.
Thus:
If you use JDK version from 9+, you should select
Run > Edit Configurations... > Select JUnit template.
Then, select @argfile (Java 9+) as in the image below. Please try it. Good luck friends.
I'm a bit late to the answer, but you may want to do this if you want the whole element, not only the values you want to group by:
var query = doc.Elements("whatever")
.GroupBy(element => new {
id = (int) element.Attribute("id"),
category = (int) element.Attribute("cat") })
.Select(e => e.First());
This will give you the first whole element matching your group by selection, much like Jon Skeets second example using DistinctBy, but without implementing IEqualityComparer comparer. DistinctBy will most likely be faster, but the solution above will involve less code if performance is not an issue.
You can set it to NULL
.
> Data$genome <- NULL
> head(Data)
chr region
1 chr1 CDS
2 chr1 exon
3 chr1 CDS
4 chr1 exon
5 chr1 CDS
6 chr1 exon
As pointed out in the comments, here are some other possibilities:
Data[2] <- NULL # Wojciech Sobala
Data[[2]] <- NULL # same as above
Data <- Data[,-2] # Ian Fellows
Data <- Data[-2] # same as above
You can remove multiple columns via:
Data[1:2] <- list(NULL) # Marek
Data[1:2] <- NULL # does not work!
Be careful with matrix-subsetting though, as you can end up with a vector:
Data <- Data[,-(2:3)] # vector
Data <- Data[,-(2:3),drop=FALSE] # still a data.frame
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
I recently found out that :active:focus
does the same thing in css as :active:hover
if you need to override a custom css library, they might use both.
Use multiselect function as below.
$("#drp_Books_Ill_Illustrations").val(["val1", "val2"]).trigger("change");
Your web_window variable must have gone out of scope when you tried to close the window. Add this line into your _openpageview function to test:
setTimeout(function(){web_window.close();},1000);
You can use regular expressions for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work:
select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual;
which will return "12345569".
also you can use this one:
select regexp_replace('stack12345overflow569', '[^0-9]', '') as numbers,
regexp_replace('Stack12345OverFlow569', '[^a-z and ^A-Z]', '') as characters
from dual
which will return "12345569" for numbers and "StackOverFlow" for characters.
Before messing with too much things, please check the user the service is trying to run as. In my case it was NETWORK this one did not have write permissions to some locations where it was needed. Changing the user to Local System Account did the trick.
If the event viewer shows any error like "Can't create test file C:\Program Files\MySQL\MySQL Server 5.6\data\XXX.lower-test", there is a high probability for this solution to work.
Good luck!
I use this query to get it:
SELECT name FROM sqlite_master WHERE type='table'
And to use in iOS:
NSString *aStrQuery=[NSString stringWithFormat:@"SELECT name FROM sqlite_master WHERE type='table'"];
To brute force all CSV files on your server to download, add in your .htaccess file:
AddType application/octet-stream csv
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");
Note that testers are no longer added via UUID in the new Apple TestFlight.
Test Flight builds now require an App Store Distribution Provisioning Profile. The portal does not allow UUIDs to be added to this type of provisioning profile.
Instead, add "Internal Testers" via iTunes Connect:
Internal testers are iTunes Connect users with the Admin or Technical role. They can be added in Users and Roles.
After adding a user, be sure to click on their name and flip the "Internal Tester" switch.
Then, go to App > Prerelease > Internal Testers
and invite them to the build.
I know this is a bit old, but instead of looping through the array with a for loop, it would be much easier to use the method <array>.indexOf(<element>[, fromIndex])
It loops through an array, finding and returning the first index of a value. If the value is not contained in the array, it returns -1.
<array>
is the array to look through, <element>
is the value you are looking for, and [fromIndex]
is the index to start from (defaults to 0).
I hope this helps reduce the size of your code!
document.getElementById('username').value="moo"
document.forms[0].submit()
In addition to ScarletGarden's comment, you also need to consider the impact of search engines and your redirect. Has this page moved permanently? Temporarily? It makes a difference.
see: Response.Redirect vs. "301 Moved Permanently":
We've all used Response.Redirect at one time or another. It's the quick and easy way to get visitors pointed in the right direction if they somehow end up in the wrong place. But did you know that Response.Redirect sends an HTTP response status code of "302 Found" when you might really want to send "301 Moved Permanently"?
The distinction seems small, but in certain cases it can actually make a big difference. For example, if you use a "301 Moved Permanently" response code, most search engines will remove the outdated link from their index and replace it with the new one. If you use "302 Found", they'll continue returning to the old page...
Use the CSS
property list-style-position
to position the bullet:
list-style-position:inside /* or outside */;
I try to get in the habit of using HostingEnvironment
instead of Server
as it works within the context of WCF services too.
HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml");
My guess is that it indicates "Unicode", is it correct?
Yes.
If so, since when is it available?
Python 2.x.
In Python 3.x the strings use Unicode by default and there's no need for the u
prefix. Note: in Python 3.0-3.2, the u is a syntax error. In Python 3.3+ it's legal again to make it easier to write 2/3 compatible apps.
-- If no parameters need to be passed to a procedure, simply:
BEGIN
MY_PACKAGE_NAME.MY_PROCEDURE_NAME
END;
To only modify the title's font (and not the font of the axis) I used this:
import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})
The fontdict accepts all kwargs from matplotlib.text.Text.
If you're a beginner (like me), the solution may be as simple as making sure the parent folder that the file you're working in is a Java project.
I made the mistake of simply creating a Java folder, then creating a file in the folder and expecting it to work. The file needs to live in a project if you want to avoid this error.
600851475143
cannot be represented as a 32-bit integer (type int
). It can be represented as a 64-bit integer (type long
). long literals in Java end with an "L": 600851475143L
If someone getting this from a rest client (ex. Postman) - You need to set the Header to Accept application/json.
To do this on postman, click on the Headers tab, and add a new key 'Accept' and type the value 'application/json'.
The node.js docs for fs.mkdir
basically defer to the Linux man page for mkdir(2)
. That indicates that EEXIST
will also be indicated if the path exists but isn't a directory which creates an awkward corner case if you go this route.
You may be better off calling fs.stat
which will tell you whether the path exists and if it's a directory in a single call. For (what I'm assuming is) the normal case where the directory already exists, it's only a single filesystem hit.
These fs
module methods are thin wrappers around the native C APIs so you've got to check the man pages referenced in the node.js docs for the details.
The following code is Linux (maybe Unix) only, but it works in a real project.
private double getAverageValueByLinux() throws InterruptedException {
try {
long delay = 50;
List<Double> listValues = new ArrayList<Double>();
for (int i = 0; i < 100; i++) {
long cput1 = getCpuT();
Thread.sleep(delay);
long cput2 = getCpuT();
double cpuproc = (1000d * (cput2 - cput1)) / (double) delay;
listValues.add(cpuproc);
}
listValues.remove(0);
listValues.remove(listValues.size() - 1);
double sum = 0.0;
for (Double double1 : listValues) {
sum += double1;
}
return sum / listValues.size();
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
private long getCpuT throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader("/proc/stat"));
String line = reader.readLine();
Pattern pattern = Pattern.compile("\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)\\D+(\\d+)")
Matcher m = pattern.matcher(line);
long cpuUser = 0;
long cpuSystem = 0;
if (m.find()) {
cpuUser = Long.parseLong(m.group(1));
cpuSystem = Long.parseLong(m.group(3));
}
return cpuUser + cpuSystem;
}
Update as an alternative to the excellent answer from 2010:
You can now use the Get-LocalGroupMember, Get-LocalGroup, Get-LocalUser etc. to get and map users and groups
Example:
PS C:\WINDOWS\system32> Get-LocalGroupMember -name users
ObjectClass Name PrincipalSource
----------- ---- ---------------
User DESKTOP-R05QDNL\someUser1 Local
User DESKTOP-R05QDNL\someUser2 MicrosoftAccount
Group NT AUTHORITY\INTERACTIVE Unknown
You could combine that with Get-LocalUser. Alias glu can also be used instead. Aliases exists for the majority of the new cmndlets.
In case some are wondering (I know you didn't ask about this) Adding users could be for example done like so:
$description = "Netshare user"
$userName = "Test User"
$user = "test.user"
$pwd = "pwd123"
New-LocalUser $user -Password (ConvertTo-SecureString $pwd -AsPlainText -Force) -FullName $userName -Description $description
iconoclast's answer did not work for me.
I upgraded my php from 5.3.* (xampp 1.7.4) to 5.5.* (xampp 1.8.3) and the problem was solved.
Try iconoclast's answer first, if it doesn't work then upgrading might solve the problem.
In most of the cases, deleting all the node packages and then installing them again, solve the problem.
But In my case node_modules folder has not write permission.
The default shortcut key is Ctrl-Alt-C.
The answer may sound silly, but after wasting hours of time, this is how I got it to work
mysql -u root -p
I got the error message
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Even though I was typing the correct password(the temporary password you get when you first install mysql)
I got it right when I typed in the password when the password prompt was blinking
The classpath is the path where the Java Virtual Machine look for user-defined classes, packages and resources in Java programs.
In this context, the format()
method load a template file from this path.
I've come across two strategies for managing diff/merge of binary files with Git on windows.
Tortoise git lets you configure diff/merge tools for different file types based on their file extensions. See 2.35.4.3. Diff/Merge Advanced Settings http://tortoisegit.org/docs/tortoisegit/tgit-dug-settings.html. This strategy of course relys on suitable diff/merge tools being available.
Using git attributes you can specify a tool/command to convert your binary file to text and then let your default diff/merge tool do it's thing. See http://git-scm.com/book/it/v2/Customizing-Git-Git-Attributes. The article even gives an example of using meta data to diff images.
I got both strategies to work with binary files of software models, but we went with tortoise git as the configuration was easy.
Updated for Angular 5
import { Directive, HostListener, Input } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector : '[href]'
})
export class HrefDirective {
@Input() public href: string | undefined;
@HostListener('click', ['$event']) public onClick(event: Event): void {
if (!this.href || this.href === '#' || (this.href && this.href.length === 0)) {
event.preventDefault();
}
}
}
Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.
In the case the first arg is '-v', then do your conditional ps -ef
, else in all other cases throw the usage.
#!/bin/sh
case $1 in
'-v') if [ "$1" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi;;
*) echo "usage: $0 [-v]"
exit 1;; #It is good practice to throw a code, hence allowing $? check
esac
If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.
#!/bin/sh
usage ()
{
echo "usage: $0 [-v]"
exit 1
}
unset arg_match
for arg in $*
do
case $arg in
'-v') if [ "$arg" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi
arg_match=1;; # this is set, but could increment.
*) ;;
esac
done
if [ ! $arg_match ]
then
usage
fi
But, allow multiple occurrences of an argument is convenient to use in situations such as:
$ adduser -u:sam -s -f -u:bob -trace -verbose
We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:
$ adduser -u sam -s -f -u bob -trace -verbose
It's very simple.
You can call it from anywhere in APP.
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("Hello from Terminal");
Well, if you are going to iterate anyhow, why don't use the simplest method of all, df['Column'].values[i]
df['Column'] = ''
for i in range(len(df)):
df['Column'].values[i] = something/update/new_value
Or if you want to compare the new values with old or anything like that, why not store it in a list and then append in the end.
mylist, df['Column'] = [], ''
for <condition>:
mylist.append(something/update/new_value)
df['Column'] = mylist
Here are a few additional tips on testing rules that may ease the debugging for users on shared hosting
When testing a new rule, add a condition to only execute it with a fake
user-agent that you will use for your requests. This way it will not affect anyone else on your site.
e.g
#protect with a fake user agent
RewriteCond %{HTTP_USER_AGENT} ^my-fake-user-agent$
#Here is the actual rule I am testing
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^ http://www.domain.com%{REQUEST_URI} [L,R=302]
If you are using Firefox, you can use the User Agent Switcher to create the fake user agent string and test.
I have seen so many posts where people are still testing their rules and they are using 301's. DON'T.
If you are not using suggestion 1 on your site, not only you, but anyone visiting your site at the time will be affected by the 301.
Remember that they are permanent, and aggressively cached by your browser. Use a 302 instead till you are sure, then change it to a 301.
If your rule does not work and it looks right to you, and you were not using suggestions 1 and 2, then re-test after clearing your browser cache or while in private browsing.
Use a HTTP capture tool like Fiddler to see the actual HTTP traffic between your browser and the server.
While others might say that your site does not look right
, you could instead see and report that all of the images, css and js are returning 404 errors
, quickly narrowing down the problem.
While others will report that you started at URL A and ended at URL C
, you will be able to see that they started at URL A, were 302 redirected to URL B and 301 redirected to URL C
. Even if URL C was the ultimate goal, you will know that this is bad for SEO and needs to be fixed.
You will be able to see cache headers that were set on the server side, replay requests, modify request headers to test ....
If you don't want to create a new dataframe, or if your dataframe has more columns than just the ones you want to split, you could:
df["flips"], df["row_name"] = zip(*df["row"].str.split().tolist())
del df["row"]
You can do it with dynamic_cast
(at least for polymorphic types).
Actually, on second thought--you can't tell if it is SPECIFICALLY a particular type with dynamic_cast
--but you can tell if it is that type or any subclass thereof.
template <class DstType, class SrcType>
bool IsType(const SrcType* src)
{
return dynamic_cast<const DstType*>(src) != nullptr;
}
Thanks to 0A0D for a great answer. I've had good luck with it. Darin Dimitrov also makes a good argument about limiting the complexity of your JS files. Still, I do find occasions where collapsing functions to their definitions makes browsing through a file much easier.
Regarding #region in general, this SO Question covers it quite well.
I have made a few modifications to the Macro to support more advanced code collapse. This method allows you to put a description after the //#region keyword ala C# and shows it in the code as shown:
Example code:
//#region InputHandler
var InputHandler = {
inputMode: 'simple', //simple or advanced
//#region filterKeys
filterKeys: function(e) {
var doSomething = true;
if (doSomething) {
alert('something');
}
},
//#endregion filterKeys
//#region handleInput
handleInput: function(input, specialKeys) {
//blah blah blah
}
//#endregion handleInput
};
//#endregion InputHandler
Updated Macro:
Option Explicit On
Option Strict On
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Imports System.Collections.Generic
Public Module JsMacros
Sub OutlineRegions()
Dim selection As EnvDTE.TextSelection = CType(DTE.ActiveDocument.Selection, EnvDTE.TextSelection)
Const REGION_START As String = "//#region"
Const REGION_END As String = "//#endregion"
selection.SelectAll()
Dim text As String = selection.Text
selection.StartOfDocument(True)
Dim startIndex As Integer
Dim endIndex As Integer
Dim lastIndex As Integer = 0
Dim startRegions As New Stack(Of Integer)
Do
startIndex = text.IndexOf(REGION_START, lastIndex)
endIndex = text.IndexOf(REGION_END, lastIndex)
If startIndex = -1 AndAlso endIndex = -1 Then
Exit Do
End If
If startIndex <> -1 AndAlso startIndex < endIndex Then
startRegions.Push(startIndex)
lastIndex = startIndex + 1
Else
' Outline region ...
Dim tempStartIndex As Integer = CInt(startRegions.Pop())
selection.MoveToLineAndOffset(CalcLineNumber(text, tempStartIndex), CalcLineOffset(text, tempStartIndex))
selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
selection.OutlineSection()
lastIndex = endIndex + 1
End If
Loop
selection.StartOfDocument()
End Sub
Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer) As Integer
Dim lineNumber As Integer = 1
Dim i As Integer = 0
While i < index
If text.Chars(i) = vbLf Then
lineNumber += 1
i += 1
End If
If text.Chars(i) = vbCr Then
lineNumber += 1
i += 1
If text.Chars(i) = vbLf Then
i += 1 'Swallow the next vbLf
End If
End If
i += 1
End While
Return lineNumber
End Function
Private Function CalcLineOffset(ByVal text As String, ByVal index As Integer) As Integer
Dim offset As Integer = 1
Dim i As Integer = index - 1
'Count backwards from //#region to the previous line counting the white spaces
Dim whiteSpaces = 1
While i >= 0
Dim chr As Char = text.Chars(i)
If chr = vbCr Or chr = vbLf Then
whiteSpaces = offset
Exit While
End If
i -= 1
offset += 1
End While
'Count forwards from //#region to the end of the region line
i = index
offset = 0
Do
Dim chr As Char = text.Chars(i)
If chr = vbCr Or chr = vbLf Then
Return whiteSpaces + offset
End If
offset += 1
i += 1
Loop
Return whiteSpaces
End Function
End Module
Passing data from one Activity to Activity in android
An intent contains the action and optionally additional data. The data can be passed to other activity using intent putExtra()
method. Data is passed as extras and are key/value pairs
. The key is always a String. As value you can use the primitive data types int, float, chars, etc. We can also pass Parceable and Serializable
objects from one activity to other.
Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);
Retrieving bundle data from android activity
You can retrieve the information using getData()
methods on the Intent object. The Intent object can be retrieved via the getIntent()
method.
Intent intent = getIntent();
if (null != intent) { //Null Checking
String StrData= intent.getStringExtra(KEY);
int NoOfData = intent.getIntExtra(KEY, defaultValue);
boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
char charData = intent.getCharExtra(KEY, defaultValue);
}
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParameters,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(httpParameters, true);
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 35 * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30 * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
NewScores is an alias to Scores table - it looks like you can combine the queries as follows:
SELECT
ROW_NUMBER() OVER( ORDER BY NETT) AS Rank,
Name,
FlagImg,
Nett,
Rounds
FROM (
SELECT
Members.FirstName + ' ' + Members.LastName AS Name,
CASE
WHEN MenuCountry.ImgURL IS NULL THEN
'~/images/flags/ismygolf.png'
ELSE
MenuCountry.ImgURL
END AS FlagImg,
AVG(CAST(NewScores.NetScore AS DECIMAL(18, 4))) AS Nett,
COUNT(Score.ScoreID) AS Rounds
FROM
Members
INNER JOIN
Score NewScores
ON Members.MemberID = NewScores.MemberID
LEFT OUTER JOIN MenuCountry
ON Members.Country = MenuCountry.ID
WHERE
Members.Status = 1
AND NewScores.InsertedDate >= DATEADD(mm, -3, GETDATE())
GROUP BY
Members.FirstName + ' ' + Members.LastName,
MenuCountry.ImgURL
) AS Dertbl
ORDER BY;
In my case, it was very slow and i needed to change inspections settings, i tried everything, the only thing that worked was going from 2018.2 version to 2016.2, sometimes is better to be some updates behind...
I believe VirtualBox is throwing this error for a number of reasons. Very annoying that it's one error for so many things but, I guess it's the same requirement it's just that the root cause is different.
Potential gotchas:
So for my little mess around machine that I'm resurrecting that has 8GB RAM but only a ye-olde Core i3, I'm having success if I install: 32 bit version of linux, allocating 2.5GB RAM.
Oh, and wherever I say "VT-x" above, that obviously applies equally to AMD's "AMD-V" virtualization tech.
I hope that helps.
I realize that this is an old question with many fine answers. However when I found this I also found a more recent article on TechNet by Saeid Hasani
T-SQL: How to Generate Random Passwords
While the solution focuses on passwords it applies to the general case. Saeid works through various considerations to arrive at a solution. It is very instructive.
A script containing all the code blocks form the article is separately available via the TechNet Gallery, but I would definitely start at the article.
First of all, Android does not recommend you to do that within the back button, but rather using the lifecycle methods provided. The back button should not destroy the Activity.
Activities are being added to the stack, accessible from the Overview (square button since they introduced the Material design in 5.0) when the back button is pressed on the last remaining Activity from the UI stack. If the user wants to close down your app, they should swipe it off (close it) from the Overview menu.
Your app is responsible to stop any background tasks and jobs you don't want to run, on onPause(), onStop() and onDestroy() lifecycle methods. Please read more about the lifecycles and their proper implementation here: http://developer.android.com/training/basics/activity-lifecycle/stopping.html
But to answer your question, you can do hacks to implement the exact behaviour you want, but as I said, it is not recommended:
@Override
public void onBackPressed() {
// make sure you have this outcommented
// super.onBackPressed();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
you can use Session.Remove() method; Session.Remove
Session.Remove("yourSessionName");
There should only be one element with a given id. If you're stuck with that situation, see the 2nd half of my answer for options.
How a browser behaves when you have multiple elements with the same id (illegal HTML) is not defined by specification. You could test all the browsers and find out how they behave, but it's unwise to use this configuration or rely on any particular behavior.
Use classes if you want multiple objects to have the same identifier.
<div>
<span class="a">1</span>
<span class="a">2</span>
<span>3</span>
</div>
$(function() {
var w = $("div");
console.log($(".a").length); // 2
console.log($("body .a").length); // 2
console.log($(".a", w).length); // 2
});
If you want to reliably look at elements with IDs that are the same because you can't fix the document, then you will have to do your own iteration as you cannot rely on any of the built in DOM functions.
You could do so like this:
function findMultiID(id) {
var results = [];
var children = $("div").get(0).children;
for (var i = 0; i < children.length; i++) {
if (children[i].id == id) {
results.push(children[i]);
}
}
return(results);
}
Or, using jQuery:
$("div *").filter(function() {return(this.id == "a");});
jQuery working example: http://jsfiddle.net/jfriend00/XY2tX/.
As to Why you get different results, that would have to do with the internal implementation of whatever piece of code was carrying out the actual selector operation. In jQuery, you could study the code to find out what any given version was doing, but since this is illegal HTML, there is no guarantee that it will stay the same over time. From what I've seen in jQuery, it first checks to see if the selector is a simple id like #a
and if so, just used document.getElementById("a")
. If the selector is more complex than that and querySelectorAll()
exists, jQuery will often pass the selector off to the built in browser function which will have an implementation specific to that browser. If querySelectorAll()
does not exist, then it will use the Sizzle selector engine to manually find the selector which will have it's own implementation. So, you can have at least three different implementations all in the same browser family depending upon the exact selector and how new the browser is. Then, individual browsers will all have their own querySelectorAll()
implementations. If you want to reliably deal with this situation, you will probably have to use your own iteration code as I've illustrated above.
One of the earlier solutions almost worked. I tried something slightly different and it ended up working for me.
(Make sure you look at his solution) This was his solution.. Click Here It worked except for: builder.getContext().getTheme().applyStyle(R.style.Theme_Window_NoMinWidth, true);
I changed it to
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get layout inflater
LayoutInflater layoutInflater = getActivity().getLayoutInflater();
// Set layout by setting view that is returned from inflating the XML layout
builder.setView(layoutInflater.inflate(R.layout.dialog_window_layout, null));
AlertDialog dialog = builder.create();
dialog.getContext().setTheme(R.style.Theme_Window_NoMinWidth);
The last line is whats different really.
You can use the getDeclaredConstructor
method of Class. It expects an array of classes. Here is a tested and working example:
public static JFrame createJFrame(Class c, String name, Component parentComponent)
{
try
{
JFrame frame = (JFrame)c.getDeclaredConstructor(new Class[] {String.class}).newInstance("name");
if (parentComponent != null)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else
{
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
frame.setLocationRelativeTo(parentComponent);
frame.pack();
frame.setVisible(true);
}
catch (InstantiationException instantiationException)
{
ExceptionHandler.handleException(instantiationException, parentComponent, Language.messages.get(Language.InstantiationExceptionKey), c.getName());
}
catch(NoSuchMethodException noSuchMethodException)
{
//ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.NoSuchMethodExceptionKey, "NamedConstructor");
ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.messages.get(Language.NoSuchMethodExceptionKey), "(Constructor or a JFrame method)");
}
catch (IllegalAccessException illegalAccessException)
{
ExceptionHandler.handleException(illegalAccessException, parentComponent, Language.messages.get(Language.IllegalAccessExceptionKey));
}
catch (InvocationTargetException invocationTargetException)
{
ExceptionHandler.handleException(invocationTargetException, parentComponent, Language.messages.get(Language.InvocationTargetExceptionKey));
}
finally
{
return null;
}
}
function stripTrailingSlash(str) {
if(str.substr(-1) === '/') {
return str.substr(0, str.length - 1);
}
return str;
}
Note: IE8 and older do not support negative substr offsets. Use str.length - 1
instead if you need to support those ancient browsers.
I had 20.8 GB in the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder (6 android images: - android-10 - android-15 - android-21 - android-23 - android-25 - android-26 ).
I have compressed the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder.
Now it takes only 4.65 GB.
I did not encountered any problem up to now...
Compression seems to vary from 2/3 to 6, sometimes much more:
c_harm's answer is in my opinion the best. Please note that if you want to use
"My string".truncate(n)
you will have to use a regexp object constructor rather than a literal. Also you'll have to escape the \S
when converting it.
String.prototype.truncate =
function(n){
var p = new RegExp("^.{0," + n + "}[\\S]*", 'g');
var re = this.match(p);
var l = re[0].length;
var re = re[0].replace(/\s$/,'');
if (l < this.length) return re + '…';
};
try to use this pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'values', pure: false })
export class ValuesPipe implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => value[key]);
}
}
<div *ngFor="#value of object | values"> </div>
You can use Spacers if all you want is a little bit of spacing between items in a row. The example below centers 2 Text widgets within a row with some spacing between them.
Spacer creates an adjustable, empty spacer that can be used to tune the spacing between widgets in a Flex
container, like Row
or Column
.
In a row
, if we want to put space between two widgets such that it occupies all remaining space.
widget = Row (
children: <Widget>[
Spacer(flex: 20),
Text(
"Item #1",
),
Spacer(), // Defaults to flex: 1
Text(
"Item #2",
),
Spacer(flex: 20),
]
);
This usually occurs when your current directory does not exist anymore. Most likely, from another terminal you remove that directory (from within a script or whatever). To get rid of this, in case your current directory was recreated in the meantime, just cd
to another (existing) directory and then cd
back; the simplest would be: cd; cd -
.
With AngularJS
:
angular.element('#Element')[0].focus();
In this particular case, a viewModel is required to launch the task and notify the view upon its completion. An "async property", not an "async constructor", is in order.
I just released AsyncMVVM, which solves exactly this problem (among others). Should you use it, your ViewModel would become:
public class ViewModel : AsyncBindableBase
{
public ObservableCollection<TData> Data
{
get { return Property.Get(GetDataAsync); }
}
private Task<ObservableCollection<TData>> GetDataAsync()
{
//Get the data asynchronously
}
}
Strangely enough, Silverlight is supported. :)
Just to give it a name closer to it's actual action. "fill_parent"
does not fill the remaining space as the name would imply (for that you use the weight attribute). Instead, it takes up as much space as its layout parent. That's why the new name is "match_parent"
Also very helpful, while investigating the Environment.SpecialFolder
enum. Use LINQPad or create a solution and execute this code:
Enum.GetValues(typeof(Environment.SpecialFolder))
.Cast<Environment.SpecialFolder>()
.Select(specialFolder => new
{
Name = specialFolder.ToString(),
Path = Environment.GetFolderPath(specialFolder)
})
.OrderBy(item => item.Path.ToLower())
This is the result on my machine:
MyComputer
LocalizedResources
CommonOemLinks
ProgramFiles C:\Program Files (x86)
ProgramFilesX86 C:\Program Files (x86)
CommonProgramFiles C:\Program Files (x86)\Common Files
CommonProgramFilesX86 C:\Program Files (x86)\Common Files
CommonApplicationData C:\ProgramData
CommonStartMenu C:\ProgramData\Microsoft\Windows\Start Menu
CommonPrograms C:\ProgramData\Microsoft\Windows\Start Menu\Programs
CommonAdminTools C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools
CommonStartup C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
CommonTemplates C:\ProgramData\Microsoft\Windows\Templates
UserProfile C:\Users\fisch
LocalApplicationData C:\Users\fisch\AppData\Local
CDBurning C:\Users\fisch\AppData\Local\Microsoft\Windows\Burn\Burn
History C:\Users\fisch\AppData\Local\Microsoft\Windows\History
InternetCache C:\Users\fisch\AppData\Local\Microsoft\Windows\INetCache
Cookies C:\Users\fisch\AppData\Local\Microsoft\Windows\INetCookies
ApplicationData C:\Users\fisch\AppData\Roaming
NetworkShortcuts C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Network Shortcuts
PrinterShortcuts C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
Recent C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Recent
SendTo C:\Users\fisch\AppData\Roaming\Microsoft\Windows\SendTo
StartMenu C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu
Programs C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
AdminTools C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Administrative Tools
Startup C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Templates C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Templates
Desktop C:\Users\fisch\Desktop
DesktopDirectory C:\Users\fisch\Desktop
Favorites C:\Users\fisch\Favorites
MyMusic C:\Users\fisch\Music
MyDocuments C:\Users\fisch\OneDrive\Documents
MyDocuments C:\Users\fisch\OneDrive\Documents
MyPictures C:\Users\fisch\OneDrive\Pictures
MyVideos C:\Users\fisch\Videos
CommonDesktopDirectory C:\Users\Public\Desktop
CommonDocuments C:\Users\Public\Documents
CommonMusic C:\Users\Public\Music
CommonPictures C:\Users\Public\Pictures
CommonVideos C:\Users\Public\Videos
Windows C:\Windows
Fonts C:\Windows\Fonts
Resources C:\Windows\resources
System C:\Windows\system32
SystemX86 C:\Windows\SysWoW64
("fisch" is the first 5 letters of my last name. This is the user name assigned when signing in with a Microsoft Account.)
var object = {
key1 : {
name : 'xxxxxx',
value : '100.0'
},
key2 : {
name : 'yyyyyyy',
value : '200.0'
},
key3 : {
name : 'zzzzzz',
value : '500.0'
},
}
If thats how your object looks and you want to loop each name and value then I would try and do something like.
$.each(object,function(key,innerjson){
/*
key would be key1,key2,key3
innerjson would be the name and value **
*/
//Alerts and logging of the variable.
console.log(innerjson); //should show you the value
alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});
If anyone wants the true solution for centering BOTH images and text within a span using bootstrap row-fluid, here it is (how to implement this and explanation follows my example):
css
div.row-fluid [class*="span"] .center-in-span {
float: none;
margin: 0 auto;
text-align: center;
display: block;
width: auto;
height: auto;
}
html
<div class="row-fluid">
<div class="span12">
<img class="center-in-span" alt="MyExample" src="/path/to/example.jpg"/>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<p class="center-in-span">this is text</p>
</div>
</div>
USAGE: To use this css to center an image within a span, simply apply the .center-in-span class to the img element, as shown above.
To use this css to center text within a span, simply apply the .center-in-span class to the p element, as shown above.
EXPLANATION: This css works because we are overriding specific bootstrap styling. The notable differences from the other answers that were posted are that the width and height are set to auto, so you don't have to used a fixed with (good for a dynamic webpage). also, the combination of setting the margin to auto, text-align:center and display:block, takes care of both images and paragraphs.
Let me know if this is thorough enough for easy implementation.
All to complicated... Go with Caliburn Micro (http://caliburnmicro.codeplex.com/)
View:
<TreeView Micro:Message.Attach="[Event SelectedItemChanged] = [Action SetSelectedItem($this.SelectedItem)]" />
ViewModel:
public void SetSelectedItem(YourNodeViewModel item) {};
Use a third-party JavaScript library. It will give you that and much more. A good example is datatables (if you are also using jQuery): https://datatables.net
Or just order your bound array in $scope.results when the header is clicked.
As we know the height of a heap is log(n), where n is the total number of elements.Lets represent it as h
When we perform heapify operation, then the elements at last level(h) won't move even a single step.
The number of elements at second last level(h-1) is 2h-1 and they can move at max 1 level(during heapify).
Similarly, for the ith, level we have 2i elements which can move h-i positions.
Therefore total number of moves=S= 2h*0+2h-1*1+2h-2*2+...20*h
S=2h {1/2 + 2/22 + 3/23+ ... h/2h} -------------------------------------------------1
this is AGP series, to solve this divide both sides by 2
S/2=2h {1/22 + 2/23+ ... h/2h+1} -------------------------------------------------2
subtracting equation 2 from 1 gives
S/2=2h {1/2+1/22 + 1/23+ ...+1/2h+ h/2h+1}
S=2h+1 {1/2+1/22 + 1/23+ ...+1/2h+ h/2h+1}
now 1/2+1/22 + 1/23+ ...+1/2h is decreasing GP whose sum is less than 1 (when h tends to infinity, the sum tends to 1). In further analysis, let's take an upper bound on the sum which is 1.
This gives S=2h+1{1+h/2h+1}
=2h+1+h
~2h+h
as h=log(n), 2h=n
Therefore S=n+log(n)
T(C)=O(n)
Here how you can print without using Data::Dumper
print "@{[%hash]}";
Using create will cause one query per new item. If you want to reduce the number of INSERT queries, you'll need to use something else.
I've had some success using the Bulk Insert snippet, even though the snippet is quite old. Perhaps there are some changes required to get it working again.
In order to vertically and horizontally center an element we can also use below mentioned properties.
This CSS property aligns-items vertically and accepts the following values:
flex-start: Items align to the top of the container.
flex-end: Items align to the bottom of the container.
center: Items align at the vertical center of the container.
baseline: Items display at the baseline of the container.
stretch: Items are stretched to fit the container.
This CSS property justify-content , which aligns items horizontally and accepts the following values:
flex-start: Items align to the left side of the container.
flex-end: Items align to the right side of the container.
center: Items align at the center of the container.
space-between: Items display with equal spacing between them.
space-around: Items display with equal spacing around them.
You could set both left
and right
property to 0
. This will make the div stretch to the document width, but requires that no parent element is positioned (which is not the case, seeing as #header
is position: relative;
)
#site_nav_global_primary {
position: absolute;
top: 0;
left: 0;
right: 0;
}
Demo at: http://jsfiddle.net/xWnq2/, where I removed position:relative;
from #header
I have found a useful article that also explains the topic quite clearly and easy language. Link is JSONP
Some of the worth noting points are:
Working is as follows:
<script src="url?callback=function_name">
is included in the html code((1,2,3,4),
(5,6,7,8),
(9,0,1,2))
Using tuples instead of lists makes it marginally harder to change the data structure in unwanted ways.
If you are going to do extensive use of those, you are best off wrapping a true number array in a class, so you can define methods and properties on them. (Or, you could NumPy, SciPy, ... if you are going to do your processing with those libraries.)
select * from
(select
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_FruitType DESC) as tt
,*
from tblFruit
) a
where a.tt=1
You can use .filter()
with boolean operators ie &&:
var find = my_array.filter(function(result) {
return result.param1 === "srting1" && result.param2 === 'string2';
});
return find[0];
AFAIK the delay method only works for numeric CSS modifications.
For other purposes JavaScript comes with a setTimeout method:
window.setTimeout(function(){$("#div").removeClass("error");}, 1000);
invisible(cat("Dataset: ", dataset, fill = TRUE))
invisible(cat(" Width: " ,width, fill = TRUE))
invisible(cat(" Bin1: " ,bin1interval, fill = TRUE))
invisible(cat(" Bin2: " ,bin2interval, fill = TRUE))
invisible(cat(" Bin3: " ,bin3interval, fill = TRUE))
produces output without NULL at the end of the line or on the next line
Dataset: 17 19 26 29 31 32 34 45 47 51 52 59 60 62 63
Width: 15.33333
Bin1: 17 32.33333
Bin2: 32.33333 47.66667
Bin3: 47.66667 63
While we are talking about STL, maps and dictionary, I'd recommend taking a look at the C5 library. It offers several types of dictionaries and maps that I've frequently found useful (along with many other interesting and useful data structures).
If you are a C++ programmer moving to C# as I did, you'll find this library a great resource (and a data structure for this dictionary).
-Paul
After struggling a lot, I finally found a solution, here we go -
Download the file jtds-1.3.1.jar
and ntlmauth.dll
and save it in Program File -> Java -> JDK -> jre -> bin.
Then use the following code -
String pPSSDBDriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(pPSSDBDriverName);
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://<ur_server:port>;UseNTLMv2=true;Domain=AD;Trusted_Connection=yes");
stmt = conn.createStatement();
String sql = " DELETE FROM <data> where <condition>;
stmt.executeUpdate(sql);
Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.
I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.
here is a copy of the script I made for your solution but have dos2unix installed.
#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"
this script has been tested on 3 machines with no errors.
Yes, Google Custom Search has now replaced the old Search API, but you can still use Google Custom Search to search the entire web, although the steps are not obvious from the Custom Search setup.
To create a Google Custom Search engine that searches the entire web:
Now your custom search engine will search the entire web.
Pricing
Source: https://developers.google.com/custom-search/json-api/v1/overview#Pricing
https://perldoc.perl.org/perlre.html#Quoting-metacharacters and https://perldoc.perl.org/functions/quotemeta.html
In the official documentation, such characters are called metacharacters. Example of quoting:
my $regex = quotemeta($string)
s/$regex/something/
Calculating point around circumference of circle given distance travelled.
For comparison...
This may be useful in Game AI when moving around a solid object in a direct path.
public static Point DestinationCoordinatesArc(Int32 startingPointX, Int32 startingPointY,
Int32 circleOriginX, Int32 circleOriginY, float distanceToMove,
ClockDirection clockDirection, float radius)
{
// Note: distanceToMove and radius parameters are float type to avoid integer division
// which will discard remainder
var theta = (distanceToMove / radius) * (clockDirection == ClockDirection.Clockwise ? 1 : -1);
var destinationX = circleOriginX + (startingPointX - circleOriginX) * Math.Cos(theta) - (startingPointY - circleOriginY) * Math.Sin(theta);
var destinationY = circleOriginY + (startingPointX - circleOriginX) * Math.Sin(theta) + (startingPointY - circleOriginY) * Math.Cos(theta);
// Round to avoid integer conversion truncation
return new Point((Int32)Math.Round(destinationX), (Int32)Math.Round(destinationY));
}
/// <summary>
/// Possible clock directions.
/// </summary>
public enum ClockDirection
{
[Description("Time moving forwards.")]
Clockwise,
[Description("Time moving moving backwards.")]
CounterClockwise
}
private void ButtonArcDemo_Click(object sender, EventArgs e)
{
Brush aBrush = (Brush)Brushes.Black;
Graphics g = this.CreateGraphics();
var startingPointX = 125;
var startingPointY = 75;
for (var count = 0; count < 62; count++)
{
var point = DestinationCoordinatesArc(
startingPointX: startingPointX, startingPointY: startingPointY,
circleOriginX: 75, circleOriginY: 75,
distanceToMove: 5,
clockDirection: ClockDirection.Clockwise, radius: 50);
g.FillRectangle(aBrush, point.X, point.Y, 1, 1);
startingPointX = point.X;
startingPointY = point.Y;
// Pause to visually observe/confirm clock direction
System.Threading.Thread.Sleep(35);
Debug.WriteLine($"DestinationCoordinatesArc({point.X}, {point.Y}");
}
}
very simple
<img onload="loaded(this, 'success')" onerror="error(this,
'error')" src="someurl" alt="" />
function loaded(_this, status){
console.log(_this, status)
// do your work in load
}
function error(_this, status){
console.log(_this, status)
// do your work in error
}
The following code does what is required
function doTest() {
SpreadsheetApp.getActiveSheet().getRange('F2').setValue('Hello');
}
You can use axis
:
> axis(side=1, at=c(0:23))
That is, something like this:
plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()
Python3. Use inspect to capture the calling local namespace then use ideas presented here. Can return more than one answer as has been pointed out.
def varname(var):
import inspect
frame = inspect.currentframe()
var_id = id(var)
for name in frame.f_back.f_locals.keys():
try:
if id(eval(name)) == var_id:
return(name)
except:
pass
Besides using Start-Process -Wait
, piping the output of an executable will make Powershell wait. Depending on the need, I will typically pipe to Out-Null
, Out-Default
, Out-String
or Out-String -Stream
. Here is a long list of some other output options.
# Saving output as a string to a variable.
$output = ping.exe example.com | Out-String
# Filtering the output.
ping stackoverflow.com | where { $_ -match '^reply' }
# Using Start-Process affords the most control.
Start-Process -Wait SomeExecutable.com
I do miss the CMD/Bash style operators that you referenced (&, &&, ||). It seems we have to be more verbose with Powershell.
By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.
(\s|\(|\.|,|^)bqr(\s|,|\)|$)
delete this line:
jsonp: 'jsonp_callback',
Or replace this line:
url: 'http://url.of.my.server/submit?callback=json_callback',
because currently you are asking jQuery to create a random callback function name with callback=?
and then telling jQuery that you want to use jsonp_callback
instead.
this would probably call for a many-to-many relation ship as follows
public class Person{
private Long personId;
@manytomany
private Set skills;
//Getters and setters
}
public class Skill{
private Long skillId;
private String skillName;
@manyToMany(MappedBy="skills,targetClass="Person")
private Set persons; // (people would not be a good convenion)
//Getters and setters
}
you may need to define a joinTable + JoinColumn but it will possible work also without...
"ls".execute()
returns a Process
object which is why "ls".execute().text
works. You should be able to just read the error stream to determine if there were any errors.
There is a extra method on Process
that allow you to pass a StringBuffer
to retrieve the text: consumeProcessErrorStream(StringBuffer error)
.
Example:
def proc = "ls".execute()
def b = new StringBuffer()
proc.consumeProcessErrorStream(b)
println proc.text
println b.toString()
You can do that using FileInfo
class:
FileInfo fi = new FileInfo("path");
var created = fi.CreationTime;
var lastmodified = fi.LastWriteTime;
I'm not sure that there is any option for simply printing the full effective search path.
But: the search path consists of directories specified by -L
options on the command line, followed by directories added to the search path by SEARCH_DIR("...")
directives in the linker script(s). So you can work it out if you can see both of those, which you can do as follows:
If you're invoking ld
directly:
-L
options are whatever you've said they are.--verbose
option. Look for the SEARCH_DIR("...")
directives, usually near the top of the output. (Note that these are not necessarily the same for every invocation of ld
-- the linker has a number of different built-in default linker scripts, and chooses between them based on various other linker options.)If you're linking via gcc
:
-v
option to gcc
so that it shows you how it invokes the linker. In fact, it normally does not invoke ld
directly, but indirectly via a tool called collect2
(which lives in one of its internal directories), which in turn invokes ld
. That will show you what -L
options are being used.-Wl,--verbose
to the gcc
options to make it pass --verbose
through to the linker, to see the linker script as described above.@Mock
creates a mock. @InjectMocks
creates an instance of the class and injects the mocks that are created with the @Mock
(or @Spy
) annotations into this instance.
Note you must use @RunWith(MockitoJUnitRunner.class)
or Mockito.initMocks(this)
to initialize these mocks and inject them (JUnit 4).
With JUnit 5, you must use @ExtendWith(MockitoExtension.class)
.
@RunWith(MockitoJUnitRunner.class) // JUnit 4
// @ExtendWith(MockitoExtension.class) for JUnit 5
public class SomeManagerTest {
@InjectMocks
private SomeManager someManager;
@Mock
private SomeDependency someDependency; // this will be injected into someManager
// tests...
}
You definitely want to use the second expression since months in JS are enumerated from 0.
Also you may use Date.parse method, but it uses different date format:
var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);
You might execute something like this in the database:
select "insert into targettable(field1, field2, ...) values(" || field1 || ", " || field2 || ... || ");"
from targettable;
Something more sophisticated is here.
JAVA_HOME
is not necessary if you start java and javac from the command line. But JAVA_HOME
should point to the real jdk directory, C:\Program Files\Java\jdk1.7.0
in your case.
I'd never use the CLASSPATH
environment variable outside of build scripts, especially not global defined. The -cp
flag is better. But in your case, as you do not need additional libraries (rt.jar
doesn't count), you won't need a classpath declaration. A missing -cp
is equivalent to a -cp .
and that's what you need here)
The (I was pretty sure, that a source file needs one public class... or was it one public class at most ?)HelloWorld
class needs to be declared as public
. This actually may be the cause for your problems.
If you're still facing the issue even after replacing doGet()
with doPost()
and changing the form method="post"
. Try clearing the cache of the browser or hit the URL in another browser or incognito/private mode. It may works!
For best practices, please follow this link. https://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html
Sounds like you're expecting size_t
to be the same as unsigned long
(possibly 64 bits) when it's actually an unsigned int
(32 bits). Try using %zu
in both cases.
I'm not entirely certain though.
Here are some instructions on how to initiate a GitHub repository and then push code you've already created to it. The first set of instructions are directly from GitHub.
Source: https://help.github.com/articles/create-a-repo/
In the upper-right corner of any page, click, and then click New repository.
Create a short, memorable name for your repository. For example, "hello-world".
Optionally, add a description of your repository. For example, "My first repository on GitHub."
Choose between creating a public or private repository.
Initialize this repository with a README.
Create repository.
Congratulations! You've successfully created your first repository, and initialized it with a README file.
Now after these steps you will want to push the code on your local computer up to the repository you just created and you do this following these steps:
git init
(in the root folder where your code is located)
git add -A
(this will add all the files and folders in your directory to be committed)
git commit -am "First Project commit"
git remote add origin [email protected]:YourGithubName/your-repo-name.git
(you'll find this address on the GitHub repository you just created under "ssh clone URL" on the main page)
git push -u origin master
That's it. Your code will now be pushed up to GitHub. Now every time you want to keep pushing code that has changed just do.
git commit -m "New changes"
git push origin master
(if master is the branch you are working on)
If I understood your problem correctly, it's similar to one I just had. You want to be able limit the usability of DISTINCT to a specified field, rather than applying it to all the data.
If you use GROUP BY without an aggregate function, which ever field you GROUP BY will be your DISTINCT filed.
If you make your query:
SELECT * from table GROUP BY field1;
It will show all your results based on a single instance of field1.
For example, if you have a table with name, address and city. A single person has multiple addresses recorded, but you just want a single address for the person, you can query as follows:
SELECT * FROM persons GROUP BY name;
The result will be that only one instance of that name will appear with its address, and the other one will be omitted from the resulting table. Caution: if your fileds have atomic values such as firstName, lastName you want to group by both.
SELECT * FROM persons GROUP BY lastName, firstName;
because if two people have the same last name and you only group by lastName, one of those persons will be omitted from the results. You need to keep those things into consideration. Hope this helps.
You can try this too WARNING: this you should not do but since the question is asking for infinite loop with no end...this is how you could do it.
while [[ 0 -ne 1 ]]; do echo "it's looping"; sleep 2; done
The answer to that can be quite broad.
Essentially, the major difference for me that usually influences my decisions on which to use is that with a SQLDataReader, you are "streaming" data from the database. With a SQLDataAdapter, you are extracting the data from the database into an object that can itself be queried further, as well as performing CRUD operations on.
Obviously with a stream of data SQLDataReader is MUCH faster, but you can only process one record at a time. With a SQLDataAdapter, you have a complete collection of the matching rows to your query from the database to work with/pass through your code.
WARNING: If you are using a SQLDataReader, ALWAYS, ALWAYS, ALWAYS make sure that you write proper code to close the connection since you are keeping the connection open with the SQLDataReader. Failure to do this, or proper error handling to close the connection in case of an error in processing the results will CRIPPLE your application with connection leaks.
Pardon my VB, but this is the minimum amount of code you should have when using a SqlDataReader:
Using cn As New SqlConnection("..."), _
cmd As New SqlCommand("...", cn)
cn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
''# ...
End While
End Using
End Using
equivalent C#:
using (var cn = new SqlConnection("..."))
using (var cmd = new SqlCommand("..."))
{
cn.Open();
using(var rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
//...
}
}
}
Using Firefox:
specifying two values:
Doesn't work with any combination of syntax -- as several pointed out above. Using Firebug, I get "Error in parsing value for 'background-position'. Declaration dropped." until the animation ends.
'backgroundPosition': '17.5em' -- specifiying 1 value:
works in FF and CHrome OPera, SF(Safari) and IE, with a caveat that the 2nd value or y position (vertical) gets set to "center". From Firebug, the element's style gets set to:
style="background-position: 17.5em center;"
Assuming the underlying data types are date/time/datetime types:
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), CollectionDate, 112)
+ ' ' + CONVERT(CHAR(8), CollectionTime, 108))
FROM dbo.whatever;
This will convert CollectionDate
and CollectionTime
to char sequences, combine them, and then convert them to a datetime
.
The parameters to CONVERT
are data_type
, expression
and the optional style
(see syntax documentation).
The date and time style
value 112
converts to an ISO yyyymmdd
format. The style
value 108
converts to hh:mi:ss
format. Evidently both are 8 characters long which is why the data_type
is CHAR(8)
for both.
The resulting combined char sequence is in format yyyymmdd hh:mi:ss
and then converted to a datetime
.
The following way you can access all the information from logged user.
$customer_data=Mage::getSingleton('customer/session')->getCustomer();
echo "<pre>" print_r($customer_data);
Given the ease of use of Access, I don't see a compelling reason to use Excel at all other than to export data for number crunching. Access is designed to easily build data forms and, in my opinion, will be orders of magnitude easier and less time-consuming than using Excel. A few hours to learn the Access object model will pay for itself many times over in terms of time and effort.
Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:
public ActionResult GetImages(string artistName, string apiKey)
MVC will auto-populate the parameters when given a URL like:
/Artist/GetImages/?artistName=cher&apiKey=XXX
One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:
public ActionResult GetImages(string id, string apiKey)
would be populated correctly with a URL like the following:
/Artist/GetImages/cher?apiKey=XXX
In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
If you wanted to support a url like
/Artist/GetImages/cher/api-key
you could add a route like:
routes.MapRoute(
"ArtistImages", // Route name
"{controller}/{action}/{artistName}/{apikey}", // URL with parameters
new { controller = "Home", action = "Index", artistName = "", apikey = "" } // Parameter defaults
);
and a method like the first example above.
Josh Bloch favors your approach:
The reason that I favor the
instanceof
approach is that when you use thegetClass
approach, you have the restriction that objects are only equal to other objects of the same class, the same run time type. If you extend a class and add a couple of innocuous methods to it, then check to see whether some object of the subclass is equal to an object of the super class, even if the objects are equal in all important aspects, you will get the surprising answer that they aren't equal. In fact, this violates a strict interpretation of the Liskov substitution principle, and can lead to very surprising behavior. In Java, it's particularly important because most of the collections (HashTable
, etc.) are based on the equals method. If you put a member of the super class in a hash table as the key and then look it up using a subclass instance, you won't find it, because they are not equal.
See also this SO answer.
Effective Java chapter 3 also covers this.
Your @POST
method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:
@XmlRootElement
public class MyJaxBean {
@XmlElement public String param1;
@XmlElement public String param2;
}
Then your @POST
method would look like the following:
@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
System.out.println("param1 = " + input.param1);
System.out.println("param2 = " + input.param2);
}
This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input
in this case. The actual message would look something like:
POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com
{"param1":"hello","param2":"world"}
Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.
HTML <FORM>
The parameters would be annotated using @FormParam:
@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
@FormParam("param2") String param2) {
...
}
The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:
POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25
param1=hello¶m2=world
The content is URL encoded in this case.
If you do not know the names of the FormParam's you can do the following:
@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
...
}
HTTP Headers
You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:
@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
@HeaderParam("param2") String param2) {
...
}
Here's what the HTTP message would look like. Note that this POST does not have a body.
POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world
I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.
HTTP Query Parameters
This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.
@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
@QueryParam("param2") String param2) {
...
}
Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:
POST /create?param1=hello¶m2=world HTTP/1.1
Content-Length: 0
Host: www.example.com
You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.
HTTP Path Parameters
Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:
@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
@PathParam("param2") String param2) {
...
}
The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.
POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com
This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.
As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM
-based HTML pages, then use @FormParam
. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer
implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM
encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.
Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.
I struggled with this for a while. Running PHP on the server. This code will post a json and get the json reply from the server
NSURL *url = [NSURL URLWithString:@"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSString *post = [NSString stringWithFormat:@"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil){
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(@"Server Response (we want to see a 200 return code) %@",response);
NSLog(@"dictionary %@",dictionary);
}
else if ([data length] == 0 && error == nil){
NSLog(@"no data returned");
//no data, but tried
}
else if (error != nil)
{
NSLog(@"there was a download error");
//couldn't download
}
}];
In the VBA editor, go to View
, Toolbars
, Customise...
or right click on the tool bar and select Customise...
Under the Commands
tab, select the Edit
menu on the left.
Then approximately two thirds of the way down there's two icons, Comment Block
and Uncomment Block
.
Drag and drop these onto your toolbar and then you have easy access to highlight a block of code, and comment it out and uncomment with the click of a button!
See GauravSingh's answer if you want to assign keyboard shortcuts.
Only related with currency trading (Forex), but many Forex brokers are offering MetaTrader which let you code in MQL. The main problem with it (aside that it's limited to Forex) is that you've to code in MQL which might not be your preferred language.
Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here
$employee = array(
"employee_id" => 10011,
"Name" => "Nathan",
"Skills" =>
array(
"analyzing",
"documentation" =>
array(
"desktop",
"mobile"
)
)
);
Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{
"employee_id": 10011,
"Name": "Nathan",
"Skills": {
"0": "analyzing",
"documentation": [
"desktop",
"mobile"
]
}
}
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
url: "employee.php",
async: false,
cache: false,
data: {
employee_id: 10011
},
success: function (jsonString) {
var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
});
Most problems can be solved using (i) just locks, (ii) just semaphores, ..., or (iii) a combination of both! As you may have discovered, they're very similar: both prevent race conditions, both have acquire()
/release()
operations, both cause zero or more threads to become blocked/suspected...
Really, the crucial difference lies solely on how they lock and unlock.
For both locks/semaphores, trying to call acquire()
while the primitive is in state 0 causes the invoking thread to be suspended. For locks - attempts to acquire the lock is in state 1 are successful. For semaphores - attempts to acquire the lock in states {1, 2, 3, ...} are successful.
For locks in state state 0, if same thread that had previously called acquire()
, now calls release, then the release is successful. If a different thread tried this -- it is down to the implementation/library as to what happens (usually the attempt ignored or an error is thrown). For semaphores in state 0, any thread can call release and it will be successful (regardless of which thread previous used acquire to put the semaphore in state 0).
From the preceding discussion, we can see that locks have a notion of an owner (the sole thread that can call release is the owner), whereas semaphores do not have an owner (any thread can call release on a semaphore).
What causes a lot of confusion is that, in practice they are many variations of this high-level definition.
Important variations to consider:
acquire()
/release()
be called? -- [Varies massively]These depends on your book / lecturer / language / library / environment.
Here's a quick tour noting how some languages answer these details.
pthread_mutex_t
. By default, they can't be shared with any other processes (PTHREAD_PROCESS_PRIVATE
), however mutex's have an attribute called pshared. When set, so the mutex is shared between processes (PTHREAD_PROCESS_SHARED
). sem_t
. Similar to mutexes, semaphores can be shared between threasds of many processes or kept private to the threads of one single process. This depends on the pshared argument provided to sem_init
. threading.RLock
) is mostly the same as C/C++ pthread_mutex_t
s. Both are both reentrant. This means they may only be unlocked by the same thread that locked it. It is the case that sem_t
semaphores, threading.Semaphore
semaphores and theading.Lock
locks are not reentrant -- for it is the case any thread can perform unlock the lock / down the semaphore.threading.Semaphore
) is mostly the same as sem_t
. Although with sem_t
, a queue of thread ids is used to remember the order in which threads became blocked when attempting to lock it while it is locked. When a thread unlocks a semaphore, the first thread in the queue (if there is one) is chosen to be the new owner. The thread identifier is taken off the queue and the semaphore becomes locked again. However, with threading.Semaphore
, a set is used instead of a queue, so the order in which threads became blocked is not stored -- any thread in the set may be chosen to be the next owner.java.util.concurrent.ReentrantLock
) is mostly the same as C/C++ pthread_mutex_t
's, and Python's threading.RLock
in that it also implements a reentrant lock. Sharing locks between processes is harder in Java because of the JVM acting as an intermediary. If a thread tries to unlock a lock it doesn't own, an IllegalMonitorStateException
is thrown.java.util.concurrent.Semaphore
) is mostly the same as sem_t
and threading.Semaphore
. The constructor for Java semaphores accept a fairness boolean parameter that control whether to use a set (false) or a queue (true) for storing the waiting threads. In theory, semaphores are often discussed, but in practice, semaphores aren't used so much. A semaphore only hold the state of one integer, so often it's rather inflexible and many are needed at once -- causing difficulty in understanding code. Also, the fact that any thread can release a semaphore is sometimes undesired. More object-oriented / higher-level synchronization primitives / abstractions such as "condition variables" and "monitors" are used instead.
Here is another solution for adding class definitions to the widgets after declaring the fields in the class.
def __init__(self, *args, **kwargs):
super(SampleClass, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['class'] = 'my_class'
Try this runner I wrote. It could be helpful.
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class ProxyAuthHelper {
public static void main(String[] args) throws Exception {
String tmp = System.getProperty("http.proxyUser", System.getProperty("https.proxyUser"));
if (tmp == null) {
System.out.println("Proxy username: ");
tmp = new Scanner(System.in).nextLine();
}
final String userName = tmp;
tmp = System.getProperty("http.proxyPassword", System.getProperty("https.proxyPassword"));
if (tmp == null) {
System.out.println("Proxy password: ");
tmp = new Scanner(System.in).nextLine();
}
final char[] password = tmp.toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("\n--------------\nProxy auth: " + userName);
return new PasswordAuthentication (userName, password);
}
});
Class<?> clazz = Class.forName(args[0]);
Method method = clazz.getMethod("main", String[].class);
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
method.invoke(null, new Object[]{newArgs});
}
}
As user1511510 has identified, there's an unusual case when abc is at the end of the file name. We need to look for either /abc/
or /abc
followed by a string-terminator '\0'
. A naive way to do this would be to check if either /abc/
or /abc\0
are substrings:
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "/user/desktop/abc";
const int exists = strstr(str, "/abc/") || strstr(str, "/abc\0");
printf("%d\n",exists);
return 0;
}
but exists
will be 1 even if abc is not followed by a null-terminator. This is because the string literal "/abc\0"
is equivalent to "/abc"
. A better approach is to test if /abc
is a substring, and then see if the character after this substring (indexed using the pointer returned by strstr()
) is either a /
or a '\0'
:
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "/user/desktop/abc", *substr;
const int exists = (substr = strstr(str, "/abc")) && (substr[4] == '\0' || substr[4] == '/');
printf("%d\n",exists);
return 0;
}
This should work in all cases.
$(document.body).on('hidden.bs.modal', function () {
$('#myModal').removeData('bs.modal')
});
Android NDK official hello-libs
CMake example
Just worked for me on Ubuntu 17.10 host, Android Studio 3, Android SDK 26, so I strongly recommend that you base your project on it.
The shared library is called libgperf
, the key code parts are:
hello-libs/app/src/main/cpp/CMakeLists.txt:
// -L
add_library(lib_gperf SHARED IMPORTED)
set_target_properties(lib_gperf PROPERTIES IMPORTED_LOCATION
${distribution_DIR}/gperf/lib/${ANDROID_ABI}/libgperf.so)
// -I
target_include_directories(hello-libs PRIVATE
${distribution_DIR}/gperf/include)
// -lgperf
target_link_libraries(hello-libs
lib_gperf)
android {
sourceSets {
main {
// let gradle pack the shared library into apk
jniLibs.srcDirs = ['../distribution/gperf/lib']
Then, if you look under /data/app
on the device, libgperf.so
will be there as well.
on C++ code, use: #include <gperf.h>
header location: hello-libs/distribution/gperf/include/gperf.h
lib location: distribution/gperf/lib/arm64-v8a/libgperf.so
If you only support some architectures, see: Gradle Build NDK target only ARM
The example git tracks the prebuilt shared libraries, but it also contains the build system to actually build them as well: https://github.com/googlesamples/android-ndk/tree/840858984e1bb8a7fab37c1b7c571efbe7d6eb75/hello-libs/gen-libs
Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of
So you should prevent the default behaviour of the button click
$('#btnSave').click(function (e) {
// prevent the default event behaviour
e.preventDefault();
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
// perform your save call here
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
Note:
After that, Click Apply and OK.
Use <location>
configuration tag, and <allow users="?"/>
to allow anonymous only or <allow users="*"/>
for all:
<configuration>
<location path="Path/To/Public/Folder">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
If the variable table
contains invalid characters (like a space) you should add square brackets around the variable.
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo.[" + table + "]";
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input
If you want the placeholder text to be red you need to target it specifically in CSS.
Write:
input::placeholder{
color: #f00;
}
It seems people mix a content encoding with a built files/resources encoding. Having only maven properties is not enough. Having -Dfile.encoding=UTF8
not effective. To avoid having issues with encoding you should follow the following simple rules
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
Always set encoding explicitly, when work with files, strings, IO in your code. If you do not follow this rule, your application depend on the environment. The -Dfile.encoding=UTF8
exactly is responsible for run-time environment configuration, but we should not depend on it. If you have thousands of clients, it takes more effort to configure systems and to find issues because of it. You just have an additional dependency on it which you can avoid by setting it explicitly. Most methods in Java that use a default encoding are marked as deprecated because of it.
Make sure the content, you are working with, also is in the same encoding, that you expect. If it is not, the previous steps do not matter! For instance a file will not be processed correctly, if its encoding is not UTF8 but you expect it. To check file encoding on Linux:
$ file --mime F_PRDAUFT.dsv
@Produces("application/json; charset=UTF-8") @Consumes("application/json; charset=UTF-8")
Hope this will be useful to someone.
Yes using Option Explicit
is a good habit. Using .Select
however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet
which might not be what you actually wanted.
Is this what you are trying?
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
Else
Exit For
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
NOTE
If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10
If you want to copy all rows which have data then use this code.
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
Hope this is what you wanted?
Sid
Google changed their policies last month regarding auto-play inside Chrome. Please see this announcement.
They do, however, allow auto-play if you are embedding a video and it is muted. You can add the muted
property and it should allow the video to start playing.
<video autoplay controls muted>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
Use float-right
for block elements, or text-right
for inline elements:
<div class="row">
<div class="col">left</div>
<div class="col text-right">inline content needs to be right aligned</div>
</div>
<div class="row">
<div class="col">left</div>
<div class="col">
<div class="float-right">element needs to be right aligned</div>
</div>
</div>
http://www.codeply.com/go/oPTBdCw1JV
If float-right
is not working, remember that Bootstrap 4 is now flexbox, and many elements are display:flex
which can prevent float-right
from working.
In some cases, the utility classes like align-self-end
or ml-auto
work to right align elements that are inside a flexbox container like the Bootstrap 4 .row, Card or Nav. The ml-auto
(margin-left:auto) is used in a flexbox element to push elements to the right.
AWS added a new feature to connect to instance without any open port, the AWS SSM Session Manager. https://aws.amazon.com/blogs/aws/new-session-manager/
I've created a neat SSH ProxyCommand script that temporary adds your public ssh key to target instance during connection to target instance. The nice thing about this is you will connect without the need to add the ssh(22) port to your security groups, because the ssh connection is tunneled through ssm session manager.
AWS SSM SSH ProxyComand -> https://gist.github.com/qoomon/fcf2c85194c55aee34b78ddcaa9e83a1
Be sure you're running the right instance of Python with the right directories on the path. In my case, this error resulted from running the python
executable by accident - I had actually installed Django under the python2.7
framework & libraries. The same could happen as a result of virtualenv as well.
SELECT name FROM sqlite_master where name = '<TABLE_NAME_HERE>'
If the table name does not exist then there would not be any records returned!
You can as well use
SELECT count(name) FROM sqlite_master where name = '<TABLE_NAME_HERE>'
if the count is 1, means table exists, otherwise, it would return 0
As of October 3, 2012, a new "Elastic Beanstalk for Java with Apache Tomcat 7" Linux x64 AMI deployed with the Sample Application has the install here:
/etc/tomcat7/
The /etc/tomcat7/tomcat7.conf file has the following settings:
# Where your java installation lives
JAVA_HOME="/usr/lib/jvm/jre"
# Where your tomcat installation lives
CATALINA_BASE="/usr/share/tomcat7"
CATALINA_HOME="/usr/share/tomcat7"
JASPER_HOME="/usr/share/tomcat7"
CATALINA_TMPDIR="/var/cache/tomcat7/temp"
Do you want to match a class exactly, e.g. only matching FileInputStream
instead of any subclass of FileInputStream
? If so, use getClass()
and ==
. I would typically do this in an equals
, so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the same class than of one specific class.
Otherwise, use instanceof
. Note that with getClass()
you will need to ensure you have a non-null reference to start with, or you'll get a NullPointerException
, whereas instanceof
will just return false
if the first operand is null.
Personally I'd say instanceof
is more idiomatic - but using either of them extensively is a design smell in most cases.
Putting this information here for future readers' benefit.
401 (Unauthorized) response header -> Request authentication header
Here are several WWW-Authenticate
response headers. (The full list is at IANA: HTTP Authentication Schemes.)
WWW-Authenticate: Basic
-> Authorization: Basic + token - Use for basic authentication WWW-Authenticate: NTLM
-> Authorization: NTLM + token (2 challenges)WWW-Authenticate: Negotiate
-> Authorization: Negotiate + token - used for Kerberos authentication
Negotiate
: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
You need to print the result of the getText()
. You're currently printing the object TxtBoxContent
.
getText()
will only get the inner text of an element. To get the value, you need to use getAttribute()
.
WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
System.out.println("Printing " + TxtBoxContent.getAttribute("value"));
The Date
documentation states that :
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = new Date();_x000D_
var timeDiff = endTime - startTime; //in ms_x000D_
// strip the ms_x000D_
timeDiff /= 1000;_x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
OR another way of doing it for modern browser
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = performance.now();_x000D_
var timeDiff = endTime - startTime; //in ms _x000D_
// strip the ms _x000D_
timeDiff /= 1000; _x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
No this is not enough (in some specific cases)! By default PDO uses emulated prepared statements when using MySQL as a database driver. You should always disable emulated prepared statements when using MySQL and PDO:
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Another thing that always should be done it set the correct encoding of the database:
$dbh = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
Also see this related question: How can I prevent SQL injection in PHP?
Also note that that only is about the database side of the things you would still have to watch yourself when displaying the data. E.g. by using htmlspecialchars()
again with the correct encoding and quoting style.
Arrived here because my source repo had %20
in it which was creating local folders with %20
in them when using simplistic git clone <url>
.
Easy solution:
git clone https://teamname.visualstudio.com/Project%20Name/_git/Repo%20Name "Repo Name"
Put this in a file and make it executable:
#!/bin/bash
start=`grep -n $1 < $3 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[0]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "couldn't find start pattern!" 1>&2
exit 1
fi
stop=`tail -n +$start < $3 | grep -n $2 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[1]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "couldn't find end pattern!" 1>&2
exit 1
fi
stop=$(( $stop + $start - 1))
sed "$start,$stop!d" < $3
Execute the file with arguments (NOTE that the script does not handle spaces in arguments!):
To use with your example, use arguments: 1234 5555 myfile.txt
Includes lines with starting and stopping pattern.
Use this to remove title from android app in your Androidmainfest.xml
android:theme="@android:style/Theme.NoTitleBar"
or you can use this in your activity
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Maybe it's because you have a line break in your PHP code. If you need line breaks in your alert window message, include it as an escaped syntax at the end of each line in your PHP code. I usually do it the following way:
$message = 'line 1.\\n';
$message .= 'line 2.';
If you really need this you can achieve your goal with help of separate table for sequencing (if you don't mind) and a trigger.
Tables
CREATE TABLE table1_seq
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);
Now the trigger
DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO table1_seq VALUES (NULL);
SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;
Then you just insert rows to table1
INSERT INTO Table1 (name)
VALUES ('Jhon'), ('Mark');
And you'll have
| ID | NAME | ------------------ | LHPL001 | Jhon | | LHPL002 | Mark |
Here is SQLFiddle demo
Why not...
bool isEmpty = !list.Any();
if(isEmpty)
{
// error message
}
else
{
// show grid
}
The GridView
has also an EmptyDataTemplate
which is shown if the datasource is empty. This is an approach in ASP.NET:
<emptydatarowstyle backcolor="LightBlue" forecolor="Red"/>
<emptydatatemplate>
<asp:image id="NoDataErrorImg"
imageurl="~/images/NoDataError.jpg" runat="server"/>
No Data Found!
</emptydatatemplate>
This question already had many highly upvoted answers and an accepted answer, but all of them so far were distracted by various ways to express the boolean problem and missed a crucial point:
I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified)
This logic should not be the responsibility of your code in the first place, rather it should be handled by argparse
module. Don't bother writing a complex if statement, instead prefer to setup your argument parser something like this:
#!/usr/bin/env python
import argparse as ap
parser = ap.ArgumentParser()
parser.add_argument('--foo', nargs=3, default=['x', 'y', 'z'])
args = parser.parse_args()
print(args.foo)
And yes, it should be an option not a positional argument, because it is after all optional.
edited: To address the concern of LarsH in the comments, below is an example of how you could write it if you were certain you wanted the interface with either 3 or 0 positional args. I am of the opinion that the previous interface is better style, because optional arguments should be options, but here's an alternative approach for the sake of completeness. Note the overriding kwarg usage
when creating your parser, because argparse
will auto-generate a misleading usage message otherwise!
#!/usr/bin/env python
import argparse as ap
parser = ap.ArgumentParser(usage='%(prog)s [-h] [a b c]\n')
parser.add_argument('abc', nargs='*', help='specify 3 or 0 items', default=['x', 'y', 'z'])
args = parser.parse_args()
if len(args.abc) != 3:
parser.error('expected 3 arguments')
print(args.abc)
Here are some usage examples:
# default case
wim@wim-zenbook:/tmp$ ./three_or_none.py
['x', 'y', 'z']
# explicit case
wim@wim-zenbook:/tmp$ ./three_or_none.py 1 2 3
['1', '2', '3']
# example failure mode
wim@wim-zenbook:/tmp$ ./three_or_none.py 1 2
usage: three_or_none.py [-h] [a b c]
three_or_none.py: error: expected 3 arguments
You should set async = false in head. Use post/get instead of ajax.
jQuery.ajaxSetup({ async: false });
$.post({
url: 'api.php',
data: 'id1=' + q + '',
dataType: 'json',
success: function (data) {
id = data[0];
vname = data[1];
}
});
I found that calling of stored procedures in code-first approach is not convenient.
I prefer to use Dapper
instead.
The following code was written with Entity Framework:
var clientIdParameter = new SqlParameter("@ClientId", 4);
var result = context.Database
.SqlQuery<ResultForCampaign>("GetResultsForCampaign @ClientId", clientIdParameter)
.ToList();
The following code was written with Dapper
:
return Database.Connection.Query<ResultForCampaign>(
"GetResultsForCampaign ",
new
{
ClientId = 4
},
commandType: CommandType.StoredProcedure);
I believe the second piece of code is simpler to understand.
I had the same problem try this:
python manage.py sqlsequencereset table_name
Eg:
python manage.py sqlsequencereset auth
you need to run this in production settings(if you have) and you need Postgres installed to run this on the server
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(YourObjectType));
YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream);
You could also use the JavaScriptSerializer
, but DataContractJsonSerializer
is supposedly better able to handle complex types.
Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use DataContractJsonSerializer
since it is hard baked for WCF.
I have used in Google Sheets
={sheetname!columnnamefrom:columnnameto}
Example:
={sheet1!A:A}
={sheet2!A4:A20}