When you're using Data Type: int you can select the row which you want to get autoincremented and go to the column properties tag. There you can set the identity to 'yes'. The starting value for autoincrement can also be edited there. Hope I could help ;)
1st add font.ttf file on font Folder. Then Add this line in onCreate method
Typeface typeface = ResourcesCompat.getFont(getApplicationContext(), R.font.myfont);
mytextView.setTypeface(typeface);
And here is my xml
<TextView
android:id="@+id/idtext1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:gravity="center"
android:text="My Text"
android:textColor="#000"
android:textSize="10sp"
/>
There's no one answer. The standard defines minimum ranges. An int must be able to hold at least 65535. Most modern compilers however allow ints to be 32-bit values. Additionally, there's nothing preventing multiple types from having the same capacity (e.g. int and long).
That being said, the standard does say in your particular case:
0 ? +18446744073709551615
as the range for unsigned long long int.
Further reading: http://en.wikipedia.org/wiki/C_variable_types_and_declarations#Size
Try using the below query.
SELECT REPLACE(CONVERT(VARCHAR(11),GETDATE(),6), ' ','/');
Result: 20/Jun/13
SELECT REPLACE(CONVERT(VARCHAR(11),GETDATE(),106), ' ','/');
Result: 20/Jun/2013
You can't have async methods with ref
or out
parameters.
Lucian Wischik explains why this is not possible on this MSDN thread: http://social.msdn.microsoft.com/Forums/en-US/d2f48a52-e35a-4948-844d-828a1a6deb74/why-async-methods-cannot-have-ref-or-out-parameters
As for why async methods don't support out-by-reference parameters? (or ref parameters?) That's a limitation of the CLR. We chose to implement async methods in a similar way to iterator methods -- i.e. through the compiler transforming the method into a state-machine-object. The CLR has no safe way to store the address of an "out parameter" or "reference parameter" as a field of an object. The only way to have supported out-by-reference parameters would be if the async feature were done by a low-level CLR rewrite instead of a compiler-rewrite. We examined that approach, and it had a lot going for it, but it would ultimately have been so costly that it'd never have happened.
A typical workaround for this situation is to have the async method return a Tuple instead. You could re-write your method as such:
public async Task Method1()
{
var tuple = await GetDataTaskAsync();
int op = tuple.Item1;
int result = tuple.Item2;
}
public async Task<Tuple<int, int>> GetDataTaskAsync()
{
//...
return new Tuple<int, int>(1, 2);
}
Put the title in its own span.
<span id="dialog_title_span">'+dialog_title+'</span>
$('#dialog_title_span').text("new dialog title");
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.window.width',0)
profile.set_preference('browser.window.height',0)
profile.update_preferences()
write this code into setup part of your test code, before the: webdriver.Firefox()
line.
To use $variables
inside your calc()
of the height property:
HTML:
<div></div>
SCSS:
$a: 4em;
div {
height: calc(#{$a} + 7px);
background: #e53b2c;
}
In this code you just need to call this in your button click.
private void list_paired_Devices() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
ArrayList<String> devices = new ArrayList<>();
for (BluetoothDevice bt : pairedDevices) {
devices.add(bt.getName() + "\n" + bt.getAddress());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(bluetooth.this, android.R.layout.simple_list_item_1, devices);
emp.setAdapter(arrayAdapter);
}
You could use cast
(as int) after replacing NaN
with 0
,
data_df = df.withColumn("Plays", df.call_time.cast('float'))
I found that when within a Miniconda3 environment I had to run:
conda deactivate
Neither deactivate
nor source deactivate
worked for me.
I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:
It's a real short VB.Net app: I can post code if any one is interested.
To get the text content
document.getElementById ( "tdid" ).innerText
or
document.getElementById ( "tdid" ).textContent
var tdElem = document.getElementById ( "tdid" );
var tdText = tdElem.innerText | tdElem.textContent;
If you can use jQuery then you can use
$("#tdid").text();
To get the HTML content
var tdElem = document.getElementById ( "tdid" );
var tdText = tdElem.innerHTML;
in jQuery
$("#tdid").html();
The answer you want, "1317427200", is achieved if your reference months are January and October. If so, the dates you are looking for are 1970-JAN-01 and 2011-OCT-01, correct?
Then the problem are these numbers you are using for your months.
See, if you check the Calendar API documentation or even the constants provided in there ("Calendar.JANUARY", "Calendar.FEBRUARY" and so on), you'll discover that months start at 0 (being January).
So checking your code, you are passing february and november, which would result in "1317510000".
Best regards.
There is no standard, so there is no guarantee. With that said, its common for the sitemap to be self labeled and on the root, like this:
example.com/sitemap.xml
Case is sensitive on some servers, so keep that in mind. If its not there, look in the robots file on the root:
example.com/robots.txt
If you don't see it listed in the robots file head to Google and search this:
site:example.com filetype:xml
This will limit the results to XML files on your target domain. At this point its trial-and-error and based on the specifics of the website you are working with. If you get several pages of results from the Google search phrase above then try to limit the results further:
filetype:xml site:example.com inurl:sitemap
or
filetype:xml site:example.com inurl:products
If you still can't find it you can right-click > "View Source"
and do a search (aka: "control find" or Ctrl + F
) for .xml
to see if there is a reference to it in the code.
Taking a uniform random variable as the value of RGB may generate a large amount of gray, white, and black, which are often not the colors we want.
The cv::applyColorMap
can easily generate a random RGB palette, and you can choose a favorite color map from the list here
Example for C++11:
#include <algorithm>
#include <numeric>
#include <random>
#include <opencv2/opencv.hpp>
std::random_device rd;
std::default_random_engine re(rd());
// Generating randomized palette
cv::Mat palette(1, 255, CV_8U);
std::iota(palette.data, palette.data + 255, 0);
std::shuffle(palette.data, palette.data + 255, re);
cv::applyColorMap(palette, palette, cv::COLORMAP_JET);
// ...
// Picking random color from palette and drawing
auto randColor = palette.at<cv::Vec3b>(i % palette.cols);
cv::rectangle(img, cv::Rect(0, 0, 100, 100), randColor, -1);
Example for Python3:
import numpy as np, cv2
palette = np.arange(0, 255, dtype=np.uint8).reshape(1, 255, 1)
palette = cv2.applyColorMap(palette, cv2.COLORMAP_JET).squeeze(0)
np.random.shuffle(palette)
# ...
rand_color = tuple(palette[i % palette.shape[0]].tolist())
cv2.rectangle(img, (0, 0), (100, 100), rand_color, -1)
If you don't need so many colors, you can just cut the palette to the desired length.
put it your input field
ref={(el) => this.myInput = el}
JPanel pnlCircle = new JPanel() {
public void paintComponent(Graphics g) {
int X=100;
int Y=100;
int d=200;
g.drawOval(X, Y, d, d);
}
};
you can change X,Y coordinates and radius what you want.
I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.
I had the same problem. I looked into my complied dll with reflector and have seen that the name of the resource was not right. I renamed and it looks fine now.
function random(number) {_x000D_
return Math.floor(Math.random() * (number+1));_x000D_
}_x000D_
setInterval(() => {_x000D_
const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';//rgb value (0-255,0-255,0-255)_x000D_
document.body.style.backgroundColor = rndCol; _x000D_
}, 1000);
_x000D_
<script src="test.js"></script>_x000D_
it changes background color in every 1 second (written as 1000 in JS)
_x000D_
The underlying type of a variadic method function(Object... args)
is function(Object[] args)
. Sun added varargs in this manner to preserve backwards compatibility.
So you should just be able to prepend extraVar
to args
and call String.format(format, args)
.
The easiest solution I found, is given on python.org devguide:
sudo apt-get build-dep python3.6
If that package is not available for your system, try reducing the minor version until you find a package that is available in your system’s package manager.
I tried explaining details, on my blog.
I don't think that the Python tutorial diagram (cited in various other answers) is good as this suggestion works for positive stride, but does not for a negative stride.
This is the diagram:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
From the diagram, I expect a[-4,-6,-1]
to be yP
but it is ty
.
>>> a = "Python"
>>> a[2:4:1] # as expected
'th'
>>> a[-4:-6:-1] # off by 1
'ty'
What always work is to think in characters or slots and use indexing as a half-open interval -- right-open if positive stride, left-open if negative stride.
This way, I can think of a[-4:-6:-1]
as a(-6,-4]
in interval terminology.
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
+---+---+---+---+---+---+---+---+---+---+---+---+
| P | y | t | h | o | n | P | y | t | h | o | n |
+---+---+---+---+---+---+---+---+---+---+---+---+
-6 -5 -4 -3 -2 -1 0 1 2 3 4 5
null
is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL
value) and hence cannot accurately represent the JSON null
. So they will sometimes represent it as an empty array.
Whether null
is a legal value in that particular element of that particular API is entirely up to the API designer.
<html>
<head>
<script type="text/javascript">
function GetTimeZoneOffset() {
var d = new Date()
var gmtOffSet = -d.getTimezoneOffset();
var gmtHours = Math.floor(gmtOffSet / 60);
var GMTMin = Math.abs(gmtOffSet % 60);
var dot = ".";
var retVal = "" + gmtHours + dot + GMTMin;
document.getElementById('<%= offSet.ClientID%>').value = retVal;
}
</script>
</head>
<body onload="GetTimeZoneOffset()">
<asp:HiddenField ID="clientDateTime" runat="server" />
<asp:HiddenField ID="offSet" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</body>
</html>
key point to notice here is,body has an attribute onload
. Just give it a function name and that function will be called on page load.
Alternatively, you can also call the function on page load event like this
<html>
<head>
<script type="text/javascript">
window.onload = load();
function load() {
var d = new Date()
var gmtOffSet = -d.getTimezoneOffset();
var gmtHours = Math.floor(gmtOffSet / 60);
var GMTMin = Math.abs(gmtOffSet % 60);
var dot = ".";
var retVal = "" + gmtHours + dot + GMTMin;
document.getElementById('<%= offSet.ClientID%>').value = retVal;
}
</script>
</head>
<body >
<asp:HiddenField ID="clientDateTime" runat="server" />
<asp:HiddenField ID="offSet" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></body>
</body>
</html>
In my case, I had made a stupid typo in the shebang.
So in case someone else on with fat fingers stumbles across this question:
Whoops: #!/usr/local/bin ruby
I meant to write: #!/usr/bin/env ruby
The vague error ZSH gives sent me down the wrong path:
ZSH: zsh: permission denied: ./foo.rb
Bash: bash: ./foo.rb: /usr/local/bin: bad interpreter: Permission denied
You have some code you want to run. Normally, when you call it you are then waiting for it to be finished before you carry on (which can cause your app to go grey/produce a spinning time for a cursor).
An alternative method is to run this code in parallel and carry on with your own work. But what if your original code needs to do different things depending on the response from the code it called? Well, in that case you can pass in the name/location of the code you want it to call when it's done. This is a "call back".
Normal code: Ask for Information->Process Information->Deal with results of Processing->Continue to do other things.
With callbacks: Ask for Information->Process Information->Continue to do other things. And at some later point->Deal with results of Processing.
select column_name, data_type, character_maximum_length
from information_schema.columns
where table_name = 'myTable'
This code also helps in, "To Detect Numbers in Given String" when numbers found it stops its execution.
function hasDigitFind(_str_) {
this._code_ = 10; /*When empty string found*/
var _strArray = [];
if (_str_ !== '' || _str_ !== undefined || _str_ !== null) {
_strArray = _str_.split('');
for(var i = 0; i < _strArray.length; i++) {
if(!isNaN(parseInt(_strArray[i]))) {
this._code_ = -1;
break;
} else {
this._code_ = 1;
}
}
}
return this._code_;
}
After trying almost every key on my keyboard:
C:\Users\Tim>cd ^
Mehr? Desktop
C:\Users\Tim\Desktop>
So it seems to be the ^ key.
"I'm specifically looking to target the index, just like the first example - if it's possible."
No, it isn't possible.
The closest you can get is to get an Array of the object's keys, and use that:
var keys = Object.keys( obj );
...but there's no guarantee that the keys will be returned in the order you defined. So it could end up looking like:
keys[ 0 ]; // 'evenmore'
keys[ 1 ]; // 'something'
@Gadde - your answer was very helpful. Thank you! I needed a "Maps"-like zoom for a div and was able to produce the feel I needed with your post. My criteria included the need to have the click repeat and continue to zoom out/in with each click. Below is my final result.
var currentZoom = 1.0;
$(document).ready(function () {
$('#btn_ZoomIn').click(
function () {
$('#divName').animate({ 'zoom': currentZoom += .1 }, 'slow');
})
$('#btn_ZoomOut').click(
function () {
$('#divName').animate({ 'zoom': currentZoom -= .1 }, 'slow');
})
$('#btn_ZoomReset').click(
function () {
currentZoom = 1.0
$('#divName').animate({ 'zoom': 1 }, 'slow');
})
});
If you intend to change A, B, C.... you see high above the columns, you can not. You can hide A, B, C...: Button Office(top left) Excel Options(bottom) Advanced(left) Right looking: Display options fot this worksheet: Select the worksheet(eg. Sheet3) Uncheck: Show column and row headers Ok
Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).
(I don't see anything obviously wrong with the code you have posted above)
Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?
Class creat:
namespace WindowsFormsApplication1
{
class select
{
public string Text { get; set; }
public string Value { get; set; }
}
}
Form1 Codes:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
List<select> sl = new List<select>();
sl.Add(new select() { Text = "", Value = "" });
sl.Add(new select() { Text = "AAA", Value = "aa" });
sl.Add(new select() { Text = "BBB", Value = "bb" });
comboBox1.DataSource = sl;
comboBox1.DisplayMember = "Text";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
select sl1 = comboBox1.SelectedItem as select;
t1.Text = Convert.ToString(sl1.Value);
}
}
}
This typically occurs when there is unintended output from the script before you start the session. With your current code, you could try to use output buffering to solve it.
try adding a call to the ob_start();
function at the very top of your script and ob_end_flush();
at the very end of the document.
int i;
for (i = 0; i < ARRAY_SIZE; ++i)
{
myArray[i] = VALUE;
}
I think this is better than
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5...
incase the size of the array changes.
Mutable default arguments don't generally do what you want. Instead, try this:
class Node:
def __init__(self, wordList=None, adjacencyList=None):
if wordList is None:
self.wordList = []
else:
self.wordList = wordList
if adjacencyList is None:
self.adjacencyList = []
else:
self.adjacencyList = adjacencyList
http://cfaj.freeshell.org/shell/cus-faq-2.html#11
How do I get the exit code of cmd1
in cmd1|cmd2
First, note that cmd1
exit code could be non-zero and still don't mean an error. This happens for instance in
cmd | head -1
You might observe a 141 (or 269 with ksh93) exit status of cmd1
, but it's because cmd
was interrupted by a SIGPIPE signal when head -1
terminated after having read one line.
To know the exit status of the elements of a pipeline
cmd1 | cmd2 | cmd3
a. with Z shell (zsh
):
The exit codes are provided in the pipestatus special array.
cmd1
exit code is in $pipestatus[1]
, cmd3
exit code in
$pipestatus[3]
, so that $?
is always the same as
$pipestatus[-1]
.
b. with Bash:
The exit codes are provided in the PIPESTATUS
special array.
cmd1
exit code is in ${PIPESTATUS[0]}
, cmd3
exit code in
${PIPESTATUS[2]}
, so that $?
is always the same as
${PIPESTATUS: -1}
.
...
For more details see Z shell.
object Enum.Parse(System.Type enumType, string value, bool ignoreCase);
So if you had an enum named mood it would look like this:
enum Mood
{
Angry,
Happy,
Sad
}
// ...
Mood m = (Mood) Enum.Parse(typeof(Mood), "Happy", true);
Console.WriteLine("My mood is: {0}", m.ToString());
Angular 2.0.0 Final:
I have found that using a ViewChild
setter is most reliable way to set the initial form control focus:
@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
if (_input !== undefined) {
setTimeout(() => {
this._renderer.invokeElementMethod(_input.nativeElement, "focus");
}, 0);
}
}
The setter is first called with an undefined
value followed by a call with an initialized ElementRef
.
Working example and full source here: http://plnkr.co/edit/u0sLLi?p=preview
Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).
UPDATE for Angular 4+
Renderer
has been deprecated in favor of Renderer2
, but Renderer2
does not have the invokeElementMethod
. You will need to access the DOM directly to set the focus as in input.nativeElement.focus()
.
I'm still finding that the ViewChild setter approach works best. When using AfterViewInit
I sometimes get read property 'nativeElement' of undefined
error.
@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
if (_input !== undefined) {
setTimeout(() => { //This setTimeout call may not be necessary anymore.
_input.nativeElement.focus();
}, 0);
}
}
Using Javascript
<div id="mydiv" style="width:200px;background:white" onmouseover="this.style.background='gray';" onmouseout="this.style.background='white';">
Jack and Jill went up the hill
To fetch a pail of water.
Jack fell down and broke his crown,
And Jill came tumbling after.
</div>
Thanks to tmoschou for adding this comment to an outdated accepted answer:
As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content field will
result in unpredictable output.
For more details see this and an explanation
Original answer:
You can use the copy
module, with the parameter content=
.
I gave the exact same answer here: Write variable to a file in Ansible
In your case, it looks like you want this variable written to a local logfile, so you could combine it with the local_action
notation:
- local_action: copy content={{ foo_result }} dest=/path/to/destination/file
I understand there has already been an accepted answer, but wanted to post what I am using in case it can help anyone. I get the direction like cliphex
with the mousewheel event but with support for Firefox. It's useful doing it this way in case you are doing something like locking scroll and can't get the current scroll top.
See a live version here.
$(window).on('mousewheel DOMMouseScroll', function (e) {
var direction = (function () {
var delta = (e.type === 'DOMMouseScroll' ?
e.originalEvent.detail * -40 :
e.originalEvent.wheelDelta);
return delta > 0 ? 0 : 1;
}());
if(direction === 1) {
// scroll down
}
if(direction === 0) {
// scroll up
}
});
Try using an a link element and click it with javascriipt
<a id="SimulateOpenLink" href="#" target="_blank" rel="noopener noreferrer"></a>
and the script
function openURL(url) {
document.getElementById("SimulateOpenLink").href = url
document.getElementById("SimulateOpenLink").click()
}
Use it like this
//do stuff
var id = 123123141;
openURL("/api/user/" + id + "/print") //this open webpage bypassing pop-up blocker
openURL("https://www.google.com") //Another link
Depending on what you want to do, you can try:
browser.waitForAngular();
or
btnLoginEl.click().then(function() {
// do some stuff
});
to solve the promise. It would be better if you can do that in the beforeEach
.
NB: I noticed that the expect() waits for the promise inside (i.e. getCurrentUrl) to be solved before comparing.
Have you looked at all the addresses in the return, discard the ones of family InterNetworkV6 and retain only the IPv4 ones?
You have to find the right user that needs to use temp folder. In my computer I follow the above link and find the special folder c:\inetpub, that iis use to execute her web services. I check what users could use these folder and find something like these: computername\iis_isusrs
The main issue comes when you try to add it to all permit on temp folder I was going to properties, security tab, edit button, add user button then i put iis_isusrs
and "check names" button
It doesn´t find anything The reason is the in my case it looks ( windows 2008 r2 iis 7 ) on pdgs.local location You have to go to "Select Users or Groups" form, click on Advanced button, click on Locations button and will see a specific hierarchy
So when you try to add an user, its search name on pdgs.local. You have to select computername and click ok, Click on "Find Now"
Look for IIS_IUSRS on Name(RDN) column, click ok. So we go back to "Select Users or Groups" form with new and right user underline
click ok, allow full control, and click ok again.
That´s all folks, Hope it helps,
Jose from Moralzarzal ( Madrid )
No, there is no "easy" way. Your best bet would be to do a loop where you first check each previous sibling, then move to the parent node and all of its previous siblings.
You'll need to break the selector into two, 1 to check if the current node could be the top level node in your selector, and 1 to check if it's descendants match.
Edit: This might as well be a plugin. You can use this with any selector in any HTML:
(function($) {
$.fn.closestPrior = function(selector) {
selector = selector.replace(/^\s+|\s+$/g, "");
var combinator = selector.search(/[ +~>]|$/);
var parent = selector.substr(0, combinator);
var children = selector.substr(combinator);
var el = this;
var match = $();
while (el.length && !match.length) {
el = el.prev();
if (!el.length) {
var par = el.parent();
// Don't use the parent - you've already checked all of the previous
// elements in this parent, move to its previous sibling, if any.
while (par.length && !par.prev().length) {
par = par.parent();
}
el = par.prev();
if (!el.length) {
break;
}
}
if (el.is(parent) && el.find(children).length) {
match = el.find(children).last();
}
else if (el.find(selector).length) {
match = el.find(selector).last();
}
}
return match;
}
})(jQuery);
You can use the StringUtils class in Apache Commons:
StringUtils.substringAfterLast(one, "-");
Great blog post on the subject
Extracting the Key Hash from .p12 key
Great and simple hexadecimal editor for mac: HexFiend
OpenSSL should be preinstalled on mac, and here is the link for Windows version.
freopen("/my/newstdin", "r", stdin);
freopen("/my/newstdout", "w", stdout);
freopen("/my/newstderr", "w", stderr);
... do your stuff
freopen("/dev/stdin", "r", stdin);
...
...
This peaks the needle on my round-peg-square-hole-o-meter, what are you trying to accomplish?
Edit:
Remember that stdin, stdout and stderr are file descriptors 0, 1 and 2 for every newly created process. freopen() should keep the same fd's, just assign new streams to them.
So, a good way to ensure that this is actually doing what you want it to do would be:
printf("Stdout is descriptor %d\n", fileno(stdout));
freopen("/tmp/newstdout", "w", stdout);
printf("Stdout is now /tmp/newstdout and hopefully still fd %d\n",
fileno(stdout));
freopen("/dev/stdout", "w", stdout);
printf("Now we put it back, hopefully its still fd %d\n",
fileno(stdout));
I believe this is the expected behavior of freopen(), as you can see, you're still only using three file descriptors (and associated streams).
This would override any shell redirection, as there would be nothing for the shell to redirect. However, its probably going to break pipes. You might want to be sure to set up a handler for SIGPIPE, in case your program finds itself on the blocking end of a pipe (not FIFO, pipe).
So, ./your_program --stdout /tmp/stdout.txt --stderr /tmp/stderr.txt should be easily accomplished with freopen() and keeping the same actual file descriptors. What I don't understand is why you'd need to put them back once changing them? Surely, if someone passed either option, they would want it to persist until the program terminated?
The >
and <
are transitive properties, so if a > b
and b > c
, then a > c
. So you can
int a=10, b=6, c=4, d=21, e=4;
int maxNum = a;
int maxNum = max(b, maxNum);
int maxNum = max(c, maxNum);
int maxNum = max(d, maxNum);
int maxNum = max(e, maxNum);
Here is the simplest solution:
a= input("Choose the option\n")
if(int(a)):
print (a);
else:
print("Try Again")
In file php.ini you should try this for all errors:
error_reporting = off
You can use WMI to get CPU percentage information. You can even log into a remote computer if you have the correct permissions. Look at http://www.csharphelp.com/archives2/archive334.html to get an idea of what you can accomplish.
Also helpful might be the MSDN reference for the Win32_Process namespace.
See also a CodeProject example How To: (Almost) Everything In WMI via C#.
I know this is an old question, but I wanted to make an answer of my own. here is another way to do this if you "really" want to add to the end of the list instead of using list.add(str)
you can do it this way, but I don't recommend.
String[] items = new String[]{"Hello", "World"};
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, items);
int endOfList = list.size();
list.add(endOfList, "This goes end of list");
System.out.println(Collections.singletonList(list));
this is the 'Compact' way of adding the item to the end of list. here is a safer way to do this, with null checking and more.
String[] items = new String[]{"Hello", "World"};
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, items);
addEndOfList(list, "Safer way");
System.out.println(Collections.singletonList(list));
private static void addEndOfList(List<String> list, String item){
try{
list.add(getEndOfList(list), item);
} catch (IndexOutOfBoundsException e){
System.out.println(e.toString());
}
}
private static int getEndOfList(List<String> list){
if(list != null) {
return list.size();
}
return -1;
}
Heres another way to add items to the end of list, happy coding :)
You can also size another element so that it covers the links (using the right z-index): That will "eat" the clicks.
(We discovered this by accident because we had an issue with suddenly inactive links due to "responsive" design causing a H2 to cover them when the browser window was mobile-sized.)
Simple you can use bellow class.
.nopadmar {_x000D_
padding: 0 !important;_x000D_
margin: 0 !important;_x000D_
}
_x000D_
<div class="container-fluid">_x000D_
<div class="row">_x000D_
<div class="col-md-6 nopadmar">Your Content<div>_x000D_
<div class="col-md-6 nopadmar">Your Content<div>_x000D_
</div>_x000D_
</div>
_x000D_
In VS2008, the doc entry that seems the most useful is:
Windows Presentation Foundation Building a WPF Application (WPF)
ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/wpf_conceptual/html/a58696fd-bdad-4b55-9759-136dfdf8b91c.htm
ApplicationDefinition Identifies the XAML markup file that contains the application definition (a XAML markup file whose root element is Application). ApplicationDefinition is mandatory when Install is true and OutputType is winexe. A WPF application and, consequently, an MSBuild project can only have one ApplicationDefinition.
Page Identifies a XAML markup file whose content is converted to a binary format and compiled into an assembly. Page items are typically implemented in conjunction with a code-behind class.
The most common Page items are XAML files whose top-level elements are one of the following:
Window (System.Windows..::.Window).
Page (System.Windows.Controls..::.Page).
PageFunction (System.Windows.Navigation..::.PageFunction<(Of <(T>)>)).
ResourceDictionary (System.Windows..::.ResourceDictionary).
FlowDocument (System.Windows.Documents..::.FlowDocument).
UserControl (System.Windows.Controls..::.UserControl).
Resource Identifies a resource file that is compiled into an application assembly. As mentioned earlier, UICulture processes Resource items.
Content Identifies a content file that is distributed with an application. Metadata that describes the content file is compiled into the application (using AssemblyAssociatedContentFileAttribute).
You could use the isNaN Function. It returns true if the data is not a number. That would be something like that:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (isNaN(x)) // this is the code I need to change
{
alert("Must input numbers");
return false;
}
}
Note: isNan considers 10.2 as a valid number.
This is also possible with Notepad++:
Check Bookmark line (if there is no Mark tab update to the current version).
Enter your search term and click Mark All
Now go to the menu Search → Bookmark → Remove Bookmarked lines
Done.
You could try like this, for single array
irb(main):019:0> a = ["item 1", "item 2", "item 3", "item 4"]
=> ["item 1", "item 2", "item 3", "item 4"]
irb(main):020:0> Hash[*a]
=> {"item 1"=>"item 2", "item 3"=>"item 4"}
for array of array
irb(main):022:0> a = [[1, 2], [3, 4]]
=> [[1, 2], [3, 4]]
irb(main):023:0> Hash[*a.flatten]
=> {1=>2, 3=>4}
I just had the same problem and...
declare @userId uniqueidentifier
set @userId = (select top 1 UserId from aspnet_Users)
or even shorter:
declare @userId uniqueidentifier
SELECT TOP 1 @userId = UserId FROM aspnet_Users
To just get the list of the changed files with the paths, use
svn diff --summarize -r<rev-of-commit>:<rev-of-commit - 1>
For example:
svn diff --summarize -r42:41
should result in something like
M path/to/modifiedfile
A path/to/newfile
Following on @Arne Mertz's answer, as of C++11 std::ios_base::failure
inherits from system_error
(see http://www.cplusplus.com/reference/ios/ios_base/failure/), which contains both the error code and message that strerror(errno)
would return.
std::ifstream f;
// Set exceptions to be thrown on failure
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
f.open(fileName);
} catch (std::system_error& e) {
std::cerr << e.code().message() << std::endl;
}
This prints No such file or directory.
if fileName
doesn't exist.
Example:
Process process = Process.Start(@"Data\myApp.exe");
int id = process.Id;
Process tempProc = Process.GetProcessById(id);
this.Visible = false;
tempProc.WaitForExit();
this.Visible = true;
String name = "admin";
char[] ch = name.toString().toCharArray(); //it will read and store each character of String and store into char[].
for(int i=0; i<ch.length; i++)
{
System.out.println(ch[i]+
"-->"+
(int)ch[i]); //this will print both character and its value
}
I'm not sure if you need perfomance for doing this, but here is the fastest method to convert byte[] to hex string that I can think of :
static readonly char[] hexchar = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static string HexStr(byte[] data, int offset, int len, bool space = false)
{
int i = 0, k = 2;
if (space) k++;
var c = new char[len * k];
while (i < len)
{
byte d = data[offset + i];
c[i * k] = hexchar[d / 0x10];
c[i * k + 1] = hexchar[d % 0x10];
if (space && i < len - 1) c[i * k + 2] = ' ';
i++;
}
return new string(c, 0, c.Length);
}
update
If you use the router you can use lifecycle hooks or resolvers to delay navigation until the data arrived. https://angular.io/guide/router#milestone-5-route-guards
To load data before the initial rendering of the root component APP_INITIALIZER
can be used How to pass parameters rendered from backend to angular2 bootstrap method
original
When console.log(this.ev)
is executed after this.fetchEvent();
, this doesn't mean the fetchEvent()
call is done, this only means that it is scheduled. When console.log(this.ev)
is executed, the call to the server is not even made and of course has not yet returned a value.
Change fetchEvent()
to return a Promise
fetchEvent(){
return this._apiService.get.event(this.eventId).then(event => {
this.ev = event;
console.log(event); // Has a value
console.log(this.ev); // Has a value
});
}
change ngOnInit()
to wait for the Promise
to complete
ngOnInit() {
this.fetchEvent().then(() =>
console.log(this.ev)); // Now has value;
}
This actually won't buy you much for your use case.
My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>
and in ngOnInit()
isDataAvailable:boolean = false;
ngOnInit() {
this.fetchEvent().then(() =>
this.isDataAvailable = true); // Now has value;
}
By default Vagrant uses a generated private key to login, you can try this:
ssh -l ubuntu -p 2222 -i .vagrant/machines/default/virtualbox/private_key 127.0.0.1
I caused this error to happen when I redacted my Path environment variable. After editing, I accidentally added Path=
to the beginning of the path string. With such a malformed path variable, I was unable to run XCopy at the command line (no command or file not found), and Visual Studio refused to run post-build step, citing error with code 9009.
XCopy commonly resides in C:\Windows\System32. Once the Path environment variable allowed XCopy to get resolved at DOS prompt, Visual Studio built my solution well.
To anyone reading this in 2017, this is how I've done something similar.
DELETE pets, pets_activities FROM pets inner join pets_activities
on pets_activities.id = pets.id WHERE pets.`order` > :order AND
pets.`pet_id` = :pet_id
Generally, to delete rows from multiple tables, the syntax I follow is given below. The solution is based on an assumption that there is some relation between the two tables.
DELETE table1, table2 FROM table1 inner join table2 on table2.id = table1.id
WHERE [conditions]
If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest
android:exported="true"
Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.
finish();
The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class
in the code, so compile will fail.
I searched on the web and found something like this below, and it works well.
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);
You can also use the setClassName method:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();
You can also pass the values from one app to another app :
Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
launchIntent.putExtra("AppID", "MY-CHILD-APP1");
launchIntent.putExtra("UserID", "MY-APP");
launchIntent.putExtra("Password", "MY-PASSWORD");
startActivity(launchIntent);
finish();
} else {
Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}
OAuth 2.0 spec doesn't define the part. But there could be couple of options:
When resource server gets the token in the Authz Header then it calls the validate/introspect API on Authz server to validate the token. Here Authz server might validate it either from using DB Store or verifying the signature and certain attributes. As part of response, it decodes the token and sends the actual data of token along with remaining expiry time.
Authz Server can encrpt/sign the token using private key and then publickey/cert can be given to Resource Server. When resource server gets the token, it either decrypts/verifies signature to verify the token. Takes the content out and processes the token. It then can either provide access or reject.
getActivity()
is used for fragment
. For activity
, wherever you can use this
, you can replace the this
in fragment
in similar cases with getActivity()
.
Just write in your Custom ArrayAdaper
this code:
private List<Cart_items> customListviewList ;
refreshEvents(carts);
public void refreshEvents(List<Cart_items> events)
{
this.customListviewList.clear();
this.customListviewList.addAll(events);
notifyDataSetChanged();
}
Another Solution in Case You Don't Have Control Over Dynamic Content
This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).
Wrap up Your Content
Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.
<div class="selector">
<grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>
Use Angular Injector
You can use the following code to get a reference to $compile if you don't have one.
$(".selector").each(function () {
var content = $(this);
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
});
});
Summary
The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.
One Caveat of the previous code
If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.
Here is the way to remedy it:
Replace the prevous code snippet with the following overload.
...
angular.element(document).injector().invoke(
[
"$compile", function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
}
]);
...
This caused a lot of grief for me before I pieced it together.
Below code is for getting data from online server using GET method and okHTTP library for android kotlin...
Log.e("Main",response.body!!.string())
in above line !! is the thing using which you can get the json from response body
val client = OkHttpClient()
val request: Request = Request.Builder()
.get()
.url("http://172.16.10.126:8789/test/path/jsonpage")
.addHeader("", "")
.addHeader("", "")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle this
Log.e("Main","Try again latter!!!")
}
override fun onResponse(call: Call, response: Response) {
// Handle this
Log.e("Main",response.body!!.string())
}
})
Looks like you are using maven (src/main/java)
. In this case put the applicationContext.xml
file in the src/main/resources
directory. It will be copied in the classpath directory and you should be able to access it with
@ContextConfiguration("/applicationContext.xml")
From the Spring-Documentation: A plain path, for example "context.xml", will be treated as a classpath resource from the same package in which the test class is defined. A path starting with a slash is treated as a fully qualified classpath location, for example "/org/example/config.xml".
So it's important that you add the slash when referencing the file in the root directory of the classpath.
If you work with the absolute file path you have to use 'file:C:...' (if I understand the documentation correctly).
TikZ can do this.
A quick demo:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
[scale=.8,auto=left,every node/.style={circle,fill=blue!20}]
\node (n6) at (1,10) {6};
\node (n4) at (4,8) {4};
\node (n5) at (8,9) {5};
\node (n1) at (11,8) {1};
\node (n2) at (9,6) {2};
\node (n3) at (5,5) {3};
\foreach \from/\to in {n6/n4,n4/n5,n5/n1,n1/n2,n2/n5,n2/n3,n3/n4}
\draw (\from) -- (\to);
\end{tikzpicture}
\end{document}
produces:
More examples @ http://www.texample.net/tikz/examples/tag/graphs/
More information about TikZ: http://sourceforge.net/projects/pgf/ where I guess an installation guide will also be present.
It can be also self-signed certificate, etc. Turning off SSL verification globally is unsafe. You can install the certificate so it will be visible for the system, but the certificate should be perfectly correct.
Or you can clone with one time configuration parameter, so the command will be:
git clone -c http.sslverify=false https://myserver/<user>/<project>.git;
GIT will remember the false value, you can check it in the <project>/.git/config
file.
Why not JSON.stringify
and .includes()
?
You can easily check if a JSON object includes a value by turning it into a string and checking the string.
console.log(JSON.stringify(JSONObject).includes("dog"))
--> true
Edit: make sure to check browser compatibility for .includes()
You need to instantiate an object in order to call its member functions. The member functions need an object to operate on; they can't just be used on their own. The main()
function could, for example, look like this:
int main()
{
Name_pairs np;
cout << "Enter names and ages. Use 0 to cancel.\n";
while(np.test())
{
np.read_names();
np.read_ages();
}
np.print();
keep_window_open();
}
The following should work:
ABC: *\([a-zA-Z]+\) *(.+)
Explanation:
ABC: # match literal characters 'ABC:'
* # zero or more spaces
\([a-zA-Z]+\) # one or more letters inside of parentheses
* # zero or more spaces
(.+) # capture one or more of any character (except newlines)
To get your desired grouping based on the comments below, you can use the following:
(ABC:) *(\([a-zA-Z]+\).+)
Try to slightly modify your code:
Sub forEachWs()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next
End Sub
Sub resizingColumns(ws As Worksheet)
With ws
.Range("A:A").ColumnWidth = 20.14
.Range("B:B").ColumnWidth = 9.71
.Range("C:C").ColumnWidth = 35.86
.Range("D:D").ColumnWidth = 30.57
.Range("E:E").ColumnWidth = 23.57
.Range("F:F").ColumnWidth = 21.43
.Range("G:G").ColumnWidth = 18.43
.Range("H:H").ColumnWidth = 23.86
.Range("i:I").ColumnWidth = 27.43
.Range("J:J").ColumnWidth = 36.71
.Range("K:K").ColumnWidth = 30.29
.Range("L:L").ColumnWidth = 31.14
.Range("M:M").ColumnWidth = 31
.Range("N:N").ColumnWidth = 41.14
.Range("O:O").ColumnWidth = 33.86
End With
End Sub
Note, resizingColumns
routine takes parametr - worksheet to which Ranges belongs.
Basically, when you're using Range("O:O")
- code operats with range from ActiveSheet, that's why you should use With ws
statement and then .Range("O:O")
.
And there is no need to use global variables (unless you are using them somewhere else)
I got the same issue and after a lot of time spent on the search I found the solution
Just change your method especially // DownloadsProvider part
getpath()
to
@SuppressLint("NewApi") public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
// This is for checking Main Memory
if ("primary".equalsIgnoreCase(type)) {
if (split.length > 1) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
return Environment.getExternalStorageDirectory() + "/";
}
// This is for checking SD Card
} else {
return "storage" + "/" + docId.replace(":", "/");
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
String fileName = getFilePath(context, uri);
if (fileName != null) {
return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
}
String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
id = id.replaceFirst("raw:", "");
File file = new File(id);
if (file.exists())
return id;
}
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
For more solution click on the link here
https://gist.github.com/HBiSoft/15899990b8cd0723c3a894c1636550a8
I hope will do the same for you!
To load other file(css ,js) and folder(images) , in codeigniter project
we have to follow two simple step:
1.create folder public (can give any name) in your codeigniters folder put your bootstrap files css and js folder in side public folder. https://i.stack.imgur.com/O2gr6.jpg
2.now we have to use two line of code 1.load->helper('url'); ?> 2.
go to your view file
put first line to load base URL
<?php $this->load->helper('url'); ?>
secondly in your html head tag put this
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/public/css/bootstrap.css">
now you can enjoy the bootstrap in your codeigniter
This works for plain BSD so it should be universally compatible with all flavors. Below.e.g in pwd
( .
)
find . -size 0 | xargs rm
Python has a get function that its very useful to return a value of an existent key, if the key exist;
if not it will return a default value.
def main():
names = ['Jack','Maria','Betsy','James','Jack']
names_repeated = dict()
default_value = 0
for find_name in names:
names_repeated[find_name] = names_repeated.get(find_name, default_value) + 1
if you cannot find the name inside the dictionary, it will return the default_value, if the name exist then it will add any existing value with 1.
hope this can help
Assuming you want curl installed: just execute the install command and see what happens.
$ sudo yum install curl
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.cat.pdx.edu
* epel: mirrors.kernel.org
* extras: mirrors.cat.pdx.edu
* remi-php72: repo1.sea.innoscale.net
* remi-safe: repo1.sea.innoscale.net
* updates: mirrors.cat.pdx.edu
Package curl-7.29.0-54.el7_7.1.x86_64 already installed and latest version
Nothing to do
Try to add ReactiveFormsModule in your component as well.
import { FormGroup, FormArray, FormBuilder,
Validators,ReactiveFormsModule } from '@angular/forms';
The OPTIONS is from http://www.w3.org/TR/cors/ See http://metajack.im/2010/01/19/crossdomain-ajax-for-xmpp-http-binding-made-easy/ for a bit more info
You can use IntHolder as mutable alternative to Integer. But does it worth?
Got it! I found an idea here
http://www.mail-archive.com/[email protected]/msg18410.html
In this example, they loaded a blank popup window into an object, cloned the contents of the element to be displayed, and appended it to the body of the object. Since I already knew what the contents of view-details (or any page I load in the lightbox), I just had to clone that content instead and load it into an object. Then, I just needed to print that object. The final outcome looks like this:
$('.printBtn').bind('click',function() {
var thePopup = window.open( '', "Customer Listing", "menubar=0,location=0,height=700,width=700" );
$('#popup-content').clone().appendTo( thePopup.document.body );
thePopup.print();
});
I had one small drawback in that the style sheet I was using in view-details.php was using a relative link. I had to change it to an absolute link. The reason being that the window didn't have a URL associated with it, so it had no relative position to draw on.
Works in Firefox. I need to test it in some other major browsers too.
I don't know how well this solution works when you're dealing with images, videos, or other process intensive solutions. Although, it works pretty well in my case, since I'm just loading tables and text values.
Thanks for the input! You gave me some ideas of how to get around this.
There are many ways to do it with sed
or awk
:
sed -n '/TERMINATE/,$p' file
This looks for TERMINATE
in your file and prints from that line up to the end of the file.
awk '/TERMINATE/,0' file
This is exactly the same behaviour as sed
.
In case you know the number of the line from which you want to start printing, you can specify it together with NR
(number of record, which eventually indicates the number of the line):
awk 'NR>=535' file
$ seq 10 > a #generate a file with one number per line, from 1 to 10
$ sed -n '/7/,$p' a
7
8
9
10
$ awk '/7/,0' a
7
8
9
10
$ awk 'NR>=7' a
7
8
9
10
System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");
Another good option is FireDaemon. It's used by some big shops like NASA, IBM, etc; see their web site for a full list.
I think you are looking for:
window.location = 'http://someUrl.com';
It's not jQuery; it's pure JavaScript.
I didn't want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).
private static void playSound(String sound){
// cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
URL file = cl.getResource(sound);
final Media media = new Media(file.toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
Notice : You need to initialize JavaFX. A quick way to do that, is to call the constructor of JFXPanel() once in your app :
static{
JFXPanel fxPanel = new JFXPanel();
}
Assuming you want to parse the number of digits used to represent from a variable which is not always constant, a good way will be to use numpy.binary.
could be useful when you apply binary to power sets
import numpy as np
np.binary_repr(6, width=8)
Here's the NoCache
attribute proposed by mattytommo, simplified by using the information from Chris Moschini's answer:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : OutputCacheAttribute
{
public NoCacheAttribute()
{
this.Duration = 0;
}
}
In the newer version that is > 2.2 you can use git restore --staged <file_name>
.
Note here
If you want to unstage (move to changes) your files one at a time you use above command with your file name. eg
git restore --staged abc.html
Now if you want unstage all your file at once, you can do something like this
git restore --staged .
Please note space and dot (.) which means consider staged all files.
Here is my solution for a problem where you want to convert all the letters in a string with position of those letters in English alphabet and return a string of those nos.
https://gist.github.com/bondnotanymore/e0f1dcaacfb782348e74fac8b224769e
Let me know if you want to understand it in detail.I have used the following concepts - List comprehension - Dictionary comprehension
# make a list out of text - ['h','e','l','l','o']
text = list('hello')
while text:
print text.pop()
:)
In python empty object are evaluated as false. The .pop() removes and returns the last item on a list. And that's why it prints on reverse !
But can be fixed by using:
text.pop( 0 )
aspirinemaga, just replace:
$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);
for it:
$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);
@Someone Somewhere, I tried all of the above to no avail. The fix I found is from http://www.helloandroid.com/tutorials/remove-autofocus-edittext-android . Basically, you need to create an invisible layout just above the problematic Button:
<LinearLayout android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="0px"
android:layout_height="0px" >
<requestFocus />
</LinearLayout>
.NET Core 2.1.0
var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var config = builder.Build();
3. Install the following dependencies:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.json
4. Then, IMPORTANT: Right-click on the appsettings.json file -> click on Properties -> select Copy if newer:
Finally, you can do:
config["key1"]
Considering that my config file will look like this:
{ "ConnectionStrings": "myconnection string here", "key1": "value here" }
The difference is:
- orphanRemoval = true: "Child" entity is removed when it's no longer referenced (its parent may not be removed).
- CascadeType.REMOVE: "Child" entity is removed only when its "Parent" is removed.
A version in Kotlin, in this algorithm I created a decorator that allows you to set and get variables from the environment.
import java.util.Collections
import kotlin.reflect.KProperty
?
class EnvironmentDelegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return System.getenv(property.name) ?: "-"
}
?
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
val key = property.name
?
val classes: Array<Class<*>> = Collections::class.java.declaredClasses
val env = System.getenv()
?
val cl = classes.first { "java.util.Collections\$UnmodifiableMap" == it.name }
?
val field = cl.getDeclaredField("m")
field.isAccessible = true
val obj = field[env]
val map = obj as MutableMap<String, String>
map.putAll(mapOf(key to value))
}
}
?
class KnownProperties {
var JAVA_HOME: String by EnvironmentDelegate()
var sample: String by EnvironmentDelegate()
}
?
fun main() {
val knowProps = KnownProperties()
knowProps.sample = "2"
?
println("Java Home: ${knowProps.JAVA_HOME}")
println("Sample: ${knowProps.sample}")
}
In your case, ('AND' and 'OR' and 'NOT')
evaluates to "NOT"
, which may or may not be in your list...
while 'AND' not in MyList and 'OR' not in MyList and 'NOT' not in MyList:
print 'No Boolean Operator'
I had the same problem with spring boot. It resolved when i set package to marshaller.
@Bean
public Jaxb2Marshaller marshaller() throws Exception
{
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setPackagesToScan("com.octory.ws.dto");
return marshaller;
}
@Bean
public WebServiceTemplate webServiceTemplate(final Jaxb2Marshaller marshaller)
{
WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
webServiceTemplate.setMarshaller(marshaller);
webServiceTemplate.setUnmarshaller(marshaller);
return webServiceTemplate;
}
When I'm running a springboot project, the application.yml configuration is like this:
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/lof?serverTimezone=GMT
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
Notice that there isn't quotation marks around the password. And I can run this project in my windows System.
But when I try to deploy to the server, I have the problem and I fix it by changing the application.yml to:
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/lof?serverTimezone=GMT
username: root
password: "root"
driver-class-name: com.mysql.cj.jdbc.Driver
OpenPyxl
is quite a nice library, built to read/write Excel 2010 xlsx/xlsm files:
https://openpyxl.readthedocs.io/en/stable
The other answer, referring to it is using the deperciated function (get_sheet_by_name
). This is how to do it without it:
import openpyxl
wbkName = 'New.xlsx' #The file should be created before running the code.
wbk = openpyxl.load_workbook(wbkName)
wks = wbk['test1']
someValue = 1337
wks.cell(row=10, column=1).value = someValue
wbk.save(wbkName)
wbk.close
I know this is an old question but why can't you do it like:
db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);
I am not sure how to do this using query expressions.
Note: the accepted solution is now outdated and part of legacy code. http://legacy.datatables.net/ref The solutions might not be appropriate for those working with the newer versions of DataTables (its legacy now) For the newer solution: you could use: https://datatables.net/reference/api/columns().visible()
alternatives you could implement a button: https://datatables.net/extensions/buttons/built-in look at the last option under the link provided that allows having a button that could toggle column visibility.
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes
or AxesSubplot
object. The functions of interest are set_autoscale_on
, set_autoscalex_on
, and set_autoscaley_on
.
In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on
property to False
. Here is a modified version of the FFT subplot snippet from your code:
fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))
You can use $routeProvider resolve property to delay route change until data is loaded.
angular.module('app', ['ngRoute']).
config(['$routeProvider', function($routeProvider, EntitiesCtrlResolve, EntityCtrlResolve) {
$routeProvider.
when('/entities', {
templateUrl: 'entities.html',
controller: 'EntitiesCtrl',
resolve: EntitiesCtrlResolve
}).
when('/entity/:entityId', {
templateUrl: 'entity.html',
controller: 'EntityCtrl',
resolve: EntityCtrlResolve
}).
otherwise({redirectTo: '/entities'});
}]);
Notice that the resolve
property is defined on route.
EntitiesCtrlResolve
and EntityCtrlResolve
is constant objects defined in same file as EntitiesCtrl
and EntityCtrl
controllers.
// EntitiesCtrl.js
angular.module('app').constant('EntitiesCtrlResolve', {
Entities: function(EntitiesService) {
return EntitiesService.getAll();
}
});
angular.module('app').controller('EntitiesCtrl', function(Entities) {
$scope.entities = Entities;
// some code..
});
// EntityCtrl.js
angular.module('app').constant('EntityCtrlResolve', {
Entity: function($route, EntitiesService) {
return EntitiesService.getById($route.current.params.projectId);
}
});
angular.module('app').controller('EntityCtrl', function(Entity) {
$scope.entity = Entity;
// some code..
});
A custom HtmlHelper extension is another option. Note: ParameterDictionary is my own type. You could substitute a RouteValueDictionary but you'd have to construct it differently.
public static string ActionLinkSpan( this HtmlHelper helper, string linkText, string actionName, string controllerName, object htmlAttributes )
{
TagBuilder spanBuilder = new TagBuilder( "span" );
spanBuilder.InnerHtml = linkText;
return BuildNestedAnchor( spanBuilder.ToString(), string.Format( "/{0}/{1}", controllerName, actionName ), htmlAttributes );
}
private static string BuildNestedAnchor( string innerHtml, string url, object htmlAttributes )
{
TagBuilder anchorBuilder = new TagBuilder( "a" );
anchorBuilder.Attributes.Add( "href", url );
anchorBuilder.MergeAttributes( new ParameterDictionary( htmlAttributes ) );
anchorBuilder.InnerHtml = innerHtml;
return anchorBuilder.ToString();
}
List<YourClass> list = ArrayList<YourClass>();
List<String> userNames = list.stream().map(m -> m.getUserName()).collect(Collectors.toList());
output: ["John","Alex"]
You can track by $index
if your data source has duplicate identifiers
e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]
You can't iterate this collection while using 'id' as identifier (duplicate id:1).
WON'T WORK:
<element ng-repeat="item.id as item.name for item in dataSource">
// something with item ...
</element>
but you can, if using track by $index
:
<element ng-repeat="item in dataSource track by $index">
// something with item ...
</element>
I had mostly the same problem and ended up a a different solution that makes this type of problem trivial to query.
I have a table of sensor data (1 minute data from about 30 sensors)
SensorReadings->(timestamp,value,idSensor)
and I have a sensor table that has lots of mostly static stuff about the sensor but the relevant fields are these:
Sensors->(idSensor,Description,tvLastUpdate,tvLastValue,...)
The tvLastupdate and tvLastValue are set in a trigger on inserts to the SensorReadings table. I always have direct access to these values without needing to do any expensive queries. This does denormalize slightly. The query is trivial:
SELECT idSensor,Description,tvLastUpdate,tvLastValue
FROM Sensors
I use this method for data that is queried often. In my case I have a sensor table, and a large event table, that have data coming in at the minute level AND dozens of machines are updating dashboards and graphs with that data. With my data scenario the trigger-and-cache method works well.
one way you could handle this is with a generator. Instead of calling the function, yield it; then whatever is consuming the generator can send the result of calling it back into the generator, or a sentinel if the generator failed: The trampoline that accomplishes the above might look like so:
def consume_exceptions(gen):
action = next(gen)
while True:
try:
result = action()
except Exception:
# if the action fails, send a sentinel
result = None
try:
action = gen.send(result)
except StopIteration:
# if the generator is all used up, result is the return value.
return result
a generator that would be compatible with this would look like this:
def do_smth1():
1 / 0
def do_smth2():
print "YAY"
def do_many_things():
a = yield do_smth1
b = yield do_smth2
yield "Done"
>>> consume_exceptions(do_many_things())
YAY
Note that do_many_things()
does not call do_smth*
, it just yields them, and consume_exceptions
calls them on its behalf
Delete your .git folder, and reinitialize the git with git init, in my case that's work , because git add command staging the folder and the files in .git folder, if you close CLI after the commit , there will be double folder in staging area that make git system throw this issue.
I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands
OP, you can convert a string to type Boolean
by using any of the methods stated below:
string sample = "True";
bool myBool = bool.Parse(sample);
///or
bool myBool = Convert.ToBoolean(sample);
bool.Parse
expects one parameter which in this case is sample
, .ToBoolean
also expects one parameter.
You can use TryParse
which is the same as Parse
but it doesn't throw any exception :)
string sample = "false";
Boolean myBool;
if (Boolean.TryParse(sample , out myBool))
{
}
Please note that you cannot convert any type of string to type Boolean
because the value of a Boolean
can only be True
or False
Hope you understand :)
Read up on the configuration settings (e.g., display_errors
, display_startup_errors
, log_errors
) and update your php.ini
or .htaccess
or .user.ini
file, whichever is appropriate.
It works.
You can use java.util.concurrent.TimeUnit library which internally uses Thread.sleep. The syntax should look like this :
@Test
public void testExipres(){
SomeCacheObject sco = new SomeCacheObject();
sco.putWithExipration("foo", 1000);
TimeUnit.MINUTES.sleep(2);
assertNull(sco.getIfNotExipred("foo"));
}
This library provides more clear interpretation for time unit. You can use 'HOURS'/'MINUTES'/'SECONDS'.
If you are using Java with Hibernate then using NUMBER(1,0) is the best approach. As you can see in here, this value is automatically translated to Boolean by Hibernate.
I guess you want to use to edit the json text. Then you can use ivarni's way:
{{data | json}}and add an adition attribute to make
editable
<pre contenteditable="true">{{data | json}}</pre>
Hope this can help you.
You should not set state (or do anything else with side effects) from within the rendering function. When using hooks, you can use useEffect
for this.
The following version works:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const StateSelector = () => {
const initialValue = [
{ id: 0, value: " --- Select a State ---" }];
const allowedState = [
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
const [stateOptions, setStateValues] = useState(initialValue);
// initialValue.push(...allowedState);
console.log(initialValue.length);
// ****** BEGINNING OF CHANGE ******
useEffect(() => {
// Should not ever set state during rendering, so do this in useEffect instead.
setStateValues(allowedState);
}, []);
// ****** END OF CHANGE ******
return (<div>
<label>Select a State:</label>
<select>
{stateOptions.map((localState, index) => (
<option key={localState.id}>{localState.value}</option>
))}
</select>
</div>);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
and here it is in a code sandbox.
I'm assuming that you want to eventually load the list of states from some dynamic source (otherwise you could just use allowedState
directly without using useState
at all). If so, that api call to load the list could also go inside the useEffect
block.
So some days I lack brain cells and:
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/CustomSwitchStyle"/>
does not apply the theme because style is incorrect. I was supposed to use app:theme :P
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="@style/CustomSwitchStyle"/>
Whoopsies. This post was what gave me insight into my mistake...hopefully if someone stumbles across this it will help them like it did me. Thank you Gaëtan Maisse for your answer
This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself. Given that you have added an php command to catch the variable, you will get it.
As example (DEMO):
HTML:
<div class="header">
<img src="img/logo.png" alt="logo" />
<h1>My website name</h1>
</div>
CSS:
.header img {
float: left;
width: 100px;
height: 100px;
background: #555;
}
.header h1 {
position: relative;
top: 18px;
left: 10px;
}
I got this error after change a loop in my program, let`s see:
for ...
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:
for ...
x_batch = []
y_batch = []
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
Then, check if you are using np.asarray() or something like that.
Every 5-10 minutes my application pool kept crashing with this exit code. I do not want to ruin your trust of the Garbage Collector, but the following solution worked for me.
I added a Job that calls GC.GetTotalMemory(true)
every minute.
I suppose that, for some reason, the GC is not automatically inspecting the memory often enough for the high number of disposable objects that I use.
I've had this same error, without your whole code it is difficult to pinpoint exactly how to fix it but it is caused by not having a __set function.
The way that I have gotten around it in the past is I have done things like this:
$user = createUser();
$role = $user->role;
$role->rolename = 'Test';
now if you do this:
echo $user->role->rolename;
you should see 'Test'
I switched to a different USB port and it suddenly got recognized...
int scrWidth = getWindowManager().getDefaultDisplay().getWidth();
int scrHeight = getWindowManager().getDefaultDisplay().getHeight();
https://firebase.google.com/docs/auth/web/manage-users
You have to add an auth state change observer.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
I've found this issue to be prevalent in Entity Framework when we instantiate an Entity manually rather than through DBContext which will resolve all the Navigation Properties. If there are Foreign Key references (Navigation Properties) between tables and you use those references in your lambda (e.g. ProductDetail.Products.ID) then that "Products" context remains null if you manually created the Entity.
for win xp
Steps
I have an easier solution (that I used myself recently, for a host of lazy reasons). Add this method to the class you are working in:
public static void DumbDebug(string message)
{
File.WriteAllText(@"C:\AdHocConsole\" + message + ".txt", "this is really dumb. I wish Microsoft had more obvious solutions to its solutions problems.");
}
Then...open up the directory AdHocConsole, and order by created time. Make sure when you add your 'print statements'. They are distinct though, else there will be juggling.
Most answers here address this question in very dry, technical terms. I'd like to address this in terms that normal human beings can understand.
Imagine that you are trying to slice up pizzas. You have a robotic pizza cutter that can cut pizza slices exactly in half. It can halve a whole pizza, or it can halve an existing slice, but in any case, the halving is always exact.
That pizza cutter has very fine movements, and if you start with a whole pizza, then halve that, and continue halving the smallest slice each time, you can do the halving 53 times before the slice is too small for even its high-precision abilities. At that point, you can no longer halve that very thin slice, but must either include or exclude it as is.
Now, how would you piece all the slices in such a way that would add up to one-tenth (0.1) or one-fifth (0.2) of a pizza? Really think about it, and try working it out. You can even try to use a real pizza, if you have a mythical precision pizza cutter at hand. :-)
Most experienced programmers, of course, know the real answer, which is that there is no way to piece together an exact tenth or fifth of the pizza using those slices, no matter how finely you slice them. You can do a pretty good approximation, and if you add up the approximation of 0.1 with the approximation of 0.2, you get a pretty good approximation of 0.3, but it's still just that, an approximation.
For double-precision numbers (which is the precision that allows you to halve your pizza 53 times), the numbers immediately less and greater than 0.1 are 0.09999999999999999167332731531132594682276248931884765625 and 0.1000000000000000055511151231257827021181583404541015625. The latter is quite a bit closer to 0.1 than the former, so a numeric parser will, given an input of 0.1, favour the latter.
(The difference between those two numbers is the "smallest slice" that we must decide to either include, which introduces an upward bias, or exclude, which introduces a downward bias. The technical term for that smallest slice is an ulp.)
In the case of 0.2, the numbers are all the same, just scaled up by a factor of 2. Again, we favour the value that's slightly higher than 0.2.
Notice that in both cases, the approximations for 0.1 and 0.2 have a slight upward bias. If we add enough of these biases in, they will push the number further and further away from what we want, and in fact, in the case of 0.1 + 0.2, the bias is high enough that the resulting number is no longer the closest number to 0.3.
In particular, 0.1 + 0.2 is really 0.1000000000000000055511151231257827021181583404541015625 + 0.200000000000000011102230246251565404236316680908203125 = 0.3000000000000000444089209850062616169452667236328125, whereas the number closest to 0.3 is actually 0.299999999999999988897769753748434595763683319091796875.
P.S. Some programming languages also provide pizza cutters that can split slices into exact tenths. Although such pizza cutters are uncommon, if you do have access to one, you should use it when it's important to be able to get exactly one-tenth or one-fifth of a slice.
I'd recommend to strip from the second and the following strings the string os.path.sep
, preventing them to be interpreted as absolute paths:
first_path_str = '/home/build/test/sandboxes/'
original_other_path_to_append_ls = [todaystr, '/new_sandbox/']
other_path_to_append_ls = [
i_path.strip(os.path.sep) for i_path in original_other_path_to_append_ls
]
output_path = os.path.join(first_path_str, *other_path_to_append_ls)
SQL Server 2012 and 2014 supports IIF(cont,true,false) function. Thus for minimal selection you can use it like
SELECT IIF(first>second, second, first) the_minimal FROM table
While IIF is just a shorthand for writing CASE...WHEN...ELSE
, it's easier to write.
The answer, as always, is "It depends". I assume from the tags you're talking about C#.
Your best bet is to determine
and write some test cases.
It also depends on how you sort the list (if it's sorted at all), what kind of comparisons need to be made, how long the "Compare" operation takes for the particular object in the list, or even how you intend to use the collection.
Generally, the best one to choose isn't so much based on the size of data you're working with, but rather how you intend to access it. Do you have each piece of data associated with a particular string, or other data? A hash based collection would probably be best. Is the order of the data you're storing important, or are you going to need to access all of the data at the same time? A regular list may be better then.
Additional:
Of course, my above comments assume 'performance' means data access. Something else to consider: what are you looking for when you say "performance"? Is performance individual value look up? Is it management of large (10000, 100000 or more) value sets? Is it the performance of filling the data structure with data? Removing data? Accessing individual bits of data? Replacing values? Iterating over the values? Memory usage? Data copying speed? For example, If you access data by a string value, but your main performance requirement is minimal memory usage, you might have conflicting design issues.
Here is the solution:
<input type="text" id="end_dt"/>
$(document).ready(function () {
$("#end_dt").datepicker({ dateFormat: "MM/dd/yyyy" });
});
hopefully this will resolve the issue :)
You can call it three ways - with parameters, with DEFAULT and via EXECUTE
SET NOCOUNT ON;
DECLARE
@Table SYSNAME = 'YourTable',
@Schema SYSNAME = 'dbo',
@Rows INT;
SELECT dbo.TableRowCount( @Table, @Schema )
SELECT dbo.TableRowCount( @Table, DEFAULT )
EXECUTE @Rows = dbo.TableRowCount @Table
SELECT @Rows
Here is a very good tutorial for MVVM beginners; http://geekswithblogs.net/mbcrump/archive/2010/06/27/getting-started-with-mvvm-general-infolinks.aspx [Getting started with MVVM (General Info+Links)]
Use port number 22 (for sftp) instead of 21 (normal ftp). Solved this problem for me.
The thought process here is that you spend most of your time in development
. When in development, you create a feature
branch (off of development
), complete the feature, and then merge back into development
. This can then be added to the final production version by merging into production
.
See A Successful Git Branching Model for more detail on this approach.
If you want to squish every commit into a single commit (e.g. when releasing a project publicly for the first time), try:
git checkout --orphan <new-branch>
git commit
in the graphical layout, you can choose the theme on the toolbar. (the one that looks like a star).
choose the NoTitleBar
and have fun.
I'm currently working on such a statement and figured out another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement. For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (constraints allow it) or fail.
A clean solution could be create a generic class to handle the list, so you don't need to create a different class each time you need it.
public class ListModel<T>
{
public List<T> Items { get; set; }
public ListModel(List<T> list) {
Items = list;
}
}
and when you return the View you just need to simply do:
List<customClass> ListOfCustomClass = new List<customClass>();
//Do as needed...
return View(new ListModel<customClass>(ListOfCustomClass));
then define the list in the model:
@model ListModel<customClass>
and ready to go:
@foreach(var element in Model.Items) {
//do as needed...
}
Why would you use -z? To test if a string is non-empty, you typically use -n:
if test -n "$errorstatus"; then echo errorstatus is not empty fi
Here's a shorter version of the accepted answer:
$url .= (parse_url($url, PHP_URL_QUERY) ? '&' : '?') . 'category=action';
Edit: as discussed in the accepted answer, this is flawed in that it doesn't check to see if category
already exists. A better solution would be to treat the $_GET
for what it is - an array - and use functions like in_array()
.
The problem is that in IE (which is what I presume you're testing in), the <iframe>
element has a document
property that refers to the document containing the iframe, and this is getting used before the contentDocument
or contentWindow.document
properties. What you need is:
function GetDoc(x) {
return x.contentDocument || x.contentWindow.document;
}
Also, document.all
is not available in all browsers and is non-standard. Use document.getElementById()
instead.
You can use the same way as specified by Alireza Maddah and if u want to use two data table into one json array following is the way:
public string ConvertDataTabletoString()
{
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=master;Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,description from LocationDetails", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
SqlCommand cmd1 = new SqlCommand("_another_query_", con);
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
System.Web.Script.Serialization.JavaScriptSerializer serializer1 = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, object> row1;
foreach (DataRow dr in dt1.Rows) //use the old variable rows only
{
row1 = new Dictionary<string, object>();
foreach (DataColumn col in dt1.Columns)
{
row1.Add(col.ColumnName, dr[col]);
}
rows.Add(row1); // Finally You can add into old json array in this way
}
return serializer.Serialize(rows);
}
}
}
The same way can be used for as many as data tables as you want.
When handling money in MySQL, use DECIMAL(13,2) if you know the precision of your money values or use DOUBLE if you just want a quick good-enough approximate value. So if your application needs to handle money values up to a trillion dollars (or euros or pounds), then this should work:
DECIMAL(13, 2)
Or, if you need to comply with GAAP then use:
DECIMAL(13, 4)
import sys
import PIL
import PIL.Image as PILimage
from PIL import ImageDraw, ImageFont, ImageEnhance
from PIL.ExifTags import TAGS, GPSTAGS
class Worker(object):
def __init__(self, img):
self.img = img
self.exif_data = self.get_exif_data()
self.lat = self.get_lat()
self.lon = self.get_lon()
self.date =self.get_date_time()
super(Worker, self).__init__()
@staticmethod
def get_if_exist(data, key):
if key in data:
return data[key]
return None
@staticmethod
def convert_to_degress(value):
"""Helper function to convert the GPS coordinates
stored in the EXIF to degress in float format"""
d0 = value[0][0]
d1 = value[0][1]
d = float(d0) / float(d1)
m0 = value[1][0]
m1 = value[1][1]
m = float(m0) / float(m1)
s0 = value[2][0]
s1 = value[2][1]
s = float(s0) / float(s1)
return d + (m / 60.0) + (s / 3600.0)
def get_exif_data(self):
"""Returns a dictionary from the exif data of an PIL Image item. Also
converts the GPS Tags"""
exif_data = {}
info = self.img._getexif()
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decoded == "GPSInfo":
gps_data = {}
for t in value:
sub_decoded = GPSTAGS.get(t, t)
gps_data[sub_decoded] = value[t]
exif_data[decoded] = gps_data
else:
exif_data[decoded] = value
return exif_data
def get_lat(self):
"""Returns the latitude and longitude, if available, from the
provided exif_data (obtained through get_exif_data above)"""
# print(exif_data)
if 'GPSInfo' in self.exif_data:
gps_info = self.exif_data["GPSInfo"]
gps_latitude = self.get_if_exist(gps_info, "GPSLatitude")
gps_latitude_ref = self.get_if_exist(gps_info, 'GPSLatitudeRef')
if gps_latitude and gps_latitude_ref:
lat = self.convert_to_degress(gps_latitude)
if gps_latitude_ref != "N":
lat = 0 - lat
lat = str(f"{lat:.{5}f}")
return lat
else:
return None
def get_lon(self):
"""Returns the latitude and longitude, if available, from the
provided exif_data (obtained through get_exif_data above)"""
# print(exif_data)
if 'GPSInfo' in self.exif_data:
gps_info = self.exif_data["GPSInfo"]
gps_longitude = self.get_if_exist(gps_info, 'GPSLongitude')
gps_longitude_ref = self.get_if_exist(gps_info, 'GPSLongitudeRef')
if gps_longitude and gps_longitude_ref:
lon = self.convert_to_degress(gps_longitude)
if gps_longitude_ref != "E":
lon = 0 - lon
lon = str(f"{lon:.{5}f}")
return lon
else:
return None
def get_date_time(self):
if 'DateTime' in self.exif_data:
date_and_time = self.exif_data['DateTime']
return date_and_time
if __name__ == '__main__':
try:
img = PILimage.open(sys.argv[1])
image = Worker(img)
lat = image.lat
lon = image.lon
date = image.date
print(date, lat, lon)
except Exception as e:
print(e)
Another possibility may be the USB driver on your PC. In my case, switching from my 3.0 USB port to my 2.0 port fixed the problem.
For Jupyter and Windows users, you can change the Target path in your Jupyter Notebook (anaconda3)
shortcut from C:\Users\<YourUserName>\anaconda3
to C:\Users\<YourUserName>\anaconda3\envs\<YourEnvironmentName>
you could do the same thing for the Anaconda Prompt..etc.
After changing the path you can check your active environment by opening a terminal in Jupyter and run conda info --envs
.
If you want to convert a python datetime to seconds since epoch you could do it explicitly:
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0
In Python 3.3+ you can use timestamp()
instead:
>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0
Why you should not use datetime.strftime('%s')
Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
I think zeroclipboard is great. this version work with latest Flash 11: http://www.itjungles.com/javascript/javascript-easy-cross-browser-copy-to-clipboard-solution.
Dictionary:
Hashtable:
As already mentioned, array_unique() could be used, but only when dealing with simple data. The objects are not so simple to handle.
When php tries to merge the arrays, it tries to compare the values of the array members. If a member is an object, it cannot get its value and uses the spl hash instead. Read more about spl_object_hash here.
Simply told if you have two objects, instances of the very same class and if one of them is not a reference to the other one - you will end up having two objects, no matter the value of their properties.
To be sure that you don't have any duplicates within the merged array, Imho you should handle the case on your own.
Also if you are going to merge multidimensional arrays, consider using array_merge_recursive() over array_merge().
Many good answers have been given to this question so far, but I still miss one with awk
not using getline
. Since, in general, it is not necessary to use getline
, I would go for:
awk ' f && NR==f+1; /blah/ {f=NR}' file #all matches after "blah"
or
awk '/blah/ {f=NR} f && NR==f+1' file #matches after "blah" not being also "blah"
The logic always consists in storing the line where "blah" is found and then printing those lines that are one line after.
Sample file:
$ cat a
0
blah1
1
2
3
blah2
4
5
6
blah3
blah4
7
Get all the lines after "blah". This prints another "blah" if it appears after the first one.
$ awk 'f&&NR==f+1; /blah/ {f=NR}' a
1
4
blah4
7
Get all the lines after "blah" if they do not contain "blah" themselves.
$ awk '/blah/ {f=NR} f && NR==f+1' a
1
4
7
The best way is to copy all the files and folders inside a directory on your local file system by: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH
SRC_PATH
is on container
DEST_PATH
is on localhost
Then do docker-compose down
attach a volume to the same DEST_PATH
and run Docker containers by using docker-compose up -d
Add volume by following in docker-compose.yml
volumes:
- DEST_PATH:SRC_PATH
Came from Google here with a solution for High Sierra.
Something changed in the networking setup of macos and some apps (including ping) cannot resolve localhost.
Editing /etc/hosts seems like a fix:
cmd: sudo nano /etc/hosts/
content 127.0.0.1 localhost
Or simply (if you're sure your /etc/hosts is empty)
sudo echo '127.0.0.1 localhost' > /etc/hosts
Simply removing and reinstalling the app worked for me:
You can use load_only function:
from sqlalchemy.orm import load_only
fields = ['name', 'addr', 'phone', 'url']
companies = session.query(SomeModel).options(load_only(*fields)).all()
/^[\s]*$/
matches empty strings and strings containing whitespaces only
I ran
docker info | grep Name: | xargs | cut -d' ' -f2
inside my container.
First of all this code snippet
char *addr=NULL;
strcpy(addr,retstring().c_str());
is invalid because you did not allocate memory where you are going to copy retstring().c_str().
As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.
Regex is a little quicker than the accepted answer (for my 23 MB test file) that I used. But there isn't a lot in it.
import re
bad_words = ['bad', 'naughty']
regex = f"^.*(:{'|'.join(bad_words)}).*\n"
subst = ""
with open('oldfile.txt') as oldfile:
lines = oldfile.read()
result = re.sub(regex, subst, lines, re.MULTILINE)
with open('newfile.txt', 'w') as newfile:
newfile.write(result)
Prerequisites :
install antiword : sudo apt-get install antiword
install docx : pip install docx
from subprocess import Popen, PIPE
from docx import opendocx, getdocumenttext
from cStringIO import StringIO
def document_to_text(filename, file_path):
cmd = ['antiword', file_path]
p = Popen(cmd, stdout=PIPE)
stdout, stderr = p.communicate()
return stdout.decode('ascii', 'ignore')
print document_to_text('your_file_name','your_file_path')
Notice – New versions of python-docx removed this function. Make sure to pip install docx and not the new python-docx
Here's a safe way:
using (var transitron = ctx.Database.BeginTransaction())
{
try
{
var employer = new Employ { Id = 1 };
ctx.Entry(employer).State = EntityState.Deleted;
ctx.SaveChanges();
transitron.Commit();
}
catch (Exception ex)
{
transitron.Rollback();
//capture exception like: entity does not exist, Id property does not exist, etc...
}
}
Here you can pile up all the changes you want, so you can do a series of deletion before the SaveChanges and Commit, so they will be applied only if they are all successful.
The real question is: whether to use interfaces or base classes. This has been covered before.
In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.
If you don't want to use dangerouslySetInnerHTML then you can use the below mentioned solution
var Iframe = React.createClass({
render: function() {
return(
<div>
<iframe src={this.props.src} height={this.props.height} width={this.props.width}/>
</div>
)
}
});
ReactDOM.render(
<Iframe src="http://plnkr.co/" height="500" width="500"/>,
document.getElementById('example')
);
here live demo is available Demo
I would add this to the LI's CSS
.list-item
{
float: left;
clear: left;
}
I ran into the same problem with getting hidden element width, so I wrote this plugin call jQuery Actual to fix it. Instead of using
$('#some-element').height();
use
$('#some-element').actual('height');
will give you the right value for hidden element or element has a hidden parent.
Hope this help :)
You can create it like this
conda create --prefix C:/tensorflow2 python=3.7
and you don't have to move to that folder to activate it.
# To activate this environment, use:
# > activate C:\tensorflow2
As you see I do it like this.
D:\Development_Avector\PycharmProjects\TensorFlow>activate C:\tensorflow2
(C:\tensorflow2) D:\Development_Avector\PycharmProjects\TensorFlow>
(C:\tensorflow2) D:\Development_Avector\PycharmProjects\TensorFlow>conda --version
conda 4.5.13
localhost:55828/token
(not localhost:55828/API/token
)[email protected]&password=Test123$&grant_type=password
When you use JavaScript to make post request, you may use following:
$http.post("localhost:55828/token",
"userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password",
{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
).success(function (data) {//...
See screenshots below from Postman:
Somehow the accepted answer is only talking about including css file from bootstrap.
But I think this question is related to the one here - Bootstrap Dropdown not working in React
There are couple of answers that can help -
You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user
.
Now, you can access every property of the user. For example, you can access the username like that : app.user.username
.
Warning, if the user is not logged, the app.user
is null.
If you want to check if the user is logged, you can use the is_granted
twig function. For example, if you want to check if the user has ROLE_ADMIN
, you just have to do is_granted("ROLE_ADMIN")
.
So, in every of your pages you can do :
{% if is_granted("ROLE") %}
Hi {{ app.user.username }}
{% endif %}
The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
</head>
<body>
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: '100%',
videoId: 'osz5tVY97dQ',
playerVars: { 'autoplay': 1, 'playsinline': 1 },
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
event.target.playVideo();
}
</script>
</body>
</html>
public static class ErrorCode
{
public const IDictionary<string , string > m_ErrorCodeDic;
public static ErrorCode()
{
m_ErrorCodeDic = new Dictionary<string, string>()
{ {"1","User name or password problem"} };
}
}
Probably initialise in the constructor.
with(dfr[dfr$var3 < 155,], plot(var1, var2))
should do the trick.
Edit regarding multiple conditions:
with(dfr[(dfr$var3 < 155) & (dfr$var4 > 27),], plot(var1, var2))
no gQuery
document.getElementById('your_box').onclick();
I used certain class on my checkboxes.
var x = document.getElementsByClassName("box_class");
var i;
for (i = 0; i < x.length; i++) {
if(x[i].checked) x[i].checked = false;
else x[i].checked = true;
x[i].onclick();
}
To cross-correlate 1d arrays use numpy.correlate.
For 2d arrays, use scipy.signal.correlate2d.
There is also scipy.stsci.convolve.correlate2d.
There is also matplotlib.pyplot.xcorr which is based on numpy.correlate.
See this post on the SciPy mailing list for some links to different implementations.
Edit: @user333700 added a link to the SciPy ticket for this issue in a comment.
For someone who needs quick reference of C# Escape Sequences that can be used in string
literals:
\t Horizontal tab (ASCII code value: 9)
\n Line feed (ASCII code value: 10)
\r Carriage return (ASCII code value: 13)
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\x12 ASCII character in hexadecimal notation (e.g. for 0x12)
\x1234 Unicode character in hexadecimal notation (e.g. for 0x1234)
It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline
which gets adjusted to current OS settings. With .Net Core it gets really important.
Javascript, the language, came first, from Netscape.
Microsoft reverse engineered Javascript and called it JScript to avoid trademark issues with Sun. (Netscape and Sun were partnered up at the time, so this was less of an issue)
The languages are identical, both are dialects of ECMA script, the after-the-fact standard.
Although the languages are identical, since JScript runs in Internet Explorer, it has access to different objects exposed by the browser (such as ActiveXObject)
You're only adding the File object to the JSON object. The File object only contains meta information about the file: Path, name and so on.
You must load the image and read the bytes from it. Then put these bytes into the JSON object.
I modified the original function a bit to be (in my opinion more useful, or logical).
// display "X time" ago, $rcs is precision depth
function time_ago ($tm, $rcs = 0) {
$cur_tm = time();
$dif = $cur_tm - $tm;
$pds = array('second','minute','hour','day','week','month','year','decade');
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
for ($v = count($lngh) - 1; ($v >= 0) && (($no = $dif / $lngh[$v]) <= 1); $v--);
if ($v < 0)
$v = 0;
$_tm = $cur_tm - ($dif % $lngh[$v]);
$no = ($rcs ? floor($no) : round($no)); // if last denomination, round
if ($no != 1)
$pds[$v] .= 's';
$x = $no . ' ' . $pds[$v];
if (($rcs > 0) && ($v >= 1))
$x .= ' ' . $this->time_ago($_tm, $rcs - 1);
return $x;
}
You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,
float arr1[10] = { }; // all elements are 0
float arr2[10] = { 0 }; // all elements are 0
float arr3[10] = { 1 }; // first element is 1, all others are 0
float arr4[10] = { 1, 2 }; // first element is 1, second is 2, all others are 0