I just add small detail:
new FileWriter("outfilename", true)
2.nd parameter (true) is a feature (or, interface) called appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html). It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content
In other words, you can add some content to your gzipped file, or some http process
A NET/CLI version using System::String
System::String^ GetFileExtension(System::String^ FileName)
{
int Ext=FileName->LastIndexOf('.');
if( Ext != -1 )
return FileName->Substring(Ext+1);
return "";
}
You can also just use the pipeline with the AddScript Method:
string cmdArg = ".\script.ps1 -foo bar"
Collection<PSObject> psresults;
using (Pipeline pipeline = _runspace.CreatePipeline())
{
pipeline.Commands.AddScript(cmdArg);
pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
psresults = pipeline.Invoke();
}
return psresults;
It will take a string, and whatever parameters you pass it.
Make sure that you have added /path/to/sdk/platform-tools to your path variable.
When you run react-native run-android, it runs adb reverse tcp:< device-port > tcp:< local-port > command to forward the request from your device to the server running locally on your computer. You will see something like this if adb is not found.
/bin/sh: 1: adb: not found
Starting the app (.../platform-tools/adb shell am start -n
com.first_app/com.first_app.MainActivity...
Starting: Intent { cmp=com.first_app/.MainActivity }
$sXML = download_page('http://alanstorm.com/atom');
// Comment This
// $oXML = new SimpleXMLElement($sXML);
// foreach($oXML->entry as $oEntry){
// echo $oEntry->title . "\n";
// }
// Use json encode
$xml = simplexml_load_string($sXML);
$json = json_encode($xml);
$arr = json_decode($json,true);
print_r($arr);
Yes, there does seem to be 3rd libraries (none in Java Math). Two that have come up are:
http://www.iro.umontreal.ca/~simardr/ssj/indexe.html
but, it is actually not that difficult to write your own methods to calculate mean, median, mode and range.
MEAN
public static double mean(double[] m) {
double sum = 0;
for (int i = 0; i < m.length; i++) {
sum += m[i];
}
return sum / m.length;
}
MEDIAN
// the array double[] m MUST BE SORTED
public static double median(double[] m) {
int middle = m.length/2;
if (m.length%2 == 1) {
return m[middle];
} else {
return (m[middle-1] + m[middle]) / 2.0;
}
}
MODE
public static int mode(int a[]) {
int maxValue, maxCount;
for (int i = 0; i < a.length; ++i) {
int count = 0;
for (int j = 0; j < a.length; ++j) {
if (a[j] == a[i]) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = a[i];
}
}
return maxValue;
}
UPDATE
As has been pointed out by Neelesh Salpe, the above does not cater for multi-modal collections. We can fix this quite easily:
public static List<Integer> mode(final int[] numbers) {
final List<Integer> modes = new ArrayList<Integer>();
final Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();
int max = -1;
for (final int n : numbers) {
int count = 0;
if (countMap.containsKey(n)) {
count = countMap.get(n) + 1;
} else {
count = 1;
}
countMap.put(n, count);
if (count > max) {
max = count;
}
}
for (final Map.Entry<Integer, Integer> tuple : countMap.entrySet()) {
if (tuple.getValue() == max) {
modes.add(tuple.getKey());
}
}
return modes;
}
ADDITION
If you are using Java 8 or higher, you can also determine the modes like this:
public static List<Integer> getModes(final List<Integer> numbers) {
final Map<Integer, Long> countFrequencies = numbers.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
final long maxFrequency = countFrequencies.values().stream()
.mapToLong(count -> count)
.max().orElse(-1);
return countFrequencies.entrySet().stream()
.filter(tuple -> tuple.getValue() == maxFrequency)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
I'm using the same approach, I suggest to write the singleton a little better:
public static MyApp getInstance() {
if (instance == null) {
synchronized (MyApp.class) {
if (instance == null) {
instance = new MyApp ();
}
}
}
return instance;
}
but I'm not using everywhere, I use getContext()
and getApplicationContext()
where I can do it!
Rob Heiser suggested checking out your java version by using 'java -version'.
That will identify the Java version that will be commonly found and used. Doing dev work, you can often have more than one version installed (I currently have 2 JREs - 6 and 7 - and may soon have 8).
http://www.coderanch.com/t/453224/java/java/java-version-work-setting-path
java -version will look for java.exe in the System32 directory in Windows. That's where a JRE will install it.
I'm assuming that IE either simply looks for java and that automatically starts checking in System32 or it'll use the path and hit whichever java.exe comes first in your path (if you tamper with the path to point to another JRE).
Also from what SLaks said, I would disagree with one thing. There is likely slightly better performance out of 64-it IE in 64-bit environments. So there is some reason for using it.
I agree with Erroid, you must add PHP directory into PATH environment.
PATH=%PATH%;<Your_PHP_Path>
Example
PATH=%PATH%;C:\php
It worked for me. Thank you.
If your project uses docker-compose, here is an approach for backing up and restoring your volumes.
Basically you add db-backup
and db-restore
services to your docker-compose.yml file, and adapt it for the name of your volume. My volume is named dbdata
in this example.
version: "3"
services:
db:
image: percona:5.7
volumes:
- dbdata:/var/lib/mysql
db-backup:
image: alpine
tty: false
environment:
- TARGET=dbdata
volumes:
- ./backup:/backup
- dbdata:/volume
command: sh -c "tar -cjf /backup/$${TARGET}.tar.bz2 -C /volume ./"
db-restore:
image: alpine
environment:
- SOURCE=dbdata
volumes:
- ./backup:/backup
- dbdata:/volume
command: sh -c "rm -rf /volume/* /volume/..?* /volume/.[!.]* ; tar -C /volume/ -xjf /backup/$${SOURCE}.tar.bz2"
For data consistency, stop your db container before backing up or restoring
docker-compose stop db
To back up to the default destination (backup/dbdata.tar.bz2
):
docker-compose run --rm db-backup
Or, if you want to specify an alternate target name, do:
docker-compose run --rm -e TARGET=mybackup db-backup
To restore from backup/dbdata.tar.bz2
, do:
docker-compose run --rm db-restore
Or restore from a specific file using:
docker-compose run --rm -e SOURCE=mybackup db-restore
I adapted commands from https://loomchild.net/2017/03/26/backup-restore-docker-named-volumes/ to create this approach.
Just like @Dampes8N said:
$result = mysql_query($sql,$conecction);
$fp = fopen('file.csv', 'w');
while($row = mysql_fetch_assoc($result)){
fputcsv($fp, $row);
}
fclose($fp);
Hope this helps.
Put data by intent:
Intent intent = new Intent(mContext, HomeWorkReportActivity.class);
intent.putExtra("subjectName", "Maths");
intent.putExtra("instituteId", 22);
mContext.startActivity(intent);
Get data by intent:
String subName = getIntent().getStringExtra("subjectName");
int insId = getIntent().getIntExtra("instituteId", 0);
If we use an integer value for the intent, we must set the second parameter to 0 in getIntent().getIntExtra("instituteId", 0)
. Otherwise, we do not use 0, and Android gives me an error.
Loop through all files ending with: .img
, .bin
, .txt
suffix, and print the file name:
for i in *.img *.bin *.txt;
do
echo "$i"
done
Or in a recursive manner (find also in all subdirectories):
for i in `find . -type f -name "*.img" -o -name "*.bin" -o -name "*.txt"`;
do
echo "$i"
done
All you have to do is use the value attribute of input tags:
<input type="text" value="Your Value" />
Or, in the case of a textarea:
<textarea>Your Value</textarea>
I'm not cool enough for comments. I fixed the plunker from the accepted answer to work for rc2. Nothing fancy, links to the CDN were just broken is all.
'@angular/core': {
main: 'bundles/core.umd.js',
defaultExtension: 'js'
},
'@angular/compiler': {
main: 'bundles/compiler.umd.js',
defaultExtension: 'js'
},
'@angular/common': {
main: 'bundles/common.umd.js',
defaultExtension: 'js'
},
'@angular/platform-browser-dynamic': {
main: 'bundles/platform-browser-dynamic.umd.js',
defaultExtension: 'js'
},
'@angular/platform-browser': {
main: 'bundles/platform-browser.umd.js',
defaultExtension: 'js'
},
we can change angular CLI favicon icon. we have to put icon file in "assets" folder and give that path in index.html.
<link rel="icon" type="image/x-icon" href="./assets/images/favicon.png">
It's work for me.
The 'r' is for reading, 'w' for writing and 'a' is for appending.
The 't' represents text mode as apposed to binary mode.
Several times here on SO I've seen people using rt and wt modes for reading and writing files.
Edit: Are you sure you saw rt and not rb?
These functions generally wrap the fopen function which is described here:
http://www.cplusplus.com/reference/cstdio/fopen/
As you can see it mentions the use of b to open the file in binary mode.
The document link you provided also makes reference to this b mode:
Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.
Tryprint
Example:
print "Hello World!"
print
print "Hi!"
Hope this works!:)
USE COUNT_STAR
LOGS= LOAD 'log';
LOGS_GROUP= GROUP LOGS ALL;
LOG_COUNT = FOREACH LOGS_GROUP GENERATE COUNT_STAR(LOGS);
Here's a complete working example based on your testing. Compare it to what you have currently to figure out where you are going wrong.
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(1000).fadeOut();
});
</script>
</head>
<body>
<div id=deletesuccess > hiiiiiiiiiii </div>
</body>
</html>
mvn install primary jobs are to 1)Download The Dependencies and 2)Build The Project
while job 1 is nowadays taken care by IDs like intellij (they download for any dependency at POM)
mvn install is majorly now used for job 2.
In VS2013 you can click in the solution explorer for this functionality.
The shortcut is:
ctrl + ;
To search only the names of files, and not the contents (especially in C#), uncheck these options:
You can use overflow:auto;
You can also control the x or y axis individually with the overflow-x
and overflow-y
properties.
Example:
.content {overflow:auto;}
.content {overflow-y:auto;}
.content {overflow-x:auto;}
Use the end() function.
$array = [1,2,3,4,5];
$last = end($array); // 5
if you want the algebric form and still use round for it it's hard to get simpler than:
interval = 5
n = 4
print(round(n/interval))*interval
Figured out my own problem. The solution ended up being based in interpolators.
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator()); //add this
fadeIn.setDuration(1000);
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator()); //and this
fadeOut.setStartOffset(1000);
fadeOut.setDuration(1000);
AnimationSet animation = new AnimationSet(false); //change to false
animation.addAnimation(fadeIn);
animation.addAnimation(fadeOut);
this.setAnimation(animation);
val fadeIn = AlphaAnimation(0f, 1f)
fadeIn.interpolator = DecelerateInterpolator() //add this
fadeIn.duration = 1000
val fadeOut = AlphaAnimation(1f, 0f)
fadeOut.interpolator = AccelerateInterpolator() //and this
fadeOut.startOffset = 1000
fadeOut.duration = 1000
val animation = AnimationSet(false) //change to false
animation.addAnimation(fadeIn)
animation.addAnimation(fadeOut)
this.setAnimation(animation)
As the question specifies Linux, my favourite technique for discovering the IP-addresses of a machine is to use netlink. By creating a netlink socket of the protocol NETLINK_ROUTE, and sending an RTM_GETADDR, your application will received a message(s) containing all available IP addresses. An example is provided here.
In order to simply parts of the message handling, libmnl is convenient. If you are curios in figuring out more about the different options of NETLINK_ROUTE (and how they are parsed), the best source is the source code of iproute2 (especially the monitor application) as well as the receive functions in the kernel. The man page of rtnetlink also contains useful information.
I like putting the inputs inside the labels (added bonus: now you don't need the for
attribute on the label), and put vertical-align: middle
on the input.
label > input[type=radio] {_x000D_
vertical-align: middle;_x000D_
margin-top: -2px;_x000D_
}_x000D_
_x000D_
#d2 { _x000D_
font-size: 30px;_x000D_
}
_x000D_
<div>_x000D_
<label><input type="radio" name="radio" value="1">Good</label>_x000D_
<label><input type="radio" name="radio" value="2">Excellent</label>_x000D_
<div>_x000D_
<br>_x000D_
<div id="d2">_x000D_
<label><input type="radio" name="radio2" value="1">Good</label>_x000D_
<label><input type="radio" name="radio2" value="2">Excellent</label>_x000D_
<div>
_x000D_
(The -2px margin-top
is a matter of taste.)
Another option I really like is using a table. (Hold your pitch forks! It's really nice!) It does mean you need to add the for
attribute to all your labels and id
s to your inputs. I'd recommended this option for labels with long text content, over multiple lines.
<table><tr><td>_x000D_
<input id="radioOption" name="radioOption" type="radio" />_x000D_
</td><td>_x000D_
<label for="radioOption"> _x000D_
Really good option_x000D_
</label>_x000D_
</td></tr></table>
_x000D_
But always look out in the console / log for messages. If you see a notification that your query could not be converted to SQL and will be evaluated locally then you may need to rewrite it.
Entity Framework 7 (now renamed to Entity Framework Core 1.0 / 2.0) does not yet support GroupBy()
for translation to GROUP BY
in generated SQL (even in the final 1.0 release it won't). Any grouping logic will run on the client side, which could cause a lot of data to be loaded.
Eventually code written like this will automagically start using GROUP BY, but for now you need to be very cautious if loading your whole un-grouped dataset into memory will cause performance issues.
For scenarios where this is a deal-breaker you will have to write the SQL by hand and execute it through EF.
If in doubt fire up Sql Profiler and see what is generated - which you should probably be doing anyway.
https://blogs.msdn.microsoft.com/dotnet/2016/05/16/announcing-entity-framework-core-rc2
While you have a return value in checkform, it isn't being used anywhere - try using onclick="return checkform()"
instead.
You may want to considering replacing this method with onsubmit="return checkform()"
in the form tag instead, though both will work for clicking the button.
I find that the accepted answer here is overly complicated for most use cases. This code does the job well (using jQuery) and differentiates between fully visible and partially visible elements:
var element = $("#element");
var topOfElement = element.offset().top;
var bottomOfElement = element.offset().top + element.outerHeight(true);
var $window = $(window);
$window.bind('scroll', function() {
var scrollTopPosition = $window.scrollTop()+$window.height();
var windowScrollTop = $window.scrollTop()
if (windowScrollTop > topOfElement && windowScrollTop < bottomOfElement) {
// Element is partially visible (above viewable area)
console.log("Element is partially visible (above viewable area)");
} else if (windowScrollTop > bottomOfElement && windowScrollTop > topOfElement) {
// Element is hidden (above viewable area)
console.log("Element is hidden (above viewable area)");
} else if (scrollTopPosition < topOfElement && scrollTopPosition < bottomOfElement) {
// Element is hidden (below viewable area)
console.log("Element is hidden (below viewable area)");
} else if (scrollTopPosition < bottomOfElement && scrollTopPosition > topOfElement) {
// Element is partially visible (below viewable area)
console.log("Element is partially visible (below viewable area)");
} else {
// Element is completely visible
console.log("Element is completely visible");
}
});
The variable can be declared in the .js
file and simply referenced in the HTML file.
My version of helpers.js
:
var myFunctionWasCalled = false;
function doFoo()
{
if (!myFunctionWasCalled) {
alert("doFoo called for the very first time!");
myFunctionWasCalled = true;
}
else {
alert("doFoo called again");
}
}
And a page to test it:
<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="helpers.js"></script>
</head>
<body>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
<script type="text/javascript">doFoo();</script>
<p>Some stuff in between</p>
<script type="text/javascript">doFoo();</script>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
</body>
</html>
You'll see the test alert()
will display two different things, and the value written to the page will be different the second time.
When a new view is loaded in AngularJS
, Google Analytics does not count it as a new page load. Fortunately there is a way to manually tell GA to log a url as a new pageview.
_gaq.push(['_trackPageview', '<url>']);
would do the job, but how to bind that with AngularJS?
Here is a service which you could use:
(function(angular) {
angular.module('analytics', ['ng']).service('analytics', [
'$rootScope', '$window', '$location', function($rootScope, $window, $location) {
var track = function() {
$window._gaq.push(['_trackPageview', $location.path()]);
};
$rootScope.$on('$viewContentLoaded', track);
}
]);
}(window.angular));
When you define your angular module, include the analytics module like so:
angular.module('myappname', ['analytics']);
UPDATE:
You should use the new Universal Google Analytics tracking code with:
$window.ga('send', 'pageview', {page: $location.url()});
Great way of implementing Camera session in Swift 5, iOS 13
https://github.com/egzonpllana/CameraSession
Camera Session is an iOS app that tries to make the simplest possible way of implementation of AVCaptureSession.
Through the app you can find these camera session implemented:
The custom camera features like torch and rotate camera options.
[root@piwik-dev tmp]# mail -v root@localhost
Subject: Test
Hello world
Cc: <Ctrl+D>
root@localhost... Connecting to [127.0.0.1] via relay...
220 piwik-dev.example.com ESMTP Sendmail 8.13.8/8.13.8; Thu, 23 Aug 2012 10:49:40 -0400
>>> EHLO piwik-dev.example.com
250-piwik-dev.example.com Hello localhost.localdomain [127.0.0.1], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-DELIVERBY
250 HELP
>>> MAIL From:<[email protected]> SIZE=46
250 2.1.0 <[email protected]>... Sender ok
>>> RCPT To:<[email protected]>
>>> DATA
250 2.1.5 <[email protected]>... Recipient ok
354 Enter mail, end with "." on a line by itself
>>> .
250 2.0.0 q7NEneju002633 Message accepted for delivery
root@localhost... Sent (q7NEneju002633 Message accepted for delivery)
Closing connection to [127.0.0.1]
>>> QUIT
221 2.0.0 piwik-dev.example.com closing connection
What you need to do is configure Fiddler to work as a "reverse proxy"
There are instructions on 2 different ways you can do this on Fiddler's website. Here is a copy of the steps:
Step #0
Before either of the following options will work, you must enable other computers to connect to Fiddler. To do so, click Tools > Fiddler Options > Connections and tick the "Allow remote computers to connect" checkbox. Then close Fiddler.
Option #1: Configure Fiddler as a Reverse-Proxy
Fiddler can be configured so that any traffic sent to http://127.0.0.1:8888
is automatically sent to a different port on the same machine. To set this configuration:
http://127.0.0.1:8888
Option #2: Write a FiddlerScript rule
Alternatively, you can write a rule that does the same thing.
Say you're running a website on port 80 of a machine named WEBSERVER. You're connecting to the website using Internet Explorer Mobile Edition on a Windows SmartPhone device for which you cannot configure the web proxy. You want to capture the traffic from the phone and the server's response.
http://webserver:8888
Requests from the SmartPhone will appear in Fiddler. The requests are forwarded from port 8888 to port 80 where the webserver is running. The responses are sent back through Fiddler to the SmartPhone, which has no idea that the content originally came from port 80.
Use a Macro.
Macro>Start Recording
Use the keyboard to make your changes in a repeatable manner e.g.
home>type "able">end>down arrow>home
Then go back to the menu and click stop recording then run a macro multiple times.
That should do it and no regex based complications!
The element has both an attribute and a property named checked
. The property determines the current state.
The attribute is a string, and the property is a boolean. When the element is created from the HTML code, the attribute is set from the markup, and the property is set depending on the value of the attribute.
If there is no value for the attribute in the markup, the attribute becomes null
, but the property is always either true
or false
, so it becomes false
.
When you set the property, you should use a boolean value:
document.getElementById('myRadio').checked = true;
If you set the attribute, you use a string:
document.getElementById('myRadio').setAttribute('checked', 'checked');
Note that setting the attribute also changes the property, but setting the property doesn't change the attribute.
Note also that whatever value you set the attribute to, the property becomes true
. Even if you use an empty string or null
, setting the attribute means that it's checked. Use removeAttribute
to uncheck the element using the attribute:
document.getElementById('myRadio').removeAttribute('checked');
here is a version that can split on a pattern using patindex, a simple adaptation of the post above. I had a case where I needed to split a string that contained multiple separator chars.
alter FUNCTION dbo.splitstring ( @stringToSplit VARCHAR(1000), @splitPattern varchar(10) )
RETURNS
@returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE @name NVARCHAR(255)
DECLARE @pos INT
WHILE PATINDEX(@splitPattern, @stringToSplit) > 0
BEGIN
SELECT @pos = PATINDEX(@splitPattern, @stringToSplit)
SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)
INSERT INTO @returnList
SELECT @name
SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
END
INSERT INTO @returnList
SELECT @stringToSplit
RETURN
END
select * from dbo.splitstring('stringa/stringb/x,y,z','%[/,]%');
result looks like this
stringa stringb x y z
I think a nice solution is with the function filter of pandas and regex (match everything except "b"):
df.filter(regex="^(?!b$)")
The Scanner class is bases on logic implemented in String next(Pattern)
method. The additional API method like nextDouble()
or nextFloat()
. Provide the pattern inside.
Then class description says:
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
From the description it can be sad that someone has forgot about char as it is a primitive type for sure.
But the concept of class is to find patterns, a char has no pattern is just next character. And this logic IMHO caused that nextChar has not been implemented.
If you need to read a filed char by char you can used more efficient class.
You can easily draw simple svg
s onto a canvas by:
Note: The only drawback of the method is that it cannot draw images embedded in the svg
. (see demo)
(Note that the embedded image is only visible in the svg
)
var svg = document.querySelector('svg');_x000D_
var img = document.querySelector('img');_x000D_
var canvas = document.querySelector('canvas');_x000D_
_x000D_
// get svg data_x000D_
var xml = new XMLSerializer().serializeToString(svg);_x000D_
_x000D_
// make it base64_x000D_
var svg64 = btoa(xml);_x000D_
var b64Start = 'data:image/svg+xml;base64,';_x000D_
_x000D_
// prepend a "header"_x000D_
var image64 = b64Start + svg64;_x000D_
_x000D_
// set it as the source of the img element_x000D_
img.src = image64;_x000D_
_x000D_
// draw the image onto the canvas_x000D_
canvas.getContext('2d').drawImage(img, 0, 0);
_x000D_
svg, img, canvas {_x000D_
display: block;_x000D_
}
_x000D_
SVG_x000D_
_x000D_
<svg height="40">_x000D_
<rect width="40" height="40" style="fill:rgb(255,0,255);" />_x000D_
<image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>_x000D_
</svg>_x000D_
<hr/><br/>_x000D_
_x000D_
IMAGE_x000D_
<img/>_x000D_
<hr/><br/>_x000D_
_x000D_
CANVAS_x000D_
<canvas></canvas>_x000D_
<hr/><br/>
_x000D_
For people coming from Google, this question is not about data attributes - OP added a non-standard attribute to their HTML object, and wondered how to set it.
However, you should not add custom attributes to your properties - you should use data attributes - e.g. OP should have used data-icon
, data-url
, data-target
, etc.
In any event, it turns out that the way you set these attributes via JavaScript is the same for both cases. Use:
ele.setAttribute(attributeName, value);
to change the given attribute attributeName
to value
for the DOM element ele
.
For example:
document.getElementById("someElement").setAttribute("data-id", 2);
Note that you can also use .dataset
to set the values of data attributes, but as @racemic points out, it is 62% slower (at least in Chrome on macOS at the time of writing). So I would recommend using the setAttribute
method instead.
Below is a quick example of how to do this (which best explained the matter to me) that I essentially found at this website. That website link also explains WSDL, which is important for working with SOAP services.
However, I don't think the API address they were using in the example below still works, so just switch in one of your own choosing.
$wsdl = 'http://terraservice.net/TerraService.asmx?WSDL';
$trace = true;
$exceptions = false;
$xml_array['placeName'] = 'Pomona';
$xml_array['MaxItems'] = 3;
$xml_array['imagePresence'] = true;
$client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions));
$response = $client->GetPlaceList($xml_array);
var_dump($response);
Going to answer this myself (correct me if I'm wrong):
It is not possible to iterate over a group of rows (like an array) in Excel without VBA installed / macros enabled.
The reason you're having the problem is that it only tries to match "naked" addresses. things like "www.google.com" or "http://www.google.com".
Running your text through Html.fromHtml() should do the trick. You have to do it programatically, but it works.
If you have something like this:
var json = [ {a:b, c:d}, {e:f, g:h, ...}, {..}, ... ]
then, you can do:
alert(json.length)
In shell you assign to a variable without the dollar-sign:
TEST=`pwd`
echo $TEST
that's better (and can be nested) but is not as portable as the backtics:
TEST=$(pwd)
echo $TEST
Always remember: the dollar-sign is only used when reading a variable.
If you make the image a background-image of a div in CSS, when that div is set to "display: none", the image will not load. When CSS is disabled, it still will not load, because, well, CSS is disabled.
So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:
r" |(?<![0-9])[.,](?![0-9])"
You could use strcmp()
:
/* strcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char szKey[] = "apple";
char szInput[80];
do {
printf ("Guess my favourite fruit? ");
gets (szInput);
} while (strcmp (szKey,szInput) != 0);
puts ("Correct answer!");
return 0;
}
I remember asking this question about seven years ago when I was rather new to programming.
I was very careful when I asked and surprisingly I didn't get as much criticism as you are getting here. They did however point me in the direction of the "Dragon Book" which is in my opinion, a really great book that explains everything you need to know to write a compiler (you will of course have to master a language or two. The more languages you know, the merrier.).
And yes, many people say reading that book is crazy and you won't learn anything from it, but I disagree completely with that.
Many people also say that writing compilers is stupid and pointless. Well, there are a number of reasons why compiler development are useful:
I didn't write my own compiler right away, but after asking I knew where to start. And now, after learning many different languages and reading the Dragon Book, writing isn't that much of a problem. (I'm also studying computer engineering atm, but most of what I know about programming is self taught.)
In conclusion, The Dragon Book is a great "tutorial". But spend some time mastering a language or two before attempting to write a compiler. Don't expect to be a compiler guru within the next decade or so though.
The book is also good if you want to learn how to write parsers/interpreters.
Here's how you do it.
First, decorate your list this way:
<div class="p">
<div class="text-bullet-centered">⁕</div>
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
</div>
<div class="p">
<div class="text-bullet-centered">⁕</div>
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
</div>
Add this CSS:
.p {
position: relative;
margin: 20px;
margin-left: 50px;
}
.text-bullet-centered {
position: absolute;
left: -40px;
top: 50%;
transform: translate(0%,-50%);
font-weight: bold;
}
And voila, it works. Resize a window, to see that it indeed works.
As a bonus, you can easily change font and color of bullets, which is very hard to do with normal lists.
.p {_x000D_
position: relative;_x000D_
margin: 20px;_x000D_
margin-left: 50px;_x000D_
}_x000D_
_x000D_
.text-bullet-centered {_x000D_
position: absolute;_x000D_
left: -40px;_x000D_
top: 50%;_x000D_
transform: translate(0%, -50%);_x000D_
font-weight: bold;_x000D_
}
_x000D_
<div class="p">_x000D_
<div class="text-bullet-centered">⁕</div>_x000D_
text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text_x000D_
text text text text text text text text text text text text text_x000D_
</div>_x000D_
<div class="p">_x000D_
<div class="text-bullet-centered">⁕</div>_x000D_
text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text_x000D_
text text text text text text text text text text text text text_x000D_
</div>
_x000D_
The normal way of doing it is:
You don't need a JsonResult or jQuery for this.
You can use js and add a class in html to maintain the standard of conditional comments:
var ua = navigator.userAgent,
doc = document.documentElement;
if ((ua.match(/MSIE 10.0/i))) {
doc.className = doc.className + " ie10";
} else if((ua.match(/rv:11.0/i))){
doc.className = doc.className + " ie11";
}
Or use a lib like bowser:
Or modernizr for feature detection:
Although you can access "inherited" static members through the inherited classes name, static members are not really inherited. This is in part why they can't be virtual or abstract and can't be overridden. In your example, if you declared a Base.Method(), the compiler will map a call to Inherited.Method() back to Base.Method() anyway. You might as well call Base.Method() explicitly. You can write a small test and see the result with Reflector.
So... if you can't inherit static members, and if static classes can contain only static members, what good would inheriting a static class do?
You have a JSON Lines format text file. You need to parse your file line by line:
import json
data = []
with open('file') as f:
for line in f:
data.append(json.loads(line))
Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.
Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.
If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.
Windows containers are not running on Linux and also You can't run Linux containers on Windows directly.
To me it happened in DogController
that autowired DogService
that autowired DogRepository
. Dog
class used to have field name
but I changed it to coolName
, but didn't change methods in DogRepository
: Dog findDogByName(String name)
. I change that method to Dog findDogByCoolName(String name)
and now it works.
For me, I had an issue until I removed the padding. It looks like there is a bug on certain devices that doesn't alter the size of the view to accommodate the padding, and instead compresses the contents.
Remove padding
, use layout_margin
instead.
You can use each
for this:
$('#productList li').each(function(i, li) {
var $product = $(li);
// your code goes here
});
That being said - are you sure you want to be updating the values to be +1 each time? Couldn't you just find the count and then set the values based on that?
Your standard project setup will have a project structure something like:
src/main/java
src/main/resources
You place log4j.properties inside the resources folder, you can create the resources folder if one does not exist
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
Your problem may be that you are dealing with DATETIME data, not just dates. If a row has a mydate that is '2008-11-25 09:30 AM', then your WHERE mydate<='2008-11-25'; is not going to return that row. '2008-11-25' has an implied time of 00:00 (midnight), so even though the date part is the same, they are not equal, and mydate is larger.
If you use < '2008-11-26' instead of <= '2008-11-25', that would work. The Datediff method works because it compares just the date portion, and ignores the times.
To get a meaningful/useful view of the two tables, you normally need to determine an identifying field from each table that can then be used in the ON clause in a JOIN.
THen in your view:
SELECT T1.*, T2.* FROM T1 JOIN T2 ON T1.IDFIELD1 = T2.IDFIELD2
You mention no fields are "common", but although the identifying fields may not have the same name or even be the same data type, you could use the convert / cast functions to join them in some way.
Commenting EDIT: As of Java 8, static methods are now allowed in interfaces.
It is right, static methods since Java 8 are allowed in interfaces, but your example still won't work. You cannot just define a static method: you have to implement it or you will obtain a compilation error.
Yes. Only comments and the end tag for the html element are allowed after the end tag for the body.
Browsers may perform error recovery, but you should never depend on that.
This should work for Firefox by using AutoAuth plugin:
FirefoxProfile firefoxProfile = new ProfilesIni().getProfile("default");
File ffPluginAutoAuth = new File("D:\\autoauth-2.1-fx+fn.xpi");
firefoxProfile.addExtension(ffPluginAutoAuth);
driver = new FirefoxDriver(firefoxProfile);
SELECT * FROM table WHERE field1 NOT LIKE '%$x%';
(Make sure you escape $x properly beforehand to avoid SQL injection)
Edit: NOT IN
does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%'
can use an index. LIKE '%xxx'
or LIKE '%xxx%'
can't.
I modified one of the answers above to give me a bit more information. This spared me a second query later on. It was something like this:
Get-ChildItem `
-Path "C:\data\path" -Filter "Example*.dat" -recurse | `
Select-String -pattern "dummy" | `
Select-Object -Property Path,LineNumber,Line | `
Export-CSV "C:\ResultFile.csv"
I can specify the path and file wildcards with this structures, and it saves the filename, line number and relevant line to an output file.
super(...)
), which basically does the sameOQ asked about static string
vs const
. Both have different use cases (although both are treated as static).
Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const
fields because you might have base and subclass in different assemblies and private fields are inherited.
Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).
If you meant static readonly
vs const
, then I'd recommend static readonly
for almost all cases because it is more future proof.
I found the following to be a working solution::
npm install aws-sdk
Once you've installed the aws-sdk , use the following code replacing values with your where needed.
var AWS = require('aws-sdk');
var fs = require('fs');
var s3 = new AWS.S3();
// Bucket names must be unique across all S3 users
var myBucket = 'njera';
var myKey = 'jpeg';
//for text file
//fs.readFile('demo.txt', function (err, data) {
//for Video file
//fs.readFile('demo.avi', function (err, data) {
//for image file
fs.readFile('demo.jpg', function (err, data) {
if (err) { throw err; }
params = {Bucket: myBucket, Key: myKey, Body: data };
s3.putObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Successfully uploaded data to myBucket/myKey");
}
});
});
I found the complete tutorial on the subject here in case you're looking for references ::
from this example here, you can see the the conversions both ways:
NSString *str=@"5678901234567890";
long long verylong;
NSRange range;
range.length = 15;
range.location = 0;
[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];
NSLog(@"long long value %lld",verylong);
Modernizr is also a great option for giving IE HTML5 rendering capabilities.
Just set an onload function on the body:
<body onload="init()">
Then do something like this in javascript:
function init() {
var someimage = 'changableBackgroudImage';
document.body.style.background = 'url(img/'+someimage+'.png) no-repeat center center'
}
You can change the 'someimage' variable to whatever you want depending on some conditions, such as the time of day or something, and that image will be set as the background image.
You'll probably want the following.
List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList.RemoveAll(item => item == null);
Goto Package properties->Configurations->Enable Package Configurations->Add->xml configuration file->Specify dtsconfig file->click next->In OLEDB Properties tick the connection string->connection string value will be displayed->click next and finish package is hence configured.
You can add Environment variable also in this process
If there are spaces in the phone2 field from inadvertant data entry, you can ignore those records with the IFNULL and TRIM functions:
SELECT phone, phone2
FROM jewishyellow.users
WHERE phone LIKE '813%'
AND TRIM(IFNULL(phone2,'')) <> '';
This works well for specific articles where the text is all wrapped in <p>
tags. Since the web is an ugly place, it's not always the case.
Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span>
or a <div>
, or an <li>
).
To find all text nodes in the DOM, you can use soup.find_all(text=True)
.
This is going to return some undesired text, like the contents of <script>
and <style>
tags. You'll need to filter out the text contents of elements you don't want.
blacklist = [
'style',
'script',
# other elements,
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]
If you are working with a known set of tags, you can tag the opposite approach:
whitelist = [
'p'
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]
This works:
assertThat(list,IsEmptyCollection.empty())
The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:
document.onkeydown = TabExample;
function TabExample(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var tabKey = 9;
if(evt.keyCode == tabKey) {
// do work
}
}
If you want convert Keys:
List<string> listNumber = dicNumber.Keys.ToList();
else if you want convert Values:
List<string> listNumber = dicNumber.Values.ToList();
Actually, contrary to the other answers, I believe that OP's solution is the one that is most elegant.
Here's what you gain by using an external .bat
wrapper:
main()
?system("pause")
here.enter
keypress (unless you do things mentioned in the footnote).cmd.exe
on Windows platform), they don't want to wait, since they'll see the output anyway. With the .bat
wrapper technique, they can decide whether to run the .bat
(or .sh
) wrapper, or run the executable directly.Focusing on the last two points - with any other technique, I'd expect the program to offer at least --no-wait
switch so that I, as the user, can use the application with all sort of operations such as piping the output, chaining it with other programs etc. These are part of normal CLI workflow, and adding waiting at the end when you're already inside a terminal just gets in the way and destroys user experience.
For these reasons, IMO .bat
solution is the nicest here.
Do it onSubmit()
:
$('form#id').submit(function(){
$(this).find(':input[type=submit]').prop('disabled', true);
});
What is happening is you're disabling the button altogether before it actually triggers the submit event.
You should probably also think about naming your elements with IDs or CLASSes, so you don't select all inputs of submit type on the page.
Demonstration: http://jsfiddle.net/userdude/2hgnZ/
(Note, I use preventDefault()
and return false
so the form doesn't actual submit in the example; leave this off in your use.)
visibility:hidden will hide the element but element is their with DOM. And in case of display:none it'll remove the element from the DOM.
So you have option for element to either hide or unhide. But once you delete it ( I mean display none) it has not clear opposite value. display have several values like display:block,display:inline, display:inline-block and many other. you can check it out from W3C.
This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here
You should convert the stream into byte array and then you can read file content
Please refer following link
http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx]
Hope this helps
UPDATE :
The stream that you get from your HTTP call is read-only sequential (non-seekable) and the FileStream is read/write seekable. You will need first to read the entire stream from the HTTP call into a byte array, then create the FileStream from that array.
Taken from here
// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);
string result = System.Text.Encoding.UTF8.GetString(binData);
GCC comes with a compiler runtime library (libgcc) which it uses for (among other things) providing a low-level OS abstraction for multithreading related functionality in the languages it supports. The most relevant example is libstdc++'s C++11 <thread>
, <mutex>
, and <future>
, which do not have a complete implementation when GCC is built with its internal Win32 threading model. MinGW-w64 provides a winpthreads (a pthreads implementation on top of the Win32 multithreading API) which GCC can then link in to enable all the fancy features.
I must stress this option does not forbid you to write any code you want (it has absolutely NO influence on what API you can call in your code). It only reflects what GCC's runtime libraries (libgcc/libstdc++/...) use for their functionality. The caveat quoted by @James has nothing to do with GCC's internal threading model, but rather with Microsoft's CRT implementation.
To summarize:
posix
: enable C++11/C11 multithreading features. Makes libgcc depend on libwinpthreads, so that even if you don't directly call pthreads API, you'll be distributing the winpthreads DLL. There's nothing wrong with distributing one more DLL with your application.win32
: No C++11 multithreading features.Neither have influence on any user code calling Win32 APIs or pthreads APIs. You can always use both.
As with most style conventions, there are only two things that matter:
Those may seem to contradict, but they each have value for their own reasons.
In Solution Explorer Under Project Click on Dependencies->NuGet->Microsoft.NetCore.All-> Here list of all Microsoft .NetCore pakcages will appear. Search for Microsoft.EntityFrameworkCore(2.0.3) in bracket version can be seen Like this
You were very close, you can use this:
DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))
Please see this fiddle.
I tried to delete a column while using the package data.table
and got an unexpected result. I kind of think the following might be worth posting. Just a little cautionary note.
[ Edited by Matthew ... ]
DF = read.table(text = "
fruit state grade y1980 y1990 y2000
apples Ohio aa 500 100 55
apples Ohio bb 0 0 44
apples Ohio cc 700 0 33
apples Ohio dd 300 50 66
", sep = "", header = TRUE, stringsAsFactors = FALSE)
DF[ , !names(DF) %in% c("grade")] # all columns other than 'grade'
fruit state y1980 y1990 y2000
1 apples Ohio 500 100 55
2 apples Ohio 0 0 44
3 apples Ohio 700 0 33
4 apples Ohio 300 50 66
library('data.table')
DT = as.data.table(DF)
DT[ , !names(dat4) %in% c("grade")] # not expected !! not the same as DF !!
[1] TRUE TRUE FALSE TRUE TRUE TRUE
DT[ , !names(DT) %in% c("grade"), with=FALSE] # that's better
fruit state y1980 y1990 y2000
1: apples Ohio 500 100 55
2: apples Ohio 0 0 44
3: apples Ohio 700 0 33
4: apples Ohio 300 50 66
Basically, the syntax for data.table
is NOT exactly the same as data.frame
. There are in fact lots of differences, see FAQ 1.1 and FAQ 2.17. You have been warned!
I've tried all possible solutions offered but unluckly my vscode settings won't changed its linter path. So, I tride to explore vscode settings in settings > User Settings > python. Find Linting: Pylint Path and change it to "pylint_django". Don't forget to change the linter to "pylint_django" at settings > User Settings > python configuration from "pyLint" to "pylint_django".
You can simply use %
twice, that is "%%"
Example:
printf("You gave me 12.3 %% of profit");
Try this:
In the IIS Manager right click on Web sites, chose New, then Web site...
This way you can recreate the Default Web Site.
After these steps restart IIS: Right click on local computer, All Tasks, Restart IIS...
This is a working example.
HTML Form :
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
PHP Code :
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
If you just need to output the date in ISO8601 format including the trailing Z and you are on at least SQL Server 2012, then you may use FORMAT
:
SELECT FORMAT(GetUtcDate(),'yyyy-MM-ddTHH:mm:ssZ')
This will give you something like:
2016-02-18T21:34:14Z
Just as @Pxtl points out in a comment FORMAT may have performance implications, a cost that has to be considered compared to any flexibility it brings.
You only need to delete one folder it is throwing error for. Just go to your M2 repo and org/apache/maven/plugins/maven-compiler-plugins and delete the folder 2.3.2
I've found that using a validation method provides a lot of control over setting defaults. You can even set defaults (or fail validation) for updates. You even set a different default value for inserts vs updates if you really wanted to. Note that the default won't be set until #valid? is called.
class MyModel
validate :init_defaults
private
def init_defaults
if new_record?
self.some_int ||= 1
elsif some_int.nil?
errors.add(:some_int, "can't be blank on update")
end
end
end
Regarding defining an after_initialize method, there could be performance issues because after_initialize is also called by each object returned by :find : http://guides.rubyonrails.org/active_record_validations_callbacks.html#after_initialize-and-after_find
The difference is that when using --mirror
, all refs are copied as-is. This means everything: remote-tracking branches, notes, refs/originals/* (backups from filter-branch). The cloned repo has it all. It's also set up so that a remote update will re-fetch everything from the origin (overwriting the copied refs). The idea is really to mirror the repository, to have a total copy, so that you could for example host your central repo in multiple places, or back it up. Think of just straight-up copying the repo, except in a much more elegant git way.
The new documentation pretty much says all this:
--mirror
Set up a mirror of the source repository. This implies
--bare
. Compared to--bare
,--mirror
not only maps local branches of the source to local branches of the target, it maps all refs (including remote branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by agit remote update
in the target repository.
My original answer also noted the differences between a bare clone and a normal (non-bare) clone - the non-bare clone sets up remote tracking branches, only creating a local branch for HEAD
, while the bare clone copies the branches directly.
Suppose origin has a few branches (master (HEAD)
, next
, pu
, and maint
), some tags (v1
, v2
, v3
), some remote branches (devA/master
, devB/master
), and some other refs (refs/foo/bar
, refs/foo/baz
, which might be notes, stashes, other devs' namespaces, who knows).
git clone origin-url
(non-bare): You will get all of the tags copied, a local branch master (HEAD)
tracking a remote branch origin/master
, and remote branches origin/next
, origin/pu
, and origin/maint
. The tracking branches are set up so that if you do something like git fetch origin
, they'll be fetched as you expect. Any remote branches (in the cloned remote) and other refs are completely ignored.
git clone --bare origin-url
: You will get all of the tags copied, local branches master (HEAD)
, next
, pu
, and maint
, no remote tracking branches. That is, all branches are copied as is, and it's set up completely independent, with no expectation of fetching again. Any remote branches (in the cloned remote) and other refs are completely ignored.
git clone --mirror origin-url
: Every last one of those refs will be copied as-is. You'll get all the tags, local branches master (HEAD)
, next
, pu
, and maint
, remote branches devA/master
and devB/master
, other refs refs/foo/bar
and refs/foo/baz
. Everything is exactly as it was in the cloned remote. Remote tracking is set up so that if you run git remote update
all refs will be overwritten from origin, as if you'd just deleted the mirror and recloned it. As the docs originally said, it's a mirror. It's supposed to be a functionally identical copy, interchangeable with the original.
Since this is very common question I have prepared some screen shots from Visual Studio to make it easy to follow in 4 simple steps.
I made myself a custom jquery function:
<tr data-href="site.com/whatever">
$('tr[data-href]').on("click", function() {
document.location = $(this).data('href');
});
Easy and perfect for me. Hopefully it helps you.
(I know OP want CSS and HTML only, but consider jQuery)
Agreed with Matt Kantor using data attr. Edited answer above
This answer is not exactly what you want, but it might be useful in some cases. If you know the element has some dimensions when displayed, you can also use this:
var hasDisplayNone = (element.offsetHeight === 0 && element.offsetWidth === 0);
EDIT: Why this might be better than direct check of CSS display
property? Because you do not need to check all parent elements. If some parent element has display: none
, its children are hidden too but still has element.style.display !== 'none'
.
For me it was caused by a splash screen image that was too big (over 4000x2000). The problem disappeared after reducing its dimensions.
Use ng-disabled or a special CSS class with ng-class
<input data-ng-model="userInf.username"
class="span12 editEmail"
type="text"
placeholder="[email protected]"
pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}"
required
ng-disabled="{expression or condition}"
/>
You can also use ng-pattern
and I feel that will be a best practice. Similarly try to use ng-message
. Please look the ng-pattern attribute on the following html. The code snippet is partial but hope you understand it.
angular.module('myApp', ['ngMessages']);
angular.module("myApp.controllers",[]).controller("registerCtrl", function($scope, Client) {
$scope.ph_numbr = /^(\+?(\d{1}|\d{2}|\d{3})[- ]?)?\d{3}[- ]?\d{3}[- ]?\d{4}$/;
});
<form class="form-horizontal" role="form" method="post" name="registration" novalidate>
<div class="form-group" ng-class="{ 'has-error' : (registration.phone.$invalid || registration.phone.$pristine)}">
<label for="inputPhone" class="col-sm-3 control-label">Phone :</label>
<div class="col-sm-9">
<input type="number" class="form-control" ng-pattern="ph_numbr" id="inputPhone" name="phone" placeholder="Phone" ng-model="user.phone" ng-required="true">
<div class="help-block" ng-messages="registration.phone.$error">
<p ng-message="required">Phone number is required.</p>
<p ng-message="pattern">Phone number is invalid.</p>
</div>
</div>
</div>
</form>
Based on your application type/size/load/no. of users ..etc - u can keep following as your production properties
spring.datasource.tomcat.initial-size=50
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=300
spring.datasource.tomcat.max-idle=150
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true
You would use the command Mechanical snail listed. Notice the uppercase O. Full command line to use could be:
wget www.examplesite.com/textfile.txt --output-document=newfile.txt
or
wget www.examplesite.com/textfile.txt -O newfile.txt
Hope that helps.
You're missing a required space between the bracket and -e
:
#!/bin/bash
if [ -e x.txt ]
then
echo "ok"
else
echo "nok"
fi
I picked up the content using JavaScript and created a window that I could print in stead...
Here's what I do. I find the minimum first then after the minimum is found, it is removed from ArrayList.
ArrayList<Integer> a = new ArrayList<>();
a.add(3);
a.add(6);
a.add(2);
a.add(5);
while (a.size() > 0) {
int min = 1000;
for (int b:a) {
if (b < min)
min = b;
}
System.out.println("minimum: " + min);
System.out.println("index of min: " + a.indexOf((Integer) min));
a.remove((Integer) min);
}
You can use the LIKE operator to compare the content of a T-SQL string, e.g.
SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'.
The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".
The easiest solution I found was to simply put that in your fragment :
androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavController navController = Navigation.findNavController(getActivity(),
R.id.nav_host_fragment);
navController.navigate(R.id.action_position_to_destination);
}
});
Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.
This is not the best practice in .NET framework (4 & +) to check equality
String.Compare(x.Username, (string)drUser["Username"],
StringComparison.OrdinalIgnoreCase) == 0
Use the following instead
String.Equals(x.Username, (string)drUser["Username"],
StringComparison.OrdinalIgnoreCase)
- Use an overload of the String.Equals method to test whether two strings are equal.
- Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.
Setting the -fx-text-fill
works for me.
See below:
if (passed) {
resultInfo.setText("Passed!");
resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
resultInfo.setText("Failed!");
resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}
Beamer just delegates responsibility for managing layout of itemize
environments back to the base LaTeX packages, so there's nothing funky you need to do in Beamer itself to alter the apperaance / layout of your lists.
Since Beamer redefines itemize, item, etc., the fully proper way to manipulate things like indentation is to redefine the Beamer templates. I get the impression that you're not looking to go that far, but if that's not the case, let me know and I'll elaborate.
There are at least three ways of accomplishing your goal from within your document, without mussing about with Beamer templates.
itemize
In the following code snippet, you can change the value of \itemindent
from 0em
to whatever you please, including negative values. 0em
is the default item indentation.
The advantage of this method is that the list is styled normally. The disadvantage is that Beamer's redefinition of itemize
and \item
means that the number of paramters that can be manipulated to change the list layout is limited. It can be very hard to get the spacing right with multi-line items.
\begin{itemize}
\setlength{\itemindent}{0em}
\item This is a normally-indented item.
\end{itemize}
list
In the following code snippet, the second parameter to \list
is the bullet to use, and the third parameter is a list of layout parameters to change. The \leftmargin
parameter adjusts the indentation of the entire list item and all of its rows; \itemindent
alters the indentation of subsequent lines.
The advantage of this method is that you have all of the flexibility of lists in non-Beamer LaTeX. The disadvantage is that you have to setup the bullet style (and other visual elements) manually (or identify the right command for the template you're using). Note that if you leave the second argument empty, no bullet will be displayed and you'll save some horizontal space.
\begin{list}{$\square$}{\leftmargin=1em \itemindent=0em}
\item This item uses the margin and indentation provided above.
\end{list}
customlist
environmentThe shortcomings of the list
solution can be ameliorated by defining a new customlist
environment that basically redefines the itemize
environment from Beamer but also incorporates the \leftmargin
and \itemindent
(etc.) parameters. Put the following in your preamble:
\makeatletter
\newenvironment{customlist}[2]{
\ifnum\@itemdepth >2\relax\@toodeep\else
\advance\@itemdepth\@ne%
\beamer@computepref\@itemdepth%
\usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
\usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
\usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
\begin{list}
{
\usebeamertemplate{itemize \beameritemnestingprefix item}
}
{ \leftmargin=#1 \itemindent=#2
\def\makelabel##1{%
{%
\hss\llap{{%
\usebeamerfont*{itemize \beameritemnestingprefix item}%
\usebeamercolor[fg]{itemize \beameritemnestingprefix item}##1}}%
}%
}%
}
\fi
}
{
\end{list}
\usebeamertemplate{itemize/enumerate \beameritemnestingprefix body end}%
}
\makeatother
Now, to use an itemized list with custom indentation, you can use the following environment. The first argument is for \leftmargin
and the second is for \itemindent
. The default values are 2.5em and 0em respectively.
\begin{customlist}{2.5em}{0em}
\item Any normal item can go here.
\end{customlist}
A custom bullet style can be incorporated into the customlist
solution using the standard Beamer mechanism of \setbeamertemplate
. (See the answers to this question on the TeX Stack Exchange for more information.)
Alternatively, the bullet style can just be modified directly within the environment, by replacing \usebeamertemplate{itemize \beameritemnestingprefix item}
with whatever bullet style you'd like to use (e.g. $\square$
).
There are essentially three different ways how to express something like if-then-else in Prolog. To compare them consider char_class/2
. For a
and b
the class should be ab
and other
for all other terms. One could write this clumsily like so:
char_class(a, ab).
char_class(b, ab).
char_class(X, other) :-
dif(X, a),
dif(X, b).
?- char_class(Ch, Class).
Ch = a, Class = ab
; Ch = b, Class = ab
; Class = other,
dif(Ch, a), dif(Ch, b).
To write things more compactly, an if-then-else construct is needed. Prolog has a built-in one:
?- ( ( Ch = a ; Ch = b ) -> Class = ab ; Class = other ).
Ch = a, Class = ab.
While this answer is sound, it is incomplete. Just the first answer from ( Ch = a ; Ch = b )
is given. The other answers are chopped away. Not very relational, indeed.
A better construct, often called a "soft cut" (don't believe the name, a cut is a cut is a cut), gives slightly better results (this is in YAP):
?- ( ( Ch = a ; Ch = b ) *-> Class = ab ; Class = other ).
Ch = a, Class = ab
; Ch = b, Class = ab.
Alternatively, SICStus has if/3
with very similar semantics:
?- if( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
Ch = a, Class = ab
; Ch = b, Class = ab.
So the last answer is still suppressed. Now enter library(reif)
for SICStus, YAP, and SWI. Install it and say:
?- use_module(library(reif)).
?- if_( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
Ch = a, Class = ab
; Ch = b, Class = ab
; Class = other,
dif(Ch, a), dif(Ch, b).
Note that all the if_/3
is compiled away to a wildly nested if-then-else for
char_class(Ch, Class) :-
if_( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
which expands in YAP 6.3.4 to:
char_class(A,B) :-
( A\=a
->
( A\=b
->
B=other
;
( A==b
->
B=ab
)
;
A=b,
B=ab
;
dif(A,b),
B=other
)
;
( A==a
->
B=ab
)
;
A=a,
B=ab
;
dif(A,a),
( A\=b
->
B=other
;
( A==b
->
B=ab
)
;
A=b,
B=ab
;
dif(A,b),
B=other
)
).
You can do this with make - with gnu make it is the -j flag (this will also help on a uniprocessor machine).
For example if you want 4 parallel jobs from make:
make -j 4
You can also run gcc in a pipe with
gcc -pipe
This will pipeline the compile stages, which will also help keep the cores busy.
If you have additional machines available too, you might check out distcc, which will farm compiles out to those as well.
The DELIMITER statement changes the standard delimiter which is semicolon ( ;) to another. The delimiter is changed from the semicolon( ;) to double-slashes //.
Why do we have to change the delimiter?
Because we want to pass the stored procedure, custom functions etc. to the server as a whole rather than letting mysql tool to interpret each statement at a time.
This will help....
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return
c.substring(nameEQ.length,c.length);
}
return null;
}
>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])
For implementing the timeout on the function, this stackoverflow thread has answers on that.
cliff.meyers's original answer that suggested using <env-entry>
will not help when using only System.getProperty()
According to the Tomcat 6.0 docs <env-entry>
is for JNDI. So that means it won't have any effect on System.getProperty()
.
With the <env-entry>
from cliff.meyers's example, the following code
System.getProperty("SMTP_PASSWORD");
will return null, not the value "abc123ftw".
According to the Tomcat 6 docs, to use <env-entry>
you'd have to write code like this to use <env-entry>
:
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our data source
String s = (String)envCtx.lookup("SMTP_PASSWORD");
Caveat: I have not actually tried the example above. But I have tried <env-entry>
with System.getProperty(), and that definitely does not work.
<section>
means that the content inside is grouped (i.e. relates to a single theme), and should appear as an entry in an outline of the page.
<div>
, on the other hand, does not convey any meaning, aside from any found in its class
, lang
and title
attributes.
So no: using a <div>
does not define a section in HTML.
From the spec:
<section>
The
<section>
element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content. Eachsection
should be identified, typically by including a heading (h1-h6 element) as a child of the<section>
element.Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site’s home page could be split into sections for an introduction, news items, and contact information.
...
The
<section>
element is not a generic container element. When an element is needed only for styling purposes or as a convenience for scripting, authors are encouraged to use the<div>
element instead. A general rule is that the<section>
element is appropriate only if the element’s contents would be listed explicitly in the document’s outline.
(https://www.w3.org/TR/html/sections.html#the-section-element)
<div>
The
<div>
element has no special meaning at all. It represents its children. It can be used with theclass
,lang
, andtitle
attributes to mark up semantics common to a group of consecutive elements.Note: Authors are strongly encouraged to view the
<div>
element as an element of last resort, for when no other element is suitable. Use of more appropriate elements instead of the<div>
element leads to better accessibility for readers and easier maintainability for authors.
(https://www.w3.org/TR/html/grouping-content.html#the-div-element)
Short answer: you can't. AngularJS won't allow you to inject services into the config because it can't be sure they have been loaded correctly.
See this question and answer: AngularJS dependency injection of value inside of module.config
A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consist of collection of two kinds of blocks:
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
For debugging:
Installing the APK file:
adb install path-to-your-apk-file.apk
).For most software that isn't actually string-processing software, program logic ought not to depend on the content of string variables. Whenever I see something like this in a program:
if (s == "value")
I get a bad feeling. Why is there a string literal in this method? What's setting s
? Does it know that logic depends on the value of the string? Does it know that it has to be lower case to work? Should I be fixing this by changing it to use String.Compare
? Should I be creating an Enum
and parsing into it?
From this perspective, one gets to a philosophy of code that's pretty simple: you avoid examining a string's contents wherever possible. Comparing a string to String.Empty
is really just a special case of comparing it to a literal: it's something to avoid doing unless you really have to.
Knowing this, I don't blink when I see something like this in our code base:
string msg = Validate(item);
if (msg != null)
{
DisplayErrorMessage(msg);
return;
}
I know that Validate
would never return String.Empty
, because we write better code than that.
Of course, the rest of the world doesn't work like this. When your program is dealing with user input, databases, files, and so on, you have to account for other philosophies. There, it's the job of your code to impose order on chaos. Part of that order is knowing when an empty string should mean String.Empty
and when it should mean null
.
(Just to make sure I wasn't talking out of my ass, I just searched our codebase for `String.IsNullOrEmpty'. All 54 occurrences of it are in methods that process user input, return values from Python scripts, examine values retrieved from external APIs, etc.)
Subversion usually asks me for my "Subversion username" if it fails using my logged in username. So, when I am lazy (usually) I'll just let it ask me for my password and I'll hit enter, and wait for the username prompt and use my Subversion username.
Otherwise, Michael's solution is a good way to specify the username right off.
The tabularx
package gives you
X
, all X
columns will grow to fill up the total width.For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
In SQL Server Enterprise Manager, open \Server Objects\Linked Servers\Providers
, right click on the OraOLEDB.Oracle
provider, select properties and check the "Allow inprocess"
option. Recreate your linked server and test again.
You can also execute the following query if you don't have access to SQL Server Management Studio :
EXEC master.dbo.sp_MSset_oledb_prop N'OraOLEDB.Oracle', N'AllowInProcess', 1
Gutch's code is close, but it'll only work right if:
The Approved Method is to do it the other way around. Open the existing document with a PdfStamper, and use the returned PdfContentByte from getOverContent() to write text (and whatever else you might need) directly to the page. No second document needed.
And you can use a ColumnText to handle layout and such for you... no need to get down and dirty with beginText(),setFontAndSize(),drawText(),drawText()...,endText().
Here ready static class
import java.io.*;
import java.util.Properties;
public class Settings {
public static String Get(String name,String defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return props.getProperty(name);
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static Integer Get(String name,Integer defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return Integer.valueOf(props.getProperty(name));
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static Boolean Get(String name,Boolean defVal){
File configFile = new File(Variables.SETTINGS_FILE);
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
reader.close();
return Boolean.valueOf(props.getProperty(name));
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
return defVal;
} catch (IOException ex) {
// I/O error
logger.error(ex);
return defVal;
} catch (Exception ex){
logger.error(ex);
return defVal;
}
}
public static void Set(String name, String value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer, Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
public static void Set(String name, Integer value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer,Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
public static void Set(String name, Boolean value){
File configFile = new File(Variables.SETTINGS_FILE);
try {
Properties props = new Properties();
FileReader reader = new FileReader(configFile);
props.load(reader);
props.setProperty(name, value.toString());
FileWriter writer = new FileWriter(configFile);
props.store(writer,Variables.SETTINGS_COMMENT);
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
logger.error(ex);
} catch (IOException ex) {
// I/O error
logger.error(ex);
} catch (Exception ex){
logger.error(ex);
}
}
}
Here sample:
Settings.Set("valueName1","value");
String val1=Settings.Get("valueName1","value");
Settings.Set("valueName2",true);
Boolean val2=Settings.Get("valueName2",true);
Settings.Set("valueName3",100);
Integer val3=Settings.Get("valueName3",100);
You can use isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
The comp.lang.c FAQ list shares three different ways to easily generate random numbers with a Gaussian distribution.
You may take a look of it: http://c-faq.com/lib/gaussian.html
The url you are referring is a query type and I see that the request object supports a method called arguments to get the query arguments. You may also want try self.request.get('def')
directly to get your value from the object..
You can do it with _.pullAllBy.
var countries = {};_x000D_
_x000D_
countries.results = [_x000D_
{id:'AF',name:'Afghanistan'},_x000D_
{id:'AL',name:'Albania'},_x000D_
{id:'DZ',name:'Algeria'}_x000D_
];_x000D_
_x000D_
// Remove element by id_x000D_
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');_x000D_
_x000D_
// Remove element by name_x000D_
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');_x000D_
console.log(countries);
_x000D_
.as-console-wrapper {_x000D_
max-height: 100% !important;_x000D_
top: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
Another way to do it could be by creating an alias. For example in terminal write:
alias printhello='python /home/hello_world.py'
Writing printhello
will run hello_world.py, but this is only temporary.
To make aliases permanent, you have to add them to bashrc, you can edit it by writing this in the terminal:
gedit ~/.bashrc
For the parameter or without parameter URLs Use this :
Method 1:
$currentURL = current_url(); //for simple URL
$params = $_SERVER['QUERY_STRING']; //for parameters
$fullURL = $currentURL . '?' . $params; //full URL with parameter
Method 2:
$full_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
Method 3:
base_url(uri_string());
Use typedefs to define more complicated types i.e function pointers
I will take the example of defining a state-machine in C
typedef int (*action_handler_t)(void *ctx, void *data);
now we have defined a type called action_handler that takes two pointers and returns a int
define your state-machine
typedef struct
{
state_t curr_state; /* Enum for the Current state */
event_t event; /* Enum for the event */
state_t next_state; /* Enum for the next state */
action_handler_t event_handler; /* Function-pointer to the action */
}state_element;
The function pointer to the action looks like a simple type and typedef primarily serves this purpose.
All my event handlers now should adhere to the type defined by action_handler
int handle_event_a(void *fsm_ctx, void *in_msg );
int handle_event_b(void *fsm_ctx, void *in_msg );
References:
Expert C programming by Linden
You may use +
or <<
operator, but in ruby .concat
function is the most preferable one, as it is much faster than other operators. You can use it like.
source = "#{ROOT_DIR}/".concat(project.concat("/App.config"))
If you don't want to use LINQ
// Get the files
DirectoryInfo info = new DirectoryInfo("path/to/files"));
FileInfo[] files = info.GetFiles();
// Sort by creation-time descending
Array.Sort(files, delegate(FileInfo f1, FileInfo f2)
{
return f2.CreationTime.CompareTo(f1.CreationTime);
});
We can use the CONCAT
SQL function.
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
This works perfectly for my case.
string
is a string, and string[]
is an array of strings
Use Android Query library, very cool indeed.You can change it to use ProgressDialog
as you see in other examples, this one will show progress view from your layout and hide it after completion.
File target = new File(new File(Environment.getExternalStorageDirectory(), "ApplicationName"), "tmp.pdf");
new AQuery(this).progress(R.id.progress_view).download(_competition.qualificationScoreCardsPdf(), target, new AjaxCallback<File>() {
public void callback(String url, File file, AjaxStatus status) {
if (file != null) {
// do something with file
}
}
});
download the zip file according to your OS (e.g.: protoc-3.7.0-osx-x86_64.zip). This applies also to other OS.
Move the executable in protoc-3/bin/protoc to one of your directories in PATH. In Mac I suggest to put it into /usr/local/bin
(optional) There is also an include file, you can add. This is a snippet of the README.md
If you intend to use the included well known types then don't forget to
copy the contents of the 'include' directory somewhere as well, for example
into '/usr/local/include/'.
Please refer to our official github site for more installation instructions:
https://github.com/protocolbuffers/protobuf
The error occurs when the DNS resolution fails. Check if you can wget (or curl) the api url from the command line. Changing the DNS server and testing it might help.
var x = "somestring"
alert(x.charAt(0));
The charAt() method allows you to specify the position of the character you want.
What you were trying to do is get the character at the position of an array "x", which is not defined as X is not an array.
That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).
The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:
[data getBytes:&byteData length:len];
Which fills the array you have allocated with data from the NSData object.
getText()
function won't work like the way it used to be for webdriver, in order to get it work for protractor you will need to wrap it in a function and return the text something like we did for our protractor framework we have kept it in a common function like -
getText : function(element, callback) {
element.getText().then (function(text){
callback(text);
});
},
By this you can have the text of an element.
Let me know if it is still unclear.
If you come here because you have to turn on or off the colspan
attribute (say for a mobile layout):
Duplicate the <td>
s and only show the ones with the desired colspan
:
table.colspan--on td.single {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
table.colspan--off td.both {_x000D_
display: none;_x000D_
}
_x000D_
<!-- simple table -->_x000D_
<table class="colspan--on">_x000D_
<thead>_x000D_
<th>col 1</th>_x000D_
<th>col 2</th>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<!-- normal row -->_x000D_
<td>a</td>_x000D_
<td>b</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<!-- the <td> spanning both columns -->_x000D_
<td class="both" colspan="2">both</td>_x000D_
_x000D_
<!-- the two single-column <td>s -->_x000D_
<td class="single">A</td>_x000D_
<td class="single">B</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<!-- normal row -->_x000D_
<td>a</td>_x000D_
<td>b</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
<!--_x000D_
that's all_x000D_
-->_x000D_
_x000D_
_x000D_
_x000D_
<!--_x000D_
stuff only needed for making this interactive example looking good:_x000D_
-->_x000D_
<br><br>_x000D_
<button onclick="toggle()">Toggle colspan</button>_x000D_
<script>/*toggle classes*/var tableClasses = document.querySelector('table').classList;_x000D_
function toggle() {_x000D_
tableClasses.toggle('colspan--on');_x000D_
tableClasses.toggle('colspan--off');_x000D_
}_x000D_
</script>_x000D_
<style>/* some not-needed styles to make this example more appealing */_x000D_
td {text-align: center;}_x000D_
table, td, th {border-collapse: collapse; border: 1px solid black;}</style>
_x000D_
A)
String str = "a string";
int length = str.length( ); // length == 8
http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29
edit
If you want to count the number of a specific type of characters in a String
, then a simple method is to iterate through the String
checking each index against your test case.
int charCount = 0;
char temp;
for( int i = 0; i < str.length( ); i++ )
{
temp = str.charAt( i );
if( temp.TestCase )
charCount++;
}
where TestCase
can be isLetter( )
, isDigit( )
, etc.
Or if you just want to count everything but spaces, then do a check in the if
like temp != ' '
B)
String str = "a string";
char atPos0 = str.charAt( 0 ); // atPos0 == 'a'
http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29
We are looking at building a few helpers, still deciding on APIs and if this goes in core or not. See: https://code.google.com/archive/p/dapper-dot-net/issues/6 for progress.
In the mean time you can do the following
val = "my value";
cnn.Execute("insert into Table(val) values (@val)", new {val});
cnn.Execute("update Table set val = @val where Id = @id", new {val, id = 1});
etcetera
See also my blog post: That annoying INSERT problem
Update
As pointed out in the comments, there are now several extensions available in the Dapper.Contrib project in the form of these IDbConnection
extension methods:
T Get<T>(id);
IEnumerable<T> GetAll<T>();
int Insert<T>(T obj);
int Insert<T>(Enumerable<T> list);
bool Update<T>(T obj);
bool Update<T>(Enumerable<T> list);
bool Delete<T>(T obj);
bool Delete<T>(Enumerable<T> list);
bool DeleteAll<T>();
I been seeking the same thing without using some unsupported PHP class. Excel CSV dosn't always use the quote separators and escapes the quotes using "" because the algorithm was probably made back the 80's or something. After looking at several .csv parsers in the comments section on PHP.NET, I seen ones that even used callbacks or eval'd code and they either didnt work like needed or simply didnt work at all. So, I wrote my own routines for this and they work in the most basic PHP configuration. The array keys can either be numeric or named as the fields given in the header row. Hope this helps.
function SW_ImplodeCSV(array $rows, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
// SW_ImplodeCSV - returns 2D array as string of csv(MS Excel .CSV supported)
// AUTHOR: [email protected]
// RELEASED: 9/21/13 BETA
{ $r=1; $row=array(); $fields=array(); $csv="";
$escapes=array('\r', '\n', '\t', '\\', '\"'); //two byte escape codes
$escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code
if($mode=='EXCEL')// escape code = ""
{ $delim=','; $enclos='"'; $rowbr="\r\n"; }
else //mode=STANDARD all fields enclosed
{ $delim=','; $enclos='"'; $rowbr="\r\n"; }
$csv=""; $i=-1; $i2=0; $imax=count($rows);
while( $i < $imax )
{
// get field names
if($i == -1)
{ $row=$rows[0];
if($fmt=='2D_FIELDNAME_ARRAY')
{ $i2=0; $i2max=count($row);
while( list($k, $v) = each($row) )
{ $fields[$i2]=$k;
$i2++;
}
}
else //if($fmt='2D_NUMBERED_ARRAY')
{ $i2=0; $i2max=(count($rows[0]));
while($i2<$i2max)
{ $fields[$i2]=$i2;
$i2++;
}
}
if($headerrow==true) { $row=$fields; }
else { $i=0; $row=$rows[0];}
}
else
{ $row=$rows[$i];
}
$i2=0; $i2max=count($row);
while($i2 < $i2max)// numeric loop (order really matters here)
//while( list($k, $v) = each($row) )
{ if($i2 != 0) $csv=$csv.$delim;
$v=$row[$fields[$i2]];
if($mode=='EXCEL') //EXCEL 2quote escapes
{ $newv = '"'.(str_replace('"', '""', $v)).'"'; }
else //STANDARD
{ $newv = '"'.(str_replace($escapes2, $escapes, $v)).'"'; }
$csv=$csv.$newv;
$i2++;
}
$csv=$csv."\r\n";
$i++;
}
return $csv;
}
function SW_ExplodeCSV($csv, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
{ // SW_ExplodeCSV - parses CSV into 2D array(MS Excel .CSV supported)
// AUTHOR: [email protected]
// RELEASED: 9/21/13 BETA
//SWMessage("SW_ExplodeCSV() - CALLED HERE -");
$rows=array(); $row=array(); $fields=array();// rows = array of arrays
//escape code = '\'
$escapes=array('\r', '\n', '\t', '\\', '\"'); //two byte escape codes
$escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code
if($mode=='EXCEL')
{// escape code = ""
$delim=','; $enclos='"'; $esc_enclos='""'; $rowbr="\r\n";
}
else //mode=STANDARD
{// all fields enclosed
$delim=','; $enclos='"'; $rowbr="\r\n";
}
$indxf=0; $indxl=0; $encindxf=0; $encindxl=0; $enc=0; $enc1=0; $enc2=0; $brk1=0; $rowindxf=0; $rowindxl=0; $encflg=0;
$rowcnt=0; $colcnt=0; $rowflg=0; $colflg=0; $cell="";
$headerflg=0; $quotedflg=0;
$i=0; $i2=0; $imax=strlen($csv);
while($indxf < $imax)
{
//find first *possible* cell delimiters
$indxl=strpos($csv, $delim, $indxf); if($indxl===false) { $indxl=$imax; }
$encindxf=strpos($csv, $enclos, $indxf); if($encindxf===false) { $encindxf=$imax; }//first open quote
$rowindxl=strpos($csv, $rowbr, $indxf); if($rowindxl===false) { $rowindxl=$imax; }
if(($encindxf>$indxl)||($encindxf>$rowindxl))
{ $quoteflg=0; $encindxf=$imax; $encindxl=$imax;
if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
}
else
{ //find cell enclosure area (and real cell delimiter)
$quoteflg=1;
$enc=$encindxf;
while($enc<$indxl) //$enc = next open quote
{// loop till unquoted delim. is found
$enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//close quote
$encindxl=$enc; //last close quote
$indxl=strpos($csv, $delim, $enc+1); if($indxl===false) { $indxl=$imax; }//last delim.
$enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//open quote
if(($indxl==$imax)||($enc==$imax)) break;
}
$rowindxl=strpos($csv, $rowbr, $enc+1); if($rowindxl===false) { $rowindxl=$imax; }
if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
}
if($quoteflg==0)
{ //no enclosured content - take as is
$colflg=1;
//get cell
// $cell=substr($csv, $indxf, ($indxl-$indxf)-1);
$cell=substr($csv, $indxf, ($indxl-$indxf));
}
else// if($rowindxl > $encindxf)
{ // cell enclosed
$colflg=1;
//get cell - decode cell content
$cell=substr($csv, $encindxf+1, ($encindxl-$encindxf)-1);
if($mode=='EXCEL') //remove EXCEL 2quote escapes
{ $cell=str_replace($esc_enclos, $enclos, $cell);
}
else //remove STANDARD esc. sceme
{ $cell=str_replace($escapes, $escapes2, $cell);
}
}
if($colflg)
{// read cell into array
if( ($fmt=='2D_FIELDNAME_ARRAY') && ($headerflg==1) )
{ $row[$fields[$colcnt]]=$cell; }
else if(($fmt=='2D_NUMBERED_ARRAY')||($headerflg==0))
{ $row[$colcnt]=$cell; } //$rows[$rowcnt][$colcnt] = $cell;
$colcnt++; $colflg=0; $cell="";
$indxf=$indxl+1;//strlen($delim);
}
if($rowflg)
{// read row into big array
if(($headerrow) && ($headerflg==0))
{ $fields=$row;
$row=array();
$headerflg=1;
}
else
{ $rows[$rowcnt]=$row;
$row=array();
$rowcnt++;
}
$colcnt=0; $rowflg=0; $cell="";
$rowindxf=$rowindxl+2;//strlen($rowbr);
$indxf=$rowindxf;
}
$i++;
//SWMessage("SW_ExplodeCSV() - colcnt = ".$colcnt." rowcnt = ".$rowcnt." indxf = ".$indxf." indxl = ".$indxl." rowindxf = ".$rowindxf);
//if($i>20) break;
}
return $rows;
}
...bob can now go back to his speadsheets
For linebreaks, PHP as "\n"
(see double quote strings) and PHP_EOL
.
Here, you are using <br />
, which is not a PHP line-break : it's an HTML linebreak.
Here, you can simplify what you posted (with HTML linebreaks) : no need for the strings concatenations : you can put everything in just one string, like this :
$var = "Hi there<br/>Welcome to my website<br/>";
Or, using PHP linebreaks :
$var = "Hi there\nWelcome to my website\n";
Note : you might also want to take a look at the nl2br()
function, which inserts <br>
before \n
.
you can use like this. it's better than
<link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
<!--[if IE 7]><link rel="stylesheet" type="text/css" media="screen" href="css/ie7.css" /><![endif]-->
<!--[if IE 6]><link rel="stylesheet" type="text/css" media="screen" href="css/ie6.css" /><![endif]-->
-------------------------------------------------------------
<!--[if lt IE 7 ]> <body class="ie6"> <![endif]-->
<!--[if IE 7 ]> <body class="ie7"> <![endif]-->
<!--[if IE 8 ]> <body class="ie8"> <![endif]-->
<!--[if !IE]>--> <body> <!--<![endif]-->
div.foo { color: inherit;} .ie7 div.foo { color: #ff8000; }
The WHEN part is compared with ==, but you can't really compare with NULL. Try
CASE WHEN last_name is NULL THEN ... ELSE .. END
instead or COALESCE:
COALESCE(' '+last_name,'')
(' '+last_name is NULL when last_name is NULL, so it should return '' in that case)
By default, Maven will always look in the official Maven repository, which is http://repo1.maven.org.
When Maven tries to build a project, it will look in your local repository (by default ~/.m2/repository
but you can configure it by changing the <localRepository>
value in your ~/.m2/settings.xml
) to find any dependency, plugin or report defined in your pom.xml
. If the adequate artifact is not found in your local repository, it will look in all external repositories configured, starting with the default one, http://repo1.maven.org.
You can configure Maven to avoid this default repository by setting a mirror in your settings.xml
file:
<mirrors>
<mirror>
<id>repoMirror</id>
<name>Our mirror for Maven repository</name>
<url>http://the/server/</url>
<mirrorOf>*</mirrorOf>
</mirror>
</mirrors>
This way, instead of contacting http://repo1.maven.org
, Maven will contact your entreprise repository (http://the/server
in this example).
If you want to add another repository, you can define a new one in your settings.xml file:
<profiles>
<profile>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>foo.bar</id>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
<url>http://new/repository/server</url>
</repository>
</repositories>
You can see the complete settings.xml
model here.
Concerning the clean
process, you can ask Maven to run it offline. In this case, Maven will not try to reach any external repositories:
mvn -o clean
$_SERVER['HTTP_REFERER']
is the answer
I would like to emphasize @icza answer and simplify it a bit since it is a crucial concept. I assume that reader is familiar with slices.
c := append(a, b...)
This is a valid answer to the question. BUT if you need to use slices 'a' and 'c' later in code in different context, this is not the safe way to concatenate slices.
To explain, lets read the expression not in terms of slices, but in terms of underlying arrays:
"Take (underlying) array of 'a' and append elements from array 'b' to it. If array 'a' has enough capacity to include all elements from 'b' - underlying array of 'c' will not be a new array, it will actually be array 'a'. Basically, slice 'a' will show len(a) elements of underlying array 'a', and slice 'c' will show len(c) of array 'a'."
append() does not necessarily create a new array! This can lead to unexpected results. See Go Playground example.
Always use make() function if you want to make sure that new array is allocated for the slice. For example here are few ugly but efficient enough options for the task.
la := len(a)
c := make([]int, la, la + len(b))
_ = copy(c, a)
c = append(c, b...)
la := len(a)
c := make([]int, la + len(b))
_ = copy(c, a)
_ = copy(c[la:], b)
Had the same problem running PHP 7.2. I had to do the following :
sudo apt-get install php7.2-xml
You can open Xcode Help -> Run and debug -> Network debugging for more info. Hope it helps.
According to Mozilla Dev Network, placeholder
is not a valid attribute on a <select>
input.
Instead, add an option with an empty value
and the selected
attribute, as shown below. The empty value
attribute is mandatory to prevent the default behaviour which is to use the contents of the <option>
as the <option>
's value.
<select>
<option value="" selected>select your beverage</option>
<option value="tea">Tea</option>
<option value="coffee">Coffee</option>
<option value="soda">Soda</option>
</select>
In modern browsers, adding the required
attribute to the <select>
element will not allow the user to submit the form which the element is part of if the selected option has an empty value.
If you want to style the default option inside the list (which appears when clicking the element), there's a limited number of CSS properties that are well-supported. color
and background-color
are the 2 safest bets, other CSS properties are likely to be ignored.
In my option the best way (in HTML5) to mark the default option is using the custom data-*
attributes.1 Here's how to style the default option to be greyed out:
select option[data-default] {_x000D_
color: #888;_x000D_
}
_x000D_
<select>_x000D_
<option value="" selected data-default>select your beverage</option>_x000D_
<option value="tea">Tea</option>_x000D_
<option value="coffee">Coffee</option>_x000D_
<option value="soda">Soda</option>_x000D_
</select>
_x000D_
However, this will only style the item inside the drop-down list, not the value displayed on the input. If you want to style that with CSS, target your <select>
element directly. In that case, you can only change the style of the currently selected element at any time.2
If you wanted to make it slightly harder for the user to select the default item, you could set the display: none;
CSS rule on the <option>
, but remember that this will not prevent users from selecting it (using e.g. arrow keys/typing), this just makes it harder for them to do so.
1 This answer previously advised the use of a default
attribute which is non-standard and has no meaning on its own.
2 It's technically possible to style the select itself based on the selected value using JavaScript, but that's outside the scope of this question. This answer, however, covers this method.
Here's one example, given to me by @jleahy: Suppose you have a collection of tasks, executed asynchronously, and managed by an std::shared_ptr<Task>
. You may want to do something with those tasks periodically, so a timer event may traverse a std::vector<std::weak_ptr<Task>>
and give the tasks something to do. However, simultaneously a task may have concurrently decided that it is no longer needed and die. The timer can thus check whether the task is still alive by making a shared pointer from the weak pointer and using that shared pointer, provided it isn't null.
EDIT: This answer was submitted before the OP's jsFiddle example was posted in question. See second answer for response to that jsFiddle.
Here is an example of how it could work:
HTML:
<div id="someDiv">
Once upon a midnight dreary
<br>While I pondered weak and weary
<br>Over many a quaint and curious
<br>Volume of forgotten lore.
</div>
Type new text here:<br>
<input type="text" id="replacementtext" />
<input type="button" id="mybutt" value="Swap" />
<input type="hidden" id="vault" />
javascript/jQuery:
//Declare persistent vars outside function
var savText, newText, myState = 0;
$('#mybutt').click(function(){
if (myState==0){
savText = $('#someDiv').html(); //save poem data from DIV
newText = $('#replacementtext').val(); //save data from input field
$('#replacementtext').val(''); //clear input field
$('#someDiv').html( newText ); //replace poem with insert field data
myState = 1; //remember swap has been done once
} else {
$('#someDiv').html(savText);
$('#replacementtext').val(newText); //replace contents
myState = 0;
}
});
There is a pandas function that can be applied to DateTime index in pandas data frame.
date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list
the element inside the list:
u'1910-11-02'
You might need to replace the 'u'.
There might be some additional arguments that I should put into the previous functions.
Note that usage of a SerialPort.DataReceived
event is optional. You can set proper timeout using SerialPort.ReadTimeout
and continuously call SerialPort.Read()
after you wrote something to a port until you get a full response.
Moreover you can use SerialPort.BaseStream
property to extract an underlying Stream
instance. The benefit of using a Stream
is that you can easily utilize various decorators with it:
var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and
// overrides needen virtual methods.
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.
For more information check:
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
if you do not want to be bothered by the date format, you could compare the column with the general date format, for example
select *
From table
where cast (RegistrationDate as date) between '20161201' and '20161220'
make sure the date is in DATE format, otherwise cast (col as DATE)
You have obviously a problem with the WCF security subsystem. What binding are you using? What authentication? Encryption? Signing? Do you have to cross domain boundaries?
A bit of goggling further reveals that others are experiencing this error if the clocks of client and server are out of sync (more than about five minutes) because some security schemata rely on synchronized clocks.
I read all the above answers and those are actually good.
look at this code:
for i in range(1, 4):
print("Before change:", i)
i = 20 # changing i variable
print("After change:", i) # this line will always print 20
When we execute above code the output is like below,
Before Change: 1
After change: 20
Before Change: 2
After change: 20
Before Change: 3
After change: 20
in python for loop is not trying to increase i
value. for loop is just assign values to i
which we gave. Using range(4)
what we are doing is we give the values to for loop which need assign to the i.
You can use while loop
instead of for loop
to do same thing what you want,
i = 0
while i < 6:
print(i)
j = 0
while j < 5:
i += 2 # to increase `i` by 2
This will give,
0
2
4
Thank you !
business = Business.where(:user_id => current_user.id).first
if business.nil?
# no business found
else
# business.ceo = "me"
end
I tried using Google reCAPTCHA explicitly. Here is the example:
// put somewhere in your index.html
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('your-recaptcha-element', {
'sitekey' : '6Ldcfv8SAAAAAB1DwJTM6T7qcJhVqhqtss_HzS3z'
});
};
//link function of Angularjs directive
link: function (scope, element, attrs) {
...
var domElem = '<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>';
$('#your-recaptcha-element').append($compile(domElem)(scope));
}
You can define a base class for A
and B
where you can hold a common methods/properties/fields of those.
After implement C:Base
.
Or in order to simulate multiple inheritance, define a common interface
(s) and implement them in C
Hope this helps.
It was already pointed in this comment and in this answer, but I'll try to give a more direct answer to the question:
from IPython.display import display
import numpy as np
import pandas as pd
n = 100
foo = pd.DataFrame(index=range(n))
foo['floats'] = np.random.randn(n)
with pd.option_context("display.max_rows", foo.shape[0]):
display(foo)
pandas.option_context is available since pandas 0.13.1 (pandas 0.13.1 release notes). According to this,
[it] allow[s] you to execute a codeblock with a set of options that revert to prior settings when you exit the with block.
Create a "colorize" method:
$.fn.colorize = function custom_colorize(some_color) {
this.css('color', some_color);
return this;
}
Use it:
$('#my_div').colorize('green');
This simple-ish example combines the best of How to Create a Basic Plugin in the jQuery docs, and answers from @Candide, @Michael.
this
may be chained. (Thanks @Potheek.)$('.class1, .class2').on('click', some_function);
Or:
$('.class1').add('.class2').on('click', some_function);
This also works with existing objects:
const $class1 = $('.class1');
const $class2 = $('.class2');
$class1.add($class2).on('click', some_function);
Make two folders: final/src/
to store the source java code, and
final/WebRoot/
.
You cannot put the source and the webroot together. I think you may misunderstand your teacher.
If you are using arrow or if you don't mind using arrow. You can substitute python's time formatting for arrow's one.
import logging
from arrow.arrow import Arrow
class ArrowTimeFormatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
arrow_time = Arrow.fromtimestamp(record.created)
if datefmt:
arrow_time = arrow_time.format(datefmt)
return str(arrow_time)
logger = logging.getLogger(__name__)
default_handler = logging.StreamHandler()
default_handler.setFormatter(ArrowTimeFormatter(
fmt='%(asctime)s',
datefmt='YYYY-MM-DD HH:mm:ss.SSS'
))
logger.setLevel(logging.DEBUG)
logger.addHandler(default_handler)
Now you can use all of arrow's time formatting in datefmt
attribute.
Doing it in one bulk read:
import re
textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)
Line by line:
import re
textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += reg.findall(line)
textfile.close()
But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:
import re
textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += [(reg.findall(line),offset)]
offset += len(line)
textfile.close()
But it still just makes more sense to read the whole file in at once.
This command will make a dump of given database in json and bson format.
mongodump -d <database name> -o <target directory>
So I was using Qt with Windows XP and MinGW compiler and this thing was driving me crazy.
Basically the moc_xxx.cpp was generated empty even when I was added
Q_OBJECT
Deleting everything making functions virtual, explicit and whatever you guess doesn't worked. Finally I started removing line by line and it turned out that I had
#ifdef something
Around the file. Even when the #ifdef was true moc file was not generated.
So removing all #ifdefs fixed the problem.
This thing was not happening with Windows and VS 2013.
df[df['col'].astype(bool)]
Empty strings are falsy, which means you can filter on bool values like this:
df = pd.DataFrame({
'A': range(5),
'B': ['foo', '', 'bar', '', 'xyz']
})
df
A B
0 0 foo
1 1
2 2 bar
3 3
4 4 xyz
df['B'].astype(bool)
0 True
1 False
2 True
3 False
4 True
Name: B, dtype: bool
df[df['B'].astype(bool)]
A B
0 0 foo
2 2 bar
4 4 xyz
If your goal is to remove not only empty strings, but also strings only containing whitespace, use str.strip
beforehand:
df[df['B'].str.strip().astype(bool)]
A B
0 0 foo
2 2 bar
4 4 xyz
.astype
is a vectorised operation, this is faster than every option presented thus far. At least, from my tests. YMMV.
Here is a timing comparison, I've thrown in some other methods I could think of.
Benchmarking code, for reference:
import pandas as pd
import perfplot
df1 = pd.DataFrame({
'A': range(5),
'B': ['foo', '', 'bar', '', 'xyz']
})
perfplot.show(
setup=lambda n: pd.concat([df1] * n, ignore_index=True),
kernels=[
lambda df: df[df['B'].astype(bool)],
lambda df: df[df['B'] != ''],
lambda df: df[df['B'].replace('', np.nan).notna()], # optimized 1-col
lambda df: df.replace({'B': {'': np.nan}}).dropna(subset=['B']),
],
labels=['astype', "!= ''", "replace + notna", "replace + dropna", ],
n_range=[2**k for k in range(1, 15)],
xlabel='N',
logx=True,
logy=True,
equality_check=pd.DataFrame.equals)
As simple as you can use const adults = family.filter(({ age }) => age > 18 );
const family =[{"name":"Jack", "age": 26},_x000D_
{"name":"Jill", "age": 22},_x000D_
{"name":"James", "age": 5 },_x000D_
{"name":"Jenny", "age": 2 }];_x000D_
_x000D_
const adults = family.filter(({ age }) => age > 18 );_x000D_
_x000D_
console.log(adults)
_x000D_
to creating some thing that is running like service you can use this thing :
The first thing that you must do is installing the Cement framework: Cement frame work is a CLI frame work that you can deploy your application on it.
command line interface of the app :
interface.py
from cement.core.foundation import CementApp
from cement.core.controller import CementBaseController, expose
from YourApp import yourApp
class Meta:
label = 'base'
description = "your application description"
arguments = [
(['-r' , '--run'],
dict(action='store_true', help='Run your application')),
(['-v', '--version'],
dict(action='version', version="Your app version")),
]
(['-s', '--stop'],
dict(action='store_true', help="Stop your application")),
]
@expose(hide=True)
def default(self):
if self.app.pargs.run:
#Start to running the your app from there !
YourApp.yourApp()
if self.app.pargs.stop:
#Stop your application
YourApp.yourApp.stop()
class App(CementApp):
class Meta:
label = 'Uptime'
base_controller = 'base'
handlers = [MyBaseController]
with App() as app:
app.run()
YourApp.py class:
import threading
class yourApp:
def __init__:
self.loger = log_exception.exception_loger()
thread = threading.Thread(target=self.start, args=())
thread.daemon = True
thread.start()
def start(self):
#Do every thing you want
pass
def stop(self):
#Do some things to stop your application
Keep in mind that your app must run on a thread to be daemon
To run the app just do this in command line
python interface.py --help
What if you don't want to commit every commit that you make in Git, to the SVN repository? What if you just want to selectively send commits up the pipe? Well, I have a better solution.
I keep one local Git repository where all I ever do is fetch and merge from SVN. That way I can make sure I'm including all the same changes as SVN, but I keep my commit history separate from the SVN entirely.
Then I keep a separate SVN local working copy that is in a separate folder. That's the one I make commits back to SVN from, and I simply use the SVN command line utility for that.
When I'm ready to commit my local Git repository's state to SVN, I simply copy the whole mess of files over into the local SVN working copy and commit it from there using SVN rather than Git.
This way I never have to do any rebasing, because rebasing is like freebasing.
It sounds like you want to re-implement, or possibly extend, AuthorizeAttribute
. If so, you should make sure that you inherit that, and not ActionFilterAttribute
, in order to let ASP.NET MVC do more of the work for you.
Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// Do whatever checking you need here
// If you want the base check as well (against users/roles) call
base.OnAuthorization(filterContext);
}
}
There is a good question with an answer with more details here on SO.
This is quite simple do The inner join and then group by user_id and use max aggregate function in payment_id assuming your table being user and payment query can be
select user.id, max(payment.id) from user inner join payment on (user.id = payment.user_id) group by user.id
You can't do this with CSS alone. Using jQuery you can do
HTML
<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />
CSS
.highlight{
background:yellow;
}
jQuery
$('#check').click(function(){
$('#lab').toggleClass('highlight')
})
This will work in all browsers
Yes. Starting with CPython 3.6, dictionaries return items in the order you inserted them.
Ignore the part that says this is an implementation detail. This behaviour is guaranteed in CPython 3.6 and is required for all other Python implementations starting with Python 3.7.
Take a look at this discussion which handles manually hiding and showing the IME. However, my feeling is that if a focused EditText
is not bringing the IME up it is because you are calling AlertDialog.show()
in your OnCreate()
or some other method which is evoked before the screen is actually presented. Moving it to OnPostResume()
should fix it in that case I believe.
DateAndTime Reformat:
SELECT *, to_char( last_update, 'DD-MON-YYYY') as re_format from actor;
DEMO:
You can choose between the following two methods to set the text of an Entry
widget. For the examples, assume imported library import tkinter as tk
and root window root = tk.Tk()
.
Method A: Use delete
and insert
Widget Entry
provides methods delete
and insert
which can be used to set its text to a new value. First, you'll have to remove any former, old text from Entry
with delete
which needs the positions where to start and end the deletion. Since we want to remove the full old text, we start at 0
and end at wherever the end currently is. We can access that value via END
. Afterwards the Entry
is empty and we can insert new_text
at position 0
.
entry = tk.Entry(root)
new_text = "Example text"
entry.delete(0, tk.END)
entry.insert(0, new_text)
Method B: Use StringVar
You have to create a new StringVar
object called entry_text
in the example. Also, your Entry
widget has to be created with keyword argument textvariable
. Afterwards, every time you change entry_text
with set
, the text will automatically show up in the Entry
widget.
entry_text = tk.StringVar()
entry = tk.Entry(root, textvariable=entry_text)
new_text = "Example text"
entry_text.set(new_text)
Complete working example which contains both methods to set the text via Button
:
This window
is generated by the following complete working example:
import tkinter as tk
def button_1_click():
# define new text (you can modify this to your needs!)
new_text = "Button 1 clicked!"
# delete content from position 0 to end
entry.delete(0, tk.END)
# insert new_text at position 0
entry.insert(0, new_text)
def button_2_click():
# define new text (you can modify this to your needs!)
new_text = "Button 2 clicked!"
# set connected text variable to new_text
entry_text.set(new_text)
root = tk.Tk()
entry_text = tk.StringVar()
entry = tk.Entry(root, textvariable=entry_text)
button_1 = tk.Button(root, text="Button 1", command=button_1_click)
button_2 = tk.Button(root, text="Button 2", command=button_2_click)
entry.pack(side=tk.TOP)
button_1.pack(side=tk.LEFT)
button_2.pack(side=tk.LEFT)
root.mainloop()
As pointed out already, most standard implementations of List
are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.
Here:
def random_color():
rgbl=[255,0,0]
random.shuffle(rgbl)
return tuple(rgbl)
The result is either red, green or blue. The method is not applicable to other sets of colors though, where you'd have to build a list of all the colors you want to choose from and then use random.choice to pick one at random.