Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
Just to propose a sed
alternative. :) To skip first one million lines, try |sed '1,1000000d'
.
Example:
$ perl -wle 'print for (1..1_000_005)'|sed '1,1000000d'
1000001
1000002
1000003
1000004
1000005
This solution helped me to skip the number of lines specified by the linetostart
variable.
You get the index (int) and the line (string) if you want to keep track of those too.
In your case, you substitute linetostart with 18, or assign 18 to linetostart variable.
f = open("file.txt", 'r')
for i, line in enumerate(f, linetostart):
#Your code
try this
Package manager console
Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3
and then add by using add reference .
I had the same issue today. My problem was solved my moving META-INF to the resources folder.
Find if the given number is a power of 2.
#include <math.h>
int main(void)
{
int n,logval,powval;
printf("Enter a number to find whether it is s power of 2\n");
scanf("%d",&n);
logval=log(n)/log(2);
powval=pow(2,logval);
if(powval==n)
printf("The number is a power of 2");
else
printf("The number is not a power of 2");
getch();
return 0;
}
Difference between "return" and "print" can also be found in the following example:
RETURN:
def bigger(a, b):
if a > b:
return a
elif a <b:
return b
else:
return a
The above code will give correct results for all inputs.
PRINT:
def bigger(a, b):
if a > b:
print a
elif a <b:
print b
else:
print a
NOTE: This will fail for many test cases.
ERROR:
----
FAILURE
: Test case input: 3, 8.
Expected result: 8
FAILURE
: Test case input: 4, 3.
Expected result: 4
FAILURE
: Test case input: 3, 3.
Expected result: 3
You passed 0 out of 3 test cases
If the folder is already writable so thats not the problem.
You can also just navigate to /www/projet_etienne/app/cache/
and manualy remove the folders in there (dev, dev_new, dev_old).
Make sure to SAVE a copy of those folder somewhere to put back if this doesn't fix the problem
I know this is not the way it should be done but it worked for me a couple of times now.
I had this problem and took long while to figure it out. Problem came up when I removed projects from solution and replaced those with nuget packages.
Solution seemed to be fine but the .csproj file still contained those projects multiple times as reference.
Seems that VS does not clean that file appropriately. It was still referencing the removed projects under the hood. When manually removed the references from csproj file all works again! wohoo
The server_name
docs directive is used to identify virtual hosts, they're not used to set the binding.
netstat
tells you that nginx listens on 0.0.0.0:80
which means that it will accept connections from any IP.
If you want to change the IP nginx binds on, you have to change the listen
docs rule.
So, if you want to set nginx to bind to localhost
, you'd change that to:
listen 127.0.0.1:80;
In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).
This is my favorite method for being easy to read:
Dir.glob("*/*.txt") do |my_text_file|
puts "working on: #{my_text_file}..."
end
And you can even extend this to work on all files in subdirs:
Dir.glob("**/*.txt") do |my_text_file| # note one extra "*"
puts "working on: #{my_text_file}..."
end
Had the same error initially. so.. pre-installed git and node.js and later installed Aptana, which installed perfectly. Rajeeva.
It's a bit of hacky way, but for me this code works (iOS 6):
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[self presentViewController:self.signInViewController animated:YES completion:^{
[self.signInViewController dismissViewControllerAnimated:NO completion:^{
appDelegate.window.rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext;
[self presentViewController:self.signInViewController animated:NO completion:nil];
appDelegate.window.rootViewController.modalPresentationStyle = UIModalPresentationFullScreen;
}];
}];
This code works also on iPhone
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 28800
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 28800
At first, wait_timeout = 28800 which is the default value. To change the session value, you need to set the global variable because the session variable is read-only.
SET @@GLOBAL.wait_timeout=300
After you set the global variable, the session variable automatically grabs the value.
SHOW SESSION VARIABLES LIKE "wait_timeout"; -- 300
SHOW GLOBAL VARIABLES LIKE "wait_timeout"; -- 300
Next time when the server restarts, the session variables will be set to the default value i.e. 28800.
P.S. I m using MySQL 5.6.16
I have tried all the hacks suggested here - to no avail. At the end I have simply created a new Maven application and manually copied into it - one by one - the pom.xml and the java files and resources. It all works now. I am new to IntelliJ and totally unimpressed but how easy it is to get it into an unstable state.
Let's say you're using this HTML5 layout:
<html>
<body>
<header>
<nav><ul>...</ul></nav>
</header>
<article>
<ul>...</ul>
</article>
<footer>
<ul>...</ul>
</footer>
</body>
</html>
You could say in your CSS:
header ul, footer ul, nav ul { list-style-type: none; }
If you're using HTML 4, assign IDs to your DIVs (instead of using the new fancy-pants elements) and change this to:
#header ul, #footer ul, #nav ul { list-style-type: none; }
If you're using a CSS reset stylesheet (like Eric Meyer's), you would actually have to give the list style back, since the reset removes the list style from all lists.
#content ul { list-style-type: disc; margin-left: 1.5em; }
chmod +w <directory>
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
Essentially console.log("Put a message here.")
if the browser has a supporting console.
Another typical debugging method is using alerts, alert("Put a message here.")
RE: Update II
This seems to make sense, you are trying to automate QUnit tests, from what I have read on QUnit this is an in-browser unit testing suite/library. QUnit expects to run in a browser and therefore expects the browser to recognize all of the JavaScript functions you are calling.
Based on your Maven configuration it appears you are using Rhino to execute your Javascript at the command line/terminal. This is not going to work for testing browser specifics, you would likely need to look into Selenium for this. If you do not care about testing your JavaScript in a browser but are only testing JavaScript at a command line level (for reason I would not be familiar with) it appears that Rhino recognizes a print()
method for evaluating expressions and printing them out. Checkout this documentation.
These links might be of interest to you.
I think this other Stack Overflow answer would solve your problem: How do I run a bat file in the background from another bat file?
Basically, you use the /B
and /C
options:
START /B CMD /C CALL "foo.bat" [args [...]] >NUL 2>&1
Johnathan Sampson's Linux example didn't work so good for me. Here's an improved version:
function getDirSize($path)
{
$io = popen('/usr/bin/du -sb '.$path, 'r');
$size = intval(fgets($io,80));
pclose($io);
return $size;
}
on first button add the following.
onclick="window.location.href='Students.html';"
similarly do the rest 2 buttons.
<input type="button" value="Add Students" onclick="window.location.href='Students.html';">
<input type="button" value="Add Courses" onclick="window.location.href='Courses.html';">
<input type="button" value="Student Payments" onclick="window.location.href='Payments.html';">
All you need is Enum.Parse.
Two choices:
1/ From the project:
2/ If you have already other jar imported, from the directory "References Libraries":
Both will lead you to this screen where you can mange your libraries:
It sounds like the only varaible stored in the .RData
file was one named isfar
.
Are you really sure that you saved the table? The command should have been:
save(the_table, file = "isfar.RData")
There are many ways to examine a variable.
Type it's name at the command prompt to see it printed. Then look at str
, ls.str
, summary
, View
and unclass
.
Here's your script...
DIR=$(pwd)
echo $DIR
while [ "$DIR" != "/" ]; do
cd ..
DIR=$(pwd)
echo $DIR
done
Note the spaces, use of quotes, and $ signs.
You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.
The second example would be the one to go with, not just for readability, but because of the fact that in the first example, If NOT value1 would return a boolean value to be compared against value2. IOW, you need to rewrite that example as
If NOT (value1 = value2)
which just makes the use of the NOT keyword pointless.
I run my application with Java 8 and Java 8 brought security certificate onto its trust store. Then I switched to Java 7 and added the following into VM options:
-Djavax.net.ssl.trustStore=C:\<....>\java8\jre\lib\security\cacerts
Simply I pointed to the location where a certificate is.
The popular answer google.maps.event.trigger(map, "resize");
didn't work for me alone.
Here was a trick that assured that the page had loaded and that the map had loaded as well. By setting a listener and listening for the idle state of the map you can then call the event trigger to resize.
$(document).ready(function() {
google.maps.event.addListener(map, "idle", function(){
google.maps.event.trigger(map, 'resize');
});
});
This was my answer that worked for me.
I have done that the more simple way, not as clean as it should be but it was a quick hack
$htmlContent = file_get_contents('pageURL');
// read all image tags into an array
preg_match_all('/<img[^>]+>/i',$htmlContent, $imgTags);
for ($i = 0; $i < count($imgTags[0]); $i++) {
// get the source string
preg_match('/src="([^"]+)/i',$imgTags[0][$i], $imgage);
// remove opening 'src=' tag, can`t get the regex right
$origImageSrc[] = str_ireplace( 'src="', '', $imgage[0]);
}
// will output all your img src's within the html string
print_r($origImageSrc);
Perhaps use plt.annotate:
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
cmap=plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
label,
xy=(x, y), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.show()
Here is what I am doing to solve this issue. I agree this is because of the timing issue and needed a pause to execute the code.
var delayInMilliseconds = 1000;
setTimeout(function() {
//add your code here to execute
}, delayInMilliseconds);
This new code will pause it for 1 second and meanwhile run your code.
Another option is to go to Window->Preferences->Java->Editor->SaveActions and check the Format source code option. Then your source code will be formatted truly automatically each time you save it.
Use the collapse
argument to paste
:
paste(a,collapse=" ")
[1] "aa bb cc"
Another option for working out the encoding is to use libmagic (which is the code behind the file command). There are a profusion of python bindings available.
The python bindings that live in the file source tree are available as the python-magic (or python3-magic) debian package. It can determine the encoding of a file by doing:
import magic
blob = open('unknown-file', 'rb').read()
m = magic.open(magic.MAGIC_MIME_ENCODING)
m.load()
encoding = m.buffer(blob) # "utf-8" "us-ascii" etc
There is an identically named, but incompatible, python-magic pip package on pypi that also uses libmagic
. It can also get the encoding, by doing:
import magic
blob = open('unknown-file', 'rb').read()
m = magic.Magic(mime_encoding=True)
encoding = m.from_buffer(blob)
break used to get out from the loop statement, but continue just stop script on specific condition and then continue looping statement until reach the end..
for($i=0; $i<10; $i++){
if($i == 5){
echo "It reach five<br>";
continue;
}
echo $i . "<br>";
}
echo "<hr>";
for($i=0; $i<10; $i++){
if($i == 5){
echo "It reach end<br>";
break;
}
echo $i . "<br>";
}
Hope it can help u;
Here's my example crontab I always use as a template:
# Use the hash sign to prefix a comment
# +---------------- minute (0 - 59)
# | +------------- hour (0 - 23)
# | | +---------- day of month (1 - 31)
# | | | +------- month (1 - 12)
# | | | | +---- day of week (0 - 7) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
#--------------------------------------------------------------------------
To run my cron job every Monday, Wednesady and Friday at 7:00PM, the result will be:
0 19 * * 1,3,5 nohup /home/lathonez/script.sh > /tmp/script.log 2>&1
You can use mysql_errno()
for this too.
$result = mysql_query($query);
if(mysql_errno()){
echo "MySQL error ".mysql_errno().": "
.mysql_error()."\n<br>When executing <br>\n$query\n<br>";
}
In the second version, you're passing the String returned from this.id
. Not the element itself.
So id.value
won't give you what you want.
You would need to pass the element with this
.
doSomething(this)
then:
function(el){
var value = el.value;
...
}
Note: In some browsers, the second one would work if you did:
window[id].value
because element IDs are a global property, but this is not safe.
It makes the most sense to just pass the element with this
instead of fetching it again with its ID.
You can use Boost.Predef
which contains various predefined macros for the target platform including the OS (BOOST_OS_*
). Yes boost is often thought as a C++ library, but this one is a preprocessor header that works with C as well!
This library defines a set of compiler, architecture, operating system, library, and other version numbers from the information it can gather of C, C++, Objective C, and Objective C++ predefined macros or those defined in generally available headers. The idea for this library grew out of a proposal to extend the Boost Config library to provide more, and consistent, information than the feature definitions it supports. What follows is an edited version of that brief proposal.
For example
#include <boost/predef.h>
#if defined(BOOST_OS_WINDOWS)
#elif defined(BOOST_OS_ANDROID)
#elif defined(BOOST_OS_LINUX)
#elif defined(BOOST_OS_BSD)
#elif defined(BOOST_OS_AIX)
#elif defined(BOOST_OS_HAIKU)
...
#endif
The full list can be found in BOOST_OS
operating system macros
See also How to get platform ids from boost
Java - encrypt / decrypt user name and password from a configuration file
Code from above link
DESKeySpec keySpec = new DESKeySpec("Your secret Key phrase".getBytes("UTF8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();
sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
.........
// ENCODE plainTextPassword String
byte[] cleartext = plainTextPassword.getBytes("UTF8");
Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
cipher.init(Cipher.ENCRYPT_MODE, key);
String encryptedPwd = base64encoder.encode(cipher.doFinal(cleartext));
// now you can store it
......
// DECODE encryptedPwd String
byte[] encrypedPwdBytes = base64decoder.decodeBuffer(encryptedPwd);
Cipher cipher = Cipher.getInstance("DES");// cipher is not thread safe
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));
You can use CSS background:url(ur_img.png)
for insert image inside input box
but for create click event you need to merge your arrow image and input box .
I really like this function:
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
You have not placed the script tags for angular js
you can do so by using cdn or downloading the angularjs for your project and then referencing it
after this you have to add your own java script in your case main.js
that should do
When you have to reload the file, you can erase the value of input. Next time you add a file, 'on change' event will trigger.
document.getElementById('my_input').value = null;
// ^ that just erase the file path but do the trick
Create a file named tsconfig.json
in your project root and include following lines in it:
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"module": "commonjs",
"target": "ES5",
"outDir": "ts-built",
"rootDir": "src"
}
}
Please note that outDir
should be the path of the directory to receive compiled JS files, and rootDir
should be the path of the directory containing your source (.ts) files.
Open a terminal and run tsc -w
, it'll compile any .ts
file in src
directory into .js
and store them in ts-built
directory.
The answer given above can't solve my problem.So I change async into false to get the alert message.
jQuery.ajax({
type:"post",
dataType:"json",
async: false,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
alert("Data was succesfully captured");
},
});
I was facing same issue in VS 2019. if anyone still facing same issue then please make sure you have/do following things:
<!--ForExport data in iamge -->
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>
<!--ForExport data in iamge -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="../js/html2canvas.min.js"></script>
<table>
<tr>
<td valign="top">
<asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
<div id="dvTable" class="divsection2" style="width: 350px">
<asp:HiddenField ID="hfImageData" runat="server" />
<table width="100%">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Response.Clear();
Response.ContentType = "image/png";
Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
I found that you can do it like this:
.submit .btn input_x000D_
{_x000D_
padding:11px 28px 12px 14px;_x000D_
background:#004990;_x000D_
border:none;_x000D_
color:#fff;_x000D_
}_x000D_
_x000D_
.submit .btn_x000D_
{_x000D_
border:none;_x000D_
color:#fff;_x000D_
font-family: 'Open Sans', sans-serif;_x000D_
font-size:1em;_x000D_
min-width:96px;_x000D_
display:inline-block;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
.submit .btn:after_x000D_
{_x000D_
content:">";_x000D_
width:6px;_x000D_
height:17px;_x000D_
position:absolute;_x000D_
right:36px;_x000D_
color:#fff;_x000D_
top:7px;_x000D_
}
_x000D_
<div class="submit">_x000D_
<div class="btn">_x000D_
<input value="Send" type="submit" />_x000D_
</div>_x000D_
</div>
_x000D_
You need to have a div parent that takes the padding and the :after. The first parent needs to be relative and the second div should be absolute so you can set the position of the after.
A logical address is the address at which an item (memory cell, storage element, network host) appears to reside from the perspective of an executing application program.
might be surprised to know.. its PHP. read all about it here
This worked for me
python -m pip install cx_Oracle --upgrade
For details refer to the oracle quick start guide
https://cx-oracle.readthedocs.io/en/latest/installation.html#quick-start-cx-oracle-installation
This works on my Mac OS:
for n in `ipcs -b -m | egrep ^m | awk '{ print $2; }'`; do ipcrm -m $n; done
You could use a semaphore.
While the condition is not met, another thread acquires the semaphore.
Your thread would try to acquire it with acquireUninterruptibly()
or tryAcquire(int permits, long timeout, TimeUnit unit)
and would be blocked.
When the condition is met, the semaphore is also released and your thread would acquire it.
You could also try using a SynchronousQueue
or a CountDownLatch
.
You can add a unique index
to group_id
; if you are sure that group_id
is unique.
It can solve your case without modifying the query.
A late answer, but it has not been mentioned yet in the answers. Maybe it should complete the already comprehensive answers available. At least it did solve my case when I had to split a table with too many fields.
You can try bootstrap tooltips.
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
further reading here
int numberOfRecords = 0;
numberOfRecords = dtFoo.Select().Length;
MessageBox.Show(numberOfRecords.ToString());
The package libmysqlclient-dev is deprecated, so use the below command to fix it.
Package libmysqlclient-dev is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source
sudo apt-get install default-libmysqlclient-dev
I would recommend using <br />
for the following reasons:
1) Text and XML editors that highlight XML syntax in different colours will highlight properly with <br />
but this is not always the case if you use <br>
2) <br />
is backwards-compatible with XHTML and well-formed HTML (ie: XHTML) is often easier to validate for errors and debug
3) Some old parsers and some coding specs require the space before the closing slash (ie: <br />
instead of <br/>
) such as the WordPress Plugin Coding spec: http://make.wordpress.org/core/handbook/coding-standards/html/
I my experience, I have never come across a case where using <br />
is problematic, however, there are many cases where <br/>
or especially <br>
might be problematic in older browsers and tools.
A shorter alternative to the first solution given by Russ Cam would be:
$('#mySelect').val('');
This assumes you want to retain the list, but make it so that no option is selected.
If you wish to select a particular default value, just pass that value instead of an empty string.
$('#mySelect').val('someDefaultValue');
or to do it by the index of the option, you could do:
$('#mySelect option:eq(0)').attr('selected','selected'); // Select first option
Now you can make use of reduce
function and get the sum.
const object1 = { 'a': 1 , 'b': 2 , 'c':3 }_x000D_
_x000D_
console.log(Object.values(object1).reduce((a, b) => a + b, 0));
_x000D_
Ok, so here was my process:
keytool -list -v -keystore permanent.jks
- got me the alias.
keytool -export -alias alias_name -file certificate_name -keystore permanent.jks
- got me the certificate to import.
Then I could import it with the keytool:
keytool -import -alias alias_name -file certificate_name -keystore keystore location
As @Christian Bongiorno says the alias can't already exist in your keystore.
This solved my problem. I added this line before the request is made:
System.Net.ServicePointManager.Expect100Continue = false;
It seemed there were a proxy in the way of the server that not supported 100-continue behavior.
The Go Programming Language Specification
Appending to and copying slices
The function copy copies slice elements from a source src to a destination dst and returns the number of elements copied. Both arguments must have identical element type T and must be assignable to a slice of type []T. The number of elements copied is the minimum of len(src) and len(dst). As a special case, copy also accepts a destination argument assignable to type []byte with a source argument of a string type. This form copies the bytes from the string into the byte slice.
copy(dst, src []T) int copy(dst []byte, src string) int
tmp
needs enough room for arr
. For example,
package main
import "fmt"
func main() {
arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)
}
Output:
[1 2 3]
[1 2 3]
For those whose bat files are still not working in Windows 8+ Task Scheduler , one thing I would like to add to Ghazi's answer - after much suffering:
1) Under Actions, Choose "Create BASIC task", not "Create Task"
That did it for me, plus the other issues not to forget:
This worked without any need to trigger a command prompt.
(Sorry my rep is too low to add my Basic Task tip to Ghazi's comments)
for s in `cmd`; do echo $s; done
If cmd has a large output:
cmd | xargs -L1 echo
Try the PowerShell PowerToy... It adds a context menu item for Open PowerShell Here.
Or you could create a shortcut that opens PowerShell with the Start In folder being your Projects folder.
You will not be able to retrieve a plain text password from wordpress.
Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.
See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password
Adding to Brian Agnew's answer.
You can also do //div[@id='..' or @class='...]
and you can have parenthesized expressions inside //div[@id='..' and (@class='a' or @class='b')]
.
Just if someone is interested in another option:
content=( $(cat test.txt) )
a=0
while [ $a -le ${#content[@]} ]
do
echo ${content[$a]}
a=$[a+1]
done
Out of interest, this flags up one of R's weird multiple syntax inconsistencies. For example given a two-column data frame:
df <- data.frame(x=1, y=2)
This gives a data frame
subset(df, select=-y)
but this gives a vector
df[,-2]
This is all explained in ?[
but it's not exactly expected behaviour. Well at least not to me...
Try with mysql_fetch_assoc .It will returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. Furthermore, you have to add LIMIT 1 if you really expect single row.
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage' LIMIT 1");
$row = mysql_fetch_assoc($result);
echo $row['option_value'];
Another simplest way is to create a layout file containing the textview you want with textSize, textStyle, color etc preferred by you and then use it with the ArrayAdapter.
e.g. mytextview.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv"
android:textColor="@color/font_content"
android:padding="5sp"
android:layout_width="fill_parent"
android:background="@drawable/rectgrad"
android:singleLine="true"
android:gravity="center"
android:layout_height="fill_parent"/>
and then use it with your ArrayAdapter as usual like
ListView lst = new ListView(context);
String[] arr = {"Item 1","Item 2"};
ArrayAdapter<String> ad = new ArrayAdapter<String>(context,R.layout.mytextview,arr);
lst.setAdapter(ad);
This way you won't need to create a custom adapter for it.
For GOOGLE, GOOGLEDOWN, GOOGLEUP i.e similar kind of value you can try below code
$("#HowYouKnow option:contains('GOOGLE')").each(function () {
if($(this).html()=='GOOGLE'){
$(this).attr('selected', 'selected');
}
});
In this way,number of loop iteration can be reduced and will work in all situation.
Shawn Wildermuth has a nice guide here: https://wildermuth.com/2017/11/19/ASP-NET-Core-2-0-and-the-End-of-Bower
The article links to the gulpfile on GitHub where he's implemented the strategy in the article. You could just copy and paste most of the gulpfile contents into yours, but be sure to add the appropriate packages in package.json under devDependencies: gulp gulp-uglify gulp-concat rimraf merge-stream
...We don't have a newer version of MySQL yet, so I was able to do this (works only on UNIX):
host=maindb
echo "show full processlist\G" | mysql -h$host | grep -B 6 -A 1 Locked
The above will query for all locked sessions, and return the information and SQL that is involved.
...So- assuming you wanted to query for sessions that were sleeping:
host=maindb
echo "show full processlist\G" | mysql -h$host | grep -B 6 -A 1 Sleep
Or, assuming you needed to provide additional connection parameters for MySQL:
host=maindb
user=me
password=mycoolpassword
echo "show full processlist\G" | mysql -h$host -u$user -p$password | grep -B 6 -A 1 Locked
With a couple of tweaks, I'm sure a shell script could be easily created to query the processlist the way you want it.
i have solve this problem several times using the same steps :
1- Close Eclipse.
2- Restart your phone.
3- End adb.exe process in Task Manager (Windows). In Mac, force close in Activity Monitor.
4- Issue kill and start command in \platform-tools\
C:\sdk\platform-tools>adb kill-server
C:\sdk\platform-tools>adb start-server
5- If it says something like 'started successfully', you are good.
but now it's doesn't work cause i have an anti-virus called "Baidu", this program have run "Baidu ADB server", finally i turn this process off and retry above steps it's work properly.
Maybe it's a little bit late to add answer here. But I think this answer will help the later ones and especially those who don't want to use Android Studio.
Although the documents says that RecyclerView and CardView are part of v7 appcompat library. But as I tried and found, RecyclerView and CardView are actually depend on v7 appcompat library. So if you want to use RecyclerView or CardView, you need to add both v7 appcompat library and RecyclerView/CardView.
Referencing the link here, if you want to use CardView in your Eclipse android project, you need to import both v7 appcompat library and CardView into Eclipse workspace and make them as library projects. Then make CardView project depends on v7 appcompat library project and make your project depends on CardView project.
The alternative and easier solution that i also use is to create custom marker layout and convert it into a bitmap.
view_custom_marker.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_marker_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/marker_mask">
<ImageView
android:id="@+id/profile_image"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_horizontal"
android:contentDescription="@null"
android:src="@drawable/avatar" />
</FrameLayout>
Convert this view into bitmap by using the code below
private Bitmap getMarkerBitmapFromView(@DrawableRes int resId) {
View customMarkerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.view_custom_marker, null);
ImageView markerImageView = (ImageView) customMarkerView.findViewById(R.id.profile_image);
markerImageView.setImageResource(resId);
customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
customMarkerView.buildDrawingCache();
Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
Drawable drawable = customMarkerView.getBackground();
if (drawable != null)
drawable.draw(canvas);
customMarkerView.draw(canvas);
return returnedBitmap;
}
Add your custom marker in on Map ready callback.
@Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady() called with");
mGoogleMap = googleMap;
MapsInitializer.initialize(this);
addCustomMarker();
}
private void addCustomMarker() {
Log.d(TAG, "addCustomMarker()");
if (mGoogleMap == null) {
return;
}
// adding a marker on map with image from drawable
mGoogleMap.addMarker(new MarkerOptions()
.position(mDummyLatLng)
.icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(R.drawable.avatar))));
}
For more details please follow the link below
Another easy way:
//In your ListViewActivity:
public void refreshListView() {
listAdapter = new ListAdapter(this);
setListAdapter(listAdapter);
}
function post(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
Example:
post('url', {name: 'Johnny Bravo'});
There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.
The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.
Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.
I know this is too late but for those who are coming here for the first time, I'd like to post a solution. I have a float value index
and a string imgfile
and I had the same problem as you. This is how I fixed the issue
index = 1.0
imgfile = 'data/2.jpg'
out = '%.1f,%s' % (index,imgfile)
print out
The output is
1.0,data/2.jpg
You may modify this formatting example as per your convenience.
I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful
library(dplyr)
iris %>%
mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))
You also can use casting.
example:
string s;
int value = 3;
s.push_back((char)('0' + value));
This is probably considered dirty by some, but a very practical solution in case of github repositories is just to make a script, e.g. "git-ls":
#!/bin/sh
remote_url=${1:? "$0 requires URL as argument"}
curl -s $remote_url | grep js-directory-link | sed "s/.* title=\"\(.*\)\".*/\1/"
Make it executable and reachable of course: chmod a+x git-ls; sudo cp git-ls /usr/local/bin
. Now, you just run it as you wish:
git-ls https://github.com/mrquincle/aim-bzr
git-ls https://github.com/mrquincle/aim-bzr/tree/master/aim_modules
Also know that there is a git instaweb
utility for your local files. To have the ability to show files and have a server like that does in my opinion not destroy any of the inherent decentralized characteristics of git.
If you have multiple Java versions installed on your Mac, here's a quick way to switch the default version using Terminal. In this example, I am going to switch Java 10 to Java 8.
$ java -version
java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
10.0.1, x86_64: "Java SE 10.0.1" /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
1.8.0_171, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
Then, in your .bash_profile add the following.
# Java 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home
Now if you try java -version again, you should see the version you want.
$ java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)
The concept is storing persistent data across page loads for a web visitor. Cookies store it directly on the client. Sessions use a cookie as a key of sorts, to associate with the data that is stored on the server side.
It is preferred to use sessions because the actual values are hidden from the client, and you control when the data expires and becomes invalid. If it was all based on cookies, a user (or hacker) could manipulate their cookie data and then play requests to your site.
Edit: I don't think there is any advantage to using cookies, other than simplicity. Look at it this way... Does the user have any reason to know their ID#? Typically I would say no, the user has no need for this information. Giving out information should be limited on a need to know basis. What if the user changes his cookie to have a different ID, how will your application respond? It's a security risk.
Before sessions were all the rage, I basically had my own implementation. I stored a unique cookie value on the client, and stored my persistent data in the database along with that cookie value. Then on page requests I matched up those values and had my persistent data without letting the client control what that was.
If it's a framework-dependent application (the default), you run it by dotnet yourapp.dll
.
If it's a self-contained application, you run it using yourapp.exe
on Windows and ./yourapp
on Unix.
For more information about the differences between the two app types, see the .NET Core Application Deployment article on .Net Docs.
I would change the query in the following ways:
group by
.left outer join
to ensure that all data is available.count(<fieldname>)
you can eliminate the comparisons to is null
. This is important for the second and third calculated values.mde
table. These use mde.mdeid
.The following version follows your example by using union all
:
SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
SUM(TOTALMAILED) as TotalMailed,
SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
from MailDataExtract
where SentDate is not null
group by SentDate
) union all
(select MDE.ReturnMailDate AS ReceiptDate, 0,
COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by MDE.ReturnMailDate;
)
) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;
The following does something similar using full outer join
:
SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
from MailDataExtract
where SentDate is not null
group by cast(SentDate as date)
) sd full outer join
(select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by cast(MDE.ReturnMailDate as date)
) mde
on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;
Here's a different example that can't be rewritten without aliases ( can't GROUP BY DISTINCT
).
Imagine a table called purchases
that records purchases made by customers
at stores
, i.e. it's a many to many table and the software needs to know which customers have made purchases at more than one store:
SELECT DISTINCT customer_id, SUM(1)
FROM ( SELECT DISTINCT customer_id, store_id FROM purchases)
GROUP BY customer_id HAVING 1 < SUM(1);
..will break with the error Every derived table must have its own alias
. To fix:
SELECT DISTINCT customer_id, SUM(1)
FROM ( SELECT DISTINCT customer_id, store_id FROM purchases) AS custom
GROUP BY customer_id HAVING 1 < SUM(1);
( Note the AS custom
alias).
Using a collection initializer
From C# 3, you can use collection initializers to construct a List and populate it using a single expression. The following example constructs a Human and its ContactNumbers:
var human = new Human(1, "Address", "Name") {
ContactNumbers = new List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
}
}
Specializing the Human
constructor
You can change the constructor of the Human
class to provide a way to populate the ContactNumbers
property:
public class Human
{
public Human(int id, string address, string name, IEnumerable<ContactNumber> contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
public Human(int id, string address, string name, params ContactNumber[] contactNumbers) : this(id, address, name)
{
ContactNumbers = new List<ContactNumber>(contactNumbers);
}
}
// Using the first constructor:
List<ContactNumber> numbers = List<ContactNumber>() {
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
};
var human = new Human(1, "Address", "Name", numbers);
// Using the second constructor:
var human = new Human(1, "Address", "Name",
new ContactNumber(1),
new ContactNumber(2),
new ContactNumber(3)
);
Bottom line
Which alternative is a best practice? Or at least a good practice? You judge it! IMO, the best practice is to write the program as clearly as possible to anyone who has to read it. Using the collection initializer is a winner for me, in this case. With much less code, it can do almost the same things as the alternatives -- at least, the alternatives I gave...
Solution using CyclicBarrier
public class Downloader {
private CyclicBarrier barrier;
private final static int NUMBER_OF_DOWNLOADING_THREADS;
private DownloadingThread extends Thread {
private final String url;
public DownloadingThread(String url) {
super();
this.url = url;
}
@Override
public void run() {
barrier.await(); // label1
download(url);
barrier.await(); // label2
}
}
public void startDownload() {
// plus one for the main thread of execution
barrier = new CyclicBarrier(NUMBER_OF_DOWNLOADING_THREADS + 1); // label0
for (int i = 0; i < NUMBER_OF_DOWNLOADING_THREADS; i++) {
new DownloadingThread("http://www.flickr.com/someUser/pic" + i + ".jpg").start();
}
barrier.await(); // label3
displayMessage("Please wait...");
barrier.await(); // label4
displayMessage("Finished");
}
}
label0 - cyclic barrier is created with number of parties equal to the number of executing threads plus one for the main thread of execution (in which startDownload() is being executed)
label 1 - n-th DownloadingThread enters the waiting room
label 3 - NUMBER_OF_DOWNLOADING_THREADS have entered the waiting room. Main thread of execution releases them to start doing their downloading jobs in more or less the same time
label 4 - main thread of execution enters the waiting room. This is the 'trickiest' part of the code to understand. It doesn't matter which thread will enter the waiting room for the second time. It is important that whatever thread enters the room last ensures that all the other downloading threads have finished their downloading jobs.
label 2 - n-th DownloadingThread has finished its downloading job and enters the waiting room. If it is the last one i.e. already NUMBER_OF_DOWNLOADING_THREADS have entered it, including the main thread of execution, main thread will continue its execution only when all the other threads have finished downloading.
When you go to a stream url, you get offered a file. feed this file to a parser to extract the contents out of it. the file is (usually) plain text and contains the url to play.
My problem was my recycler view looked like this
<android.support.v7.widget.RecyclerView
android:id="@+id/chatview"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
</android.support.v7.widget.RecyclerView>
When it should have looked like this
<android.support.v7.widget.RecyclerView
android:id="@+id/chatview"
android:layout_width="395dp"
android:layout_height="525dp"
android:layout_marginTop="52dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="8dp"></android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
You are looking for dynamic_cast<B*>(pointer)
Notice that that @InjectMocks
are about to be deprecated
deprecate @InjectMocks and schedule for removal in Mockito 3/4
and you can follow @avp answer and link on:
Why You Should Not Use InjectMocks Annotation to Autowire Fields
Here's the code by Sinetheta converted to a jQuery plugin: Save below code to a js file.
$.fn.collapsible = function() {
$(this).addClass("ui-accordion ui-widget ui-helper-reset");
var headers = $(this).children("h3");
headers.addClass("accordion-header ui-accordion-header ui-helper-reset ui-state-active ui-accordion-icons ui-corner-all");
headers.append('<span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-s">');
headers.click(function() {
var header = $(this);
var panel = $(this).next();
var isOpen = panel.is(":visible");
if(isOpen) {
panel.slideUp("fast", function() {
panel.hide();
header.removeClass("ui-state-active")
.addClass("ui-state-default")
.children("span").removeClass("ui-icon-triangle-1-s")
.addClass("ui-icon-triangle-1-e");
});
}
else {
panel.slideDown("fast", function() {
panel.show();
header.removeClass("ui-state-default")
.addClass("ui-state-active")
.children("span").removeClass("ui-icon-triangle-1-e")
.addClass("ui-icon-triangle-1-s");
});
}
});
};
Refer it in your UI page and call similar to jQuery accordian call:
$("#accordion").collapsible();
Looks cleaner and avoids any classes to be added to the markup.
!python 'script.py'
replace script.py with your real file name, DON'T forget ''
For Windows, try:
NBTSTAT -A 10.100.3.104
or
ping -a 10.100.3.104
For Linux, try:
nmblookup -A 10.100.3.104
They are almost same.
Is this a local custom CSS file? Is this your website? Maybe you should clear your cache.
Also the last CSS declaration takes precedence.
path = r"C:\Users\mememe\Google Drive\Programs\Python\file.csv"
Closing the path in r"string" also solved this problem very well.
JavaScript's forEach works a bit different from how one might be used to from other languages for each loops. If reading on the MDN, it says that a function is executed for each of the elements in the array, in ascending order. To continue to the next element, that is, run the next function, you can simply return the current function without having it do any computation.
Adding a return and it will go to the next run of the loop:
var myArr = [1,2,3,4];_x000D_
_x000D_
myArr.forEach(function(elem){_x000D_
if (elem === 3) {_x000D_
return;_x000D_
}_x000D_
_x000D_
console.log(elem);_x000D_
});
_x000D_
Output: 1, 2, 4
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
First, disable the php5
module:
a2dismod php5
then, enable the php7
module:
a2enmod php7.0
Next, reload/restart the Apache service:
service apache2 restart
wrt the comment, you need to specify exact installed php-7.x version.
LINQ solution:
// Use the first value in group
var _people = personList
.GroupBy(p => p.FirstandLastName, StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
// Use the last value in group
var _people = personList
.GroupBy(p => p.FirstandLastName, StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key, g => g.Last(), StringComparer.OrdinalIgnoreCase);
If you prefer a non-LINQ solution then you could do something like this:
// Use the first value in list
var _people = new Dictionary<string, Person>(StringComparer.OrdinalIgnoreCase);
foreach (var p in personList)
{
if (!_people.ContainsKey(p.FirstandLastName))
_people[p.FirstandLastName] = p;
}
// Use the last value in list
var _people = new Dictionary<string, Person>(StringComparer.OrdinalIgnoreCase);
foreach (var p in personList)
{
_people[p.FirstandLastName] = p;
}
For me the solution was that my ddclient was not cronning properly...
A robust way to check if an object is an array in javascript is detailed here:
Here are two functions from the xa.js framework which I attach to a utils = {}
‘container’. These should help you properly detect arrays.
var utils = {};
/**
* utils.isArray
*
* Best guess if object is an array.
*/
utils.isArray = function(obj) {
// do an instanceof check first
if (obj instanceof Array) {
return true;
}
// then check for obvious falses
if (typeof obj !== 'object') {
return false;
}
if (utils.type(obj) === 'array') {
return true;
}
return false;
};
/**
* utils.type
*
* Attempt to ascertain actual object type.
*/
utils.type = function(obj) {
if (obj === null || typeof obj === 'undefined') {
return String (obj);
}
return Object.prototype.toString.call(obj)
.replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};
If you then want to check if an object is in an array, I would also include this code:
/**
* Adding hasOwnProperty method if needed.
*/
if (typeof Object.prototype.hasOwnProperty !== 'function') {
Object.prototype.hasOwnProperty = function (prop) {
var type = utils.type(this);
type = type.charAt(0).toUpperCase() + type.substr(1);
return this[prop] !== undefined
&& this[prop] !== window[type].prototype[prop];
};
}
And finally this in_array function:
function in_array (needle, haystack, strict) {
var key;
if (strict) {
for (key in haystack) {
if (!haystack.hasOwnProperty[key]) continue;
if (haystack[key] === needle) {
return true;
}
}
} else {
for (key in haystack) {
if (!haystack.hasOwnProperty[key]) continue;
if (haystack[key] == needle) {
return true;
}
}
}
return false;
}
MyServiceClient client = new MyServiceClient(binding, endpoint);
client.Endpoint.Address = new EndpointAddress("net.tcp://localhost/webSrvHost/service.svc");
client.Endpoint.Binding = new NetTcpBinding()
{
Name = "yourTcpBindConfig",
ReaderQuotas = XmlDictionaryReaderQuotas.Max,
ListenBacklog = 40 }
It's very easy to modify the uri in config or binding info in config. Is this what you want?
I know this is a late reply but maybe it can help someone.
Removing whitespace can be done by using the trim() function. After that if you want to sort the array with case sensitive manner you can just use:
Arrays.sort(yourArray);
and for case insensitive manner:
Arrays.sort(yourArray,String.CASE_INSENSITIVE_ORDER);
Hope this helps!
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MaxWidth="200"/>
</Grid.ColumnDefinitions>
<TextBox Background="Azure" Text="Hello" />
</Grid>
Use immediate children selector >
:
$('#tblOne > tbody > tr')
Description: Selects all direct child elements specified by "child" of elements specified by "parent".
It occurs when IIS is not being connected to SQL SERVER. For a solution, see this screenshot:
Reducing the image size before output results in something that looks sharper, in my case:
convert -density 300 a.pdf -resize 25% a.png
how about using the CSS :first-child pseudo-class:
.MyClass td:first-child { border: solid 1px red; }
The way you are doing it is indeed the recommended one (for Python 2.x).
The issue of whether the class is passed explicitly to super
is a matter of style rather than functionality. Passing the class to super
fits in with Python's philosophy of "explicit is better than implicit".
Using Visual Studio
This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).
Using Process Explorer
If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)
Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.
Programmatically
Check this SO question that explains how to do it.
I was able to solve this problem with these steps:
With jquery library
<button onclick="$('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">
Rebase doesn't happen in the background. "rebase in progress" means that you started a rebase, and the rebase got interrupted because of conflict. You have to resume the rebase
(git rebase --continue
) or abort it (git rebase --abort
).
As the error message from git rebase --continue
suggests, you asked git to apply a patch that results in an empty patch. Most likely, this means the patch was already applied and you want to drop it using git rebase --skip
.
In C, a "stream" is an abstraction; from the program's perspective it is simply a producer (input stream) or consumer (output stream) of bytes. It can correspond to a file on disk, to a pipe, to your terminal, or to some other device such as a printer or tty. The FILE
type contains information about the stream. Normally, you don't mess with a FILE
object's contents directly, you just pass a pointer to it to the various I/O routines.
There are three standard streams: stdin
is a pointer to the standard input stream, stdout
is a pointer to the standard output stream, and stderr
is a pointer to the standard error output stream. In an interactive session, the three usually refer to your console, although you can redirect them to point to other files or devices:
$ myprog < inputfile.dat > output.txt 2> errors.txt
In this example, stdin
now points to inputfile.dat
, stdout
points to output.txt
, and stderr
points to errors.txt
.
fprintf
writes formatted text to the output stream you specify.
printf
is equivalent to writing fprintf(stdout, ...)
and writes formatted text to wherever the standard output stream is currently pointing.
sprintf
writes formatted text to an array of char
, as opposed to a stream.
mkdirs()
also creates parent directories in the path this File
represents.
javadocs for mkdirs()
:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
javadocs for mkdir()
:
Creates the directory named by this abstract pathname.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
will yield false
for the first [and no dir will be created], and true
for the second, and you will have created non_existing_dir/someDir
INSERT tracking (userID, courseID, course, bookmark, course_date, posttest, post_attempts, post_score, post_date, complete, complete_date, exempted, exempted_date, exempted_reason, emailSent)
SELECT userID, 11, course, bookmark, course_date, posttest, post_attempts, post_score, post_date, complete, complete_date, exempted, exempted_date, exempted_reason, emailSent
FROM tracking WHERE courseID = 6 AND course_date > '08-01-2008'
Some firewalls do that if a connection is idle for x number of minutes. Some ISPs set their routers to do that for various reasons as well.
In this day and age, you'll need to gracefully handle (re-establish as needed) that condition.
Actually, the Robustness Diagrams (or Analysis Diagrams, as they are sometimes called) are just specialized Class Diagrams. They are a part of UML, and have been from the beginning (see Jacobson's book, The Unified Software Development Process - part of the "Three Amigos" series of books). The aforementioned book has a good definition of these three classes on pp 183-185.
function FastScrollUp()
{
window.scroll(0,0)
};
function FastScrollDown()
{
$i = document.documentElement.scrollHeight ;
window.scroll(0,$i)
};
var step = 20;
var h,t;
var y = 0;
function SmoothScrollUp()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, -step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollUp()},20);
};
function SmoothScrollDown()
{
h = document.documentElement.scrollHeight;
y += step;
window.scrollBy(0, step)
if(y >= h )
{clearTimeout(t); y = 0; return;}
t = setTimeout(function(){SmoothScrollDown()},20);
}
I'd suggest that fetching large XML files from the server should be avoided: the variable "xml" should used like a cache, and not as the data store itself.
In most scenarios, it is possible to examine the cache and see if you need to make a request to the server to get the data that you want. This will make your app lighter and faster.
cheers, jrh.
Like this: .
The .
means any character except newline (which sometimes is but often isn't included, check your regex flavour).
You can rewrite your expression as ^.{1,35}$
, which should match any line of length 1-35.
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
wll it looks like I found the answer, although I havent tested it yet
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
from this page https://github.com/eligrey/FileSaver.js
Check your imports. There could be two classes with the same name. Either from your code or from a library you are using. Personally that was the issue.
I was having this same issue - I am using Selectize with Rails and wanted to Selectize an association field - I wanted the name of the associated record to show up in the dropdown, but I needed the value of each option to be the id of the record, since Rails uses the value
to set associations.
I solved this by setting a coffeescript var of @valueAttr
to the id
of each object and a var of @dataAttr
to the name
of the record. Then I went through each option and set:
opts.labelField = @dataAttr
opts.valueField = @valueAttr
It helps to see the full diff: https://github.com/18F/C2/pull/912/files
In a few words: The constructor is called first, then any @FXML
annotated fields are populated, then initialize()
is called.
This means the constructor does not have access to @FXML
fields referring to components defined in the .fxml file, while initialize()
does have access to them.
Quoting from the Introduction to FXML:
[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.
You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.
Have you tried using System.Net.IPAddress just in case?
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1"); //127.0.0.1 as an example
The docs on Microsoft's site have a complete example which works fine on my machine.
This advice is a variant of the "be as unspecific as possible regarding inputs and as specific as possible regarding outputs" rule of thumb.
Usually if you have a method that takes a plain non-null value, you can map it over the Optional
, so the plain version is strictly more unspecific regarding inputs. However there are a bunch of possible reasons why you would want to require an Optional
argument nonetheless:
Optional
Optional
if the given value is emptyOptional
is so awesome that whoever uses your API should be required to learn about it ;-)strtok
maintains a static, internal reference pointing to the next available token in the string; if you pass it a NULL pointer, it will work from that internal reference.
This is the reason strtok
isn't re-entrant; as soon as you pass it a new pointer, that old internal reference gets clobbered.
Here's a quick way I've found to make a two dimensional array.
function createArray(x, y) {
return Array.apply(null, Array(x)).map(e => Array(y));
}
You can easily turn this function into an ES5 function as well.
function createArray(x, y) {
return Array.apply(null, Array(x)).map(function(e) {
return Array(y);
});
}
Why this works: the new Array(n)
constructor creates an object with a prototype of Array.prototype
and then assigns the object's length
, resulting in an unpopulated array. Due to its lack of actual members we can't run the Array.prototype.map
function on it.
However, when you provide more than one argument to the constructor, such as when you do Array(1, 2, 3, 4)
, the constructor will use the arguments
object to instantiate and populate an Array
object correctly.
For this reason, we can use Array.apply(null, Array(x))
, because the apply
function will spread the arguments into the constructor. For clarification, doing Array.apply(null, Array(3))
is equivalent to doing Array(null, null, null)
.
Now that we've created an actual populated array, all we need to do is call map
and create the second layer (y
).
To me the best way is -
Hope this will help .
Package distance includes Levenshtein distance:
import distance
distance.levenshtein("lenvestein", "levenshtein")
# 3
You can trigger some js automatically on an IMG element using onerror, and no src.
<img src onerror='alert()'>
If url contains a certen string, redirect to index.php . You need to match against the %{REQUEST_URI} variable to check if the url contains a certen string.
To redirect example.com/foo/bar to /index.php if the uri contains bar anywhere in the uri string , you can use this :
RewriteEngine on
RewriteCond %{REQUEST_URI} bar
RewriteRule ^ /index.php [L,R]
There is another way that I found works, you have to build a class that derives from your Product class and use that. For instance:
public class PseudoProduct : Product { }
public IQueryable<Product> GetProducts(int categoryID)
{
return from p in db.Products
where p.CategoryID== categoryID
select new PseudoProduct() { Name = p.Name};
}
Not sure if this is "allowed", but it works.
Try It :
DECLARE @String NVARCHAR(100)
SET @String = '12354851'
SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))
Take a look at incredible Bluetooth Serial class that has onResume()
ability that helped me so much.
I hope this helps ;)
You can do this by wrapping the page contents in a div with the following id styling applied:
<style>
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -60px;
}
</style>
<div id="wrap">
<!-- Your page content here... -->
</div>
Worked for me.
The first part is similar to Constantine, you can get the boolean of which rows are empty*:
In [21]: ne = (df1 != df2).any(1)
In [22]: ne
Out[22]:
0 False
1 True
2 True
dtype: bool
Then we can see which entries have changed:
In [23]: ne_stacked = (df1 != df2).stack()
In [24]: changed = ne_stacked[ne_stacked]
In [25]: changed.index.names = ['id', 'col']
In [26]: changed
Out[26]:
id col
1 score True
2 isEnrolled True
Comment True
dtype: bool
Here the first entry is the index and the second the columns which has been changed.
In [27]: difference_locations = np.where(df1 != df2)
In [28]: changed_from = df1.values[difference_locations]
In [29]: changed_to = df2.values[difference_locations]
In [30]: pd.DataFrame({'from': changed_from, 'to': changed_to}, index=changed.index)
Out[30]:
from to
id col
1 score 1.11 1.21
2 isEnrolled True False
Comment None On vacation
* Note: it's important that df1
and df2
share the same index here. To overcome this ambiguity, you can ensure you only look at the shared labels using df1.index & df2.index
, but I think I'll leave that as an exercise.
Using only CSS it is not possible at all to add links :) It is not possible to link a background-image, nor a part of it, using HTML/CSS. However, it can be staged using this method:
<div class="wrapWithBackgroundImage">
<a href="#" class="invisibleLink"></a>
</div>
.wrapWithBackgroundImage {
background-image: url(...);
}
.invisibleLink {
display: block;
left: 55px; top: 55px;
position: absolute;
height: 55px width: 55px;
}
Windows uses a different epoch and time units: see Convert Windows Filetime to second in Unix/Linux
What std::time() returns on Windows is (as yet) unknown to me (;-))
Just open the R(software) and copy and paste
system("defaults write org.R-project.R force.LANG en_US.UTF-8")
Hope this will work fine or use the other method
open(on mac): Utilities/Terminal copy and paste
defaults write org.R-project.R force.LANG en_US.UTF-8
and close both terminal and R
and reopen R
.
You could use the ready to use Url Rewrite Filter with a rule like this one:
<rule>
<from>^/Check_License/Dir_My_App/Dir_ABC/My_Obj_([0-9]+)$</from>
<to>/Check_License?Contact_Id=My_Obj_$1</to>
</rule>
Check the Examples for more... examples.
Use a RegExp:
if (!/ral/i.test(referrer)) {
...
}
Or, use .toLowerCase()
:
if (referrer.toLowerCase().indexOf("ral") == -1)
You can always find out the location of the tnsnames.ora file being used by running TNSPING to check connectivity (9i or later):
C:\>tnsping dev
TNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 08-JAN-2009 12:48:38
Copyright (c) 1997, 2005, Oracle. All rights reserved.
Used parameter files:
C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = XXX)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = DEV)))
OK (30 msec)
C:\>
Sometimes, the problem is with the entry you made in tnsnames.ora, not that the system can't find it. That said, I agree that having a tns_admin environment variable set is a Good Thing, since it avoids the inevitable issues that arise with determining exactly which tnsnames file is being used in systems with multiple oracle homes.
I work on PHP and have used Swagger 2.0 to document the APIs. The Swagger Document is created on the fly (at least that is what I use in PHP). The document is generated in the JSON format.
Sample document
{
"swagger": "2.0",
"info": {
"title": "Company Admin Panel",
"description": "Converting the Magento code into core PHP and RESTful APIs for increasing the performance of the website.",
"contact": {
"email": "[email protected]"
},
"version": "1.0.0"
},
"host": "localhost/cv_admin/api",
"schemes": [
"http"
],
"paths": {
"/getCustomerByEmail.php": {
"post": {
"summary": "List the details of customer by the email.",
"consumes": [
"string",
"application/json",
"application/x-www-form-urlencoded"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "email",
"in": "body",
"description": "Customer email to ge the data",
"required": true,
"schema": {
"properties": {
"id": {
"properties": {
"abc": {
"properties": {
"inner_abc": {
"type": "number",
"default": 1,
"example": 123
}
},
"type": "object"
},
"xyz": {
"type": "string",
"default": "xyz default value",
"example": "xyz example value"
}
},
"type": "object"
}
}
}
}
],
"responses": {
"200": {
"description": "Details of the customer"
},
"400": {
"description": "Email required"
},
"404": {
"description": "Customer does not exist"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
},
"/getCustomerById.php": {
"get": {
"summary": "List the details of customer by the ID",
"parameters": [
{
"name": "id",
"in": "query",
"description": "Customer ID to get the data",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "Details of the customer"
},
"400": {
"description": "ID required"
},
"404": {
"description": "Customer does not exist"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
},
"/getShipmentById.php": {
"get": {
"summary": "List the details of shipment by the ID",
"parameters": [
{
"name": "id",
"in": "query",
"description": "Shipment ID to get the data",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "Details of the shipment"
},
"404": {
"description": "Shipment does not exist"
},
"400": {
"description": "ID required"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
}
},
"definitions": {
}
}
This can be imported into Postman as follow.
You can also use 'Import From Link'. Here paste the URL which generates the JSON format of the APIs from the Swagger or any other API Document tool.
This is my Document (JSON) generation file. It's in PHP. I have no idea of JAVA along with Swagger.
<?php
require("vendor/autoload.php");
$swagger = \Swagger\scan('path_of_the_directory_to_scan');
header('Content-Type: application/json');
echo $swagger;
How about
$('select>option:eq(3)').attr('selected', true);
example at http://www.jsfiddle.net/gaby/CWvwn/
for modern versions of jquery you should use the .prop()
instead of .attr()
$('select>option:eq(3)').prop('selected', true);
example at http://jsfiddle.net/gaby/CWvwn/1763/
Create Function [dbo].[DistanceKM]
(
@Lat1 Float(18),
@Lat2 Float(18),
@Long1 Float(18),
@Long2 Float(18)
)
Returns Float(18)
AS
Begin
Declare @R Float(8);
Declare @dLat Float(18);
Declare @dLon Float(18);
Declare @a Float(18);
Declare @c Float(18);
Declare @d Float(18);
Set @R = 6367.45
--Miles 3956.55
--Kilometers 6367.45
--Feet 20890584
--Meters 6367450
Set @dLat = Radians(@lat2 - @lat1);
Set @dLon = Radians(@long2 - @long1);
Set @a = Sin(@dLat / 2)
* Sin(@dLat / 2)
+ Cos(Radians(@lat1))
* Cos(Radians(@lat2))
* Sin(@dLon / 2)
* Sin(@dLon / 2);
Set @c = 2 * Asin(Min(Sqrt(@a)));
Set @d = @R * @c;
Return @d;
End
GO
Usage:
select dbo.DistanceKM(37.848832506474, 37.848732506474, 27.83935546875, 27.83905546875)
Outputs:
0,02849639
You can change @R parameter with commented floats.
You can use COPY. You need to specify the directory explicitly. It won't be created by itself
COPY go /usr/local/go
Reference: Docker CP reference
You can do in this way also
var prop = $('.someProperty').closest('tr');
If the number of tr is in array
$.each(prop , function() {
var gotTD = $(this).find('td:eq(1)');
});
Based on fireant's excellent answer above, here is the alpha blending but a bit more human legible. You may need to swap 1.0-alpha
and alpha
depending on which direction you're merging (mine is swapped from fireant's answer).
o* == s_img.*
b* == b_img.*
for c in range(0,3):
alpha = s_img[oy:oy+height, ox:ox+width, 3] / 255.0
color = s_img[oy:oy+height, ox:ox+width, c] * (1.0-alpha)
beta = l_img[by:by+height, bx:bx+width, c] * (alpha)
l_img[by:by+height, bx:bx+width, c] = color + beta
You can use one of Java template engines. I love this method because you are separating your logic from the view.
Java 8+:
<dependency>
<groupId>com.github.spullara.mustache.java</groupId>
<artifactId>compiler</artifactId>
<version>0.9.6</version>
</dependency>
Java 6/7:
<dependency>
<groupId>com.github.spullara.mustache.java</groupId>
<artifactId>compiler</artifactId>
<version>0.8.18</version>
</dependency>
Example template file:
{{#items}}
Name: {{name}}
Price: {{price}}
{{#features}}
Feature: {{description}}
{{/features}}
{{/items}}
Might be powered by some backing code:
public class Context {
List<Item> items() {
return Arrays.asList(
new Item("Item 1", "$19.99", Arrays.asList(new Feature("New!"), new Feature("Awesome!"))),
new Item("Item 2", "$29.99", Arrays.asList(new Feature("Old."), new Feature("Ugly.")))
);
}
static class Item {
Item(String name, String price, List<Feature> features) {
this.name = name;
this.price = price;
this.features = features;
}
String name, price;
List<Feature> features;
}
static class Feature {
Feature(String description) {
this.description = description;
}
String description;
}
}
And would result in:
Name: Item 1
Price: $19.99
Feature: New!
Feature: Awesome!
Name: Item 2
Price: $29.99
Feature: Old.
Feature: Ugly.
I found hitting ctrl+break while the macro wasn't running fixed the problem.
dynamic_cast
is known to be inefficient. It traverses up the inheritance hierarchy, and it is the only solution if you have multiple levels of inheritance, and need to check if an object is an instance of any one of the types in its type hierarchy.
But if a more limited form of instanceof
that only checks if an object is exactly the type you specify, suffices for your needs, the function below would be a lot more efficient:
template<typename T, typename K>
inline bool isType(const K &k) {
return typeid(T).hash_code() == typeid(k).hash_code();
}
Here's an example of how you'd invoke the function above:
DerivedA k;
Base *p = &k;
cout << boolalpha << isType<DerivedA>(*p) << endl; // true
cout << boolalpha << isType<DerivedB>(*p) << endl; // false
You'd specify template type A
(as the type you're checking for), and pass in the object you want to test as the argument (from which template type K
would be inferred).
Try one of these:
gdb -p 12271
gdb /path/to/exe 12271
gdb /path/to/exe
(gdb) attach 12271
With the release of the latest Android Support Library (rev 22.2.0) we've got a Design Support Library and as part of this a new view called NavigationView. So instead of doing everything on our own with the ScrimInsetsFrameLayout
and all the other stuff we simply use this view and everything is done for us.
Add the Design Support Library
to your build.gradle
file
dependencies {
// Other dependencies like appcompat
compile 'com.android.support:design:22.2.0'
}
Add the NavigationView
to your DrawerLayout
:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"> <!-- this is important -->
<!-- Your contents -->
<android.support.design.widget.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/navigation_items" /> <!-- The items to display -->
</android.support.v4.widget.DrawerLayout>
Create a new menu-resource in /res/menu
and add the items and icons you wanna display:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_home"
android:icon="@drawable/ic_action_home"
android:title="Home" />
<item
android:id="@+id/nav_example_item_1"
android:icon="@drawable/ic_action_dashboard"
android:title="Example Item #1" />
</group>
<item android:title="Sub items">
<menu>
<item
android:id="@+id/nav_example_sub_item_1"
android:title="Example Sub Item #1" />
</menu>
</item>
</menu>
Init the NavigationView and handle click events:
public class MainActivity extends AppCompatActivity {
NavigationView mNavigationView;
DrawerLayout mDrawerLayout;
// Other stuff
private void init() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.nav_home:
// TODO - Do something
break;
// TODO - Handle other items
}
return true;
}
});
}
}
Be sure to set android:windowDrawsSystemBarBackgrounds
and android:statusBarColor
in values-v21
otherwise your Drawer won`t be displayed "under" the StatusBar
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Other attributes like colorPrimary, colorAccent etc. -->
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
Add a Header to the NavigationView. For this simply create a new layout and add app:headerLayout="@layout/my_header_layout"
to the NavigationView.
colorPrimary
attributetextColorPrimary
attributetextColorSecondary
attributeYou can also check the example app by Chris Banes which highlights the NavigationView along with the other new views that are part of the Design Support Library (like the FloatingActionButton, TextInputLayout, Snackbar, TabLayout etc.)
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
Here you go...
- (NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
NSUInteger location = 0;
unichar charBuffer[[strtoremove length]];
[strtoremove getCharacters:charBuffer];
int i = 0;
for(i = [strtoremove length]; i >0; i--) {
NSCharacterSet* charSet = [NSCharacterSet whitespaceCharacterSet];
if(![charSet characterIsMember:charBuffer[i - 1]]) {
break;
}
}
return [strtoremove substringWithRange:NSMakeRange(location, i - location)];
}
So now just call it. Supposing you have a string that has spaces on the front and spaces on the end and you just want to remove the spaces on the end, you can call it like this:
NSString *oneTwoThree = @" TestString ";
NSString *resultString;
resultString = [self removeEndSpaceFrom:oneTwoThree];
resultString
will then have no spaces at the end.
A). I never have and never will trust any tool which purports to produce code without the user coding, which goes double where it's a graphical tool.
B). I've never had any problem with this with Facebook Connect. It's all still plain old JavaScript code running in a browser and undefined===undefined
wherever you are.
In short, you need to provide evidence that your object.x really really was undefined and not null or otherwise, because I believe it is impossible for what you're describing to actually be the case - no offence :) - I'd put money on the problem existing in the Tersus code.
May be include Jquery Widget first, then Draggable? I guess that will solve the problem.....
To copy conditional formatting from google spreadsheet (doc1) to another (doc2) you need to do the following:
I use zsh on a Mac, and I can post multi-line commit messages within double quotes ("). Basically I keep typing and pressing return for new lines, but the message isn't sent to Git until I close the quotes and return.
As answered by Roman Starkov, plink
needs to add the host to it's cache.
For people using Git Extensions:
(replace with the actual paths)
<the path to plink/klink.exe> <address to the server>
e.g.
%ProgramData%\chocolatey\lib\kitty\tools\klink.exe codebasehq.com
Note: Make sure to use the same plink/klink that Git Extensions is using!
Sorry for late post but still for info,I also facing same problem so I Used updated version of chromedriver ie.2.28 for updated chrome browser ie. 55 to 57 which resolved my problem.
According to the Python os module documentation os.popen has been deprecated since Python 2.6.
I think the solution for modern Python is to use check_output() from the subprocess module.
From the subprocess Python documentation:
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) Run command with arguments and return its output as a byte string.
If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.
If you run through the following code in Python 2.7 (or later):
import subprocess
try:
print subprocess.check_output(["ping", "-n", "2", "-w", "2", "1.1.1.1"])
except subprocess.CalledProcessError, e:
print "Ping stdout output:\n", e.output
You should see an output that looks something like this:
Ping stdout output:
Pinging 1.1.1.1 with 32 bytes of data:
Request timed out.
Request timed out.
Ping statistics for 1.1.1.1:
Packets: Sent = 2, Received = 0, Lost = 2 (100% loss),
The e.output string can be parsed to suit the OPs needs.
If you want the returncode or other attributes, they are in CalledProccessError as can be seen by stepping through with pdb
(Pdb)!dir(e)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__',
'__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__',
'__unicode__', '__weakref__', 'args', 'cmd', 'message', 'output', 'returncode']
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.
A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.
I'd probably use a LEFT JOIN
, which will return rows even if there's no match, and then you can select only the rows with no match by checking for NULL
s.
So, something like:
SELECT V.*
FROM voter V LEFT JOIN elimination E ON V.id = E.voter_id
WHERE E.voter_id IS NULL
Whether that's more or less efficient than using a subquery depends on optimization, indexes, whether its possible to have more than one elimination per voter, etc.
A Web Reference allows you to communicate with any service based on any technology that implements the WS-I Basic Profile 1.1, and exposes the relevant metadata as WSDL. Internally, it uses the ASMX communication stack on the client's side.
A Service Reference allows you to communicate with any service based on any technology that implements any of the many protocols supported by WCF (including but not limited to WS-I Basic Profile). Internally, it uses the WCF communication stack on the client side.
Note that both these definitions are quite wide, and both include services not written in .NET.
It is perfectly possible (though not recommended) to add a Web Reference that points to a WCF service, as long as the WCF endpoint uses basicHttpBinding
or some compatible custom variant.
It is also possible to add a Service Reference that points to an ASMX service. When writing new code, you should always use a Service Reference simply because it is more flexible and future-proof.
1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:
Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:
urn:oasis:names:tc:SAML:1.0: urn:oasis:names:tc:SAML:1.1: urn:oasis:names:tc:SAML:2.0:
You should put the print function in your view-details.php file and call it once the file is loaded, by either using
<body onload="window.print()">
or
$(document).ready(function () {
window.print();
});
With the recent update to melt.data.table
, we can now melt multiple columns. With that, we can do:
require(data.table) ## 1.9.5
melt(setDT(df), id=1:2, measure=patterns("^Q3.2", "^Q3.3"),
value.name=c("Q3.2", "Q3.3"), variable.name="loop_number")
# id time loop_number Q3.2 Q3.3
# 1: 1 2009-01-01 1 -0.433978480 0.41227209
# 2: 2 2009-01-02 1 -0.567995351 0.30701144
# 3: 3 2009-01-03 1 -0.092041353 -0.96024077
# 4: 4 2009-01-04 1 1.137433487 0.60603396
# 5: 5 2009-01-05 1 -1.071498263 -0.01655584
# 6: 6 2009-01-06 1 -0.048376809 0.55889996
# 7: 7 2009-01-07 1 -0.007312176 0.69872938
You can get the development version from here.
While a few of these answers will get you in the ballpark, you cannot do what you're trying to do with arbitrary dates for SqlServer 2005 and earlier because of daylight savings time. Using the difference between the current local and current UTC will give me the offset as it exists today. I have not found a way to determine what the offset would have been for the date in question.
That said, I know that SqlServer 2008 provides some new date functions that may address that issue, but folks using an earlier version need to be aware of the limitations.
Our approach is to persist UTC and perform the conversion on the client side where we have more control over the conversion's accuracy.
I believe the correct way of doing it would be to use query builder expressions:
$now = new DateTimeImmutable();
$thirtyDaysAgo = $now->sub(new \DateInterval("P30D"));
$qb->select('e')
->from('Entity','e')
->add('where', $qb->expr()->between(
'e.datefield',
':from',
':to'
)
)
->setParameters(array('from' => $thirtyDaysAgo, 'to' => $now));
http://docs.doctrine-project.org/en/latest/reference/query-builder.html#the-expr-class
Edit: The advantage this method has over any of the other answers here is that it's database software independent - you should let Doctrine handle the date type as it has an abstraction layer for dealing with this sort of thing.
If you do something like adding a string variable in the form 'Y-m-d' it will break when it goes to a database platform other than MySQL, for example.
Some days I faced the same problem. Reason was different sizes arrays.
PriorityQueue<Integer> lowers = new PriorityQueue<>((o1, o2) -> -1 * o1.compareTo(o2));
As an alternative to virtualenv, you can use anaconda.
On Linux, to create an environment with python 2.7:
conda create -n python2p7 python=2.7
source activate python2p7
To deactivate it, you do:
source deactivate
It is possible to install other package inside your environment.
You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");
You can confirm this by printing out the string to see that it turns out identical to the first case.
Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string
, which would make it look perhaps like this:
$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
mysql_real_escape_string($prefix));
$query = mysql_query($sql);
Note that inside the first argument of sprintf
the percent sign needs to be doubled to end up appearing once in the result.
Is it not possible in your case to do the AND on several matching results? in pseudocode
regexp_match(pattern1, data) && regexp_match(pattern2, data) && ...
Use below code to generate files on fly..
<? //Generate text file on the fly
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=savethis.txt");
// do your Db stuff here to get the content into $content
print "This is some text...\n";
print $content;
?>
I have a default my-default.ini file in the root and there is one server configuration:
[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
So that does not tell me the path.
The best way is to connect to the database and run this query:
SHOW VARIABLES WHERE Variable_Name LIKE "%dir" ;
Here's the result of that:
basedir C:\Program Files (x86)\MySQL\MySQL Server 5.6\
character_sets_dir C:\Program Files (x86)\MySQL\MySQL Server 5.6\share\charsets\
datadir C:\ProgramData\MySQL\MySQL Server 5.6\Data\
innodb_data_home_dir
innodb_log_group_home_dir .\
lc_messages_dir C:\Program Files (x86)\MySQL\MySQL Server 5.6\share\
plugin_dir C:\Program Files (x86)\MySQL\MySQL Server 5.6\lib\plugin\
slave_load_tmpdir C:\Windows\SERVIC~2\NETWOR~1\AppData\Local\Temp
tmpdir C:\Windows\SERVIC~2\NETWOR~1\AppData\Local\Temp
If you want to see all the parameters configured for the database execute this:
SHOW VARIABLES;
The storage_engine variable will tell you if you're using InnoDb or MyISAM.
A .mat-file is a compressed binary file. It is not possible to open it with a text editor (except you have a special plugin as Dennis Jaheruddin says). Otherwise you will have to convert it into a text file (csv for example) with a script. This could be done by python for example: Read .mat files in Python.
It's hard to say what your question is, but there are some alternatives.
If you mean to literally execute a request using the ICMP ping protocol, you can get an ICMP library and execute the ping request directly. Google "Python ICMP" to find things like this icmplib. You might want to look at scapy, also.
This will be much faster than using os.system("ping " + ip )
.
If you mean to generically "ping" a box to see if it's up, you can use the echo protocol on port 7.
For echo, you use the socket library to open the IP address and port 7. You write something on that port, send a carriage return ("\r\n"
) and then read the reply.
If you mean to "ping" a web site to see if the site is running, you have to use the http protocol on port 80.
For or properly checking a web server, you use urllib2 to open a specific URL. (/index.html
is always popular) and read the response.
There are still more potential meaning of "ping" including "traceroute" and "finger".
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
$wpdb->insert( $table_name, array('column_name_1'=>'hello', 'other'=> 123), array( '%s', '%d' ) );
So, you'd better to sanitize values - ALWAYS CONSIDER THE SECURITY.
As described by Herb Sutter and Scott Meyers, prefer non-friend non-member functions to member functions, to help increase encapsulation.
In some cases, like C++ streams, you won't have the choice and must use non-member functions.
But still, it does not mean you have to make these functions friends of your classes: These functions can still acess your class through your class accessors. If you succeed in writting those functions this way, then you won.
I believe the examples you gave in your question are wrong. For example;
ostream & operator<<(ostream &os) {
return os << paragraph;
}
I can't even start to think how this method could work in a stream.
Here are the two ways to implement the << and >> operators.
Let's say you want to use a stream-like object of type T.
And that you want to extract/insert from/into T the relevant data of your object of type Paragraph.
The first being as functions:
// T << Paragraph
T & operator << (T & p_oOutputStream, const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return p_oOutputStream ;
}
// T >> Paragraph
T & operator >> (T & p_oInputStream, const Paragraph & p_oParagraph)
{
// do the extraction of p_oParagraph
return p_oInputStream ;
}
The second being as methods:
// T << Paragraph
T & T::operator << (const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return *this ;
}
// T >> Paragraph
T & T::operator >> (const Paragraph & p_oParagraph)
{
// do the extraction of p_oParagraph
return *this ;
}
Note that to use this notation, you must extend T's class declaration. For STL objects, this is not possible (you are not supposed to modify them...).
Here are the prototypes of the same << and >> operators for C++ streams.
Note that is case of streams, as you can't modify the C++ stream, you must implement the functions. Which means something like:
// OUTPUT << Paragraph
template <typename charT, typename traits>
std::basic_ostream<charT,traits> & operator << (std::basic_ostream<charT,traits> & p_oOutputStream, const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return p_oOutputStream ;
}
// INPUT >> Paragraph
template <typename charT, typename traits>
std::basic_istream<charT,traits> & operator >> (std::basic_istream<charT,traits> & p_oInputStream, const CMyObject & p_oParagraph)
{
// do the extract of p_oParagraph
return p_oInputStream ;
}
The following code will work only for char-based streams.
// OUTPUT << A
std::ostream & operator << (std::ostream & p_oOutputStream, const Paragraph & p_oParagraph)
{
// do the insertion of p_oParagraph
return p_oOutputStream ;
}
// INPUT >> A
std::istream & operator >> (std::istream & p_oInputStream, const Paragraph & p_oParagraph)
{
// do the extract of p_oParagraph
return p_oInputStream ;
}
Rhys Ulerich commented about the fact the char-based code is but a "specialization" of the generic code above it. Of course, Rhys is right: I don't recommend the use of the char-based example. It is only given here because it's simpler to read. As it is only viable if you only work with char-based streams, you should avoid it on platforms where wchar_t code is common (i.e. on Windows).
Hope this will help.
You can use the assign
function:
df = df.assign(industry='yyy')
Should you want to resort to using a plug-in, malihu-custom-scrollbar-plugin, could do the job. It performs an actual scroll, not just a jump. You can even specify the speed/momentum of scroll. It also lets you set up a menu (list of links to scroll to), which have their CSS changed based on whether the anchors-to-scroll-to are in viewport, and other useful features.
There are demo on the author's site and let our company site serve as a real-world example too.
There's no reason to new (on the heap) when you can allocate on the stack (unless for some reason you've got a small stack and want to use the heap.
You might want to consider using a shared_ptr (or one of its variants) from the standard library if you do want to allocate on the heap. That'll handle doing the delete for you once all references to the shared_ptr have gone out of existance.
I have a strong feeling that at the root of this "XY problem" the OP wanted just implode()
function.
If you are writing in C++ -- it is a way better to use data structures from standard library such as vector.
C-style arrays are very error-prone, and should be avoided whenever possible.
OK, two steps to this - first is to write a function that does the translation you want - I've put an example together based on your pseudo-code:
def label_race (row):
if row['eri_hispanic'] == 1 :
return 'Hispanic'
if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
return 'Two Or More'
if row['eri_nat_amer'] == 1 :
return 'A/I AK Native'
if row['eri_asian'] == 1:
return 'Asian'
if row['eri_afr_amer'] == 1:
return 'Black/AA'
if row['eri_hawaiian'] == 1:
return 'Haw/Pac Isl.'
if row['eri_white'] == 1:
return 'White'
return 'Other'
You may want to go over this, but it seems to do the trick - notice that the parameter going into the function is considered to be a Series object labelled "row".
Next, use the apply function in pandas to apply the function - e.g.
df.apply (lambda row: label_race(row), axis=1)
Note the axis=1 specifier, that means that the application is done at a row, rather than a column level. The results are here:
0 White
1 Hispanic
2 White
3 White
4 Other
5 White
6 Two Or More
7 White
8 Haw/Pac Isl.
9 White
If you're happy with those results, then run it again, saving the results into a new column in your original dataframe.
df['race_label'] = df.apply (lambda row: label_race(row), axis=1)
The resultant dataframe looks like this (scroll to the right to see the new column):
lname fname rno_cd eri_afr_amer eri_asian eri_hawaiian eri_hispanic eri_nat_amer eri_white rno_defined race_label
0 MOST JEFF E 0 0 0 0 0 1 White White
1 CRUISE TOM E 0 0 0 1 0 0 White Hispanic
2 DEPP JOHNNY NaN 0 0 0 0 0 1 Unknown White
3 DICAP LEO NaN 0 0 0 0 0 1 Unknown White
4 BRANDO MARLON E 0 0 0 0 0 0 White Other
5 HANKS TOM NaN 0 0 0 0 0 1 Unknown White
6 DENIRO ROBERT E 0 1 0 0 0 1 White Two Or More
7 PACINO AL E 0 0 0 0 0 1 White White
8 WILLIAMS ROBIN E 0 0 1 0 0 0 White Haw/Pac Isl.
9 EASTWOOD CLINT E 0 0 0 0 0 1 White White