If one really wants to make a variable read-only, IMHO the best way would be to use property() with only getter passed to it. With property() we can have complete control over the data.
class PrivateVarC(object):
def get_x(self):
pass
def set_x(self, val):
pass
rwvar = property(get_p, set_p)
ronly = property(get_p)
I understand that OP asked a little different question but since I found another question asking for 'how to set private variables' marked duplicate with this one, I thought of adding this additional info here.
In my case, it wasn't until I PAUSEd the batch file and scrolled up a bit, that wasn't the only error I had gotten. My DROP
command had become DROP
and so the table wasn't dropping in the first place (thus the relation did indeed still exist). The 
I've learned is called a Byte Order Mark (BOM). Opening this in Notepad++, re-save the SQL file with Encoding set to UTM-8 without BOM and it runs fine.
Everybody says "Each id value must be used only once within a document", but what we do to get the elements we need when we have a stupid page that has more than one element with same id. If we use JQuery '#duplicatedId' selector we get the first element only. To achieve selecting the other elements you can do something like this
$("[id=duplicatedId]")
You will get a collection with all elements with id=duplicatedId
First off, it's not JSON: JSON mandates that all keys must be strings.
Secondly, regular arrays do what you want:
var Game = {
status: [
[
"val",
"val",
"val"
],
[
"val",
"val",
"val"
]
}
will work, if you use Game.status[0][0]
. You cannot use numbers with the dot notation (.0
).
Alternatively, you can quote the numbers (i.e. { "0": "val" }...
); you will have plain objects instead of Arrays, but the same syntax will work.
Small addition to @user995502's answer on how to run the program.
g++ player.cpp main.cpp -o main.out && ./main.out
Identifiers (including column names) that are not double-quoted are folded to lower case in PostgreSQL. Column names that were created with double-quotes and thereby retained upper-case letters (and/or other syntax violations) have to be double-quoted for the rest of their life:
"first_Name"
Values (string literals / constants) are enclosed in single quotes:
'xyz'
So, yes, PostgreSQL column names are case-sensitive (when double-quoted):
SELECT * FROM persons WHERE "first_Name" = 'xyz';
Read the manual on identifiers here.
My standing advice is to use legal, lower-case names exclusively so double-quoting is not needed.
{
int main(void);
should be
int main(void)
{
Then I let you fix the next compilation errors of your program...
For hibernate it is important to know that your object WILL have an id, when you want to persist/save it. Thus, make sure that
private String U_id;
will have a value, by the time you are going to persist your object. You can do that with the @GeneratedValue
annotation or by assigning a value manually.
In the case you need or want to assign your id's manually (and that's what the above error is actually about), I would prefer passing the values for the fields to your constructor, at least for U_id
, e.g.
public Role (String U_id) { ... }
This ensures that your object has an id, by the time you have instantiated it. I don't know what your use case is and how your application behaves in concurrency, however, in some cases this is not recommended. You need to ensure that your id is unique.
Further note: Hibernate will still require a default constructor, as stated in the hibernate documentation. In order to prevent you (and maybe other programmers if you're designing an api) of instantiations of Role
using the default constructor, just declare it as private
.
The code below can solve the NullPointerException.
@Id
@GeneratedValue
@Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
return this.stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
If you add @Id
, then you can declare some more like as above declared method.
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
With JTable.AUTO_RESIZE_OFF
, the table will not change the size of any of the columns for you, so it will take your preferred setting. If it is your goal to have the columns default to your preferred size, except to have the last column fill the rest of the pane, You have the option of using the JTable.AUTO_RESIZE_LAST_COLUMN
autoResizeMode, but it might be most effective when used with TableColumn.setMaxWidth()
instead of TableColumn.setPreferredWidth() for all but the last column.
Once you are satisfied that AUTO_RESIZE_LAST_COLUMN
does in fact work, you can experiment with a combination of TableColumn.setMaxWidth()
and TableColumn.setMinWidth()
Since API 16 you can use the finishAffinity method, which seems to be pretty close to closing all related activities by its name and Javadoc description:
this.finishAffinity();
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and into its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
Since API 21 you can use a very similar command
finishAndRemoveTask();
Finishes all activities in this task and removes it from the recent tasks list.
Visual C# Express 2005 ISO File does not require registration
This functions should help you...
bool isThereSpace(String s){
return s.Contains(" ");
}
Running this command is extremely dangerous, but will shrink your repository by erasing all your git recovery/backup files:
git reflog expire --expire=now --all && git gc --prune=now --aggressive
It will erase all files git uses to recover your repository from some bad command, for example, if you did git reset --hard
, you can usually recover the files lost. But if you do git reset --hard
before the git reflog expire...
command, then you lost everything. Now, your only hope is to use some tool which analyses your file system and try to recover the erased files, if they were not overridden.
We can use pip freeze
to get any Python package version without opening the Python shell.
pip freeze | grep 'numpy'
Here's a video that will show you, step-by-step, how to export data to Excel. It's a great solution for 'one-off' problems where you need to export to Excel:
Ad-Hoc Reporting
I wanted to add a cryptographically secure version:
RNGCryptoServiceProvider Class (MSDN or dotnetperls)
It implements IDisposable.
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] randomNumber = new byte[4];//4 for int32
rng.GetBytes(randomNumber);
int value = BitConverter.ToInt32(randomNumber, 0);
}
Use the "indirect" function on conditional formatting.
=INDIRECT("g"&ROW())="X"
=$A$1:$Z$1500
(or however wide/long you want the conditional formatting to extend depending on your worksheet)For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.
You can repeat this to do multiple row formatting depending on a column value. Just change either the g
column or x
specific text in the formula and set different formats.
For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR"
, then it will format every row that has CAR
in the H Column as the format you specified.
Create a table with a normal numeric auto_increment ID, but either define it with ZEROFILL
, or use LPAD
to add zeroes when selecting. Then CONCAT
the values to get your intended behavior. Example #1:
create table so (
id int(3) unsigned zerofill not null auto_increment primary key,
name varchar(30) not null
);
insert into so set name = 'John';
insert into so set name = 'Mark';
select concat('LHPL', id) as id, name from so;
+---------+------+
| id | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+
Example #2:
create table so (
id int unsigned not null auto_increment primary key,
name varchar(30) not null
);
insert into so set name = 'John';
insert into so set name = 'Mark';
select concat('LHPL', LPAD(id, 3, 0)) as id, name from so;
+---------+------+
| id | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+
This works:
function getBreakText($t) {
return strtr($t, array('\\r\\n' => '<br>', '\\r' => '<br>', '\\n' => '<br>'));
}
public IEnumerable<T> GetAll<T>(Control control) where T : Control
{
var type = typeof(T);
var controls = control.Controls.Cast<Control>().ToArray();
foreach (var c in controls.SelectMany(GetAll<T>).Concat(controls))
if (c.GetType() == type) yield return (T)c;
}
For something really basic use this:
<a href="#middle">Go To Middle</a>
Or for something simple in javascript check out this jQuery plugin ScrollTo. Quite useful for scrolling smoothly.
Put the values in a temporary table and then do a select where id in (select id from temptable)
Without actually seeing your data it is difficult to say how to find location of max and min in your particular case, but in general, you can search for the locations as follows. This is just a simple example below:
In [9]: a=np.array([5,1,2,3,10,4])
In [10]: np.where(a == a.min())
Out[10]: (array([1]),)
In [11]: np.where(a == a.max())
Out[11]: (array([4]),)
Alternatively, you can also do as follows:
In [19]: a=np.array([5,1,2,3,10,4])
In [20]: a.argmin()
Out[20]: 1
In [21]: a.argmax()
Out[21]: 4
Extracted from here: http://git.661346.n2.nabble.com/Revert-a-single-commit-in-a-single-file-td6064050.html
git revert <commit>
git reset
git add <path>
git commit ...
git reset --hard # making sure you didn't have uncommited changes earlier
It worked very fine to me.
It seems like Github has changed their layout since you posted this question. I just created a repository and it used to give you instructions on screen. It appears they have changed that approach.
Here is the information they used to give on repo creation:
import java.util.ArrayList;
import java.util.List;
class ArrLst{
public static void main(String args[]){
List l=new ArrayList();
l.add(10);
l.add(11);
l.add(12);
l.add(13);
l.add(14);
l.forEach((a)->System.out.println(a));
}
}
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
Run this from the branch where you want the file to end up:
git checkout otherbranch myfile.txt
General formulas:
git checkout <commit_hash> <relative_path_to_file_or_dir>
git checkout <remote_name>/<branch_name> <file_or_dir>
Some notes (from comments):
myfile.txt
and mydir
an alternative:
git show commit_id:path/to/file > path/to/file
My issue with this was that the element using the disabled attr needed to be defined as a form element, .ie input type for it to work. Both worked with attr() and prop() but chose the latter for future maintainability.
datetime.datetime.now() - datetime.timedelta(0, 15 * 60)
timedelta
is a "change in time". It takes days as the first parameter and seconds in the second parameter. 15 * 60
seconds is 15 minutes.
You can encapsulate the list trivially:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
[XmlRoot("user_list")]
public class UserList
{
public UserList() {Items = new List<User>();}
[XmlElement("user")]
public List<User> Items {get;set;}
}
public class User
{
[XmlElement("id")]
public Int32 Id { get; set; }
[XmlElement("name")]
public String Name { get; set; }
}
static class Program
{
static void Main()
{
XmlSerializer ser= new XmlSerializer(typeof(UserList));
UserList list = new UserList();
list.Items.Add(new User { Id = 1, Name = "abc"});
list.Items.Add(new User { Id = 2, Name = "def"});
list.Items.Add(new User { Id = 3, Name = "ghi"});
ser.Serialize(Console.Out, list);
}
}
Here's a cute trick to deal with directories and make. Instead of using multiline strings, or "cd ;" on each command, define a simple chdir function as so:
CHDIR_SHELL := $(SHELL)
define chdir
$(eval _D=$(firstword $(1) $(@D)))
$(info $(MAKE): cd $(_D)) $(eval SHELL = cd $(_D); $(CHDIR_SHELL))
endef
Then all you have to do is call it in your rule as so:
all:
$(call chdir,some_dir)
echo "I'm now always in some_dir"
gcc -Wall -o myTest myTest.c
You can even do the following:
some_dir/myTest:
$(call chdir)
echo "I'm now always in some_dir"
gcc -Wall -o myTest myTest.c
On the recent version (from Yosemite or El Capitan I believe... at least from Sierra onward), you need to run brew postinstall python3
after brew install python3
if you use homebrew.
So,
brew install python3 # this only installs python
brew postinstall python3 # this installs pip
According to the official Homebrew page:
On 1st March 2018 the python formula will be upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7 (although this will be keg-only so neither python nor python2 will be added to the PATH by default without a manual brew link --force). We will maintain python2, python3 and python@3 aliases.
So to install Python 3, run the following command:
brew install python3
Then, the pip
is installed automatically, and you can install any package by pip install <package>
.
I'd personally suggest using a different unit of measurement than px
. I don't think that pixels have much relevance in terms of print; ideally you'd use:
I'm sure there are others, and one excellent article about print-css can be found here: Going to Print, by Eric Meyer.
As of 5.5 you can run Kernel > Restart and Run All
If you don't have permissions on the server to delete other people's workspaces, you can just change the name of the build definition. TFS will create a new workspace and map it to "C:\Build\ProductReleases\new build name here\Sources".
What you are doing right now is you are adding .
on the string and not concatenating. It should be,
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
or simply
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '$email'");
brew switch libfoo mycopy
You can use brew switch
to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/
This will list versions installed ( for example I had Cellar/sdl2/2.0.3
, I've compiled into Cellar/sdl2/2.0.4
)
brew info sdl2
Then to switch between them
brew switch sdl2 2.0.4
brew info
Info now shows *
next to the 2.0.4
To install under Cellar/<packagename>/<version>
from source you can do for example
cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make
check where it gets installed with
make install -n
if all looks correct
make install
Then from cd $(brew --Cellar)
do the switch between version.
I'm using brew version 0.9.5
If you are looking for a rapid, normalized cross correlation in either one or two dimensions
I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).
While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.
import numpy
import cv
#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp
#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )
#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv = cv.fromarray(numpy.float32(resultNp))
#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)
#convert result back to numpy array
resultNp = np.asarray(resultCv)
For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.
You need to be more explicit and add the start and end times as well, down to the milliseconds:
select *
from xxx
where dates between '2012-10-26 00:00:00.000' and '2012-10-27 23:59:59.997'
The database can very well interpret '2012-10-27'
as '2012-10-27 00:00:00.000'
.
You are correct. You can't do new E()
. But you can change it to
private static class SomeContainer<E> {
E createContents(Class<E> clazz) {
return clazz.newInstance();
}
}
It's a pain. But it works. Wrapping it in the factory pattern makes it a little more tolerable.
Top level await
is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.
There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:
// data.js
const data = await fetch( '/data.json' );
export default data;
Now any file that imports data.js
won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.
My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await
probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.
A single css code on hover can do the trick:
box-shadow: inset 100px 0 0 0 #e0e0e0;
A complete demo can be found in my fiddle:
+
means a space only in application/x-www-form-urlencoded
content, such as the query part of a URL:
http://www.example.com/path/foo+bar/path?query+name=query+value
In this URL, the parameter name is query name
with a space and the value is query value
with a space, but the folder name in the path is literally foo+bar
, not foo bar
.
%20
is a valid way to encode a space in either of these contexts. So if you need to URL-encode a string for inclusion in part of a URL, it is always safe to replace spaces with %20
and pluses with %2B
. This is what eg. encodeURIComponent()
does in JavaScript. Unfortunately it's not what urlencode does in PHP (rawurlencode is safer).
See Also HTML 4.01 Specification application/x-www-form-urlencoded
iconv -f WINDOWS-1252 -t UTF-8 filename.txt
Note that $(element).offset()
tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed
you can get unexpected results.
If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed
element's offset()
value will be greater than the expected value by the amount you have scrolled.
If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop()
value from the fixed element's offset().top
value. Example: $("#el").offset().top - $(document).scrollTop()
If the position:fixed
element's offset parent is the document, you want to read parseInt($.css('top'))
instead.
In my experience, most often this error message means that you have put an accidental closing brace somewhere, leaving the rest of your statements outside the function.
Example:
function a() {
if (global_block) //syntax error is actually here - missing opening brace
return;
} //this unintentionally ends the function
if (global_somethingelse) {
//Chrome will show the error occurring here,
//but actually the error is in the previous statement
return;
}
//do something
}
In your Gemfile, add the following:
gem 'example', :git => 'git://github.com/example.git'
You can also add ref, branch and tag options,
For example if you want to download from a particular branch:
gem 'example', :git => "git://github.com/example.git", :branch => "my-branch"
Then run:
bundle install
You have upgraded to Razor 3. Remember that VS 12 (until update 4) doesn't support it. Install The Razor 3 from nuget or downgrade it through these step
geekswithblogs.net/anirugu/archive/2013/11/04/how-to-downgrade-razor-3-and-fix-the-issue-that.aspx
It's document.getElementById, not document.getElementsByID
I'm assuming you have <input id="Tue" ...>
somewhere in your markup.
<video id="myvideo">
<source src="path/to/movie.mp4" />
</video>
<p onclick="toggleControls();">Toggle</p>
<script>
var video = document.getElementById("myvideo");
function toggleControls() {
if (video.hasAttribute("controls")) {
video.removeAttribute("controls")
} else {
video.setAttribute("controls","controls")
}
}
</script>
See it working on jsFiddle: http://jsfiddle.net/dgLds/
I also experienced np.array_split not working with Pandas DataFrame my solution was to only split the index of the DataFrame and then introduce a new column with the "group" label:
indexes = np.array_split(df.index,N, axis=0)
for i,index in enumerate(indexes):
df.loc[index,'group'] = i
This makes grouby operations very convenient for instance calculation of mean value of each group:
df.groupby(by='group').mean()
keytool is located in JDK bin directory ($JAVA_HOME/bin). JAVA_HOME is your JDK installation directory. To use that command line you should also include $JAVA_HOME/bin to your PATH environment variable.
Improvement to kaiser's answer:
var myEl = $document.find('#some-id');
Don't forget to inject $document
into your directive
I have done this using LINQ:
var oCSP = (from P in db.Products select new { P.ProductName });
string joinedString = string.Join(",", oCSP.Select(p => p.ProductName));
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
I don't like adding new package into my project just to handle this simple task.
And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.
So I made a function to get all the folder content (and its sub folder).... NON-Recursively
var getDirectoryContent = function(dirPath) {
/*
get list of files and directories from given dirPath and all it's sub directories
NON RECURSIVE ALGORITHM
By. Dreamsavior
*/
var RESULT = {'files':[], 'dirs':[]};
var fs = fs||require('fs');
if (Boolean(dirPath) == false) {
return RESULT;
}
if (fs.existsSync(dirPath) == false) {
console.warn("Path does not exist : ", dirPath);
return RESULT;
}
var directoryList = []
var DIRECTORY_SEPARATOR = "\\";
if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;
directoryList.push(dirPath); // initial
while (directoryList.length > 0) {
var thisDir = directoryList.shift();
if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;
var thisDirContent = fs.readdirSync(thisDir);
while (thisDirContent.length > 0) {
var thisFile = thisDirContent.shift();
var objPath = thisDir+thisFile
if (fs.existsSync(objPath) == false) continue;
if (fs.lstatSync(objPath).isDirectory()) { // is a directory
let thisDirPath = objPath+DIRECTORY_SEPARATOR;
directoryList.push(thisDirPath);
RESULT['dirs'].push(thisDirPath);
} else { // is a file
RESULT['files'].push(objPath);
}
}
}
return RESULT;
}
the only drawback of this function is that this is Synchronous function... You have been warned ;)
This is a default import:
// B.js
import A from './A'
It only works if A
has the default export:
// A.js
export default 42
In this case it doesn’t matter what name you assign to it when importing:
// B.js
import A from './A'
import MyA from './A'
import Something from './A'
Because it will always resolve to whatever is the default export of A
.
This is a named import called A
:
import { A } from './A'
It only works if A
contains a named export called A
:
export const A = 42
In this case the name matters because you’re importing a specific thing by its export name:
// B.js
import { A } from './A'
import { myA } from './A' // Doesn't work!
import { Something } from './A' // Doesn't work!
To make these work, you would add a corresponding named export to A
:
// A.js
export const A = 42
export const myA = 43
export const Something = 44
A module can only have one default export, but as many named exports as you'd like (zero, one, two, or many). You can import them all together:
// B.js
import A, { myA, Something } from './A'
Here, we import the default export as A
, and named exports called myA
and Something
, respectively.
// A.js
export default 42
export const myA = 43
export const Something = 44
We can also assign them all different names when importing:
// B.js
import X, { myA as myX, Something as XSomething } from './A'
The default exports tend to be used for whatever you normally expect to get from the module. The named exports tend to be used for utilities that might be handy, but aren’t always necessary. However it is up to you to choose how to export things: for example, a module might have no default export at all.
This is a great guide to ES modules, explaining the difference between default and named exports.
When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.
If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.
inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.
The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like
With ThisWorkbook.Worksheets("Template")
.Range(inputTemplateHeader).Value = NO_ENTRY
.Range(inputTemplateContent).Value = NO_ENTRY
End With
Adjust the workbook and worksheet references to fit your particular situation.
Read line by line, not the whole file:
for line in open(file_name, 'rb'):
# process line here
Even better use with
for automatically closing the file:
with open(file_name, 'rb') as f:
for line in f:
# process line here
The above will read the file object using an iterator, one line at a time.
You have it right. The stack pointer points to the top item on the stack and the base pointer points to the "previous" top of the stack before the function was called.
When you call a function, any local variable will be stored on the stack and the stack pointer will be incremented. When you return from the function, all the local variables on the stack go out of scope. You do this by setting the stack pointer back to the base pointer (which was the "previous" top before the function call).
Doing memory allocation this way is very, very fast and efficient.
Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):
Exception in thread "main" java.lang.ClassCastException:
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
The solution is to get the 'parent' node, and perform a put
, effectively replacing the entire node, regardless of original node type.
If you need to "modify" the node using the existing value of the node:
get
the value/array of the JsonNode
put
on the parent.Code, where the goal is to modify subfield
, which is the child node of NodeA
and Node1
:
JsonNode nodeParent = someNode.get("NodeA")
.get("Node1");
// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");
Credits:
I got this inspiration from here, thanks to wassgreen@
If you are in an adapter and still want to use a color defined in resources you can try the following approach:
holder.text.setTextColor(holder.text.getContext().getResources().getColor(R.color.myRed));
Just to add a note that Google Chrome browser has origin attribute for the location. which gives you the entire domain from protocol to the port number as shown in the below screenshot.
Here is code you can get url segment.
{{ Request::segment(1) }}
If you don't want the data to be escaped then use {!! !!} else use {{ }}.
{!! Request::segment(1) !!}
Two things you need to do, if you want to make a custom button design.
1st is: create a xml resource file in drawable folder (Example: btn_shape_rectangle.xml) then copy and paste the code there.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:shape="rectangle">
<solid
android:color="#fff"/>
<stroke
android:width="1dp"
android:color="#000000"
/>
<corners android:radius="10dp" />
</shape>
2nd is go to your layout button where you want to implement this design. just link up it. Example: android:background="@drawable/btn_shape_rectangle"
You can change shape color radius what design you want can do.
Hope it will works and help you. Happy Coding
Cannot be done. MsgBox buttons can only have specific values.
You'll have to roll your own form for this.
To create a MsgBox with two options (Yes/No):
MsgBox("Some Text", vbYesNo)
You absolutely need a button tag element? because you can use instead an input type="button" element.
Then just link this CSS:
input[type="button"]{
width:150px;
height:150px;
/*just this*/ background-image: url(https://images.freeimages.com/images/large-previews/48d/marguerite-1372118.jpg);
background-position: center;
background-repeat: no-repeat;
background-size: 150px 150px;
}
_x000D_
<input type="button"/>
_x000D_
Open the IDLE and use below commands.
import sys print(sys.path)
It will give you the path where the python.exe is installed. For eg: C:\Users\\...\python.exe
Add the same path to system environment variable.
you can 'invoke' alternative bindings on Y
this way:
...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).
Note the parenthesis are required to keep the correct execution control flow. The ;
/2 it's the general or
operator. For your restricted use you could as well choice the more idiomatic
...registered(X, Y), member(Y, [ct101,ct102,ct103]).
that on backtracking binds Y to each member of the list.
edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead
...registered(X, ct101), registered(X, ct102), registered(X, ct103).
or the more compact
...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).
findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.
...setof(Y, registered(X, Y), [ct101,ct102,ct103]).
setof/3 also sorts the result list
git revert
simply creates a new commit that is the opposite of an existing commit.
It leaves the files in the same state as if the commit that has been reverted never existed. For example, consider the following simple example:
$ cd /tmp/example
$ git init
Initialized empty Git repository in /tmp/example/.git/
$ echo "Initial text" > README.md
$ git add README.md
$ git commit -m "initial commit"
[master (root-commit) 3f7522e] initial commit
1 file changed, 1 insertion(+)
create mode 100644 README.md
$ echo "bad update" > README.md
$ git commit -am "bad update"
[master a1b9870] bad update
1 file changed, 1 insertion(+), 1 deletion(-)
In this example the commit history has two commits and the last one is a mistake. Using git revert:
$ git revert HEAD
[master 1db4eeb] Revert "bad update"
1 file changed, 1 insertion(+), 1 deletion(-)
There will be 3 commits in the log:
$ git log --oneline
1db4eeb Revert "bad update"
a1b9870 bad update
3f7522e initial commit
So there is a consistent history of what has happened, yet the files are as if the bad update never occured:
cat README.md
Initial text
It doesn't matter where in the history the commit to be reverted is (in the above example, the last commit is reverted - any commit can be reverted).
do you have to do something else after?
A git revert
is just another commit, so e.g. push to the remote so that other users can pull/fetch/merge the changes and you're done.
Do you have to commit the changes revert made or does revert directly commit to the repo?
git revert
is a commit - there are no extra steps assuming reverting a single commit is what you wanted to do.
Obviously you'll need to push again and probably announce to the team.
Indeed - if the remote is in an unstable state - communicating to the rest of the team that they need to pull to get the fix (the reverting commit) would be the right thing to do :).
echo -e "YOURPASSWORD\n" | sudo -S yourcommand
The accepted answer works well. Just for completeness (and since I like it's shortness), I wanted to share how to to it with compass (SCSS/SASS):
body{
$colorStart: rgba(0,0,0,0);
$colorEnd: rgba(0,0,0,0.8);
@include background-image(linear-gradient(to bottom, $colorStart, $colorEnd), url("bg.jpg"));
}
Since you are using Mi phone which has MIUI
try this
go to Developer options, scroll down to find 'Turn on MIUI optimization' & disable it. Your Phone will be rebooted
check now
If you are using any other android phone, which has a custom skin/UI on top of android OS, then try disabling the optimization provided by that UI and check.
(usually you can find that in 'Developer options')
Use Controls
object
For i = 1 To X
Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next
better way is "destroy and remove" instead of "close" it will remove dialog's "html" from the DOM
$(this).closest('.ui-dialog-content').dialog('destroy').remove();
The following example should solve your problem:
def check_dump(x):
if not x in t:
t.append(x)
return True
t=[]
output = filter(check_dump, input)
print(output)
True
Starting with Google Play 4.9, the app info display has been changed and the promo graphic is displayed at the top.
The promo graphic will be required soon.
The promo text has turned into a short description and is now shown on the main info page, before the user presses it to view the full description.
The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.
It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,
if (window.variableName)
is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.
That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.
if ( variableName && typeof variableName !== 'undefined' )
cduruk's solution was quite effective, but caused problems on a few parts of my site. Because I was already using jQuery to add the CSS hover class, the easiest solution was to simply not add the CSS hover class on mobile devices (or more precisely, to ONLY add it when NOT on a mobile device).
Here was the general idea:
var device = navigator.userAgent.toLowerCase();
var ios = device.match(/(iphone|ipod|ipad)/);
if (!(ios)) {
$(".portfolio-style").hover(
function(){
$(this).stop().animate({opacity: 1}, 100);
$(this).addClass("portfolio-red-text");
},
function(){
$(this).stop().animate({opacity: 0.85}, 100);
$(this).removeClass("portfolio-red-text");
}
);
}
*code reduced for illustrative purposes
A slight riff on the top voted answer that I found to be a little more explicit is to use the jekyll syntax for adding a class to something and then style it that way.
So in the post you would have:
![My image](/images/my-image.png)
{:.image-caption}
*The caption for my image*
And then in your CSS file you can do something like this:
.image-caption {
text-align: center;
font-size: .8rem;
color: light-grey;
Comes out looking good!
You can also use html to override the css locally. I was having a similar issue and this worked for me:
<html>
<body>
<h4>A nested List:</h4>
<ul style="PADDING-LEFT: 12px">
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
</body>
</html>
check ur WebApiConfig and add this
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
The problem for me turned out to be pretty obscure. My class looked like this:
//-----------------------------------------
// libbase.h
class base {
public:
base() { }
virtual ~base() { }
virtual int foo() { return 0; }
};
//-----------------------------------------
//-----------------------------------------
// libbase.cpp
#include "libbase.h"
//-----------------------------------------
//-----------------------------------------
// main.h
class derived : public base {
public:
virtual int foo() ;
};
//-----------------------------------------
//-----------------------------------------
// main.cpp
int main () {
derived d;
}
//-----------------------------------------
The problem is in the linker. My header file went in a library somewhere, but all the virtual functions were declared 'inline' in the class declaration. Since there was no code using the virtual functions (yet), the compiler or linker neglected to put actual function bodies in place. It also failed to create the vtable.
In my main code where I derived from this class, the linker tried to connect my class to the base class and his vtable. But the vtable had been discarded.
The solution was to declare at least one of the virtual functions' bodies outside the class declaration, like this:
//-----------------------------------------
// libbase.h
class base {
public:
base() { }
virtual ~base() ; //-- No longer declared 'inline'
virtual int foo() { return 0; }
};
//-----------------------------------------
//-----------------------------------------
// libbase.cpp
#include "libbase.h"
base::~base()
{
}
//-----------------------------------------
Get rid of the change event, and instead change the value of the textbox in the click event. Rather than returning the result of the confirm, catch it in a var. If its true, change the value. Then return the var.
Nurik's answer was very helpful, but I couldn't get it to work until I found this. In short, if you're using the compatibility library (eg SupportFragmentManager instead of FragmentManager), the syntax of the XML animation files will be different.
I had a similar problem.
I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.
Let's say for example this one.
$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');
// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));
// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut
// down the process one by one like this.
$data1 = array_keys($data);
$lastkey = array_pop($data1);
echo $lastkey;
There you go!
This will display the path, filename and the content line it found that matched the pattern.
Get-ChildItem -Path d:\applications\*config -recurse | Select-String -Pattern "dummy"
In this world of flashy new native functions, we sometimes forget the basics.
for (let i = 0; i < arr.length; i++) {
console.log('index:', i, 'element:', arr[i]);
}
Clean, efficient, and you can still break
the loop. Bonus! You can also start from the end and go backwards with i--
!
Additional note: If you're using the value a lot within the loop, you may wish to do const value = arr[i];
at the top of the loop for an easy, readable reference.
Try this code to download an image from a URL on Android:
DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(imageName);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
In your HTML code
<form [formGroup]="userForm">
<input type="text" class="form-control" [value]="item.UserFirstName" formControlName="UserFirstName">
<input type="text" class="form-control" [value]="item.UserLastName" formControlName="UserLastName">
</form>
In your Typescript code
export class UserprofileComponent implements OnInit {
userForm: FormGroup;
constructor(){
this.userForm = new FormGroup({
UserFirstName: new FormControl(),
UserLastName: new FormControl()
});
}
}
This works perfectly, it does not give any error.
Simple and easy way to detect button event and perform some action
class youCell: UITableViewCell
{
var yourobj : (() -> Void)? = nil
//You can pass any kind data also.
//var user: ((String?) -> Void)? = nil
override func awakeFromNib()
{
super.awakeFromNib()
}
@IBAction func btnAction(sender: UIButton)
{
if let btnAction = self.yourobj
{
btnAction()
// user!("pass string")
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = youtableview.dequeueReusableCellWithIdentifier(identifier) as? youCell
cell?.selectionStyle = UITableViewCellSelectionStyle.None
cell!. yourobj =
{
//Do whatever you want to do when the button is tapped here
self.view.addSubview(self.someotherView)
}
cell.user = { string in
print(string)
}
return cell
}
Maybe this is unrelated but a similar error appears when you upgrade postgres
to a major version using brew
; using brew info postgresql
found out this that helped:
To migrate existing data from a previous major version of PostgreSQL run:
brew postgresql-upgrade-database
Use isinstance(object, type)
. As above this is easy to use if you know the correct type
, e.g.,
isinstance('dog', str) ## gives bool True
But for more esoteric objects, this can be difficult to use. For example:
import numpy as np
a = np.array([1,2,3])
isinstance(a,np.array) ## breaks
but you can do this trick:
y = type(np.array([1]))
isinstance(a,y) ## gives bool True
So I recommend instantiating a variable (y
in this case) with a type of the object you want to check (e.g., type(np.array())
), then using isinstance
.
Check out the language reference:
http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx
expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
If you want to set different color for clicked and unclicked radio button just use:
android:buttonTint="@drawable/radiobutton" in xml of the radiobutton and your radiobutton.xml will be:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#1E88E5"/>
<item android:state_checked="true" android:color="#00e676"/>
<item android:color="#ffffff"/>
Getting the MAC address through WifiInfo.getMacAddress()
won't work on Marshmallow and above, it has been disabled and will return the constant value of 02:00:00:00:00:00
.
Use LINQ:
Datagridview1.Columns.Cast<DataGridViewColumn>().ToList().ForEach(f => f.SortMode = DataGridViewColumnSortMode.NotSortable);
I solved this by clicking on File -> Project Structure then changed the JDK Location to Use Embedded JDK (Recommended)
There should be an event logged in the EventVwr (Warning from asp.net), which could provide you more details on where the error could be.
This also works well. Is simple, lite, and doesn't require jQuery to be used.
<a href="javascript:void(0)">Link</a>
Test with [char]9, such as:
$Tab = [char]9
Write-Output "$Tab hello"
Output:
hello
I'm answering this question because I don't find any answer why the ^
don't work for powers. The ^
operator in C# is an exclusive or operator shorten as XOR. The truth table of A ^ B
shows that it outputs true whenever the inputs differ:
Input A | Input B | Output |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Witch means that 100 ^ 3
does this calculation under the hood:
hex binary
100 = 0110 0100
3 = 0000 0011
--- --------- ^
103 = 0110 0111
With is of course not the same as Math.Pow(100, 3)
with results to one million. You can use that or one of the other existing answers.
You could also shorten your code to this that gives the same result because C# respects the order of operations.
double dimensions = 100 * 100 / Math.Pow(100, 3); // == 0.01
This is a correct answer:
<a class="btn" ng-click="remove($index)">Delete</a>
$scope.remove=function($index){
$scope.bdays.splice($index,1);
}
In @charlietfl's answer. I think it's wrong since you pass $index
as paramter but you use the wish instead in controller. Correct me if I'm wrong :)
I also searched this answer. Equivalent of command+N on Mac OS for Windows is ctr + alt + insert which @manyways already answered. If you searching this in settings it is in Settings > IDE Settings > Keymap, Other > New ...
Trying this out on Windows 10, none of the command-line instructions worked.
Right clicking on "Computer" then open Properties etc. as the post by Galen Nare above already explains, leads you to a window where you need to click on "new" and then paste the path (as said: without deleting anything else). Afterwards you can check by typing java -version in the command-line window, which should display your current java version, if everything worked out right.
Building on bgporter's answer.
def prev_month_range(when = None):
"""Return (previous month's start date, previous month's end date)."""
if not when:
# Default to today.
when = datetime.datetime.today()
# Find previous month: https://stackoverflow.com/a/9725093/564514
# Find today.
first = datetime.date(day=1, month=when.month, year=when.year)
# Use that to find the first day of this month.
prev_month_end = first - datetime.timedelta(days=1)
prev_month_start = datetime.date(day=1, month= prev_month_end.month, year= prev_month_end.year)
# Return previous month's start and end dates in YY-MM-DD format.
return (prev_month_start.strftime('%Y-%m-%d'), prev_month_end.strftime('%Y-%m-%d'))
I downloaded your project.
The error you are getting is
'NSUnknownKeyException', reason: '[<UIViewController 0x3927310> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key string.'
It is caused by the Second
view controller in MainWindow.xib
having a class of UIViewController
instead of SecondView
. Changing to the correct class resolves the problem.
By the way, it is bad practice to have names like "string" in Objective-C. It invites a runtime naming collision. Avoid them even in once off practice apps. Naming collisions can be very hard to track down and you don't want to waste the time.
Another possible reason for this error: when copying & pasting elements from one controller into another, Xcode somehow keeps that link to the original controller, even after editing & relinking this element into the new controller.
Another possible reason for this error:
Bad Outlet.
You have either removed or renamed an outlet name in your .h
file.
Remove it in .xib
or .storyboard
file's Connection Inspector.
One more possible reason
(In my case) Extension of UIView with bindable properties and setting values for those bindable properties (i.e. shadow, corner radius etc.) then remove those properties from UIView extension (for some reason) but the following <userDefinedRuntimeAttributes>
remained in xml (of foo.storyboard
):
<userDefinedRuntimeAttributes>
<userDefinedRuntimeAttribute type="color" keyPath="shadowColor">
<color key="value" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</userDefinedRuntimeAttribute>
<userDefinedRuntimeAttribute type="number" keyPath="shadowOpacity">
<real key="value" value="50"/>
</userDefinedRuntimeAttribute>
<userDefinedRuntimeAttribute type="point" keyPath="shadowOffset">
<point key="value" x="5" y="5"/>
</userDefinedRuntimeAttribute>
<userDefinedRuntimeAttribute type="number" keyPath="shadowRadius">
<real key="value" value="16"/>
</userDefinedRuntimeAttribute>
<userDefinedRuntimeAttribute type="number" keyPath="borderWidthValue">
<real key="value" value="0.0"/>
</userDefinedRuntimeAttribute>
</userDefinedRuntimeAttributes>
Solution: Right click on foo.storyboard
> Open as Source Code > search by keyPath (i.e. shadowRadius) > Delete the </userDefinedRuntimeAttributes>
that causing the problem
Go to
https://github.com/Darkseal/bootstrap4-glyphicons
download and include in your code
<link href="bootstrap4-glyphicons/css/bootstrap-glyphicons.css" rel="stylesheet">
Using SQL Server Management Studio
To configure the default language option
English
.Using Transact-SQL
To configure the default language option
This example shows how to use sp_configure to configure the default language option to French
USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO
The 33 languages of SQL Server
| LANGID | ALIAS |
|--------|---------------------|
| 0 | English |
| 1 | German |
| 2 | French |
| 3 | Japanese |
| 4 | Danish |
| 5 | Spanish |
| 6 | Italian |
| 7 | Dutch |
| 8 | Norwegian |
| 9 | Portuguese |
| 10 | Finnish |
| 11 | Swedish |
| 12 | Czech |
| 13 | Hungarian |
| 14 | Polish |
| 15 | Romanian |
| 16 | Croatian |
| 17 | Slovak |
| 18 | Slovenian |
| 19 | Greek |
| 20 | Bulgarian |
| 21 | Russian |
| 22 | Turkish |
| 23 | British English |
| 24 | Estonian |
| 25 | Latvian |
| 26 | Lithuanian |
| 27 | Brazilian |
| 28 | Traditional Chinese |
| 29 | Korean |
| 30 | Simplified Chinese |
| 31 | Arabic |
| 32 | Thai |
| 33 | Bokmål |
Yes, you're looking for the ReDim
statement, which dynamically allocates the required amount of space in the array.
The following statement
Dim MyArray()
declares an array without dimensions, so the compiler doesn't know how big it is and can't store anything inside of it.
But you can use the ReDim
statement to resize the array:
ReDim MyArray(0 To 3)
And if you need to resize the array while preserving its contents, you can use the Preserve
keyword along with the ReDim
statement:
ReDim Preserve MyArray(0 To 3)
But do note that both ReDim
and particularly ReDim Preserve
have a heavy performance cost. Try to avoid doing this over and over in a loop if at all possible; your users will thank you.
However, in the simple example shown in your question (if it's not just a throwaway sample), you don't need ReDim
at all. Just declare the array with explicit dimensions:
Dim MyArray(0 To 3)
Have you tried using the [FromUri]
attribute when sending parameters over the query string.
Here is an example:
[HttpGet]
[Route("api/department/getndeptsfromid")]
public List<Department> GetNDepartmentsFromID([FromUri]int FirstId, [FromUri] int CountToFetch)
{
return HHSService.GetNDepartmentsFromID(FirstId, CountToFetch);
}
Include this package at the top also, using System.Web.Http;
You have to define an SMTP
server and a port for this. All except like sending mails from live hosts.
This is a useful link regarding this.
NB: The port should be unused. Please take care that, Some applications like
Skype
uses the default ports and there by prevents sending mail.
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
i use like tim say sprintf('%0.6f', x)
, it's a string then i change it to number by using command str2double(x)
.
You may do this with a for
loop instead of a while
:
max_loop=20
for ((count = 0; count < max_loop; count++)); do
if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
echo "Files Present" | mailx -s "File Present" -r [email protected] [email protected]
break
else
echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected]
sleep 1800
fi
done
if [ "$count" -eq "$max_loop" ]; then
echo "Maximum number of trials reached" >&2
exit 1
fi
F5 is a standard page reload.
and
Ctrl + F5 refreshes the page by clearing the cached content of the page.
Having the cursor in the address field and pressing Enter will also do the same as Ctrl + F5.
A more modern solution might be to use css variables
and calc
. calc
is widely supported but variables
is not yet in IE11 (polyfills available).
:root {
box-width: 100px;
border-width: 1px;
}
#box {
width: calc(var(--box-width) - var(--border-width));
}
Although this does use some calculations, which the original questions was looking to avoid. I think this is an ok time to use calculations as they are controlled by the css itself. It also has no need for additional markup or misappropriating other css properties that may be needed later on.
This solution is only really useful if a fixed height isn't needed.
You can use simple following code
String str= "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.print(words[i]+" ");
Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;
DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2
In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.
One place this is very helpful is if you want to turn a column into a comma-separated list;
DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list
Swift 4:
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
// Code
}
For the time .seconds(Int)
, .microseconds(Int)
and .nanoseconds(Int)
may also be used.
Using autoview
image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true
The div element has its own alignment attribute, align.
<div align="center">
my text here.
</div>
Create an initializer for it:
# config/initializers/time_formats.rb
Add something like this to it:
Time::DATE_FORMATS[:custom_datetime] = "%d.%m.%Y"
And then use it the following way:
post.updated_at.to_s(:custom_datetime)
?? Your have to restart rails server for this to work.
Check the documentation for more information: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s
You could attempt to load the the https page in an iframe and route all ajax requests in/out of the frame via some bridge, it's a hackaround but it might work (not sure if it will impose the same access restrictions given the secure context). Otherwise a local http proxy to reroute requests (like any cross domain calls) would be the accepted solution.
You can use simple for loop for conversion:
public void byteArrToString(){
byte[] b = {'a','b','$'};
String str = "";
for(int i=0; i<b.length; i++){
char c = (char) b[i];
str+=c;
}
System.out.println(str);
}
StringBuffer
is synchronized, but StringBuilder
is not. As a result, StringBuilder
is faster than StringBuffer
.
Go to Run (WINDOWS + R) and Type shell:startup, paste your .bat file there !
Add below setting to .eslintrc.js
/ .eslintrc.json
to ignore these errors:
rules: {
// suppress errors for missing 'import React' in files
"react/react-in-jsx-scope": "off",
// allow jsx syntax in js files (for next.js project)
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }], //should add ".ts" if typescript project
}
Why?
If you're using NEXT.js
then you do not require to import React
at top of files, nextjs does that for you.
If you can update your connector to a version, which supports the new authentication plugin of MySQL 8, then do that. If that is not an option for some reason, change the default authentication method of your database user to native.
In the terminal just write : $ mongod --version
Simply disable default browser behaviour using preventDefault
and pass the event
within your HTML.
<a href=/foo onclick= yes_js_login(event)>Lorem ipsum</a>
yes_js_login = function(e) {
e.preventDefault();
}
I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default
declaration for a class, and instead append the export
tag to the class declaration. The imported class should be instead listed in the import
command of the module.
That is: instead of
class Foo {
// ...
}
export default Foo;
and the simple import Foo from './foo';
in the module that will import, one should use
export class Foo {
// ...
}
and import {Foo} from './foo'
in the importer.
The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in export default
can lead to problems
I was going to answer this question. Then I saw it get marked as a duplicate of this question, after I'd written the code, so I am going to post my solution here.
Keeping in mind that you have to re-write the text file. First I read the entire file, and store it in a string. Then I store each line as a index of a string array, ex line one = array index 0. I then edit the index corresponding to the line that you wish to edit. Once this is done I concatenate all the strings in the array into a single string. Then I write the new string into the file, which writes over the old content. Don't worry about losing your old content as it has been written again with the edit. below is the code I used.
public class App {
public static void main(String[] args) {
String file = "file.txt";
String newLineContent = "Hello my name is bob";
int lineToBeEdited = 3;
ChangeLineInFile changeFile = new ChangeLineInFile();
changeFile.changeALineInATextFile(file, newLineContent, lineToBeEdited);
}
}
And the class.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class ChangeLineInFile {
public void changeALineInATextFile(String fileName, String newLine, int lineNumber) {
String content = new String();
String editedContent = new String();
content = readFile(fileName);
editedContent = editLineInContent(content, newLine, lineNumber);
writeToFile(fileName, editedContent);
}
private static int numberOfLinesInFile(String content) {
int numberOfLines = 0;
int index = 0;
int lastIndex = 0;
lastIndex = content.length() - 1;
while (true) {
if (content.charAt(index) == '\n') {
numberOfLines++;
}
if (index == lastIndex) {
numberOfLines = numberOfLines + 1;
break;
}
index++;
}
return numberOfLines;
}
private static String[] turnFileIntoArrayOfStrings(String content, int lines) {
String[] array = new String[lines];
int index = 0;
int tempInt = 0;
int startIndext = 0;
int lastIndex = content.length() - 1;
while (true) {
if (content.charAt(index) == '\n') {
tempInt++;
String temp2 = new String();
for (int i = 0; i < index - startIndext; i++) {
temp2 += content.charAt(startIndext + i);
}
startIndext = index;
array[tempInt - 1] = temp2;
}
if (index == lastIndex) {
tempInt++;
String temp2 = new String();
for (int i = 0; i < index - startIndext + 1; i++) {
temp2 += content.charAt(startIndext + i);
}
array[tempInt - 1] = temp2;
break;
}
index++;
}
return array;
}
private static String editLineInContent(String content, String newLine, int line) {
int lineNumber = 0;
lineNumber = numberOfLinesInFile(content);
String[] lines = new String[lineNumber];
lines = turnFileIntoArrayOfStrings(content, lineNumber);
if (line != 1) {
lines[line - 1] = "\n" + newLine;
} else {
lines[line - 1] = newLine;
}
content = new String();
for (int i = 0; i < lineNumber; i++) {
content += lines[i];
}
return content;
}
private static void writeToFile(String file, String content) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) {
writer.write(content);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String readFile(String filename) {
String content = null;
File file = new File(filename);
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return content;
}
}
Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository
in your settings.xml
or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.
A workaround is as follows. In the value:
releases::default::https://YOUR_NEXUS_URL/releases
you need to remove the default
section, making it:
releases::https://YOUR_NEXUS_URL/releases
The prior version 2.8.2 does not have this bug.
Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.
Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:
$ uname -a
armv7l
Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.
You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.
You can follow the GitHub issue for 64-bit support here, if you're interested.
read
will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:
import boto3
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8')
I was not able to modify the protected mode settings manually on my system since they were disabled. But the below VBA snippet for updating the registry values did the trick for me.(Please be cautious about any restrictions on your organization on modifying registry, before trying this)
Const HKEY_CURRENT_USER = &H80000001
strComputer = "."
Set ScriptMe=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
'Disable protected mode for local intranet'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue
'Disable protected mode for trusted pages'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue
'Disable protected mode for internet'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue
'Disable protected mode for restricted sites'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue
msgbox "Protected Mode Settings are updated"
Just copy paste the above code into notepad and save it with .vbs extension and double click it!
Now try running your automation script again
library(plyr)
ldply(apply(data, 1, function(x) data.frame(
x = paste(x[2:4],sep="",collapse="-"))))
# x
#1 a-d-g
#2 b-e-h
#3 c-f-i
# and with just the vector of names you have:
ldply(apply(data, 1, function(x) data.frame(
x = paste(x[c('b','c','d')],sep="",collapse="-"))))
# or equally:
mynames <-c('b','c','d')
ldply(apply(data, 1, function(x) data.frame(
x = paste(x[mynames],sep="",collapse="-"))))
I am using Laravel 8 and just installed the fruitcake/laravel-cors
and use it in app/Http/Kernel.php
like blow:
protected $middleware = [
....
\Fruitcake\Cors\HandleCors::class,
];
note : add it to end of array like me
create procedure PSaleCForms
as
begin
declare
@b varchar(9),
@c nvarchar(500),
@q nvarchar(max)
declare @T table(FY nvarchar(9),Qtr int,title nvarchar (max),invoicenumber nvarchar(max),invoicedate datetime,sp decimal 18,2),grandtotal decimal(18,2))
declare @data cursor
set @data= Cursor
forward_only static
for
select x.DBTitle,y.CurrentFinancialYear from [Accounts Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on y.DBID=x.DBID where x.cfy=1
open @data
fetch next from @data
into @c,@b
while @@FETCH_STATUS=0
begin
set @q=N'Select '''+@b+''' [fy], case cast(month(i.invoicedate)/3.1 as int) when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr], l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from ['+@c+'].dbo.invoicemain i inner join ['+@c+'].dbo.ledgermain l on l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''
insert into @T exec [master].dbo.sp_executesql @q fetch next from @data into @c,@b end close @data deallocate @data select * from @T return end
The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX
and on POSIX conformant systems you can query it with
$ getconf ARG_MAX # Get argument limit in bytes
E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.
If you need to process a list of files exceeding this limit, you might want to look at the xargs
utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX
.
To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".
Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX
. The restriction also does not apply to shell-builtins.
If it's any help to anyone, the Version 2.0 of the bootstrap datepicker no longer works with the accepted answer.
Here's how I got it working on mine:
$('yourpickerid').datepicker({
format: 'dd/mm/yyyy',
}).on('changeDate', function(e){
$(this).datepicker('hide');
});
See http://bootstrap-datepicker.readthedocs.org/en/latest/events.html#changedate
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[spCountNewLastIDAnyTableRows]
(
@PassedTableName as NVarchar(255),
@PassedColumnName as NVarchar(225)
)
AS
BEGIN
DECLARE @ActualTableName AS NVarchar(255)
DECLARE @ActualColumnName as NVarchar(225)
SELECT @ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @PassedTableName
SELECT @ActualColumnName = QUOTENAME( COLUMN_NAME )
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = @PassedColumnName
DECLARE @sql AS NVARCHAR(MAX)
SELECT @sql = 'select MAX('+ @ActualColumnName + ') + 1 as LASTID' + ' FROM ' + @ActualTableName
EXEC(@SQL)
END
I had angular-cli version 1.0.0-beta.28.3
, and the only thing that worked for me was deleting the angular-cli directly from the global node_modules folder:
cd /usr/local/bin/lib/node_modules
rm -rf angular-cli
After that ng version
output was, as expected:
command not found: ng
And I could install the latest angular-cli version:
npm install -g @angular/cli@latest
Hope it helps...
This is my code - by calling the function play()
the video plays or pauses and the button image is changed.
By calling the function volume()
the volume is turned on/off and the button image also changes.
function play() {
var video = document.getElementById('slidevideo');
if (video.paused) {
video.play()
play_img.src = 'img/pause.png';
}
else {
video.pause()
play_img.src = 'img/play.png';
}
}
function volume() {
var video = document.getElementById('slidevideo');
var img = document.getElementById('volume_img');
if (video.volume > 0) {
video.volume = 0
volume_img.src = 'img/volume_off.png';
}
else {
video.volume = 1
volume_img.src = 'img/volume_on.png';
}
}
[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
string[] formats = { "MM/dd/yyyy" };
DateTime parsedDateTime;
return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
DateTimeStyles.None, out parsedDateTime);
}
Simply specify the date time formats that you wish to accept in the array named formats.
How about this. using the modulo operator
if(a%b==0)
{
System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
System.out.println("b is NOT a factor of a");
}
Also check that
<modules>
<remove name="FormsAuthentication"/>
</modules>
If you found anything like this just remove:
<remove name="FormsAuthentication"/>
Line from web.config and here you go it will work fine I have tested it.
Adding exclusions was not enough for me. I had to provide a fake jar:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>system</scope>
<systemPath>${project.basedir}/empty.jar</systemPath>
</dependency>
You can always do:
... ng-model="file.PLIK_STATUS" ng-change="file.PLIK_STATUS = setFileStatus(file.PLIK_ID,file.PLIK_STATUS,'{{file.PLIK_STATUS}}')" ...
and in controller:
$scope.setFileStatus = function (plik_id, new_status, old_status) {
var answer = confirm('Czy na pewno zmienic status dla pliku ?');
if (answer) {
podasysService.setFileStatus(plik_id, new_status).then(function (result) {
return new_status;
});
}else{
return old_status;
}
};
You can try {0: (000) 000-####} if your target number starts with 0.
I believe you need your support package in both Library and application. However, to fix this, make sure you have same file at both locations (same checksum).
Simply copy the support-package file from one location and copy at another then clean+refresh your library/project and you should be good to go.
Use the ampersand just like you would from the shell.
#!/usr/bin/bash
function_to_fork() {
...
}
function_to_fork &
# ... execution continues in parent process ...
The ls
command will only print the name of the file in the directory. Why not do something like
print("/mnt/mediashare/net/192.168.1.220_STORAGE_1d1b7/" + i)
This will print out the directory with the filename.
It is a bit time consuming converting your markup and CSS to React-PDF's format, but it is easy to understand. Exporting a PDF and from it is fairly straightforward.
To allow a user to download a PDF generated by react-PDF, use their on the fly rendering, which provides a customizable download link. When clicked, the site renders and downloads the PDF for the user.
Here's their REPL which will familiarize you with the markup and styling required. They have a download link for the PDF too, but they don't show the code for that here.
using (StreamWriter writer = new StreamWriter(File.Open(@"E:\Sample.txt", FileMode.Append), Encoding.GetEncoding(1250))) ////File.Create(path)
{
writer.Write("Sample Text");
}
Here is another way using select and merge:
In [6]: # first lets create some dummy dataframes with some column(s) different
...: df1 = pd.DataFrame({'a': range(-5,0), 'b': range(10,15), 'c': range(20,25)})
...: df2 = pd.DataFrame({'a': range(-5,0), 'b': range(10,15), 'c': [20] + list(range(101,105))})
In [7]: df1
Out[7]:
a b c
0 -5 10 20
1 -4 11 21
2 -3 12 22
3 -2 13 23
4 -1 14 24
In [8]: df2
Out[8]:
a b c
0 -5 10 20
1 -4 11 101
2 -3 12 102
3 -2 13 103
4 -1 14 104
In [10]: # make condition over the columns you want to comapre
...: condition = df1['c'] != df2['c']
...:
...: # select rows from each dataframe where the condition holds
...: diff1 = df1[condition]
...: diff2 = df2[condition]
In [11]: # merge the selected rows (dataframes) with some suffixes (optional)
...: diff1.merge(diff2, on=['a','b'], suffixes=('_before', '_after'))
Out[11]:
a b c_before c_after
0 -4 11 21 101
1 -3 12 22 102
2 -2 13 23 103
3 -1 14 24 104
Here is the same thing from a Jupyter screenshot:
For people just migrating from java
, In Kotlin
List
is by default immutable and mutable version of Lists is called MutableList
.
Hence if you have something like :
val list: List<String> = ArrayList()
In this case you will not get an add()
method as list is immutable. Hence you will have to declare a MutableList
as shown below :
val list: MutableList<String> = ArrayList()
Now you will see an add()
method and you can add elements to any list.
Please take note that proxy_cache_bypass can give you a world of hurt if your app doesn't return a cacheable response for that specific request where you trigger it.
If for example your app sends a cookie with every first request, then a script which triggers proxy_pass_bypass via curl will probably get that cookie in the answer, and nginx will not use that response to refresh the cached item.
SELECT <...>
FROM A.tableA JOIN B.tableB
In "pure" bash you have many tools for (sub)string manipulation, mainly, but not exclusively in parameter expansion :
${parameter//substring/replacement}
${parameter##remove_matching_prefix}
${parameter%%remove_matching_suffix}
Indexed substring expansion (special behaviours with negative offsets, and, in newer Bashes, negative lengths):
${parameter:offset}
${parameter:offset:length}
${parameter:offset:length}
And of course, the much useful expansions that operate on whether the parameter is null:
${parameter:+use this if param is NOT null}
${parameter:-use this if param is null}
${parameter:=use this and assign to param if param is null}
${parameter:?show this error if param is null}
They have more tweakable behaviours than those listed, and as I said, there are other ways to manipulate strings (a common one being $(command substitution)
combined with sed or any other external filter). But, they are so easily found by typing man bash
that I don't feel it merits to further extend this post.
As of Docker Compose 1.6, there is now improved support for data volumes in Docker Compose. The following compose file will create a data image which will persist between restarts (or even removal) of parent containers:
Here is the blog announcement: Compose 1.6: New Compose file for defining networks and volumes
Here's an example compose file:
version: "2"
services:
db:
restart: on-failure:10
image: postgres:9.4
volumes:
- "db-data:/var/lib/postgresql/data"
web:
restart: on-failure:10
build: .
command: gunicorn mypythonapp.wsgi:application -b :8000 --reload
volumes:
- .:/code
ports:
- "8000:8000"
links:
- db
volumes:
db-data:
As far as I can understand: This will create a data volume container (db_data
) which will persist between restarts.
If you run: docker volume ls
you should see your volume listed:
local mypthonapp_db-data
...
You can get some more details about the data volume:
docker volume inspect mypthonapp_db-data
[
{
"Name": "mypthonapp_db-data",
"Driver": "local",
"Mountpoint": "/mnt/sda1/var/lib/docker/volumes/mypthonapp_db-data/_data"
}
]
Some testing:
# Start the containers
docker-compose up -d
# .. input some data into the database
docker-compose run --rm web python manage.py migrate
docker-compose run --rm web python manage.py createsuperuser
...
# Stop and remove the containers:
docker-compose stop
docker-compose rm -f
# Start it back up again
docker-compose up -d
# Verify the data is still there
...
(it is)
# Stop and remove with the -v (volumes) tag:
docker-compose stop
docker=compose rm -f -v
# Up again ..
docker-compose up -d
# Check the data is still there:
...
(it is).
Notes:
You can also specify various drivers in the volumes
block. For example, You could specify the Flocker driver for db_data:
volumes:
db-data:
driver: flocker
Disclaimer: This approach is promising, and I'm using it successfully in a development environment. I would be apprehensive to use this in production just yet!
In my case it happened when calling a function by passing a parameter of a Core Data managed object's property. At the time of calling the object was no longer existed, and that caused this error.
I have solved the issue by checking if the managed object exists or not before calling the function.
In the example you give, you're perfectly right, you have to set the title attribute.
If the aria-label
is one tool used by assistive technologies (like screen readers), it is not natively supported on browsers and has no effect on them. It won't be of any help to most of the people targetted by the WCAG (except screen reader users), for instance a person with intellectal disabilities.
The "X" is not sufficient enough to give information to the action led by the button (think about someone with no computer knowledge). It might mean "close", "delete", "cancel", "reduce", a strange cross, a doodle, nothing.
Despite the fact that the W3C seems to promote the aria-label
rather that the title
attribute here: http://www.w3.org/TR/2014/NOTE-WCAG20-TECHS-20140916/ARIA14 in a similar example, you can see that the technology support does not include standard browsers : http://www.w3.org/WAI/WCAG20/Techniques/ua-notes/aria#ARIA14
In fact aria-label
, in this exact situation might be used to give more context to an action:
For instance, blind people do not perceive popups like those of us with good vision, it's like a change of context. "Back to the page" will be a more convenient alternative for a screen reader, when "Close" is more significant for someone with no screen reader.
<button
aria-label="Back to the page"
title="Close" onclick="myDialog.close()">X</button>
compare properties in the array if one matches the input then set something to the value of the loops current position, which is also the index of the current looked up item.
simple eg.
dim x,y,z as integer
dim aNames, aIndexes as array
dim sFind as string
for x = 1 to length(aNames)
if aNames(x) = sFind then y = x
y is then the index of the item in the array, then loop could be used to store these in an array also so instead of the above you would have:
z = 1
for x = 1 to length(aNames)
if aNames(x) = sFind then
aIndexes(z) = x
z = z + 1
endif
In the Edit Application Pool window, set the .NET CLR version to No Managed Code
This
PRIMARY KEY (
id
(11))
is generated automatically by phpmyadmin, change to
PRIMARY KEY (
id
)
.
Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.
Pretty Simple example is available here,
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
For selections, you can also convert the selection using the "To spaces" function. I usually just use it via the ctrl-shift-A then find "To Spaces" from there.
using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
writer.WriteLine("whatever you text is");
}
The second "true" parameter tells it to append.
just write
<input type="number" step="0.1" lang="nb">
lang='nb" let you write your decimal numbers with comma or period
I can't believe how complex everyone is making this. This is actually very simple. Just paste this into your html (no directive./controller changes required - "bg-info" is a bootstrap class):
<div class="form-group col-md-12">
<div ng-class="{'bg-info': (!transport_type)}" ng-click="transport_type=false">CARS</div>
<div ng-class="{'bg-info': transport_type=='TRAINS'}" ng-click="transport_type='TRAINS'">TRAINS</div>
<div ng-class="{'bg-info': transport_type=='PLANES'}" ng-click="transport_type='PLANES'">PLANES</div>
</div>
After change .env with the new configuration, you have to stop the server and run it again (php artisan serve). Cause laravel gets the environment when it's initialized the server. If you don't restart, you will change the .env asking yourself why the changes aren't taking place!!
Inefficient alternative:
str.reverse.chop.reverse
--Short and sweet:
SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema],
T.[name] AS [table_name], I.[name] AS [index_name], AC.[name] AS [column_name],
I.[type_desc], I.[is_unique], I.[data_space_id], I.[ignore_dup_key], I.[is_primary_key],
I.[is_unique_constraint], I.[fill_factor], I.[is_padded], I.[is_disabled], I.[is_hypothetical],
I.[allow_row_locks], I.[allow_page_locks], IC.[is_descending_key], IC.[is_included_column]
FROM sys.[tables] AS T
INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]
INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id]
INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id]
WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP'
ORDER BY T.[name], I.[index_id], IC.[key_ordinal]
The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await
with Task'1.Result
, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.
I've rewritten your function and function call, which should fix your issue:
async Task<string> GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
And your final function call:
Task<string> result = GetResponseString(text);
var finalResult = result.Result;
Or even better:
var finalResult = await GetResponseString(text);
The best way is using the transparent color code
android:background="#00000000"
use the color code #00000000 for making any thing transparent
Upgrading from Ubuntu 10.0.4 to 12.0.4 we got wrong footed. We had a JDK installation configured (auto-configured?) pointing to /usr/lib/jvm/java-6-openjdk this no longer contained a JDK, Changing to /usr/lib/jvm/default-java fixed, and should make for a seamless java-7 upgrade.
So in answer to the question: do not specify JAVA_HOME on Ubuntu.
Here I think it's worth mentioning SORT BY
and ORDER BY
both clauses and why they different,
SELECT * FROM <table_name> SORT BY <column_name> DESC LIMIT 2
If you are using SORT BY
clause it sort data per reducer which means if you have more than one MapReduce task it will result partially ordered data. On the other hand, the ORDER BY
clause will result in ordered data for the final Reduce task. To understand more please refer to this link.
SELECT * FROM <table_name> ORDER BY <column_name> DESC LIMIT 2
Note: Finally, Even though the accepted answer contains SORT BY
clause, I mostly prefer to use ORDER BY
clause for the general use case to avoid any data loss.
You can use String.Format:
DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"
In my view, With Expire Header, server can tell the client when my data would be stale, while with Etag, server would check the etag value for client' each request.
Which whitespace character? The most common is the normal space, which is between each word in my sentences. This is just " "
.
If you are using at least Java 8 you can use method runAsync
from class CompletableFuture
CompletableFuture.runAsync(() -> {...});
If you need to return a result use supplyAsync
instead
CompletableFuture.supplyAsync(() -> 1);
If you want it to stop looking after a while (timeout) then the following jQuery will work. It will time out after 10sec. I needed to use this code rather than pure JS because I needed to select an input via name and was having trouble implementing some of the other solutions.
// Wait for element to exist.
function imageLoaded(el, cb,time) {
if ($(el).length) {
// Element is now loaded.
cb($(el));
var imageInput = $('input[name=product\\[image_location\\]]');
console.log(imageInput);
} else if(time < 10000) {
// Repeat every 500ms.
setTimeout(function() {
time = time+500;
imageLoaded(el, cb, time)
}, 500);
}
};
var time = 500;
imageLoaded('input[name=product\\[image_location\\]]', function(el) {
//do stuff here
},time);
You haven't specified what language you are using but assuming C# / .NET you could use SOAP extensions.
Otherwise, use a sniffer such as Wireshark
Python 2
The error is caused because ElementTree did not expect to find non-ASCII strings set the XML when trying to write it out. You should use Unicode strings for non-ASCII instead. Unicode strings can be made either by using the u
prefix on strings, i.e. u'€'
or by decoding a string with mystr.decode('utf-8')
using the appropriate encoding.
The best practice is to decode all text data as it's read, rather than decoding mid-program. The io
module provides an open()
method which decodes text data to Unicode strings as it's read.
ElementTree will be much happier with Unicodes and will properly encode it correctly when using the ET.write()
method.
Also, for best compatibility and readability, ensure that ET encodes to UTF-8 during write()
and adds the relevant header.
Presuming your input file is UTF-8 encoded (0xC2
is common UTF-8 lead byte), putting everything together, and using the with
statement, your code should look like:
with io.open('myText.txt', "r", encoding='utf-8') as f:
data = f.read()
root = ET.Element("add")
doc = ET.SubElement(root, "doc")
field = ET.SubElement(doc, "field")
field.set("name", "text")
field.text = data
tree = ET.ElementTree(root)
tree.write("output.xml", encoding='utf-8', xml_declaration=True)
Output:
<?xml version='1.0' encoding='utf-8'?>
<add><doc><field name="text">data€</field></doc></add>
This is my solution:
public class Foo : IDisposable
{
private event EventHandler _statusChanged;
public event EventHandler StatusChanged
{
add
{
_statusChanged += value;
}
remove
{
_statusChanged -= value;
}
}
public void Dispose()
{
_statusChanged = null;
}
}
You need to call Dispose()
or use using(new Foo()){/*...*/}
pattern to unsubscribe all members of invocation list.
If your query consists only of the $where
operator, you can pass in just the JavaScript expression:
db.T.find("this.Grade1 > this.Grade2");
For greater performance, run an aggregate operation that has a $redact
pipeline to filter the documents which satisfy the given condition.
The $redact
pipeline incorporates the functionality of $project
and $match
to implement field level redaction where it will return all documents matching the condition using $$KEEP
and removes from the pipeline results those that don't match using the $$PRUNE
variable.
Running the following aggregate operation filter the documents more efficiently than using $where
for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where
, which can slow down the query:
db.T.aggregate([
{
"$redact": {
"$cond": [
{ "$gt": [ "$Grade1", "$Grade2" ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
which is a more simplified version of incorporating the two pipelines $project
and $match
:
db.T.aggregate([
{
"$project": {
"isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
"Grade1": 1,
"Grade2": 1,
"OtherFields": 1,
...
}
},
{ "$match": { "isGrade1Greater": 1 } }
])
With MongoDB 3.4 and newer:
db.T.aggregate([
{
"$addFields": {
"isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
}
},
{ "$match": { "isGrade1Greater": 1 } }
])
[[]]*3
is not the same as [[], [], []]
.
It's as if you'd said
a = []
listy = [a, a, a]
In other words, all three list references refer to the same list instance.
I Just enhanced Ege Özcan's dynamic sort to dive deep inside objects. If Data looks like this:
obj = [
{
a: { a: 1, b: 2, c: 3 },
b: { a: 4, b: 5, c: 6 }
},
{
a: { a: 3, b: 2, c: 1 },
b: { a: 6, b: 5, c: 4 }
}];
and if you want to sort it over a.a property I think my enhancement helps very well. I add new functionality to objects like this:
Object.defineProperty(Object.prototype, 'deepVal', {
enumerable: false,
writable: true,
value: function (propertyChain) {
var levels = propertyChain.split('.');
parent = this;
for (var i = 0; i < levels.length; i++) {
if (!parent[levels[i]])
return undefined;
parent = parent[levels[i]];
}
return parent;
}
});
and changed _dynamicSort's return function:
return function (a,b) {
var result = ((a.deepVal(property) > b.deepVal(property)) - (a.deepVal(property) < b.deepVal(property)));
return result * sortOrder;
}
And now you can sort by a.a. this way:
obj.sortBy('a.a');
See Commplete script in JSFiddle
Don't set the style object itself, set the background color property of the style object that is a property of the element.
And yes, even though you said no, jquery and tablesorter with its zebra stripe plugin can do this all for you in 3 lines of code.
And just setting the class attribute would be better since then you have non-hard-coded control over the styling which is more organized
I was having the same problem using my class SharedModule.
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [MyService]
}
}
}
Then I changed it putting directly in the app.modules this way
@NgModule({declarations: [
AppComponent,
NaviComponent],imports: [BrowserModule,RouterModule.forRoot(ROUTES),providers: [MoviesService],bootstrap: [MyService] })
Obs: I'm using "@angular/core": "^6.0.2".
I hope its help you.
The main point is this:
col-lg-*
col-md-*
col-xs-*
col-sm
define how many columns will there be in these different screen sizes.
Example: if you want there to be two columns in desktop screens and in phone screens you put two col-md-6
and two col-xs-6
classes in your columns.
If you want there to be two columns in desktop screens and only one column in phone screens (ie two rows stacked on top of each other) you put two col-md-6
and two col-xs-12
in your columns and because sum will be 24 they will auto stack on top of each other, or just leave xs
style out.
Sometimes value stored in Database could contain spaces so running this could be fail
String.Equals(row.Name, "test", StringComparison.OrdinalIgnoreCase)
Solution to this problems is to remove space then convert its case then select like this
return db.UsersTBs.Where(x => x.title.ToString().ToLower().Replace(" ",string.Empty).Equals(customname.ToLower())).FirstOrDefault();
Note in this case
customname is value to match with Database value
UsersTBs is class
title is the Database column
I found a workaround a week ago. You can use direct commands with "ExecuteCommand
":
MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
where f.Code == Code
select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}
In the ExecuteCommand
statement, you can send the query directly, with the value for the specific record you want to update.
value = 0 --> 0 is the new value for the record;
code = {0} --> is the field where you will send the filter value;
Code --> is the new value for the field;
I hope this reference helps.
Care and feeding of Eclipse's memory hunger is a pain...
More or less, keep trying smaller amounts til it works, that's your max.
For debugging purposes in case you want to look up a raw Mat::type in a debugger:
+--------+----+----+----+----+------+------+------+------+
| | C1 | C2 | C3 | C4 | C(5) | C(6) | C(7) | C(8) |
+--------+----+----+----+----+------+------+------+------+
| CV_8U | 0 | 8 | 16 | 24 | 32 | 40 | 48 | 56 |
| CV_8S | 1 | 9 | 17 | 25 | 33 | 41 | 49 | 57 |
| CV_16U | 2 | 10 | 18 | 26 | 34 | 42 | 50 | 58 |
| CV_16S | 3 | 11 | 19 | 27 | 35 | 43 | 51 | 59 |
| CV_32S | 4 | 12 | 20 | 28 | 36 | 44 | 52 | 60 |
| CV_32F | 5 | 13 | 21 | 29 | 37 | 45 | 53 | 61 |
| CV_64F | 6 | 14 | 22 | 30 | 38 | 46 | 54 | 62 |
+--------+----+----+----+----+------+------+------+------+
So for example, if type = 30 then OpenCV data type is CV_64FC4. If type = 50 then the OpenCV data type is CV_16UC(7).
However you can use eval function to bring concurrency TO SOME EXTENT
/* content of the threads to be run */
var threads = [
[
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');"
],
[
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');"
]
];
window.onload = function() {
var lines = 0, quantum = 3, max = 0;
/* get the longer thread length */
for(var i=0; i<threads.length; i++) {
if(max < threads[i].length) {
max = threads[i].length;
}
}
/* execute them */
while(lines < max) {
for(var i=0; i<threads.length; i++) {
for(var j = lines; j < threads[i].length && j < (lines + quantum); j++) {
eval(threads[i][j]);
}
}
lines += quantum;
}
}
Ok...so first you need to import the image into your project.
1) Select the PictureBox in the Form Design View
2) Open PictureBox Tasks
(it's the little arrow printed to right on the edge of the PictureBox)
3) Click on "Choose image..."
4) Select the second option "Project resource file:"
(this option will create a folder called "Resources" which you can access with Properties.Resources)
5) Click on "Import..." and select your image from your computer
(now a copy of the image will be saved in "Resources" folder created at step 4)
6) Click on "OK"
Now the image is in your project and you can use it with the Properties command. Just type this code when you want to change the picture in the PictureBox:
pictureBox1.Image = Properties.Resources.MyImage;
Note:
MyImage represent the name of the image...
After typing "Properties.Resources.", all imported image files are displayed...
Example: Display different output depending on whether the user is logged in or not.
<?php
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, visitor!';
}
?>
Indeed there is.
chmod a+x
is relative to the current state and just sets the x
flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.
chmod 755
, however, sets the mask as written: rwxr-xr-x
, no matter how it was before. It is equivalent to chmod u=rwx,go=rx
.
For passing arguments to Run Project command either you have to set the arguments in the Project properties Run panel