This is what has to occur.
You have to copy your DLL that you want to Register to: c:\windows\SysWOW64\
Then in the Run dialog, type this in:
C:\Windows\SysWOW64\regsvr32.exe c:\windows\system32\YourDLL.dll
and you will get the message:
DllRegisterServer in c:\windows\system32\YourDLL.dll succeeded.
Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/')
followed by relative paths for os.system
, subprocess
methods, or whatever...
If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial .exe
file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?
Python lists are mutable objects and here:
plot_data = [[]] * len(positions)
you are repeating the same list len(positions)
times.
>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>>
Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.
If you want different lists, you can do this way:
plot_data = [[] for _ in positions]
for example:
>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]
This is what finally worked for me since the file to be downloaded was determined when the page is loaded.
JS to update the form's action attribute:
function setFormAction() {
document.getElementById("myDownloadButtonForm").action = //some code to get the filename;
}
Calling JS to update the form's action attribute:
<body onLoad="setFormAction();">
Form tag with the submit button:
<form method="get" id="myDownloadButtonForm" action="">
Click to open document:
<button type="submit">Open Document</button>
</form>
The following did NOT work:
<form method="get" id="myDownloadButtonForm" action="javascript:someFunctionToReturnFileName();">
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
You could do something like this:
$("#txtArea").on("keypress",function(e) {_x000D_
var key = e.keyCode;_x000D_
_x000D_
// If the user has pressed enter_x000D_
if (key == 13) {_x000D_
document.getElementById("txtArea").value =document.getElementById("txtArea").value + "\n";_x000D_
return false;_x000D_
}_x000D_
else {_x000D_
return true;_x000D_
}_x000D_
});
_x000D_
<textarea id="txtArea"></textarea>
_x000D_
Bootstrap 4 removed .btn-group-justified. As a replacement you can use <div class="btn-group d-flex" role="group"></div>
as a wrapper around elements with .w-100.
Try this:
<div class="btn-group d-flex" role="group>
<button type="button" class="btn btn-primary w-100">Submit</button>
<button type="button" class="btn btn-primary w-100">Cancel</button>
</div>
In T-SQL you can:
SELECT [Date]
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY [Date], DATEPART(hh, [Date])
or
by minute use DATEPART(mi, [Date])
or
by 10 minutes use DATEPART(mi, [Date]) / 10
(like Timothy suggested)
If you're in charge (or have any control over the web service), get them to add a unique root element!
If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.
Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
c:\opencv\samples\cpp
.jQuery UI extends the jQuery native toggleClass
to take a second optional parameter: duration
toggleClass( class, [duration] )
AppServ is a small program in Windows to run:
It will also give you a startup and stop button for Apache. Which I find very useful.
and doesnt give any clues
Yes it does, unfortunately your code is ignoring all of those clues. Take a look at your exception handler:
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
All you're examining is the source of the exception. Which, in this case, is "Microsoft Access Database Engine". You're not examining the error message itself, or the stack trace, or any inner exception, or anything useful about the exception.
Don't ignore the exception, it contains information about what went wrong and why.
There are various logging tools out there (NLog, log4net, etc.) which can help you log useful information about an exception. Failing that, you should at least capture the exception message, stack trace, and any inner exception(s). Currently you're ignoring the error, which is why you're not able to solve the error.
In your debugger, place a breakpoint inside the catch
block and examine the details of the exception. You'll find it contains a lot of information.
The easiest way is probably to create an std::bitset
representing the value, then stream that to cout
.
#include <bitset>
...
char a = -58;
std::bitset<8> x(a);
std::cout << x << '\n';
short c = -315;
std::bitset<16> y(c);
std::cout << y << '\n';
Your code looks fine, but there are a couple of things to be aware of:
Post::find($id);
acts upon the primary key, if you have set your primary key in your model to something other than id
by doing:
protected $primaryKey = 'slug';
then find
will search by that key instead.
Laravel also expects the id
to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:
public $incrementing = false;
try this:
key=key.replace(/ /g,"_");
that'll do a global find/replace
sed
The -i
flag works differently on macOS sed
than in GNU sed
.
Here's the way to use it on macOS / OS X:
sed -i '' '8i\
8 This is Line 8' FILE
See man 1 sed
for more info.
Try using MAX
with a GROUP BY
.
SELECT u.userName, MAX(c.carPrice)
FROM users u
LEFT JOIN cars c ON u.id = c.belongsToUser
WHERE u.id = 4;
GROUP BY u.userName;
GROUP BY
The group by clause is used to split the selected records into groups based on unique combinations of the group by columns. This then allows us to use aggregate functions (eg. MAX, MIN, SUM, AVG, ...) that will be applied to each group of records in turn. The database will return a single result record for each grouping.
For example, if we have a set of records representing temperatures over time and location in a table like this:
Location Time Temperature
-------- ---- -----------
London 12:00 10.0
Bristol 12:00 12.0
Glasgow 12:00 5.0
London 13:00 14.0
Bristol 13:00 13.0
Glasgow 13:00 7.0
...
Then if we want to find the maximum temperature by location, then we need to split the temperature records into groupings, where each record in a particular group has the same location. We then want to find the maximum temperature of each group. The query to do this would be as follows:
SELECT Location, MAX(Temperature)
FROM Temperatures
GROUP BY Location;
when I create my JLabel and enter the text to it, there is no wordwrap or anything
HTML formatting can be used to cause word wrap in any Swing component that offers styled text. E.G. as demonstrated in this answer.
Make the toString method as readable as you possibly can!
The sole exception for this in my book is if you can prove to me that it consumes significant resources :) (Yes, this means profiling)
Also note that the Java 5 compiler generates faster code than the handwritten "StringBuffer" approach used in earlier versions of Java. If you use "+" this and future enhancements comes for free.
In the page file:
<script type="text/javascript">
var a = eval('[<% =string.Join(", ", numbers) %>]');
</script>
while in code behind:
public int[] numbers = WhatEverGetTheArray();
This happened to me when I created the virtualenv in the wrong location. I then thought I could move the dir to another location without it mattering. It mattered.
mkdir ~/projects
virtualenv myenv
cd myenv
git clone [my repository]
Oh crap, I forgot to cd into projects
before creating the virtualenv and cloning the rep. Oh well, I'm too lazy to destroy and recreate. I'll just move the dir with no issues.
cd ~
mv myenv projects
cd projects/myenv/myrepo
pip install -r requirements
Nope, wants more permissions, what the? I thought it was strange but SUDO AWAY! It then installed the packages into a global location.
The lesson I learned was, just delete the virtualenv dir. Don't move it.
You can use a quick lambda
function to check if all the values in a given row are 0
. Then you can use the result of applying that lambda
as a way to choose only the rows that match or don't match that condition:
import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.DataFrame(np.random.randn(5,3),
index=['one', 'two', 'three', 'four', 'five'],
columns=list('abc'))
df.loc[['one', 'three']] = 0
print df
print df.loc[~df.apply(lambda row: (row==0).all(), axis=1)]
Yields:
a b c
one 0.000000 0.000000 0.000000
two 2.240893 1.867558 -0.977278
three 0.000000 0.000000 0.000000
four 0.410599 0.144044 1.454274
five 0.761038 0.121675 0.443863
[5 rows x 3 columns]
a b c
two 2.240893 1.867558 -0.977278
four 0.410599 0.144044 1.454274
five 0.761038 0.121675 0.443863
[3 rows x 3 columns]
You can use apply
for this, and it's a bit neater:
import numpy as np
import pandas as pd
np.random.seed(1)
df = pd.DataFrame(np.random.randn(4,4)* 4 + 3)
0 1 2 3
0 9.497381 0.552974 0.887313 -1.291874
1 6.461631 -6.206155 9.979247 -0.044828
2 4.276156 2.002518 8.848432 -5.240563
3 1.710331 1.463783 7.535078 -1.399565
df.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))
0 1 2 3
0 0.515087 0.133967 -0.651699 0.135175
1 0.125241 -0.689446 0.348301 0.375188
2 -0.155414 0.310554 0.223925 -0.624812
3 -0.484913 0.244924 0.079473 0.114448
Also, it works nicely with groupby
, if you select the relevant columns:
df['grp'] = ['A', 'A', 'B', 'B']
0 1 2 3 grp
0 9.497381 0.552974 0.887313 -1.291874 A
1 6.461631 -6.206155 9.979247 -0.044828 A
2 4.276156 2.002518 8.848432 -5.240563 B
3 1.710331 1.463783 7.535078 -1.399565 B
df.groupby(['grp'])[[0,1,2,3]].apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))
0 1 2 3
0 0.5 0.5 -0.5 -0.5
1 -0.5 -0.5 0.5 0.5
2 0.5 0.5 0.5 -0.5
3 -0.5 -0.5 -0.5 0.5
You can call javascript functions from c# using Jering.Javascript.NodeJS, an open-source library by my organization:
string javascriptModule = @"
module.exports = (callback, x, y) => { // Module must export a function that takes a callback as its first parameter
var result = x + y; // Your javascript logic
callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}";
// Invoke javascript
int result = await StaticNodeJSService.InvokeFromStringAsync<int>(javascriptModule, args: new object[] { 3, 5 });
// result == 8
Assert.Equal(8, result);
The library supports invoking directly from .js files as well. Say you have file C:/My/Directory/exampleModule.js
containing:
module.exports = (callback, message) => callback(null, message);
You can invoke the exported function:
string result = await StaticNodeJSService.InvokeFromFileAsync<string>("C:/My/Directory/exampleModule.js", args: new[] { "test" });
// result == "test"
Assert.Equal("test", result);
In
[ -f "$file" ]
the [
command does a stat()
(not lstat()
) system call on the path stored in $file
and returns true if that system call succeeds and the type of the file as returned by stat()
is "regular".
So if [ -f "$file" ]
returns true, you can tell the file does exist and is a regular file or a symlink eventually resolving to a regular file (or at least it was at the time of the stat()
).
However if it returns false (or if [ ! -f "$file" ]
or ! [ -f "$file" ]
return true), there are many different possibilities:
stat()
system call may fail.In short, it should be:
if [ -f "$file" ]; then
printf '"%s" is a path to a regular file or symlink to regular file\n' "$file"
elif [ -e "$file" ]; then
printf '"%s" exists but is not a regular file\n' "$file"
elif [ -L "$file" ]; then
printf '"%s" exists, is a symlink but I cannot tell if it eventually resolves to an actual file, regular or not\n' "$file"
else
printf 'I cannot tell if "%s" exists, let alone whether it is a regular file or not\n' "$file"
fi
To know for sure that the file doesn't exist, we'd need the stat()
system call to return with an error code of ENOENT
(ENOTDIR
tells us one of the path components is not a directory is another case where we can tell the file doesn't exist by that path). Unfortunately the [
command doesn't let us know that. It will return false whether the error code is ENOENT, EACCESS (permission denied), ENAMETOOLONG or anything else.
The [ -e "$file" ]
test can also be done with ls -Ld -- "$file" > /dev/null
. In that case, ls
will tell you why the stat()
failed, though the information can't easily be used programmatically:
$ file=/var/spool/cron/crontabs/root
$ if [ ! -e "$file" ]; then echo does not exist; fi
does not exist
$ if ! ls -Ld -- "$file" > /dev/null; then echo stat failed; fi
ls: cannot access '/var/spool/cron/crontabs/root': Permission denied
stat failed
At least ls
tells me it's not because the file doesn't exist that it fails. It's because it can't tell whether the file exists or not. The [
command just ignored the problem.
With the zsh
shell, you can query the error code with the $ERRNO
special variable after the failing [
command, and decode that number using the $errnos
special array in the zsh/system
module:
zmodload zsh/system
ERRNO=0
if [ ! -f "$file" ]; then
err=$ERRNO
case $errnos[err] in
("") echo exists, not a regular file;;
(ENOENT|ENOTDIR)
if [ -L "$file" ]; then
echo broken link
else
echo does not exist
fi;;
(*) syserror -p "can't tell: " "$err"
esac
fi
(beware the $errnos
support was broken with some versions of zsh
when built with recent versions of gcc
).
Windows type
command works similarly to UNIX cat
.
Example 1: Merge with file names (This will merge file1.csv & file2.csv to create concat.csv)
type file1.csv file2.csv > concat.csv
Example 2: Merge files with pattern (This will merge all files with csv extension and create concat.csv)
When using asterisk(*) to concatenate all files. Please DON'T use same extension for target file(Eg. .csv). There should be some difference in pattern else target file will also be considered in concatenation
type *.csv > concat_csv.txt
Delegates are the way to go.
As seen with other answers using views might get outdated. Who knows tomorrow there might be another wrapper and may need to use cell superview]superview]superview]superview]
. And if you use tags you would end up with n number of if else conditions to identify the cell. To avoid all of that set up delegates. (By doing so you will be creating a re usable cell class. You can use the same cell class as a base class and all you have to do is implement the delegate methods.)
First we need a interface (protocol) which will be used by cell to communicate(delegate) button clicks. (You can create a separate .h file for protocol and include in both table view controller and custom cell classes OR just add it in custom cell class which will anyway get included in table view controller)
@protocol CellDelegate <NSObject>
- (void)didClickOnCellAtIndex:(NSInteger)cellIndex withData:(id)data;
@end
Include this protocol in custom cell and table view controller. And make sure table view controller confirms to this protocol.
In custom cell create two properties :
@property (weak, nonatomic) id<CellDelegate>delegate;
@property (assign, nonatomic) NSInteger cellIndex;
In UIButton
IBAction delegate click : (Same can be done for any action in custom cell class which needs to be delegated back to view controller)
- (IBAction)buttonClicked:(UIButton *)sender {
if (self.delegate && [self.delegate respondsToSelector:@selector(didClickOnCellAtIndex:withData:)]) {
[self.delegate didClickOnCellAtIndex:_cellIndex withData:@"any other cell data/property"];
}
}
In table view controller cellForRowAtIndexPath
after dequeing the cell, set the above properties.
cell.delegate = self;
cell.cellIndex = indexPath.row; // Set indexpath if its a grouped table.
And implement the delegate in table view controller:
- (void)didClickOnCellAtIndex:(NSInteger)cellIndex withData:(id)data
{
// Do additional actions as required.
NSLog(@"Cell at Index: %d clicked.\n Data received : %@", cellIndex, data);
}
This would be the ideal approach to get custom cell button actions in table view controller.
I am using Spring Boot and had this issue with a collection, in spite of not directly overwriting it, because I am declaring an extra field for the same collection with a custom serializer and deserializer in order to provide a more frontend-friendly representation of the data:
public List<Attribute> getAttributes() {
return attributes;
}
public void setAttributes(List<Attribute> attributes) {
this.attributes = attributes;
}
@JsonSerialize(using = AttributeSerializer.class)
public List<Attribute> getAttributesList() {
return attributes;
}
@JsonDeserialize(using = AttributeDeserializer.class)
public void setAttributesList(List<Attribute> attributes) {
this.attributes = attributes;
}
It seems that even though I am not overwriting the collection myself, the deserialization does it under the hood, triggering this issue all the same. The solution was to change the setter associated with the deserializer so that it would clear the list and add everything, rather than overwrite it:
@JsonDeserialize(using = AttributeDeserializer.class)
public void setAttributesList(List<Attribute> attributes) {
this.attributes.clear();
this.attributes.addAll(attributes);
}
You don't need jQuery when it is so simple to do this using pure JavaScript. Here are two options:
Method 1 - Retrieve the exact value of the href
attribute:
Select the element and then use the .getAttribute()
method.
This method does not return the full URL, instead it retrieves the exact value of the href
attribute.
var anchor = document.querySelector('a'),_x000D_
url = anchor.getAttribute('href');_x000D_
_x000D_
alert(url);
_x000D_
<a href="/relative/path.html"></a>
_x000D_
Method 2 - Retrieve the full URL path:
Select the element and then simply access the href
property.
This method returns the full URL path.
In this case: http://stacksnippets.net/relative/path.html
.
var anchor = document.querySelector('a'),_x000D_
url = anchor.href;_x000D_
_x000D_
alert(url);
_x000D_
<a href="/relative/path.html"></a>
_x000D_
As your title implies, you want to get the href
value on click. Simply select an element, add a click event listener and then return the href
value using either of the aforementioned methods.
var anchor = document.querySelector('a'),_x000D_
button = document.getElementById('getURL'),_x000D_
url = anchor.href;_x000D_
_x000D_
button.addEventListener('click', function (e) {_x000D_
alert(url);_x000D_
});
_x000D_
<button id="getURL">Click me!</button>_x000D_
<a href="/relative/path.html"></a>
_x000D_
You can take the SelectedItem
and cast it back to your class
and access its properties
.
MessageBox.Show(((ComboboxItem)ComboBox_Countries_In_Silvers.SelectedItem).Value);
Edit You can try using DataTextField and DataValueField, I used it with DataSource.
ComboBox_Servers.DataTextField = "Text";
ComboBox_Servers.DataValueField = "Value";
You can also closure array with replacements like this.
var url = '/getElement/_/_/_'.replace(/_/g, (_ => this.ar[this.i++]).bind({ar: ["invoice", "id", 1337],i: 0}))
> '/getElement/invoice/id/1337
or you can try bind
'/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))
Unfortunately there is no SELECT statement that will always work regardless of database.
Most databases support:
SELECT 1
Some databases don't support this but have a table called DUAL that you can use when you don't need a table:
SELECT 1 FROM DUAL
MySQL also supports this for compatibility reasons, but not all databases do. A workaround for databases that don't support either of the above is to create a table called DUAL that contains a single row, then the above will work.
HSQLDB supports neither of the above, so you can either create the DUAL table or else use:
SELECT 1 FROM any_table_that_you_know_exists_in_your_database
I prefer to stop the MongoDB server using the port
command itself.
sudo port unload mongodb
And to start it again.
sudo port load mongodb
git log --decorate
This will tell you what refs are pointing to the currently checked out commit.
import operator
To sort the list of dictionaries by key='name':
list_of_dicts.sort(key=operator.itemgetter('name'))
To sort the list of dictionaries by key='age':
list_of_dicts.sort(key=operator.itemgetter('age'))
You can do this:
$('.searchbychar').click(function () {
var divID = '#' + this.id;
$('html, body').animate({
scrollTop: $(divID).offset().top
}, 2000);
});
F.Y.I.
.
(dot) like in your first line of code.$( 'searchbychar' ).click(function() {
$('.searchbychar').attr('id')
will return a string ID not a jQuery object. Hence, you can not apply .offset()
method to it.To use this function/method,you need an instance of the class Date .
This method is always used in conjunction with a Date object.
See the code below :
var d = new Date();
d.getTime();
You can get errors working correctly without hacking global.cs, messing with HandleErrorAttribute, doing Response.TrySkipIisCustomErrors, hooking up Application_Error, or whatever:
In system.web (just the usual, on/off)
<customErrors mode="On">
<error redirect="/error/401" statusCode="401" />
<error redirect="/error/500" statusCode="500" />
</customErrors>
and in system.webServer
<httpErrors existingResponse="PassThrough" />
Now things should behave as expected, and you can use your ErrorController to display whatever you need.
int Random = (int)(Math.random()*100);
if You need to generate more than one value, then just use for loop for that
for (int i = 1; i <= 10 ; i++)
{
int Random = (int)(Math.random()*100);
System.out.println(Random);
}
If You want to specify a more decent range, like from 10 to 100 ( both are in the range )
so the code would be :
int Random =10 + (int)(Math.random()*(91));
/* int Random = (min.value ) + (int)(Math.random()* ( Max - Min + 1));
*Where min is the smallest value You want to be the smallest number possible to
generate and Max is the biggest possible number to generate*/
You can get a list of all matching elements with a list comprehension:
[x for x in myList if x.n == 30] # list of all elements with .n==30
If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do
def contains(list, filter):
for x in list:
if filter(x):
return True
return False
if contains(myList, lambda x: x.n == 3) # True if any element has .n==3
# do stuff
Rather than learning un-Official websites learn from oracle website
link follows:Click here
*You can find Initialization as well as declaration with full description *
int n; // size of array here 10
int[] a = new int[n];
for (int i = 0; i < a.length; i++)
{
a[i] = Integer.parseInt(s.nextLine()); // using Scanner class
}
Input: 10//array size 10 20 30 40 50 60 71 80 90 91
Displaying data:
for (int i = 0; i < a.length; i++)
{
System.out.println(a[i] + " ");
}
Output: 10 20 30 40 50 60 71 80 90 91
Here it is:
rfc2616#section-10.4.1 - 400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
rfc7231#section-6.5.1 - 6.5.1. 400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
Refers to malformed (not wellformed) cases!
rfc4918 - 11.2. 422 Unprocessable Entity
The 422 (Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Conclusion
Rule of thumb: [_]00 covers the most general case and cases that are not covered by designated code.
422 fits best object validation error (precisely my recommendation:)
As for semantically erroneous - Think of something like "This username already exists" validation.
400 is incorrectly used for object validation
import re
url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'
urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)
>>> print urls
['http://example.com', 'http://example2.com']
You would do something like this by tapping into the scroll
event handler on window
, and using another table
with a fixed position to show the header at the top of the page.
HTML:
<table id="header-fixed"></table>
CSS:
#header-fixed {
position: fixed;
top: 0px; display:none;
background-color:white;
}
JavaScript:
var tableOffset = $("#table-1").offset().top;
var $header = $("#table-1 > thead").clone();
var $fixedHeader = $("#header-fixed").append($header);
$(window).bind("scroll", function() {
var offset = $(this).scrollTop();
if (offset >= tableOffset && $fixedHeader.is(":hidden")) {
$fixedHeader.show();
}
else if (offset < tableOffset) {
$fixedHeader.hide();
}
});
This will show the table head when the user scrolls down far enough to hide the original table head. It will hide again when the user has scrolled the page up far enough again.
Working example: http://jsfiddle.net/andrewwhitaker/fj8wM/
For SQL Server 2008 only
CAST(@SomeDateTime AS Date)
Then cast it back to datetime if you want
CAST(CAST(@SomeDateTime AS Date) As datetime)
Let's say that you want to display the time elapsed between 5pm on Monday and 2:30pm the next day, Tuesday.
In cell A1 (for example), type in the date. In A2, the time. (If you type in 5 pm, including the space, it will display as 5:00 PM. If you want the day of the week to display as well, then in C3 (for example) enter the formula, =A1, then highlight the cell, go into the formatting dropdown menu, select Custom, and type in dddd.
Repeat all this in the row below.
Finally, say you want to display that duration in cell D2. Enter the formula, =(a2+b2)-(a1+b1). If you want this displayed as "22h 30m", select the cell, and in the formatting menu under Custom, type in h"h" m"m".
The loop only breaks if you return literally false
. Ex:
// this is how jquery calls your function
// notice hard comparison (===) against false
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
This means you can return anything else, including undefined
, which is what you return if you return nothing, so you can simply use an empty return statement:
$.each(collection, function (index, item) {
if (!someTestCondition)
return; // go to next iteration
// otherwise do something
});
It's possible this might vary by version; this is applicable for jquery 1.12.4. But really, when you exit out the bottom of the function, you are also returning nothing, and that's why the loop continues, so I would expect that there is no possibility whatsoever that returning nothing could not continue the loop. Unless they want to force everyone to start returning something to keep the loop going, returning nothing has to be a way to keep it going.
Using project Project facets we can configure characteristics and requirements for projects.
To find Project facets on eclipse:
I think the current right way to do this is by pip
like Pramod comments
pip install beautifulsoup4
because of last changes in Python, see discussion here. This was not so in the past.
Try below code:
@Html.DropDownList("ProductTypeID",null,"",new { @class = "form-control"})
Simple to do:
header code...
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command Set
objMyRecordset = New ADODB.Recordset
On Error GoTo ERRORHAND
Working code...
objMyConn.ConnectionString = ConnStr
objMyConn.Open
code....
'Copy Data FROM Excel'
objMyConn.BeginTrans <-- define transactions to possible be rolled back
For NewRows = 2 To Rows
objMyRecordset.AddNew
For NewColumns = 0 To Columns - 1
objMyRecordset.Fields(NewColumns).Value = ActiveSheet.Cells(NewRows, NewColumns + 1)
Next NewColumns objMyRecordset.Update Next NewRows
objMyConn.CommitTrans <- if success, commit them to DB
objMyConn.Close
ERRORHAND:
Success = False
objMyConn.RollbackTrans <-- here we roll back if error encountered somewhere
LogMessage = "ERROR writing database: " & Err.Description
...
I hope this will meet your requirement
import PyPDF4
import io
pdfFile = open(r'test.pdf', 'rb')
pdfReader = PyPDF4.PdfFileReader(pdfFile)
pageObj = pdfReader.getPage(1)
pagetext = pageObj.extractText()
for line in io.StringIO(pagetext):
print(line)
//VC6.0 (386 & better)
__int64 my_qw_var = 0x1234567890abcdef;
__int32 v_dw_h;
__int32 v_dw_l;
__asm
{
mov eax,[dword ptr my_qw_var + 4] //dwh
mov [dword ptr v_dw_h],eax
mov eax,[dword ptr my_qw_var] //dwl
mov [dword ptr v_dw_l],eax
}
//Oops 0.8 format
printf("val = 0x%0.8x%0.8x\n", (__int32)v_dw_h, (__int32)v_dw_l);
Regards.
As this is tagged "embedded" I'll assume you're using a microcontroller. All of the above suggestions are valid & work (read-modify-write, unions, structs, etc.).
However, during a bout of oscilloscope-based debugging I was amazed to find that these methods have a considerable overhead in CPU cycles compared to writing a value directly to the micro's PORTnSET / PORTnCLEAR registers which makes a real difference where there are tight loops / high-frequency ISR's toggling pins.
For those unfamiliar: In my example, the micro has a general pin-state register PORTn which reflects the output pins, so doing PORTn |= BIT_TO_SET results in a read-modify-write to that register. However, the PORTnSET / PORTnCLEAR registers take a '1' to mean "please make this bit 1" (SET) or "please make this bit zero" (CLEAR) and a '0' to mean "leave the pin alone". so, you end up with two port addresses depending whether you're setting or clearing the bit (not always convenient) but a much faster reaction and smaller assembled code.
a piece of code who work with python to read rs232 just in case somedoby else need it
ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()
Webrtc is a part of peer to peer connection. We all know that before creating peer to peer connection, it requires handshaking process to establish peer to peer connection. And websockets play the role of handshaking process.
Update 2016-06-27: instead of using Observables, use either
A Subject is both an Observable (so we can subscribe()
to it) and an Observer (so we can call next()
on it to emit a new value). We exploit this feature. A Subject allows values to be multicast to many Observers. We don't exploit this feature (we only have one Observer).
BehaviorSubject is a variant of Subject. It has the notion of "the current value". We exploit this: whenever we create an ObservingComponent, it gets the current navigation item value from the BehaviorSubject automatically.
The code below and the plunker use BehaviorSubject.
ReplaySubject is another variant of Subject. If you want to wait until a value is actually produced, use ReplaySubject(1)
. Whereas a BehaviorSubject requires an initial value (which will be provided immediately), ReplaySubject does not. ReplaySubject will always provide the most recent value, but since it does not have a required initial value, the service can do some async operation before returning it's first value. It will still fire immediately on subsequent calls with the most recent value. If you just want one value, use first()
on the subscription. You do not have to unsubscribe if you use first()
.
import {Injectable} from '@angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Injectable()
export class NavService {
// Observable navItem source
private _navItemSource = new BehaviorSubject<number>(0);
// Observable navItem stream
navItem$ = this._navItemSource.asObservable();
// service command
changeNav(number) {
this._navItemSource.next(number);
}
}
import {Component} from '@angular/core';
import {NavService} from './nav.service';
import {Subscription} from 'rxjs/Subscription';
@Component({
selector: 'obs-comp',
template: `obs component, item: {{item}}`
})
export class ObservingComponent {
item: number;
subscription:Subscription;
constructor(private _navService:NavService) {}
ngOnInit() {
this.subscription = this._navService.navItem$
.subscribe(item => this.item = item)
}
ngOnDestroy() {
// prevent memory leak when component is destroyed
this.subscription.unsubscribe();
}
}
@Component({
selector: 'my-nav',
template:`
<div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
<div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>`
})
export class Navigation {
item = 1;
constructor(private _navService:NavService) {}
selectedNavItem(item: number) {
console.log('selected nav item ' + item);
this._navService.changeNav(item);
}
}
Original answer that uses an Observable: (it requires more code and logic than using a BehaviorSubject, so I don't recommend it, but it may be instructive)
So, here's an implementation that uses an Observable instead of an EventEmitter. Unlike my EventEmitter implementation, this implementation also stores the currently selected navItem
in the service, so that when an observing component is created, it can retrieve the current value via API call navItem()
, and then be notified of changes via the navChange$
Observable.
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import {Observer} from 'rxjs/Observer';
export class NavService {
private _navItem = 0;
navChange$: Observable<number>;
private _observer: Observer;
constructor() {
this.navChange$ = new Observable(observer =>
this._observer = observer).share();
// share() allows multiple subscribers
}
changeNav(number) {
this._navItem = number;
this._observer.next(number);
}
navItem() {
return this._navItem;
}
}
@Component({
selector: 'obs-comp',
template: `obs component, item: {{item}}`
})
export class ObservingComponent {
item: number;
subscription: any;
constructor(private _navService:NavService) {}
ngOnInit() {
this.item = this._navService.navItem();
this.subscription = this._navService.navChange$.subscribe(
item => this.selectedNavItem(item));
}
selectedNavItem(item: number) {
this.item = item;
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
@Component({
selector: 'my-nav',
template:`
<div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
<div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
`,
})
export class Navigation {
item:number;
constructor(private _navService:NavService) {}
selectedNavItem(item: number) {
console.log('selected nav item ' + item);
this._navService.changeNav(item);
}
}
See also the Component Interaction Cookbook example, which uses a Subject
in addition to observables. Although the example is "parent and children communication," the same technique is applicable for unrelated components.
if nothing worked, try this
public struct Platform {
public static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0 // Use this line in Xcode 7 or newer
}
}
No, there is not, see how the "Related XML Attributes" section is missing in the ImageView.setAlpha(int) documentation. The alternative is to use View.setAlpha(float) whose XML counterpart is android:alpha
. It takes a range of 0.0 to 1.0 instead of 0 to 255. Use it e.g. like
<ImageView android:alpha="0.4">
However, the latter in available only since API level 11.
The line
SELECT @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))
is wrong.
@Prefix
is 'J'
and LEN(...anything...)
is an int
, hence the type mismatch.
It seems to me, you actually want to do,
SELECT
@maxCode = MAX(
CAST(SUBSTRING(
Voucher_No,
@startFrom + 1,
LEN(Voucher_No) - (@startFrom + 1)) AS INT)
FROM
dbo.Journal_Entry;
SELECT @Prefix + CAST(@maxCode AS VARCHAR(10));
but, I couldn't say. If you illustrated before and after data, it would help.
In the Windows command prompt you can disable tab completion, by launching it thusly:
cmd.exe /f:off
Then the tab character will be echoed to the screen and work as you expect. Or you can disable the tab completion character, or modify what character is used for tab completion by modifying the registry.
The cmd.exe
help page explains it:
You can enable or disable file name completion for a particular invocation of CMD.EXE with the /F:ON or /F:OFF switch. You can enable or disable completion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDIT.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar and/or HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar
with the hex value of a control character to use for a particular function (e.g. 0x4 is Ctrl-D and 0x6 is Ctrl-F). The user specific settings take precedence over the machine settings. The command line switches take precedence over the registry settings.
If completion is enabled with the /F:ON switch, the two control characters used are Ctrl-D for directory name completion and Ctrl-F for file name completion. To disable a particular completion character in the registry, use the value for space (0x20) as it is not a valid control character.
To use arrow functions with function.prototype.call
, I made a helper function on the object prototype:
// Using
// @func = function() {use this here} or This => {use This here}
using(func) {
return func.call(this, this);
}
usage
var obj = {f:3, a:2}
.using(This => This.f + This.a) // 5
Edit
You don't NEED a helper. You could do:
var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5
If you just need swipe, you are better off size wise just using only the part you need. This should work on any touch device.
This is ~450 bytes' after gzip compression, minification, babel etc.
I wrote the below class based on the other answers, it uses percentage moved instead of pixels, and a event dispatcher pattern to hook/unhook things.
Use it like so:
const dispatcher = new SwipeEventDispatcher(myElement);
dispatcher.on('SWIPE_RIGHT', () => { console.log('I swiped right!') })
export class SwipeEventDispatcher {_x000D_
constructor(element, options = {}) {_x000D_
this.evtMap = {_x000D_
SWIPE_LEFT: [],_x000D_
SWIPE_UP: [],_x000D_
SWIPE_DOWN: [],_x000D_
SWIPE_RIGHT: []_x000D_
};_x000D_
_x000D_
this.xDown = null;_x000D_
this.yDown = null;_x000D_
this.element = element;_x000D_
this.options = Object.assign({ triggerPercent: 0.3 }, options);_x000D_
_x000D_
element.addEventListener('touchstart', evt => this.handleTouchStart(evt), false);_x000D_
element.addEventListener('touchend', evt => this.handleTouchEnd(evt), false);_x000D_
}_x000D_
_x000D_
on(evt, cb) {_x000D_
this.evtMap[evt].push(cb);_x000D_
}_x000D_
_x000D_
off(evt, lcb) {_x000D_
this.evtMap[evt] = this.evtMap[evt].filter(cb => cb !== lcb);_x000D_
}_x000D_
_x000D_
trigger(evt, data) {_x000D_
this.evtMap[evt].map(handler => handler(data));_x000D_
}_x000D_
_x000D_
handleTouchStart(evt) {_x000D_
this.xDown = evt.touches[0].clientX;_x000D_
this.yDown = evt.touches[0].clientY;_x000D_
}_x000D_
_x000D_
handleTouchEnd(evt) {_x000D_
const deltaX = evt.changedTouches[0].clientX - this.xDown;_x000D_
const deltaY = evt.changedTouches[0].clientY - this.yDown;_x000D_
const distMoved = Math.abs(Math.abs(deltaX) > Math.abs(deltaY) ? deltaX : deltaY);_x000D_
const activePct = distMoved / this.element.offsetWidth;_x000D_
_x000D_
if (activePct > this.options.triggerPercent) {_x000D_
if (Math.abs(deltaX) > Math.abs(deltaY)) {_x000D_
deltaX < 0 ? this.trigger('SWIPE_LEFT') : this.trigger('SWIPE_RIGHT');_x000D_
} else {_x000D_
deltaY > 0 ? this.trigger('SWIPE_UP') : this.trigger('SWIPE_DOWN');_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
export default SwipeEventDispatcher;
_x000D_
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
select
(select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...
You can run something like
git ls-files | xargs wc -l
which will give you the total count ?
Or use this tool ? http://line-count.herokuapp.com/
Java 8 added a new way of making Comparators that reduces the amount of code you have to write, Comparator.comparing. Also check out Comparator.reversed
Here's a sample
import org.junit.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class ComparatorTest {
@Test
public void test() {
List<Person> peopleList = new ArrayList<>();
peopleList.add(new Person("A", 1000));
peopleList.add(new Person("B", 1));
peopleList.add(new Person("C", 50));
peopleList.add(new Person("Z", 500));
//sort by name, ascending
peopleList.sort(Comparator.comparing(Person::getName));
assertTrue(peopleList.get(0).getName().equals("A"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("Z"));
//sort by name, descending
peopleList.sort(Comparator.comparing(Person::getName).reversed());
assertTrue(peopleList.get(0).getName().equals("Z"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("A"));
//sort by age, ascending
peopleList.sort(Comparator.comparing(Person::getAge));
assertTrue(peopleList.get(0).getAge() == 1);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1000);
//sort by age, descending
peopleList.sort(Comparator.comparing(Person::getAge).reversed());
assertTrue(peopleList.get(0).getAge() == 1000);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1);
}
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
}
i tend to use simple forward code as much as i can ,below code worked fine with me
using System;
using System.IO;
using System.Text.RegularExpressions;
/// <summary>
/// Replaces text in a file.
/// </summary>
/// <param name="filePath">Path of the text file.</param>
/// <param name="searchText">Text to search for.</param>
/// <param name="replaceText">Text to replace the search text.</param>
static public void ReplaceInFile( string filePath, string searchText, string replaceText )
{
StreamReader reader = new StreamReader( filePath );
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace( content, searchText, replaceText );
StreamWriter writer = new StreamWriter( filePath );
writer.Write( content );
writer.Close();
}
REST
is an architectural style and a design for network-based software architectures.
REST
concepts are referred to as resources. A representation of a resource must be stateless. It is represented via some media type. Some examples of media types include XML
, JSON
, and RDF
. Resources are manipulated by components. Components request and manipulate resources via a standard uniform interface. In the case of HTTP, this interface consists of standard HTTP ops e.g. GET
, PUT
, POST
, DELETE
.
REST
is typically used over HTTP
, primarily due to the simplicity of HTTP and its very natural mapping to RESTful principles. REST however is not tied to any specific protocol.
Client-Server Communication
Client-server architectures have a very distinct separation of concerns. All applications built in the RESTful style must also be client-server in principle.
Stateless
Each client request to the server requires that its state be fully represented. The server must be able to completely understand the client request without using any server context or server session state. It follows that all state must be kept on the client. We will discuss stateless representation in more detail later.
Cacheable
Cache constraints may be used, thus enabling response data to to be marked as cacheable or not-cachable. Any data marked as cacheable may be reused as the response to the same subsequent request.
Uniform Interface
All components must interact through a single uniform interface. Because all component interaction occurs via this interface, interaction with different services is very simple. The interface is the same! This also means that implementation changes can be made in isolation. Such changes, will not affect fundamental component interaction because the uniform interface is always unchanged. One disadvantage is that you are stuck with the interface. If an optimization could be provided to a specific service by changing the interface, you are out of luck as REST prohibits this. On the bright side, however, REST is optimized for the web, hence incredible popularity of REST over HTTP!
The above concepts represent defining characteristics of REST and differentiate the REST architecture from other architectures like web services. It is useful to note that a REST service is a web service, but a web service is not necessarily a REST service.
See this blog post on REST Design Principals for more details on REST and the above principles.
Use the javaScript Function escape(), that lets you encode strings.
e.g.,
escape("yourString");
If you have USB-Debugging/ADB enabled on your phone and your PC is authorized for debugging on your phone then you can try one of the follwing tools:
scrcpy connects over adb to your device and executes a temporary app to stream the contents of your screen to your PC and you're able to remote control your device. It works on GNU/Linux, Windows and macOS.
Vysor is a chrome web app that connects to your device via adb and installs a companion app to stream your screen content to the PC. You can then remote control your device with your mouse.
MonkeyRemote is a remote control tool written by myself before I found Vysor. It also connects through adb and lets you control your device by mouse but in contrast to Vysor, the streamed screen content updates very slow (~1 frame per second). The upside is that there is no need for a companion app to be installed.
like Answers above, if you do bootstrap 4 just add few line of css to .carousel , carousel-inner ,carousel-item and img as follows
.carousel .carousel-inner{
height:500px
}
.carousel-inner .carousel-item img{
min-height:200px;
//prevent it from stretch in screen size < than 768px
object-fit:cover
}
@media(max-width:768px){
.carousel .carousel-inner{
//prevent it from adding a white space between carousel and container elements
height:auto
}
}
list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)
from tkinter import *
def close_window():
import sys
sys.exit()
root = Tk()
frame = Frame (root)
frame.pack()
button = Button (frame, text="Good-bye", command=close_window)
button.pack()
mainloop()
I generally implement this usecase using org.apache.commons.lang3.builder.EqualsBuilder
Assert.assertTrue(EqualsBuilder.reflectionEquals(expected,actual));
If you store an object in session state, that object must be serializable.
edit:
In order for the session to be serialized correctly, all objects the application stores as session attributes must declare the [Serializable] attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable interface.
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
Try using file to view the encoding details (reference):
cd directory/of/interest
file *
It produces useful output like this:
$ file *
CR6Series_stats resaved.dat: ASCII text, with very long lines, with CRLF line terminators
CR6Series_stats utf8.dat: UTF-8 Unicode (with BOM) text, with very long lines, with CRLF line terminators
CR6Series_stats.dat: ASCII text, with very long lines, with CRLF line terminators
readme.md: ASCII text, with CRLF line terminators
Try using a class method:
+(NSString*)theMainTitle
{
return @"Hello World";
}
I use it sometimes.
From the docs:
public Form createNamed(string|FormTypeInterface $type, string $name, mixed $data = null, array $options = array())
mixed $data = null is the default options. So for example I have a field called status and I implemented it as so:
$default = array('Status' => 'pending');
$filter_form = $this->get('form.factory')->createNamedBuilder('filter', 'form', $default)
->add('Status', 'choice', array(
'choices' => array(
'' => 'Please Select...',
'rejected' => 'Rejected',
'incomplete' => 'Incomplete',
'pending' => 'Pending',
'approved' => 'Approved',
'validated' => 'Validated',
'processed' => 'Processed'
)
))->getForm();
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
This will scroll to the end of the textbox when the text is changed, but still allows the user to scroll up
outbox.SelectionStart = outbox.Text.Length;
outbox.ScrollToEnd();
tested on Visual Studio Enterprise 2017
Your issue is not really with Angular, but with Array methods. The proper way to remove a particularly item from an array is with Array.splice
. Also, when using ng-repeat, you have access to the special $index
property, which is the current index of the array you passed in.
The solution is actually pretty straightforward:
View:
<a ng-click="delete($index)">Delete</a>
Controller:
$scope.delete = function ( idx ) {
var person_to_delete = $scope.persons[idx];
API.DeletePerson({ id: person_to_delete.id }, function (success) {
$scope.persons.splice(idx, 1);
});
};
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
This seems to work for me at least when i tried on visual studio 2017.
public static class Words
{
public const string temp = "What";
public const string temp2 = "the";
}
var i = "the";
switch (i)
{
case Words.temp:
break;
case Words.temp2:
break;
}
I had to enable HTTP Activation
in .NET Framework 4.5 Advanced Services
> WCF Services
Any time you get the...
"Fatal error: Call to a member function bind_param() on boolean"
...it is likely because there is an issue with your query. The prepare()
might return FALSE
(a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php
tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log
. If you're examining error logs in a Linux environment you can use tail -f /path/to/log
in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare()
statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case there is no foo
column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.
There should be better ways but what I did today was:
Download from https://github.com/protocolbuffers/protobuf/releases (protoc-3.14.0-osx-x86_64.zip
at this moment)
Unzip (double click the zip
file)
Here, I added a symbolic link
ln -s ~/Downloads/protoc-3.14.0-osx-x86_64/bin/protoc /usr/local/bin/protoc
protoc --version
You can do this directly with tar and even better:
tar -N '2014-02-01 18:00:00' -jcvf archive.tar.bz2 files
This instructs tar to compress files newer than 1st of January 2014, 18:00:00.
Let's bring this question back from the dead ;) There is a reason Google doesn't give you a simple solution. Special cases and browser quirks affect the calculation, and it is not as trivial as it seems to be.
Unfortunately, there are problems with the solutions outlined here so far. I don't mean to disparage them at all - they are great starting points and touch on all the key properties needed for a more robust approach. But I wouldn't recommend copying and pasting the code from any of the other answers because
$( document ).width()
and .height()
fall prey to jQuery's buggy detection of document size.window.innerWidth
, if the browser supports it, makes your code fail to detect scroll bars in mobile browsers, where the width of the scroll bar is generally 0. They are just shown temporarily as an overlay and don't take up space in the document. Zooming on mobile also becomes a problem that way (long story).html
and body
element to non-default values (what happens then is a little involved - see this description). I have spent more time than I would have imagined on a finding a solution that "just works" (cough). The algorithm I have come up with is now part of a plugin, jQuery.isInView, which exposes a .hasScrollbar
method. Have a look at the source if you wish.
In a scenario where you are in full control of the page and don't have to deal with unknown CSS, using a plugin may be overkill - after all, you know which edge cases apply, and which don't. However, if you need reliable results in an unknown environment, then I don't think the solutions outlined here will be enough. You are better off using a well-tested plugin - mine or anybody elses.
No need to add extra elements. While flexbox uses very non-intuitive property names if you know what it can do you'll find yourself using it quite often.
<div style="display: flex; justify-content: space-between;">
<span>Item Left</span>
<span>Item Right</span>
</div>
Plan on needing this often?
.align_between {display: flex; justify-content: space-between;}
I see other people using secondary words in the primary position which makes a mess of information hierarchy. If align is the primary task and right, left, and/or between are the secondary the class should be .align_outer
, not .outer_align
as it will make sense as you vertically scan your code:
.align_between {}
.align_left {}
.align_outer {}
.align_right {}
Good habits over time will allow you to get to bed sooner than later.
If the list is fixed in the script, I like the following the best:
validate() {
grep -F -q -x "$1" <<EOF
item 1
item 2
item 3
EOF
}
Then use validate "$x"
to test if $x
is allowed.
If you want a one-liner, and don't care about whitespace in item names, you can use this (notice -w
instead of -x
):
validate() { echo "11 22 33" | grep -F -q -w "$1"; }
Notes:
sh
compliant.validate
does not accept substrings (remove the -x
option to grep if you want that).validate
interprets its argument as a fixed string, not a regular
expression (remove the -F
option to grep if you want that).Sample code to exercise the function:
for x in "item 1" "item2" "item 3" "3" "*"; do
echo -n "'$x' is "
validate "$x" && echo "valid" || echo "invalid"
done
To convert your JSON string to hashmap you can make use of this :
HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;
Use this class :) (handles even lists , nested lists and json)
public class Utility {
public static Map<String, Object> jsonToMap(Object json) throws JSONException {
if(json instanceof JSONObject)
return _jsonToMap_((JSONObject)json) ;
else if (json instanceof String)
{
JSONObject jsonObject = new JSONObject((String)json) ;
return _jsonToMap_(jsonObject) ;
}
return null ;
}
private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
This worked for me, including recursively into submodules (perhaps that's why your -f didn't work, cause you changed a submodule inside the submodule):
git submodule update -f --recursive
From my experience, it usually means one of the prior cells is keeping the kernel busy. When you hit run on the intended cell and [*]
appears, from there, try to scroll up to the prior cell which is also advertising a [*]
. Then goto kernel
->interrupt
, and lastly, try running the cell again.
According to the documentation, it is better to handle multiple exceptions through tuples or like this:
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error: ", sys.exc_info()[0]
raise
This will work:
select * into DestinationDatabase.dbo.[TableName1] from (
Select * from sourceDatabase.dbo.[TableName1])Temp
You will not be able to retrieve a plain text password from wordpress.
Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.
See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password
i was also getting this error, remove oracle folder from
C:\Program Files (x86)\Oracle\Inventory
and
C:\Program Files\Oracle\Inventory
Also remove all component of oracle other version (which you had already in your system).
Go to services and remove all oracle component and delete old client from
C:\app\username\product\11.2.0\client_1\
This syntax isn't valid in any version of PostgreSQL:
ALTER SEQUENCE payments_id_seq LASTVALUE 22
This would work:
ALTER SEQUENCE payments_id_seq RESTART WITH 22;
And is equivalent to:
SELECT setval('payments_id_seq', 22, FALSE);
More in the current manual for ALTER SEQUENCE
and sequence functions.
Note that setval()
expects either (regclass, bigint)
or (regclass, bigint, boolean)
. In the above example I am providing untyped literals. That works too. But if you feed typed variables to the function you may need explicit type casts to satisfy function type resolution. Like:
SELECT setval(my_text_variable::regclass, my_other_variable::bigint, FALSE);
For repeated operations you might be interested in:
ALTER SEQUENCE payments_id_seq START WITH 22; -- set default
ALTER SEQUENCE payments_id_seq RESTART; -- without value
START [WITH]
stores a default RESTART
number, which is used for subsequent RESTART
calls without value. You need Postgres 8.4 or later for the last part.
I was having the problem as a beginner..........
There was issue in the path of the xml file I have saved.
You can use Git GUI on Windows, see instructions:
Here's some code with a dummy geom_blank
layer,
range_act <- range(range(results$act), range(results$pred))
d <- reshape2::melt(results, id.vars = "pred")
dummy <- data.frame(pred = range_act, value = range_act,
variable = "act", stringsAsFactors=FALSE)
ggplot(d, aes(x = pred, y = value)) +
facet_wrap(~variable, scales = "free") +
geom_point(size = 2.5) +
geom_blank(data=dummy) +
theme_bw()
It will use the equals method to see if the key is present even and especially if there are more than one element in the same bucket.
Getting the object keys to get the object values. Using map() to add new Options.
const selectValues = {_x000D_
"1": "test 1",_x000D_
"2": "test 2"_x000D_
}_x000D_
const selectTest = document.getElementById('selectTest')_x000D_
Object.keys(selectValues).map(key => selectTest.add(new Option(selectValues[key], key)))
_x000D_
<select id="selectTest"></select>
_x000D_
Don't forget that you can also redirect constructors to other constructors at the same level of inheritance:
public Bar(int i, int j) : this(i) { ... }
^^^^^
Incase you're looping the OR conditions, you don't need the the second $query->where from the other posts (actually I don't think you need in general, you can just use orWhere in the nested where if easier)
$attributes = ['first'=>'a','second'=>'b'];
$query->where(function ($query) use ($attributes)
{
foreach ($attributes as $key=>value)
{
//you can use orWhere the first time, doesn't need to be ->where
$query->orWhere($key,$value);
}
});
You can do this with Object.assign()
.
In your example, you would do:
ReactDOM.render(
<div style={Object.assign(divStyle, divStyle2)}>
Hello World!
</div>,
mountNode
);
That will merge the two styles. The second style will replace the first if there are matching properties.
As Brandon noted, you should use Object.assign({}, divStyle, divStyle2)
if you want to reuse divStyle
without the fontSize applied to it.
I like to use this to make components with default properties. For example, here's a little stateless component with a default margin-right
:
const DivWithDefaults = ({ style, children, ...otherProps }) =>
<div style={Object.assign({ marginRight: "1.5em" }, style)} {...otherProps}>
{children}
</div>;
So we can render something like this:
<DivWithDefaults>
Some text.
</DivWithDefaults>
<DivWithDefaults className="someClass" style={{ width: "50%" }}>
Some more text.
</DivWithDefaults>
<DivWithDefaults id="someID" style={{ marginRight: "10px", height: "20px" }}>
Even more text.
</DivWithDefaults>
Which will give us the result:
<div style="margin-right:1.5em;">Some text.</div>
<div style="margin-right:1.5em;width50%;" class="someClass">Some more text.</div>
<div style="margin-right:10px;height:20px;" id="someID">Even more text.</div>
VB.NET doesn't support for multi line comment.
The only way to do multi-line comments in VB.NET is to do a lot of single line comments('
).
Or just highlight the whole code and just use (Ctrl+E,C)
, (Ctrl+E,U)
to comment or uncomment.
Only in c# /* */
Or in ASP.NET html source using <!-- -->
.
Ensure the database's backup mode is set to Simple (see here for an overview of the different modes). This will avoid SQL Server waiting for a transaction log backup before reusing space.
Use dbcc shrinkfile
or Management Studio to shrink the log files.
Step #2 will do nothing until the backup mode is set.
Actually, contrary to the other answers, I believe that OP's solution is the one that is most elegant.
Here's what you gain by using an external .bat
wrapper:
main()
?system("pause")
here.enter
keypress (unless you do things mentioned in the footnote).cmd.exe
on Windows platform), they don't want to wait, since they'll see the output anyway. With the .bat
wrapper technique, they can decide whether to run the .bat
(or .sh
) wrapper, or run the executable directly.Focusing on the last two points - with any other technique, I'd expect the program to offer at least --no-wait
switch so that I, as the user, can use the application with all sort of operations such as piping the output, chaining it with other programs etc. These are part of normal CLI workflow, and adding waiting at the end when you're already inside a terminal just gets in the way and destroys user experience.
For these reasons, IMO .bat
solution is the nicest here.
I use eUML2 plugin from Soyatec, under Eclipse and it works fine for the generation of UML giving the source code. This tool is useful up to Eclipse 4.4.x
Give it a chance:
Try getting string via function gets(string) then check condition as if(string[0] == '\0')
In your receiving intent you need to do:
Intent i = getIntent();
stock_list = i.getStringArrayListExtra("stock_list");
The way you have it you've just created a new empty intent without any extras.
If you only have a single extra you can condense this down to:
stock_list = getIntent().getStringArrayListExtra("stock_list");
I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.
//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
"ln": {c.ln},
"ip": {c.ip},
"ua": {c.ua}})
//okay, moving on...
if err != nil {
//handle postform error
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
//handle read response error
}
fmt.Printf("%s\n", string(body))
I did that in the following way for an image, you should be able to do it for text using similar steps.
// folder & name of image on PC
File fileObj = new File("C:\\Displayable\\imgcopy.jpg");
Boolean testB = fileObj.createNewFile();
System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);
// image on server
URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg");
InputStream webIS = url.openStream();
FileOutputStream fo = new FileOutputStream(fileObj);
int c = 0;
do {
c = webIS.read();
System.out.println("==============> " + c);
if (c !=-1) {
fo.write((byte) c);
}
} while(c != -1);
webIS.close();
fo.close();
Make sure to include the Bootstrap CSS either via the Bootstrap CDN or download it and link it locally
Your error message is pretty explicit about what is going wrong:
laravel/framework v5.2.9 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
Do you have mbstring
installed on your server and is it enabled?
You can install mbstring
as part of the libapache2-mod-php5 package:
sudo apt-get install libapache2-mod-php5
Or standalone with:
sudo apt-get install php-mbstring
Installing it will also enable it, however you can also enable it by editing your php.ini
file and remove the ;
that is commenting it out if it is already installed.
If this is on your local machine, then follow the appropriate steps to install this on your environment.
The solutions of Fabricio works just fine.
A very common usecase of calc is add 100% width and adding some margin around the element.
One can do so with:
@someMarginVariable: 15px;
margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);
width: -o-calc(~"100% - "@someMarginVariable*2);
Or can use a mixin like:
.fullWidthMinusMarginPaddingMixin(@marginSize,@paddingSize) {
@minusValue: (@marginSize+@paddingSize)*2;
padding: @paddingSize;
margin: @marginSize;
width: calc(~"100% - "@minusValue);
width: -moz-calc(~"100% - "@minusValue);
width: -webkit-calc(~"100% - "@minusValue);
width: -o-calc(~"100% - "@minusValue);
}
If you don't want to use CSS try this one between your rows:
<tr>
<td class="divider"><hr /></td>
</tr>
Cheers!!
For API level 17 or higher, View.generateViewId()
will solve this problem. The utility method provides a unique id that is not used in build time.
@abdu
The main thing I've found that MySQL has over MSSQL is timezone support - the ability to nicely change between timezones, respecting daylight savings is fantastic.
Compare this:
mysql> SELECT CONVERT_TZ('2008-04-01 12:00:00', 'UTC', 'America/Los_Angeles');
+-----------------------------------------------------------------+
| CONVERT_TZ('2008-04-01 12:00:00', 'UTC', 'America/Los_Angeles') |
+-----------------------------------------------------------------+
| 2008-04-01 05:00:00 |
+-----------------------------------------------------------------+
to the contortions involved at this answer.
As for the 'easier to use' comment, I would say that the point is that they are different, and if you know one, there will be an overhead in learning the other.
AngularJS pass string, numbers and booleans by value while it passes arrays and objects by reference. So you can create an empty object and make your date a property of that object. In that way angular will detect model changes.
In controller
app.module('yourModule').controller('yourController',function($scope){
$scope.vm={selectedDate:''}
});
In html
<div ng-controller="yourController">
<input id="selectedDueDate" type="text" ng-model="vm.selectedDate" />
</div>
it's because the name of the submit button is named "submit", change it to anything but "submit", try "submitme" and retry it. It should then work.
By default [Route("api/[controller]") will generated by .Net Core/Asp.Net Web API.You need to modify little bit,just add [Action] like [Route("api/[controller]/[action]")]. I have mentioned a dummy solution:
// Default generated controller
//
[Route("api/[controller]")
public class myApiController : Controller
{
[HttpGet]
public string GetInfo()
{
return "Information";
}
}
//
//A little change would do the magic
//
[Route("api/[controller]/[action]")]
public class ServicesController : Controller
{
[HttpGet]
[ActionName("Get01")]
public string Get01()
{
return "GET 1";
}
[HttpGet]
[ActionName("Get02")]
public string Get02()
{
return "Get 2";
}
[HttpPost]
[ActionName("Post01")]
public HttpResponseMessage Post01(MyCustomModel01 model)
{
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
//.. DO Something ..
return Request.CreateResonse(HttpStatusCode.OK, "Optional Message");
}
[HttpPost]
[ActionName("Post02")]
public HttpResponseMessage Post02(MyCustomModel02 model)
{
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
//.. DO Something ..
return Request.CreateResonse(HttpStatusCode.OK, "Optional Message");
}
}
Try using sendmail instead of smtp driver (according to these recommendations: http://code.tutsplus.com/tutorials/sending-emails-with-laravel-4-gmail--net-36105)
MAIL_DRIVER=sendmail
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=apppassword
MAIL_ENCRYPTION=tls
I believe that join()
is just a convenience method. Try df1.merge(df2)
instead, which allows you to specify left_on
and right_on
:
In [30]: left.merge(right, left_on="key1", right_on="key2")
Out[30]:
key1 lval key2 rval
0 foo 1 foo 4
1 bar 2 bar 5
SELECT *
FROM (SELECT * FROM MyTbl ORDER BY Fname )
WHERE ROWNUM = 1;
If you want to run test methods in a specific order in JUnit 5, you can use the below code.
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class MyClassTest {
@Test
@Order(1)
public void test1() {}
@Test
@Order(2)
public void test2() {}
}
This is late, but here is my python implementation of the flowingdata NBA heatmap.
updated:1/4/2014: thanks everyone
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# ------------------------------------------------------------------------
# Filename : heatmap.py
# Date : 2013-04-19
# Updated : 2014-01-04
# Author : @LotzJoe >> Joe Lotz
# Description: My attempt at reproducing the FlowingData graphic in Python
# Source : http://flowingdata.com/2010/01/21/how-to-make-a-heatmap-a-quick-and-easy-solution/
#
# Other Links:
# http://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor
#
# ------------------------------------------------------------------------
import matplotlib.pyplot as plt
import pandas as pd
from urllib2 import urlopen
import numpy as np
%pylab inline
page = urlopen("http://datasets.flowingdata.com/ppg2008.csv")
nba = pd.read_csv(page, index_col=0)
# Normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())
# Sort data according to Points, lowest to highest
# This was just a design choice made by Yau
# inplace=False (default) ->thanks SO user d1337
nba_sort = nba_norm.sort('PTS', ascending=True)
nba_sort['PTS'].head(10)
# Plot it out
fig, ax = plt.subplots()
heatmap = ax.pcolor(nba_sort, cmap=plt.cm.Blues, alpha=0.8)
# Format
fig = plt.gcf()
fig.set_size_inches(8, 11)
# turn off the frame
ax.set_frame_on(False)
# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(nba_sort.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(nba_sort.shape[1]) + 0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
# Set the labels
# label source:https://en.wikipedia.org/wiki/Basketball_statistics
labels = [
'Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 'Free throws attempts', 'Free throws percentage',
'Three-pointers made', 'Three-point attempt', 'Three-point percentage', 'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']
# note I could have used nba_sort.columns but made "labels" instead
ax.set_xticklabels(labels, minor=False)
ax.set_yticklabels(nba_sort.index, minor=False)
# rotate the
plt.xticks(rotation=90)
ax.grid(False)
# Turn off all the ticks
ax = plt.gca()
for t in ax.xaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
for t in ax.yaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
The output looks like this:
There's an ipython notebook with all this code here. I've learned a lot from 'overflow so hopefully someone will find this useful.
the best way to prevent multiple from submission is this just pass the button id in the method.
function DisableButton() {
document.getElementById("btnPostJob").disabled = true;
}
window.onbeforeunload = DisableButton;
Deprecated in iOS 9.0.
There`s much more fast then UIImageWriteToSavedPhotosAlbum way to do it using iOS 4.0+ AssetsLibrary framework
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
// TODO: error handling
} else {
// TODO: success handling
}
}];
[library release];
If there is a piece of code that you repeat all the time according to Don't Repeat Yourself you should put it in your own library and call that. With that in mind there are 2 aspects to getting the right answer here. The first is clarity and brevity in the code that calls the library function. The second is the performance implications of foreach.
First let's think about the clarity and brevity in the calling code.
You can do foreach in a number of ways:
Out of all the ways to do a foreach List.ForEach with a lamba is the clearest and briefest.
list.ForEach(i => Console.Write("{0}\t", i));
So at this stage it may look like the List.ForEach is the way to go. However what's the performance of this? It's true that in this case the time to write to the console will govern the performance of the code. When we know something about performance of a particular language feature we should certainly at least consider it.
According to Duston Campbell's performance measurements of foreach the fastest way of iterating the list under optimised code is using a for loop without a call to List.Count.
The for loop however is a verbose construct. It's also seen as a very iterative way of doing things which doesn't match with the current trend towards functional idioms.
So can we get brevity, clarity and performance? We can by using an extension method. In an ideal world we would create an extension method on Console that takes a list and writes it with a delimiter. We can't do this because Console is a static class and extension methods only work on instances of classes. Instead we need to put the extension method on the list itself (as per David B's suggestion):
public static void WriteLine(this List<int> theList)
{
foreach (int i in list)
{
Console.Write("{0}\t", t.ToString());
}
Console.WriteLine();
}
This code is going to used in many places so we should carry out the following improvements:
Here's how the code for the function would look:
public static void WriteToConsole<T>(this IList<T> collection)
{
int count = collection.Count();
for(int i = 0; i < count; ++i)
{
Console.Write("{0}\t", collection[i].ToString(), delimiter);
}
Console.WriteLine();
}
We can improve this even further by allowing the client to pass in the delimiter. We could then provide a second function that writes to console with the standard delimiter like this:
public static void WriteToConsole<T>(this IList<T> collection)
{
WriteToConsole<T>(collection, "\t");
}
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
int count = collection.Count();
for(int i = 0; i < count; ++i)
{
Console.Write("{0}{1}", collection[i].ToString(), delimiter);
}
Console.WriteLine();
}
So now, given that we want a brief, clear performant way of writing lists to the console we have one. Here is entire source code including a demonstration of using the the library function:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleWritelineTest
{
public static class Extensions
{
public static void WriteToConsole<T>(this IList<T> collection)
{
WriteToConsole<T>(collection, "\t");
}
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
int count = collection.Count();
for(int i = 0; i < count; ++i)
{
Console.Write("{0}{1}", collection[i].ToString(), delimiter);
}
Console.WriteLine();
}
}
internal class Foo
{
override public string ToString()
{
return "FooClass";
}
}
internal class Program
{
static void Main(string[] args)
{
var myIntList = new List<int> {1, 2, 3, 4, 5};
var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};
var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};
var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};
// Using the standard delimiter /t
myIntList.WriteToConsole();
myDoubleList.WriteToConsole();
myDoubleArray.WriteToConsole();
myFooList.WriteToConsole();
// Using our own delimiter ~
myIntList.WriteToConsole("~");
Console.Read();
}
}
}
=======================================================
You might think that this should be the end of the answer. However there is a further piece of generalisation that can be done. It's not clear from fatcat's question if he is always writing to the console. Perhaps something else is to be done in the foreach. In that case Jason Bunting's answer is going to give that generality. Here is his answer again:
list.ForEach(i => Console.Write("{0}\t", i));
That is unless we make one more refinement to our extension methods and add FastForEach as below:
public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)
{
int count = collection.Count();
for (int i = 0; i < count; ++i)
{
actionToPerform(collection[i]);
}
Console.WriteLine();
}
This allows us to execute any arbitrary code against every element in the collection using the fastest possible iteration method.
We can even change the WriteToConsole function to use FastForEach
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
collection.FastForEach(item => Console.Write("{0}{1}", item.ToString(), delimiter));
}
So now the entire source code, including an example usage of FastForEach is:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleWritelineTest
{
public static class Extensions
{
public static void WriteToConsole<T>(this IList<T> collection)
{
WriteToConsole<T>(collection, "\t");
}
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
collection.FastForEach(item => Console.Write("{0}{1}", item.ToString(), delimiter));
}
public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)
{
int count = collection.Count();
for (int i = 0; i < count; ++i)
{
actionToPerform(collection[i]);
}
Console.WriteLine();
}
}
internal class Foo
{
override public string ToString()
{
return "FooClass";
}
}
internal class Program
{
static void Main(string[] args)
{
var myIntList = new List<int> {1, 2, 3, 4, 5};
var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};
var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};
var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};
// Using the standard delimiter /t
myIntList.WriteToConsole();
myDoubleList.WriteToConsole();
myDoubleArray.WriteToConsole();
myFooList.WriteToConsole();
// Using our own delimiter ~
myIntList.WriteToConsole("~");
// What if we want to write them to separate lines?
myIntList.FastForEach(item => Console.WriteLine(item.ToString()));
Console.Read();
}
}
}
Simply add these two dependencies in the pom file: I have tried and succeed after trying the discussion before.
<!--Using logback-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
Commons-Logging -> Logback and default Info while Debug will not be present; You can use:
private static Logger log = LoggerFactory.getLogger(HuaweiAPI.class);
to define the information you want to log:like Final Result like this. Only the information I want to log will be present.
IIRC, the INSERT INTO command uses the schema of the source table to create the temp table. That's part of the reason you can't just try to create a table with an additional column. Identity columns are internally tied to a SQL Server construct called a generator.
Suppose you want the value of the first item.
ListBox list = new ListBox();
Console.Write(list.Items[0].Value);
Believe me or not... I tried out almost each answer I had found here on stackoverflow. Nothing would help, until I just restarted the machine. My Android Studio works on Ubuntu 16.04 LTS.
All arguments in Java are passed by value. When you pass a String
to a function, the value that's passed is a reference to a String object, but you can't modify that reference, and the underlying String object is immutable.
The assignment
zText += foo;
is equivalent to:
zText = new String(zText + "foo");
That is, it (locally) reassigns the parameter zText
as a new reference, which points to a new memory location, in which is a new String
that contains the original contents of zText
with "foo"
appended.
The original object is not modified, and the main()
method's local variable zText
still points to the original (empty) string.
class StringFiller {
static void fillString(String zText) {
zText += "foo";
System.out.println("Local value: " + zText);
}
public static void main(String[] args) {
String zText = "";
System.out.println("Original value: " + zText);
fillString(zText);
System.out.println("Final value: " + zText);
}
}
prints:
Original value:
Local value: foo
Final value:
If you want to modify the string, you can as noted use StringBuilder
or else some container (an array or an AtomicReference
or a custom container class) that gives you an additional level of pointer indirection. Alternatively, just return the new value and assign it:
class StringFiller2 {
static String fillString(String zText) {
zText += "foo";
System.out.println("Local value: " + zText);
return zText;
}
public static void main(String[] args) {
String zText = "";
System.out.println("Original value: " + zText);
zText = fillString(zText);
System.out.println("Final value: " + zText);
}
}
prints:
Original value:
Local value: foo
Final value: foo
This is probably the most Java-like solution in the general case -- see the Effective Java item "Favor immutability."
As noted, though, StringBuilder
will often give you better performance -- if you have a lot of appending to do, particularly inside a loop, use StringBuilder
.
But try to pass around immutable Strings
rather than mutable StringBuilders
if you can -- your code will be easier to read and more maintainable. Consider making your parameters final
, and configuring your IDE to warn you when you reassign a method parameter to a new value.
Use runlike from git repository https://github.com/lavie/runlike
To install runlike
pip install runlike
As it accept container id as an argument so to extract container id use following command
docker ps -a -q
You are good to use runlike to extract complete docker run command with following command
runlike <docker container ID>
Writing the actual condition can be the tricky part, so I tend to
Advantages of using the Immediate window:
This example breaks when the code is referring to a table with the name "Setting":
table.GetTableName().Contains("Setting")
I edited the most voted one a little cuz it didn't count blanks columns or rows well not totally, so here is my code i tested it and now can get any cell in any part of an excel file. also now u can have blanks columns between filled column and it will read them
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
int cblacks=0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i <= 10 || i <= rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp >= cols) cols = tmp;else{rows++;cblacks++;}
}
cols++;
}
cols=cols+cblacks;
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell(c);
if(cell != null) {
System.out.print(cell+"\n");//Your Code here
}
}
}
}} catch(Exception ioe) {
ioe.printStackTrace();}
If you need to download only text file into String
you can use this simple way, Swift 5:
let list = try? String(contentsOf: URL(string: "https://example.com/file.txt")!)
In case you want non optional result or error handling:
do {
let list = try String(contentsOf: URL(string: "https://example.com/file.txt")!)
}
catch {
// Handle error here
}
You should know that network operations may take some time, to prevent it from running in main thread and locking your UI, you may want to execute the code asynchronously, for example:
DispatchQueue.global().async {
let list = try? String(contentsOf: URL(string: "https://example.com/file.txt")!)
}
The following works for me
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/playground", { useNewUrlParser: true,useUnifiedTopology: true })
.then(res => console.log('Connected to db'));
The mongoose
version is 5.8.10
.
You can use a combination of substring and lastIndexOf
Sample
var fileName = "test.jpg";
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
In Python 3, print is a function, you need to call it like print("hello world")
.
Drop database exist in all versions of MySQL. But if you want to keep the table structure, here is an idea
mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql
This is a program, not a mysql command
Then, log into mysql and
source dump.sql;
In general, the simplest (and quite optimal) algorithm is checking on which side of the half-plane created by the edges the point is.
Here's some high quality info in this topic on GameDev, including performance issues.
And here's some code to get you started:
float sign (fPoint p1, fPoint p2, fPoint p3)
{
return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y);
}
bool PointInTriangle (fPoint pt, fPoint v1, fPoint v2, fPoint v3)
{
float d1, d2, d3;
bool has_neg, has_pos;
d1 = sign(pt, v1, v2);
d2 = sign(pt, v2, v3);
d3 = sign(pt, v3, v1);
has_neg = (d1 < 0) || (d2 < 0) || (d3 < 0);
has_pos = (d1 > 0) || (d2 > 0) || (d3 > 0);
return !(has_neg && has_pos);
}
You can use this method, It is easy to understand and implement :
public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
calendar.add(Calendar.MINUTE, nombreMinute);
calendar.add(Calendar.SECOND, nombreSeconde);
return calendar.getTime();
}
You can put the graphic in a pseudo-element with its own dimensional context:
#graphic {
position: relative;
width: 200px;
height: 100px;
}
#graphic::before {
position: absolute;
content: '';
z-index: -1;
width: 200px;
height: 50px;
background-image: url(image.jpg);
}
#graphic {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
position: relative;_x000D_
}_x000D_
#graphic::before {_x000D_
content: '';_x000D_
_x000D_
position: absolute;_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
z-index: -1;_x000D_
_x000D_
background-image: url(http://placehold.it/500x500/); /* Image is 500px by 500px, but only 200px by 50px is showing. */_x000D_
}
_x000D_
<div id="graphic">lorem ipsum</div>
_x000D_
Browser support is good, but if you need to support IE8, use a single colon :before
. IE has no support for either syntax in versions prior to that.
Try filtering out the rows that contain strings with the delimiter and work on those only like:
SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM MyTable
WHERE CHARINDEX('/', myColumn) > 0
Or
SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM MyTable
WHERE myColumn LIKE '%/%'
<audio autoplay>
<source src="file.mp3" type="audio/mpeg">
</audio>
It removes the auto play bar but still plays the music. Invisible sounds!
The key point that you missing here is that the variable "result" is a stack variable, and as such it does not get "replaced". To elaborate, every time fact is called, a NEW variable called "result" is created internally in the interpreter and linked to that invocation of the methods. This is in contrast of object fields which linked to the instance of the object and not a specific method call
SUMIF didn't worked for me, had to use SUMIFS.
=SUMIFS(TableAmount,TableMonth,"January")
TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.
Hope this can help someone!
If you are starting the script within the command line, then add exit /b
to keep CMD opened
Using writeLines also allows you to dispense with the "\n" newline character, by using c()
. As in:
writeLines(c("File not supplied.","Usage: ./program F=filename",[additional text for third line]))
This is helpful if you plan on writing a multiline message with combined fixed and variable input, such as the [additional text for third line] above.
You can try use in javascript:
window.onload = function() {
alert("let's go!");
}
Its a good practice separate javascript of html
For future sake I'll post this. If you do not need to support < IE11 then you should use MutationObserver.
Here is a link to the caniuse js MutationObserver
Simple usage with powerful results.
var observer = new MutationObserver(function (mutations) {
//your action here
});
//set up your configuration
//this will watch to see if you insert or remove any children
var config = { subtree: true, childList: true };
//start observing
observer.observe(elementTarget, config);
When you don't need to observe any longer just disconnect.
observer.disconnect();
Check out the MDN documentation for more information
In a more basic way to explain: An interface is sort of like an empty muffin pan. It's a class file with a set of method definitions that have no code.
An abstract class is the same thing, but not all functions need to be empty. Some can have code. It's not strictly empty.
Why differentiate: There's not much practical difference in Python, but on the planning level for a large project, it could be more common to talk about interfaces, since there's no code. Especially if you're working with Java programmers who are accustomed to the term.
The only working method for me:
function removeItem (array, value) {
var i = 0;
while (i < array.length) {
if(array[i] === value) {
array.splice(i, 1);
} else {
++i;
}
}
return array;
}
Usage:
var new = removeItem( ["apple","banana", "orange"], "apple");
// ---> ["banana", "orange"]
I faced the same issue regarding apt-get: command not found
here are the steps how I resolved it on ubuntu xenial
Search the appropriate version of apt from here
(apt_1.4_amd64.deb
for ubuntu xenial)
Download the apt.deb
wget http://security.ubuntu.com/ubuntu/pool/main/a/apt/apt_1.4_amd64.deb
Install the apt.deb package
sudo dpkg -i apt_1.4_amd64.deb
Now we can easily run
sudo apt-get install htop
I assume you are using the caption feature of Word, that is, captions were not typed in as normal text, but were inserted using Insert > Caption (Word versions before 2007), or References > Insert Caption (in the ribbon of Word 2007 and up). If done correctly, the captions are really 'fields'. You'll know if it is a field if the caption's background turns grey when you put your cursor on them (or is permanently displayed grey).
Captions are fields - Unfortunately fields (like caption fields) are only updated on specific actions, like opening of the document, printing, switching from print view to normal view, etc. The easiest way to force updating of all (caption) fields when you want it is by doing the following:
Captions are normal text - If the caption number is not a field, I am afraid you'll have to edit the text manually.
I found this answer years ago on vim.org:
Add the following to your .vimrc:
"This unsets the "last search pattern" register by hitting return
nnoremap <CR> :noh<CR><CR>
Thus, after your search, just hit return again in command mode, and the highlighting disappears.
My 2c for this is to implement the functionality you require to be called in a toolkit class and call that from wherever you need:
// Util.cs
static class Util
{
static void DoSomething( FooBase foo ) {}
}
// FooBase.cs
class FooBase
{
virtual void Do() { Util.DoSomething( this ); }
}
// FooDerived.cs
class FooDerived : FooBase
{
override void Do() { ... }
}
// FooDerived2.cs
class FooDerived2 : FooDerived
{
override void Do() { Util.DoSomething( this ); }
}
This does require some thought as to access privilege, you may need to add some internal
accessor methods to facilitate the functionality.
The modern way to do it would be using flexbox. See the example below. You don't even need to wrap Some text...
into any HTML tag, since text directly contained in a flex container is wrapped in an anonymous flex item.
header {_x000D_
border: 1px solid blue;_x000D_
height: 150px;_x000D_
display: flex; /* defines flexbox */_x000D_
flex-direction: column; /* top to bottom */_x000D_
justify-content: space-between; /* first item at start, last at end */_x000D_
}_x000D_
h1 {_x000D_
margin: 0;_x000D_
}
_x000D_
<header>_x000D_
<h1>Header title</h1>_x000D_
Some text aligns to the bottom_x000D_
</header>
_x000D_
If there is only some text and you want to align vertically to the bottom of the container.
section {_x000D_
border: 1px solid blue;_x000D_
height: 150px;_x000D_
display: flex; /* defines flexbox */_x000D_
align-items: flex-end; /* bottom of the box */_x000D_
}
_x000D_
<section>Some text aligns to the bottom</section>
_x000D_
You can also use this syntax. For YYYY-MM-JJ HH-MM:
var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';
You don't. The C++ standard has no concept of directories. It is up to the implementation to turn a string into a file handle. The contents of that string and what it maps to is OS dependent. Keep in mind that C++ can be used to write that OS, so it gets used at a level where asking how to iterate through a directory is not yet defined (because you are writing the directory management code).
Look at your OS API documentation for how to do this. If you need to be portable, you will have to have a bunch of #ifdefs for various OSes.
Just noticed that I had named my file ' index.html'
instead for 'index.html'
with a leading space. That was why it could not find it.
Try This
$(".ClassName").css('color','');
Or
$("#Idname").css('color','');
>>> [1,2,3,4,5,6,7,8,9][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
A version from @user166390 answer with an added IEqualityComparer
parameter to allow for case insensitive key comparison.
public static T MergeLeft<T, K, V>(this T me, params Dictionary<K, V>[] others)
where T : Dictionary<K, V>, new()
{
return me.MergeLeft(me.Comparer, others);
}
public static T MergeLeft<T, K, V>(this T me, IEqualityComparer<K> comparer, params Dictionary<K, V>[] others)
where T : Dictionary<K, V>, new()
{
T newMap = Activator.CreateInstance(typeof(T), new object[] { comparer }) as T;
foreach (Dictionary<K, V> src in
(new List<Dictionary<K, V>> { me }).Concat(others))
{
// ^-- echk. Not quite there type-system.
foreach (KeyValuePair<K, V> p in src)
{
newMap[p.Key] = p.Value;
}
}
return newMap;
}
For anyone still looking for a simpler method to transfer repos from Gitlab to Github while preserving all history.
Step 1. Login to Github, create a private repo with the exact same name as the repo you would like to transfer.
Step 2. Under "push an existing repository from the command" copy the link of the new repo, it will look something like this:
[email protected]:your-name/name-of-repo.git
Step 3. Open up your local project and look for the folder .git
typically this will be a hidden folder. Inside the .git
folder open up config
.
The config file will contain something like:
[remote "origin"]
url = [email protected]:your-name/name-of-repo.git
fetch = +refs/heads/:refs/remotes/origin/
Under [remote "origin"]
, change the URL to the one that you copied on Github.
Step 4. Open your project folder in the terminal and run: git push --all
. This will push your code to Github as well as all the commit history.
Step 5. To make sure everything is working as expected, make changes, commit, push and new commits should appear on the newly created Github repo.
Step 6. As a last step, you can now archive your Gitlab repo or set it to read only.
Platform independent solution in one line is
Python 2:
python -c "import sys; print sys.executable"
Python 3:
python -c "import sys; print(sys.executable)"
Unless you need more than just the contents of the file, you could use file_get_contents
.
$xml = file_get_contents("http://www.example.com/file.xml");
For anything more complex, I'd use cURL.
You get SyntaxError
error exception because Python has no &&
operator. It has and
and &
where the latter one is the correct choice to create boolean expressions on Column
(|
for a logical disjunction and ~
for logical negation).
Condition you created is also invalid because it doesn't consider operator precedence. &
in Python has a higher precedence than ==
so expression has to be parenthesized.
(col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>
On a side note when
function is equivalent to case
expression not WHEN
clause. Still the same rules apply. Conjunction:
df.where((col("foo") > 0) & (col("bar") < 0))
Disjunction:
df.where((col("foo") > 0) | (col("bar") < 0))
You can of course define conditions separately to avoid brackets:
cond1 = col("Age") == ""
cond2 = col("Survived") == "0"
cond1 & cond2
@Erik's answer didn't fly for me.
Following did:
@Html.TextBoxFor(m => m.ShortName, new { data_val_required = "You need me" })
plus doing this manually under field I had to add error message container
@Html.ValidationMessageFor(m => m.ShortName, null, new { @class = "field-validation-error", data_valmsg_for = "ShortName" })
Hope this saves you some time.
I was getting the error because i had added the controller script before the script where i had defined the corresponding module in the app. First add the script
<script src = "(path of module.js file)"></script>
Then only add
<script src = "(path of controller.js file)"></script>
In the main file.
Change
private ArrayList finishingOrder;
//Make an ArrayList to hold RaceCar objects to determine winners
finishingOrder = Collections.synchronizedCollection(new ArrayList(numberOfRaceCars)
to
private List finishingOrder;
//Make an ArrayList to hold RaceCar objects to determine winners
finishingOrder = Collections.synchronizedList(new ArrayList(numberOfRaceCars)
List is a supertype of ArrayList so you need to specify that.
Otherwise, what you're doing seems fine. Other option is you can use Vector, which is synchronized, but this is probably what I would do.
if (typeof($('#container .prateleira')[0]) === 'undefined') {
$('#ctl00_Conteudo_ctrPaginaSistemaAreaWrapper').css('display','none');
}
Running IIS 7.5, I had luck adding permissions for the local computer user IUSR. The app pool user didn't work.
@[User::path] ="MDS/Material/"+(DT_STR, 4, 1252) DATEPART("yy" , GETDATE())+ "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
l = [-1.2, 0.0, 1]
x = 100.0
for i in l:
if i < x:
x = i
print (x)
This is the answer, i needed this for my homework, took your code, and i deleted the " " around the numbers, it then worked, i hope this helped
Assuming you want to do it yourself and not rely upon other providers, IP2Nation provides a MySQL database of the mappings which are updated as the regional registries change things around.
The following adds elements to a list in a loop.
l<-c()
i=1
while(i<100) {
b<-i
l<-c(l,b)
i=i+1
}
This is how google does it: StringPrintf
(BSD License)
and facebook does it in a quite similar fashion: StringPrintf
(Apache License)
Both provide with a convenient StringAppendF
too.
If you are using React.js, you could do this:
render() {
// ...
<img
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}
src={item.src} key={item.key}
ref={item.key} />
// ... }
Where:
As a side note, I have been getting the same error in completely unrelated situation - after my system clock year setting has been changed (i.e. 2015 -> 2016); changing the clock back to the correct one solved the issue.
Note 1: I'm posting this mainly because I had the exactly same error message, but the working solution proven to be different than just updating the plugin's version (as posted by Jared Burrows
).
Note 2: using
classpath 'com.android.tools.build:gradle:+'
can make the plugin version default to newest one. Bear in mind that your build may break on API changes (and is, for that very reason, discouraged by Android API docs), so use this at your own risk only if you're constantly updating the version anyway.
This is good for shallow cloning. The object spread is a standard part of ECMAScript 2018.
For deep cloning you'll need a different solution.
const clone = {...original}
to shallow clone
const newobj = {...original, prop: newOne}
to immutably add another prop to the original and store as a new object.
This avoid to load unised attributes, directly from db:
DB::table('roles')->pluck('title', 'name');
References: https://laravel.com/docs/5.8/queries#retrieving-results (search for pluck)
Maybe next you can apply toArray()
if you need such format
Your query execution will return list of Object[]
.
List result_source = LoadSource.list();
for(Object[] objA : result_source) {
// read it all
}
Ran into the same problem myself, but my controller definitions looked a little different than above. For controllers defined like this:
function MyController($scope, $http) {
// ...
}
Just add a line after the declaration indicating which objects to inject when the controller is instantiated:
function MyController($scope, $http) {
// ...
}
MyController.$inject = ['$scope', '$http'];
This makes it minification-safe.
let employee = <Employee>JSON.parse(employeeString);
Remember: Strong typings is compile time only since javascript doesn't support it.
what about this simple inArray function:
Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
Technical differences are a consequence of the goal of each one (OpenJDK is meant to be the reference implementation, open to the community, while Oracle is meant to be a commercial one)
They both have "almost" the same code of the classes in the Java API; but the code for the virtual machine itself is actually different, and when it comes to libraries, OpenJDK tends to use open libraries while Oracle tends to use closed ones; for instance, the font library.
I know this is question is really old, but I found an easy and simple jQuery solution in css-tricks. That's the one I'm using now.
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
The easiest way with BS3 is to reset the max-width and padding set by BS3 CSS simply like this. You get again a container-fluid :
.container{
max-width:100%;
padding:0;
}
I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.
$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
$this->{'value_'.$period}=1;
}
This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.
You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.
class timevalues
{
// Database table values:
public $value_hour; // maps to values.value_hour
public $value_day; // maps to values.value_day
public $value_month; // maps to values.value_month
public $values=array();
public function __construct()
{
$this->value_hour=0;
$this->value_day=0;
$this->value_month=0;
$this->values=array(
'hour'=>$this->value_hour,
'day'=>$this->value_day,
'month'=>$this->value_month,
);
}
}