I tried this with python3 and it worked, source
def output_reader(proc):
for line in iter(proc.stdout.readline, b''):
print('got line: {0}'.format(line.decode('utf-8')), end='')
def main():
proc = subprocess.Popen(['python', 'fake_utility.py'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
t = threading.Thread(target=output_reader, args=(proc,))
t.start()
try:
time.sleep(0.2)
import time
i = 0
while True:
print (hex(i)*512)
i += 1
time.sleep(0.5)
finally:
proc.terminate()
try:
proc.wait(timeout=0.2)
print('== subprocess exited with rc =', proc.returncode)
except subprocess.TimeoutExpired:
print('subprocess did not terminate in time')
t.join()
Exact same thing, just omit the -c
option. Apache's docs on it here.
htpasswd /etc/apache2/.htpasswd newuser
Also, htpasswd
typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
You can convert both the values to lower case and compare.
Here is an example:
If LCase(Range("J6").Value) = LCase("Tawi") Then
Range("J6").Value = "Tawi-Tawi"
End If
Much more convenient way if you are sure you need a default timezone :
Date d = java.sql.Timestamp.valueOf( myLocalDateTime );
You may try something like that:
public Stream ConvertToBase64(Stream stream)
{
Byte[] inArray = new Byte[(int)stream.Length];
Char[] outArray = new Char[(int)(stream.Length * 1.34)];
stream.Read(inArray, 0, (int)stream.Length);
Convert.ToBase64CharArray(inArray, 0, inArray.Length, outArray, 0);
return new MemoryStream(Encoding.UTF8.GetBytes(outArray));
}
If you only need the dictionary keys 1
, 2
, and 3
use: your_dict.keys()
.
If you only need the dictionary values -0.3246
, -0.9185
, and -3985
use: your_dict.values()
.
If you want both keys and values use: your_dict.items()
which returns a list of tuples [(key1, value1), (key2, value2), ...]
.
Another option is to configure the server rather than the test client.
Configure the slave node service so that it knows where the firefox is. Install location can change from node to node, or even need multiple services running on a node to support access to different versions of FF.
java -jar "selenium-server-standalone-2.2.0.jar"
-Dwebdriver.firefox.bin="C:\FirefoxCollection\Mozilla Firefox 36.0\firefox.exe"
It looks like you're comparing strings incorrectly. To compare a string to another, use the std::string::compare
function.
Example
while ((wrong < MAX_WRONG) && (soFar.compare(THE_WORD) != 0))
the sub query looks like
insert into table_name (col1,col2,....) values (select col1,col2,... FROM table_2 ...)
hope this help
I had the same problem when I was trying to upgrade from ADT 20.0.x to ADT 23.0.x on Eclipse Indigo.
To fix the issue, I had to uninstall the ADT plugin (remove feature) from Eclipse, then reinstall the newer versions.
This maybe done by going to Help->Install New Software
. Then at the bottom of the page, click What is already installed?
All what is left now is to install the newer versions as usual from help->Install New Software
.
Firefox
On Firefox you can use an extension called FirePHP which enables the logging and dumping of information from your PHP applications to the console. This is an addon to the awesome web development extension Firebug.
Chrome
However if you are using Chrome there is a PHP debugging tool called Chrome Logger or webug (webug has problems with the order of logs).
More recently Clockwork is in active development which extends the Developer Tools by adding a new panel to provide useful debugging and profiling information. It provides out of the box support for Laravel 4 and Slim 2 and support can be added via its extensible API.
Using Xdebug
A better way to debug your PHP would be via Xdebug. Most browsers provide helper extensions to help you pass the required cookie/query string to initialize the debugging process.
The below pom.xml configuration is making the build successful and make sure project buildpath JRE System library should point to Java8.
org.apache.maven.pluginsmaven-compiler-plugin3.7.0 1.81.8
You can simply do this
$(function() {
$( "#datepicker" ).datepicker({ maxDate: new Date });
});
FYI: while checking the documentation, found that it also accepts numeric values too.
Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.
so 0
represents today. Therefore you can do this too
$( "#datepicker" ).datepicker({ maxDate: 0 });
$ sbt sbtVersion
This prints the sbt version used in your current project, or if it is a multi-module project for each module.
$ sbt 'inspect sbtVersion'
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] Setting: java.lang.String = 0.13.1
[info] Description:
[info] Provides the version of sbt. This setting should be not be modified.
[info] Provided by:
[info] */*:sbtVersion
[info] Defined at:
[info] (sbt.Defaults) Defaults.scala:68
[info] Delegates:
[info] *:sbtVersion
[info] {.}/*:sbtVersion
[info] */*:sbtVersion
[info] Related:
[info] */*:sbtVersion
You may also want to use sbt about
that (copying Mark Harrah's comment):
The about command was added recently to try to succinctly print the most relevant information, including the sbt version.
I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:
public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public VndApiJsonMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
}
}
Which can be used simply like the following:
HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");
List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());
var responseObject = await response.Content.ReadAsAsync<Person>(formatters);
Super simple and works exactly as I expected.
If xCode keep complaining about armv7, make sure you disconnect any connect device (especially iPhone 5!!) and try again. Took me hours to find out that little piece of information.
Another way to do it in Angular:
Markup:
<textarea #inputMessage></textarea>
Add ViewChild()
property:
@ViewChild('inputMessage')
inputMessageRef: ElementRef;
Scroll anywhere you want inside of the component using scrollIntoView()
function:
this.inputMessageRef.nativeElement.scrollIntoView();
Member functions that do not modify the class instance should be declared as const
:
int getId() const {
return id;
}
string getName() const {
return name;
}
Anytime you see "discards qualifiers", it's talking about const
or volatile
.
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
From SourceTree, click on Tools->Options. Then on the "General" tab, make sure to check the box to allow SourceTree to modify your Git config files.
Then switch to the "Diff" tab. On the lower half, use the drop down to select the external program you want to use to do the diffs and merging. I've installed KDiff3 and like it well enough. When you're done, click OK.
Now when there is a merge, you can go under Actions->Resolve Conflicts->Launch External Merge Tool.
Here's how to fix this error when launching Eclipse:
Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.
Go and install latest JDK
Make sure you have installed 64 bit Eclipse
Alternatively, if you don't want to deal with threads, try this method:
public static void pause(int seconds){
Date start = new Date();
Date end = new Date();
while(end.getTime() - start.getTime() < seconds * 1000){
end = new Date();
}
}
It starts when you call it, and ends when the number of seconds have passed.
You need to set the thumbnail class to position relative then the post-content to absolute.
Check this fiddle
.post-content {
top:0;
left:0;
position: absolute;
}
.thumbnail{
position:relative;
}
Giving it top and left 0 will make it appear in the top left corner.
Try passing it directly to the ng-click function:
<div class="col-lg-1 text-center">
<span class="glyphicon glyphicon-trash" data="{{event.id}}"
ng-click="deleteEvent(event.id)"></span>
</div>
Then it should be available in your handler:
$scope.deleteEvent=function(idPassedFromNgClick){
console.log(idPassedFromNgClick);
}
Here's an example
I recently had this issue. The problem was that the method I was trying to mock had no access modifier. Adding public solved the problem.
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
Yes, this behaviour is guaranteed:
The
@Before
methods of superclasses will be run before those of the current class, unless they are overridden in the current class. No other ordering is defined.
The
@After
methods declared in superclasses will be run after those of the current class, unless they are overridden in the current class.
I encountered this issue because I used setState
instead of state
in the constructor.
EXAMPLE
Change the following incorrect code
constructor(props) {
super(props);
this.setState({
key: ''
});
}
to
constructor(props) {
super(props);
this.state = {
key: ''
};
}
.html
<form [formGroup]="contactForm">
<button [disabled]="contactForm.invalid" (click)="onSubmit()">SEND</button>
.ts
contactForm: FormGroup;
You need to loop through the list and use end=" "
to keep it on one line
names = ["Sam", "Peter", "James", "Julian", "Ann"]
index=0
for name in names:
print(names[index], end=", ")
index += 1
This constructor was deprecated in API level 26.1.0. use NotificationCompat.Builder(Context, String) instead. All posted Notifications must specify a NotificationChannel Id.
As a complement to @JoshuaUlrich answer, here is the definition of function as.Date.character
:
as.Date.character
function (x, format = "", ...)
{
charToDate <- function(x) {
xx <- x[1L]
if (is.na(xx)) {
j <- 1L
while (is.na(xx) && (j <- j + 1L) <= length(x)) xx <- x[j]
if (is.na(xx))
f <- "%Y-%m-%d"
}
if (is.na(xx) || !is.na(strptime(xx, f <- "%Y-%m-%d",
tz = "GMT")) || !is.na(strptime(xx, f <- "%Y/%m/%d",
tz = "GMT")))
return(strptime(x, f))
stop("character string is not in a standard unambiguous format")
}
res <- if (missing(format))
charToDate(x)
else strptime(x, format, tz = "GMT")
as.Date(res)
}
<bytecode: 0x265b0ec>
<environment: namespace:base>
So basically if both strptime(x, format="%Y-%m-%d")
and strptime(x, format="%Y/%m/%d")
throws an NA
it is considered ambiguous and if not unambiguous.
here is an another example
<a data-container = "body" data-toggle = "popover" data-placement = "left"
data-content = "<img src='<?php echo baseImgUrl . $row1[2] ?>' width='250' height='100' ><div><h3> <?php echo $row1['1'] ?></h3> <p> <span><?php echo $countsss ?>videos </span>
<span><?php echo $countsss1 ?> followers</span>
</p></div>
<?php echo $row1['4'] ?> <hr><div>
<span> <button type='button' class='btn btn-default pull-left green'>Follow </button> </span> <span> <button type='button' class='btn btn-default pull-left green'> Go to channel page</button> </span><span> <button type='button' class='btn btn-default pull-left green'>Close </button> </span>
</div>">
<?php echo $row1['1'] ?>
</a>
# echo ::memstat | mdb -k
Page Summary Pages MB %Tot
------------ ---------------- ---------------- ----
Kernel 7308 57 23%
Anon 9055 70 29%
Exec and libs 1968 15 6%
Page cache 2224 17 7%
Free (cachelist) 6470 50 20%
Free (freelist) 4641 36 15%
Total 31666 247
Physical 31256 244
Should not enclose true with double quote " " it should be like
$(document).ready(function() {
$('input').attr('required', true);
});
Also you can use prop
jQuery(document).ready(function() {
$('input').prop('required', true);
});
Instead of true you can try required. Such as
$('input').prop('required', 'required');
Do you want to roll back your repo to that state, or you just want your local repo to look like that?
If you reset --hard
, it will make your local code and local history be just like it was at that commit. But if you wanted to push this to someone else who has the new history, it would fail:
git reset --hard c14809fa
And if you reset --soft
, it will move your HEAD to where they were , but leave your local files etc. the same:
git reset --soft c14809fa
So what exactly do you want to do with this reset?
Edit -
You can add "tags" to your repo.. and then go back to a tag. But a tag is really just a shortcut to the sha1.
You can tag this as TAG1.. then a git reset --soft c14809fa
, git reset --soft TAG1
, or git reset --soft c14809fafb08b9e96ff2879999ba8c807d10fb07
would all do the same thing.
There are some straightforward examples already, but I notice from how you've worded your question that you probably come from a PHP background, and you're expecting JavaScript to work the same way -- it does not. A PHP array
is very different from a JavaScript Array
.
In PHP, an associative array can do most of what a numerically-indexed array can (the array_*
functions work, you can count()
it, etc.) You simply create an array and start assigning to string-indexes instead of numeric.
In JavaScript, everything is an object (except for primitives: string, numeric, boolean), and arrays are a certain implementation that lets you have numeric indexes. Anything pushed to an array will effect its length
, and can be iterated over using Array methods (map
, forEach
, reduce
, filter
, find
, etc.) However, because everything is an object, you're always free to simply assign properties, because that's something you do to any object. Square-bracket notation is simply another way to access a property, so in your case:
array['Main'] = 'Main Page';
is actually equivalent to:
array.Main = 'Main Page';
From your description, my guess is that you want an 'associative array', but for JavaScript, this is a simple case of using an object as a hashmap. Also, I know it's an example, but avoid non-meaningful names that only describe the variable type (e.g. array
), and name based on what it should contain (e.g. pages
). Simple objects don't have many good direct ways to iterate, so often we'll turn then into arrays first using Object
methods (Object.keys
in this case -- there's also entries
and values
being added to some browsers right now) which we can loop.
// assigning values to corresponding keys
const pages = {
Main: 'Main page',
Guide: 'Guide page',
Articles: 'Articles page',
Forum: 'Forum board',
};
Object.keys(pages).forEach((page) => console.log(page));
POST variables should be accessible via the request object: HttpRequest.getParameterMap(). The exception is if the form is sending multipart MIME data (the FORM has enctype="multipart/form-data"). In that case, you need to parse the byte stream with a MIME parser. You can write your own or use an existing one like the Apache Commons File Upload API.
If your problem is like the following while using Google Chrome:
[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]
Then create a batch file by following these steps:
Open notepad in Desktop.
start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit
This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.
Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.
I just had to restart the MongoDB (v4.4) service after editing the config file on a Windows box. Here's what I did:
Win+R
to open the Run panelThats it!
This will work for simnple data types (str, int, float, list etc.)
>>> def my_print(var_str) : print var_str+':', globals()[var_str] >>> a = 5 >>> b = ['hello', ',world!'] >>> my_print('a') a: 5 >>> my_print('b') b: ['hello', ',world!']
Add <br style="clear: both" />
after the last floated div worked for me.
You can also add column to a specific position using before column or after column like:
rails generate migration add_dob_to_customer dob:date
The migration file will generate the following code except after: :email. you need to add after: :email or before: :email
class AddDobToCustomer < ActiveRecord::Migration[5.2]
def change
add_column :customers, :dob, :date, after: :email
end
end
if you want to find datadir in linux or windows you can do following command
mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"'
if you are interested to find datadir you can use grep & awk command
mysql -uUSER -p -e 'SHOW VARIABLES WHERE Variable_Name = "datadir"' | grep 'datadir' | awk '{print $2}'
You can stop a macro by pressing ctrl + break but if you don't have the break key you could use this autohotkey (open source) code:
+ESC:: SendInput {CtrlBreak} return
Pressing shift + Escape will be like pressing ctrl + break and thus will stop your macro.
All the glory to this page
I just wrote up a quick test, try this:
IEnumerable<Object> myList = new List<Object>();
Stopwatch watch = new Stopwatch();
int x;
watch.Start();
for (var i = 0; i <= 1000000; i++)
{
if (myList.Count() == 0) x = i;
}
watch.Stop();
Stopwatch watch2 = new Stopwatch();
watch2.Start();
for (var i = 0; i <= 1000000; i++)
{
if (!myList.Any()) x = i;
}
watch2.Stop();
Console.WriteLine("myList.Count() = " + watch.ElapsedMilliseconds.ToString());
Console.WriteLine("myList.Any() = " + watch2.ElapsedMilliseconds.ToString());
Console.ReadLine();
The second is almost three times slower :)
Trying the stopwatch test again with a Stack or array or other scenarios it really depends on the type of list it seems - because they prove Count to be slower.
So I guess it depends on the type of list you're using!
(Just to point out, I put 2000+ objects in the List and count was still faster, opposite with other types)
Adding position: relative
to the parent, and a max-height:100%
; on div2 works.
<body>_x000D_
<div id="div1" style="height: 500px;position:relative;">_x000D_
<div id="div2" style="max-height:100%;overflow:auto;border:1px solid red;">_x000D_
<div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</body>?
_x000D_
Update: The following shows the "updated" example and answer. http://jsfiddle.net/Wcgvt/181/
The secret there is to use box-sizing: border-box
, and some padding to make the second div height 100%, but move it's content down 50px. Then wrap the content in a div with overflow: auto
to contain the scrollbar. Pay attention to z-indexes to keep all the text selectable - hope this helps, several years later.
This Code Is working Fine :
txtTimer.setText(String.format("%02d:%02d:%02d",(SecondsCounter/3600), ((SecondsCounter % 3600)/60), (SecondsCounter % 60)));
What's wrong with transforming the version string into a tuple and going from there? Seems elegant enough for me
>>> (2,3,1) < (10,1,1)
True
>>> (2,3,1) < (10,1,1,1)
True
>>> (2,3,1,10) < (10,1,1,1)
True
>>> (10,3,1,10) < (10,1,1,1)
False
>>> (10,3,1,10) < (10,4,1,1)
True
@kindall's solution is a quick example of how good the code would look.
There is an important difference between floor() and DIV 1. For negative numbers, they behave differently. DIV 1 returns the integer part (as cast as signed does), while floor(x) returns "the largest integer value not greater than x" (from the manual). So : select floor(-1.1) results in -2, while select -1.1 div 1 results in -1
It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:
sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})
This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:
axs.set_ylabel('mylabel',size=6)
you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.
def set_pubfig:
sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})
Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.
Note: If you specify these numbers, specifying font_scale
in sns.set_context
is ignored for all specified font elements, even if you set it.
If you don't want to change your table structure, you can run the following query:
ALTER TABLE [UserStore]
NOCHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT FK_UserIdentity_User_UserId
BEGIN TRAN
UPDATE [user]
SET Id = 10
WHERE Id = 9
UPDATE [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9
UPDATE [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9
COMMIT TRAN
ALTER TABLE [UserStore]
CHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE UserIdentity
CHECK CONSTRAINT FK_UserIdentity_User_UserId
Best I can give you is a "works for me" on SVN 1.5. You may try adding --no-auth-cache
to your svn update
to see if that lets you override more easily.
If you want to permanently switch from user2 to user1, head into ~/.subversion/auth/ on *nix and delete the auth cache file for domain.com (most likely in ~/.subversion/auth/svn.simple/ -- just read through them and you'll find the one you want to drop). While it is possible to update the current auth cache, you have to make sure to update the length tokens as well. Simpler just to get prompted again next time you update.
Yes, I believe you are creating thousands of objects. If you're looking for an easy way to delete a bunch of them at once, use canvas tags described here. This lets you perform the same operation (such as deletion) on a large number of objects.
Can I see (...) the real SQL
If you want to see the SQL sent directly to the database (that is formatted similar to your example), you'll have to use some kind of jdbc driver proxy like P6Spy (or log4jdbc).
Alternatively you can enable logging of the following categories (using a log4j.properties
file here):
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
The first is equivalent to hibernate.show_sql=true
, the second prints the bound parameters among other things.
You can use:
ImageView imgView = new ImageView(this);
InputStream is = getClass().getResourceAsStream("/drawable/" + fileName);
imgView.setImageDrawable(Drawable.createFromStream(is, ""));
use Set Comprehensions {x for x in l2} or set(l2) to get set, then use List Comprehensions to get list
l2set = set(l2)
l3 = [x for x in l1 if x not in l2set]
benchmark test code:
import time
l1 = list(range(1000*10 * 3))
l2 = list(range(1000*10 * 2))
l2set = {x for x in l2}
tic = time.time()
l3 = [x for x in l1 if x not in l2set]
toc = time.time()
diffset = toc-tic
print(diffset)
tic = time.time()
l3 = [x for x in l1 if x not in l2]
toc = time.time()
difflist = toc-tic
print(difflist)
print("speedup %fx"%(difflist/diffset))
benchmark test result:
0.0015058517456054688
3.968189239501953
speedup 2635.179227x
Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0
) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE
).
Since your integer array cannot contain a value larger than Integer.MAX_VALUE
and smaller than Integer.MIN_VALUE
your code works across all edge cases.
In my experience, openssl always being troublesome, I tried the second method suggested by facebook. And it's wonderful. This is the best method to get the hash key.
Second option is to print out the key hash sent to Facebook and use that value. Make the following changes to the onCreate() method in your main activity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.loginhowto",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
...other operations
}//end of onCreate
Replace com.facebook.samples.loginhowto with your own package name ( package name in Manifest.xml).
Official link - https://developers.facebook.com/docs/android/login-with-facebook/ ( See the bottom of the page)
openssl
folderopenssl
folder in C:
drivebin
of openssl
i.e C:\openssl\bin
in command promptrun the following command to generate your keyhash. While generating hashkey it should ask you password.
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Anhsirk.android\debug.keystore" | openssl sha1 -binary | openssl base64
NOTE: in the above code note that , you need to give your path to user ( i.e in my case it is C:\Users\Anhsirk , you just need to change this for your user account.
Give password as android
. If it don’t ask for password your keystore path is incorrect.
If everything works fine, it should give you the hashkey below.
You may want to add
HttpURLConnection.setFollowRedirects(false);
// note : or
// huc.setInstanceFollowRedirects(false)
if you don't want to follow redirection (3XX)
Instead of doing a "GET", a "HEAD" is all you need.
huc.setRequestMethod("HEAD");
return (huc.getResponseCode() == HttpURLConnection.HTTP_OK);
It's either through system property
-Dorg.slf4j.simpleLogger.defaultLogLevel=debug
or simplelogger.properties
file on the classpath
see http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html for details
Start from pandas 0.13, this is the most efficient way.
df.query('Gender=="Male" & Year=="2014" ')
You haven't set the timezone only added a Z
to the end of the date/time, so it will look like a GMT date/time but this doesn't change the value.
Set the timezone to GMT and it will be correct.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
I changed :
compile 'com.google.android.gms:play-services:9.0.0'
compile 'com.google.android.gms:play-services-auth:9.0.0'
to :
compile 'com.google.android.gms:play-services-maps:9.0.0'
compile 'com.google.android.gms:play-services-auth:9.0.0'
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp
. "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
It works.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}
Try this one, this function allows alphanumeric and spaces:
function alpha(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}
in your html:
<input type="text" name="name" onkeypress="return alpha(event)"/>
I also found the apache commons IOUtils
class , so :
InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));
$haystack = array (
'say hello',
'hello stackoverflow',
'hello world',
'foo bar bas'
);
$matches = preg_grep('/hello/i', $haystack);
print_r($matches);
Output
Array
(
[1] => say hello
[2] => hello stackoverflow
[3] => hello world
)
Instead of using input type button
you can use button
and insert the image inside the button content.
<button class="btn btn-default">
<img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook
</button>
The problem with doing this only with CSS is that you cannot set linear-gradient
to the background you must use solid color.
.sign-in-facebook {
background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;
background-position: -9px -7px;
background-repeat: no-repeat;
background-size: 39px 43px;
padding-left: 41px;
color: #000;
}
.sign-in-facebook:hover {
background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;
background-position: -9px -7px;
background-repeat: no-repeat;
background-size: 39px 43px;
padding-left: 41px;
color: #000;
}
body {_x000D_
padding: 30px;_x000D_
}
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style type="text/css">_x000D_
.sign-in-facebook {_x000D_
background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;_x000D_
background-position: -9px -7px;_x000D_
background-repeat: no-repeat;_x000D_
background-size: 39px 43px;_x000D_
padding-left: 41px;_x000D_
color: #000;_x000D_
}_x000D_
.sign-in-facebook:hover {_x000D_
background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;_x000D_
background-position: -9px -7px;_x000D_
background-repeat: no-repeat;_x000D_
background-size: 39px 43px;_x000D_
padding-left: 41px;_x000D_
color: #000;_x000D_
}_x000D_
</style>_x000D_
_x000D_
_x000D_
<h4>Only with CSS</h4>_x000D_
_x000D_
<input type="button" value="Sign In with Facebook" class="btn btn-default sign-in-facebook" style="margin-top:2px; margin-bottom:2px;">_x000D_
_x000D_
<h4>Only with HTML</h4>_x000D_
_x000D_
<button class="btn btn-default">_x000D_
<img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook_x000D_
</button>
_x000D_
If
side_effect_func
is a function then whatever that function returns is what calls to the mock return. Theside_effect_func
function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input:>>> def side_effect_func(value): ... return value + 1 ... >>> m = MagicMock(side_effect=side_effect_func) >>> m(1) 2 >>> m(2) 3 >>> m.mock_calls [call(1), call(2)]
I recently used Spring Security 3.0 for this (combined with Wicket btw), and am quite happy with it. Here's a good thorough tutorial and documentation. Also take a look at this tutorial which gives a good explanation of the hashing/salting/decoding setup for Spring Security 2.
If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su
then apt-get install -y wget
Maybe your remote repo is in the branch which you want to push. You can try to checkout another branch in your remote machine. I did this, than these error disappeared, and I pushed success to my remote repo. Notice that I use ssh to connect my own server instead of github.com.
you can Try the following snippet:
var str = "How are you doing today?";
var res = str.split("o");
console.log("My Result:",res)
and your output like that
My Result: H,w are y,u d,ing t,day?
It can be as follows:
UPDATE A
SET A.`id` = (SELECT id from B WHERE A.title = B.title)
Following are the results when we use both [MaxLength]
and [StringLength]
attributes, in EF code first
. If both are used, [MaxLength]
wins the race. See the test result in studentname
column in below class
public class Student
{
public Student () {}
[Key]
[Column(Order=1)]
public int StudentKey { get; set; }
//[MaxLength(50),StringLength(60)] //studentname column will be nvarchar(50)
//[StringLength(60)] //studentname column will be nvarchar(60)
[MaxLength(50)] //studentname column will be nvarchar(50)
public string StudentName { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
I use the len
function. It's much faster than empty
. len(df.index)
is even faster.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10000, 4), columns=list('ABCD'))
def empty(df):
return df.empty
def lenz(df):
return len(df) == 0
def lenzi(df):
return len(df.index) == 0
'''
%timeit empty(df)
%timeit lenz(df)
%timeit lenzi(df)
10000 loops, best of 3: 13.9 µs per loop
100000 loops, best of 3: 2.34 µs per loop
1000000 loops, best of 3: 695 ns per loop
len on index seems to be faster
'''
The wiki lists some more wrappers:
For me it was because only Windows Authentication was enabled. To change security authentication mode. In SQL Server Management Studio Object Explorer, right-click the server, and then click Properties. On the Security page, under Server authentication, select the new server authentication mode, and then click OK. Change Server Authentication Mode - MSDN - Microsoft https://msdn.microsoft.com/en-AU/library/ms188670.aspx
well I would like to do this in the below way
const findMaxAndMin = (arr) => {
if (arr.length <= 0) return -1;
let min = arr[0];
let max = arr[0];
arr.map((n) => {
n > max ? (max = n) : false;
n < min ? (min = n) : false;
});
return [min, max];
};
If it was installed with plesk (not sure if it's just that, or on the phpmyadmin side: It changes the root user to admin.
An alternative, and perhaps a not so good procedural coding one, is to send the "function name" to a script that then executes the function. For instance, with a login form, there is typically the login, forgotusername, forgotpassword, signin activities that are presented on the form as buttons or anchors. All of these can be directed to/as, say,
weblogin.php?function=login
weblogin.php?function=forgotusername
weblogin.php?function=forgotpassword
weblogin.php?function=signin
And then a switch statement on the receiving page does any prep work and then dispatches or runs the (next) specified function.
Use the "containment" option:
jQuery UI API - Draggable Widget - containment
The documentation says it only accepts the values: 'parent'
, 'document'
, 'window'
, [x1, y1, x2, y2]
but I seem to remember it will accept a selector such as '#container' too.
The cleanest way to work with it. Assuming your table is a list of integers called "dbo.tvp_Int" (Customize for your own table type)
Create this extension method...
public static void AddWithValue_Tvp_Int(this SqlParameterCollection paramCollection, string parameterName, List<int> data)
{
if(paramCollection != null)
{
var p = paramCollection.Add(parameterName, SqlDbType.Structured);
p.TypeName = "dbo.tvp_Int";
DataTable _dt = new DataTable() {Columns = {"Value"}};
data.ForEach(value => _dt.Rows.Add(value));
p.Value = _dt;
}
}
Now you can add a table valued parameter in one line anywhere simply by doing this:
cmd.Parameters.AddWithValueFor_Tvp_Int("@IDValues", listOfIds);
This is commonly reported as an error due to using the wrong version of SSMS(Sql Server Management Studio). Use the version designed for your database version. You can use the command select @@version
to check which version of sql server you are actually using. This version is reported in a way that is easier to interpret than that shown in the Help About in SSMS.
Using a newer version of SSMS than your database is generally error-free, i.e. backward compatible.
Download and install SAP Crystal Reports Runtime engine for .net (32 bit or 64 bit) depending on your os version. Should work there after
What solved my problem was just using the below two lines in ipython notebook at the top
%matplotib inline
%pylab inline
And it worked. I'm using Ubuntu16.04 and ipython-5.1
-ErrorAction Stop
is changing things for you. Try adding this and see what you get:
Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception"
$error[0]
}
I think sim serial Number and sim number is unique. You can try this for get sim serial number and get sim number and Don't forget to add permission in manifest file.
TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();
And add below permission into your Androidmanifest.xml
file.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Let me know if there is any issue.
Response.Redirect()
should be used when:
Server.Transfer()
should be used when:
There's also byte_lite, compatible with C++98, C++11 and later.
{% load static %}
Please add this template tag on top of the HTML or base HTML file
function TellFirstCharacterType(inputString){
var firstCharacter = inputString[0];
if(isNaN(firstCharacter)){
if(firstCharacter == firstCharacter.toUpperCase()){
return "It's a uppercase character";
}
else{
return "It's a lowercase character";
}
}
else{
return "It's a Number";
}
}
If I recall correctly NULL is defined differently in the headers that I have used. For C it is defined as (void*)0, and for C++ it's defines as just 0. The code looked something like:
#ifndef __cplusplus
#define NULL (void*)0
#else
#define NULL 0
#endif
Personally I still use the NULL value to represent null pointers, it makes it explicit that you're using a pointer rather than some integral type. Yes internally the NULL value is still 0 but it isn't represented as such.
Additionally I don't rely on the automatic conversion of integers to boolean values but explicitly compare them.
For example prefer to use:
if (pointer_value != NULL || integer_value == 0)
rather than:
if (pointer_value || !integer_value)
Suffice to say that this is all remedied in C++11 where one can simply use nullptr
instead of NULL
, and also nullptr_t
that is the type of a nullptr
.
I finally found a way to customize the given Themes.
Go to C:\Program Files\Sublime Text 3\Packages
and copy + rename Color Scheme - Default.sublime-package
to Color Scheme - Default.zip
. Afterwards unzip it and copy the Theme, you want to change to %APPDATA%\Sublime Text 3\Packages\User
. (In my case, All Hallow's Eve.tmTheme
).
Then you can open it with any Text Editor and change / add something, for example for changing this
in JavaScript:
<dict>
<key>name</key>
<string>Lang Variable</string>
<key>scope</key>
<string>variable.language</string>
<key>settings</key>
<dict>
<key>foreground</key>
<string>#FF0000</string>
</dict>
</dict>
This will mark this
in JavaScript Files red. You can select your Theme under Preferences -> Color Scheme -> User -> <Your Name>
.
Depends on what you want to do:
to read the value as an ascii code, you can write
char a = 'a';
int ia = (int)a;
/* note that the int cast is not necessary -- int ia = a would suffice */
to convert the character '0' -> 0
, '1' -> 1
, etc, you can write
char a = '4';
int ia = a - '0';
/* check here if ia is bounded by 0 and 9 */
Explanation:
a - '0'
is equivalent to ((int)a) - ((int)'0')
, which means the ascii values of the characters are subtracted from each other. Since 0
comes directly before 1
in the ascii table (and so on until 9
), the difference between the two gives the number that the character a
represents.
This may be useful:
var serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
Where "json" is the string that contains the JSON values. Then to retrieve the values from the jsonObject you may use
myProperty = Convert.MyPropertyType(jsonObject["myProperty"]);
Changing MyPropertyType to the proper type (ToInt32, ToString, ToBoolean, etc).
- What is the difference between connection and read timeout for sockets?
The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read
call, a read timeout error will be raised.
- What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?
It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt()
call may also do the trick ... not sure.)
- What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?
It means that a call to read
on the socket stream may block for ever. Once again there is no infinite loop, but the read
can be unblocked by a Thread.interrupt()
call, closing the socket, and (of course) the other end sending data or closing the connection.
1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.
I had the need to keep a pod running for subsequent kubectl exec calls and as the comments above pointed out my pod was getting killed by my k8s cluster because it had completed running all its tasks. I managed to keep my pod running by simply kicking the pod with a command that would not stop automatically as in:
kubectl run YOUR_POD_NAME -n YOUR_NAMESPACE --image SOME_PUBLIC_IMAGE:latest --command tailf /dev/null
Random generator = new Random();
int i = generator.nextInt(10) + 1;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form id="myform">
<select class="form-control" name="user_type">
<option value="">Select</option>
<option value="2">1</option>
<option value="3">2</option>
</select>
</form>
<script>
$('#myform').validate({ // initialize the plugin
rules: {
user_type:{ required: true},
}
});
</script>
select value will be blank
cmd /k cd c:\ is the right answer
thanks for the help, I've solved my problem :) Here is the code if anyone else needs it :D
import java.util.*;
public class HelloWorld {
public static void main(String[] Args) {
Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(9);
list.add(11);
map.put(1,list);
int First = list.get(1);
int Second = list.get(2);
if (First < Second) {
System.out.println("One or more of your items have been restocked. The current stock is: " + First);
Random rn = new Random();
int answer = rn.nextInt(99) + 1;
System.out.println("You are buying " + answer + " New stock");
First = First + answer;
list.set(1, First);
System.out.println("There are now " + First + " in stock");
}
}
}
Java does not support multiple inheritance. However, your problem may be solved using interfaces.
The easiest solution would be to create an interface for AbstractBillingActivity
and PreferenceActivity
and implement them both.
You are really going to want to do 2 or 3, don't disable event validation.
There are two main problems with adding items to an asp:listbox client side.
The first is that it interferes with event validation. What came back to the server is not what it sent down.
The second is that even if you disable event validation, when your page gets posted back the items in the listbox will be rebuilt from the viewstate, so any changes you made on the client are lost. The reason for this is that a asp.net does not expect the contents of a listbox to be modified on the client, it only expects a selection to be made, so it discards any changes you might have made.
The best option is most likely to use an update panel as has been recommended. Another option, if you really need to do this client side, is to use a plain old <select>
instead of an <asp:ListBox>
, and to keep your list of items in a hidden field. When the page renders on the client you can populate it from a split of your text field contents.
Then, when you are ready to post it, you repopulate the hidden field's contents from your modified <select>
. Then, of course, you have to split that again on the server and do something with your items, since your select is empty now that it's back on the server.
All in all it's a pretty cumbersome solution that I would not really recommend, but if you really have to do client-side modifications of a listBox, it does work. I would really recommend you look into an updatePanel before going this route, however.
Just to add to CKoenig's response. His answer will work as long as the class you're dealing with is a reference type (like a class). If the custom object were a struct, this is a value type, and the results of .FirstOrDefault
will give you a local copy of that, which will mean it won't persist back to the collection, as this example shows:
struct MyStruct
{
public int TheValue { get; set; }
}
Test code:
List<MyStruct> coll = new List<MyStruct> {
new MyStruct {TheValue = 10},
new MyStruct {TheValue = 1},
new MyStruct {TheValue = 145},
};
var found = coll.FirstOrDefault(c => c.TheValue == 1);
found.TheValue = 12;
foreach (var myStruct in coll)
{
Console.WriteLine(myStruct.TheValue);
}
Console.ReadLine();
The output is 10,1,145
Change the struct to a class and the output is 10,12,145
HTH
You can pass parameters but either it is not a vue.js way or the way you are doing is wrong.
However there are cases when you need to do so.I am going to show you a simple example passing value to computed property using getter and setter.
<template>
<div>
Your name is {{get_name}} <!-- John Doe at the beginning -->
<button @click="name = 'Roland'">Change it</button>
</div>
</template>
And the script
export default {
data: () => ({
name: 'John Doe'
}),
computed:{
get_name: {
get () {
return this.name
},
set (new_name) {
this.name = new_name
}
},
}
}
When the button clicked we are passing to computed property the name 'Roland' and in set()
we are changing the name from 'John Doe' to 'Roland'.
Below there is a common use case when computed is used with getter and setter. Say you have the follow vuex store:
export default new Vuex.Store({
state: {
name: 'John Doe'
},
getters: {
get_name: state => state.name
},
mutations: {
set_name: (state, payload) => state.name = payload
},
})
And in your component you want to add v-model
to an input but using the vuex store.
<template>
<div>
<input type="text" v-model="get_name">
{{get_name}}
</div>
</template>
<script>
export default {
computed:{
get_name: {
get () {
return this.$store.getters.get_name
},
set (new_name) {
this.$store.commit('set_name', new_name)
}
},
}
}
</script>
I wrote this a long time ago (from years 1985-1992, with just a few tweaks since then), and just copy and paste the bits needed into each project.
You must call cfmakeraw
on a tty
obtained from tcgetattr
. You cannot zero-out a struct termios
, configure it, and then set the tty
with tcsetattr
. If you use the zero-out method, then you will experience unexplained intermittent failures, especially on the BSDs and OS X. "Unexplained intermittent failures" include hanging in read(3)
.
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
int
set_interface_attribs (int fd, int speed, int parity)
{
struct termios tty;
if (tcgetattr (fd, &tty) != 0)
{
error_message ("error %d from tcgetattr", errno);
return -1;
}
cfsetospeed (&tty, speed);
cfsetispeed (&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
// enable reading
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr (fd, TCSANOW, &tty) != 0)
{
error_message ("error %d from tcsetattr", errno);
return -1;
}
return 0;
}
void
set_blocking (int fd, int should_block)
{
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (fd, &tty) != 0)
{
error_message ("error %d from tggetattr", errno);
return;
}
tty.c_cc[VMIN] = should_block ? 1 : 0;
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
if (tcsetattr (fd, TCSANOW, &tty) != 0)
error_message ("error %d setting term attributes", errno);
}
...
char *portname = "/dev/ttyUSB1"
...
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
error_message ("error %d opening %s: %s", errno, portname, strerror (errno));
return;
}
set_interface_attribs (fd, B115200, 0); // set speed to 115,200 bps, 8n1 (no parity)
set_blocking (fd, 0); // set no blocking
write (fd, "hello!\n", 7); // send 7 character greeting
usleep ((7 + 25) * 100); // sleep enough to transmit the 7 plus
// receive 25: approx 100 uS per char transmit
char buf [100];
int n = read (fd, buf, sizeof buf); // read up to 100 characters if ready to read
The values for speed are B115200
, B230400
, B9600
, B19200
, B38400
, B57600
, B1200
, B2400
, B4800
, etc. The values for parity are 0
(meaning no parity), PARENB|PARODD
(enable parity and use odd), PARENB
(enable parity and use even), PARENB|PARODD|CMSPAR
(mark parity), and PARENB|CMSPAR
(space parity).
"Blocking" sets whether a read()
on the port waits for the specified number of characters to arrive. Setting no blocking means that a read()
returns however many characters are available without waiting for more, up to the buffer limit.
Addendum:
CMSPAR
is needed only for choosing mark and space parity, which is uncommon. For most applications, it can be omitted. My header file /usr/include/bits/termios.h
enables definition of CMSPAR
only if the preprocessor symbol __USE_MISC
is defined. That definition occurs (in features.h
) with
#if defined _BSD_SOURCE || defined _SVID_SOURCE
#define __USE_MISC 1
#endif
The introductory comments of <features.h>
says:
/* These are defined by the user (or the compiler)
to specify the desired environment:
...
_BSD_SOURCE ISO C, POSIX, and 4.3BSD things.
_SVID_SOURCE ISO C, POSIX, and SVID things.
...
*/
You can use System.IO.Path.GetDirectoryName(fileName)
, or turn the path into a FileInfo
using FileInfo.Directory
.
If you're doing other things with the path, the FileInfo
class may have advantages.
I think you're mixed up between PATH and PYTHONPATH. All you have to do to run a 'script' is have it's parental directory appended to your PATH variable. You can test this by running
which myscript.py
Also, if myscripy.py
depends on custom modules, their parental directories must also be added to the PYTHONPATH variable. Unfortunately, because the designers of python were clearly on drugs, testing your imports in the repl with the following will not guarantee that your PYTHONPATH is set properly for use in a script. This part of python programming is magic and can't be answered appropriately on stackoverflow.
$python
Python 2.7.8 blahblahblah
...
>from mymodule.submodule import ClassName
>test = ClassName()
>^D
$myscript_that_needs_mymodule.submodule.py
Traceback (most recent call last):
File "myscript_that_needs_mymodule.submodule.py", line 5, in <module>
from mymodule.submodule import ClassName
File "/path/to/myscript_that_needs_mymodule.submodule.py", line 5, in <module>
from mymodule.submodule import ClassName
ImportError: No module named submodule
Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.
In jQuery:
$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })
In plain vanilla javaScript (from w3c):
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
//xmlhttp.data and shtuff
// ...our code here...
}
else
{
alert("Problem retrieving data");
}
}
}
First, Update your last perfect migration via this command :
Update-Database –TargetMigration
Example:
Update-Database -20180906131107_xxxx_xxxx
And, then delete your unused migration manually.
I found out that my back-up project worked well if I precompile without bundle update
. Maybe something went wrong with gem updated but I don't know which gem has an error.
Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.
A version that works on both Linux and Mac OS X (by adding the -e
switch to sed
):
export LC_CTYPE=C LANG=C
find . -name '*.txt' -print0 | xargs -0 sed -i -e 's/this/that/g'
If you are using Ubuntu 18.04 or higher with python3.xxx then try this command
$ sudo apt install python3-sklearn
then try your command. hope it will work
Unfortunately, it's not possible with CSS currently, but you can use Number.prototype.toLocaleString()
. It can also format for other number formats, e.g. latin, arabic, etc.
It's probably easiest to have a function to pick a random value from an array. This is more generic, and is straightforward to call.
<T> T randomValue(T[] values) {
return values[mRandom.nextInt(values.length)];
}
Call like so:
MyEnum value = randomValue(MyEnum.values());
SELECT some_cols
FROM prefix_users
WHERE (some conditions)
ORDER BY pic_set DESC, last_activity;
In a microservice infrastructure (does not fit the problem, I know ;)) you must not use:
server:
ssl:
trust-store: path-to-truststore...
trust-store-password: my-secret-password...
Instead the ribbon loadbalancer can be configuered:
ribbon:
TrustStore: keystore.jks
TrustStorePassword : example
ReadTimeout: 60000
IsSecure: true
MaxAutoRetries: 1
Here https://github.com/rajaramkushwaha/https-zuul-proxy-spring-boot-app you can find a working sample. There was also a github discussion about that, but I didn't find it anymore.
You need to add 2 methods, note __hash__
and __eq__
:
class MyThing:
def __init__(self,name,location,length):
self.name = name
self.location = location
self.length = length
def __hash__(self):
return hash((self.name, self.location))
def __eq__(self, other):
return (self.name, self.location) == (other.name, other.location)
def __ne__(self, other):
# Not strictly necessary, but to avoid having both x==y and x!=y
# True at the same time
return not(self == other)
The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.
You can checkout the old version of the file to merge, saving it under a different name, then run whatever your merge tool is on the two files.
eg.
git show B:src/common/store.ts > /tmp/store.ts
(where B is the branch name/commit/tag)
meld src/common/store.ts /tmp/store.ts
$data
is indeed an array, but it's made up of objects.
Convert its content to array before creating it:
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = (array)$result;
#or first convert it and then change its properties using
#an array syntax, it's up to you
}
Excel::create(....
rdtsc solution did not work for me.
Firstly, I use Visual Studio 2015 Express, for which installer "modify" query does not propose any "Common Tools for Visual C++ 2015" option you could uncheck.
Secondly, even after 2 uninstall/reinstall (many hours waiting for them to complete...), the problem still remains.
I finally fixed the issue by reinstalling the whole Windows SDK from a standalone installer (independently from Visual C++ 2015 install): https://developer.microsoft.com/fr-fr/windows/downloads/windows-8-1-sdk or https://developer.microsoft.com/fr-fr/windows/downloads/windows-10-sdk
This fixed the issue for me.
Swift 4.2
You can use a general function for your every textField just add the following function in your base controller
// White space validation.
func checkTextFieldIsNotEmpty(text:String) -> Bool
{
if (text.trimmingCharacters(in: .whitespaces).isEmpty)
{
return false
}else{
return true
}
}
Parent container has to have this:
position: relative;
Button itself has to have this:
position: relative;
bottom: 20px;
right: 20px;
or whatever you like
The simplest external tool that I found that is also portable is jisql - https://www.xigole.com/software/jisql/jisql.jsp . You would run it as:
java -classpath lib/jisql.jar:\
lib/jopt-simple-3.2.jar:\
lib/javacsv.jar:\
/home/scott/postgresql/postgresql-8.4-701.jdbc4.jar
com.xigole.util.sql.Jisql -user scott -password blah \
-driver postgresql \
-cstring jdbc:postgresql://localhost:5432/scott -c \; \
-query "select * from test;"
Module is like a big container containing one or many small containers called Component, Service, Pipe
A Component contains :
HTML template or HTML code
Code(TypeScript)
Service: It is a reusable code that is shared by the Components so that rewriting of code is not required
Pipe: It takes in data as input and transforms it to the desired output
Reference: https://scrimba.com/
Django will use the version of Python specified by the PYTHONPATH environment variable. You can use echo $PYTHONPATH
in a shell to determine which version will be used.
The module versions used by Django will be the module versions installed under the version of Python specified by PYTHONPATH.
Just use multiple in-clauses to get around this:
select field1, field2, field3 from table1
where name in ('value1', 'value2', ..., 'value999')
or name in ('value1000', ..., 'value1999')
or ...;
Changing between timezones
import pytz
from datetime import datetime
other_tz = pytz.timezone('Europe/Madrid')
# From random aware datetime...
aware_datetime = datetime.utcnow().astimezone(other_tz)
>> 2020-05-21 08:28:26.984948+02:00
# 1. Change aware datetime to UTC and remove tzinfo to obtain an unaware datetime
unaware_datetime = aware_datetime.astimezone(pytz.UTC).replace(tzinfo=None)
>> 2020-05-21 06:28:26.984948
# 2. Set tzinfo to UTC directly on an unaware datetime to obtain an utc aware datetime
aware_datetime_utc = unaware_datetime.replace(tzinfo=pytz.UTC)
>> 2020-05-21 06:28:26.984948+00:00
# 3. Convert the aware utc datetime into another timezone
reconverted_aware_datetime = aware_datetime_utc.astimezone(other_tz)
>> 2020-05-21 08:28:26.984948+02:00
# Initial Aware Datetime and Reconverted Aware Datetime are equal
print(aware_datetime1 == aware_datetime2)
>> True
jQuery:
(function($) {
$.textMetrics = function(el) {
var h = 0, w = 0;
var div = document.createElement('div');
document.body.appendChild(div);
$(div).css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none'
});
$(div).html($(el).html());
var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
$(styles).each(function() {
var s = this.toString();
$(div).css(s, $(el).css(s));
});
h = $(div).outerHeight();
w = $(div).outerWidth();
$(div).remove();
var ret = {
height: h,
width: w
};
return ret;
}
})(jQuery);
Using just scipy, glob and having PIL installed (pip install pillow
) you can use scipy's imread method:
from scipy import misc
import glob
for image_path in glob.glob("/home/adam/*.png"):
image = misc.imread(image_path)
print image.shape
print image.dtype
According to the doc, scipy.misc.imread
is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead
. See the answer by Charles.
Just use
y_pred = (y_pred > 0.5)
accuracy_score(y_true, y_pred, normalize=False)
@CaptSolo, I tried your example, but it didn't work.
from itertools import groupby
[(c,len(list(cs))) for c,cs in groupby('Pedro Manoel')]
Output:
[('P', 1), ('e', 1), ('d', 1), ('r', 1), ('o', 1), (' ', 1), ('M', 1), ('a', 1), ('n', 1), ('o', 1), ('e', 1), ('l', 1)]
As you can see, there are two o's and two e's, but they got into separate groups. That's when I realized you need to sort the list passed to the groupby function. So, the correct usage would be:
name = list('Pedro Manoel')
name.sort()
[(c,len(list(cs))) for c,cs in groupby(name)]
Output:
[(' ', 1), ('M', 1), ('P', 1), ('a', 1), ('d', 1), ('e', 2), ('l', 1), ('n', 1), ('o', 2), ('r', 1)]
Just remembering, if the list is not sorted, the groupby function will not work!
Here's some simple code to add a time out to your recv
function using poll
in C:
struct pollfd fd;
int ret;
fd.fd = mySocket; // your socket handler
fd.events = POLLIN;
ret = poll(&fd, 1, 1000); // 1 second for timeout
switch (ret) {
case -1:
// Error
break;
case 0:
// Timeout
break;
default:
recv(mySocket,buf,sizeof(buf), 0); // get your data
break;
}
Is there some handy way of defining direction per column?
No. You cannot specify the sort order other than by a callback function that inverses the value. Not even this is possible for a multicolumn sort.
You might be able to do
_.each(array_of_objects, function(o) {
o.typeDesc = -o.type; // assuming a number
});
_.sortBy(array_of_objects, ['typeDesc', 'name'])
For everything else, you will need to resort to the native .sort()
with a custom comparison function:
array_of_objects.sort(function(a, b) {
return a.type - b.type // asc
|| +(b.name>a.name)||-(a.name>b.name) // desc
|| …;
});
The generateNumbers(int[] numbers)
function definition has arguments (int[] numbers)
that expects an array of integers. However, in the main, generateNumbers();
doesn't have any arguments.
To resolve it, simply add an array of numbers to the arguments while calling thegenerateNumbers()
function in the main.
you can try this
pd.pandas.set_option('display.max_columns', None)
style="position:absolute"
For retrieving data using Ajax + jQuery, you should write the following code:
<html>
<script type="text/javascript" src="jquery-1.3.2.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">
</div>
</body>
</html>
For mysqli connection, write this:
<?php
$con=mysqli_connect("localhost","root","");
For displaying the data from database, you should write this :
<?php
include("connection.php");
mysqli_select_db("samples",$con);
$result=mysqli_query("select * from student",$con);
echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";
while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td align=center>$data[0]</td>";
echo "<td align=center>$data[1]</td>";
echo "<td align=center>$data[2]</td>";
echo "<td align=center>$data[3]</td>";
echo "<td align=center>$data[4]</td>";
echo "</tr>";
}
echo "</table>";
?>
Technically what you are looking for is the unset value in combination with the shorthand property all:
The unset CSS keyword resets a property to its inherited value if it inherits from its parent, and to its initial value if not. In other words, it behaves like the inherit keyword in the first case, and like the initial keyword in the second case. It can be applied to any CSS property, including the CSS shorthand all.
.customClass {
/* specific attribute */
color: unset;
}
.otherClass{
/* unset all attributes */
all: unset;
/* then set own attributes */
color: red;
}
You can use the initial value as well, this will default to the initial browser value.
.otherClass{
/* unset all attributes */
all: initial;
/* then set own attributes */
color: red;
}
As an alternative:
If possible it is probably good practice to encapsulate the class or id in a kind of namespace:
.namespace .customClass{
color: red;
}
<div class="namespace">
<div class="customClass"></div>
</div>
because of the specificity of the selector this will only influence your own classes
It is easier to accomplish this in "preprocessor scripting languages" like SASS with nesting capabilities:
.namespace{
.customClass{
color: red
}
}
This worked for me:
import re
thestring = "text1\ntext2\nhttp://url.com/bla1/blah1/\ntext3\ntext4\nhttp://url.com/bla2/blah2/\ntext5\ntext6"
URLless_string = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', thestring)
print URLless_string
Result:
text1
text2
text3
text4
text5
text6
You aren't doing anything with the return value of replace
. You'll need to assign the result of the method, which is the new String
:
sentence = sentence.replace("and", " ");
A String
is immutable in java. Methods like replace
return a new String
.
Your contains
test is unnecessary: replace
will just no-op if there aren't instances of the text to replace.
To get multiple stats, collapse the index, and retain column names:
df = df.groupby(['col1','col2']).agg(['mean', 'count'])
df.columns = [ ' '.join(str(i) for i in col) for col in df.columns]
df.reset_index(inplace=True)
df
Produces:
You don't say if this is a desktop or web app. I would use the getResourceAsStream()
method from an appropriate ClassLoader if it's a desktop or the Context if it's a web app.
I want to add one more answer :
It happens when you try to pass positional parameter with wrong position order along with keyword argument in calling function.
there is difference between parameter and argument
you can read in detail about here Arguments and Parameter in python
def hello(a,b=1, *args):
print(a, b, *args)
hello(1, 2, 3, 4,a=12)
since we have three parameters :
a is positional parameter
b=1 is keyword and default parameter
*args is variable length parameter
so we first assign a as positional parameter , means we have to provide value to positional argument in its position order, here order matter. but we are passing argument 1 at the place of a in calling function and then we are also providing value to a , treating as keyword argument. now a have two values :
one is positional value: a=1
second is keyworded value which is a=12
We have to change hello(1, 2, 3, 4,a=12)
to hello(1, 2, 3, 4,12)
so now a will get only one positional value which is 1 and b will get value 2 and rest of values will get *args (variable length parameter)
if we want that *args should get 2,3,4 and a should get 1 and b should get 12
then we can do like this
def hello(a,*args,b=1):
pass
hello(1, 2, 3, 4,b=12)
Something more :
def hello(a,*c,b=1,**kwargs):
print(b)
print(c)
print(a)
print(kwargs)
hello(1,2,1,2,8,9,c=12)
output :
1
(2, 1, 2, 8, 9)
1
{'c': 12}
I also ran into the same issue the other day. Google search got me here and several other places, but none gave the solution to this issue. I ended up saving the uploaded file (MultiPartFile) as a tmp file, then use FileSystemResource to upload it via RestTemplate. Here's the code I use,
String tempFileName = "/tmp/" + multiFile.getOriginalFileName();
FileOutputStream fo = new FileOutputStream(tempFileName);
fo.write(asset.getBytes());
fo.close();
parts.add("file", new FileSystemResource(tempFileName));
String response = restTemplate.postForObject(uploadUrl, parts, String.class, authToken, path);
//clean-up
File f = new File(tempFileName);
f.delete();
I am still looking for a more elegant solution to this problem.
My problem was; None admin users were getting "the http request is unauthorized with client authentication scheme 'negotiate' asmx" on my asmx services.
I gived read/execute folder permissions for the none admin users and my problem was solved.
try using:
RAISERROR('your message here!!!',0,1) WITH NOWAIT
you could also try switching to "Results to Text" it is just a few icons to the right of "Execute" on the default tool bar.
With both of the above in place, and you still you do not see the messages, make sure you are running the same server/database/owner version of the procedure that you are editing. Make sure you are hitting the RAISERROR command, make it the first command inside the procedure.
If all else fails, you could create a table:
create table temp_log (RowID int identity(1,1) primary key not null
, MessageValue varchar(255))
then:
INSERT INTO temp_log VALUES ('Your message here')
then after running the procedure (provided no rollbacks) just select
the table.
its done through service.bat file in apache tomcat7
visit this blog .. install tomcat7 on windows
Hey i have posted a video tutorial on youtube about this, you can check that and you can find here the sample code :
http://myfundatimemachine.blogspot.in/2012/06/database-connection-to-java-application.html
This works if you already have or set up the rename command (e.g. through brew install in Mac):
rename --lower-case --force somedir/*
It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.
There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit()
method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.
CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.
Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.
As some people have posted, there are numerous ways to do this. According to this website, the fastest way is the modulus operator:
if (x % 2 == 0)
total += 1; //even number
else
total -= 1; //odd number
However, here is some other code that was bench marked by the author which ran slower than the common modulus operation above:
if ((x & 1) == 0)
total += 1; //even number
else
total -= 1; //odd number
System.Math.DivRem((long)x, (long)2, out outvalue);
if ( outvalue == 0)
total += 1; //even number
else
total -= 1; //odd number
if (((x / 2) * 2) == x)
total += 1; //even number
else
total -= 1; //odd number
if (((x >> 1) << 1) == x)
total += 1; //even number
else
total -= 1; //odd number
while (index > 1)
index -= 2;
if (index == 0)
total += 1; //even number
else
total -= 1; //odd number
tempstr = x.ToString();
index = tempstr.Length - 1;
//this assumes base 10
if (tempstr[index] == '0' || tempstr[index] == '2' || tempstr[index] == '4' || tempstr[index] == '6' || tempstr[index] == '8')
total += 1; //even number
else
total -= 1; //odd number
How many people even knew of the Math.System.DivRem method or why would they use it??
Just assign it to it's own first element:
$array = $array[0];
You can use .on() to capture multiple events and then test for touch on the screen, e.g.:
$('#selector')
.on('touchstart mousedown', function(e){
e.preventDefault();
var touch = e.touches[0];
if(touch){
// Do some stuff
}
else {
// Do some other stuff
}
});
I just made sure that I am in the same directory as the json file and then simply ran this
curl -s -H "Content-Type: application/json" -XPOST localhost:9200/product/default/_bulk?pretty --data-binary @product.json
So if you too make sure you are at the same directory and run it this way. Note: product/default/ in the command is something specific to my environment. you can omit it or replace it with whatever is relevant to you.
I like to create extension
extension String {
func isValidateEmail() -> Bool {
let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
return emailPredicate.evaluate(with: self)
}
}
usage:
if emailid.text!.isValidateEmail() == false(){
//do what ever you want if string is not matched.
}
You can use .map().
Pass each element in the current matched set through a function, producing a new jQuery object containing the return value.
As the return value is a jQuery object, which contains an array, it's very common to call .get()
on the result to work with a basic array.
Use
var arr = $('input[name="pname[]"]').map(function () {
return this.value; // $(this).val()
}).get();
When using regular expressions from RegexBuddy's library, make sure to use the same matching modes in your own code as the regex from the library. If you generate a source code snippet on the Use tab, RegexBuddy will automatically set the correct matching options in the source code snippet. If you copy/paste the regex, you have to do that yourself.
In this case, as others pointed out, you missed the case insensitivity option.
There is obviously another process listening on the port. You might find out that process by using the following command:
$ lsof -i :8000
or change your tornado app's port. tornado's error info not Explicitly on this.
Joining the party late, but just as a complement, I ran into some problems with Seaborn not so long ago, because CoLab installed a version with !pip that wasn't updated. In my specific case, I couldn't use Scatterplot, for example. The answer to this is below:
To install the module, all you need is:
!pip install seaborn
To upgrade it to the most updated version:
!pip install --upgrade seaborn
If you want to install a specific version
!pip install seaborn==0.9.0
I believe all the rules common to pip apply normally, so that pretty much should work.
If you enabled it as a DHCP client then your router should get an IP address from a DHCP server. If you connect your router on a net with a DHCP server you should reach your router's administrator page on the IP address assigned by the DHCP.
you can do it better with two datagridview, you add the same datasource , hide the headers of the second, set the height of the second = to the height of the rows of the first, turn off all resizable atributes of the second, synchronize the scrollbars of both, only horizontal, put the second on the botton of the first etc.
take a look:
dgv3.ColumnHeadersVisible = false;
dgv3.Height = dgv1.Rows[0].Height;
dgv3.Location = new Point(Xdgvx, this.dgv1.Height - dgv3.Height - SystemInformation.HorizontalScrollBarHeight);
dgv3.Width = dgv1.Width;
private void dgv1_Scroll(object sender, ScrollEventArgs e)
{
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
{
dgv3.HorizontalScrollingOffset = e.NewValue;
}
}
If anyone experiences this problem with an express server, add the following middleware
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Contents of the Answer
1) How to access Model data in Javascript/Jquery code block in
.cshtml
file2) How to access Model data in Javascript/Jquery code block in
.js
file
.cshtml
fileThere are two types of c# variable (Model
) assignments to JavaScript variable.
int
, string
, DateTime
(ex: Model.Name
)Model
, Model.UserSettingsObj
)Lets look into the details of these two assignments.
For the rest of the answer lets consider the below AppUser
Model as an example.
public class AppUser
{
public string Name { get; set; }
public bool IsAuthenticated { get; set; }
public DateTime LoginDateTime { get; set; }
public int Age { get; set; }
public string UserIconHTML { get; set; }
}
And the values we assign this Model are
AppUser appUser = new AppUser
{
Name = "Raj",
IsAuthenticated = true,
LoginDateTime = DateTime.Now,
Age = 26,
UserIconHTML = "<i class='fa fa-users'></i>"
};
Lets use different syntax for assignment and observe the results.
1) Without wrapping property assignment in quotes.
var Name = @Model.Name;
var Age = @Model.Age;
var LoginTime = @Model.LoginDateTime;
var IsAuthenticated = @Model.IsAuthenticated;
var IconHtml = @Model.UserIconHTML;
As you can see there are couple of errors, Raj
and True
is considered to be javascript variables and since they dont exist its an variable undefined
error. Where as for the dateTime varialble the error is unexpected number
numbers cannot have special characters, The HTML tags are converted into its entity names so that the browser doesn't mix up your values and the HTML markup.
2) Wrapping property assignment in Quotes.
var Name = '@Model.Name';
var Age = '@Model.Age';
var LoginTime = '@Model.LoginDateTime';
var IsAuthenticated = '@Model.IsAuthenticated';
var IconHtml = '@Model.UserIconHTML';
The results are valid, So wrapping the property assignment in quotes gives us valid syntax. But note that the Number Age
is now a string, So if you dont want that we can just remove the quotes and it will be rendered as a number type.
3) Using @Html.Raw
but without wrapping it in quotes
var Name = @Html.Raw(Model.Name);
var Age = @Html.Raw(Model.Age);
var LoginTime = @Html.Raw(Model.LoginDateTime);
var IsAuthenticated = @Html.Raw(Model.IsAuthenticated);
var IconHtml = @Html.Raw(Model.UserIconHTML);
The results are similar to our test case 1. However using @Html.Raw()
on the HTML
string did show us some change. The HTML is retained without changing to its entity names.
From the docs Html.Raw()
Wraps HTML markup in an HtmlString instance so that it is interpreted as HTML markup.
But still we have errors in other lines.
4) Using @Html.Raw
and also wrapping it within quotes
var Name ='@Html.Raw(Model.Name)';
var Age = '@Html.Raw(Model.Age)';
var LoginTime = '@Html.Raw(Model.LoginDateTime)';
var IsAuthenticated = '@Html.Raw(Model.IsAuthenticated)';
var IconHtml = '@Html.Raw(Model.UserIconHTML)';
The results are good with all types. But our HTML
data is now broken and this will break the scripts. The issue is because we are using single quotes '
to wrap the the data and even the data has single quotes.
We can overcome this issue with 2 approaches.
1) use double quotes " "
to wrap the HTML part. As the inner data has only single quotes. (Be sure that after wrapping with double quotes there are no "
within the data too)
var IconHtml = "@Html.Raw(Model.UserIconHTML)";
2) Escape the character meaning in your server side code. Like
UserIconHTML = "<i class=\"fa fa-users\"></i>"
Conclusion of property assignment
Html.Raw
to interpret your HTML data as is.Lets use different syntax for assignment and observe the results.
1) Without wrapping object assignment in quotes.
var userObj = @Model;
When you assign a c# object to javascript variable the value of the .ToString()
of that oject will be assigned. Hence the above result.
2 Wrapping object assignment in quotes
var userObj = '@Model';
3) Using Html.Raw
without quotes.
var userObj = @Html.Raw(Model);
4) Using Html.Raw
along with quotes
var userObj = '@Html.Raw(Model)';
The Html.Raw
was of no much use for us while assigning a object to variable.
5) Using Json.Encode()
without quotes
var userObj = @Json.Encode(Model);
//result is like
var userObj = {"Name":"Raj",
"IsAuthenticated":true,
"LoginDateTime":"\/Date(1482572875150)\/",
"Age":26,
"UserIconHTML":"\u003ci class=\"fa fa-users\"\u003e\u003c/i\u003e"
};
We do see some change, We see our Model is being interpreted as a object. But we have those special characters changed into entity names
. Also wrapping the above syntax in quotes is of no much use. We simply get the same result within quotes.
From the docs of Json.Encode()
Converts a data object to a string that is in the JavaScript Object Notation (JSON) format.
As you have already encountered this entity Name
issue with property assignment and if you remember we overcame it with the use of Html.Raw
. So lets try that out. Lets combine Html.Raw
and Json.Encode
6) Using Html.Raw
and Json.Encode
without quotes.
var userObj = @Html.Raw(Json.Encode(Model));
Result is a valid Javascript Object
var userObj = {"Name":"Raj",
"IsAuthenticated":true,
"LoginDateTime":"\/Date(1482573224421)\/",
"Age":26,
"UserIconHTML":"\u003ci class=\"fa fa-users\"\u003e\u003c/i\u003e"
};
7) Using Html.Raw
and Json.Encode
within quotes.
var userObj = '@Html.Raw(Json.Encode(Model))';
As you see wrapping with quotes gives us a JSON data
Conslusion on Object assignment
Html.Raw
and Json.Encode
in combintaion to assign your object to javascript variable as JavaScript object.Html.Raw
and Json.Encode
also wrap it within quotes
to get a JSONNote: If you have observed the DataTime data format is not right. This is because as said earlier Converts a data object to a string that is in the JavaScript Object Notation (JSON) format
and JSON does not contain a date
type. Other options to fix this is to add another line of code to handle this type alone using javascipt Date() object
var userObj.LoginDateTime = new Date('@Html.Raw(Model.LoginDateTime)');
//without Json.Encode
.js
fileRazor syntax has no meaning in .js
file and hence we cannot directly use our Model insisde a .js
file. However there is a workaround.
1) Solution is using javascript Global variables.
We have to assign the value to a global scoped javascipt variable and then use this variable within all code block of your .cshtml
and .js
files. So the syntax would be
<script type="text/javascript">
var userObj = @Html.Raw(Json.Encode(Model)); //For javascript object
var userJsonObj = '@Html.Raw(Json.Encode(Model))'; //For json data
</script>
With this in place we can use the variables userObj
and userJsonObj
as and when needed.
Note: I personally dont suggest using global variables as it gets very hard for maintainance. However if you have no other option then you can use it with having a proper naming convention .. something like userAppDetails_global
.
2) Using function() or closure
Wrap all the code that is dependent on the model data in a function. And then execute this function from the .cshtml
file .
external.js
function userDataDependent(userObj){
//.... related code
}
.cshtml
file
<script type="text/javascript">
userDataDependent(@Html.Raw(Json.Encode(Model))); //execute the function
</script>
Note: Your external file must be referenced prior to the above script. Else the userDataDependent
function is undefined.
Also note that the function must be in global scope too. So either solution we have to deal with global scoped players.
The inclusion of your comparison class (or more specifically the AsEnumerable
call you needed to use to get it to work) meant that the sorting logic went from being based on the database server to being on the database client (your application). This meant that your client now needs to retrieve and then process a larger number of records, which will always be less efficient that performing the lookup on the database where the approprate indexes can be used.
You should try to develop a where clause that satisfies your requirements instead, see Using an IEqualityComparer with a LINQ to Entities Except clause for more details.
Just use ` character to separate command on multiline
git difftool -d HEAD filename.txt
This shows a comparison using VI slit window in the terminal.
Make sure that "Named Pipes" are enabled from "SQL Server Configuration Manager". This worked for me.
Aahh got it... I got it working :)
Thanks Christopher, your suggesion is correct.
But, finding "Default SMTP Virtual Server" was tricky ;)
Even if you use IIS7 to deploy your web site, you have to open IIS6 Manager to configure SMTP server (why?).
I configured SMTP server as follows to make things work:
If you do not care so much about efficiency, you could rely on numpy's array indexing to make it elegant:
a = ['123', 'abc', 456]
order = [2, 0, 1]
a2 = list( np.array(a, dtype=object)[order] )
While it is really not possible to use a char
or a string
as the base for an enum, i think this is not what you really like to do.
Like you mentioned you'd like to have an enum of possibilities and show a string representation of this within a combo box. If the user selects one of these string representations you'd like to get out the corresponding enum. And this is possible:
First we have to link some string to an enum value. This can be done by using the DescriptionAttribute
like it is described here or here.
Now you need to create a list of enum values and corresponding descriptions. This can be done by using the following method:
/// <summary>
/// Creates an List with all keys and values of a given Enum class
/// </summary>
/// <typeparam name="T">Must be derived from class Enum!</typeparam>
/// <returns>A list of KeyValuePair<Enum, string> with all available
/// names and values of the given Enum.</returns>
public static IList<KeyValuePair<T, string>> ToList<T>() where T : struct
{
var type = typeof(T);
if (!type.IsEnum)
{
throw new ArgumentException("T must be an enum");
}
return (IList<KeyValuePair<T, string>>)
Enum.GetValues(type)
.OfType<T>()
.Select(e =>
{
var asEnum = (Enum)Convert.ChangeType(e, typeof(Enum));
return new KeyValuePair<T, string>(e, asEnum.Description());
})
.ToArray();
}
Now you'll have a list of key value pairs of all enums and their description. So let's simply assign this as a data source for a combo box.
var comboBox = new ComboBox();
comboBox.ValueMember = "Key"
comboBox.DisplayMember = "Value";
comboBox.DataSource = EnumUtilities.ToList<Separator>();
comboBox.SelectedIndexChanged += (sender, e) =>
{
var selectedEnum = (Separator)comboBox.SelectedValue;
MessageBox.Show(selectedEnum.ToString());
}
The user sees all the string representations of the enum and within your code you'll get the desired enum value.
You can try this:
int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
this.Controls.Add(txt);
txt.Top = cleft * 40;
txt.Size = new Size(200, 16);
txt.Left = 150;
cleft = cleft + 1;
Label lbl = new Label();
this.Controls.Add(lbl);
lbl.Top = aleft * 40;
lbl.Size = new Size(100, 16);
lbl.ForeColor = Color.Blue;
lbl.Text = "BoxNo/CardNo";
lbl.Left = 70;
aleft = aleft + 1;
return;
}
private void btd_Click(object sender, EventArgs e)
{
//Here you Delete Text Box One By One(int ix for Text Box)
for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
//Here you Delete Lable One By One(int ix for Lable)
for (int x = this.Controls.Count - 2; x >= 0; x--)
{
if (this.Controls[ix] is TextBox)
this.Controls[ix].Dispose();
if (this.Controls[x] is Label)
this.Controls[x].Dispose();
return;
}
}
Another approach for a delayed component:
Delayed.jsx
:
import React from 'react';
import PropTypes from 'prop-types';
class Delayed extends React.Component {
constructor(props) {
super(props);
this.state = {hidden : true};
}
componentDidMount() {
setTimeout(() => {
this.setState({hidden: false});
}, this.props.waitBeforeShow);
}
render() {
return this.state.hidden ? '' : this.props.children;
}
}
Delayed.propTypes = {
waitBeforeShow: PropTypes.number.isRequired
};
export default Delayed;
Usage:
import Delayed from '../Time/Delayed';
import React from 'react';
const myComp = props => (
<Delayed waitBeforeShow={500}>
<div>Some child</div>
</Delayed>
)
I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single =
instead of ==
or ===
. For example, when you see this:
if (value = someFunction()) {
...
}
you don't know if that's what they meant to do, or if they intended to write this:
if (value == someFunction()) {
...
}
If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:
if ((value = someFunction()) === <whatever truthy value you are expecting>) {
...
}
Have a look at jQuery's .parseXML()
[docs]:
var $xml = $(jQuery.parseXML(xml));
var $test = $xml.find('Page[Name="test"] > controls > test');
In :w !sudo tee %
...
%
means "the current file"As eugene y pointed out, %
does indeed mean "the current file name", which is passed to tee
so that it knows which file to overwrite.
(In substitution commands, it's slightly different; as :help :%
shows, it's equal to 1,$ (the entire file)
(thanks to @Orafu for pointing out that this does not evaluate to the filename). For example, :%s/foo/bar
means "in the current file, replace occurrences of foo
with bar
." If you highlight some text before typing :s
, you'll see that the highlighted lines take the place of %
as your substitution range.)
:w
isn't updating your fileOne confusing part of this trick is that you might think :w
is modifying your file, but it isn't. If you opened and modified file1.txt
, then ran :w file2.txt
, it would be a "save as"; file1.txt
wouldn't be modified, but the current buffer contents would be sent to file2.txt
.
Instead of file2.txt
, you can substitute a shell command to receive the buffer contents. For instance, :w !cat
will just display the contents.
If Vim wasn't run with sudo access, its :w
can't modify a protected file, but if it passes the buffer contents to the shell, a command in the shell can be run with sudo. In this case, we use tee
.
As for tee
, picture the tee
command as a T-shaped pipe in a normal bash piping situation: it directs output to specified file(s) and also sends it to standard output, which can be captured by the next piped command.
For example, in ps -ax | tee processes.txt | grep 'foo'
, the list of processes will be written to a text file and passed along to grep
.
+-----------+ tee +------------+
| | -------- | |
| ps -ax | -------- | grep 'foo' |
| | || | |
+-----------+ || +------------+
||
+---------------+
| |
| processes.txt |
| |
+---------------+
(Diagram created with Asciiflow.)
See the tee
man page for more info.
In the situation your question describes, using tee
is a hack because we're ignoring half of what it does. sudo tee
writes to our file and also sends the buffer contents to standard output, but we ignore standard output. We don't need to pass anything to another piped command in this case; we're just using tee
as an alternate way of writing a file and so that we can call it with sudo
.
You can add this to your .vimrc
to make this trick easy-to-use: just type :w!!
.
" Allow saving of files as sudo when I forgot to start vim using sudo.
cmap w!! w !sudo tee > /dev/null %
The > /dev/null
part explicitly throws away the standard output, since, as I said, we don't need to pass anything to another piped command.
This should do what you want:
C:\PS> if ('=keep this,' -match '=([^,]*)') { $matches[1] }
keep this
I also encountered similar problem which is asked here. The issue was that some applications come with their own JRE and sometimes the installed JDK appears at lower priority level in environment path. Now there are two options:
I also removed the path as suggested by @CrazyCoder
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
Just use like this somewhere inside the form
@method('PUT')
I was in the same trouble. For my case, that was a conflict between /etc/zabbix/zabbix_agentd.conf and zabbix_server.conf parameters. I adjusted
"DBHost=localhost",
"DBName=zabbix",
"DBUser=zabbix",
"DBPassword=******",
"DebugLevel=3"
"ListenPort".
If you run the default installation, you should keep ListenPort=10051 for the server and 10050 for the agent.
Cheers!
<form id="myform">
<input type="textbox" id="field"/>
<input type="button" value="submit">
</form>
<script>
$(function () {
$("#field").keyup(function (event) {
if (event.which === 13) {
document.myform.submit();
}
}
});
</script>
I would suggest:
DECLARE @sqlStatement nvarchar(MAX),
@tableName nvarchar(50) = 'TripEvent',
@columnName nvarchar(50) = 'CreatedDate';
SELECT @sqlStatement = 'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT ' + dc.name + ';'
FROM sys.default_constraints AS dc
LEFT JOIN sys.columns AS sc
ON (dc.parent_column_id = sc.column_id)
WHERE dc.parent_object_id = OBJECT_ID(@tableName)
AND type_desc = 'DEFAULT_CONSTRAINT'
AND sc.name = @columnName
PRINT' ['+@tableName+']:'+@@SERVERNAME+'.'+DB_NAME()+'@'+CONVERT(VarChar, GETDATE(), 127)+'; '+@sqlStatement;
IF(LEN(@sqlStatement)>0)EXEC sp_executesql @sqlStatement
The following example the fastest (not parallelized) way list files and sub-folders in a directory tree handling exceptions. It would be faster to use Directory.EnumerateDirectories using SearchOption.AllDirectories to enumerate all directories, but this method will fail if hits a UnauthorizedAccessException or PathTooLongException.
Uses the generic Stack collection type, which is a last in first out (LIFO) stack and does not use recursion. From https://msdn.microsoft.com/en-us/library/bb513869.aspx, allows you to enumerate all sub-directories and files and deal effectively with those exceptions.
public class StackBasedIteration
{
static void Main(string[] args)
{
// Specify the starting folder on the command line, or in
// Visual Studio in the Project > Properties > Debug pane.
TraverseTree(args[0]);
Console.WriteLine("Press any key");
Console.ReadKey();
}
public static void TraverseTree(string root)
{
// Data structure to hold names of subfolders to be
// examined for files.
Stack<string> dirs = new Stack<string>(20);
if (!System.IO.Directory.Exists(root))
{
throw new ArgumentException();
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = System.IO.Directory.EnumerateDirectories(currentDir); //TopDirectoryOnly
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file. It may or may not be acceptable
// to ignore the exception and continue enumerating the remaining files and
// folders. It is also possible (but unlikely) that a DirectoryNotFound exception
// will be raised. This will happen if currentDir has been deleted by
// another application or thread after our call to Directory.Exists. The
// choice of which exceptions to catch depends entirely on the specific task
// you are intending to perform and also on how much you know with certainty
// about the systems on which this code will run.
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
string[] files = null;
try
{
files = System.IO.Directory.EnumerateFiles(currentDir);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
// Perform the required action on each file here.
// Modify this block to perform your required task.
foreach (string file in files)
{
try
{
// Perform whatever action is required in your scenario.
System.IO.FileInfo fi = new System.IO.FileInfo(file);
Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
}
catch (System.IO.FileNotFoundException e)
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
Console.WriteLine(e.Message);
continue;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
foreach (string str in subDirs)
dirs.Push(str);
}
}
}
The current implementation of async
/ await
only supports the await
keyword inside of async
functions Change your start
function signature so you can use await
inside start
.
var start = async function(a, b) {
}
For those interested, the proposal for top-level await
is currently in Stage 2: https://github.com/tc39/proposal-top-level-await
Suggested From Android Studio lint check : Remove Unnecessary boxing : So, unboxing is :
public static long integerToLong (int minute ){
int delay = minute*1000;
long diff = (long) delay;
return diff ;
}
The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:
When you iterate over it with for i in ar:
the values of i will be 2, 4 and 6. So, when you try to access ar[i]
for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.
If you intend to use indexes anyhow, try using for index, value in enumerate(ar):
, then theSum = theSum + ar[index]
should work just fine.
If your sed
allows in place editing via the -i
parameter:
sed -e 's/$/string after each line/' -i filename
If not, you have to make a temporary file:
typeset TMP_FILE=$( mktemp )
touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename
Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Instead do this:
var crypto = require('crypto');
var hmac;
var algorithm = 'sha1';
var key = 'abcdeg';
var text = 'I love cupcakes';
var hash;
hmac = crypto.createHmac(algorithm, key);
// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');
// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
hash = hmac.read();
//...do something with the hash...
});
More formally, if you wish, the line
hmac.end(text, function () {
could be written
hmac.end(text, 'utf8', function () {
because in this example text is a utf string
You can do as @Hugo of @Laurent said, or you can use git rebase
to delete the commits you want to get rid off, if you know which ones. I tend to use git rebase -i head~N
(where N is a number, allowing you to manipulate the last N commits) for this kind of operations.
Chengs's answer is correct, howewer according to the admin docs not every admin template can be overwritten this way: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#overriding-admin-templates
Templates which may be overridden per app or model
Not every template in contrib/admin/templates/admin may be overridden per app or per model. The following can:
app_index.html change_form.html change_list.html delete_confirmation.html object_history.html
For those templates that cannot be overridden in this way, you may still override them for your entire project. Just place the new version in your templates/admin directory. This is particularly useful to create custom 404 and 500 pages
I had to overwrite the login.html of the admin and therefore had to put the overwritten template in this folder structure:
your_project
|-- your_project/
|-- myapp/
|-- templates/
|-- admin/
|-- login.html <- do not misspell this
(without the myapp subfolder in the admin) I do not have enough repution for commenting on Cheng's post this is why I had to write this as new answer.
I use
function windowHasScroll()
{
return document.body.clientHeight > document.documentElement.clientHeight;
}
I tried a lot of stuff the guys informed here, without success. After, I just realized I was using the Deno Support for VSCode extension. I uninstalled it and a restart was required. After restart the problem was solved.