I had this issue while installing dynamic ax setup in VM, while installing it was showing me to 'licence is not valid, Reinstall visual studio shell 2010 version', so i uninstalled the visual studio shell 2010 version and its following component and tried to install again the AX admin it worked.
If you want to apply a selector to the context provided by an existing jQuery set, try the find() function:
element.find(">:first-child").toggleClass("redClass");
Jørn Schou-Rode noted that you probably only want to find the first direct descendant of the context element, hence the child selector (>). He also points out that you could just as well use the children() function, which is very similar to find() but only searches one level deep in the hierarchy (which is all you need...):
element.children(":first").toggleClass("redClass");
Java doesn't want you to make an array of HashMaps, but it will let you make an array of Objects. So, just write up a class declaration as a shell around your HashMap, and make an array of that class. This lets you store some extra data about the HashMaps if you so choose--which can be a benefit, given that you already have a somewhat complex data structure.
What this looks like:
private static someClass[] arr = new someClass[someNum];
and
public class someClass {
private static int dataFoo;
private static int dataBar;
private static HashMap<String, String> yourArray;
...
}
That's not exactly what I had in mind. What do you do if you have a generic type to only be known at runtime?
public MyDTO toObject() {
try {
var methodInfo = MethodBase.GetCurrentMethod();
if (methodInfo.DeclaringType != null) {
var fullName = methodInfo.DeclaringType.FullName + "." + this.dtoName;
Type type = Type.GetType(fullName);
if (type != null) {
var obj = JsonConvert.DeserializeObject(payload);
//var obj = JsonConvert.DeserializeObject<type.MemberType.GetType()>(payload); // <--- type ?????
...
}
}
// Example for java.. Convert this to C#
return JSONUtil.fromJSON(payload, Class.forName(dtoName, false, getClass().getClassLoader()));
} catch (Exception ex) {
throw new ReflectInsightException(MethodBase.GetCurrentMethod().Name, ex);
}
}
$("#closeLink").click(closeIt);
Let's say you want to call your function passing some args to it i.e., closeIt(1, false)
. Then, you should build an anonymous function and call closeIt
from it.
$("#closeLink").click(function() {
closeIt(1, false);
});
Solution: In order to increase your buffer history on iterm bash terminal you've got two options:
Go to iterm -> Preferences -> Profiles -> Terminal Tab -> Scrollback Buffer (section)
Option 1. select the checkbox Unlimited scrollback
Option 2. type the selected Scrollback lines
numbers you'd like your terminal buffer to cache (See image below)
What are you going to do with the URI?
If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.
HttpGet get = new HttpGet("http://stackoverflow.com");
After compiling a few answers, I've come up with the following code. What surprised me was that the timer does not get frozen on a PC (Chrome, FF) or Android Chrome - the trigger worked in the background, and the visibility check was the only reliable info.
var timestamp = new Date().getTime();
var timerDelay = 5000;
var processingBuffer = 2000;
var redirect = function(url) {
//window.location = url;
log('ts: ' + timestamp + '; redirecting to: ' + url);
}
var isPageHidden = function() {
var browserSpecificProps = {hidden:1, mozHidden:1, msHidden:1, webkitHidden:1};
for (var p in browserSpecificProps) {
if(typeof document[p] !== "undefined"){
return document[p];
}
}
return false; // actually inconclusive, assuming not
}
var elapsedMoreTimeThanTimerSet = function(){
var elapsed = new Date().getTime() - timestamp;
log('elapsed: ' + elapsed);
return timerDelay + processingBuffer < elapsed;
}
var redirectToFallbackIfBrowserStillActive = function() {
var elapsedMore = elapsedMoreTimeThanTimerSet();
log('hidden:' + isPageHidden() +'; time: '+ elapsedMore);
if (isPageHidden() || elapsedMore) {
log('not redirecting');
}else{
redirect('appStoreUrl');
}
}
var log = function(msg){
document.getElementById('log').innerHTML += msg + "<br>";
}
setTimeout(redirectToFallbackIfBrowserStillActive, timerDelay);
redirect('nativeApp://');
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
Just use the length
property of a JavaScript
array like so:
$scope.names.length
Also, I don't see a starting <script>
tag in your code.
If you want the length inside your view, do it like so:
{{ names.length }}
Working with the many answers above, I have implemented Apples new method os_proc_available_memory()
for iOS 13+ coupled with NSByteCountFormatter
which offers a number of useful formatting options for nicer output of the memory:
#include <os/proc.h>
....
- (NSString *)memoryStringForBytes:(unsigned long long)memoryBytes {
NSByteCountFormatter *byteFormatter = [[NSByteCountFormatter alloc] init];
byteFormatter.allowedUnits = NSByteCountFormatterUseGB;
byteFormatter.countStyle = NSByteCountFormatterCountStyleMemory;
NSString *memoryString = [byteFormatter stringFromByteCount:memoryBytes];
return memoryString;
}
- (void)memoryLoggingOutput {
if (@available(iOS 13.0, *)) {
NSLog(@"Physical memory available: %@", [self memoryStringForBytes:[NSProcessInfo processInfo].physicalMemory]);
NSLog(@"Memory A (brackets): %@", [self memoryStringForBytes:(long)os_proc_available_memory()]);
NSLog(@"Memory B (no brackets): %@", [self memoryStringForBytes:(long)os_proc_available_memory]);
}
}
Important note: Do not forget the ()
at the end. I have included both NSLog
options in in the memoryLoggingOutput
method because it does not warn you that they are missing and failure to include the brackets returns an unexpected yet constant result.
The string returned from the method memoryStringForBytes
outputs values like so:
NSLog(@"%@", [self memoryStringForBytes:(long)os_proc_available_memory()]); // 1.93 GB
// 2 seconds later
NSLog(@"%@", [self memoryStringForBytes:(long)os_proc_available_memory()]); // 1.84 GB
For DBeaver users:
Right click your connection, choose "Edit Connection"
On the "Connection settings" screen (main screen) click on "Edit Driver Settings"
Click on "Connection properties"
Right click the "user properties" area and choose "Add new property"
Add two properties: "useSSL" and "allowPublicKeyRetrieval"
Set their values to "false" and "true" by double clicking on the "value" column
After executing the below regex, your answer is in the first capture.
/^(.*?)\.txt/
In case you have two-factor authentication enabled, make sure that you create a new access token and not regenerate an old one.
That didn't seem to work in my case.
The following code is cross-browser compliant. It works in IE7, IE8, Fx 3, Safari, and Chrome, so no need to handle cross-browser issues. Did not test in IE6.
<iframe id="iframeId" name="iframeId">...</iframe>
<script type="text/javascript">
var iframeDoc;
if (window.frames && window.frames.iframeId &&
(iframeDoc = window.frames.iframeId.document)) {
var iframeBody = iframeDoc.body;
var ifromContent = iframeBody.innerHTML;
}
</script>
A simple answer, if the red "stop" box is not working, is to try pressing the "Ctrl + Break" buttons on the keyboard.
If you are running SQL Server on Linux, there is an app you can add to your systray called "killall" Just click on the "killall" button and then click on the program that is caught in a loop and it will terminate the program. Hope that helps.
you need to use backslash before ". like \"
From the doc here you can see that
A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.
and " (double quote) is a escacpe sequence
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence
She said "Hello!" to me.
you would write
System.out.println("She said \"Hello!\" to me.");
console.log is only defined when the console is open. If you want to check for it in your code make sure you check for for it within the window property
if (window.console)
console.log(msg)
this throws an exception in IE9 and will not work correctly. Do not do this
if (console)
console.log(msg)
You can write a function that splits the database by a factor, orders by another desired variable, extract the number of rows you want in each factor (category) and combine these into a database.
top<-function(x, num, c1,c2){
sorted<-x[with(x,order(x[,c1],x[,c2],decreasing=T)),]
splits<-split(sorted,sorted[,c1])
df<-lapply(splits,head,num)
do.call(rbind.data.frame,df)}
x is the dataframe;
num is the number of number of rows you would like to see;
c1 is the column number of the variable you would like to split by;
c2 is the column number of the variable you would like to rank by or handle ties.
Using the mtcars data, the function extracts the 3 heaviest cars (mtcars$wt is the 6th column) in each cylinder class (mtcars$cyl is the 2nd column)
top(mtcars,3,2,6)
mpg cyl disp hp drat wt qsec vs am gear carb
4.Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
4.Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
4.Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2
6.Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
6.Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
6.Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
8.Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4
8.Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
8.Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4
You can also easily get the lightest in a class by changing head in the lapply function to tail OR by removing the decreasing=T argument in the order function which will return it to its default, decreasing=F.
LandingScreenViewController *nextView=[self.storyboard instantiateViewControllerWithIdentifier:@"nextView"];
[self presentViewController:nextView animated:YES completion:^{}];
The other answers are preferable, but for a pure Bash solution, I've modified the script in my answer here to be able to output a continuous stream of hex characters representing the contents of a file. (Its normal mode is to emulate hexdump -C
.)
if you are installing from source here is a tutorial.would be happy if it helps http://raihan90.blogspot.com/2009/03/mysql-step-by-step-hacking-into-mysql.html
As of Twig 1.5, the correct answer is to use the dump function. It is fully documented in the Twig documentation. Here is the documentation to enable this inside Symfony2.
{{ dump(user) }}
A lot of the solutions offered here do not seem to work anymore. I'm currently on a chromebook and wanted to view an HTML5 banner. This seems impossible now through Google Drive or other apps (as mentioned in previous comments).
The method I ended up using to view the HTML5 was the following:
There may well an easier way, but this way is pretty good too. Hope it helps and worked well for me.
Simple use of this:
<a href="#" id="mytooltip" class="btn btn-praimary" data-toggle="tooltip" title="my tooltip">
tooltip
</a>
Using jQuery:
$(document).ready(function(){
$('#mytooltip').tooltip();
});
You can left side of tooltip u can simple add this->data-placement="left"
<a href="#" id="mytooltip" class="btn btn-praimary" data-toggle="tooltip" title="my tooltip" data-placement="left">tooltip</a>
If can deviate a little from the straight path of DataTable -> SQL table, it can also be done via a list of objects:
1) DataTable -> Generic list of objects
public static DataTable ConvertTo<T>(IList<T> list)
{
DataTable table = CreateTable<T>();
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
table.Rows.Add(row);
}
return table;
}
Source and more details can be found here. Missing properties will remain to their default values (0 for int
s, null for reference types etc.)
2) Push the objects into the database
One way is to use EntityFramework.BulkInsert
extension. An EF datacontext is required, though.
It generates the BULK INSERT command required for fast insert (user defined table type solution is much slower than this).
Although not the straight method, it helps constructing a base of working with list of objects instead of DataTable
s which seems to be much more memory efficient.
@Hostlistnening deals basically with the host element say (a button) listening to an action by a user and performing a certain function say alert("Ahoy!") while @Hostbinding is the other way round. Here we listen to the changes that occurred on that button internally (Say when it was clicked what happened to the class) and we use that change to do something else, say emit a particular color.
Think of the scenario that you would like to make a favorite icon on a component, now you know that you would have to know whether the item has been Favorited with its class changed, we need a way to determine this. That is exactly where @Hostbinding comes in.
And where there is the need to know what action actually was performed by the user that is where @Hostlistening comes in
I used the following method to quickly convert a couple of Fortran codes to Python. True, it's not pass by reference as the original question was posed, but is a simple work around in some cases.
a=0
b=0
c=0
def myfunc(a,b,c):
a=1
b=2
c=3
return a,b,c
a,b,c = myfunc(a,b,c)
print a,b,c
If there is something that is throwing off your Distinct query, you might want to look at MoreLinq and use the DistinctBy operator and select distinct objects by id.
var distinct = items.DistinctBy( i => i.Id );
Honestly, I am going to argue that using NewRelic for profiling is the best.
It's a PHP extension which doesn't seem to slow down runtime at all and they do the monitoring for you, allowing decent drill down. In the expensive version they allow heavy drill down (but we can't afford their pricing model).
Still, even with the free/standard plan, it's obvious and simple where most of the low hanging fruit is. I also like that it can give you an idea on DB interactions too.
Yes there is:
https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1440
https://www.youtube.com/embed/kObNpTFPV5c?vq=hd1080
etc...
Options are:
Code for 1440: vq=hd1440
Code for 1080: vq=hd1080
Code for 720: vq=hd720
Code for 480p: vq=large
Code for 360p: vq=medium
Code for 240p: vq=small
UPDATE
As of 10 of April 2018, this code still works.
Some users reported "not working", if it doesn't work for you, please read below:
From what I've learned, the problem is related with network speed and or screen size.
When YT player starts, it collects the network speed, screen and player sizes, among other information, if the connection is slow or the screen/player size smaller than the quality requested(vq=
), a lower quality video is displayed despite the option selected on vq=
.
Also make sure you read the comments below.
Copy code using clone and appendTo function :
Here is also working example jsfiddle
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="copy"><a href="http://brightwaay.com">Here</a> </div>
<br/>
<div id="copied"></div>
<script type="text/javascript">
$(function(){
$('#copy').clone().appendTo('#copied');
});
</script>
</body>
</html>
Very quick and easy visual instructions to change this (and the select top 1000) for 2008 R2 through SSMS GUI
http://bradmarsh.net/index.php/2008/04/21/sql-2008-change-edit-top-200-rows/
Summary:
For all those recommending using table variables, be cautious in doing so. Table variable cannot be indexed whereas a temp table can be. A table variable is best when working with small amounts of data but if you are working on larger sets of data (e.g. 50k records) a temp table will be much faster than a table variable.
Also keep in mind that you can't rely on a try/catch to force a cleanup within the stored procedure. certain types of failures cannot be caught within a try/catch (e.g. compile failures due to delayed name resolution) if you want to be really certain you may need to create a wrapper stored procedure that can do a try/catch of the worker stored procedure and do the cleanup there.
e.g. create proc worker AS BEGIN -- do something here END
create proc wrapper AS
BEGIN
Create table #...
BEGIN TRY
exec worker
exec worker2 -- using same temp table
-- etc
END TRY
END CATCH
-- handle transaction cleanup here
drop table #...
END CATCH
END
One place where table variables are always useful is they do not get rolled back when a transaction is rolled back. This can be useful for capturing debug data that you want to commit outside the primary transaction.
You are getting that error probably because the element is not within the DOM yet. $(document).ready(); will not work. Try adding your code to a pageinit event handler.
Here is a working example:
<!DOCTYPE html>
<html>
<head>
<title>Button Disable</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
</head>
<body>
<div id="MyPageId" data-role="page">
<div data-role="header">
<h1>Button Disable</h1>
</div>
<div data-role="content">
<button id="button1" type="button" onclick="javascript:alert('#button1 clicked');">Button 1</button>
<button id="button2" type="button" onclick="javascript:alert('#button2 clicked');">Button 2</button>
</div>
<div data-role="footer">
<p>footer</p>
</div>
</div>
<script type="text/javascript">//<![CDATA[
$('#MyPageId').bind("pageinit", function (event, data) {
$("#button1").button("disable");
});
//]]></script>
</body>
</html>
Hope that helps someone
you can use the following Bootstrap class with
<tr class="w-25">
</tr>
for more details check the following page https://getbootstrap.com/docs/4.1/utilities/sizing/
Program Debug Database file (pdb) is a file format by Microsoft for storing debugging information.
When you build a project using Visual Studio or command prompt the compiler creates these symbol files.
Check Microsoft Docs
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
Use document.getElementsByClassName('className').style = your_style
.
var d = document.getElementsByClassName("left1");
d.className = d.className + " otherclass";
Use single quotes for JS strings contained within an html attribute's double quotes
Example
<div class="somelclass"></div>
then document.getElementsByClassName('someclass').style = "NewclassName";
<div class='someclass'></div>
then document.getElementsByClassName("someclass").style = "NewclassName";
This is personal experience.
Since I had to compile some source with 7 compatibility, because of some legacy system and ran into the same problem. I found out that in the gradle configuration there where two options set to java 8
sourceCompatibility = 1.8
targetCompatibility = 1.8
switching these to 1.7 solved the problem for me, keeping JAVA_HOME pointing to the installed JDK-7
sourceCompatibility = 1.7
targetCompatibility = 1.7
Pointers can be used like any other iterators:
int x[3] = {1, 2, 3};
std::vector<int> v(x, x + 3);
test(v)
It's sad that Oracle doesn't allow this, I get asked to do this by developers all the time..
Here's a slightly dangerous, somewhat quick and dirty method:
CREATE TABLE table_right_columns AS SELECT column1 column3, column2 FROM table_wrong_columns; -- Notice how we correct the position of the columns :)
DROP TABLE table_wrong_columns;
And next time you create a table, please consider the future requirements! ;)
You should have READ_EXTERNAL_STORAGE permission for reading sdcard. Add permission in manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this link Permissions overview
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
}
SQL Server doesn't allow you to reference the alias in the GROUP BY clause because of the logical order of processing. The GROUP BY clause is processed before the SELECT clause, so the alias is not known when the GROUP BY clause is evaluated. This also explains why you can use the alias in the ORDER BY clause.
Here is one source for information on the SQL Server logical processing phases.
if( strtotime($database_date) > strtotime('now') ) {
...
This error can occur on anything that requires elevated privileges in Windows.
It happens when the "Application Information" service is disabled in Windows services. There are a few viruses that use this as an attack vector to prevent people from removing the virus. It also prevents people from installing software to remove viruses.
The normal way to fix this would be to run services.msc, or to go into Administrative Tools and run "Services". However, you will not be able to do that if the "Application Information" service is disabled.
Instead, reboot your computer into Safe Mode (reboot and press F8 until the Windows boot menu appears, select Safe Mode with Networking). Then run services.msc and look for services that are designated as "Disabled" in the Startup Type column. Change these "Disabled" services to "Automatic".
Make sure the "Application Information" service is set to a Startup Type of "Automatic".
When you are done enabling your services, click Ok at the bottom of the tool and reboot your computer back into normal mode. The problem should be resolved when Windows reboots.
I figured out a much simpler one:
- (UIImage *)normalizedImage {
if (self.imageOrientation == UIImageOrientationUp) return self;
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
[self drawInRect:(CGRect){0, 0, self.size}];
UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return normalizedImage;
}
BTW: @Anomie's code does not take scale
into account, so will not work for 2x images.
While I find most answers here quite correct, many of them contain unnecessary Bashisms. POSIX parameter expansion gives you all you need:
[ "${host#user}" != "${host}" ]
and
[ "${host#node}" != "${host}" ]
${var#expr}
strips the smallest prefix matching expr
from ${var}
and returns that. Hence if ${host}
does not start with user
(node
), ${host#user}
(${host#node}
) is the same as ${host}
.
expr
allows fnmatch()
wildcards, thus ${host#node??}
and friends also work.
svn log
- I'm sure WebSVN has some feature for that too.
The "View Log" link near the center-top of the WebSVN overview shows the svn-log. However, the user-interface isn't exactly brilliant; I much prefer TortoiseSVN's log viewer.
I had the same issues but nothing worked. What I did was I added this to the selector:
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
var sb = new StringBuilder();
sb.Append(beforeText);
sb.Insert(2, insertText);
afterText = sb.ToString();
It can't be done via CSS as CSS only changes the presentation (e.g. only Javascript can make the alert popup). I'd strongly recommend you check out a Javascript library called jQuery as it makes doing something like this trivial:
$(document).ready(function(){
$("a").click(function(){
alert("hohoho");
});
});
You can use the border and box-shadow properties along with CSS pseudo elements to achieve a triple-border sort of effect. See the example below for an idea of how to create three borders at the bottom of a div:
.triple-border:after {_x000D_
content: " ";_x000D_
display: block;_x000D_
width: 100%;_x000D_
background: #FFE962;_x000D_
height: 9px;_x000D_
padding-bottom: 8px;_x000D_
border-bottom: 9px solid #A3C662;_x000D_
box-shadow: -2px 11px 0 -1px #34b6af;_x000D_
}
_x000D_
<div class="triple-border">Triple border bottom with multiple colours</div>
_x000D_
You'll have to play around with the values to get the alignment correct. However, you can also achieve more flexibility, e.g. 4 borders if you put some of the attributes in the proper element rather than the pseudo selector.
Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).
It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).
But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.
A good example: here
And a good documentation from Mozilla: here
This will definitely work. Orange outline won't show up anymore.. Common for all tags:
*:focus {
outline: none;
}
Specific to some tag, ex: input tag
input:focus{
outline:none;
}
Yes. We have inbuilt function to remove an individual character of a string in java, that is, deleteCharAt
For example,
public class StringBuilderExample
{
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder("helloworld");
System.out.println("Before : " + sb);
sb = sb.deleteCharAt(3);
System.out.println("After : " + sb);
}
}
Output
Before : helloworld
After : heloworld
It subjects to architecture of the server on which PHP runs. For 64-bit,
print PHP_INT_MIN . ", ” . PHP_INT_MAX;
yields -9223372036854775808, 9223372036854775807
Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser
RSA Public Key
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
Encrypted Private Key
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----
CRL
-----BEGIN X509 CRL-----
-----END X509 CRL-----
CRT
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
CSR
-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----
NEW CSR
-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----
PEM
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
PKCS7
-----BEGIN PKCS7-----
-----END PKCS7-----
PRIVATE KEY
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
DSA KEY
-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----
Elliptic Curve
-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----
PGP Private Key
-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----
PGP Public Key
-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----
You can configure log4j.properties like above answers, or use org.apache.log4j.BasicConfigurator
public class FooImpl implements Foo {
private static final Logger LOGGER = Logger.getLogger(FooBar.class);
public Object createObject() {
BasicConfigurator.configure();
LOGGER.info("something");
return new Object();
}
}
So under the table, configure do:
configure() {
Logger root = Logger.getRootLogger();
root.addAppender(new ConsoleAppender(
new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
}
Well, according to Google's lectures (maybe here, I don't remember) , you should consider using Fragments whenever it's possible, as it makes your code easier to maintain and control.
However, I think that on some cases it can get too complex, as the activity that hosts the fragments need to navigate/communicate between them.
I think you should decide by yourself what's best for you. It's usually not that hard to convert an activity to a fragment and vice versa.
I've created a post about this dillema here, if you wish to read some further.
I don't know about performance or elegance of my solution, but it's what I'm using:
if (preg_match('/^[\[\{]\"/', $string)) {
$aJson = json_decode($string, true);
if (!is_null($aJson)) {
... do stuff here ...
}
}
Since all my JSON encoded strings start with {" it suffices to test for this with a RegEx. I'm not at all fluent with RegEx, so there might be a better way to do this. Also: strpos() might be quicker.
Just trying to give in my tuppence worth.
P.S. Just updated the RegEx string to /^[\[\{]\"/
to also find JSON array strings. So it now looks for either [" or {" at the beginning of the string.
It might be old but in my case, it was because of docker. Hope it will help others.
It's because command substitution is performed in a subshell, so while the subshell inherits the variables, changes to them are lost when the subshell ends.
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment
It is not a big deal. you can simply put like this
WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")}");
Excuse here for I used $ which is for string Interpolation .
Yes there is a way to do it.
First declare a class.
//anyfile.ts
export class Custom
{
name: string,
empoloyeeID: number
}
Then in your component import the class
import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<Custom> = [];
constructor() {
}
ngOnInit() {
}
onEmpCreate(){
//console.log(this.name,this.empoloyeeID);
let customObj = new Custom();
customObj.name = "something";
customObj.employeeId = 12;
this.empList.push(customObj);
this.name ="";
this.empoloyeeID = 0;
}
}
Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html
Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2
Well, you want to split, right?
String animals = "dog, cat, bear, elephant, giraffe";
String[] animalsArray = animals.split(",");
If you want to additionally get rid of whitespaces around items:
String[] animalsArray = animals.split("\\s*,\\s*");
The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:
var black = $('.black');
var white = $('.white');
The selector will find every element classed under black or white. Button functions stay as stated above:
$('#showBlackButton').click(function() {
black.show();
white.hide();
});
$('#showWhiteButton').click(function() {
white.show();
black.hide();
});
Oracle, PostgreSQL, SQL Server and many more RDBMS engines have analytic functions called LAG
and LEAD
that do this very thing.
In SQL Server prior to 2012 you'd need to do the following:
SELECT value - (
SELECT TOP 1 value
FROM mytable m2
WHERE m2.col1 < m1.col1 OR (m2.col1 = m1.col1 AND m2.pk < m1.pk)
ORDER BY
col1, pk
)
FROM mytable m1
ORDER BY
col1, pk
, where COL1
is the column you are ordering by.
Having an index on (COL1, PK)
will greatly improve this query.
You may also use math.log1p
.
According to the official documentation :
math.log1p(x)
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.
You may convert back to the original value using math.expm1
which returns e
raised to the power x, minus 1.
I based this on @asawyer's answer. He doesn't seem to get a compile error, but some of us do. Here is a version which the C# compiler in Visual Studio 2010 will accept.
var timer = new System.Threading.Timer(
e => MyMethod(),
null,
TimeSpan.Zero,
TimeSpan.FromMinutes(5));
Ftrujillo's answer works well but if you only have one package to scan this is the shortest form::
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("your.package.to.scan");
return marshaller;
}
Try this option.
update that coding part in Page_Load event before catching IsPostback
TextBox1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('ctl00_ContentPlaceHolder1_Button1').click();return false;}} else {return true}; ");
Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.
If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)
This is an old question and had many answers, but none of those fit well enough to my context. In my case, the containers are very lean and do not contain any of the networking tools necessary to extract the host's ip address from within the container.
Also, usin the --net="host"
approach is a very rough approach that is not applicable when one wants to have well isolated network configuration with several containers.
So, my approach is to extract the hosts' address at the host's side, and then pass it to the container with --add-host
parameter:
$ docker run --add-host=docker-host:`ip addr show docker0 | grep -Po 'inet \K[\d.]+'` image_name
or, save the host's IP address in an environment variable and use the variable later:
$ DOCKERIP=`ip addr show docker0 | grep -Po 'inet \K[\d.]+'`
$ docker run --add-host=docker-host:$DOCKERIP image_name
And then the docker-host
is added to the container's hosts file, and you can use it in your database connection strings or API URLs.
An example where things could go wrong with Shell=True is shown here
>>> from subprocess import call
>>> filename = input("What file would you like to display?\n")
What file would you like to display?
non_existent; rm -rf / # THIS WILL DELETE EVERYTHING IN ROOT PARTITION!!!
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
Check the doc here: subprocess.call()
Use this method.. and modify it according to ur view names. This code works great.
private boolean validateMobilenumber() {
if (mobilenumber.getText().toString().trim().isEmpty() || mobilenumber.getText().toString().length() < 10) {
input_layout_mobilenumber.setErrorEnabled(true);
input_layout_mobilenumber.setError(getString(R.string.err_msg_mobilenumber));
// requestFocus(mobilenumber);
return false;
} else {
input_layout_mobilenumber.setError(null);
input_layout_mobilenumber.setErrorEnabled(false);
mobilenumber.setBackground(mobilenumber.getBackground().getConstantState().newDrawable());
}
If your text will be consumed by non-browsers then it's safer to type the character with the keyboard-combo option shift right bracket
because ’
will not be transformed into an apostrophe by a regular XML or JSON parser. (e.g. if you are serving this content to native Android/iOS apps).
sed -ie 's/old_link/new_link/g' *
Works on both BSD & Linux with gnu sed
Does the user you're executing this script under even see that table??
select top 1 * from products
Do you get any output for this??
If yes: does this user have the permission to modify the table, i.e. execute DDL scripts like ALTER TABLE
etc.? Typically, regular users don't have this elevated permissions.
Without a loop, just for the kicks of it...
You can either convert the array to a non-associative one, by doing:
$page = array_values($page);
And then acessing each element by it's zero-based index:
echo $page[0]; // 'index.html'
echo $page[1]; // 'services.html'
Or you can use a slightly more complicated version:
$value = array_slice($page, 0, 1);
echo key($value); // Home
echo current($value); // index.html
$value = array_slice($page, 1, 1);
echo key($value); // Service
echo current($value); // services.html
push
does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:
import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
arr:[]
}
export default function userState(state = initialUserState, action){
console.log(arr);
switch (action.type){
case ADD_ITEM :
return {
...state,
arr:[...state.arr, action.newItem]
}
default:return state
}
}
ok figured it out:
<string name="sample_string"><![CDATA[some test line 1 <br />some test line 2]]></string>
so wrap in CDATA is necessary and breaks added inside as html tags
Here are categories for NSArray and NSDictionary to make this super-easy. I've added an option for pretty-print (newlines and tabs to make easier to read).
@interface NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end
.
@implementation NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];
if (! jsonData) {
NSLog(@"%s: error: %@", __func__, error.localizedDescription);
return @"{}";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
.
@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end
.
@implementation NSArray (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];
if (! jsonData) {
NSLog(@"%s: error: %@", __func__, error.localizedDescription);
return @"[]";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
I got this error generating a data frame consisting of timestamps and data:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))
Adding the suggested solution works for me:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))
Thanks Chang She!
Example:
data
2005-01-01 00:10:00 7.53
2005-01-01 00:20:00 7.54
2005-01-01 00:30:00 7.62
2005-01-01 00:40:00 7.68
2005-01-01 00:50:00 7.81
2005-01-01 01:00:00 7.95
2005-01-01 01:10:00 7.96
2005-01-01 01:20:00 7.95
2005-01-01 01:30:00 7.98
2005-01-01 01:40:00 8.06
2005-01-01 01:50:00 8.04
2005-01-01 02:00:00 8.06
2005-01-01 02:10:00 8.12
2005-01-01 02:20:00 8.12
2005-01-01 02:30:00 8.25
2005-01-01 02:40:00 8.27
2005-01-01 02:50:00 8.17
2005-01-01 03:00:00 8.21
2005-01-01 03:10:00 8.29
2005-01-01 03:20:00 8.31
2005-01-01 03:30:00 8.25
2005-01-01 03:40:00 8.19
2005-01-01 03:50:00 8.17
2005-01-01 04:00:00 8.18
data
2005-01-01 00:00:00 7.636000
2005-01-01 01:00:00 7.990000
2005-01-01 02:00:00 8.165000
2005-01-01 03:00:00 8.236667
2005-01-01 04:00:00 8.180000
In my case, six was installed for python 2.7 and for 3.7 too, and both pip install six
and pip3 install six
reported it as already installed, while I still had apps (particularly, the apt program itself) complaining about missing six.
The solution was to install it for python3.6 specifically:
/usr/bin/python3.6 -m pip install six
If you have a class with an object property, or if your property actually casts to an object, you can reshape the object by reassigning its properties, as in:
MyClass varClass = new MyClass();
varClass.propObjectProperty = new { Id = 1, Description = "test" };
//if you need to treat the class as an object
var varObjectProperty = ((dynamic)varClass).propObjectProperty;
((dynamic)varClass).propObjectProperty = new { Id = varObjectProperty.Id, Description = varObjectProperty.Description, NewDynamicProperty = "new dynamic property description" };
//if your property is an object, instead
var varObjectProperty = varClass.propObjectProperty;
varClass.propObjectProperty = new { Id = ((dynamic)varObjectProperty).Id, Description = ((dynamic)varObjectProperty).Description, NewDynamicProperty = "new dynamic property description" };
With this approach, you basically rewrite the object property adding or removing properties as if you were first creating the object with the
new { ... }
syntax.
In your particular case, you're probably better off creating an actual object to which you assign properties like "dob" and "address" as if it were a person, and at the end of the process, transfer the properties to the actual "Person" object.
The way to go with javascript:
var data = new FormData();
$.each($("input[type='file']")[0].files, function(i, file) {
data.append('file', file);
});
$.ajax({
type: 'POST',
url: '/your/url',
cache: false,
contentType: false,
processData: false,
data : data,
success: function(result){
console.log(result);
},
error: function(err){
console.log(err);
}
})
If you call data.append('file', file) multiple times your request will contain an array of your files.
"The
append()
method of theFormData
interface appends a new value onto an existing key inside aFormData
object, or adds the key if it does not already exist. The difference betweenFormData.se
t andappend()
is that if the specified key already exists,FormData.set
will overwrite all existing values with the new one, whereasappend()
will append the new value onto the end of the existing set of values."
Myself using node.js and multipart handler middleware multer get the data as follows:
router.post('/trip/save', upload.array('file', 10), function(req, res){
// Your array of files is in req.files
}
To amend SDP's answer above, you do NOT need to declarecol-xs-12
in <div class="col-xs-12 col-sm-6">
. Bootstrap 3 is mobile-first, so every div column is assumed to be a 100% width div by default - which means at the "xs" size it is 100% width, it will always default to that behavior regardless of what you set at sm, md, lg
. If you want your xs
columns to be not 100%, then you normally do a col-xs-(1-11)
.
The original question asked to "remove illegal characters":
public string RemoveInvalidChars(string filename)
{
return string.Concat(filename.Split(Path.GetInvalidFileNameChars()));
}
You may instead want to replace them:
public string ReplaceInvalidChars(string filename)
{
return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));
}
This answer was on another thread by Ceres, I really like it neat and simple.
The difference between a non-lateral
and a lateral
join lies in whether you can look to the left hand table's row. For example:
select *
from table1 t1
cross join lateral
(
select *
from t2
where t1.col1 = t2.col1 -- Only allowed because of lateral
) sub
This "outward looking" means that the subquery has to be evaluated more than once. After all, t1.col1
can assume many values.
By contrast, the subquery after a non-lateral
join can be evaluated once:
select *
from table1 t1
cross join
(
select *
from t2
where t2.col1 = 42 -- No reference to outer query
) sub
As is required without lateral
, the inner query does not depend in any way on the outer query. A lateral
query is an example of a correlated
query, because of its relation with rows outside the query itself.
Judging by your other post: How to Get the inner text of a span in PHP. You're quite new to web programming, and need to learn about the differences between code on the client (JavaScript) and code on the server (PHP).
As for the correct approach to grabbing the span text from the client I recommend Johns answer.
These are a good place to get started.
JavaScript: https://stackoverflow.com/questions/11246/best-resources-to-learn-javascript
PHP: https://stackoverflow.com/questions/772349/what-is-a-good-online-tutorial-for-php
Also I recommend using jQuery (Once you've got some JavaScript practice) it will eliminate most of the cross-browser compatability issues that you're going to have. But don't use it as a crutch to learn on, it's good to understand JavaScript too. http://jquery.com/
If your email address is '[email protected]', try changing the createDirectoryEntry() as below.
XYZ is an optional parameter if it exists in mydomain directory
static DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
DirectoryEntry ldapConnection = new DirectoryEntry("myname.mydomain.com");
ldapConnection.Path = "LDAP://OU=Users, OU=XYZ,DC=mydomain,DC=com";
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
return ldapConnection;
}
This will basically check for com -> mydomain -> XYZ -> Users -> abcd
The main function looks as below:
try
{
username = "Firstname LastName"
DirectoryEntry myLdapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(cn=" + username + ")";
....
For me it was simply that I hadn't added react-scripts
to the project so:
npm i -S react-scripts
If this doesn't work, then rm node_modules
as suggested by others
rm -r node_modules
npm i
django-admin --version
python manage.py --version
pip freeze | grep django
time
is a built-in command in most shells that writes execution time information to the tty.
You could also try something like
start_time=`date +%s`
<command-to-execute>
end_time=`date +%s`
echo execution time was `expr $end_time - $start_time` s.
Or in bash
:
start_time=`date +%s`
<command-to-execute> && echo run time is $(expr `date +%s` - $start_time) s
Select
UserID,
Value,
Date
From
Table,
(
Select
UserID,
Max(Date) as MDate
From
Table
Group by
UserID
) as subQuery
Where
Table.UserID = subQuery.UserID and
Table.Date = subQuery.mDate
class Program
{
static void Main(string[] args)
{
Type type = typeof(MyReflectionClass);
MethodInfo method = type.GetMethod("MyMethod");
MyReflectionClass c = new MyReflectionClass();
string result = (string)method.Invoke(c, null);
Console.WriteLine(result);
}
}
public class MyReflectionClass
{
public string MyMethod()
{
return DateTime.Now.ToString();
}
}
Here's another solution that avoids the use of jObject.CreateReader()
, and instead creates a new JsonTextReader
(which is the behavior used by the default JsonCreate.Deserialze
method:
public abstract class JsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
StringWriter writer = new StringWriter();
serializer.Serialize(writer, jObject);
using (JsonTextReader newReader = new JsonTextReader(new StringReader(writer.ToString())))
{
newReader.Culture = reader.Culture;
newReader.DateParseHandling = reader.DateParseHandling;
newReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
newReader.FloatParseHandling = reader.FloatParseHandling;
serializer.Populate(newReader, target);
}
return target;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
I think this message is not about avoiding to use switch
. Instead it wants you to check for hasOwnProperty
. The background can be read here: https://stackoverflow.com/a/16735184/1374488
For me just adding the "LOCAL" Keyword did the trick, please see the attached image for easier solution.
My attached image contains both use cases:
(a) Where I was getting this error. (b) Where error was resolved by just adding "Local" keyword.
Safari is blocking any call to window.open() which is made inside an async call.
The solution that I found to this problem is to call window.open before making an asnyc call and set the location when the promise resolves.
var windowReference = window.open();
myService.getUrl().then(function(url) {
windowReference.location = url;
});
Take the primitive type int
for example. There are several ways to declare and int
array:
int[] i = new int[capacity];
int[] i = new int[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
where in all of these, you can use int i[]
instead of int[] i
.
With reflection, you can use (Type[]) Array.newInstance(Type.class, capacity);
Note that in method parameters, ...
indicates variable arguments
. Essentially, any number of parameters is fine. It's easier to explain with code:
public static void varargs(int fixed1, String fixed2, int... varargs) {...}
...
varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};
Inside the method, varargs
is treated as a normal int[]
. Type...
can only be used in method parameters, so int... i = new int[] {}
will not compile.
Note that when passing an int[]
to a method (or any other Type[]
), you cannot use the third way. In the statement int[] i = *{a, b, c, d, etc}*
, the compiler assumes that the {...}
means an int[]
. But that is because you are declaring a variable. When passing an array to a method, the declaration must either be new Type[capacity]
or new Type[] {...}
.
Multidimensional arrays are much harder to deal with. Essentially, a 2D array is an array of arrays. int[][]
means an array of int[]
s. The key is that if an int[][]
is declared as int[x][y]
, the maximum index is i[x-1][y-1]
. Essentially, a rectangular int[3][5]
is:
[0, 0] [1, 0] [2, 0]
[0, 1] [1, 1] [2, 1]
[0, 2] [1, 2] [2, 2]
[0, 3] [1, 3] [2, 3]
[0, 4] [1, 4] [2, 4]
You don't need the assignment, list.append(x)
will always append x
to a
and therefore there's no need te redefine a
.
a = []
for i in range(5):
a.append(i)
print(a)
is all you need. This works because list
s are mutable.
Also see the docs on data structures.
here is generic swipe left detector for any view in kotlin using databinding
@BindingAdapter("onSwipeLeft")
fun View.setOnSwipeLeft(runnable: Runnable) {
setOnTouchListener(object : View.OnTouchListener {
var x0 = 0F; var y0 = 0F; var t0 = 0L
val defaultClickDuration = 200
override fun onTouch(v: View?, motionEvent: MotionEvent?): Boolean {
motionEvent?.let { event ->
when(event.action) {
MotionEvent.ACTION_DOWN -> {
x0 = event.x; y0 = event.y; t0 = System.currentTimeMillis()
}
MotionEvent.ACTION_UP -> {
val x1 = event.x; val y1 = event.y; val t1 = System.currentTimeMillis()
if (x0 == x1 && y0 == y1 && (t1 - t0) < defaultClickDuration) {
performClick()
return false
}
if (x0 > x1) { runnable.run() }
}
else -> {}
}
}
return true
}
})
}
and then to use it in your layout:
app:onSwipeLeft="@{() -> viewModel.swipeLeftHandler()}"
the above solutions wont work on ipad-2
recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)
Not saying your mapping is correct or wrong but I think hibernate wants a instance of the set where you declare the field.
@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
//@ElementCollection(targetClass=Role.class)
@Column(name = "ROLE_ID")
private Set<Role> roles = new HashSet<Role>();
When deciding to use Array or ArrayList, your first instinct really shouldn't be worrying about performance, though they do perform differently. You first concern should be whether or not you know the size of the Array before hand. If you don't, naturally you would go with an array list, just for functionality.
Even if you download the ISO files there will be lots of stuff not included in the installer which requires connection to internet when installing, for example:
Perhaps some of them are not possible to include but it is annoying nonetheless.
How about you store it like this? Maybe in username:password format, so
sebastion:password123
anotheruser:password321
Then you can use list($username,$password) = explode(':',file_get_contents('users.txt'));
to parse the data on your end.
Try this:
$('select[name="' + name + '"] option:selected').val();
This will get the selected value of your menu.
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
You are probably using Console.WriteLine
for printing the array.
int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
Console.WriteLine(item.ToString());
}
If you don't want to have every item on a separate line use Console.Write
:
int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
Console.Write(item.ToString());
}
or string.Join<T>
(in .NET Framework 4 or later):
int[] array = new int[] { 1, 2, 3 };
Console.WriteLine(string.Join(",", array));
If your array is populated through an SQL Query consider reversing the result in MySQL, ie :
SELECT * FROM model_input order by creation_date desc
You can write a simple gradle script to print your GRADLE_HOME
directory.
task getHomeDir {
doLast {
println gradle.gradleHomeDir
}
}
and name it build.gradle
.
Then run it with:
gradle getHomeDir
If you installed with homebrew, use brew info gradle
to find the base path (i.e. /usr/local/Cellar/gradle/1.10/
), and just append libexec
.
The same task in Kotlin in case you use build.gradle.kts
:
tasks.register("getHomeDir") {
println("Gradle home dir: ${gradle.gradleHomeDir}")
}
would this work?
cat requirements.txt | while read x; do conda install "$x" -p ./lib ;done
or
conda install --file requirements.txt -p ./lib
If you need to write line by line from string builder
StringBuilder sb = new StringBuilder();
sb.AppendLine("New Line!");
using (var sw = new StreamWriter(@"C:\MyDir\MyNewTextFile.txt", true))
{
sw.Write(sb.ToString());
}
If you need to write all text as single line from string builder
StringBuilder sb = new StringBuilder();
sb.Append("New Text line!");
using (var sw = new StreamWriter(@"C:\MyDir\MyNewTextFile.txt", true))
{
sw.Write(sb.ToString());
}
I tried changing the port from 8080
to 80
in the server.xml
but it didn't work for me. Then I found alternative, update the iptables
which i'm sure there is an impact on performance.
I use the following commands:
sudo /sbin/iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo /sbin/service iptables save
http://www.excelsior-usa.com/articles/tomcat-amazon-ec2-advanced.html#port80
You can use a generator expression (supported in all browsers for years now, and in Node) to get the key-value pairs in a list you can reduce on:
>>> a = {"b": 3}
Object { b=3}
>>> [[i, a[i]] for (i in a) if (a.hasOwnProperty(i))]
[["b", 3]]
It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.
CMP
subtracts the operands and sets the flags. Namely, it sets the zero flag if the difference is zero (operands are equal).
TEST
sets the zero flag, ZF
, when the result of the AND operation is zero. If two operands are equal, their bitwise AND is zero when both are zero. TEST
also sets the sign flag, SF
, when the most significant bit is set in the result, and the parity flag, PF
, when the number of set bits is even.
JE
[Jump if Equals] tests the zero flag and jumps if the flag is set. JE
is an alias of JZ
[Jump if Zero] so the disassembler cannot select one based on the opcode. JE
is named such because the zero flag is set if the arguments to CMP
are equal.
So,
TEST %eax, %eax
JE 400e77 <phase_1+0x23>
jumps if the %eax
is zero.
You can append to your PATH
in a minimal fashion. No need for
parentheses unless you're appending more than one element. It also
usually doesn't need quotes. So the simple, short way to append is:
path+=/some/new/bin/dir
This lower-case syntax is using path
as an array, yet also
affects its upper-case partner equivalent, PATH
(to which it is
"bound" via typeset
).
(Notice that no :
is needed/wanted as a separator.)
Then the common pattern for testing a new script/executable becomes:
path+=$PWD/.
# or
path+=$PWD/bin
You can sprinkle path settings around your .zshrc
(as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)
).
Treating path
this way (as an array) also means: no need to do a
rehash
to get the newly pathed commands to be found.
Also take a look at vared path
as a dynamic way to edit path
(and other things).
You may only be interested in path
for this question, but since
we're talking about exports and arrays, note that
arrays generally cannot be exported.
You can even prevent PATH
from taking on duplicate entries
(refer to
this
and this):
typeset -U path
F# is essentially the C++ of functional programming languages. They kept almost everything from Objective Caml, including the really stupid parts, and threw it on top of the .NET runtime in such a way that it brings in all the bad things from .NET as well.
For example, with Objective Caml you get one type of null, the option<T>. With F# you get three types of null, option<T>, Nullable<T>, and reference nulls. This means if you have an option you need to first check to see if it is "None", then you need to check if it is "Some(null)".
F# is like the old Java clone J#, just a bastardized language just to attract attention. Some people will love it, a few of those will even use it, but in the end it is still a 20-year-old language tacked onto the CLR.
If you want the margin-left
to work on a span
element you'll need to make it display: inline-block
or display:block
as well.
You're correct, in that example the throws
is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.
For testing simple objects, use:
if (obj[x] !== undefined)
If you don't know what object type it is, use:
if (obj.hasOwnProperty(x))
All other options are slower...
A performance evaluation of 100,000,000 cycles under Node.js to the five options suggested by others here:
function hasKey1(k,o) { return (x in obj); }
function hasKey2(k,o) { return (obj[x]); }
function hasKey3(k,o) { return (obj[x] !== undefined); }
function hasKey4(k,o) { return (typeof(obj[x]) !== 'undefined'); }
function hasKey5(k,o) { return (obj.hasOwnProperty(x)); }
The evaluation tells us that unless we specifically want to check the object's prototype chain as well as the object itself, we should not use the common form:
if (X in Obj)...
It is between 2 to 6 times slower depending on the use case
hasKey1 execution time: 4.51 s
hasKey2 execution time: 0.90 s
hasKey3 execution time: 0.76 s
hasKey4 execution time: 0.93 s
hasKey5 execution time: 2.15 s
Bottom line, if your Obj is not necessarily a simple object and you wish to avoid checking the object's prototype chain and to ensure x is owned by Obj directly, use if (obj.hasOwnProperty(x))...
.
Otherwise, when using a simple object and not being worried about the object's prototype chain, using if (typeof(obj[x]) !== 'undefined')...
is the safest and fastest way.
If you use a simple object as a hash table and never do anything kinky, I would use if (obj[x])...
as I find it much more readable.
An object and an instance are the same thing.
Personally I prefer to use the word "instance" when referring to a specific object of a specific type, for example "an instance of type Foo". But when talking about objects in general I would say "objects" rather than "instances".
A reference either refers to a specific object or else it can be a null reference.
They say that they have to create an instance to their application. What does it mean?
They probably mean you have to write something like this:
Foo foo = new Foo();
If you are unsure what type you should instantiate you should contact the developers of the application and ask for a more complete example.
I changed the TextView's color to blue by using for example:
android:textColor="#3399FF"
in the xml file. How to make it underlined is explained here.
Then use its onClick property to specify a method (I'm guessing you could call setOnClickListener(this)
as another way), e.g.:
myTextView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doSomething();
}
});
In that method, I can do whatever I want as normal, such as launch an intent. Note that you still have to do the normal myTextView.setMovementMethod(LinkMovementMethod.getInstance());
thing, like in your acitivity's onCreate() method.
I just had this problem and wrapping each cell with the CLEAN
function fixed it for me. That should be relatively easy to do by doing =CLEAN(
, selecting your cell, and then autofilling the rest of the column. After I did this, pastes into Notepad or any other program no longer had duplicate quotes.
From the mysql documentation version: 8.0.18:
A superuser account 'root'@'localhost'
is created. A password for the superuser is set and stored
in the error log file. To reveal it, use the following command:
shell> sudo grep 'temporary password' /var/log/mysqld.log
Change the root password as soon as possible by logging in with the generated, temporary password
and set a custom password for the superuser account:
shell> mysql -uroot -p
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass4!';
I found I had to be logged in as a domain user.
It gave me this error when I was logged in as local machine Administrator and trying to add domain service account.
Logged in as domain user (but admin on machine) and it accepted the credentials.
I think you want something along the line of:
Parent:
<Editor name={this.state.fileData} />
Editor:
var Editor = React.createClass({
displayName: 'Editor',
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
value: this.props.name
};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
});
This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html
Update for React 16.8:
import React, { useState } from 'react';
const Editor = (props) => {
const [value, setValue] = useState(props.name);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
}
Editor.propTypes = {
name: PropTypes.string.isRequired
};
You can also:
DataRowView row = dataGrid.SelectedItem as DataRowView;
MessageBox.Show(row.Row.ItemArray[1].ToString());
As others have said, you're not using the right function name and it doesn't exist univerally in all browsers.
If you need to do cross-browser fetching of anything other than an element with an id with document.getElementById()
, then I would strongly suggest you get a library that supports CSS3 selectors across all browsers. It will save you a massive amount of development time, testing and bug fixing. The easiest thing to do is to just use jQuery because it's so widely available, has excellent documentation, has free CDN access and has an excellent community of people behind it to answer questions. If that seems like more than you need, then you can get Sizzle which is just a selector library (it's actually the selector engine inside of jQuery and others). I've used it by itself in other projects and it's easy, productive and small.
If you want to select multiple nodes at once, you can do that many different ways. If you give them all the same class, you can do that with:
var list = document.getElementsByClassName("myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
and it will return a list of nodes that have that class name.
In Sizzle, it would be this:
var list = Sizzle(".myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
In jQuery, it would be this:
$(".myButton").each(function(index, element) {
// element is a node with the desired class name
});
In both Sizzle and jQuery, you can put multiple class names into the selector like this and use much more complicated and powerful selectors:
$(".myButton, .myInput, .homepage.gallery, #submitButton").each(function(index, element) {
// element is a node that matches the selector
});
Use the SQLite keyword default
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " ("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_NAME + " TEXT NOT NULL, "
+ KEY_WORKED + " INTEGER, "
+ KEY_NOTE + " INTEGER DEFAULT 0);");
This link is useful: http://www.sqlite.org/lang_createtable.html
I had this because something bad was in my vendor/bundle
. Nothing to do with Apache, just in local dev env.
To fix, I deleted vendor\bundle
, and also deleted the reference to it in my .bundle/config
so it wouldn't get re-used.
Then, I re-bundled (which then installed to GEM_HOME
instead of vendor/bundle
and the problem went away.
Just Select App from dropdown menu with Run(green play icon). it will run the whole the App not the specific Activity. if it doesn't help try to use in that activity in ManiFest.xml file. thankyou
First use git remote update
, to bring your remote refs up to date. Then you can do one of several things, such as:
git status -uno
will tell you whether the branch you are tracking
is ahead, behind or has diverged. If it says nothing, the local and
remote are the same. Sample result:On branch DEV
Your branch is behind 'origin/DEV' by 7 commits, and can be fast-forwarded.
(use "git pull" to update your local branch)
git show-branch *master
will show you the commits in all of the
branches whose names end in 'master' (eg master and origin/master).If you use -v
with git remote update (git remote -v update
) you can see which branches got updated, so you don't really need any further commands.
When a client connects to an Oracle server, it first connnects to the Oracle listener service. It often redirects the client to another port. So the client has to open another connection on a different port, which is blocked by the firewall.
So you might in fact have encountered a firewall problem due to Oracle port redirection. It should be possible to diagnose it with a network monitor on the client machine or with the firewall management software on the firewall.
Nobody mentions the similar but even simpler solution than above with no need to deal with the package of the class. Assuming myfile.properties is in the classpath.
Properties properties = new Properties();
InputStream in = ClassLoader.getSystemResourceAsStream("myfile.properties");
properties.load(in);
in.close();
Enjoy
Simply use
$(document).height() // - $('body').offset().top
and / or
$(window).height()
instead of $('body').height();
With current versions of Docker, you can use the --device
flag to achieve what you want, without needing to give access to all USB devices.
For example, if you wanted to make only /dev/ttyUSB0
accessible within your Docker container, you could do something like:
docker run -t -i --device=/dev/ttyUSB0 ubuntu bash
After hours of analysis reading tons of logs and internet, finally found problem.
If you use docker and php 7.4 (my case) you probably get error because default security level in OpenSSL it too high for wsdl cert. Even if you disable verify and allow self-signed in SoapClient options.
You need lower seclevel in /etc/ssl/openssl.cnf
from DEFAULT@SECLEVEL=2
to
DEFAULT@SECLEVEL=1
Or just add into Dockerfile
RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf
Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876
You can verify it by run on container
curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl
Before that change I got error:
SSL routines:tls_process_ske_dhe:dh key too small
Try to save the .config file as utf-8 if you have some "special" characters in there. That was the issue in my case of a console application.
Another benefit of require()
is that it returns a logical value by default. TRUE
if the packages is loaded, FALSE
if it isn't.
> test <- library("abc")
Error in library("abc") : there is no package called 'abc'
> test
Error: object 'test' not found
> test <- require("abc")
Loading required package: abc
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
there is no package called 'abc'
> test
[1] FALSE
So you can use require()
in constructions like the one below. Which mainly handy if you want to distribute your code to our R installation were packages might not be installed.
if(require("lme4")){
print("lme4 is loaded correctly")
} else {
print("trying to install lme4")
install.packages("lme4")
if(require(lme4)){
print("lme4 installed and loaded")
} else {
stop("could not install lme4")
}
}
Try this:
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/map_toolbar_details_selected" />
Also for colors i had success with
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:color="@color/primary_color" />
<item
android:color="@color/secondary_color" />
</selector>
Random random = new Random();
double NextDouble(double minimum, double maximum)
{
return random.NextDouble()*random.Next(minimum,maximum);
}
You are in the "Output" tab instead of the Terminal. The output tab is actually only for you to read from.
Press F5
to begin Debugging
and it'll bring you into the Terminal tab.
The terminal is interactive, so you can read output AND type back. It is indeed a console prompt/ terminal (hence its name).
You guys are completely right numbers can only go in the numeric field. I use the exact same thing as already listed with a bit of css styling on a span tag:
<span>$</span><input type="number" min="0.01" step="0.01" max="2500" value="25.67">
Then add a bit of styling magic:
span{
position:relative;
margin-right:-20px
}
input[type='number']{
padding-left:20px;
text-align:left;
}
List of One Liners
Let's solve this problem for this array:
var array = ['A', 'B', 'C'];
1. Remove only the first: Use If you are sure that the item exist
array.splice(array.indexOf('B'), 1);
2. Remove only the last: Use If you are sure that the item exist
array.splice(array.lastIndexOf('B'), 1);
3. Remove all occurrences:
array = array.filter(v => v !== 'B');
It is very simple if position is '0' then call onNothingSelected method in OnItemSelectedListener. It worked fine for me.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
**if (position == 0)
{
onNothingSelected(parent);
}**
else {
String mechanicType = mechanicTpes[position];
Toast.makeText(FirstUser.this, "Mechanic Tpye : "+mechanicType, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(FirstUser.this, "NOTHING SELECTED IN SPINNER", Toast.LENGTH_SHORT).show();
}
});
Since the cleanup is not dependent on the username
, you could put the cleanup in a separate useEffect
that is given an empty array as second argument.
Example
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
const [name, setName] = useState("");_x000D_
const [username, setUsername] = useState("");_x000D_
_x000D_
useEffect(_x000D_
() => {_x000D_
console.log("effect");_x000D_
},_x000D_
[username]_x000D_
);_x000D_
_x000D_
useEffect(() => {_x000D_
return () => {_x000D_
console.log("cleaned up");_x000D_
};_x000D_
}, []);_x000D_
_x000D_
const handleName = e => {_x000D_
const { value } = e.target;_x000D_
_x000D_
setName(value);_x000D_
};_x000D_
_x000D_
const handleUsername = e => {_x000D_
const { value } = e.target;_x000D_
_x000D_
setUsername(value);_x000D_
};_x000D_
_x000D_
return (_x000D_
<div>_x000D_
<div>_x000D_
<input value={name} onChange={handleName} />_x000D_
<input value={username} onChange={handleUsername} />_x000D_
</div>_x000D_
<div>_x000D_
<div>_x000D_
<span>{name}</span>_x000D_
</div>_x000D_
<div>_x000D_
<span>{username}</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
function App() {_x000D_
const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
useEffect(() => {_x000D_
setTimeout(() => {_x000D_
setShouldRender(false);_x000D_
}, 5000);_x000D_
}, []);_x000D_
_x000D_
return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
you can use layout_constraintCircle for center view inside ConstraintLayout.
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mparent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/btn_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_home_black_24dp"
app:layout_constraintCircle="@id/mparent"
app:layout_constraintCircleRadius="0dp"
/>
</android.support.constraint.ConstraintLayout>
with constraintCircle to parent and zero radius you can make your view be center of parent.
You want to count the number of itemids in your array. Simply use:
int counter=list.size();
Less code increases efficiency. Do not re-invent the wheel...
You want something more like this:
SELECT TableA.*, TableB.*, TableC.*, TableD.*
FROM TableA
JOIN TableB
ON TableB.aID = TableA.aID
JOIN TableC
ON TableC.cID = TableB.cID
JOIN TableD
ON TableD.dID = TableA.dID
WHERE DATE(TableC.date)=date(now())
In your example, you are not actually including TableD
. All you have to do is perform another join just like you have done before.
A note: you will notice that I removed many of your parentheses, as they really are not necessary in most of the cases you had them, and only add confusion when trying to read the code. Proper nesting is the best way to make your code readable and separated out.
return results == null ? 0 : (results[1] || 0);
class Example extends React.Component {_x000D_
constructor() {_x000D_
super();_x000D_
this.state = { time: {}, seconds: 5 };_x000D_
this.timer = 0;_x000D_
this.startTimer = this.startTimer.bind(this);_x000D_
this.countDown = this.countDown.bind(this);_x000D_
}_x000D_
_x000D_
secondsToTime(secs){_x000D_
let hours = Math.floor(secs / (60 * 60));_x000D_
_x000D_
let divisor_for_minutes = secs % (60 * 60);_x000D_
let minutes = Math.floor(divisor_for_minutes / 60);_x000D_
_x000D_
let divisor_for_seconds = divisor_for_minutes % 60;_x000D_
let seconds = Math.ceil(divisor_for_seconds);_x000D_
_x000D_
let obj = {_x000D_
"h": hours,_x000D_
"m": minutes,_x000D_
"s": seconds_x000D_
};_x000D_
return obj;_x000D_
}_x000D_
_x000D_
componentDidMount() {_x000D_
let timeLeftVar = this.secondsToTime(this.state.seconds);_x000D_
this.setState({ time: timeLeftVar });_x000D_
}_x000D_
_x000D_
startTimer() {_x000D_
if (this.timer == 0 && this.state.seconds > 0) {_x000D_
this.timer = setInterval(this.countDown, 1000);_x000D_
}_x000D_
}_x000D_
_x000D_
countDown() {_x000D_
// Remove one second, set state so a re-render happens._x000D_
let seconds = this.state.seconds - 1;_x000D_
this.setState({_x000D_
time: this.secondsToTime(seconds),_x000D_
seconds: seconds,_x000D_
});_x000D_
_x000D_
// Check if we're at zero._x000D_
if (seconds == 0) { _x000D_
clearInterval(this.timer);_x000D_
}_x000D_
}_x000D_
_x000D_
render() {_x000D_
return(_x000D_
<div>_x000D_
<button onClick={this.startTimer}>Start</button>_x000D_
m: {this.state.time.m} s: {this.state.time.s}_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Example/>, document.getElementById('View'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="View"></div>
_x000D_
How about:
if (stream.markSupported() == false) {
// lets replace the stream object
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(stream, baos);
stream.close();
stream = new ByteArrayInputStream(baos.toByteArray());
// now the stream should support 'mark' and 'reset'
}
Based on my experience, even with python 3.3+, an empty __init__.py
is still needed sometimes. One situation is when you want to refer a subfolder as a package. For example, when I ran python -m test.foo
, it didn't work until I created an empty __init__.py
under the test folder. And I'm talking about 3.6.6 version here which is pretty recent.
Apart from that, even for reasons of compatibility with existing source code or project guidelines, its nice to have an empty __init__.py
in your package folder.
You can do this in 2 steps:
1: Change the input type(In your EditText
field) in the layout file to android:inputType="number"
2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());
In Windows: Right click on "Git Bash" icon -> Run as Administrator. it helped me.
Git tries to create a config file on disk C:/ but it has no permission to do that.
This solution fixed my problem while replacing br tag to '\n' .
alert(content.replace(/<br\/\>/g,'\n'));
I think you should not rely on the implicit conversion. It is a bad practice.
Instead you should try like this:
datenum >= to_date('11/26/2013','mm/dd/yyyy')
or like
datenum >= date '2013-09-01'
In your HTML code
<form [formGroup]="userForm">
<input type="text" class="form-control" [value]="item.UserFirstName" formControlName="UserFirstName">
<input type="text" class="form-control" [value]="item.UserLastName" formControlName="UserLastName">
</form>
In your Typescript code
export class UserprofileComponent implements OnInit {
userForm: FormGroup;
constructor(){
this.userForm = new FormGroup({
UserFirstName: new FormControl(),
UserLastName: new FormControl()
});
}
}
This works perfectly, it does not give any error.
Parsing is just process of analyse the string of character and find the tokens from that string and parser is a component of interpreter and compiler.It uses lexical analysis and then syntactic analysis.It parse it and then compile this code after this whole process of compilation.
I went with a slightly modified version of @shibbir's answer:
// Clear form fields in a designated area of a page
$.clearFormFields = function(area) {
$(area).find('input[type="text"],input[type="email"],textarea,select').val('');
};
Called this way:
$('#my-modal').on('hidden', function(){
$.clearFormFields(this)
});
Well, I don't know guys but:
using here python 3.6 and django 2.2
Renaming MIDDLEWARE_CLASSES to MIDDLEWARE in settings.py worked.
I believe this should work for all browsers:
var event;
if (typeof (Event) === 'function') {
event = new Event('resize');
} else { /*IE*/
event = document.createEvent('Event');
event.initEvent('resize', true, true);
}
window.dispatchEvent(event);
You could try to split on (?<=\D)(?=\d)|(?<=\d)(?=\D)
, like:
str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
It matches positions between a number and not-a-number (in any order).
(?<=\D)(?=\d)
- matches a position between a non-digit (\D
) and a digit (\d
)(?<=\d)(?=\D)
- matches a position between a digit and a non-digit.<button type="submit" name="uname" value="uname" onclick="browserlink(ex.google.com,home.html etc)or myfunction();"> submit</button>
if you want to open a page on the click of a button in HTML without any scripting language then you can use above code.
I used MyActivity.class and getCanonicalName method and I got answer.
protected Boolean isActivityRunning(Class activityClass)
{
ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo task : tasks) {
if (activityClass.getCanonicalName().equalsIgnoreCase(task.baseActivity.getClassName()))
return true;
}
return false;
}
This works now with the Visual Studio AddIn treated in this article: SlowCheetah - Web.config Transformation Syntax now generalized for any XML configuration file.
You can right-click on your web.config and click "Add Config Transforms." When you do this, you'll get a web.debug.config and a web.release.config. You can make a web.whatever.config if you like, as long as the name lines up with a configuration profile. These files are just the changes you want made, not a complete copy of your web.config.
You might think you'd want to use XSLT to transform a web.config, but while they feels intuitively right it's actually very verbose.
Here's two transforms, one using XSLT and the same one using the XML Document Transform syntax/namespace. As with all things there's multiple ways in XSLT to do this, but you get the general idea. XSLT is a generalized tree transformation language, while this deployment one is optimized for a specific subset of common scenarios. But, the cool part is that each XDT transform is a .NET plugin, so you can make your own.
<?xml version="1.0" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="/configuration/appSettings"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> <xsl:element name="add"> <xsl:attribute name="key">NewSetting</xsl:attribute> <xsl:attribute name="value">New Setting Value</xsl:attribute> </xsl:element> </xsl:copy> </xsl:template> </xsl:stylesheet>
Or the same thing via the deployment transform:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <appSettings> <add name="NewSetting" value="New Setting Value" xdt:Transform="Insert"/> </appSettings> </configuration>
You can try this way also.
<?php
$obj = json_decode("{}");
var_dump($obj);
?>
Output:
object(stdClass)#1 (0) { }
This issue may be due to the flags of chrome browser. Reset it, it worked for me. chrome://flags Right corner 'Reset all to defaults' button.
Both answers given worked for the problem I stated -- Thanks!
In my real application though, I was trying to constrain a panel inside of a ScrollViewer and Kent's method didn't handle that very well for some reason I didn't bother to track down. Basically the controls could expand beyond the MaxWidth setting and defeated my intent.
Nir's technique worked well and didn't have the problem with the ScrollViewer, though there is one minor thing to watch out for. You want to be sure the right and left margins on the TextBox are set to 0 or they'll get in the way. I also changed the binding to use ViewportWidth instead of ActualWidth to avoid issues when the vertical scrollbar appeared.
Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:
# Set seed for reproducibility.
set.seed(1)
# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))
# compare data frames by specific columns and keep only
# the rows with equal values
data_A[data_A$id %in% data_B$id,] # will keep data in data_A
data_B[data_B$id %in% data_A$id,] # will keep data in data_b
Results:
> data_A[data_A$id %in% data_B$id,]
id value
1 1 1
2 2 2
3 3 3
> data_B[data_B$id %in% data_A$id,]
id value
1 1 5
2 2 6
3 3 7
This is a CORS issue. There are some settings you can change in angular - these are the ones I typically set in the Angular .config method (not all are related to CORS):
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
You also need to configure your webservice - the details of this will depend on the server side language you are using. If you use a network monitoring tool you will see it sends an OPTIONS request initially. Your server needs to respond appropriately to allow the CORS request.
The reason it works in your brower is because it isn't make a cross-origin request - whereas your Angular code is.
public class camera_act extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_act);
ImageView imageView = findViewById(R.id.image);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,90);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode,resultCode,data);
Bitmap bitmap = data.getExtras.get("imageKey");
imageView.setBitmapImage(bitmap);
}
}
}
closures are beautiful! they solve a lot of problems that come with anonymous functions, and make really elegant code possible (at least as long as we talk about php).
javascript programmers use closures all the time, sometimes even without knowing it, because bound variables aren't explicitly defined - that's what "use" is for in php.
there are better real-world examples than the above one. lets say you have to sort an multidimensional array by a sub-value, but the key changes.
<?php
function generateComparisonFunctionForKey($key) {
return function ($left, $right) use ($key) {
if ($left[$key] == $right[$key])
return 0;
else
return ($left[$key] < $right[$key]) ? -1 : 1;
};
}
$myArray = array(
array('name' => 'Alex', 'age' => 70),
array('name' => 'Enrico', 'age' => 25)
);
$sortByName = generateComparisonFunctionForKey('name');
$sortByAge = generateComparisonFunctionForKey('age');
usort($myArray, $sortByName);
usort($myArray, $sortByAge);
?>
warning: untested code (i don't have php5.3 installed atm), but it should look like something like that.
there's one downside: a lot of php developers may be a bit helpless if you confront them with closures.
to understand the nice-ty of closures more, i'll give you another example - this time in javascript. one of the problems is the scoping and the browser inherent asynchronity. especially, if it comes to window.setTimeout();
(or -interval). so, you pass a function to setTimeout, but you can't really give any parameters, because providing parameters executes the code!
function getFunctionTextInASecond(value) {
return function () {
document.getElementsByName('body')[0].innerHTML = value; // "value" is the bound variable!
}
}
var textToDisplay = prompt('text to show in a second', 'foo bar');
// this returns a function that sets the bodys innerHTML to the prompted value
var myFunction = getFunctionTextInASecond(textToDisplay);
window.setTimeout(myFunction, 1000);
myFunction returns a function with a kind-of predefined parameter!
to be honest, i like php a lot more since 5.3 and anonymous functions/closures. namespaces may be more important, but they're a lot less sexy.
Is just casting the value returned by time()
#include <stdio.h>
#include <time.h>
int main(void) {
printf("Timestamp: %d\n",(int)time(NULL));
return 0;
}
what you want?
$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167
To get microseconds since the epoch, from C11 on, the portable way is to use
int timespec_get(struct timespec *ts, int base)
Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime
or gettimeofday
(marked obsolete in POSIX.1-2008, which recommends clock_gettime
).
The code for both functions is nearly identical:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>
int main(void) {
struct timespec tms;
/* The C11 way */
/* if (! timespec_get(&tms, TIME_UTC)) { */
/* POSIX.1-2008 way */
if (clock_gettime(CLOCK_REALTIME,&tms)) {
return -1;
}
/* seconds, multiplied with 1 million */
int64_t micros = tms.tv_sec * 1000000;
/* Add full microseconds */
micros += tms.tv_nsec/1000;
/* round up if necessary */
if (tms.tv_nsec % 1000 >= 500) {
++micros;
}
printf("Microseconds: %"PRId64"\n",micros);
return 0;
}
There's a new @config
tag for these cases. They link to the preceding @param
.
/** My function does X and Y.
@params {object} parameters An object containing the parameters
@config {integer} setting1 A required setting.
@config {string} [setting2] An optional setting.
@params {MyClass~FuncCallback} callback The callback function
*/
function(parameters, callback) {
// ...
};
/**
* This callback is displayed as part of the MyClass class.
* @callback MyClass~FuncCallback
* @param {number} responseCode
* @param {string} responseMessage
*/
I was successful using tidy
command line utility. On linux I installed it quickly with apt-get install tidy
. Then the command:
tidy -q -asxml --numeric-entities yes source.html >file.xml
gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.
This is their homepage: html-tidy.org (and the legacy one: HTML Tidy)
Actually, you will get the best performance if you avoid +
operator and use concat()
in this case. It is the best option for merging just 2 strings (not so good for many strings though). In that case the code would look like this:
String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));
In C++, you can use the global function std::getline, it takes a string and a stream and an optional delimiter and reads 1 line until the delimiter specified is reached. An example:
#include <string>
#include <iostream>
#include <fstream>
int main() {
std::ifstream input("filename.txt");
std::string line;
while( std::getline( input, line ) ) {
std::cout<<line<<'\n';
}
return 0;
}
This program reads each line from a file and echos it to the console.
For C you're probably looking at using fgets
, it has been a while since I used C, meaning I'm a bit rusty, but I believe you can use this to emulate the functionality of the above C++ program like so:
#include <stdio.h>
int main() {
char line[1024];
FILE *fp = fopen("filename.txt","r");
//Checks if file is empty
if( fp == NULL ) {
return 1;
}
while( fgets(line,1024,fp) ) {
printf("%s\n",line);
}
return 0;
}
With the limitation that the line can not be longer than the maximum length of the buffer that you're reading in to.
While changing the default behavior for Visual Studio Code requires an extension, you may override the default behavior in the workspace or user level. It works for most of the supported languages (I can guarantee HTML, JavaScript, and C#).
Benefits
Outcomes
.vscode/settings.json
is created in the project root folderHow To?
Go to: Menu File → Preferences → Workspace Settings
Add and save "editor.formatOnType": true
to settings.json (which overrides default behavior for the project you work on by creating .vscode/settings.json file).
Benefits
Outcomes
settings.json
is modified (see location by operating system below)How To?
Go to: menu File → Preferences → User Settings
Add or change the value of "editor.formatOnType": false
to "editor.formatOnType": true
in the user settings.json
Your Visual Studio Code user's settings.json
location is:
Settings file locations depending on your platform, the user settings file is located here:
%APPDATA%\Code\User\settings.json
$HOME/Library/Application Support/Code/User/settings.json
$HOME/.config/Code/User/settings.json
The workspace setting file is located under the .vscode folder in your project.More details may be found here.
Here's something that has been working for me (without instrumentation):
Instead of using @OneToOne
on both sides, I use @OneToMany
in the inverse part of the relationship (the one with mappedBy
). That makes the property a collection (List
in the example below), but I translate it into an item in the getter, making it transparent to the clients.
This setup works lazily, that is, the selects are only made when getPrevious()
or getNext()
are called - and only one select for each call.
CREATE TABLE `TB_ISSUE` (
`ID` INT(9) NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(255) NULL,
`PREVIOUS` DECIMAL(9,2) NULL
CONSTRAINT `PK_ISSUE` PRIMARY KEY (`ID`)
);
ALTER TABLE `TB_ISSUE` ADD CONSTRAINT `FK_ISSUE_ISSUE_PREVIOUS`
FOREIGN KEY (`PREVIOUS`) REFERENCES `TB_ISSUE` (`ID`);
@Entity
@Table(name = "TB_ISSUE")
public class Issue {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
@Column
private String name;
@OneToOne(fetch=FetchType.LAZY) // one to one, as expected
@JoinColumn(name="previous")
private Issue previous;
// use @OneToMany instead of @OneToOne to "fake" the lazy loading
@OneToMany(mappedBy="previous", fetch=FetchType.LAZY)
// notice the type isnt Issue, but a collection (that will have 0 or 1 items)
private List<Issue> next;
public Integer getId() { return id; }
public String getName() { return name; }
public Issue getPrevious() { return previous; }
// in the getter, transform the collection into an Issue for the clients
public Issue getNext() { return next.isEmpty() ? null : next.get(0); }
}
TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)
The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.
"name":"value"
.Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.
What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name")
, and then create another JProperty of your desire and then add it after this using AddAfterSelf
method. You are done then.
For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm
This is the code I modified.
public class Program
{
public static void Main()
{
try
{
string jsonText = @"
{
""food"": {
""fruit"": {
""apple"": {
""colour"": ""red"",
""size"": ""small""
},
""orange"": {
""colour"": ""orange"",
""size"": ""large""
}
}
}
}";
var foodJsonObj = JObject.Parse(jsonText);
var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");
var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));
Console.WriteLine(foodJsonObj.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
}
}
}
This is a workaround, but works for me:
Created res/drawable/divider.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:startColor="#ffcdcdcd" android:endColor="#ffcdcdcd" android:angle="270.0" />
</shape>
And in styles.xml for listview item, I added the following lines:
<item name="android:divider">@drawable/divider</item>
<item name="android:dividerHeight">1px</item>
Crucial part was to include this 1px setting. Of course, drawable uses gradient (with 1px) and that's not the optimal solution. I tried using stroke but didn't get it to work. (You don't seem to use styles, so just add android:dividerHeight="1px" attribute for the ListView.
Use insert method from range, for example
Sub InsertColumn()
Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("C1").Value = "Loc"
End Sub
This is the RegKey I used:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"DisableUNCCheck"=dword:00000001
Use jQuery's noConflict
. It did wonders for me
var example=jQuery.noConflict();
example(function(){
example('div#rift_connect').click(function(){
example('span#resultado').text("Hello, dude!");
});
});
That is, assuming you included jQuery on your HTML
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Starting with Spring Boot 1.4.0 you can use this in your test:
import org.springframework.boot.context.embedded.LocalServerPort;
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {
@LocalServerPort
int randomPort;
// ...
}
go to python/scripts folder, open a command window to this path, type the following:
C:\python34\scripts> python -m pip install pygame
To test it, open python IDE and type
import pygame
print (pygame.ver)
It worked for me...
Sorry I decided to write another answer since none of the other answers are copy-pasteable enough.
If you don't want to decorate properties with some attributes, or if you have no access to the class, or if you want to decide what to serialize during runtime, etc. etc. here's how you do it in Newtonsoft.Json
//short helper class to ignore some properties from serialization
public class IgnorePropertiesResolver : DefaultContractResolver
{
private readonly HashSet<string> ignoreProps;
public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
{
this.ignoreProps = new HashSet<string>(propNamesToIgnore);
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (this.ignoreProps.Contains(property.PropertyName))
{
property.ShouldSerialize = _ => false;
}
return property;
}
}
Usage
JsonConvert.SerializeObject(YourObject, new JsonSerializerSettings()
{ ContractResolver = new IgnorePropertiesResolver(new[] { "Prop1", "Prop2" }) };);
Note: make sure you cache the ContractResolver
object if you decide to use this answer, otherwise performance may suffer.
I've published the code here in case anyone wants to add anything
If you are running behind the any firewall(if firewall blocking gem installation). just try following command it works.
gem install --http-proxy http://username:pwd@server:port gem