I do the following for my .NET Standard 2.0 projects.
Create a Directory.Build.props
file (e.g. in the root of your repo)
and move the properties to be shared from the .csproj
file to this file.
MSBuild will pick it up automatically and apply them to the autogenerated AssemblyInfo.cs
.
They also get applied to the nuget package when building one with dotnet pack
or via the UI in Visual Studio 2017.
See https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build
Example:
<Project>
<PropertyGroup>
<Company>Some company</Company>
<Copyright>Copyright © 2020</Copyright>
<AssemblyVersion>1.0.0.1</AssemblyVersion>
<FileVersion>1.0.0.1</FileVersion>
<Version>1.0.0.1</Version>
<!-- ... -->
</PropertyGroup>
</Project>
I don't know what you mean by "data dont get lost". Here's how you pass a normal 2D array to a function:
void myfunc(int arr[M][N]) { // M is optional, but N is required
..
}
int main() {
int somearr[M][N];
...
myfunc(somearr);
...
}
Recursion is very useful is some situations. For example consider the code for finding the factorial
int factorial ( int input )
{
int x, fact = 1;
for ( x = input; x > 1; x--)
fact *= x;
return fact;
}
Now consider it by using the recursive function
int factorial ( int input )
{
if (input == 0)
{
return 1;
}
return input * factorial(input - 1);
}
By observing these two, we can see that recursion is easy to understand.
But if it is not used with care it can be so much error prone too.
Suppose if we miss if (input == 0)
, then the code will be executed for some time and ends with usually a stack overflow.
If you prefer a useEffect
replacement approach:
const usePreviousEffect = (fn, inputs = []) => {
const previousInputsRef = useRef([...inputs])
useEffect(() => {
fn(previousInputsRef.current)
previousInputsRef.current = [...inputs]
}, inputs)
}
And use it like this:
usePreviousEffect(
([prevReceiveAmount, prevSendAmount]) => {
if (prevReceiveAmount !== receiveAmount) // side effect here
if (prevSendAmount !== sendAmount) // side effect here
},
[receiveAmount, sendAmount]
)
Note that the first time the effect executes, the previous values passed to your fn
will be the same as your initial input values. This would only matter to you if you wanted to do something when a value did not change.
To print the last column of a line just use $(NF):
awk '{print $(NF)}'
You can save generated diagram for future use.
You need to set storyboard Id from storyboard identity inspector
AddTaskViewController *add=[self.storyboard instantiateViewControllerWithIdentifier:@"storyboard_id"];
[self presentViewController:add animated:YES completion:nil];
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))
if you want to sort x in-place, you can also:
x.sort(key=operator.attrgetter('score'))
// Buttons
<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />
// Controller
[HttpPost]
public ActionResult index(FormCollection collection)
{
string submitType = "unknown";
if(collection["submit"] != null)
{
submitType = "submit";
}
else if (collection["process"] != null)
{
submitType = "process";
}
} // End of the index method
You can use lineSpacingExtra
and lineSpacingMultiplier
in your XML file.
Demo -> https://jsfiddle.net/xdsuozxf/
Safari still requires the -webkit-
prefix to use flexbox.
.row{_x000D_
box-sizing: border-box;_x000D_
display: -webkit-box;_x000D_
display: -webkit-flex;_x000D_
display: -ms-flexbox;_x000D_
display: flex;_x000D_
-webkit-flex: 0 1 auto;_x000D_
-ms-flex: 0 1 auto;_x000D_
flex: 0 1 auto;_x000D_
-webkit-box-orient: horizontal;_x000D_
-webkit-box-direction: normal;_x000D_
-webkit-flex-direction: row;_x000D_
-ms-flex-direction: row;_x000D_
flex-direction: row;_x000D_
-webkit-flex-wrap: wrap;_x000D_
-ms-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.col {_x000D_
background:red;_x000D_
border:1px solid black;_x000D_
_x000D_
-webkit-flex: 1 ;-ms-flex: 1 ;flex: 1 ;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
_x000D_
<div class="content">_x000D_
<div class="row">_x000D_
<div class="col medium">_x000D_
<div class="box">_x000D_
work on safari browser _x000D_
</div>_x000D_
</div>_x000D_
<div class="col medium">_x000D_
<div class="box">_x000D_
work on safari browser _x000D_
work on safari browser _x000D_
work on safari browser _x000D_
work on safari browser _x000D_
work on safari browser _x000D_
</div>_x000D_
</div>_x000D_
<div class="col medium">_x000D_
<div class="box">_x000D_
work on safari browser _x000D_
work on safari browser _x000D_
work on safari browser _x000D_
work on safari browser _x000D_
work on safari browser _x000D_
work on safari browser work on safari browser _x000D_
work on safari browser _x000D_
</div>_x000D_
</div>_x000D_
</div> _x000D_
</div>_x000D_
</div>
_x000D_
When I tried to access the result from
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
it was plain text result with no key-value pairs Here is an example
var fruits = {
apple: "fruits/apple.png",
banana: "fruits/banana.png",
watermelon: "watermelon.jpg",
grapes: "grapes.png",
orange: "orange.jpg"
}
Now i want to get all links in a separated array , but with this code
function linksOfPics(obJect){
Object.keys(obJect).forEach(function(x){
console.log('\"'+obJect[x]+'\"');
});
}
the result of :
linksOfPics(fruits)
"fruits/apple.png"
"fruits/banana.png"
"watermelon.jpg"
"grapes.png"
"orange.jpg"
undefined
I figured out this one which solves what I'm looking for
console.log(Object.values(fruits));
["fruits/apple.png", "fruits/banana.png", "watermelon.jpg", "grapes.png", "orange.jpg"]
Open the file gradle/wrapper/gradle-wrapper.properties
in your project. Change the version in the distributionUrl
to use the version you want to use, e.g.,
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
So quick question. What if you have two arrays of objects and you would like to 'align' these object arrays so that you can make sure each array's objects are in the order as the other array's? What if you don't know what keys and values any of the objects inside of the arrays contains... Much less what order they're even in?
So you need a 'WildCard Expression' for your [].filter
, [].map
, etc. How do you get a wild card expression?
var jux = (function(){
'use strict';
function wildExp(obj){
var keysCrude = Object.keys(obj),
keysA = ('a["' + keysCrude.join('"], a["') + '"]').split(', '),
keysB = ('b["' + keysCrude.join('"], b["') + '"]').split(', '),
keys = [].concat(keysA, keysB)
.sort(function(a, b){ return a.substring(1, a.length) > b.substring(1, b.length); });
var exp = keys.join('').split(']b').join('] > b').split(']a').join('] || a');
return exp;
}
return {
sort: wildExp
};
})();
var sortKeys = {
k: 'v',
key: 'val',
n: 'p',
name: 'param'
};
var objArray = [
{
k: 'z',
key: 'g',
n: 'a',
name: 'b'
},
{
k: 'y',
key: 'h',
n: 'b',
name: 't'
},
{
k: 'x',
key: 'o',
n: 'a',
name: 'c'
}
];
var exp = jux.sort(sortKeys);
console.log('@juxSort Expression:', exp);
console.log('@juxSort:', objArray.sort(function(a, b){
return eval(exp);
}));
You can also use this function over an iteration for each object to create a better collective expression for all of the keys in each of your objects, and then filter your array that way.
This is a small snippet from the API Juxtapose which I have almost complete, which does this, object equality with exemptions, object unities, and array condensation. If these are things you need or want for your project please comment and I'll make the lib accessible sooner than later.
Hope this helps! Happy coding :)
You can redirect anything or more URL via javascript, Just simple window.location.href
with if else
Use this code,
<script>
if(window.location.href == 'old_url')
{
window.location.href="new_url";
}
//Another url redirect
if(window.location.href == 'old_url2')
{
window.location.href="new_url2";
}
</script>
You can redirect many URL's by this procedure. Thanks.
Something like this?
The idea is to wrap the <table>
in a non-statically positioned <div>
which has an overflow:auto
CSS property. Then position the elements in the <thead>
absolutely.
#table-wrapper {_x000D_
position:relative;_x000D_
}_x000D_
#table-scroll {_x000D_
height:150px;_x000D_
overflow:auto; _x000D_
margin-top:20px;_x000D_
}_x000D_
#table-wrapper table {_x000D_
width:100%;_x000D_
_x000D_
}_x000D_
#table-wrapper table * {_x000D_
background:yellow;_x000D_
color:black;_x000D_
}_x000D_
#table-wrapper table thead th .text {_x000D_
position:absolute; _x000D_
top:-20px;_x000D_
z-index:2;_x000D_
height:20px;_x000D_
width:35%;_x000D_
border:1px solid red;_x000D_
}
_x000D_
<div id="table-wrapper">_x000D_
<div id="table-scroll">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th><span class="text">A</span></th>_x000D_
<th><span class="text">B</span></th>_x000D_
<th><span class="text">C</span></th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr> <td>1, 0</td> <td>2, 0</td> <td>3, 0</td> </tr>_x000D_
<tr> <td>1, 1</td> <td>2, 1</td> <td>3, 1</td> </tr>_x000D_
<tr> <td>1, 2</td> <td>2, 2</td> <td>3, 2</td> </tr>_x000D_
<tr> <td>1, 3</td> <td>2, 3</td> <td>3, 3</td> </tr>_x000D_
<tr> <td>1, 4</td> <td>2, 4</td> <td>3, 4</td> </tr>_x000D_
<tr> <td>1, 5</td> <td>2, 5</td> <td>3, 5</td> </tr>_x000D_
<tr> <td>1, 6</td> <td>2, 6</td> <td>3, 6</td> </tr>_x000D_
<tr> <td>1, 7</td> <td>2, 7</td> <td>3, 7</td> </tr>_x000D_
<tr> <td>1, 8</td> <td>2, 8</td> <td>3, 8</td> </tr>_x000D_
<tr> <td>1, 9</td> <td>2, 9</td> <td>3, 9</td> </tr>_x000D_
<tr> <td>1, 10</td> <td>2, 10</td> <td>3, 10</td> </tr>_x000D_
<!-- etc... -->_x000D_
<tr> <td>1, 99</td> <td>2, 99</td> <td>3, 99</td> </tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
You need something like a regular expression.
You have to be in Extended
mode
If you want all the lines to end up on a single line use \r\n
. If you want to simply remove empty lines, use \n\r
as @Link originally suggested.
Replace either expression with nothing.
You could consider using an external tool like ffmpeg to merge the images into a movie (see answer here) or you could try to use OpenCv to combine the images into a movie like the example here.
I'm attaching below a code snipped I used to combine all png files from a folder called "images" into a video.
import cv2
import os
image_folder = 'images'
video_name = 'video.avi'
images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 1, (width,height))
for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows()
video.release()
For Byron, you can try this..
public String test(){
String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN
where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
List<String> li = jdbcTemplate.queryForList(sql,String.class);
return li.get(0).toString();
}
I used the Google Apps Script method indexOf()
and its results were wrong. So I wrote the small function Myindexof()
, instead of indexOf
:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');
On my Linux system (Red Hat Enterprise 6.9), the split
command does not have the command-line options for either -n
or --additional-suffix
.
Instead, I've used this:
split -d -l NUM_LINES really_big_file.txt split_files.txt.
where -d
is to add a numeric suffix to the end of the split_files.txt.
and -l
specifies the number of lines per file.
For example, suppose I have a really big file like this:
$ ls -laF
total 1391952
drwxr-xr-x 2 user.name group 40 Sep 14 15:43 ./
drwxr-xr-x 3 user.name group 4096 Sep 14 15:39 ../
-rw-r--r-- 1 user.name group 1425352817 Sep 14 14:01 really_big_file.txt
This file has 100,000 lines, and I want to split it into files with at most 30,000 lines. This command will run the split and append an integer at the end of the output file pattern split_files.txt.
.
$ split -d -l 30000 really_big_file.txt split_files.txt.
The resulting files are split correctly with at most 30,000 lines per file.
$ ls -laF
total 2783904
drwxr-xr-x 2 user.name group 156 Sep 14 15:43 ./
drwxr-xr-x 3 user.name group 4096 Sep 14 15:39 ../
-rw-r--r-- 1 user.name group 1425352817 Sep 14 14:01 really_big_file.txt
-rw-r--r-- 1 user.name group 428604626 Sep 14 15:43 split_files.txt.00
-rw-r--r-- 1 user.name group 427152423 Sep 14 15:43 split_files.txt.01
-rw-r--r-- 1 user.name group 427141443 Sep 14 15:43 split_files.txt.02
-rw-r--r-- 1 user.name group 142454325 Sep 14 15:43 split_files.txt.03
$ wc -l *.txt*
100000 really_big_file.txt
30000 split_files.txt.00
30000 split_files.txt.01
30000 split_files.txt.02
10000 split_files.txt.03
200000 total
The Background
property expects a Brush
object, not a string. Change the type of the property to Brush
and initialize it thus:
Background = new SolidColorBrush(Colors.Red);
You can use !setup.py install
to do that.
Colab is just like a Jupyter notebook. Therefore, we can use the !
operator here to install any package in Colab. What !
actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a !
preceding the line.
For example: !pip install tensorflow
. This will treat that line (here pip install tensorflow
) as a command prompt line and not some Python code. However, if you do this without adding the !
preceding the line, it'll throw up an error saying "invalid syntax".
But keep in mind that you'll have to upload the setup.py
file to your drive before doing this (preferably into the same folder where your notebook is).
Hope this answers your question :)
I am happy with the listings
package:
Here is how I configure it:
\lstset{
language=C,
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
columns=fullflexible,
showstringspaces=false
}
I use it like this:
\begin{lstlisting}[caption=Caption example.,
label=a_label,
float=t]
// Insert the code here
\end{lstlisting}
tv.setText(Integer.toString(intValue))
Have a look at http://bootboxjs.com/
Very easy to use:
bootbox.confirm("Are you sure?", function(result) {
Example.show("Confirm result: "+result);
});
If the function is not defined when using that function in html, such as onclick = ‘function () ', it means function is in a callback, in my case is 'DOMContentLoaded'.
I initialised the slider with one of the properties as
variableWidth: true
then i could set the width of the slides to anything i wanted in CSS with:
.slick-slide {
width: 200px;
}
You can use the code from this question: How can I save a screenshot directly to a file in Windows?
Just change WIN32_API.GetDesktopWindow()
to the Handle property of the window you want to capture.
I had the solution stored on a network share and every time I opened it I would get the warning about untrusted sources. I moved it to a local drive and the "namespace does not exist" error went away as well.
With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. I made a test with BufferReader.readLine()!=null and it worked properly.
No, you do not need to check whether you’re already on the main thread. By dispatching the block to the main queue, you’re just scheduling the block to be executed serially on the main thread, which happens when the corresponding run loop is run.
If you already are on the main thread, the behaviour is the same: the block is scheduled, and executed when the run loop of the main thread is run.
In my case I was having the same error and later I come to know that the 'condition' is mysql reserved keyword and I used that as field name.
git checkout
has the --ours
option to check out the version of the file that you had locally (as opposed to --theirs
, which is the version that you pulled in). You can pass .
to git checkout
to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add
, and commit your work once done:
git checkout --ours . # checkout our local version of all files
git add -u # mark all conflicted files as merged
git commit # commit the merge
Note the .
in the git checkout
command. That's very important, and easy to miss. git checkout
has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in .
or a filename in order to get the second behavior from git checkout
.
It's also a good habit to have, when passing in a filename, to offset it with --
, such as git checkout --ours -- <filename>
. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout
command.
I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.
The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.
Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD
is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff
).
Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit
if you need to edit it beforehand (for instance, if you rename function foo
to bar
, and someone else adds new code that calls foo
, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).
The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<
, =======
, and >>>>>>>
) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add
before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD
(your side of the merge), and the version from the remote branch.
In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours
or git checkout --theirs
. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add
, and then you can commit the merge with git commit
.
Reload the current document:
<script type="text/javascript">
function reloadPage()
{
window.location.reload()
}
</script>
For me, an IDE is better because it allows faster navigation in code which is important if you have something in your mind to implement. Supposed you do not use an IDE, it takes longer to get to the destination. Your thoughts may be interupted more often. It means more clicks/more keys have to be pressed. One has to concentrate more on the thought how to implement things. Of course, you can write down things too but then one must jump between the design and implementation. Also, a GUI designer makes a big difference. If you do that by hand, it may take longer.
I have faced this problem after upgrading to android studio 3.4 and sdk version to 28.0.0. Applying below dependency solved the problem for me.
implementation 'com.android.support:exifinterface:28.0.0'
How about this ?
ViewModel:
class ViewModel
{
public Action CloseAction { get; set; }
private void Stuff()
{
// Do Stuff
CloseAction(); // closes the window
}
}
In your ViewModel use CloseAction() to close the window just like in the example above.
View:
public View()
{
InitializeComponent();
ViewModel vm = new ViewModel (); // this creates an instance of the ViewModel
this.DataContext = vm; // this sets the newly created ViewModel as the DataContext for the View
if (vm.CloseAction == null)
vm.CloseAction = new Action(() => this.Close());
}
You can combine ID and Class in CSS, but IDs are intended to be unique, so adding a class to a CSS selector would over-qualify it.
You can also use .filter()
$('.slide-link').filter('[data-slide="0"]').addClass('active');
Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).
The command line option
-verbose:gc
causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:[GC 325407K->83000K(776768K), 0.2300771 secs] [GC 325816K->83372K(776768K), 0.2454258 secs] [Full GC 267628K->83769K(776768K), 1.8479984 secs]
Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g.,
325407K->83000K
from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.The next number in parentheses (e.g.,
(776768K)
again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.The last item on the line (e.g.,
0.2300771 secs
) indicates the time taken to perform the collection; in this case approximately a quarter of a second.The format for the major collection in the third line is similar.
The format of the output produced by
-verbose:gc
is subject to change in future releases.
I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?
Usually (in oop at least) you shape your object to behave the way you want. name in USERNAMES
is not case insensitive, so USERNAMES
needs to change:
class NameList(object):
def __init__(self, names):
self.names = names
def __contains__(self, name): # implements `in`
return name.lower() in (n.lower() for n in self.names)
def add(self, name):
self.names.append(name)
# now this works
usernames = NameList(USERNAMES)
print someone in usernames
The great thing about this is that it opens the path for many improvements, without having to change any code outside the class. For example, you could change the self.names
to a set for faster lookups, or compute the (n.lower() for n in self.names)
only once and store it on the class and so on ...
You cannot access elements of an empty vector by subscript.
Always check that the vector is not empty & the index is valid while using the []
operator on std::vector
.
[]
does not add elements if none exists, but it causes an Undefined Behavior if the index is invalid.
You should create a temporary object of your structure, fill it up and then add it to the vector, using vector::push_back()
subject subObj;
subObj.name = s1;
sub.push_back(subObj);
I successfully solved my problem. Here is my code:
The complex JSON object:
{
"medications":[{
"aceInhibitors":[{
"name":"lisinopril",
"strength":"10 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"antianginal":[{
"name":"nitroglycerin",
"strength":"0.4 mg Sublingual Tab",
"dose":"1 tab",
"route":"SL",
"sig":"q15min PRN",
"pillCount":"#30",
"refills":"Refill 1"
}],
"anticoagulants":[{
"name":"warfarin sodium",
"strength":"3 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"betaBlocker":[{
"name":"metoprolol tartrate",
"strength":"25 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"diuretic":[{
"name":"furosemide",
"strength":"40 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"mineral":[{
"name":"potassium chloride ER",
"strength":"10 mEq Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}]
}
],
"labs":[{
"name":"Arterial Blood Gas",
"time":"Today",
"location":"Main Hospital Lab"
},
{
"name":"BMP",
"time":"Today",
"location":"Primary Care Clinic"
},
{
"name":"BNP",
"time":"3 Weeks",
"location":"Primary Care Clinic"
},
{
"name":"BUN",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Cardiac Enzymes",
"time":"Today",
"location":"Primary Care Clinic"
},
{
"name":"CBC",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Creatinine",
"time":"1 Year",
"location":"Main Hospital Lab"
},
{
"name":"Electrolyte Panel",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Glucose",
"time":"1 Year",
"location":"Main Hospital Lab"
},
{
"name":"PT/INR",
"time":"3 Weeks",
"location":"Primary Care Clinic"
},
{
"name":"PTT",
"time":"3 Weeks",
"location":"Coumadin Clinic"
},
{
"name":"TSH",
"time":"1 Year",
"location":"Primary Care Clinic"
}
],
"imaging":[{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
},
{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
},
{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
}
]
}
The jQuery code to grab the data and display it on my webpage:
$(document).ready(function() {
var items = [];
$.getJSON('labOrders.json', function(json) {
$.each(json.medications, function(index, orders) {
$.each(this, function() {
$.each(this, function() {
items.push('<div class="row">'+this.name+"\t"+this.strength+"\t"+this.dose+"\t"+this.route+"\t"+this.sig+"\t"+this.pillCount+"\t"+this.refills+'</div>'+"\n");
});
});
});
$('<div>', {
"class":'loaded',
html:items.join('')
}).appendTo("body");
});
});
Easy way: Use a 3rd sheet to check.
Say you want to find differences between Sheet 1 and Sheet 2.
=IF(Sheet2!A1<>Sheet1!A1,"difference","")
. You could adjust the formula to show the actual values that were different.
think of FINAL as the "End of the line" - that guy cannot produce offspring anymore. So when you see it this way, there are ton of real world scenarios that you will come across that requires you to flag an 'end of line' marker to the class. It is Domain Driven Design - if your domain demands that a given ENTITY (class) cannot create sub-classes, then mark it as FINAL.
I should note that there is nothing stopping you from inheriting a "should be tagged as final" class. But that is generally classified as "abuse of inheritance", and done because most often you would like to inherit some function from the base class in your class.
The best approach is to look at the domain and let it dictate your design decisions.
This may do the trick:
\b\p{L}*Id\b
Where \p{L}
matches any (Unicode) letter and \b
matches a word boundary.
You don't need to override onBackPressed()
- it's already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed()
whenever you want to "programatically press" the back button.
That would only result to finish()
being called, though ;)
I think you're confused with what the back button does. By default, it's just a call to finish()
, so it just exits the current activity. If you have something behind that activity, that screen will show.
What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won't be there when you exit yours.
Reasons of ignoring these argument is permanent generation has been removed in HotSpot for JDK8 because of following drawbacks
The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace. The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error.
Advantages of MetaSpace
Metaspace Tuning
The maximum metaspace size can be set using the -XX:MaxMetaspaceSize flag, and the default is unlimited, which means that only your system memory is the limit. The -XX:MetaspaceSize tuning flag defines the initial size of metaspace If you don’t specify this flag, the Metaspace will dynamically re-size depending of the application demand at runtime.
Change enables other optimizations and features in the future
There is improved GC performace also.
you show fragment in a container (with id= fragmentcontainer) so you remove fragment with:
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer);
fragmentTransaction.remove(fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
SELECT * FROM Tran_LibraryBooksTrans LBT
LEFT JOIN Tran_LibraryIssuedBooks LIB ON
CASE WHEN LBT.IssuedTo='SN' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
WHEN LBT.IssuedTo='SM' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
WHEN LBT.IssuedTo='BO' AND LBT.LIBRARYTRANSID=LIB.LIBRARYTRANSID THEN 1
ELSE 0 END
ids and classes are still attributes, so you can apply a regexp attribute filter to them if you select accordingly. Read more here: http://rosshawkins.net/archive/2011/10/14/jquery-wildcard-selectors-some-simple-examples.aspx
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
Use the global method std::remove with the begin and end iterator, and then use std::vector.erase to actually remove the elements.
Documentation links
std::remove http://www.cppreference.com/cppalgorithm/remove.html
std::vector.erase http://www.cppreference.com/cppvector/erase.html
std::vector<int> v;
v.push_back(1);
v.push_back(2);
//Vector should contain the elements 1, 2
//Find new end iterator
std::vector<int>::iterator newEnd = std::remove(v.begin(), v.end(), 1);
//Erase the "removed" elements.
v.erase(newEnd, v.end());
//Vector should now only contain 2
Thanks to Jim Buck for pointing out my error.
You could just do ...
(.*?)\.txt
a = [1,1,1,2,2,3]
a.slice!(0) # remove first index
a.slice!(-1) # remove last index
# a = [1,1,2,2] as desired
For the event where there are multiple check-boxes from which you'd like to select/deselect only a few, the following work with the Chrome Driver (somehow failed for IE Driver):
NOTE: My check-boxes didn't have an ID associated with them, which would be the best way to identify them according to the Documentation. Note the !
sign at the beginning of the statement.
if(!driver.findElement(By.xpath("//input[@type='checkbox' and @name='<name>']")).isSelected())
{
driver.findElement(By.xpath("//input[@type='checkbox' and @name= '<name>']")).click();
}
Pipe the result to wc
using the -l
(line count) switch:
grep -Rl "curl" ./ | wc -l
The "ternary expression" x ? y : z
can only be used for conditional assignment. That is, you could do something like:
String mood = inProfit() ? "happy" : "sad";
because the ternary expression is returning something (of type String
in this example).
It's not really meant to be used as a short, in-line if-else
. In particular, you can't use it if the individual parts don't return a value, or return values of incompatible types. (So while you could do this if both method happened to return the same value, you shouldn't invoke it for the side-effect purposes only).
So the proper way to do this would just be with an if-else block:
if (jXPanel6.isVisible()) {
jXPanel6.setVisible(true);
}
else {
jXPanel6.setVisible(false);
}
which of course can be shortened to
jXPanel6.setVisible(jXPanel6.isVisible());
Both of those latter expressions are, for me, more readable in that they more clearly communicate what it is you're trying to do. (And by the way, did you get your conditions the wrong way round? It looks like this is a no-op anyway, rather than a toggle).
Don't mix up low character count with readability. The key point is what is most easily understood; and mildly misusing language features is a definite way to confuse readers, or at least make them do a mental double-take.
There are standard statistical functions and methods for finding outliers to data, which is probably what you need in the first case. Using derivatives would solve your second. I'm not sure for a method which solves both continuous functions and sampled data, however.
In short, it is all built-in data types (e.g. int
, char
, float
, long
, unsigned char
, double
, etc.) and all aggregation of POD data. Yes, it's a recursive definition. ;)
To be more clear, a POD is what we call "a struct": a unit or a group of units that just store data.
If you just want to change the color, change the variable (recommended):
@input-border-focus: red;
$input-border-focus: red;
If you wan't to remove it completely, you'll have to overwrite the Mixin that sets the outline.
.form-control-focus(@color: @input-border-focus) {}
If you are using css overwrite it via:
.form-control:focus{
border-color: #cccccc;
-webkit-box-shadow: none;
box-shadow: none;
}
This will get the file path from the MediaProvider, DownloadsProvider, and ExternalStorageProvider, while falling back to the unofficial ContentProvider method you mention.
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
These are taken from my open source library, aFileChooser.
With Excel 2007 on Windows, I found these steps simplest;
You can do the same thing with the connection opened just once. Something like this.
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
string StrQuery= @"INSERT INTO tableName VALUES (" + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";
try
{
SqlConnection conn = new SqlConnection();
conn.Open();
using (SqlCommand comm = new SqlCommand(StrQuery, conn))
{
comm.ExecuteNonQuery();
}
conn.Close();
}
Also, depending on your specific scenario you may want to look into binding the grid to the database. That would reduce the amount of manual work greatly: http://www.switchonthecode.com/tutorials/csharp-tutorial-binding-a-datagridview-to-a-database
Why not just wrap an anchor tag around a button element.
<a href="somepage.html"><button type="button">Text of Some Page</button></a>
This will work for IE9+, Chrome, Safari, Firefox, and probably Opera.
Provide the directory on the command line:
svn checkout file:///home/landonwinters/svn/waterproject/trunk public_html
Add the following inside the end of the try/catch to avoid the error that appears when the JSP engine flushes the response via getWriter()
out.clear(); // where out is a JspWriter
out = pageContext.pushBody();
As has been noted, this isn't best practice, but it avoids the errors in your logs.
If you want to get full screen without actionBar and Title.
Add it in style.xml
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
and use the style at manifest.xml.
android:theme="@style/AppTheme.NoActionBar"
Microsoft .NET framework 3.5 can be installed on windows 10 without having installation media. The file you need is called microsoft-windows-netfx3-ondemand-package.cab
. Just google it and you will get the download links.
After downloading it, copy that file to C:\dotnet35
and run the following command.
Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess
Tested and worked in Windows 10 without any issue.
The map() function is a best choice for this case
tl;dr - Do this:
const newArr = [
{name: 'eve'},
{name: 'john'},
{name: 'jane'}
].map(v => ({...v, isActive: true}))
The map() function won't modify the initial array, but creates a new one. This is also a good practice to keep initial array unmodified.
Alternatives:
const initialArr = [
{name: 'eve'},
{name: 'john'},
{name: 'jane'}
]
const newArr1 = initialArr.map(v => ({...v, isActive: true}))
const newArr2 = initialArr.map(v => Object.assign(v, {isActive: true}))
// Results of newArr1 and newArr2 are the same
Add a key value pair conditionally
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr1 = arr.map(v => ({...v, isActive: v.value > 1}))
What if I don't want to add new field at all if the condition is false?
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr = arr.map(v => {
return v.value > 1 ? {...v, isActive: true} : v
})
Adding WITH modification of the initial array
const initialArr = [{a: 1}, {b: 2}]
initialArr.forEach(v => {v.isActive = true;});
This is probably not a best idea, but in a real life sometimes it's the only way.
Questions
...
), or Object.assign
and what's the difference?Personally I prefer to use spread operator, because I think it uses much wider in modern web community (especially react's developers love it). But you can check the difference yourself: link(a bit opinionated and old, but still)
function
keyword instead of =>
?Sure you can. The fat arrow (=>
) functions play a bit different with this
, but it's not so important for this particular case. But fat arrows function shorter and sometimes plays better as a callbacks. Therefore the usage of fat arrow functions is more modern approach.
.map(v => ({...v, isActive: true})
?Map function iterates by array's elements and apply callback function for each of them. That callback function should return something that will become an element of a new array.
We tell to the .map()
function following: take current value(v
which is an object), take all key-value pairs away from v
andput it inside a new object({...v}
), but also add property isActive
and set it to true ({...v, isActive: true}
) and then return the result. Btw, if original object contains isActive
filed it will be overwritten. Object.assign
works in a similar way.
Yes.
[{value: 1}, {value: 1}, {value: 2}].map(v => ({...v, isActive: true, howAreYou: 'good'}))
.map()
methodYou shouldn't do any side effects[link 1, link 2], but apparently you can.
Also be noticed that map()
iterates over each element of the array and apply function for each of them. So if you do some heavy stuff inside, you might be slow. This (a bit hacky) solution might be more productive in some cases (but I don't think you should apply it more then once in a lifetime).
Sure you can.
const arr = [{value: 1}, {value: 1}, {value: 2}]
const newArr = arr.map(addIsActive)
function addIsActive(v) {
return {...v, isActive: true}
}
Nothing is wrong with for
, you can still use it, it's just an old-school approach which is more verbose, less safe and mutate the initial array. But you can try:
const arr = [{a: 1}, {b: 2}]
for (let i = 0; i < arr.length; i++) {
arr[i].isActive = true
}
It would be smart to learn well following methods map(), filter(), reduce(), forEach(), and find(). These methods can solve 80% of what you usually want to do with arrays.
Use the fact that a data.frame
is a list of columns, then use do.call
to recreate a data.frame
.
do.call(data.frame,lapply(DT, function(x) replace(x, is.infinite(x),NA)))
data.table
You could use data.table
and set
. This avoids some internal copying.
DT <- data.table(dat)
invisible(lapply(names(DT),function(.name) set(DT, which(is.infinite(DT[[.name]])), j = .name,value =NA)))
Or using column numbers (possibly faster if there are a lot of columns):
for (j in 1:ncol(DT)) set(DT, which(is.infinite(DT[[j]])), j, NA)
# some `big(ish)` data
dat <- data.frame(a = rep(c(1,Inf), 1e6), b = rep(c(Inf,2), 1e6),
c = rep(c('a','b'),1e6),d = rep(c(1,Inf), 1e6),
e = rep(c(Inf,2), 1e6))
# create data.table
library(data.table)
DT <- data.table(dat)
# replace (@mnel)
system.time(na_dat <- do.call(data.frame,lapply(dat, function(x) replace(x, is.infinite(x),NA))))
## user system elapsed
# 0.52 0.01 0.53
# is.na (@dwin)
system.time(is.na(dat) <- sapply(dat, is.infinite))
# user system elapsed
# 32.96 0.07 33.12
# modified is.na
system.time(is.na(dat) <- do.call(cbind,lapply(dat, is.infinite)))
# user system elapsed
# 1.22 0.38 1.60
# data.table (@mnel)
system.time(invisible(lapply(names(DT),function(.name) set(DT, which(is.infinite(DT[[.name]])), j = .name,value =NA))))
# user system elapsed
# 0.29 0.02 0.31
data.table
is the quickest. Using sapply
slows things down noticeably.
After not finding anything to get around "Object must implement IConvertible" exception when using Zyphrax's answer (except for implementing the interface).. I tried something a little bit unconventional and worked for my situation.
Using the Newtonsoft.Json nuget package...
var castedObject = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(myObject), myType);
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
.zip application/zip, application/octet-stream
The u in u'Some String'
means that your string is a Unicode string.
Q: I'm in a terrible, awful hurry and I landed here from Google Search. I'm trying to write this data to a file, I'm getting an error, and I need the dead simplest, probably flawed, solution this second.
A: You should really read Joel's Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) essay on character sets.
Q: sry no time code pls
A: Fine. try str('Some String')
or 'Some String'.encode('ascii', 'ignore')
. But you should really read some of the answers and discussion on Converting a Unicode string and this excellent, excellent, primer on character encoding.
You can select the shapes within a slide (Word Art also) and right click on the selection and choose "Save As Picture". It will save as a transparent PNG.
I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.
Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")
'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
'Select Range
sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
End Sub
If what you're looking for is a way to append a vector to another after creation, vector::insert
is your best bet, as has been answered several times, for example:
vector<int> first = {13};
const vector<int> second = {42};
first.insert(first.end(), second.cbegin(), second.cend());
Sadly there's no way to construct a const vector<int>
, as above you must construct and then insert
.
If what you're actually looking for is a container to hold the concatenation of these two vector<int>
s, there may be something better available to you, if:
vector
contains primitivesconst
containerIf the above are all true, I'd suggest using the basic_string
who's char_type
matches the size of the primitive contained in your vector
. You should include a static_assert
in your code to validate these sizes stay consistent:
static_assert(sizeof(char32_t) == sizeof(int));
With this holding true you can just do:
const u32string concatenation = u32string(first.cbegin(), first.cend()) + u32string(second.cbegin(), second.cend());
For more information on the differences between string
and vector
you can look here: https://stackoverflow.com/a/35558008/2642059
For a live example of this code you can look here: http://ideone.com/7Iww3I
Remove the unwanted , sign in the function. you will get the solution.
Refer this
http://blog.favrik.com/2007/11/29/ie7-error-expected-identifier-string-or-number/
To remove the special characters, try
var name = name.replace(/[!@#$%^&*]/g, "");
Combining above answer with ability to click again and again without clicking outside iframe.
var eventListener = window.addEventListener('blur', function() {
if (document.activeElement === document.getElementById('contentIFrame')) {
toFunction(); //function you want to call on click
setTimeout(function(){ window.focus(); }, 0);
}
window.removeEventListener('blur', eventListener );
});
Where, I solved this problem by adding the visibility attribute to the CSS code, it works on my website
Original code:
#zo2-body-wrap .introText .images:before_x000D_
{_x000D_
background:rgba(136,136,136,0.7);_x000D_
width:100%;_x000D_
height:100%;_x000D_
content:"";_x000D_
position:absolute;_x000D_
top:0;_x000D_
opacity:0;_x000D_
transition:all 0.2s ease-in-out 0s;_x000D_
}
_x000D_
Fixed iOS touch code:
#zo2-body-wrap .introText .images:before_x000D_
{_x000D_
background:rgba(136,136,136,0.7);_x000D_
width:100%;_x000D_
height:100%;_x000D_
content:"";_x000D_
position:absolute;_x000D_
top:0;_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:all 0.2s ease-in-out 0s;_x000D_
}
_x000D_
You can use this function to disable the form:
function disableForm(formID){
$('#' + formID).children(':input').attr('disabled', 'disabled');
}
Note that it uses jQuery.
You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM
. Then simply type where it says TYPE
: what you want to say in QUOTES.
Example.. "OTHER"
Table cells don't respect margin, but you could use transparent borders instead:
div {
display: table-cell;
border: 5px solid transparent;
}
Note: you can't use percentages here... :(
An unhandled exception will (assuming it's repeatable like bad data as opposed to read errors from a particular data node) eventually fail the job anyway.
You can configure the maximum number of times a particular map or reduce task can fail before the entire job fails through the following properties:
mapred.map.max.attempts
- The maximum number of attempts per map task. In other words, framework will try to execute a map task these many number of times before giving up on it.mapred.reduce.max.attempts
- Same as above, but for reduce tasksIf you want to fail the job out at the first failure, set this value from its default of 4 to 1.
I never remember the openssl
command needed to create a .pem
file, so I made this bash script to simplify the process:
#!/bin/bash
if [ $# -eq 2 ]
then
echo "Signing $1..."
if ! openssl pkcs12 -in $1 -out $2 -nodes -clcerts; then
echo "Error signing certificate."
else
echo "Certificate created successfully: $2"
fi
else
if [ $# -gt 2 ]
then
echo "Too many arguments"
echo "Syntax: $0 <input.p12> <output.pem>"
else
echo "Missing arguments"
echo "Syntax: $0 <input.p12> <output.pem>"
fi
fi
Name it, for example, signpem.sh
and save it on your user's folder (/Users/<username>
?). After creating the file, do a chmod +x signpem.sh
to make it executable and then you can run:
~/signpem myCertificate.p12 myCertificate.pem
And myCertificate.pem
will be created.
The main differnece is when you say ClassName obj = null; you are just creating an object for that class. It's not an instance of that class.
This statement will just allot memory for the static meber variables, not for the normal member variables.
But when you say ClassName obj = new ClassName(); you are creating an instance of the class. This staement will allot memory all member variables.
I've installed and use VB6 for legacy projects many times on Windows 7.
What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.
Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721
Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm
String info = "Hello \"world\"!";
info = info.replace("\"", "\\\"");
String info1 = "Hello "world!";
info1 = info1.replace('"', '\"').replace("\"", "\\\"");
For the 2nd field info1, 1st replace double quotes with an escape character.
I got it resolved by doing Repir on .NET framework Extended, in Add/Remove program ;
Using win2008R2, .NET framework 4.0
Luckily, Python has this built-in :)
import re
re.split('; |, ',str)
Update:
Following your comment:
>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']
Here is my Extension method. It's very efficient and it's lazy.
Usage:
var checkBoxes = tableLayoutPanel1.FindChildControlsOfType<CheckBox>();
foreach (var checkBox in checkBoxes)
{
checkBox.Checked = false;
}
The code is:
public static IEnumerable<TControl> FindChildControlsOfType<TControl>(this Control control) where TControl : Control
{
foreach (var childControl in control.Controls.Cast<Control>())
{
if (childControl.GetType() == typeof(TControl))
{
yield return (TControl)childControl;
}
else
{
foreach (var next in FindChildControlsOfType<TControl>(childControl))
{
yield return next;
}
}
}
}
I just added the oracle folder to my environmental variables and that fixed my identical error
I am currently running OS X Yosemite Developer Preview 7 and Xcode 6 beta 6 targeting iOS 7.1 and following solution works fine for me:
UINavigationItem
and UIBarButtonItem
sRun following code to remove
[self.navItem setRightBarButtonItem:nil];
[self.navItem setLeftBarButtonItem:nil];
Run following codes to add buttons again
[self.navItem setRightBarButtonItem:deleteItem];
[self.navItem setLeftBarButtonItem:addItem];
MVC5 with delete dialogue & glyphicon. May work previous versions.
@Html.Raw(HttpUtility.HtmlDecode(@Html.ActionLink(" ", "Action", "Controller", new { id = model.id }, new { @class = "glyphicon glyphicon-trash", @OnClick = "return confirm('Are you sure you to delete this Record?');" }).ToHtmlString()))
Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus
X = primes(20);
ismember([15 17],X)
ans =
0 1
Since 15 is not prime, but 17 is, ismember has done its job well here.
Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.
~isempty(find(X == 15))
~isempty(find(X == 17))
or,
any(X == 15)
any(X == 17)
Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.
tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)
The -HideTableHeaders
parameter unfortunately still causes the empty lines to be printed (and table headers appearently are still considered for column width). The only way I know that could reliably work here would be to format the output yourself:
| % { '{0,10} {1,20} {2,20}' -f $_.Operation,$_.AttributeName,$_.AttributeValue }
I'm going to take a guess. I think the column name that contains "Number"
is something like " Number"
or "Number "
. Notice that I'm assuming you might have a residual space in the column name somewhere. Do me a favor and run print "<{}>".format(data.columns[1])
and see what you get. Is it something like < Number>
? If so, then my guess was correct. You should be able to fix it with this:
data.columns = data.columns.str.strip()
A key difference between __getattr__
and __getattribute__
is that __getattr__
is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want.
__getattribute__
is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.
New-style classes derive from object
, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__
and __getattribute__
.
You almost certainly want __getattr__
.
curl -u <username>:<password> https://$your_registry/v2/$image_name/tags/list -s -o - | \
tr -d '{' | tr -d '}' | sed -e 's/[][]//g' -e 's/"//g' -e 's/ //g' | \
awk -F: '{print $3}' | sed -e 's/,/\n/g'
You can use it if your env has no 'jq', = )
To check OleDbConnection State use this:
if (oconn.State == ConnectionState.Open)
{
oconn.Close();
}
State
return the ConnectionState
public override ConnectionState State { get; }
Here are the other ConnectionState
enum
public enum ConnectionState
{
//
// Summary:
// The connection is closed.
Closed = 0,
//
// Summary:
// The connection is open.
Open = 1,
//
// Summary:
// The connection object is connecting to the data source. (This value is reserved
// for future versions of the product.)
Connecting = 2,
//
// Summary:
// The connection object is executing a command. (This value is reserved for future
// versions of the product.)
Executing = 4,
//
// Summary:
// The connection object is retrieving data. (This value is reserved for future
// versions of the product.)
Fetching = 8,
//
// Summary:
// The connection to the data source is broken. This can occur only after the connection
// has been opened. A connection in this state may be closed and then re-opened.
// (This value is reserved for future versions of the product.)
Broken = 16
}
Postgresql does not have an equivalent of Oracle's ROWNUM. In many cases you can achieve the same result by using LIMIT and OFFSET in your query.
tip 1: clean & then rebuild.
tip 2: just close VS and open again.
tip 3: the downloaded project may be inside another sub folder... open the folder which has you .net files.
c:/demo1/demo/ (all files)
You should have to open demo from vs... not demo1.
The params object is included in $stateParams, but won't be part of the url.
1) In the route configuration:
$stateProvider.state('edit_user', {
url: '/users/:user_id/edit',
templateUrl: 'views/editUser.html',
controller: 'editUserCtrl',
params: {
paramOne: { objectProperty: "defaultValueOne" }, //default value
paramTwo: "defaultValueTwo"
}
});
2) In the controller:
.controller('editUserCtrl', function ($stateParams, $scope) {
$scope.paramOne = $stateParams.paramOne;
$scope.paramTwo = $stateParams.paramTwo;
});
3A) Changing the State from a controller
$state.go("edit_user", {
user_id: 1,
paramOne: { objectProperty: "test_not_default1" },
paramTwo: "from controller"
});
3B) Changing the State in html
<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>
I think it's worth answering the generic question "R - test if string contains string" here.
For that, use the grep function.
# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"
Sometimes this error occurs for old javascript sdk. If you save locally javascript file. Update it. I prefer to load it form the facebook server all the time.
Ref parameters aren't required to be set in the function, whereas out parameters must be bound to a value before exiting the function. Variables passed as out may also be passed to a function without being initialized.
C didn't use to have consts, so #defines were the only way of providing constant values. Both C and C++ do have them now, so there is no point in using them, except when they are going to be tested with #ifdef/ifndef.
See following snippet :
$(document).on("click", "a.deleteText", function() {_x000D_
if (confirm('Are you sure ?')) {_x000D_
$(this).prev('span.text').remove();_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
<span class="text">some text</span>_x000D_
<a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
2>LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc120-mt-sgd-1_55.lib
In my case, bootstrap/bjam was not available (libraries were precompiled and committed to SCM) on old inherited project. Libraries did not have VC or BOOST versioning in their filenames eg: libboost_regex-mt-sgd.lib
, however Processed /DEFAULTLIB:libboost_regex-vc120-mt-sgd-1_55.lib
was somehow triggered automatically.
Fixed by manually adding the non-versioned filename to:
<AdditionalDependencies>$(DK_BOOST)\lib64\libboost_regex-mt-sgd.lib</AdditionalDependencies>
and blacklisting the ...vc120-mt-sgd-1_55.lib
in
<IgnoreSpecificDefaultLibraries>libboost_regex-vc120-mt-sgd-1_55.lib</IgnoreSpecificDefaultLibraries>
String[] errorSoon = { "foo", "bar" };
-- or --
String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";
You can use Will Dean's suggestion [
#define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))
] to replace the magic number 3 here with arraysize(str_array) -- although I remember there being some special case in which that particular version of arraysize might do Something Bad (sorry I can't remember the details immediately). But it very often works correctly.
The case where it doesn't work is when the "array" is really just a pointer, not an actual array. Also, because of the way arrays are passed to functions (converted to a pointer to the first element), it doesn't work across function calls even if the signature looks like an array — some_function(string parameter[])
is really some_function(string *parameter)
.
<a href="#myAnchorALongWayDownThePage">Click here to scroll</a>
<A name='myAnchorALongWayDownThePage"></a>
No fancy scrolling but it should take you there.
This should do the trick:
$("#btnAddProfile").prop('value', 'Save');
$("#btnAddProfile").button('refresh');
@reannual's answer works well, but there's an issue with it: os.popen
is now deprecated. The subprocess
module should be used instead, so here's a version of @reannual's code that uses subprocess
and directly answers the question (by giving the column width directly as an int
:
import subprocess
columns = int(subprocess.check_output(['stty', 'size']).split()[1])
Tested on OS X 10.9
Also remember one thing. Very important
You have to specify the command something like this to be more precise
grep -l "pattern" *
If you want to remove the entire row from DataTable ,
try this
DataTable dt = new DataTable(); //User DataTable
DataRow[] rows;
rows = dt.Select("Student=' " + id + " ' ");
foreach (DataRow row in rows)
dt.Rows.Remove(row);
Well $.each
is a library construct, whereas for ... in
is native js, which should be better
One of many solutions is to create an @Injectable()
class which holds data that you want to show in the header. Other components can also access this class and alter this data, effectively changing the header.
Another option is to set up @Input()
variables and @Output()
EventEmitters which you can use to alter the header data.
Edit Examples as you requested:
@Injectable()
export class HeaderService {
private _data;
set data(value) {
this._data = value;
}
get data() {
return this._data;
}
}
in other component:
constructor(private headerService: HeaderService) {}
// Somewhere
this.headerService.data = 'abc';
in header component:
let headerData;
constructor(private headerService: HeaderService) {
this.headerData = this.headerService.data;
}
I haven't actually tried this. If the get/set doesn't work you can change it to use a Subject();
// Simple Subject() example:
let subject = new Subject();
this.subject.subscribe(response => {
console.log(response); // Logs 'hello'
});
this.subject.next('hello');
If you have control over running the cscript executable then run the X:\windows\syswow64\cscript.exe
version which is the 32bit implementation.
For linux/unix, I can suggest unix package.
To increase the memory limit in linux:
install.packages("unix")
library(unix)
rlimit_as(1e12) #increases to ~12GB
You can also check the memory with this:
rlimit_all()
for detailed information: https://rdrr.io/cran/unix/man/rlimit.html
also you can find further info here: limiting memory usage in R under linux
If you have a mixture of formats in your date, don't forget to set infer_datetime_format=True
to make life easier.
df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)
Source: pd.to_datetime
or if you want a customized approach:
def autoconvert_datetime(value):
formats = ['%m/%d/%Y', '%m-%d-%y'] # formats to try
result_format = '%d-%m-%Y' # output format
for dt_format in formats:
try:
dt_obj = datetime.strptime(value, dt_format)
return dt_obj.strftime(result_format)
except Exception as e: # throws exception when format doesn't match
pass
return value # let it be if it doesn't match
df['date'] = df['date'].apply(autoconvert_datetime)
I make a little update on this issue, as I just had the same error today on an application which is linking against a static lib, after I migrated the old Visual 6 project to Visual Studio 2012.
In my case the error was that I mistakenly compiled the Release version of the static lib with /MDd instead of /MD, whereas the application is /MD in release. Setting the correct /MD in the static lib project solved the issue.
This is done in Project properties
console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.
It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.
To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.
put your javascript at the bottom of the page (ie after the element getting defined..)
If you use MIUI ROM
Go to the developer option and in that disable MIUI optimization.You will be asked to reboot your phone. Reboot it and then run the app.
Basically, the problem lies in block12. for the block1/2 to take up the total height of the block12, it must have a defined height. This stack overflow post explains that in really good detail.
So setting a defined height for block12 will allow you to set a proper height. I have created an example on JSfiddle that will show you the the blocks can be floated next to one another if the block12 div is set to a standard height through out the page.
Here is an example including a header and block3 div with some content in for examples.
#header{
position:absolute;
top:0;
left:0;
width:100%;
height:20%;
}
#block12{
position:absolute;
top:20%;
width:100%;
left:0;
height:40%;
}
#block1,#block2{
float:left;
overflow-y: scroll;
text-align:center;
color:red;
width:50%;
height:100%;
}
#clear{clear:both;}
#block3{
position:absolute;
bottom:0;
color:blue;
height:40%;
}
GitHub has a new option relative to the preceding answers, just copy/paste the command lines from the PR:
Merge
or Squash and merge
buttonview command line instructions
UPDATED with latest official NuGet documentation as of v3.3.0
NuGet offers three approaches to using package restore.
Automatic Package Restore is the NuGet team's recommended approach to Package Restore within Visual Studio, and it was introduced in NuGet 2.7. Beginning with NuGet 2.7, the NuGet Visual Studio extension integrates into Visual Studio's build events and restores missing packages when a build begins. This feature is enabled by default, but developers can opt out if desired.
Here's how it works:
- On project or solution build, Visual Studio raises an event that a build is beginning within the solution.
- NuGet responds to this event and checks for packages.config files included in the solution.
- For each packages.config file found, its packages are enumerated and Checked for exists in the solution's packages folder.
- Any missing packages are downloaded from the user's configured (and enabled) package sources, respecting the order of the package sources.
- As packages are downloaded, they are unzipped into the solution's packages folder.
If you have Nuget 2.7+ installed; it's important to pick one method for > managing Automatic Package Restore in Visual Studio.
Two methods are available:
- (Nuget 2.7+): Visual Studio -> Tools -> Package Manager -> Package Manager Settings -> Enable Automatic Package Restore
- (Nuget 2.6 and below) Right clicking on a solution and clicking "Enable Package Restore for this solution".
Command-Line Package Restore is required when building a solution from the command-line; it was introduced in early versions of NuGet, but was improved in NuGet 2.7.
nuget.exe restore contoso.sln
The MSBuild-integrated package restore approach is the original Package Restore implementation and though it continues to work in many scenarios, it does not cover the full set of scenarios addressed by the other two approaches.
It fires. Check demo http://jsfiddle.net/yeyene/kbAk3/
$("#inline_content input[name='type']").click(function(){
alert('You clicked radio!');
if($('input:radio[name=type]:checked').val() == "walk_in"){
alert($('input:radio[name=type]:checked').val());
//$('#select-table > .roomNumber').attr('enabled',false);
}
});
Move to front by transform:TranslateZ
Warning: Only works in FireFox
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160" style="width:160px; height:160px;">
<g style="transform-style: preserve-3d;">
<g id="one" style="transform-style: preserve-3d;">
<circle fill="green" cx="100" cy="105" r="20" style="transform:TranslateZ(1px);"></circle>
</g>
<g id="two" style="transform-style: preserve-3d;">
<circle fill="orange" cx="100" cy="95" r="20"></circle>
</g>
</g>
</svg>
_x000D_
Simply use
JSON.stringify(obj)
Example
var args_string = JSON.stringify(obj);
console.log(args_string);
Or
alert(args_string);
Also, note in javascript functions are considered as objects.
As an extra note :
Actually you can assign new property like this and access it console.log or display it in alert
foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);
Type "^". And get a good "Vi" tutorial :)
You can make use of ArrayList. Array has the fixed number of size.
This Example here can help you. The example is pretty easy with its output.
Output: 2 5 1 23 14
New length: 20
Element at Index 5:29
List size: 6
Removing element at index 2: 1
2 5 23 14 29
Same as the answer from 'Richie' but a bit more concise.
Query for user constraints only
SELECT column_name FROM all_cons_columns WHERE constraint_name = (
SELECT constraint_name FROM user_constraints
WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
);
Query for all constraints
SELECT column_name FROM all_cons_columns WHERE constraint_name = (
SELECT constraint_name FROM all_constraints
WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
);
To get the content of a directory you can use
$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"
Then you can loop over this variable as well:
for ($i=0; $i -lt $files.Count; $i++) {
$outfile = $files[$i].FullName + "out"
Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
An even easier way to put this is the foreach
loop (thanks to @Soapy and @MarkSchultheiss):
foreach ($f in $files){
$outfile = $f.FullName + "out"
Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}
Could they make it any harder? Here's what I did: open system properties, click on advanced, add the environment variable, shut down visual studio and start it up again.
Adapting from https://stackoverflow.com/a/49428678/1527469 (to add indexes):
System.out.print(" ");
for (int row = 0; row < array[0].length; row++) {
System.out.print("\t" + row );
}
System.out.println();
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
if (col < 1) {
System.out.print(row);
System.out.print("\t" + array[row][col]);
} else {
System.out.print("\t" + array[row][col]);
}
}
System.out.println();
}
Along with Python 2.7 and 3.3, Red Hat Software Collections now includes Python 3.4 - all work on both RHEL 6 and 7.
RHSCL 2.0 docs are at https://access.redhat.com/documentation/en-US/Red_Hat_Software_Collections/
Plus lot of articles at developerblog.redhat.com.
edit
# 1. Install the Software Collections tools:
yum install scl-utils
# 2. Download a package with repository for your system.
# (See the Yum Repositories on external link. For RHEL/CentOS 6:)
wget https://www.softwarecollections.org/en/scls/rhscl/rh-python34/epel-6-x86_64/download/rhscl-rh-python34-epel-6-x86_64.noarch.rpm
# or for RHEL/CentOS 7
wget https://www.softwarecollections.org/en/scls/rhscl/rh-python34/epel-7-x86_64/download/rhscl-rh-python34-epel-7-x86_64.noarch.rpm
# 3. Install the repo package (on RHEL you will need to enable optional channel first):
yum install rhscl-rh-python34-*.noarch.rpm
# 4. Install the collection:
yum install rh-python34
# 5. Start using software collections:
scl enable rh-python34 bash
First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true");
urlString.append("&key=YOUR_API_KEY");
return urlString.toString();
}
This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
This parser will return us string. We will call it like that.
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
Now we will send this string to our drawpath function. The drawpath function is
public void drawPath(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
/*
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE).geodesic(true));
}
*/
}
catch (JSONException e) {
}
}
Above code will draw the path on mMap. The code of decodePoly is
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass){
url = urlPass;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
drawPath(result);
}
}
}
I hope it will help.
from __future__ import with_statement
with open('file.txt','r+') as f:
counter = str(int(f.read().strip())+1)
f.seek(0)
f.write(counter)
Reference Spring Boot's TestRestTemplate
implementation as follows:
Especially, see the addAuthentication() method as follows:
private void addAuthentication(String username, String password) {
if (username == null) {
return;
}
List<ClientHttpRequestInterceptor> interceptors = Collections
.<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
username, password));
setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
interceptors));
}
Similarly, you can make your own RestTemplate
easily
by inheritance like TestRestTemplate
as follows:
your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?
I have a same problem looking 2 hours ,is very simple to we check our server configuration first.
Example:
echo $upload_max_size = ini_get('upload_max_filesize');
echo $post_max_size=ini_get('post_max_size');
any type of file size is :20mb
, but our upload_max_size
is above 20mb
but array is null
. Answer is our post_max_size
should be greater than upload_max_filesize
post_max_size = 750M
upload_max_filesize = 750M
Use
$(document).on("click", "#btn_a", function(){
alert ('button clicked');
});
to add the listener for the dynamically created button.
alert($("#btn_a").val());
will give you the value of the button
When you create and send a prepared statement to the DBMS, it's stored as the SQL query for execution.
You later bind your data to the query such that the DBMS uses that data as the query parameters for execution (parameterization). The DBMS doesn't use the data you bind as a supplemental to the already compiled SQL query; it's simply the data.
This means it's fundamentally impossible to perform SQL injection using prepared statements. The very nature of prepared statements and their relationship with the DBMS prevents this.
This is not so easy because basically popups are not supported in windows forms. Although windows forms is based on win32 and in win32 popup are supported. If you accept a few tricks, following code will set you going with a popup. You decide if you want to put it to good use :
class PopupWindow : Control
{
private const int WM_ACTIVATE = 0x0006;
private const int WM_MOUSEACTIVATE = 0x0021;
private Control ownerControl;
public PopupWindow(Control ownerControl)
:base()
{
this.ownerControl = ownerControl;
base.SetTopLevel(true);
}
public Control OwnerControl
{
get
{
return (this.ownerControl as Control);
}
set
{
this.ownerControl = value;
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.Style = WindowStyles.WS_POPUP |
WindowStyles.WS_VISIBLE |
WindowStyles.WS_CLIPSIBLINGS |
WindowStyles.WS_CLIPCHILDREN |
WindowStyles.WS_MAXIMIZEBOX |
WindowStyles.WS_BORDER;
createParams.ExStyle = WindowsExtendedStyles.WS_EX_LEFT |
WindowsExtendedStyles.WS_EX_LTRREADING |
WindowsExtendedStyles.WS_EX_RIGHTSCROLLBAR |
WindowsExtendedStyles.WS_EX_TOPMOST;
createParams.Parent = (this.ownerControl != null) ? this.ownerControl.Handle : IntPtr.Zero;
return createParams;
}
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr SetActiveWindow(HandleRef hWnd);
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_ACTIVATE:
{
if ((int)m.WParam == 1)
{
//window is being activated
if (ownerControl != null)
{
SetActiveWindow(new HandleRef(this, ownerControl.FindForm().Handle));
}
}
break;
}
case WM_MOUSEACTIVATE:
{
m.Result = new IntPtr(MouseActivate.MA_NOACTIVATE);
return;
//break;
}
}
base.WndProc(ref m);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.FillRectangle(SystemBrushes.Info, 0, 0, Width, Height);
e.Graphics.DrawString((ownerControl as VerticalDateScrollBar).FirstVisibleDate.ToLongDateString(), this.Font, SystemBrushes.InfoText, 2, 2);
}
}
Experiment with it a bit, you have to play around with its position and its size. Use it wrong and nothing shows.
As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.
This is some pseudocodish JavaScript:
Client:
var websocket = new WebSocket("server address");
websocket.onmessage = function(str) {
console.log("Someone sent: ", str);
};
// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
id: "client1"
}));
// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
to: "client2",
data: "foo"
}));
Server:
var clients = {};
server.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});
If you go to your android-sdk/tools
folder I think you'll find a message :
The adb tool has moved to platform-tools/
If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"
Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.
So you should also add C:/android-sdk/platform-tools
to you environment path. Also after you modify the PATH
variable make sure that you start a new CommandPrompt
window.
I would prefer to make a function that doesn't work with strings:
'---------------------------------------------------------------------------------------
' Procedure : RemoveTimeFromDate
' Author : berend.nieuwhof
' Date : 15-8-2013
' Purpose : removes the time part of a String and returns the date as a date
'---------------------------------------------------------------------------------------
'
Public Function RemoveTimeFromDate(DateTime As Date) As Date
Dim dblNumber As Double
RemoveTimeFromDate = CDate(Floor(CDbl(DateTime)))
End Function
Private Function Floor(ByVal x As Double, Optional ByVal Factor As Double = 1) As Double
Floor = Int(x / Factor) * Factor
End Function
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
CSRF protection
TYPES OF CSRF USAGE
IN FORM
<form>
@csrf
</form>
or
<input type="hidden" name="token" value="{{ form_token() }}" />
META TAG
<meta name="csrf-token" content="{{ csrf_token() }}">
AJAX
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
SESSION
use Illuminate\Http\Request;
Route::get('/token', function (Request $request) {
$token = $request->session()->token();
$token = csrf_token();
// ...
});
MIDDLEWARE
App\Providers\RouteServiceProvider
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
];
}
Yes, you should think of defining both your functions in a Class, and making word a member. This is cleaner :
class Spam:
def oneFunction(self,lists):
category=random.choice(list(lists.keys()))
self.word=random.choice(lists[category])
def anotherFunction(self):
for letter in self.word:
print("_", end=" ")
Once you make a Class you have to Instantiate it to an Object and access the member functions
s = Spam()
s.oneFunction(lists)
s.anotherFunction()
Another approach would be to make oneFunction
return the word so that you can use oneFunction
instead of word
in anotherFunction
>>> def oneFunction(lists):
category=random.choice(list(lists.keys()))
return random.choice(lists[category])
>>> def anotherFunction():
for letter in oneFunction(lists):
print("_", end=" ")
And finally, you can also make anotherFunction
, accept word
as a parameter which you can pass from the result of calling oneFunction
>>> def anotherFunction(words):
for letter in words:
print("_",end=" ")
>>> anotherFunction(oneFunction(lists))
Use bellow command from CLI interface
[root@localhost~]# mysqladmin variables -p<password> | grep datadir
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
This is good for taking multiple line input
import java.util.Scanner;
public class JavaApp {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String line;
while(true){
line = scanner.nextLine();
System.out.println(line);
if(line.equals("")){
break;
}
}
}
}
This is an old question, but none of the answers here provide enough context for a beginner to choose which one to pick.
make
?make
is a traditional Unix utility which reads a Makefile
to decide what programs to run to reach a particular goal. Typically, that goal is to build a single piece of software; but make
is general enough to be used for various other tasks, too, like assembling a PDF from a collection of TeX source files, or retrieving the newest versions of each of a set of web pages.
Besides encapsulating the steps to reach an individual target, make
reduces processing time by avoiding to re-execute steps which are already complete. It does this by comparing time stamps between dependencies; if A depends on B but A is newer than B, there is no need to make A
. Of course, in order for this to work properly, the Makefile
needs to document all such dependencies.
A: B
commands to produce A from B
Notice that the indentation needs to consist of a literal tab character. This is a common beginner mistake.
make
The original make
was rather pedestrian. Its lineage continues to this day into BSD make
, from which nmake
is derived. Roughly speaking, this version provides the make
functionality defined by POSIX, with a few minor enhancements and variations.
GNU make
, by contrast, significantly extends the formalism, to the point where a GNU Makefile
is unlikely to work with other versions (or occasionally even older versions of GNU make
). There is a convention to call such files GNUmakefile
instead of Makefile
, but this convention is widely ignored, especially on platforms like Linux where GNU make
is the de facto standard make
.
Telltale signs that a Makefile
uses GNU make
conventions are the use of :=
instead of =
for variable assignments (though this is not exclusively a GNU feature) and a plethora of functions like $(shell ...)
, $(foreach ...)
, $(patsubst ...)
etc.
Well, it really depends on what you are hoping to accomplish.
If the software you are hoping to build has a vcproj
file or similar, you probably want to use that instead, and not try to use make
at all.
In the general case, MinGW make
is a Windows port of GNU make
for Windows, It should generally cope with any Makefile
you throw at it.
If you know the software was written to use nmake
and you already have it installed, or it is easy for you to obtain, maybe go with that.
You should understand that if the software was not written for, or explicitly ported to, Windows, it is unlikely to compile without significant modifications. In this scenario, getting make
to run is the least of your problems, and you will need a good understanding of the differences between the original platform and Windows to have a chance of pulling it off yourself.
In some more detail, if the Makefile
contains Unix commands like grep
or curl
or yacc
then your system needs to have those commands installed, too. But quite apart from that, C or C++ (or more generally, source code in any language) which was written for a different platform might simply not work - at all, or as expected (which is often worse) - on Windows.
This is best solution : https://developer.android.com/studio/write/tool-attributes
This is design attributes we can set activty context in xml like
tools:context=".activity.ActivityName"
Adapter:
tools:context="com.PackegaName.AdapterName"
You can navigate to java class when clicking on the marked icon and tools have more features like
tools:text=""
tools:visibility:""
tools:listItems=""//for recycler view
etx
This worked for me:
For the HTML, add the required
attribute to the input element
<input class="my-input-element" type="text" placeholder="" required />
For the CSS, use the :invalid
selector to target the empty input
input.my-input-element:invalid {
}
Notes:
required
from w3Schools.com:
"When present, it specifies that an input field must be filled out before submitting the form."Try casting to List in the extension method before running the loop. That way you can take advantage of the performance of List.AddRange.
public static void AddRange<T>(this ICollection<T> destination,
IEnumerable<T> source)
{
List<T> list = destination as List<T>;
if (list != null)
{
list.AddRange(source);
}
else
{
foreach (T item in source)
{
destination.Add(item);
}
}
}
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
You can use String arrays to add jComboBox items
String [] items = { "First item", "Second item", "Third item", "Fourth item" };
JComboBox comboOne = new JComboBox (items);
The method .attr() allows getting attribute value of the first element in a jQuery object:
$('#myelement').attr('name');
To avoid memory leaks you may use smart pointers whenever you can. There are basically 2 different types of smart pointers in C++
The main difference is that reference counted smart pointers can be copied (and used in std:: containers) while scoped_ptr cannot. Non reference counted pointers have almost no overhead or no overhead at all. Reference counting always introduces some kind of overhead.
(I suggest to avoid auto_ptr, it has some serious flaws if used incorrectly)
I had something similar, and here's (an edited) version of what I ended up using successfully:
ISNULL(CONVERT(VARCHAR(50),[column name goes here],[date style goes here] ),'')
Here's why this works: If you select a date which is NULL, it will show return NULL, though it is really stored as 01/01/1900. This is why an ISNULL on the date field, while you're working with any date data type will not treat this as a NULL, as it is technically not being stored as a NULL.
However, once you convert it to a new datatype, it will convert it as a NULL, and at that point, you're ISNULL will work as you expect it to work.
I hope this works out for you as well!
~Eli
Update, nearly one year later:
I had a similar situation, where I needed the output to be of the date data-type, and my aforementioned solution didn't work (it only works if you need it displayed as a date, not be of the date data type.
If you need it to be of the date data-type, there is a way around it, and this is to nest a REPLACE
within an ISNULL
, the following worked for me:
Select
ISNULL(
REPLACE(
[DATE COLUMN NAME],
'1900-01-01',
''
),
'') AS [MeaningfulAlias]
The simple answer is yes.
Raymond Chen wrote a great article on GUIDs and why substrings of GUIDs are not guaranteed unique. The article goes in to some depth as to the way GUIDs are generated and the data they use to ensure uniqueness, which should go to some length in explaining why they are :-)
You have to specify project_id
:
reverse('edit_project', kwargs={'project_id':4})
Doc here
int[] arr = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
var result = arr.GroupBy(x => x).Select(x => new { key = x.Key, val = x.Count() });
foreach (var item in result)
{
if(item.val > 1)
{
Console.WriteLine("Duplicate value : {0}", item.key);
Console.WriteLine("MaxCount : {0}", item.val);
}
}
Console.ReadLine();
NULL is not anything...it is unknown. NULL does not equal anything. That is why you have to use the magic phrase IS NULL instead of = NULL in your SQL queries
You can refer this: http://weblogs.sqlteam.com/markc/archive/2009/06/08/60929.aspx
Try this something like this:
var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
alert(p_ids[i].value);
}
For me, the problem was twofold: First, the version of IIS I was dealing with didn't know about the .woff2
MIME type, only about .woff
. I fixed that using IIS Manager at the server level, not at the web app level, so the setting wouldn't get overridden with each new app deployment. (Under IIS Manager, I went to MIME types, and added the missing .woff2
, then updated .woff
.)
Second, and more importantly, I was bundling bootstrap.css
along with some other files as "~/bundles/css/site"
. Meanwhile, my font files were in "~/fonts"
. bootstrap.css
looks for the glyphicon fonts in "../fonts"
, which translated to "~/bundles/fonts"
-- wrong path.
In other words, my bundle path was one directory too deep. I renamed it to "~/bundles/siteCss"
, and updated all the references to it that I found in my project. Now bootstrap looked in "~/fonts"
for the glyphicon files, which worked. Problem solved.
Before I fixed the second problem above, none of the glyphicon
font files were loading. The symptom was that all instances of glyphicon
glyphs in the project just showed an empty box. However, this symptom only occurred in the deployed versions of the web app, not on my dev machine. I'm still not sure why that was the case.
It is worth mentioning that MySQL 8.0.23 and above supports Invisible Columns
CREATE TABLE tbl_Country(
CountryId INT NOT NULL AUTO_INCREMENT,
IsDeleted bit,
PRIMARY KEY (CountryId)
);
INSERT INTO tbl_Country VALUES (1, 1), (2,0);
ALTER TABLE tbl_Country ALTER COLUMN IsDeleted SET INVISIBLE;
SELECT * FROM tbl_Country;
CountryId
1
2
ALTER TABLE tbl_Country DROP COLUMN IsDeleted;
It may be useful in scenarios when there is need to "hide" a column for a time being before it could be safely dropped(like reworking corresponding application/reports etc.).
From Dockerfile reference:
The
ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build command using the--build-arg <varname>=<value>
flag.The
ENV
instruction sets the environment variable<key>
to the value<value>
.
The environment variables set usingENV
will persist when a container is run from the resulting image.
So if you need build-time customization, ARG
is your best choice.
If you need run-time customization (to run the same image with different settings), ENV
is well-suited.
If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable
Given the number of combinations involved, using ENV
to set those features at runtime is best here.
But you can combine both by:
ARG
ARG
as an ENV
That is, with a Dockerfile including:
ARG var
ENV var=${var}
You can then either build an image with a specific var
value at build-time (docker build --build-arg var=xxx
), or run a container with a specific runtime value (docker run -e var=yyy
)
Code:
var select = function(dropdown, selectedValue) {
var options = $(dropdown).find("option");
var matches = $.grep(options,
function(n) { return $(n).text() == selectedValue; });
$(matches).attr("selected", "selected");
};
Example:
select("#dropdown", "B");
Assuming no SecurityManager
is preventing you from doing this, you can use setAccessible
to get around private
and resetting the modifier to get rid of final
, and actually modify a private static final
field.
Here's an example:
import java.lang.reflect.*;
public class EverythingIsTrue {
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
public static void main(String args[]) throws Exception {
setFinalStatic(Boolean.class.getField("FALSE"), true);
System.out.format("Everything is %s", false); // "Everything is true"
}
}
Assuming no SecurityException
is thrown, the above code prints "Everything is true"
.
What's actually done here is as follows:
boolean
values true
and false
in main
are autoboxed to reference type Boolean
"constants" Boolean.TRUE
and Boolean.FALSE
public static final Boolean.FALSE
to refer to the Boolean
referred to by Boolean.TRUE
false
is autoboxed to Boolean.FALSE
, it refers to the same Boolean
as the one refered to by Boolean.TRUE
"false"
now is "true"
static final File.separatorChar
for unit testingInteger
's cache, mutating a String
, etcExtreme care should be taken whenever you do something like this. It may not work because a SecurityManager
may be present, but even if it doesn't, depending on usage pattern, it may or may not work.
JLS 17.5.3 Subsequent Modification of Final Fields
In some cases, such as deserialization, the system will need to change the
final
fields of an object after construction.final
fields can be changed via reflection and other implementation dependent means. The only pattern in which this has reasonable semantics is one in which an object is constructed and then thefinal
fields of the object are updated. The object should not be made visible to other threads, nor should thefinal
fields be read, until all updates to thefinal
fields of the object are complete. Freezes of afinal
field occur both at the end of the constructor in which thefinal
field is set, and immediately after each modification of afinal
field via reflection or other special mechanism.Even then, there are a number of complications. If a
final
field is initialized to a compile-time constant in the field declaration, changes to thefinal
field may not be observed, since uses of thatfinal
field are replaced at compile time with the compile-time constant.Another problem is that the specification allows aggressive optimization of
final
fields. Within a thread, it is permissible to reorder reads of afinal
field with those modifications of a final field that do not take place in the constructor.
private static final boolean
, because it's inlineable as a compile-time constant and thus the "new" value may not be observableEssentially,
field.getModifiers() & ~Modifier.FINAL
turns off the bit corresponding to Modifier.FINAL
from field.getModifiers()
. &
is the bitwise-and, and ~
is the bitwise-complement.
Still not being able to solve this?, have fallen onto depression like I did for it? Does your code looks like this?
public class A {
private final String myVar = "Some Value";
}
Reading the comments on this answer, specially the one by @Pshemo, it reminded me that Constant Expressions are handled different so it will be impossible to modify it. Hence you will need to change your code to look like this:
public class A {
private final String myVar;
private A() {
myVar = "Some Value";
}
}
if you are not the owner of the class... I feel you!
For more details about why this behavior read this?
$arr = array(1, 'a', 3, 4 => 1, 'b' => 1);
foreach ($arr as $key => $val) {
echo "{$key} = {$val}" . (end(array_keys($arr))===$key ? '' : ', ');
}
// output: 0 = 1, 1 = a, 2 = 3, 4 = 1, b = 1
$array[0] = 1;
$array[2] = 2;
$arrayTxt = implode( ',', $array);
$sql = "SELECT * FROM table WHERE some_id in ($arrayTxt)"
Use PHP_EOL
which produces \r\n
or \n
$data = 'my data' . PHP_EOL . 'my data';
$fp = fopen('my_file', 'a');
fwrite($fp, $data);
fclose($fp);
// File output
my data
my data
I had a false response for the following:
fputs($connection, 'STARTTLS'.$newLine);
turns out I use the wrong connection variable, so I just had to change it to:
fputs($smtpConnect, 'STARTTLS'.$newLine);
If using TLS remember to put HELO before and after:
fputs($smtpConnect, 'HELO '.$localhost . $newLine);
$response = fgets($smtpConnect, 515);
if($secure == 'tls')
{
fputs($smtpConnect, 'STARTTLS'.$newLine);
$response = fgets($smtpConnect, 515);
stream_socket_enable_crypto($smtpConnect, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
// Say hello again!
fputs($smtpConnect, 'HELO '.$localhost . $newLine);
$response = fgets($smtpConnect, 515);
}
Dynamitey is an open source .net std
library, that let's you call it like the dynamic
keyword, but using the a string for the property name rather than the compiler doing it for you, and it ends up being equal to reflection speedwise (which is not nearly as fast as using the dynamic keyword, but this is due to the extra overhead of caching dynamically, where the compiler caches statically).
Dynamic.InvokeGet(d,"value2");
obj = {'a':'c','b':'d'}
You can try:
[index for (index in obj)]
this will return:
['a','b']
to get the list of keys or
[obj[index] for (index in obj)]
to get the values
You can use tail
:
$ foo="1234567890"
$ echo -n $foo | tail -c 3
890
A somewhat roundabout way to get the last three characters would be to say:
echo $foo | rev | cut -c1-3 | rev
No, you can't. Just declare the variable outside the function. You don't have to declare it at the same time as you assign the value:
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
You can use the asList
method with varargs to do this in one line:
java.util.Arrays.asList('+', '-', '*', '^');
If the list does not need to be modified further then this would already be enough. Otherwise you can pass it to the ArrayList constructor to create a mutable list:
new ArrayList(Arrays.asList('+', '-', '*', '^'));
What worked for me besides restarting eclipse is:
After removing all filters, logcat was filled with text again Hope this will be helpful to someone else
Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.
this.Include(includes, () =>
{
_context.Cars.Include(<parameters>);
});
You can use DataColumn.Ordinal
to get the index of the column in the DataTable
. So if you need the next column as mentioned use Column.Ordinal + 1
:
row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;
The following example demonstrates how to do this:
DateTime a = new DateTime(2010, 05, 12, 13, 15, 00);
DateTime b = new DateTime(2010, 05, 12, 13, 45, 00);
Console.WriteLine(b.Subtract(a).TotalMinutes);
When executed this prints "30" since there is a 30 minute difference between the date/times.
The result of DateTime.Subtract(DateTime x)
is a TimeSpan Object which gives other useful properties.
First you need to use a database to show all collection/tables inside it.
>show dbs
users 0.56787GB
test (empty)
>db.test.help() // this will give you all the function which can be used with this db
>use users
>show tables //will show all the collection in the db
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
Even though this is fairly an old question, I have my 2 cents to share.
Like the zipball
link pointed by various answers here, There is a tarball
link as well which downloads the content of the git repository in tar.gz
format.
curl -L http://github.com/zoul/Finch/tarball/master/
Git also provides a different URL pattern where you can simply append the type of file you want to download at the end of url. This way is better if you want to process these urls in a batch or bash script.
curl -L http://github.com/zoul/Finch/archive/master.zip
curl -L http://github.com/zoul/Finch/archive/master.tar.gz
Replace master
with the commit-hash
or the branch-name
in the above urls like below.
curl -L http://github.com/zoul/Finch/archive/cfeb671ac55f6b1aba6ed28b9bc9b246e0e.zip
curl -L http://github.com/zoul/Finch/archive/cfeb671ac55f6b1aba6ed28b9bc9b246e0e.tar.gz
curl -L http://github.com/zoul/Finch/archive/your-branch-name.zip
curl -L http://github.com/zoul/Finch/archive/your-branch-name.tar.gz
Frontend refers to the client-side, whereas backend refers to the server-side of the application. Both are crucial to web development, but their roles, responsibilities and the environments they work in are totally different. Frontend is basically what users see whereas backend is how everything works
Like the comments suggest, the solution is to use nested spans/rows.
<div class="container">
<div class="row">
<div class="span4">1</div>
<div class="span8">
<div class="row">
<div class="span4">2</div>
<div class="span4">3</div>
</div>
<div class="row">
<div class="span4">4</div>
<div class="span4">5</div>
</div>
</div>
</div>
<div class="row">
<div class="span4">6</div>
<div class="span4">7</div>
<div class="span4">8</div>
</div>
</div>
Since it is basically a javascript shell, you can also use toArray()
:
db.collection.find().toArray()
However, this will print all the documents of the collection unlike pretty()
that will allow you to iterate.
Refer: http://docs.mongodb.org/manual/reference/method/cursor.toArray/
I'm using EF6, and I find something strange,
Suppose Customer has constructor with parameter ,
if I use new Customer(id, "name")
, and do
using (var db = new EfContext("name=EfSample"))
{
db.Customers.Add( new Customer(id, "name") );
db.SaveChanges();
}
It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,
But if I add the curly brackets, use new Customer(id, "name"){}
and do
using (var db = new EfContext("name=EfSample"))
{
db.Customers.Add( new Customer(id, "name"){} );
db.SaveChanges();
}
the data will then actually BE Inserted,
seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.