I guess you missed to put semi-colon ;
at the closing curly brace }
of window.fbAsyncInit = function() { ... };
since your local username on your laptop frequently does not match the server's username, you can set this in the ~/.subversion/servers file
Add the server to the [groups] section with a name, then add a section with that name and provide a username.
for example, for a login like [email protected]
this is what your config would look like:
[groups]
exampleserver = svn.example.com
[exampleserver]
username = me
I think this is enough to get you on a nice path:
Sub a()
Dim btn As Button
Application.ScreenUpdating = False
ActiveSheet.Buttons.Delete
Dim t As Range
For i = 2 To 6 Step 2
Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "btnS"
.Caption = "Btn " & i
.Name = "Btn" & i
End With
Next i
Application.ScreenUpdating = True
End Sub
Sub btnS()
MsgBox Application.Caller
End Sub
It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.
You can save the best model using keras.callbacks.ModelCheckpoint()
Example:
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model_checkpoint_callback = keras.callbacks.ModelCheckpoint("best_Model.h5",save_best_only=True)
history = model.fit(x_train,y_train,
epochs=10,
validation_data=(x_valid,y_valid),
callbacks=[model_checkpoint_callback])
This will save the best model in your working directory.
You can set the line height on the text, for example within the active class:
.active {
...
line-height: 2em;
....
}
it is easy
list-view.set selection(you pos);
or you can save your position with SharedPreference
and when you start activity
it get preferences and setSeletion
to that int
If one wants to follow a more Reactive oriented style of programming, then definitely the concept of "Everything is a stream" comes into picture and hence, use Observables to deal with these streams as often as possible.
I've seen some people promote 'package by feature' over 'package by layer' but I've used quite a few approaches over many years and found 'package by layer' much better than 'package by feature'.
Further to that I have found that a hybrid: 'package by module, layer then feature' strategy works extremely well in practice as it has many advantages of 'package by feature':
I explain in depth here: Java Package Name Structure and Organization but my standard package structure is:
revdomain.moduleType.moduleName.layer.[layerImpl].feature.subfeatureN.subfeatureN+1...
Where:
revdomain Reverse domain e.g. com.mycompany
moduleType [app*|framework|util]
moduleName e.g. myAppName if module type is an app or 'finance' if its an accounting framework
layer [model|ui|persistence|security etc.,]
layerImpl eg., wicket, jsp, jpa, jdo, hibernate (Note: not used if layer is model)
feature eg., finance
subfeatureN eg., accounting
subfeatureN+1 eg., depreciation
*Sometimes 'app' left out if moduleType is an application but putting it in there makes the package structure consistent across all module types.
I think you have got it in that last attempt, you just need to grab the string.. in Chrome's console..
startdate = moment();
startdate.subtract(1, 'd');
startdate.format('DD-MM-YYYY');
"14-04-2015"
startdate = moment();
startdate.subtract(1, 'd');
myString = startdate.format('DD-MM-YYYY');
"14-04-2015"
myString
"14-04-2015"
Another truncate with no rounding solution and example.
Convert 71.950005666 to a single decimal place number (71.9)
1) 71.950005666 * 10.0 = 719.50005666
2) Floor(719.50005666) = 719.0
3) 719.0 / 10.0 = 71.9
select Floor(71.950005666 * 10.0) / 10.0
Ok after 2 days of trying to figure out why I couldn't run the example from
http://www.tutorialspoint.com/testng/testng_environment.htm the following code did not work for me
C:\TestNG_WORKSPACE>java -cp "C:\TestNG_WORKSPACE" org.testng.TestNG testng.xml
The fix for it is as follows: I came to the following conclusion: First off install eclipse, and download the TestNG plugin. After that follow the instructions from the tutorial to create and compile the test class from cmd using javac, and add the testng.xml. To run the testng.xml on windows 10 cmd run the following line:
java -cp C:\Users\Lenovo\Desktop\eclipse\plugins\org.testng.eclipse_6.9.12.201607091356\lib\*;C:\Test org.testng.TestNG testng.xml
to clarify: C:\Users\Lenovo\Desktop\eclipse\plugins\org.testng.eclipse_6.9.12.201607091356\lib\*
The path above represents the location of jcommander.jar and testng.jar that you downloaded by installing the TESTNG plugin for eclipse. The path may vary so to be sure just open the installation location of eclipse, go to plugins and search for jcommander.jar. Then copy that location and after that add * to select all the necessary .jars.
C:\Test
The path above represents the location of the testing.xml in your project. After getting all the necessary paths, append them by using ";".
I hope I have been helpful to some of you guys :)
I had this issue too, after following this guide, it was simply 1 additional patch that was required to get past the
Rule "Prior Visual Studio 2010 instances requiring update." failed.
Was to locate this file, and patch my machine
VS10sp1-KB983509.msp
Simply do a file search on the installation media for SQL Server 2012, in my case it was in \redist\VisualStudioShell (whereas in the guide it's listed as being in a different location).
Then hit 're-run'.
That is because you are opening , writing and closing the file 10 times inside your for loop
myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()
You should open and close your file outside for loop.
myfile = open('xyz.txt', 'w')
for line in lines:
var1, var2 = line.split(",");
myfile.write("%s\n" % var1)
myfile.close()
text_file.close()
You should also notice to use write and not writelines.
writelines
writes a list of lines to your file.
Also you should check out the answers posted by folks here that uses with
statement. That is the elegant way to do file read/write operations in Python
<?php
$Words = array("hello","there","world");
$c = 0;
$message = 'Hi hello';
foreach ($Words as $word):
$trial = stripos($message,$word);
if($trial != true){
$c++;
echo 'Word '.$c.' didnt match <br> <br>';
}else{
$c++;
echo 'Word '.$c.' matched <br> <br>';
}
endforeach;
?>
I used this kind of code to check for hello, It also Has a numbering feature. You can use this if you want to do content moderation practices in websites that need the user to type
Check this library, it's completable with booth bootstrap 3 and bootstrap 4
<form>
<div class="form-group">
<input class="form-control" data-validator="required|min:4|max:10">
</div>
</form>
$(document).on('blur', '[data-validator]', function () {
new Validator($(this));
});
Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value. Several of the other answers illustrate different ways this can be accomplished.
You need to make the object first, then use []
to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2018:
If you're able to use ES6 and Babel, you can use this new feature:
{
[yourKeyVariable]: someValueArray,
}
you should just be able to call it by typing in the file name. You may have to call ./a.exe as the current directory is usually not on the path for security reasons.
If you need to handle lists of different sizes, worry not! The wonderful itertools module has you covered:
>>> from itertools import zip_longest
>>> list1 = [1,2,1]
>>> list2 = [2,1,2,3]
>>> [sum(x) for x in zip_longest(list1, list2, fillvalue=0)]
[3, 3, 3, 3]
>>>
In Python 2, zip_longest
is called izip_longest
.
See also this relevant answer and comment on another question.
I use a modified version of this:
function getElementsByClass(nameOfClass) {
var temp, all, elements;
all = document.getElementsByTagName("*");
elements = [];
for(var a=0;a<all.length;a++) {
temp = all[a].className.split(" ");
for(var b=0;b<temp.length;b++) {
if(temp[b]==nameOfClass) {
elements.push(ALL[a]);
break;
}
}
}
return elements;
};
And JQuery will do this really easily too.
For cases where you may be moving the tabs, here is some code.
for ( UINavigationController *controller in self.tabBarController.viewControllers ) {
if ( [[controller.childViewControllers objectAtIndex:0] isKindOfClass:[MyViewController class]]) {
[self.tabBarController setSelectedViewController:controller];
break;
}
}
This can be achieved using div. It can be done with table too. But i always prefer div.
<body id="doc-body" style="width: 100%; height: 100%; overflow: hidden; position: fixed" onload="InitApp()">
<div>
<!--If you don't need header background color you don't need this div.-->
<div id="div-header-hack" style="height: 20px; position: absolute; background-color: gray"></div>
<div id="div-header" style="position: absolute; top: 0px; overflow: hidden; height: 20px; background-color: gray">
</div>
<div id="div-item" style="position: absolute; top: 20px; overflow: auto" onscroll="ScrollHeader()">
</div>
</div>
</body>
Javascript:
please refer jsFiddle for this part. Else this answer becomes very lengthy.
You could still use sortBy (at the collection level) instead of orderBy (at the query level) if you still want to use all() since it returns a collection of objects.
Ascending Order
$results = Project::all()->sortBy("name");
Descending Order
$results = Project::all()->sortByDesc("name");
Check out the documentation about Collections for more details.
select sum(qty), name
from (
select count(m.owner_id) as qty, o.name
from transport t,owner o,motorbike m
where t.type='motobike' and o.owner_id=m.owner_id
and t.type_id=m.motorbike_id
group by m.owner_id
union all
select count(c.owner_id) as qty, o.name,
from transport t,owner o,car c
where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
group by c.owner_id
) t
group by name
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
This is a simple solution for merging two dictionaries where +=
can be applied to the values, it has to iterate over a dictionary only once
a = {'a':1, 'b':2, 'c':3}
dicts = [{'b':3, 'c':4, 'd':5},
{'c':9, 'a':9, 'd':9}]
def merge_dicts(merged,mergedfrom):
for k,v in mergedfrom.items():
if k in merged:
merged[k] += v
else:
merged[k] = v
return merged
for dct in dicts:
a = merge_dicts(a,dct)
print (a)
#{'c': 16, 'b': 5, 'd': 14, 'a': 10}
The difference is this:
Int32.Parse()
and Int32.TryParse()
can only convert strings. Convert.ToInt32()
can take any class that implements IConvertible
. If you pass it a string, then they are equivalent, except that you get extra overhead for type comparisons, etc. If you are converting strings, then TryParse()
is probably the better option.
a='foo'
b='baaz'
a.__add__(b)
out: 'foobaaz'
Here Response.Write():to display only string and you can not display any other data type values like int,date,etc.Conversion(from one data type to another) is not allowed. whereas Response .Output .Write(): you can display any type of data like int, date ,string etc.,by giving index values.
Here is example:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write ("hi good morning!"+"is it right?");//only strings are allowed
Response.Write("Scott is {0} at {1:d}", "cool", DateTime.Now);//this will give error(conversion is not allowed)
Response.Output.Write("\nhi goood morning!");//works fine
Response.Output.Write("Jai is {0} on {1:d}", "cool", DateTime.Now);//here the current date will be converted into string and displayed
}
import java.text.DecimalFormat;
public class RoundTest {
public static void main(String[] args) {
double i = 2;
DecimalFormat twoDForm = new DecimalFormat("#.00");
System.out.println(twoDForm.format(i));
double j=3.1;
System.out.println(twoDForm.format(j));
double k=4.144456;
System.out.println(twoDForm.format(k));
}
}
We're using Kafka 2.11 and make use of this tool - kafka-consumer-groups
.
$ rpm -qf /bin/kafka-consumer-groups
confluent-kafka-2.11-1.1.1-1.noarch
For example:
$ kafka-consumer-groups --describe --group logstash | grep -E "TOPIC|filebeat"
Note: This will not show information about old Zookeeper-based consumers.
TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG CONSUMER-ID HOST CLIENT-ID
beats_filebeat 0 20003914484 20003914888 404 logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1 logstash-0
beats_filebeat 1 19992522286 19992522709 423 logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1 logstash-0
beats_filebeat 2 19990597254 19990597637 383 logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1 logstash-0
beats_filebeat 7 19991718707 19991719268 561 logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2 logstash-0
beats_filebeat 8 20015611981 20015612509 528 logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2 logstash-0
beats_filebeat 5 19990536340 19990541331 4991 logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3 logstash-0
beats_filebeat 6 19990728038 19990733086 5048 logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3 logstash-0
beats_filebeat 3 19994613945 19994616297 2352 logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4 logstash-0
beats_filebeat 4 19990681602 19990684038 2436 logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4 logstash-0
NOTE: We use an alias that overloads kafka-consumer-groups
like so in our /etc/profile.d/kafka.sh
:
alias kafka-consumer-groups="KAFKA_JVM_PERFORMANCE_OPTS=\"-Djava.security.auth.login.config=$HOME/.kafka_client_jaas.conf\" kafka-consumer-groups --bootstrap-server ${KAFKA_HOSTS} --command-config /etc/kafka/security-enabler.properties"
Since you are in a modal window (whether dynamic or in the page) you can use the following code to accomplish your goal: (I ran into the same problem on my site and this is how I fixed it)
HTML:
<div class="content-container" style="text-align: right;">
<input type="checkbox" id="QueryGroupCopyQueries">
<label for="QueryGroupCopyQueries">Create Copies</label>
</div>
CODE:
$.each(queriesToAddToGroup, function (index, query) {
if (query.groupAddType === queriesGroupAddType.COPY) {
// USE FIND against your dynamic window and PROP to set the value
// if you are using JQUERY 1.6 or higher.
$(kendoWindow).find("input#QueryGroupCopyQueries").prop("checked", true);
return;
}
In the above "kendoWindow" is my window (mine is dynamic, but I also do this when appending to an element directly in the page). I am looping through an array of data ("queriesToAddToGroup") to see if any rows have an attribute of COPY. If so I want to turn on the checkbox within the window that sets that attribute when a user saves from this window.
Had the same Issue when i decided to install another version of Android Studio, what worked for me was:
classpath 'com.android.tools.build:gradle:3.5.0-rc01'
Copied that line and replaced it on the project i was working on.
Pulling may have created local change.
Add your untracked file:
git add .
Stash changes.
git stash
Drop local changes.
git stash drop
Pull with sudo permission
sudo git pull remote branch
npm test <filepath>
eg :
npm test test/api/controllers/test.js
here 'test/api/controllers/test.js' is filepath.
Use this to set the orientation of the screen:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
or
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
and don't forget to add this to your manifest:
android:configChanges = "orientation"
Ahem, you can apply themes to individual activities in XML such as no title. In other words, take it out of your application tag, open the tag declaration and put it in the desired activity tag.
rtrim
function
rtrim($my_string,',');
Second parameter indicates that comma to be deleted from right side.
Any recent front-end framework (Angular 1/2, react, Vue,...) can easily and automatically convert your UTC datetime to local time.
Additionally:
(Unless you are likely to change the timezone of your servers)
Example with AngularJs
// back-end: format for angular within the sql query
SELECT DATE_FORMAT(my_datetime, "%Y-%m-%dT%TZ")...
// font-end Output the localised time
{{item.my_datetime | date :'medium' }}
All localised time format available here: https://docs.angularjs.org/api/ng/filter/date
I'm using version 4.4.2 and none of the other answers worked for me. But adding useMongoClient
to the options and putting it into a variable that you call close
on seemed to work.
var db = mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: true })
//do stuff
db.close()
Here is the directive I use. It automatically cleans itself up when the form is unloaded. If you want to prevent the prompt from firing (e.g. because you successfully saved the form), call $scope.FORMNAME.$setPristine(), where FORMNAME is the name of the form you want to prevent from prompting.
.directive('dirtyTracking', [function () {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
function isDirty() {
var formObj = $scope[$element.attr('name')];
return formObj && formObj.$pristine === false;
}
function areYouSurePrompt() {
if (isDirty()) {
return 'You have unsaved changes. Are you sure you want to leave this page?';
}
}
window.addEventListener('beforeunload', areYouSurePrompt);
$element.bind("$destroy", function () {
window.removeEventListener('beforeunload', areYouSurePrompt);
});
$scope.$on('$locationChangeStart', function (event) {
var prompt = areYouSurePrompt();
if (!event.defaultPrevented && prompt && !confirm(prompt)) {
event.preventDefault();
}
});
}
};
}]);
in FacebookSDK v2.1 (I can't check older version). We have
NSString *currentUserFBID = [FBSession activeSession].accessTokenData.userID;
However according to the comment in FacebookSDK
@discussion This may not be populated for login behaviours such as the iOS system account.
So may be you should check if it is available, and then whether use it, or call the request to get the user id
For the filestream:
//Check if the directory exists
if (!System.IO.Directory.Exists(@"C:\yourDirectory"))
{
System.IO.Directory.CreateDirectory(@"C:\yourDirectory");
}
//Write the file
using (System.IO.StreamWriter outfile = new System.IO.StreamWriter(@"C:\yourDirectory\yourFile.txt"))
{
outfile.Write(yourFileAsString);
}
I was having 2 values which could contain null values.
while(dr.Read())
{
Id = dr["Id"] as int? ?? default(int?);
Alt = dr["Alt"].ToString() as string ?? default(string);
Name = dr["Name"].ToString()
}
resolved the issue
If you need to use https, then use the https library
https = require('https');
// options
var options = {
host: 'eternagame.wikia.com',
path: '/wiki/EteRNA_Dictionary'
}
// get
https.get(options, callback);
PHP's implode
function can be used to convert an array into a string --- it is similar to join
in other languages.
You can use it like so:
$string_product = implode(',', $array);
With an array like [1, 2, 3]
, this would result in a string like "1,2,3"
.
Borrowed from @Deena above, that function modification for labels is more versatile than you might have thought. For example, I had a ggplot where the denominator of counted variables was 140. I used her example thus:
scale_y_continuous(labels = function(x) paste0(round(x/140*100,1), "%"), breaks = seq(0, 140, 35))
This allowed me to get my percentages on the 140 denominator, and then break the scale at 25% increments rather than the weird numbers it defaulted to. The key here is that the scale breaks are still set by the original count, not by your percentages. Therefore the breaks must be from zero to the denominator value, with the third argument in "breaks" being the denominator divided by however many label breaks you want (e.g. 140 * 0.25 = 35).
In one reusable piece of code I use the directive <%@include file="reuse.html"%>
and in the second I use the standard action <jsp:include page="reuse.html" />
.
Let the code in the reusable file be:
<html>
<head>
<title>reusable</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<img src="candle.gif" height="100" width="50"/> <br />
<p><b>As the candle burns,so do I</b></p>
</body>
After running both the JSP files you see the same output and think if there was any difference between the directive and the action tag. But if you look at the generated servlet
of the two JSP files, you will see the difference.
Here is what you will see when you use the directive:
out.write("<html>\r\n");
out.write(" <head>\r\n");
out.write(" <title>reusable</title>\r\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
out.write(" </head>\r\n");
out.write(" <body>\r\n");
out.write(" <img src=\"candle.gif\" height=\"100\" width=\"50\"/> <br />\r\n");
out.write(" <p><b>As the candle burns,so do I</b></p>\r\n");
out.write(" </body>\r\n");
out.write("</html>\r\n");
And this is what you will see for the used standard action in the second JSP file :
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "reusable.html", out, false);
So now you know that the include directive inserts the source of reuse.html
at translation time, but the action tag inserts the response of reuse.html
at runtime.
If you think about it, there is an extra performance hit with every action tag (<jsp:include>
). It means you can guarantee you will always have the latest content, but it increases performance cost.
I had this, but not sure if this is correct. Could try this out also.
mysql_query("START TRANSACTION");
$flag = true;
$query = "INSERT INTO testing (myid) VALUES ('test')";
$query2 = "INSERT INTO testing2 (myid2) VALUES ('test2')";
$result = mysql_query($query) or trigger_error(mysql_error(), E_USER_ERROR);
if (!$result) {
$flag = false;
}
$result = mysql_query($query2) or trigger_error(mysql_error(), E_USER_ERROR);
if (!$result) {
$flag = false;
}
if ($flag) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
Idea from here: http://www.phpknowhow.com/mysql/transactions/
Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.
Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.
Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.
On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)
The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.
Jake
You can do this with 'taskkill'. With the /IM parameter, you can specify image names.
Example:
taskkill /im somecorporateprocess.exe
You can also do this to 'force' kill:
Example:
taskkill /f /im somecorporateprocess.exe
Just add one line per process you want to kill, save it as a .bat file, and add in your startup directory. Problem solved!
If this is a legacy system, PsKill will do the same.
Since the main
method is static
and the fxn()
method is not, you can't call the method without first creating a Two
object. So either you change the method to:
public static int fxn(int y) {
y = 5;
return y;
}
or change the code in main
to:
Two two = new Two();
x = two.fxn(x);
Read more on static
here in the Java Tutorials.
String s1 = "Anish";
String s2 = "Anish";
String s3 = new String("Anish");
/*
* When the intern method is invoked, if the pool already contains a
* string equal to this String object as determined by the
* method, then the string from the pool is
* returned. Otherwise, this String object is added to the
* pool and a reference to this String object is returned.
*/
String s4 = new String("Anish").intern();
if (s1 == s2) {
System.out.println("s1 and s2 are same");
}
if (s1 == s3) {
System.out.println("s1 and s3 are same");
}
if (s1 == s4) {
System.out.println("s1 and s4 are same");
}
OUTPUT
s1 and s2 are same
s1 and s4 are same
Web Sockets - It is a protocol which provides a full-duplex communication channel over a single TCP connection.
For instance a two-way communication between the Server and Browser
Since the protocol is more complicated, the server and the browser has to rely on library of websocket
which is socket.io
Example - Online chat application.
SSE(Server-Sent Event) -
In case of server sent event the communication is carried out from server to browser only and browser cannot send any data to the server. This kind of communication is mainly used
when the need is only to show the updated data, then the server sends the message whenever the data gets updated.
For instance a one-way communication between the Server to Browser.
This protocol is less complicated, so no need to rely on the external library JAVASCRIPT itself provides the EventSource
interface to receive the server sent messages.
Example - Online stock quotes or cricket score website.
The RegExp constructor creates a regular expression object for matching text with a pattern.
var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
var regex = new RegExp(pattern1 + '|' + pattern2, 'gi');
str.match(regex);
Above code works perfectly for me...
Here's the example:
// Test
public void foo() {
C c = new C();
A s;
s = ((A.B)c).get();
System.out.println(s.getR());
}
// classes
class C {}
class A {
public class B extends C{
A get() {return A.this;}
}
public String getR() {
return "This is string";
}
}
After digging into hibernate source code and Below configuration goes to Oracle db for the next value after 50 inserts. So make your INST_PK_SEQ increment 50 each time it is called.
Hibernate 5 is used for below strategy
Check also below http://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html#identifiers-generators-sequence
@Id
@Column(name = "ID")
@GenericGenerator(name = "INST_PK_SEQ",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@org.hibernate.annotations.Parameter(
name = "optimizer", value = "pooled-lo"),
@org.hibernate.annotations.Parameter(
name = "initial_value", value = "1"),
@org.hibernate.annotations.Parameter(
name = "increment_size", value = "50"),
@org.hibernate.annotations.Parameter(
name = SequenceStyleGenerator.SEQUENCE_PARAM, value = "INST_PK_SEQ"),
}
)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "INST_PK_SEQ")
private Long id;
If you want to sort based on first column (which contains number value), then try this:
arr.sort(function(a,b){
return a[0]-b[0]
})
If you want to sort based on second column (which contains string value), then try this:
arr.sort(function(a,b){
return a[1].charCodeAt(0)-b[1].charCodeAt(0)
})
P.S. for the second case, you need to compare between their ASCII values.
Hope this helps.
Others pointed out to use SQS and Step Functions. But both these solutions add additional cost. Step Function state transitions are supposedly very expensive.
AWS lambda offers some retry logic. Where it tries something for 3 times. I am not sure if that is still valid when you trigger it use the API.
Set-ExecutionPolicy Unrestricted -Scope CurrentUser
This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.
As documented under CREATE TABLE
Syntax:
Note
The olderTYPE
option was synonymous withENGINE
.TYPE
was deprecated in MySQL 4.0 and removed in MySQL 5.5. When upgrading to MySQL 5.5 or later, you must convert existing applications that rely onTYPE
to useENGINE
instead.
Therefore, you want:
CREATE TABLE dave_bannedwords(
id INT(11) NOT NULL AUTO_INCREMENT,
word VARCHAR(60) NOT NULL DEFAULT '',
PRIMARY KEY (id),
KEY id(id) -- this is superfluous in the presence of your PK, ergo unnecessary
) ENGINE = MyISAM ;
I liked the answer but the part that bothered me was the use of <script id="...">
as a container for the modal's template.
I wanted to place the modal's template in a hidden <div>
and bind the inner html with a scope variable called modal_html_template
mainly because i think it more correct (and more comfortable to process in WebStorm/PyCharm) to place the template's html inside a <div>
instead of <script id="...">
this variable will be used when calling $modal({... 'template': $scope.modal_html_template, ...})
in order to bind the inner html, i created inner-html-bind
which is a simple directive
check out the example plunker
<div ng-controller="ModalDemoCtrl">
<div inner-html-bind inner-html="modal_html_template" class="hidden">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<a ng-click="selected.item = item">{{ item }}</a>
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
<button class="btn" ng-click="open()">Open me!</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>
inner-html-bind
directive:
app.directive('innerHtmlBind', function() {
return {
restrict: 'A',
scope: {
inner_html: '=innerHtml'
},
link: function(scope, element, attrs) {
scope.inner_html = element.html();
}
}
});
you can also write the code below.
Array lbl_array = Array.CreateInstance(typeof(string), i, j);
where 'i' is the number of rows and 'j' is the number of columns. using the 'typeof(..)' method you can choose the type of your array i.e. int, string, double
this is the most simple way but it works for me with a ComboBox1 name
SOLUTION on 3 Basic STEPS:
step 1.
Declare a variable at the beginning of your form which will hold the original text value of the ComboBox. Example:
Dim xCurrentTextValue as string
step 2.
Create the event combobox1 key down and Assign to xCurrentTextValue variable the current text of the combobox if any key diferrent than "ENTER" is pressed the combobox text value keeps the original text value
Example:
Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyDown
xCurrentTextValue = ComboBox1.Text
If e.KeyCode <> Keys.Enter Then
Me.ComboBox1.Text = xCmbItem
End If
End Sub
step 3.
Validate the when the combo text is changed if len(xcurrenttextvalue)> 0 or is different than nothing then the combobox1 takes the xcurrenttextvalue variable value
Private Sub ComboBox1_TextChanged(sender As Object, e As EventArgs) Handles ComboBox1.TextChanged
If Len(xCurrentTextValue) > 0 Then
Me.ComboBox1.Text = xCurrentTextValue
End If
End Sub
========================================================== that's it,
Originally I only tried the step number 2, but I have problems when you press the DEL key and DOWN arrow key, also for some reason it didn't validate the keydown event unless I display any message box
!Sorry, this is a correction on step number 2, I forgot to change the variable xCmbItem to xCurrentTextValue, xCmbItem it was used for my personal use
THIS IS THE CORRECT CODE
xCurrentTextValue = ComboBox1.Text
If e.KeyCode <> Keys.Enter Then
Me.ComboBox1.Text = xCurrentTextValue
End If
You don't have g++ installed, simple way to have all the needed build tools is to install the package build-essential:
sudo apt-get install build-essential
, or just the g++ package:
sudo apt-get install g++
One of the pitfalls as I know is IE problem with custom elements. As quoted from the docs:
3) you do not use custom element tags such as (use the attribute version instead)
4) if you do use custom element tags, then you must take these steps to make IE 8 and below happy
<!doctype html>
<html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="optionalModuleName">
<head>
<!--[if lte IE 8]>
<script>
document.createElement('ng-include');
document.createElement('ng-pluralize');
document.createElement('ng-view');
// Optionally these for CSS
document.createElement('ng:include');
document.createElement('ng:pluralize');
document.createElement('ng:view');
</script>
<![endif]-->
</head>
<body>
...
</body>
</html>
I used to do a simple for
loop. As @A5C1D2H2I1M1N2O1R2T1 answer, lapply
is a nice solution. But if you convert all the columns, you will need a data.frame
before, otherwise you will end up with a list
. Little execution time differences.
mm2N=mm2New[,10:18]
str(mm2N)
'data.frame': 35487 obs. of 9 variables:
$ bb : int 4 6 2 3 3 2 5 2 1 2 ...
$ vabb : int -3 -3 -2 -2 -3 -1 0 0 3 3 ...
$ bb55 : int 7 6 3 4 4 4 9 2 5 4 ...
$ vabb55: int -3 -1 0 -1 -2 -2 -3 0 -1 3 ...
$ zr : num 0 -2 -1 1 -1 -1 -1 1 1 0 ...
$ z55r : num -2 -2 0 1 -2 -2 -2 1 -1 1 ...
$ fechar: num 0 -1 1 0 1 1 0 0 1 0 ...
$ varr : num 3 3 1 1 1 1 4 1 1 3 ...
$ minmax: int 3 0 4 6 6 6 0 6 6 1 ...
# For solution
t1=Sys.time()
for(i in 1:ncol(mm2N)) mm2N[,i]=as.factor(mm2N[,i])
Sys.time()-t1
Time difference of 0.2020121 secs
str(mm2N)
'data.frame': 35487 obs. of 9 variables:
$ bb : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
$ vabb : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
$ bb55 : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
$ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
$ zr : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
$ z55r : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
$ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
$ varr : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
$ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...
#lapply solution
mm2N=mm2New[,10:18]
t1=Sys.time()
mm2N <- lapply(mm2N, as.factor)
Sys.time()-t1
Time difference of 0.209012 secs
str(mm2N)
List of 9
$ bb : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
$ vabb : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
$ bb55 : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
$ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
$ zr : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
$ z55r : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
$ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
$ varr : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
$ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...
#data.frame lapply solution
mm2N=mm2New[,10:18]
t1=Sys.time()
mm2N <- data.frame(lapply(mm2N, as.factor))
Sys.time()-t1
Time difference of 0.2010119 secs
str(mm2N)
'data.frame': 35487 obs. of 9 variables:
$ bb : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
$ vabb : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
$ bb55 : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
$ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
$ zr : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
$ z55r : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
$ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
$ varr : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
$ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...
$source = "number35"
$number=$null
$result = foreach ($_ in $source.ToCharArray()){$digit="0123456789".IndexOf($\_,0);if($digit -ne -1){$number +=$\_}}[int32]$number
Just feed it digits and it wil convert to an Int32
For only pick from local add this :
i.putExtra(Intent.EXTRA_LOCAL_ONLY,true)
And this working nice :
val i = Intent(Intent.ACTION_GET_CONTENT,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
i.type = "image/*"
i.putExtra(Intent.EXTRA_LOCAL_ONLY,true)
startActivityForResult(Intent.createChooser(i,"Select Photo"),pickImageRequestCode)
ok. I solved it
SELECT `smart_projects`.project_id, `smart_projects`.business_id, `smart_projects`.title,
`page_pages`.`funnel_id` as `funnel_id`, count(distinct(page_pages.page_id) )as page_count, count(distinct (CASE WHEN page_pages.funnel_id != 0 then page_pages.funnel_id ELSE NULL END ) ) as funnel_count
FROM `smart_projects`
LEFT JOIN `page_pages` ON `smart_projects`.`project_id` = `page_pages`.`project_id`
WHERE smart_projects.status != 0
AND `smart_projects`.`business_id` = 'cd9412774edb11e9'
GROUP BY `smart_projects`.`project_id`
ORDER BY `title` DESC
Comparision:
if (userProfile.AccountType == AccountType.Retailer)
{
//your code
}
In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:
if(userProfile != null)
{
if (userProfile.AccountType == AccountType.Retailer)
{
//your code
}
}
or shorter version:
if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
//your code
}
its very simple
add two part in code :
1- add namespace:
using Microsoft.Win32;
2-add application to registery :
RegistryKey key=Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("your_app_name", Application.ExecutablePath);
if you want delete app from registery:
key.DeleteValue("your_app_name",false);
The following will result in a comma separated list. Be sure to include a using statement for System.Linq
List<string> ls = new List<string>();
ls.Add("one");
ls.Add("two");
string type = ls.Aggregate((x,y) => x + "," + y);
will yield one,two
if you need a space after the comma, simply change the last line to string type = ls.Aggregate((x,y) => x + ", " + y);
You can try: Using the --authenticationDatabase flag helps.
mongo --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"
With n
being the line number:
ng
: Jump to line number n. Default is the start of the file.nG
: Jump to line number n. Default is the end of the file.So to go to line number 320123, you would type 320123g
.
Copy-pasted straight from Wikipedia.
(Update: If I could delete this answer I would, although since it's accepted, I can't. I'm updating the description to provide better guidance and discourage folks from using the poor practice I outlined in the original answer).
You can specify these parameters via context or environment parameters, such as in context.xml. See the sections titled "Context Parameters" and "Environment Entries" on this page:
http://tomcat.apache.org/tomcat-5.5-doc/config/context.html
As @netjeff points out, these values will be available via the Context.lookup(String) method and not as System parameters.
Another way to do specify these values is to define variables inside of the web.xml file of the web application you're deploying (see below). As @Roberto Lo Giacco points out, this is generally considered a poor practice since a deployed artifact should not be environment specific. However, below is the configuration snippet if you really want to do this:
<env-entry>
<env-entry-name>SMTP_PASSWORD</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>abc123ftw</env-entry-value>
</env-entry>
command prompt:
C:\Users\admin>java -version (Press Enter>
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
Use this.dispose
for current window to close and next_window.setVisible(true)
to show next window behind button property ActionPerformed
, Example is shown below in pic for your help.
I have created a working regular expression myself:
str=str.replace(/(<\?[a-z]*(\s[^>]*)?\?(>|$)|<!\[[a-z]*\[|\]\]>|<!DOCTYPE[^>]*?(>|$)|<!--[\s\S]*?(-->|$)|<[a-z?!\/]([a-z0-9_:.])*(\s[^>]*)?(>|$))/gi, '');
Broadcasting is really good for this:
row_sums = a.sum(axis=1)
new_matrix = a / row_sums[:, numpy.newaxis]
row_sums[:, numpy.newaxis]
reshapes row_sums from being (3,)
to being (3, 1)
. When you do a / b
, a
and b
are broadcast against each other.
You can learn more about broadcasting here or even better here.
I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:
multiDexEnabled true
And it worked!
Example
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
And clean the project.
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker
without a trailing /
doesn't fetch index.php
. Instead the server will issue a 302
redirect to the version with the trailing /
.
Doing a 302 will typically cause clients to convert a POST to a GET request.
I suggest you to look at this highly rated blog post which manages to give a solution to the problem you're facing :
http://www.inter-fuser.com/2009/09/live-camera-preview-in-android-emulator.html
His code is based on the current Android APIs and should work in your case given that you are using a recent Android API.
You can use
"Hello World ".replace(/\s+/g, '');
trim()
only removes trailing spaces on the string (first and last on the chain).
In this case this regExp is faster because you can remove one or more spaces at the same time.
If you change the replacement empty string to '$', the difference becomes much clearer:
var string= ' Q W E R TY ';
console.log(string.replace(/\s/g, '$')); // $$Q$$W$E$$$R$TY$
console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#
Performance comparison - /\s+/g
is faster. See here: http://jsperf.com/s-vs-s
Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.
Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe
, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.
I solved my issue with : Java Build Path -> JRE system library - > Edit -> Alternate JRE -> -> Finish
As it was configured to JDK folder so it was giving Exception
There's no C++ construct for breaking out of the loop in this case.
Either use a flag to interrupt the loop or (if appropriate) extract your code into a function and use return
.
Just use DataRow.IsNull. It has overrides accepting a column index, a column name, or a DataColumn object as parameters.
Example using the column index:
if (table.rows[0].IsNull(0))
{
//Whatever I want to do
}
And although the function is called IsNull
it really compares with DbNull
(which is exactly what you need).
What if I want to check for DbNull but I don't have a DataRow? Use Convert.IsDBNull.
Most of previous examples will raise an exception in case your string is not long enough.
Another approach is to use
'yourstring'.ljust(100)[:100].strip()
.
This will give you first 100 chars. You might get a shorter string in case your string last chars are spaces.
You can simply git pull origin branchB
into your branchA
and git will do the trick for you.
I just ran into this and it was due to a mod_authnz_ldap misconfiguration in my .htaccess file. Absolutely nothing was being logged, but I kept getting a 500 error.
If you run into this particular issue, you can change the log level of mod_authnz_ldap like so:
LogLevel warn authnz_ldap_module:debug
That will use a log level of debug for mod_authnz_ldap but warn for everything else (https://httpd.apache.org/docs/2.4/en/mod/core.html#loglevel).
Just use /\s+/ against '' as a splitter. In this case all "extra" blanks were removed. Usually this particular behaviour is required. So, in you case it will be:
my $line = "file1.gz file1.gz file3.gz";
my @abc = split(/\s+/, $line);
Given $arrService = Get-Service -Name $ServiceName
, $arrService.Status
is a static property, corresponding to the value at the time of the call. Use $arrService.Refresh()
when needed to renew the properties to current values.
MSDN ~ ServiceController.Refresh()
Refreshes property values by resetting the properties to their current values.
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
In your case, sort the dict by key before plotting,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
:1,.d
deletes lines 1 to current.
:1,.-1d
deletes lines 1 to above current.
(Personally I'd use dgg
or kdgg
like the other answers, but TMTOWTDI.)
It worked using PSCP. Instructions:
set PATH=<path to the pscp.exe file>
pscp
use the following command to copy file form remote server to the local system
pscp [options] [user@]host:source target
So to copy the file /etc/hosts
from the server example.com
as user fred
to the file
c:\temp\example-hosts.txt
, you would type:
pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt
If you are using com.google.android.gms:play-services-maps:16.0.0
or below and your app is targeting API level 28 (Android 9.0) or above, you must include the following declaration within the element of AndroidManifest.xml
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
Check this link - https://developers.google.com/maps/documentation/android-sdk/config#specify_requirement_for_apache_http_legacy_library
You have endless loop in place:
function save() {
var filename = id('filename').value;
var name = id('name').value;
var text = id('text').value;
save(filename, name, text);
}
No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.
The ng g component plainsight/some-name
makes a new directory when we use it.
The final output will be:
plainsight/some-name/some-name.component.ts
To avoid that, make use of the flat option ng g component plainsight/some-name --flat
and it will generate the files without making a new folder
plainsight/some-name.component.ts
If you're using SELinux, just type:
sudo chcon -v -R --type=httpd_sys_content_t /path/to/www/
This will fix permission issue.
Quick one-liner to convert UTF-8 characters into their 3-byte format:
var="$(echo -n '?' | od -An -tx1)"; printf '\\x%s' ${var^^}; echo
getArguments()
setArguments()
methods seem very useful when it comes to instantiating a Fragment using a static method.
ieMyfragment.createInstance(String msg)
How to do it?
Fragment code
public MyFragment extends Fragment {
private String displayMsg;
private TextView text;
public static MyFragment createInstance(String displayMsg)
{
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.setString("KEY",displayMsg);
fragment.setArguments(args); //set
return fragment;
}
@Override
public void onCreate(Bundle bundle)
{
displayMsg = getArguments().getString("KEY"): // get
}
@Override
public View onCreateView(LayoutInlater inflater, ViewGroup parent, Bundle bundle){
View view = inflater.inflate(R.id.placeholder,parent,false);
text = (TextView)view.findViewById(R.id.myTextView);
text.setText(displayMsg) // show msg
returm view;
}
}
Let's say you want to pass a String while creating an Instance. This is how you will do it.
MyFragment.createInstance("This String will be shown in textView");
1) Why Myfragment.getInstance(String msg) is preferred over new MyFragment(String msg)?
2) Sample code on Fragments
package com.android.jigsawtest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SurafaceClass extends SurfaceView implements
SurfaceHolder.Callback {
Bitmap mBitmap;
Paint paint =new Paint();
public SurafaceClass(Context context) {
super(context);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
// TODO Auto-generated constructor stub
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(mBitmap, 0, 0, paint);
}
}
If you get to the bottom of this list and find this answer, I am almost sure it will solve all your issues :)
In my case, I had dropped a database table and I was not getting anywhere with makemigrations
and migrate
So I got a very detailed answer on how to reset everything on this link
There are 3 ways to solve this question:
In particular there is a lot of confusion around #2 and #3, as seen in comments to amfcosta's answer. That answer will yield unpredictable color results anytime you'd like to set the progressbar to anything except primary colors, as it only modifies the background color, and the actual progress bar "clip" area will still be a yellow overlay with reduced opacity. For example, using that method to set the background to dark purple will result in a progress bar "clip" color of some crazy pinkish color resulting from dark purple and yellow mixing via reduced alpha.
So anyhow, #1 is answered perfectly by Ryan and Štarke answers most of #3, but for those looking for a complete solution to #2 and #3:
res/drawable/my_progressbar.xml:
Create this file but change the colors in my_progress and my_secondsProgress:
(NOTE: This is just a copy of the actual XML file defining the default android SDK ProgressBar, but I've changed the IDs and Colors. The original is named progress_horizontal)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/my_progress_background">
<shape>
<corners android:radius="5dip" />
<gradient
android:startColor="#ff9d9e9d"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:angle="270"
/>
</shape>
</item>
<item android:id="@+id/my_secondaryProgress">
<clip>
<shape>
<corners android:radius="5dip" />
<gradient
android:startColor="#80ff171d"
android:centerColor="#80ff1315"
android:centerY="0.75"
android:endColor="#a0ff0208"
android:angle="270"
/>
</shape>
</clip>
</item>
<item android:id="@+id/my_progress">
<clip>
<shape>
<corners android:radius="5dip" />
<gradient
android:startColor="#7d2afdff"
android:centerColor="#ff2afdff"
android:centerY="0.75"
android:endColor="#ff22b9ba"
android:angle="270"
/>
</shape>
</clip>
</item>
In your Java:
final Drawable drawable;
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < 16) {
drawable = ctx.getResources().getDrawable(R.drawable.my_progressbar);
} else {
drawable = ContextCompat.getDrawable(ctx, R.drawable.my_progressbar);
}
progressBar.setProgressDrawable(drawable)
EDIT: I found the time to solve this properly. My former answer left this a bit ambiguous.
A ProgressBar is composed as 3 Drawables in a LayerDrawable.
In the example below I'll change the color of the main progress bar to cyan.
//Create new ClipDrawable to replace the old one
float pxCornerRadius = viewUtils.convertDpToPixel(5);
final float[] roundedCorners = new float[] { pxCornerRadius, pxCornerRadius, pxCornerRadius, pxCornerRadius, pxCornerRadius, pxCornerRadius, pxCornerRadius, pxCornerRadius };
ShapeDrawable shpDrawable = new ShapeDrawable(new RoundRectShape(roundedCorners, null, null));
shpDrawable.getPaint().setColor(Color.CYAN);
final ClipDrawable newProgressClip = new ClipDrawable(shpDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
//Replace the existing ClipDrawable with this new one
final LayerDrawable layers = (LayerDrawable) progressBar.getProgressDrawable();
layers.setDrawableByLayerId(R.id.my_progress, newProgressClip);
That example set it to a solid color. You may set it to a gradient color by replacing
shpDrawable.getPaint().setColor(Color.CYAN);
with
Shader shader = new LinearGradient(0, 0, 0, progressBar.getHeight(), Color.WHITE, Color.BLACK, Shader.TileMode.CLAMP);
shpDrawable.getPaint().setShader(shader);
Cheers.
-Lance
Define the range between the numbers:
r = range(1,10)
Then use it:
if num in r:
print("All right!")
I just made a simple test to see how instanceOf performance is comparing to a simple s.equals() call to a string object with only one letter.
in a 10.000.000 loop the instanceOf gave me 63-96ms, and the string equals gave me 106-230ms
I used java jvm 6.
So in my simple test is faster to do a instanceOf instead of a one character string comparison.
using Integer's .equals() instead of string's gave me the same result, only when I used the == i was faster than instanceOf by 20ms (in a 10.000.000 loop)
here is my answer:
public class WigetControl {
private Resources res;
public WigetControl(Resources res)
{
this.res = res;
}
public void setButtonDisable(Button mButton)
{
mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
mButton.setEnabled(false);
}
}
and the call can be like this:
WigetControl control = new WigetControl(getResources());
control.setButtonDisable(btNext);
To select the sibling, you'd need something like:
$(this).next();
So, Shog9's comment is not correct. First of all, you'd need to name the variable "clicked" outside of the div click function, otherwise, it is lost after the click occurs.
var clicked;
$("div a").click(function(){
clicked = $(this).next();
// Do what you need to do to the newly defined click here
});
// But you can also access the "clicked" element here
You probably need to chdir to the correct directory before calling the script. This way you can ensure what directory your script is "in" before calling the shell command.
$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh var1 var2');
chdir($old_path);
I find this useful:
function Get-Version($filePath)
{
$name = @{Name="Name";Expression= {split-path -leaf $_.FileName}}
$path = @{Name="Path";Expression= {split-path $_.FileName}}
dir -recurse -path $filePath | % { if ($_.Name -match "(.*dll|.*exe)$") {$_.VersionInfo}} | select FileVersion, $name, $path
}
SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2®ion=0&page=1', LEN(URL))
Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx
The Extensible Markup Language (XML) 1.0 only includes the block comments.
I like using this method:
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
Usage:
if ( isFunction(me.onChange) ) {
me.onChange(str); // call the function with params
}
If you have something else altering the DB (say another process) and need to ensure you see these changes, use AsNoTracking()
, otherwise EF may give you the last copy that your context had instead, hence it being good to usually use a new context every query:
http://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/
Try this:
@RequestBody(required = false) String str
If you have pip
installed (you should have it until you use Python 3.5), list the installed Python packages, like this:
$ pip list | grep -i keras
Keras (1.1.0)
If you don’t see Keras, it means that the previous installation failed or is incomplete (this lib has this dependancies: numpy (1.11.2), PyYAML (3.12), scipy (0.18.1), six (1.10.0), and Theano (0.8.2).)
Consult the pip.log
to see what’s wrong.
You can also display your Python path like this:
$ python3 -c 'import sys, pprint; pprint.pprint(sys.path)'
['',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']
Make sure the Keras library appears in the /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages
path (the path is different on Ubuntu).
If not, try do uninstall it, and retry installation:
$ pip uninstall Keras
It’s a bad idea to use and pollute your system-wide Python. I recommend using a virtualenv (see this guide).
The best usage is to create a virtualenv
directory (in your home, for instance), and store your virtualenvs in:
cd virtualenv/
virtualenv -p python3.5 py-keras
source py-keras/bin/activate
pip install -q -U pip setuptools wheel
Then install Keras:
pip install keras
You get:
$ pip list
Keras (1.1.0)
numpy (1.11.2)
pip (8.1.2)
PyYAML (3.12)
scipy (0.18.1)
setuptools (28.3.0)
six (1.10.0)
Theano (0.8.2)
wheel (0.30.0a0)
But, you also need to install extra libraries, like Tensorflow:
$ python -c "import keras"
Using TensorFlow backend.
Traceback (most recent call last):
...
ImportError: No module named 'tensorflow'
The installation guide of TesnsorFlow is here: https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation
I had the same problem with openCV on Raspberry Pi... don't know if this can solve your problem, but what worked for me was
import time
import cv2
cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,1024)
time.sleep(2)
cap.set(15, -8.0)
the time you have to use can be different
It seems old thread, but Java has evolved since then & introduced Streams & Lambdas in Java 8. So might help everyone who want to do it using Java 8 features.
Arrays.stream(<arr>)
. Once you have stream of String array elements, you can use mapToDouble(s -> Double.parseDouble(s))
which will convert stream of Strings into stream of doubles.Stream.collect(supplier, accumulator, combiner)
to calculate average if you want to control incremental calculation yourselves. Here is some good example.Collectors.averagingDouble()
which directly calculates and returns average. some examples here.And another solution
$objectData = DB::table('user')
->select('column1', 'column2')
->where('name', '=', 'Jhon')
->get();
$arrayData = array_map(function($item) {
return (array)$item;
}, $objectData->toArray());
It good in case when you need only several columns from entity.
In case of temporary tables, you might want to try
SELECT 'DROP TABLE "' + t.name + '"'
FROM tempdb.sys.tables t
WHERE t.name LIKE '[prefix]%'
Using the new FormData object (and other ES6 stuff), you can do this to turn your entire form into JSON:
let data = {};
let formdata = new FormData(theform);
for (let tuple of formdata.entries()) data[tuple[0]] = tuple[1];
and then just xhr.send(JSON.stringify(data));
like in Jan's original answer.
(For those who stumble upon this from your search engine of choice)
This just recursively traces down the folder, so you don't need to duplicate your code twice. Also the OPs logic is needlessly complex.
Wscript.Echo "begin."
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSuperFolder = objFSO.GetFolder(WScript.Arguments(0))
Call ShowSubfolders (objSuperFolder)
Wscript.Echo "end."
WScript.Quit 0
Sub ShowSubFolders(fFolder)
Set objFolder = objFSO.GetFolder(fFolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
Wscript.Echo objFile.Name
End If
Next
For Each Subfolder in fFolder.SubFolders
ShowSubFolders(Subfolder)
Next
End Sub
You could also use string[] something = text.Split('@')
. Make sure you use single quotes to surround the "@" to store it as a char
type.
This will store the characters up to and including each "@" as individual words in the array. You can then output each (element + System.Environment.NewLine
) using a for loop or write it to a text file using System.IO.File.WriteAllLines([file path + name and extension], [array name])
. If the specified file doesn't exist in that location it will be automatically created.
From the docs:
_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.
So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.
Edit: Further reading led me here:
http://www.analyticsmarket.com/blog/edit-ecommerce-data
Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.
Do you mean this?
def perform(fun, *args):
fun(*args)
def action1(args):
# something
def action2(args):
# something
perform(action1)
perform(action2, p)
perform(action3, p, r)
I think I might have been overthinking this. One way I've come up with that does the job, is simply to have a global variable, that accumulates the diagnostic data.
Somthing like this:
log1 = dict()
class TestBar(unittest.TestCase):
def runTest(self):
for t1, t2 in testdata:
f = Foo(t1)
if f.bar(t2) != 2:
log1("TestBar.runTest") = (f, t1, t2)
self.fail("f.bar(t2) != 2")
Thanks for the replies. They have given me some alternative ideas for how to record information from unit tests in python.
You may use
par(las=2) # make label text perpendicular to axis
It is written here: http://www.statmethods.net/graphs/bar.html
value = value.setScale(2, RoundingMode.CEILING)
I ran into this problem when SQL Server 2014 standard was installed on a server where SQL Server Express was also installed. I had opened SSMS from a desktop shortcut, not realizing right away that it was SSMS for SQL Server Express, not for 2014. SSMS for Express returned the error, but SQL Server 2014 did not.
You can also use glob
for this:
$dirname = "media/images/iconized/";
$images = glob($dirname."*.png");
foreach($images as $image) {
echo '<img src="'.$image.'" /><br />';
}
You can accomplish this via method overloading.
public int doSomething(int arg1, int arg2)
{
return 0;
}
public int doSomething()
{
return doSomething(defaultValue0, defaultValue1);
}
By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.
To send javascript obj to php using json and ajax:
js:
var dataPost = {
"var": "foo"
};
var dataString = JSON.stringify(dataPost);
$.ajax({
url: 'server.php',
data: {myData: dataString},
type: 'POST',
success: function(response) {
alert(response);
}
});
to use that object in php:
$obj = json_decode($_POST["myData"]);
echo $obj->var;
If you are a Xamarin user, this is the solution:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle); //always call superclass first
this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);
LoadApplication(new App());
}
you can do it like this with raw javascript
<html>
<body>
<form id="my_form" method="post" action="mailto://[email protected]">
<a href="javascript:{}" onclick="document.getElementById('my_form').submit();">submit</a>
</form>
</body>
</html>
For those asking why I have a href
element in my anchor tag, its because it's a compulsory part of an anchor tag, it may well work without but it's not to spec. So if you want to guarantee rendering etc you must give the engine a fully formed tag. So the above achieves this. You will see href="#"
used sometimes but this is not always wanted as the browser will change the page position.
The other way to see it in windows command line :
tasklist /fi "imagename eq nginx.exe"
INFO: No tasks are running which match the specified criteria.
if there is a running nginx you will see them
You are confusing objects and collections of objects. Specifically, you are confusing binary flags with sets of binary flags. A proper solution would look like this:
// These are individual flags
enum AnimalFlag // Flag, not Flags
{
HasClaws = 0,
CanFly,
EatsFish,
Endangered
};
class AnimalFlagSet
{
int m_Flags;
public:
AnimalFlagSet() : m_Flags(0) { }
void Set( AnimalFlag flag ) { m_Flags |= (1 << flag); }
void Clear( AnimalFlag flag ) { m_Flags &= ~ (1 << flag); }
bool Get( AnimalFlag flag ) const { return (m_Flags >> flag) & 1; }
};
From the bash manpage
wait [n ...]
Wait for each specified process and return its termination status
Each n may be a process ID or a job specification; if a
job spec is given, all processes in that job's pipeline are
waited for. If n is not given, all currently active child processes
are waited for, and the return status is zero. If n
specifies a non-existent process or job, the return status is
127. Otherwise, the return status is the exit status of the
last process or job waited for.
I tried all of the above suggestions, which did not work for me, but I found how to fix the error in my case.
The following steps made the project compile succesfully:
In project explorer, right-click on project, select “properties” In the tree on the right, go to Java build path. Select the tab “libraries”. Click “Add library”. Select JRE system library. Click next. Select radio button Alternate JRE. Click “installed JRE’s”. Select the JRE with the right version. Click Appy and close. In the next screen, click finish. In the properties window, click Apply and close. In the project explorer, right-click your pom.xml and select run as > maven build In the goal textbox, write “install”. Click Run.
This made the project build succesfully in my case.
There has been enough answers on RUN and CMD. I just want to add a few words on ENTRYPOINT. CMD arguments can be overwritten by command line arguments, while ENTRYPOINT arguments are always used.
This article is a good source of information.
You are looking for map_keys, with it you can write things like
BOOST_FOREACH(const key_t key, the_map | boost::adaptors::map_keys)
{
// do something with key
}
REM
Search for the CONFIG file, if this doesn't exit then the user doesn't have the .Net framework 2.0
`
SET FileName=%windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG
IF EXIST %FileName% GOTO INSTALL_DIALER
ECHO.You currently do not have the Microsoft(c) .NET Framework 2.0 installed.
Git is just trying to guess for you what you are trying to do. It is making every attempt to preserve unbroken history. Of course, it is not perfect. So git mv
allows you to be explicit with your intention and to avoid some errors.
Consider this example. Starting with an empty repo,
git init
echo "First" >a
echo "Second" >b
git add *
git commit -m "initial commit"
mv a c
mv b a
git status
Result:
# On branch master
# Changes not staged for commit:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: a
# deleted: b
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# c
no changes added to commit (use "git add" and/or "git commit -a")
Autodetection failed :( Or did it?
$ git add *
$ git commit -m "change"
$ git log c
commit 0c5425be1121c20cc45df04734398dfbac689c39
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:24:56 2013 -0400
change
and then
$ git log --follow c
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:24:56 2013 -0400
change
commit 50c2a4604a27be2a1f4b95399d5e0f96c3dbf70a
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:24:45 2013 -0400
initial commit
Now try instead (remember to delete the .git
folder when experimenting):
git init
echo "First" >a
echo "Second" >b
git add *
git commit -m "initial commit"
git mv a c
git status
So far so good:
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# renamed: a -> c
git mv b a
git status
Now, nobody is perfect:
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: a
# deleted: b
# new file: c
#
Really? But of course...
git add *
git commit -m "change"
git log c
git log --follow c
...and the result is the same as above: only --follow
shows the full history.
Now, be careful with renaming, as either option can still produce weird effects. Example:
git init
echo "First" >a
git add a
git commit -m "initial a"
echo "Second" >b
git add b
git commit -m "initial b"
git mv a c
git commit -m "first move"
git mv b a
git commit -m "second move"
git log --follow a
commit 81b80f5690deec1864ebff294f875980216a059d
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:35:58 2013 -0400
second move
commit f284fba9dc8455295b1abdaae9cc6ee941b66e7f
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:34:54 2013 -0400
initial b
Contrast it with:
git init
echo "First" >a
git add a
git commit -m "initial a"
echo "Second" >b
git add b
git commit -m "initial b"
git mv a c
git mv b a
git commit -m "both moves at the same time"
git log --follow a
Result:
commit 84bf29b01f32ea6b746857e0d8401654c4413ecd
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:37:13 2013 -0400
both moves at the same time
commit ec0de3c5358758ffda462913f6e6294731400455
Author: Sergey Orshanskiy <*****@gmail.com>
Date: Sat Oct 12 00:36:52 2013 -0400
initial a
Ups... Now the history is going back to initial a instead of initial b, which is wrong. So when we did two moves at a time, Git became confused and did not track the changes properly. By the way, in my experiments the same happened when I deleted/created files instead of using git mv
. Proceed with care; you've been warned...
From the proverbial horse's mouth...
When developing your app, you may find it necessary to share data, context or services globally across your app. For example, if your app has session data, such as the currently logged-in user, you will likely want to expose this information. In Android, the pattern for solving this problem is to have your android.app.Application instance own all global data, and then treat your Application instance as a singleton with static accessors to the various data and services.
When writing an Android app, you're guaranteed to only have one instance of the android.app.Application class, and so it's safe (and recommended by Google Android team) to treat it as a singleton. That is, you can safely add a static getInstance() method to your Application implementation. Like so:
public class AndroidApplication extends Application {
private static AndroidApplication sInstance;
public static AndroidApplication getInstance(){
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
}
With jQuery, you can try to call trigger:
$(window).trigger('resize');
Importing large sql file to MySql via command line
Example: mysql -u root -p aanew < aanew.sql
A complex filter condition is better in performance perspective, but the best performance will show old fashion for loop with a standard if clause
is the best option. The difference on a small array 10 elements difference might ~ 2 times, for a large array the difference is not that big.
You can take a look on my GitHub project, where I did performance tests for multiple array iteration options
For small array 10 element throughput ops/s: For medium 10,000 elements throughput ops/s: For large array 1,000,000 elements throughput ops/s:
NOTE: tests runs on
UPDATE: Java 11 has some progress on the performance, but the dynamics stay the same
You could use penlight library. This has a function size
which gives the actual size of the table.
It has implemented many of the function that we may need while programming and missing in Lua.
Here is the sample for using it.
> tablex = require "pl.tablex"
> a = {}
> a[2] = 2
> a[3] = 3
> a['blah'] = 24
> #a
0
> tablex.size(a)
3
I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.
Use it like:
var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]
Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().
If you're trying to do stuff with the Java default system keystore (cacerts
), then the default password is changeit
.
You can list keys without needing the password (even if it prompts you) so don't take that as an indication that it is blank.
(Incidentally who in the history of Java ever has changed the default keystore password? They should have left it blank.)
You can use a ternary operator
echo false ? 'true' : 'false';
More cleaner way using LINQ
var lines = dictionary.Select(kvp => kvp.Key + ": " + kvp.Value.ToString());
textBox3.Text = string.Join(Environment.NewLine, lines);
I use
ps -C "keyword" -o pid=
This command should give you a PID number.
For a API v3 solution, refer to:
http://blog.enbake.com/draw-circle-with-google-maps-api-v3
It creates circle around points and then show markers within and out of the range with different colors. They also calculate dynamic radius but in your case radius is fixed so may be less work.
Another thing to try is to re-install ca-certificates
as detailed here.
# yum reinstall ca-certificates
...
# update-ca-trust force-enable
# update-ca-trust extract
And another thing to try is to explicitly allow the one site's certificate in question as described here (especially if the one site is your own server and you already have the .pem in reach).
# cp /your/site.pem /etc/pki/ca-trust/source/anchors/
# update-ca-trust extract
I was running into this exact SO error after upgrading to PHP 5.6 on CentOS 6 trying to access the server itself which has a cheapsslsecurity certificate which maybe it needed to be updated, but instead I installed a letsencrypt certificate and with these two steps above it did the trick. I don't know why the second step was necessary.
Useful Commands
View openssl version:
# openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013
View PHP cli ssl current settings:
# php -i | grep ssl
openssl
Openssl default config => /etc/pki/tls/openssl.cnf
openssl.cafile => no value => no value
openssl.capath => no value => no value
The error you are getting is either because you are doing TO_DATE
on a column that's already a date, and you're using a format mask that is different to your nls_date_format
parameter[1] or because the event_occurrence column contains data that isn't a number.
You need to a) correct your query so that it's not using TO_DATE on the date column, and b) correct your data, if event_occurrence is supposed to be just numbers.
And fix the datatype of that column to make sure you can only store numbers.
[1] What Oracle does when you do: TO_DATE(date_column, non_default_format_mask)
is:
TO_DATE(TO_CHAR(date_column, nls_date_format), non_default_format_mask)
Generally, the default nls_date_format
parameter is set to dd-MON-yy
, so in your query, what is likely to be happening is your date column is converted to a string in the format dd-MON-yy, and you're then turning it back to a date using the format MMDD. The string is not in this format, so you get an error.
You're missing comma (,
) inbetween:
>>> ((1,2) (2,3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
Put comma:
>>> ((1,2), (2,3))
((1, 2), (2, 3))
If you're using React, I can recommend react-animate-height:
<AnimateHeight height={isOpen ? 'auto' : 0}>
// your content goes here
</AnimateHeight>
If you only need the docker process to go in the background you can use
Ctrl + Z
Be aware that it is not a real detach and it comes with a performance penalty.
(You can return it to foreground with the bg
command).
Another option is to just close your terminal, if you don't need it any longer.
If the link is to a valid file url, simply assigning window.location.href will work.
However, sometimes the link is not valid, and an iFrame is required.
Do your normal event.preventDefault to prevent the window from opening, and if you are using jQuery, this will work:
$('<iframe>').attr('src', downloadThing.attr('href')).appendTo('body').on("load", function() {
$(this).remove();
});
As some of the comments above mentioned, the transpose of 1D arrays are 1D arrays, so one way to transpose a 1D array would be to convert the array to a matrix like so:
np.transpose(a.reshape(len(a), 1))
Illegal State Exception is an Unchecked exception.
It indicate that method has been invoked at wrong time.
example:
Thread t = new Thread();
t.start();
//
//
t.start();
output:
Runtime Excpetion: IllegalThreadStateException
We cant start the Thread again, it will throw IllegalStateException.
I think there are two issues:
Explanation:
I checked one of mine, I have the pattern:
<a href="file://///server01\fshare\dir1\dir2\dir3">useful link </a>
Please note that we ended up with 5 slashes after the protocol (file:
)
Firefox will try to prevent cross site scripting. My solution was to modify prefs.js in the profile directory. You will add two lines:
user_pref("capability.policy.localfilelinks.checkloaduri.enabled", "allAccess");
user_pref("capability.policy.localfilelinks.sites", "http://mysite.company.org");
A. Wolff was leading you in the right direction. There are several attributes where you should not be setting a string value. You must toggle it with a boolean true
or false
.
.attr("hidden", false)
will remove the attribute the same as using .removeAttr("hidden")
.
.attr("hidden", "false")
is incorrect and the tag remains hidden.
You should not be setting hidden
, checked
, selected
, or several others to any string value to toggle it.
Well I'm really late to the party, but for what it is worth, I have blogged about this very subject whereby I create a EnumHelper
class that enables very easy transformation.
http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23
In your controller:
//If you don't have an enum value use the type
ViewBag.DropDownList = EnumHelper.SelectListFor<MyEnum>();
//If you do have an enum value use the value (the value will be marked as selected)
ViewBag.DropDownList = EnumHelper.SelectListFor(MyEnum.MyEnumValue);
In your View:
@Html.DropDownList("DropDownList")
@* OR *@
@Html.DropDownListFor(m => m.Property, ViewBag.DropDownList as SelectList, null)
The helper class:
public static class EnumHelper
{
// Get the value of the description attribute if the
// enum has one, otherwise use the value.
public static string GetDescription<TEnum>(this TEnum value)
{
var fi = value.GetType().GetField(value.ToString());
if (fi != null)
{
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
}
return value.ToString();
}
/// <summary>
/// Build a select list for an enum
/// </summary>
public static SelectList SelectListFor<T>() where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null
: new SelectList(BuildSelectListItems(t), "Value", "Text");
}
/// <summary>
/// Build a select list for an enum with a particular value selected
/// </summary>
public static SelectList SelectListFor<T>(T selected) where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null
: new SelectList(BuildSelectListItems(t), "Text", "Value", selected.ToString());
}
private static IEnumerable<SelectListItem> BuildSelectListItems(Type t)
{
return Enum.GetValues(t)
.Cast<Enum>()
.Select(e => new SelectListItem { Value = e.ToString(), Text = e.GetDescription() });
}
}
You can use the standard isspace() function in ctype.h to achieve this. Simply compare the beginning and end characters of your character array until both ends no longer have spaces.
"spaces" include:
' ' (0x20) space (SPC)
'\t' (0x09) horizontal tab (TAB)
'\n' (0x0a) newline (LF)
'\v' (0x0b) vertical tab (VT)
'\f' (0x0c) feed (FF)
'\r' (0x0d) carriage return (CR)
although there is no function which will do all of the work for you, you will have to roll your own solution to compare each side of the given character array repeatedly until no spaces remain.
Edit:
Since you have access to C++, Boost has a trim implementation waiting for you to make your life a lot easier.
It is best practice to NOT use UNDERSCORES before any variable name or parameter name in C++
Names beginning with an underscore or a double underscore are RESERVED for the C++ implementers. Names with an underscore are reserved for the library to work.
If you have a read at the C++ Coding Standard, you will see that in the very first page it says:
"Don't overlegislate naming, but do use a consistent naming convention: There are only two must-dos: a) never use "underhanded names," ones that begin with an underscore or that contain a double underscore;" (p2 , C++ Coding Standards, Herb Sutter and Andrei Alexandrescu)
More specifically, the ISO working draft states the actual rules:
In addition, some identifiers are reserved for use by C ++ implementations and shall not be used otherwise; no diagnostic is required. (a) Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use. (b) Each identifier that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
It is best practice to avoid starting a symbol with an underscore in case you accidentally wander into one of the above limitations.
You can see it for yourself why such use of underscores can be disastrous when developing a software:
Try compiling a simple helloWorld.cpp program like this:
g++ -E helloWorld.cpp
You will see all that happens in the background. Here is a snippet:
ios_base::iostate __err = ios_base::iostate(ios_base::goodbit);
try
{
__streambuf_type* __sb = this->rdbuf();
if (__sb)
{
if (__sb->pubsync() == -1)
__err |= ios_base::badbit;
else
__ret = 0;
}
You can see how many names begin with double underscore!
Also if you look at virtual member functions, you will see that *_vptr is the pointer generated for the virtual table which automatically gets created when you use one or more virtual member functions in your class! But that's another story...
If you use underscores you might get into conflict issues and you WILL HAVE NO IDEA what's causing it, until it's too late.
The answer of @alexandre with base64 does the trick.
The explanation why that works for IE is here
https://en.m.wikipedia.org/wiki/Data_URI_scheme
Under header 'format' where it says
Some browsers (Chrome, Opera, Safari, Firefox) accept a non-standard ordering if both ;base64 and ;charset are supplied, while Internet Explorer requires that the charset's specification must precede the base64 token.
The DATEDIFF function can give you the number of days between two dates. Which is more accurate, since... how do you define a month? (28, 29, 30, or 31 days?)
Mono is a runtime environment that can run .NET applications and that works on both Windows and Linux. It includes a C# compiler.
As an IDE, you could use MonoDevelop, and I suppose there's something available for Eclipse, too.
Note that WinForms support on Mono is there, but somewhat lacking. Generally, Mono developers seem to prefer different GUI toolkits such as Gtk#.
run this on Terminal:
sh "/Library/Application Support/Jenkins/Uninstall.command"
I experienced this issue when trying to restore a database on MS SQL Server 2012.
Here's what worked for me:
I had to first run the RESTORE FILELISTONLY
command below on the backup file to list the logical file names:
RESTORE FILELISTONLY
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
This displayed the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively:
LogicalName PhysicalName
com.my_db C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf
com.my_db_log C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf
All I had to do was to simply replace the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively in my database restore script:
USE master;
GO
ALTER DATABASE my_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
RESTORE DATABASE my_db
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
WITH REPLACE,
MOVE 'com.my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf',
MOVE 'com.my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf'
GO
ALTER DATABASE my_db SET MULTI_USER;
GO
And the Database Restore task ran successfully:
That's all.
I hope this helps
just enter in the directory in which your c/cpp file is.
for compiling and running c code.
$gcc filename.c
$./a.out filename.c
for compiling and running c++ code.
$g++ filename.cpp
$./a.out filename.cpp
"$" is default mac terminal symbol
You can use boost::lexical_cast:
#include <iostream>
#include <boost/lexical_cast.hpp>
int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;
try {
i = boost::lexical_cast<int>( s1 );
}
catch( boost::bad_lexical_cast & e ){
std::cout << "Exception caught : " << e.what() << std::endl;
}
try {
i = boost::lexical_cast<int>( s2 );
}
catch( boost::bad_lexical_cast & e ){
std::cout << "Exception caught : " << e.what() << std::endl;
}
return 0;
}
Here my working code using in React with Bootstrap
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<style>
@media (min-width: 768px) and (max-width: 1000px) {
.navbar-collapse.collapse {
display: none !important;
}
.navbar-toggle{
display: block !important;
}
.navbar-header{
float: none;
}
}
</style>
numpy.array
s are designed just for this case:
numpy.zeros((i,j,k))
will give you an array of dimensions ijk, filled with zeroes.
depending what you need it for, numpy may be the right library for your needs.
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
List does not implement IBindingList
so the grid does not know about your new items.
Bind your DataGridView to a BindingList<T>
instead.
var list = new BindingList<Person>(persons);
myGrid.DataSource = list;
But I would even go further and bind your grid to a BindingSource
var list = new List<Person>()
{
new Person { Name = "Joe", },
new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;
I had same issue and the solution was to rename name
field in package.json (remove white spaces)
If you want to scroll entire page to the bottom:
var scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;
See the sample on JSFiddle
If you want to scroll an element to the bottom:
function gotoBottom(id){
var element = document.getElementById(id);
element.scrollTop = element.scrollHeight - element.clientHeight;
}
And that's how it works:
Ref: scrollTop, scrollHeight, clientHeight
UPDATE: Latest versions of Chrome (61+) and Firefox does not support scrolling of body, see: https://dev.opera.com/articles/fixing-the-scrolltop-bug/
If you're trying to avoid loading jquery until your content has been loaded, the best way is to simply put the reference to it in the bottom of your page, like many other answers have said.
Use a CDN. This way, your site can use the cached version a user likely has on their computer. The //
at the beginning allows it to be called (and use the same resource) whether it's http or https. Example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Using a CDN has a couple of big benefits: it makes it more likely that users have it cached from another site, so there will be no download (and no render-blocking). Further, CDNs use the closest, fastest connection available, meaning that if they do need to load it, it will probably be faster than connecting to your server. More info from Google.
Put scripts at the bottom. Move as much of your js to the bottom of the page as possible. I use php to include a file with all my JS resources below the footer.
If you're using a template system, you may need to have javascript spread throughout the html output. If you're using jquery in scripts that get called as the page renders, this will cause errors. To have your scripts wait until jquery is loaded, put them into
window.onload() = function () { //... your js that isn't called by user interaction ... }
This will prevent errors but still run before user interaction and without timers.
Of course, if jquery is cached, it won't matter too much where you put it, except to page speed tools that will tell you you're blocking rendering.
First, disable the php5
module:
a2dismod php5
then, enable the php7
module:
a2enmod php7.0
Next, reload/restart the Apache service:
service apache2 restart
wrt the comment, you need to specify exact installed php-7.x version.
A lot of good answers already, but let me see if I can give you another viewpoint.
Simplifying things by quite a bit, you can view a framework as an application that is complete except for the actual functionality. You plug in the functionality and PRESTO! you have an application.
Consider, say, a GUI framework. The framework contains everything you need to make an application. Indeed you can often trivially make a minimal application with very few lines of source that does absolutely nothing -- but it does give you window management, sub-window management, menus, button bars, etc. That's the framework side of things. By adding your application functionality and "plugging it in" to the right places in the framework you turn this empty app that does nothing more than window management, etc. into a real, full-blown application.
There are similar types of frameworks for web apps, for server-side apps, etc. In each case the framework provides the bulk of the tedious, repetitive code (hopefully) while you provide the actual problem domain functionality. (This is the ideal. In reality, of course, the success of the framework is highly variable.)
I stress again that this is the simplified view of what a framework is. I'm not using scary terms like "Inversion of Control" and the like although most frameworks have such scary concepts built-in. Since you're a beginner, I thought I'd spare you the jargon and go with an easy simile.
If you need the "week ending" date this will work as well. This will count the number of records for each week. Example: If three work orders were created between (inclusive) 1/2/2010 and 1/8/2010 and 5 were created between (inclusive) 1/9/2010 and 1/16/2010 this would return:
3 1/8/2010
5 1/16/2010
I had to use the extra DATE() function to truncate my datetime field.
SELECT COUNT(*), DATE_ADD( DATE(wo.date_created), INTERVAL (7 - DAYOFWEEK( wo.date_created )) DAY) week_ending
FROM work_order wo
GROUP BY week_ending;
Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link
Youtube video about entire process.
Writeup with pictures about installing SQL Server
How to select a local server:
When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:
1) Make sure you have Server Type: Database
2) Make sure you have Authentication: Windows Authentication (no username & password)
3) For the server name field look to the right and select the drop down arrow, click 'browse for more'
4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14
How do I create a local database inside of Microsoft SQL Server 2014?
1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)
2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!
You could add a calculated column that includes only the date without the time. Between the two options, I'd go with the BETWEEN
operator because it's 'cleaner' to me and should make better use of indexes. Comparing execution plans would seem to indicate that BETWEEN
would be faster; however, in actual testing they performed the same.
This is the function I use in my JS:
function toArray(nl) {
for(var a=[], l=nl.length; l--; a[l]=nl[l]);
return a;
}
if you are using Glide and Kotlin,
Glide.with(this)
.asBitmap()
.load("https://...")
.addListener(object : RequestListener<Bitmap> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Bitmap>?,
isFirstResource: Boolean
): Boolean {
Toast.makeText(this@MainActivity, "failed: " + e?.printStackTrace(), Toast.LENGTH_SHORT).show()
return false
}
override fun onResourceReady(
resource: Bitmap?,
model: Any?,
target: Target<Bitmap>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
//image is ready, you can get bitmap here
var bitmap = resource
return false
}
})
.into(imageView)
Just write this query in your db phpmyadmin.
ALTER TABLE TableName ADD UNIQUE (FieldName)
Eg: ALTER TABLE user ADD UNIQUE (email)
If you have a SSHClient, you can also use open_sftp()
:
import paramiko
# lets say you have SSH client...
client = paramiko.SSHClient()
sftp = client.open_sftp()
# then you can use upload & download as shown above
...
Java 8 provides the option of using streams which can be used to sort int[] array
as:
int[] sorted = Arrays.stream(array).sorted().toArray(); // option 1
Arrays.parallelSort(array); //option 2
As mentioned in doc for parallelSort
:
The sorting algorithm is a parallel sort-merge that breaks the array into sub-arrays that are themselves sorted and then merged. When the sub-array length reaches a minimum granularity, the sub-array is sorted using the appropriate Arrays.sort method. If the length of the specified array is less than the minimum granularity, then it is sorted using the appropriate Arrays.sort method. The algorithm requires a working space no greater than the size of the original array. The ForkJoin common pool is used to execute any parallel tasks.
So if the input array is less than granularity (8192 elements in Java 9 and 4096 in Java 8 I believe), then parallelSort
simply calls sequential sort algorithm.
Just in case we want to reverse sort the integer array we can make use of comparator as:
int[] reverseSorted = IntStream.of(array).boxed()
.sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
Since Java has no way to sort primitives with custom comparator, we have to use intermediate boxing or some other third party library which implements such primitive sorting.
Like this:
#include <string>
#include <vector>
struct user
{
std::string username;
std::vector<unsigned char> userpassword;
};
int main()
{
user r; // r.username is "" and r.userpassword is empty
// ...
}
There are a lot of dependencies of anaconda that have changed over the past years and won't work if you used them now. Some of the answers need serious updation.
I found this command did the job for me :
conda install -c conda-forge xgboost
You may also want to look at the official documentation of anaconda for xgboost:
NOTE: Confirmed with Access 2003, don't know about earlier versions.
For a query in an MDB you can right-click in the query designer (anywhere in the empty space where the tables are), select Properties from the context menu, and enter text in the Description property.
You're limited to 256 characters, but it's better than nothing.
You can get at the description programatically with something like this:
Dim db As Database
Dim qry As QueryDef
Set db = Application.CurrentDb
Set qry = db.QueryDefs("myQuery")
Debug.Print qry.Properties("Description")
To keep your window open in case of exception (yet, while printing the exception)
if __name__ == '__main__':
try:
## your code, typically one function call
except Exception:
import sys
print sys.exc_info()[0]
import traceback
print traceback.format_exc()
print "Press Enter to continue ..."
raw_input()
To keep the window open in any case:
if __name__ == '__main__':
try:
## your code, typically one function call
except Exception:
import sys
print sys.exc_info()[0]
import traceback
print traceback.format_exc()
finally:
print "Press Enter to continue ..."
raw_input()
For Python3 you'll have to use input()
in place of raw_input()
, and of course adapt the print
statements.
if __name__ == '__main__':
try:
## your code, typically one function call
except BaseException:
import sys
print(sys.exc_info()[0])
import traceback
print(traceback.format_exc())
print("Press Enter to continue ...")
input()
To keep the window open in any case:
if __name__ == '__main__':
try:
## your code, typically one function call
except BaseException:
import sys
print(sys.exc_info()[0])
import traceback
print(traceback.format_exc())
finally:
print("Press Enter to continue ...")
input()
Scenario 1:
One scenario:
You use a package that gets removed from npm. If you have all the modules in the folder node_modules, then it won't be a problem for you. If you do only have the package name in the package.json, you can't get it anymore.
If a package is less than 24 hours old, you can easily remove it from npm. If it's older than 24 hours old, then you need to contact them.
But:
If you contact support, they will check to see if removing that version of your package would break any other installs. If so, we will not remove it.
So the chances for this are low, but there is scenario 2...
Scenario 2:
An other scenario where this is the case:
You develop an enterprise version of your software or a very important software and write in your package.json:
"dependencies": {
"studpid-package": "~1.0.1"
}
You use the method function1(x)
of that package.
Now the developers of studpid-package rename the method function1(x)
to function2(x)
and they make a fault...
They change the version of their package from 1.0.1
to 1.1.0
.
That's a problem because when you call npm install
the next time, you will accept version 1.1.0
because you used the tilde ("studpid-package": "~1.0.1"
).
Calling function1(x)
can cause errors and problems now.
Pushing the whole node_modules folder (often more than 100 MB) to your repository, will cost you memory space. A few kb (package.json only) compared with hundreds of MB (package.json & node_modules)... Think about it.
You could do it / should think about it if:
the software is very important.
it costs you money when something fails.
you don't trust the npm registry. npm is centralized and could theoretically be shut down.
You don't need to publish the node_modules folder in 99.9% of the cases if:
you develop a software just for yourself.
you've programmed something and just want to publish the result on GitHub because someone else could maybe be interested in it.
If you don't want the node_modules to be in your repository, just create a .gitignore
file and add the line node_modules
.
This answer might not be 100% relevant to the question. But it does address the problem. I found this simple way of achieving this requirement. Code goes below:
<a href="@Url.Action("Display", "Customer")?custId={{cust.Id}}"></a>
In the above example {{cust.Id}} is an AngularJS variable. However one can replace it with a JavaScript variable.
I haven't tried passing multiple variables using this method but I'm hopeful that also can be appended to the Url if required.