Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
I'm using babel
and the following syntax is working for me:
class MyClass {
static constant1 = 33;
static constant2 = {
case1: 1,
case2: 2,
};
// ...
}
MyClass.constant1 === 33
MyClass.constant2.case1 === 1
Please consider that you need the preset "stage-0"
.
To install it:
npm install --save-dev babel-preset-stage-0
// in .babelrc
{
"presets": ["stage-0"]
}
Update:
currently use stage-3
I do it with this python one-liner:
python -c "import subprocess as sp;[sp.call('cordova plugin rm ' + p.split()[0], shell=True) for p in sp.check_output('cordova plugin', shell=True).split('\n') if p]"
Obviously it doesn't handle any sort of error conditions, but it gets the job done.
Your method doesn't have any callbacks so there is no reason to use .CallBack()
. You can simply return a Task with the desired values using .Returns()
and Task.FromResult, e.g.:
MyType someValue=...;
mock.Setup(arg=>arg.DoSomethingAsync())
.Returns(Task.FromResult(someValue));
Update 2014-06-22
Moq 4.2 has two new extension methods to assist with this.
mock.Setup(arg=>arg.DoSomethingAsync())
.ReturnsAsync(someValue);
mock.Setup(arg=>arg.DoSomethingAsync())
.ThrowsAsync(new InvalidOperationException());
Update 2016-05-05
As Seth Flowers mentions in the other answer, ReturnsAsync
is only available for methods that return a Task<T>
. For methods that return only a Task,
.Returns(Task.FromResult(default(object)))
can be used.
As shown in this answer, in .NET 4.6 this is simplified to .Returns(Task.CompletedTask);
, e.g.:
mock.Setup(arg=>arg.DoSomethingAsync())
.Returns(Task.CompletedTask);
foo = ['a', 'b', 'c', 'd', 'e']
number_of_samples = 1
In python 2:
random_items = random.sample(population=foo, k=number_of_samples)
In python 3:
random_items = random.choices(population=foo, k=number_of_samples)
I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:
{
template: '<div>' +
'<div class="title">{{title}}</div>' +
'<div class="body" ng-transclude></div>' +
'</div>',
link: function(scope, element, attrs) {
// Title element
var title = angular.element(element.children()[0]),
// ...
}
}
Your userPhotos
array is option-typed, you should retrieve the actual underlying object with !
(if you want an error in case the object isn't there) or ?
(if you want to receive nil
in url):
let userPhotos = currentUser?.photos
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
But to preserve safe nil handling, you better use functional approach, for instance, with map
, like this:
let urls = userPhotos?.map{ $0.url }
Set type=submit
to the button you'd like to be default and type=button
to other buttons. Now in the form below you can hit Enter in any input fields, and the Render
button will work (despite the fact it is the second button in the form).
Example:
<button id='close_button' class='btn btn-success'
type=button>
<span class='glyphicon glyphicon-edit'> </span> Edit program
</button>
<button id='render_button' class='btn btn-primary'
type=submit> <!-- Here we use SUBMIT, not BUTTON -->
<span class='glyphicon glyphicon-send'> </span> Render
</button>
Tested in FF24 and Chrome 35.
In medicine there are four genders: male, female, indeterminate, and unknown. You mightn't need all four but you certainly need 1, 2, and 4. It's not appropriate to have a default value for this datatype. Even less to treat it as a Boolean with 'is' and 'isn't' states.
It's shipped with Android Studio now. Just go to Build/Analyze APK... then select your APK :)
There is an interesting project on github called Excel Builder (.js)
that offers a client-side way of downloading Excel xlsx files and includes options for formatting the Excel spreadsheet.
https://github.com/stephenliberty/excel-builder.js
You may encounter both browser and Excel compatibility issues using this library, but under the right conditions, it may be quite useful.
Another github project with less Excel options but less worries about Excel compatibility issues can be found here: ExcellentExport.js
https://github.com/jmaister/excellentexport
If you are using AngularJS, there is ng-csv:
a "Simple directive that turns arrays and objects into downloadable CSV files".
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
For python markdown with attr_list extension the syntax is a little different:
{: #someid .someclass somekey='some value' }
Example:
[Click here](http://exmaple.com){: .btn .btn-primary }
Lead information paragraph
{: .lead }
what's wrong with:
int myInt = myFloat;
bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)
you can also create a dict with the classes themselves as keys, not necessarily the classnames
typefunc={
int:lambda x: x*2,
str:lambda s:'(*(%s)*)'%s
}
def transform (param):
print typefunc[type(param)](param)
transform (1)
>>> 2
transform ("hi")
>>> (*(hi)*)
here typefunc
is a dict that maps a function for each type. transform
gets that function and applies it to the parameter.
of course, it would be much better to use 'real' OOP
There is a new function in C standard for getting a line without specifying its size. getline
function allocates string with required size automatically so there is no need to guess about string's size. The following code demonstrate usage:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, stdin)) != -1) {
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
if (ferror(stdin)) {
/* handle error */
}
free(line);
return 0;
}
Thanks Vineet Reynolds. The link you provided held a lot of user comments - one of which I tried in desperation and it helped. I added this method :
// Do not do this in production!!!
HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
public boolean verify(String string,SSLSession ssls) {
return true;
}
});
This seems fine for me now, though I know this solution is temporary. I am working with the network people to identify why my hosts file is being ignored.
You can't. The alert is a simple popup where you only can affect the content text.
If you want to change anything else, you have to use a different way of creating a popup.
The X-UA-Compatible
meta
element only changes the Document mode, not the Browser mode. The Browser mode is chosen before the page is requested, so there is no way to include any markup, JavaScript or such to change this. While the Document mode falls back to older standards and quirks modes of the rendering engine, the Browser mode just changes things like how the browser identifies, such as the User Agent string.
If you’d like to change the Browser mode for all users (rather than changing it manually in the tools or through the settings), the only way (AFAICT) is to get your site added to Microsoft’s Copat View List. This is maintained by Microsoft to apply overrides to sites which break. There is information on how to remove your site from the compat view list, but none I can find to request that you're added.
The preferred method however is to try to fix any issues on the site first, as when you don’t run using the latest document and browser mode you can not take advantage of improvements in the browser, such as increased performance.
I tried to change target sdk to 13 but does not works!!
then when I changed compileSdkVersion 13
to compileSdkVersion 14
is compiled successfully :)
NOTE: I Work with Android Studio not Eclipse
//I think its simple like
#include<stdio.h>
int main()
{
int a1[100],a2[100],i,t,l1,l2,n;
printf("Enter the number of elements:\n");
scanf("%d",&n);
printf("Enter the elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a1[i]);
}
l1=a1[0];
for(i=0;i<n;i++)
{
if(a1[i]>=l1)
{
l1=a1[i];
t=i;
}
}
for(i=0;i<(n-1);i++)
{
if(i==t)
{
continue;
}
else
{
a2[i]=a1[i];
}
}
l2=a2[0];
for(i=1;i<(n-1);i++)
{
if(a2[i]>=l2 && a2[i]<l1)
{
l2=a2[i];
}
}
printf("Second highest number is %d",l2);
return 0;
}
The second option didn't work for me because the .Text element was out of scope (C# 4.0 VS2008). This was my solution...
string test = null;
foreach (ComboBoxItem item in e.AddedItems)
{
test = item.Content.ToString();
break;
}
ALT + p works for me on Enthought Python in Windows.
There are some dedicated classes for this:
import java.text.*;
final CharacterIterator it = new StringCharacterIterator(s);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
// process c
...
}
Most recent browsers (and node.js) support Object.keys() which returns an array with all the keys in your object literal so you could do the following:
var ad = {};
Object.keys(ad).length;//this will be 0 in this case
Browser Support: Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Yes, there is a static DoEvents method in the Application class in the System.Windows.Forms namespace. System.Windows.Forms.Application.DoEvents() can be used to process the messages waiting in the queue on the UI thread when performing a long-running task in the UI thread. This has the benefit of making the UI seem more responsive and not "locked up" while a long task is running. However, this is almost always NOT the best way to do things. According to Microsoft calling DoEvents "...causes the current thread to be suspended while all waiting window messages are processed." If an event is triggered there is a potential for unexpected and intermittent bugs that are difficult to track down. If you have an extensive task it is far better to do it in a separate thread. Running long tasks in a separate thread allows them to be processed without interfering with the UI continuing to run smoothly. Look here for more details.
Here is an example of how to use DoEvents; note that Microsoft also provides a caution against using it.
By default Entity Framework uses lazy-loading for navigation properties. That's why these properties should be marked as virtual - EF creates proxy class for your entity and overrides navigation properties to allow lazy-loading. E.g. if you have this entity:
public class MemberLoan
{
public string LoandProviderCode { get; set; }
public virtual Membership Membership { get; set; }
}
Entity Framework will return proxy inherited from this entity and provide DbContext instance to this proxy in order to allow lazy loading of membership later:
public class MemberLoanProxy : MemberLoan
{
private CosisEntities db;
private int membershipId;
private Membership membership;
public override Membership Membership
{
get
{
if (membership == null)
membership = db.Memberships.Find(membershipId);
return membership;
}
set { membership = value; }
}
}
So, entity has instance of DbContext which was used for loading entity. That's your problem. You have using
block around CosisEntities usage. Which disposes context before entities are returned. When some code later tries to use lazy-loaded navigation property, it fails, because context is disposed at that moment.
To fix this behavior you can use eager loading of navigation properties which you will need later:
IQueryable<MemberLoan> query = db.MemberLoans.Include(m => m.Membership);
That will pre-load all memberships and lazy-loading will not be used. For details see Loading Related Entities article on MSDN.
Yes you can do that.
Materials you need:
1. First set the internet permissions in your manifest file
<uses-permission android:name="android.permission.INTERNET" />
2. Make a class to make an HTTPRequest from the server (i am using json parisng to get the values)
for eg:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
3. In your MainActivity
Make an object of the class JsonFunctions
and pass the url as an argument from where you want to get the data
eg:
JSONObject jsonobject;
jsonobject = JSONfunctions.getJSONfromURL("http://YOUR_DATABASE_URL");
4. And then finally read the jsontags and store the values in an arraylist and later show it in listview if you want
and if you have any problem you can follow this blog he gives excellent android tutorials AndroidHive
Since the above answer i wrote was long back and now HttpClient
, HttpPost
,HttpEntity
have been removed in Api 23. You can use the below code in the build.gradle(app-level) to still continue using org.apache.http
in your project.
android {
useLibrary 'org.apache.http.legacy'
signingConfigs {}
buildTypes {}
}
or You can use HttpURLConnection
like below to get your response from server
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
or You can use 3rd party Library like Volley
, Retrofit
to call the webservice api and get the response and later parse it with using FasterXML-jackson
, google-gson
.
As of Jackson 1.6, you can use:
JsonNode node = mapper.valueToTree(map);
or
JsonNode node = mapper.convertValue(object, JsonNode.class);
Source: is there a way to serialize pojo's directly to treemodel?
[A-Za-z0-9_.-]*
This will also match for empty strings, if you do not want that exchange the last *
for an +
Swift 3
class MyObject: NSObject, NSCoding {
let name : String
let url : String
let desc : String
init(tuple : (String,String,String)){
self.name = tuple.0
self.url = tuple.1
self.desc = tuple.2
}
func getName() -> String {
return name
}
func getURL() -> String{
return url
}
func getDescription() -> String {
return desc
}
func getTuple() -> (String, String, String) {
return (self.name,self.url,self.desc)
}
required init(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.url, forKey: "url")
aCoder.encode(self.desc, forKey: "desc")
}
}
to store and retrieve:
func save() {
let data = NSKeyedArchiver.archivedData(withRootObject: object)
UserDefaults.standard.set(data, forKey:"customData" )
}
func get() -> MyObject? {
guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
}
The Java.util.Date and .Calendar and SimpleDateFormat in Java (and Android) are notoriously troublesome. Avoid them. They are so bad that Sun/Oracle gave up on them, supplanting them with the new java.time package in Java 8 (not in Android as of 2014). The new java.time
was inspired by the Joda-Time library.
Joda-Time does work in Android.
Search StackOverflow for "Joda" to find many examples and much discussion.
A tidbit of source code using Joda-Time 2.4.
Standard format.
String output = DateTime.now().toString();
// Current date-time in user's default time zone with a String representation formatted to the ISO 8601 standard.
Localized format.
String output = DateTimeFormat.forStyle( "FF" ).print( DateTime.now() );
// Full (long) format localized for this user's language and culture.
algorithm: procedure/formula for solving a problem
How do analyze algorithms and how can we compare algorithms against each other?
example: you and a friend are asked to create a function to sum the numbers from 0 to N. You come up with f(x) and your friend comes up with g(x). Both functions have the same result, but a different algorithm. In order to objectively compare the efficiency of the algorithms we use Big-O notation.
Big-O notation: describes how quickly runtime will grow relative to the input as the input get arbitrarily large.
3 key takeaways:
Space complexity: aside from time complexity, we also care about space complexity (how much memory/space an algorithm uses). Instead of checking the time of operations, we check the size of the allocation of memory.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
var form=$("#myForm");_x000D_
$("#smt").click(function(){_x000D_
$.ajax({_x000D_
type:"POST",_x000D_
url:form.attr("action"),_x000D_
data:form.serialize(),_x000D_
success: function(response){_x000D_
console.log(response); _x000D_
}_x000D_
});_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
This is perfect code , there is no problem.. You have to check that in php script.
Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.
margin:auto
However, old IE doesn't grok this so one usually adds text-align: center
to an outer containing element. You wouldn't think that would work but the same IE's that ignore auto
also incorrectly apply the text align center to block level inner elements so things work out.
And this doesn't actually do a real float.
While using the previously mentioned childForm.ShowDialog(this) will disable your main form, it still doesent look very disabled. However if you call Enabled = false before ShowDialog() and Enable = true after you call ShowDialog() the main form will even look like it is disabled.
var childForm = new Form();
Enabled = false;
childForm .ShowDialog(this);
Enabled = true;
As of today (April 30, 2012) you can use Underscore as usual on your Node.js code. Previous comments are right pointing that REPL interface (Node's command line mode) uses the "_" to hold the last result BUT on you are free to use it on your code files and it will work without a problem by doing the standard:
var _ = require('underscore');
Happy coding!
If you are using the background image for the rounded corners then I would rather increase the padding style of the main div to give enough room for the rounded corners of the background image to be visible.
Try increasing the padding of the main div style:
#mainWrapperDivWithBGImage
{
background: url("myImageWithRoundedCorners.jpg") no-repeat scroll 0 0 transparent;
height: 248px;
margin: 0;
overflow: hidden;
padding: 10px 10px;
width: 996px;
}
P.S: I assume the rounded corners have a radius of 10px.
doSome("task")must be returning a promise object , and that promise always have a then function .So your code is just like this
promise.then(function(env) {
// logic
});
and you know this is just an ordinary call to member function .
In my case I used Framework64 like below
cd\
cd "C:\Windows\Microsoft.NET\Framework64\v4.0.30319"
installutil.exe "C:\XXX\Bin\ABC.exe"
pause
please don't try with the old cv module, use cv2:
import cv2
cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)
x1,y1 ------
| |
| |
| |
--------x2,y2
[edit] to append the follow-up questions below:
cv2.imwrite("my.png",img)
cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever
If you add jars in tomcat's lib folder you can see this error
For anybody interested in Titanium i must say that they don't have a very good documentation some classes, properties, methods are missing. But a lot is "documented" in their sample app the KitchenSink so it is not THAT bad.
I wanted to change the indentation of my existing HTML file from 4 spaces to 2 spaces.
I clicked the 'Spaces: 4' button in the status bar and changed them to two in the next dialog box.
I use 'vim' extension. I don't how to re-indent without vim
To re-indent my current file, I used this:
gg
=
G
<
stands for the less-than sign: <
>
stands for the greater-than sign: >
≤
stands for the less-than or equals sign: =
≥
stands for the greater-than or equals sign: =
SELECT a.image_id
FROM list a
INNER JOIN list b
ON a.image_id = b.image_id
AND b.style_id = 25
AND b.style_value = 'big'
INNER JOIN list c
ON a.image_id = c.image_id
AND c.style_id = 27
AND c.style_value = 'round'
WHERE a.style_id = 24
AND a.style_value = 'red'
You can use deletgate
with scp
too:
- name: Copy file to another server
become: true
shell: "scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null admin@{{ inventory_hostname }}:/tmp/file.yml /tmp/file.yml"
delegate_to: other.example.com
Because of delegate
the command is run on the other server and it scp
's the file to itself.
You have to call close()
on the GZIPOutputStream
before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush()
probably won't help ... though calling finish()
instead of close()
should work. Look at the javadocs.)
Here's the correct code (in Java);
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZipTest {
public static void main(String[] args) throws
FileNotFoundException, IOException {
String name = "/tmp/test";
GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
gz.write(10);
gz.close(); // Remove this to reproduce the reported bug
System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
}
}
(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)
OAuth(Open Authorization) is an open standard for access granting/deligation protocol. It used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords. It does not deal with authentication.
Or
OAuth 2.0 is a protocol that allows a user to grant limited access to their resources on one site, to another site, without having to expose their credentials.
Analogy 1: Many luxury cars today come with a valet key. It is a special key you give the parking attendant and unlike your regular key, will not allow the car to drive more than a mile or two. Some valet keys will not open the trunk, while others will block access to your onboard cell phone address book. Regardless of what restrictions the valet key imposes, the idea is very clever. You give someone limited access to your car with a special key, while using your regular key to unlock everything. src from auth0
Analogy 2: Assume, we want to fill an application form for a bank account. Here Oauth works as, instead of filling the form by applicant, bank can fill the form using Adhaar or passport.
Here the following three entities are involved:
Or you might have something like this (redeclaring a variable):
var data = [];
var data =
Simply point the new repo by changing the GIT repo URL with this command:
git remote set-url origin [new repo URL]
Example: git remote set-url origin [email protected]:Batman/batmanRepoName.git
Now, pushing and pulling are linked to the new REPO.
Then push normally like so:
git push -u origin master
For SQL 2005 and up
SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
FROM YourTable
for 2000 you need to do something like this
SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
INTO #Ranks FROM YourTable WHERE 1=0
INSERT INTO #Ranks
SELECT SomeColumn FROM YourTable
ORDER BY SomeColumn
SELECT * FROM #Ranks
Order By Ranks
see also here Row Number
For me this worked after I downloaded AJAX Unobtrusive library via NuGet :
Search and install via NuGet Packages: Microsoft.jQuery.Unobtrusive.Ajax
Than add in the view the references to jquery and AJAX Unobtrusive:
@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"> </script>
As with the present java SE 8 release with it's excellent date time API with java.time
these kind of calculation can be done more easily instead of using java.util.Calendar
and java.util.Date
.
Now as a sample example for scheduling a task with your use case:
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
ZonedDateTime nextRun = now.withHour(5).withMinute(0).withSecond(0);
if(now.compareTo(nextRun) > 0)
nextRun = nextRun.plusDays(1);
Duration duration = Duration.between(now, nextRun);
long initalDelay = duration.getSeconds();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new MyRunnableTask(),
initalDelay,
TimeUnit.DAYS.toSeconds(1),
TimeUnit.SECONDS);
The initalDelay
is computed to ask the scheduler to delay the execution in TimeUnit.SECONDS
. Time difference issues with unit milliseconds and below seems to be negligible for this use case. But you can still make use of duration.toMillis()
and TimeUnit.MILLISECONDS
for handling the scheduling computaions in milliseconds.
And also TimerTask is better for this or ScheduledExecutorService?
NO: ScheduledExecutorService
seemingly better than TimerTask
. StackOverflow has already an answer for you.
From @PaddyD,
You still have the issue whereby you need to restart this twice a year if you want it to run at the right local time. scheduleAtFixedRate won't cut it unless you are happy with the same UTC time all year.
As it is true and @PaddyD already has given a workaround(+1 to him), I am providing a working example with Java8 date time API with ScheduledExecutorService
. Using daemon thread is dangerous
class MyTaskExecutor
{
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
MyTask myTask;
volatile boolean isStopIssued;
public MyTaskExecutor(MyTask myTask$)
{
myTask = myTask$;
}
public void startExecutionAt(int targetHour, int targetMin, int targetSec)
{
Runnable taskWrapper = new Runnable(){
@Override
public void run()
{
myTask.execute();
startExecutionAt(targetHour, targetMin, targetSec);
}
};
long delay = computeNextDelay(targetHour, targetMin, targetSec);
executorService.schedule(taskWrapper, delay, TimeUnit.SECONDS);
}
private long computeNextDelay(int targetHour, int targetMin, int targetSec)
{
LocalDateTime localNow = LocalDateTime.now();
ZoneId currentZone = ZoneId.systemDefault();
ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
ZonedDateTime zonedNextTarget = zonedNow.withHour(targetHour).withMinute(targetMin).withSecond(targetSec);
if(zonedNow.compareTo(zonedNextTarget) > 0)
zonedNextTarget = zonedNextTarget.plusDays(1);
Duration duration = Duration.between(zonedNow, zonedNextTarget);
return duration.getSeconds();
}
public void stop()
{
executorService.shutdown();
try {
executorService.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException ex) {
Logger.getLogger(MyTaskExecutor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Note:
MyTask
is an interface with function execute
. ScheduledExecutorService
, Always use awaitTermination
after invoking shutdown
on it: There's always a likelihood your task is stuck / deadlocking and the user would wait forever.The previous example I gave with Calender was just an idea which I did mention, I avoided exact time calculation and Daylight saving issues. Updated the solution on per the complain of @PaddyD
Here is a solutions for MAC PC:
Open terminal and type following command to show hidden files:
defaults write com.apple.finder AppleShowAllFiles YES
after that go to current user folder using finder, then you can see the Library folder in it which is hidden type
suppose in my case the username is 'Delta' so the folder path is:
OS X: ~Delta/Library/Preferences/SmartGit/<main-smartgit-version>
Remove settings file and change option to Non Commercial..
You may be looking for auto-fill
:
grid-template-columns: repeat(auto-fill, 186px);
Demo: http://codepen.io/alanbuchanan/pen/wJRMox
To use up the available space more efficiently, you could use minmax
, and pass in auto
as the second argument:
grid-template-columns: repeat(auto-fill, minmax(186px, auto));
Demo: http://codepen.io/alanbuchanan/pen/jBXWLR
If you don't want the empty columns, you could use auto-fit
instead of auto-fill
.
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
This works perfectly
<i class="fa fa-power-off text-gray" style="transform: rotate(90deg);"></i>
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
What it does:
if set to "true", any cached data used by the OSGi framework and eclipse runtime will be wiped clean. This will clean the caches used to store bundle dependency resolution and eclipse extension registry data. Using this option will force eclipse to reinitialize these caches.
How to use it:
eclipse.ini
file located in your Eclipse install directory and insert -clean
as the first line. -clean
as the first argument. -clean
argument. The advantage to this step is you can keep the script around and use it each time you want to clean out the workspace. You can name it something like eclipse-clean.bat
(or eclipse-clean.sh
). (From: http://www.eclipsezone.com/eclipse/forums/t61566.html)
Other eclipse command line options: http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html
$(document).ready(function(){
$("div.width").append($("div.width").width()+" px");
$("div.innerWidth").append($("div.innerWidth").innerWidth()+" px");
$("div.outerWidth").append($("div.outerWidth").outerWidth()+" px");
});
<div class="width">Width of this div container without including padding is: </div>
<div class="innerWidth">width of this div container including padding is: </div>
<div class="outerWidth">width of this div container including padding and margin is: </div>
Here's a move that I'm using to set the color dynamically, it defaults to primary theme if the variable is undefined.
in your component define your color
/**Sets the button colors - Defaults to primary them color */
@Input('buttonsColor') _buttonsColor: string
in your style (sass here) - this forces the icon to use the color of it's container
.mat-custom{
.mat-icon, .mat-icon-button{
color:inherit !important;
}
}
in your html surround your button with a div
<div [class.mat-custom]="!!_buttonsColor" [style.color]="_buttonsColor">
<button mat-icon-button (click)="doSomething()">
<mat-icon [svgIcon]="'refresh'" color="primary"></mat-icon>
</button>
</div>
Use collectl
which has extensive process I/O monitoring including monitoring threads.
Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl
reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html
Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?
If you don't want to pass interface state or props model you can try this
class App extends React.Component <any, any>
Try :
Msg * "insert your message here"
If you are using Windows XP's command.com, this will open a message box.
Opening a new cmd window isn't quite what you were asking for, I gather. You could also use VBScript, and use this with your .bat file. You would open it from the bat file with this command:
cd C:\"location of vbscript"
What this does is change the directory command.com will search for files from, then on the next line:
"insert name of your vbscript here".vbs
Then you create a new Notepad document, type in
<script type="text/vbscript">
MsgBox "your text here"
</script>
You would then save this as a .vbs file (by putting ".vbs" at the end of the filename), save as "All Files" in the drop down box below the file name (so it doesn't save as .txt), then click Save!
If you simply want to add it without creating a new class try this:
// WPF
<ComboBox Name="language" Loaded="language_Loaded" />
// C# code
private void language_Loaded(object sender, RoutedEventArgs e)
{
List<String> language= new List<string>();
language.Add("English");
language.Add("Spanish");
language.Add("ect");
this.chartReviewComboxBox.ItemsSource = language;
}
I suggest an xml file with all your languages that you will support that way you do not have to be dependent on c# I would definitly create a class for languge like the above programmer suggest.
You could do this but it is hacky
.application-title {
background:url("/path/to/image.png");
/* set these dims according to your image size */
width:500px;
height:500px;
}
.application-title img {
display:none;
}
Here is a working example:
Always use nibName file otherwise your preloaded content of Xib will not show .
vc : ViewController = ViewController(nibName: "ViewController", bundle: nil) //change this to your class name
self.presentViewController(vc, animated: true, completion: nil)
In some cases (as one commenter mentioned) this might be caused if you are moving the player within DOM, like append
or etc..
Below code will hide your text with fixed width you decide. but not quite right for responsive designs.
.CropLongTexts {
width: 170px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Update
I have noticed in (mobile) device(s) that the text (mixed) with each other due to (fixed width)... so i have edited the code above to become hidden responsively as follow:
.CropLongTexts {
max-width: 170px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
The (max-width) ensure the text will be hidden responsively whatever the (screen size) and will not mixed with each other.
It's worth noting that if your error is due to .htaccess, for example a missing rewrite_module, you'll still see the 500 internal server error.
You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window
and document
both fit the bill (with just a few differences).
From mozilla dev network:
addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.
So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.
If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
You can create a function that takes a variable number of arguments:
function setAttributes(elem /* attribute, value pairs go here */) {
for (var i = 1; i < arguments.length; i+=2) {
elem.setAttribute(arguments[i], arguments[i+1]);
}
}
setAttributes(elem,
"src", "http://example.com/something.jpeg",
"height", "100%",
"width", "100%");
Or, you pass the attribute/value pairs in on an object:
function setAttributes(elem, obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
elem[prop] = obj[prop];
}
}
}
setAttributes(elem, {
src: "http://example.com/something.jpeg",
height: "100%",
width: "100%"
});
You could also make your own chainable object wrapper/method:
function $$(elem) {
return(new $$.init(elem));
}
$$.init = function(elem) {
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
this.elem = elem;
}
$$.init.prototype = {
set: function(prop, value) {
this.elem[prop] = value;
return(this);
}
};
$$(elem).set("src", "http://example.com/something.jpeg").set("height", "100%").set("width", "100%");
Working example: http://jsfiddle.net/jfriend00/qncEz/
Extension IDs can be found in:
chrome://extensions
(Chrome_Hotdog >> More_tools >> Extensions) Developer mode.
For Linux: $HOME/.config/google-chrome/Default/Preferences
(json file) under ["extensions"]
.
\rm -f file
will never report not found.
You need to close the connection before you can use the output parameters. Something like this
con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());
If you want using it with parameter (ie. delete all subdirs under the given directory), then put this two lines into a *.bat or *.cmd file:
@echo off
for /f "delims=" %%d in ('dir %1 /s /b /ad ^| sort /r') do rd "%%d" 2>nul && echo rmdir %%d
and add script-path to your PATH environment variable. In this case you can call your batch file from any location (I suppose UNC path should work, too).
Eg.:
YourBatchFileName c:\temp
(you may use quotation marks if needed)
will remove all empty subdirs under c:\temp folder
YourBatchFileName
will remove all empty subdirs under the current directory.
Using -engine specific rules ensures effective browser targeting.
<style type="text/css">
//Other browsers
color : black;
//Webkit (Chrome, Safari)
@media screen and (-webkit-min-device-pixel-ratio:0) {
color:green;
}
//Firefox
@media screen and (-moz-images-in-menus:0) {
color:orange;
}
</style>
//Internet Explorer
<!--[if IE]>
<style type='text/css'>
color:blue;
</style>
<![endif]-->
Currently Angular CLI doesn't support the feature of renaming or refactoring code.
You can achieve such functionality with the help of some IDE.
Intellij, Eclipse, VSCode etc.. has default support the refactoring.
Nowadays VSCode is showing some uptrend,personally I'm a fan of this
Refactoring with VSCode
Determinig reference : -
VS Code help you find all references of a variable by selecting variable and pressing shortcut SHIFT
+ F12
. This works incredibly well with Type Script.
Renaming all instances of reference :-
After finding all the references you can press F2
will open a popup and you can change the value and click enter this will update all the instances of reference.
Renaming files and imports You can rename a file and its import references with a plugin. More details can be found here
With above steps after renaming the variables and files you can achieve the angular component renaming.
The heap is the place in memory where your dynamically allocated objects live. If you used new
then it's on the heap. That's as opposed to stack space, which is where the function stack lives. If you have a local variable then that reference is on the stack.
Java's heap is subject to garbage collection and the objects are usable directly.
EHCache's off-heap storage takes your regular object off the heap, serializes it, and stores it as bytes in a chunk of memory that EHCache manages. It's like storing it to disk but it's still in RAM. The objects are not directly usable in this state, they have to be deserialized first. Also not subject to garbage collection.
^(0|[1-9][0-9]*)$
I just found the solution. It is really very simple:
mDrawerToggle.setDrawerIndicatorEnabled(false);
Hope it will help you.
Here is another variant I found that produced completely different results from the grep search for [\x80-\xFF]
in the accepted answer. Perhaps it will be useful to someone to find additional non-ascii characters:
grep --color='auto' -P -n "[^[:ascii:]]" myfile.txt
Note: my computer's grep (a Mac) did not have -P
option, so I did brew install grep
and started the call above with ggrep
instead of grep
.
Using display: inline-flex
#menu ul {_x000D_
list-style: none;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
display: inline-flex_x000D_
}
_x000D_
<div id="menu">_x000D_
<ul>_x000D_
<li>1 menu item</li>_x000D_
<li>2 menu item</li>_x000D_
<li>3 menu item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Using display: inline-block
#menu ul {_x000D_
list-style: none;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
#menu li {_x000D_
display: inline-block;_x000D_
}
_x000D_
<div id="menu">_x000D_
<ul>_x000D_
<li>1 menu item</li>_x000D_
<li>2 menu item</li>_x000D_
<li>3 menu item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Just use crontab -e
and follow the tutorial here.
Look at point 3 for a guide on how to specify the frequency.
Based on your requirement, it should effectively be:
*/10 * * * * /usr/bin/python script.py
Just one line to remove all options from the select tag and after you can add any options then make second line to add options.
$('.ddlsl').empty();
$('.ddlsl').append(new Option('Select all', 'all'));
One more short way but didn't tried
$('.ddlsl').empty().append(new Option('Select all', 'all'));
To extend a little bit answer of Calimo I present few more things you may find useful while creating this quasi dictionaries in R:
a) how to return all the VALUES of the dictionary:
>as.numeric(foo)
[1] 12 22 33
b) check whether dictionary CONTAINS KEY:
>'tic' %in% names(foo)
[1] TRUE
c) how to ADD NEW key, value pair to dictionary:
c(foo,tic2=44)
results:
tic tac toe tic2
12 22 33 44
d) how to fulfill the requirement of REAL DICTIONARY - that keys CANNOT repeat(UNIQUE KEYS)? You need to combine b) and c) and build function which validates whether there is such key, and do what you want: e.g don't allow insertion, update value if the new differs from the old one, or rebuild somehow key(e.g adds some number to it so it is unique)
e) how to DELETE pair BY KEY from dictionary:
foo<-foo[which(foo!=foo[["tac"]])]
<form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">
<div class="form-group">
<input type="file" class="form-control" name="image" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary col-xs-12">Add</button>
</div>
</form>
My Action Is
[HttpPost]
public IActionResult AddNews(IFormFile image)
{
Tbl_News tbl_News = new Tbl_News();
if (image!=null)
{
//Set Key Name
string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
//Get url To Save
string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);
using(var stream=new FileStream(SavePath, FileMode.Create))
{
image.CopyTo(stream);
}
}
return View();
}
Come on guys, there is no need to loop, just use simple math to solve this equation system:
a*b = i;
a+b = j;
a = j/b;
a = i-b;
j/b = i-b; so:
b + j/b + i = 0
b^2 + i*b + j = 0
From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.
EDIT:
There you go:
function finder($add,$product)
{
$inside_root = $add*$add - 4*$product;
if($inside_root >=0)
{
$b = ($add + sqrt($inside_root))/2;
$a = $add - $b;
echo "$a+$b = $add and $a*$b=$product\n";
}else
{
echo "No real solution\n";
}
}
Real live action:
To complete my colleague's answers, You might want to pay close attention to:
Here is an old java1.4 code which takes into account those points:
/**
* Allow for instance call, avoiding certain class circular dependencies. <br />
* Calls even private method if java Security allows it.
* @param aninstance instance on which method is invoked (if null, static call)
* @param classname name of the class containing the method
* (can be null - ignored, actually - if instance if provided, must be provided if static call)
* @param amethodname name of the method to invoke
* @param parameterTypes array of Classes
* @param parameters array of Object
* @return resulting Object
* @throws CCException if any problem
*/
public static Object reflectionCall(final Object aninstance, final String classname, final String amethodname, final Class[] parameterTypes, final Object[] parameters) throws CCException
{
Object res;// = null;
try {
Class aclass;// = null;
if(aninstance == null)
{
aclass = Class.forName(classname);
}
else
{
aclass = aninstance.getClass();
}
//Class[] parameterTypes = new Class[]{String[].class};
final Method amethod = aclass.getDeclaredMethod(amethodname, parameterTypes);
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
amethod.setAccessible(true);
return null; // nothing to return
}
});
res = amethod.invoke(aninstance, parameters);
} catch (final ClassNotFoundException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+CLASS, e);
} catch (final SecurityException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_SECURITY_ISSUE, e);
} catch (final NoSuchMethodException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_NOT_FOUND, e);
} catch (final IllegalArgumentException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ILLEGAL_ARGUMENTS+String.valueOf(parameters)+GenericConstants.CLOSING_ROUND_BRACKET, e);
} catch (final IllegalAccessException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ACCESS_RESTRICTION, e);
} catch (final InvocationTargetException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_INVOCATION_ISSUE, e);
}
return res;
}
you declare your function as returning boolean, but it never returns anything.
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
A few steps you have to follow:
You need to use the event delegation syntax of .on()
here. Change:
$("#add").click(function() {
to
$("#buildyourform").on('click', '#add', function () {
A datetime.timedelta
corresponds to the difference between two dates, not a date itself. It's only expressed in terms of days, seconds, and microseconds, since larger time units like months and years don't decompose cleanly (is 30 days 1 month or 0.9677 months?).
If you want to convert a timedelta
into hours and minutes, you can use the total_seconds()
method to get the total number of seconds and then do some math:
x = datetime.timedelta(1, 5, 41038) # Interval of 1 day and 5.41038 seconds
secs = x.total_seconds()
hours = int(secs / 3600)
minutes = int(secs / 60) % 60
If you don't mind doing some custom drawing with the Canvas API, check out this answer about drop shadows. Here's a follow-up question to that one which fixes a problem in the original.
It's a matter of operator precedence.
||
has a higher precedence than or
.
So, in between the two you have other operators including ternary (? :
) and assignment (=
) so which one you choose can affect the outcome of statements.
Here's a ruby operator precedence table.
See this question for another example using and
/&&
.
Also, be aware of some nasty things that could happen:
a = false || true #=> true
a #=> true
a = false or true #=> true
a #=> false
Both of the previous two statements evaluate to true
, but the second sets a
to false
since =
precedence is lower than ||
but higher than or
.
http://www.selectorgadget.com/ is a bookmarklet designed explicitly for this use case.
That said, I agree with most other people in that you should just learn CSS selectors yourself, trying to generate them with code is not sustainable. :)
I set the NODEJS variable in the system control panel but the only thing that worked to set the path was to do it from command line as administrator.
SET PATH=%NODEJS%;%PATH%
Another trick is that once you set the path you must close the console and open a new one for the new path to be taken into account.
However for the regular user to be able to use node I had to run set path again not as admin and restart the computer
You can delete the node from the master by issuing:
kubectl delete node hostname.company.net
The NOTReady status probably means that the master can't access the kubelet service. Check if everything is OK on the client.
You should be able to choose the SQL Server Database file option to get the right kind of database (the system.data.SqlClient
provider), and then manually correct the connection string to point to your db.
I think the reasoning behind those db choices probably goes something like this:
However, this logic doesn't quite hold. Even if each of those 4 points is true 90% of the time, by the time you apply all four of them it only applies to ~65% of your audience, which means up to 35% of the express market might legitimately want to talk to a server-class db, and that's a significant group. And so, the simplified (greedy) version:
$a = 'This', 'Is', 'a', 'cat'
Using double quotes (and optionally use the separator $ofs
)
# This Is a cat
"$a"
# This-Is-a-cat
$ofs = '-' # after this all casts work this way until $ofs changes!
"$a"
Using operator join
# This-Is-a-cat
$a -join '-'
# ThisIsacat
-join $a
Using conversion to [string]
# This Is a cat
[string]$a
# This-Is-a-cat
$ofs = '-'
[string]$a
Something like:
select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id
Strictly speaking, the difference between Database and Schema is inexisting in MySql.
However, this is not the case in other database engines such as SQL Server. In SQL server:,
Every table belongs to a grouping of objects in the database called database schema. It's a container or namespace (Querying Microsoft SQL Server 2012)
By default, all the tables in SQL Server belong to a default schema called dbo. When you query a table that hasn't been allocated to any particular schema, you can do something like:
SELECT *
FROM your_table
which is equivalent to:
SELECT *
FROM dbo.your_table
Now, SQL server allows the creation of different schema, which gives you the possibility of grouping tables that share a similar purpose. That helps to organize the database.
For example, you can create an schema called sales, with tables such as invoices, creditorders (and any other related with sales), and another schema called lookup, with tables such as countries, currencies, subscriptiontypes (and any other table used as look up table).
The tables that are allocated to a specific domain are displayed in SQL Server Studio Manager with the schema name prepended to the table name (exactly the same as the tables that belong to the default dbo schema).
There are special schemas in SQL Server. To quote the same book:
There are several built-in database schemas, and they can't be dropped or altered:
1) dbo, the default schema.
2) guest contains objects available to a guest user ("guest user" is a special role in SQL Server lingo, with some default and highly restricted permissions). Rarely used.
3) INFORMATION_SCHEMA, used by the Information Schema Views
4) sys, reserved for SQL Server internal use exclusively
Schemas are not only for grouping. It is actually possible to give different permissions for each schema to different users, as described MSDN.
Doing this way, the schema lookup mentioned above could be made available to any standard user in the database (e.g. SELECT
permissions only), whereas a table called supplierbankaccountdetails may be allocated in a different schema called financial, and to give only access to the users in the group accounts
(just an example, you get the idea).
Finally, and quoting the same book again:
It isn't the same Database Schema and Table Schema. The former is the namespace of a table, whereas the latter refers to the table definition
Use these
export class TableColumns<T> {
constructor(private t: new () => T) {
var fields: string[] = Object.keys(new t())
console.log('fields', fields)
console.log('t', t)
}
}
Usage
columns_logs = new TableColumns<LogItem>(LogItem);
Output
fields (12) ["id", "code", "source", "title", "deleted", "checked", "body", "json", "dt_insert", "dt_checked", "screenshot", "uid"]
js class
t class LogItem {
constructor() {
this.id = 0;
this.code = 0;
this.source = '';
this.title = '';
this.deleted = false;
this.checked = false;
…
The ?
in the parameters is to denote an optional parameter. The Typescript compiler does not require this parameter to be filled in. See the code example below for more details:
// baz: number | undefined means: the second argument baz can be a number or undefined
// = undefined, is default parameter syntax,
// if the parameter is not filled in it will default to undefined
// Although default JS behaviour is to set every non filled in argument to undefined
// we need this default argument so that the typescript compiler
// doesn't require the second argument to be filled in
function fn1 (bar: string, baz: number | undefined = undefined) {
// do stuff
}
// All the above code can be simplified using the ? operator after the parameter
// In other words fn1 and fn2 are equivalent in behaviour
function fn2 (bar: string, baz?: number) {
// do stuff
}
fn2('foo', 3); // works
fn2('foo'); // works
fn2();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.
fn1('foo', 3); // works
fn1('foo'); // works
fn1();
// Compile time error: Expected 1-2 arguments, but got 0
// An argument for 'bar' was not provided.
I had success after using ade.exe as explained above, plus using the latest version of Chrome Canary. Apparently your desktop version of Chrome has to be higher than the version running on your Android device.
Try this instead in the end:
exec (@query)
If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.
OR
EXECUTE sp_executesql @query
And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.
Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.
On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?
As pointed out already, most standard implementations of List
are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.
Under the help menu, there should be a menu item labeled "About Eclipse" I can't say with absolute precision because I'm using STS which is the same thing but my label is different.
In the dialog box that opens after you click the relevant about menu item there should be an installation details button in the lower left hand corner.
The version of Java that you're running Eclipse against ought to be in "System properties:" under the "Configuration" tab.
List myList = new ArrayList();
Collections.addAll(myList, filesOrig);
Thinking about it on my way to the supermarket, you could of course also skip the entire image map idea, and make use of :hover
on the elements on top of the image (changed the divs to a-blocks). Which makes things hell of a lot simpler, no jQuery needed...
Short explanation:
.area {_x000D_
background:#fff;_x000D_
display:block;_x000D_
height:475px;_x000D_
opacity:0;_x000D_
position:absolute;_x000D_
width:320px;_x000D_
}_x000D_
#area2 {_x000D_
left:320px;_x000D_
}_x000D_
#area1:hover, #area2:hover {_x000D_
opacity:0.2;_x000D_
}
_x000D_
<a id="area1" class="area" href="#"></a>_x000D_
<a id="area2" class="area" href="#"></a>_x000D_
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Saimiri_sciureus-1_Luc_Viatour.jpg/640px-Saimiri_sciureus-1_Luc_Viatour.jpg" width="640" height="475" />
_x000D_
I just created something similar with jQuery, I don't think it can be done with CSS only.
Short explanation:
#map
is on top (absolute position) (to prevent call to mouseout
when the rollovers appear) $(document).ready(function() {_x000D_
if($('#location-map')) {_x000D_
$('#location-map area').each(function() {_x000D_
var id = $(this).attr('id');_x000D_
$(this).mouseover(function() {_x000D_
$('#overlay'+id).show();_x000D_
_x000D_
});_x000D_
_x000D_
$(this).mouseout(function() {_x000D_
var id = $(this).attr('id');_x000D_
$('#overlay'+id).hide();_x000D_
});_x000D_
_x000D_
});_x000D_
}_x000D_
});
_x000D_
body,html {_x000D_
margin:0;_x000D_
}_x000D_
#emptygif {_x000D_
position:absolute;_x000D_
z-index:200;_x000D_
}_x000D_
#overlayr1 {_x000D_
position:absolute;_x000D_
background:#fff;_x000D_
opacity:0.2;_x000D_
width:300px;_x000D_
height:160px;_x000D_
z-index:100;_x000D_
display:none;_x000D_
}_x000D_
#overlayr2 {_x000D_
position:absolute;_x000D_
background:#fff;_x000D_
opacity:0.2;_x000D_
width:300px;_x000D_
height:160px;_x000D_
top:160px;_x000D_
z-index:100;_x000D_
display:none;_x000D_
}
_x000D_
<img src="http://www.tfo.be/jobs/axa/premiumplus/img/empty.gif" width="300" height="350" border="0" usemap="#location-map" id="emptygif" />_x000D_
<div id="overlayr1"> </div>_x000D_
<div id="overlayr2"> </div>_x000D_
<img src="http://2.bp.blogspot.com/_nP6ESfPiKIw/SlOGugKqaoI/AAAAAAAAACs/6jnPl85TYDg/s1600-R/monkey300.jpg" width="300" height="350" border="0" />_x000D_
<map name="location-map" id="location-map">_x000D_
<area shape="rect" coords="0,0,300,160" href="#" id="r1" />_x000D_
<area shape="rect" coords="0,161,300,350" href="#" id="r2"/>_x000D_
</map>
_x000D_
Hope it helps..
I you want to put the response of the request in the navItems
. Because http.get()
return an observable you will have to subscribe to it.
Look at this example:
// version without map_x000D_
this.http.get("../data/navItems.json")_x000D_
.subscribe((success) => {_x000D_
this.navItems = success.json(); _x000D_
});_x000D_
_x000D_
// with map_x000D_
import 'rxjs/add/operator/map'_x000D_
this.http.get("../data/navItems.json")_x000D_
.map((data) => {_x000D_
return data.json();_x000D_
})_x000D_
.subscribe((success) => {_x000D_
this.navItems = success; _x000D_
});
_x000D_
In IntelliJ IDEA this is an open bug: https://youtrack.jetbrains.com/issue/IDEA-252823
As a workaround, you can change the build tools version as other people advise.
My project was failing with this dependency:
com.android.tools.build:gradle:7.0.0-alpha03
Now it's working with this:
com.android.tools.build:gradle:4.0.2
As a side note, you should change that dependency in build.gradle
in some projects or in dependencies.kt
in newer projects.
That was the most updated version that worked.
JComboBox mycombo=new JComboBox(); //Creates mycombo JComboBox.
add(mycombo); //Adds it to the jframe.
mycombo.addItem("Hello Nepal"); //Adds data to the JComboBox.
String s=String.valueOf(mycombo.getSelectedItem()); //Assigns "Hello Nepal" to s.
System.out.println(s); //Prints "Hello Nepal".
Try setting the charset on your Content-Type:
httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );
If you dont care about the aspect ration (i.e you want to force the image to a particular dimension), here is a simplified answer
// for jpg
function resize_imagejpg($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for png
function resize_imagepng($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefrompng($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for gif
function resize_imagegif($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromgif($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
Now let's handle the upload part. First step, upload the file to your desired directory. Then called one of the above functions based on file type (jpg, png or gif) and pass the absolute path of your uploaded file as below:
// jpg change the dimension 750, 450 to your desired values
$img = resize_imagejpg('path/image.jpg', 750, 450);
The return value $img
is a resource object. We can save to a new location or override the original as below:
// again for jpg
imagejpeg($img, 'path/newimage.jpg');
Hope this helps someone. Check these links for more on resizing Imagick::resizeImage and imagejpeg()
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
You need set the keyframes animation in you CSS. And use the keyframe with jQuery:
$('#myTest').css({"animation":"my-animation 2s infinite"});
_x000D_
#myTest {_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
background: black;_x000D_
}_x000D_
_x000D_
@keyframes my-animation {_x000D_
0% {_x000D_
background: red; _x000D_
}_x000D_
50% {_x000D_
background: blue; _x000D_
}_x000D_
100% {_x000D_
background: green; _x000D_
}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myTest"></div>
_x000D_
.done()
has only one callback and it is the success callback
.then()
has both success and fail callbacks
.fail()
has only one fail callback
so it is up to you what you must do... do you care if it succeeds or if it fails?
Both the answers provided above work fine.
There is a new ISO8601DateFormatter
class that let's you create a string with just one line. For backwards compatibility I used an old C-library. I hope this is useful for someone.
Swift 3.0
extension Date {
var iso8601: String {
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
return ISO8601DateFormatter.string(from: self, timeZone: TimeZone.current, formatOptions: .withInternetDateTime)
} else {
var buffer = [CChar](repeating: 0, count: 25)
var time = time_t(self.timeIntervalSince1970)
strftime_l(&buffer, buffer.count, "%FT%T%z", localtime(&time), nil)
return String(cString: buffer)
}
}
}
This is a good way to do it:
<?php
if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' ||
$_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
Ok I did it with some trick ;) First build a UITextField
and increased it's size
like this :
CGRect frameRect = textField.frame;
frameRect.size.height = 53;
textField.frame = frameRect;
Then build a UITextView
exactly in the same area that u made my UITextField
, and deleted its background color
. Now it looks like that u have a multiple lines TextField
!
MacPorts is the way to go.
Like @user475443 pointed, MacPorts has many many more packages. With brew you'll find yourself trapped soon because the formula you need doesn't exist.
MacPorts is a native application: C + TCL. You don't need Ruby at all. To install Ruby on Mac OS X you might need MacPorts, so just go with MacPorts and you'll be happy.
MacPorts is really stable, in 8 years I never had a problem with it, and my entire Unix ecosystem relay on it.
If you are a PHP developer you can install the last version of Apache (Mac OS X uses 2.2), PHP and all the extensions you need, then upgrade all with one command. Forget to do the same with Homebrew.
MacPorts support groups.
foo@macpro:~/ port select --summary
Name Selected Options
==== ======== =======
db none db46 none
gcc none gcc42 llvm-gcc42 mp-gcc48 none
llvm none mp-llvm-3.3 none
mysql mysql56 mysql56 none
php php55 php55 php56 none
postgresql postgresql94 postgresql93 postgresql94 none
python none python24 python25-apple python26-apple python27 python27-apple none
If you have both PHP55 and PHP56 installed (with many different extensions), you can swap between them with just one command. All the relative extensions are part of the group and they will be activated within the chosen group: php55 or php56. I'm not sure Homebrew has this feature.
Rubists like to rewrite everything in Ruby, because the only thing they are at ease is Ruby itself.
The Babel docs describe this pretty concisely:
Babel includes a polyfill that includes a custom regenerator runtime and core.js.
This will emulate a full ES6 environment. This polyfill is automatically loaded when using babel-node and babel/register.
Make sure you require it at the entry-point to your application, before anything else is called. If you're using a tool like webpack, that becomes pretty simple (you can tell webpack to include it in the bundle).
If you're using a tool like gulp-babel
or babel-loader
, you need to also install the babel
package itself to use the polyfill.
Also note that for modules that affect the global scope (polyfills and the like), you can use a terse import to avoid having unused variables in your module:
import 'babel/polyfill';
import matplotlib.pyplot as plt # For ploting
import numpy as np # to work with numerical data efficiently
fs = 100 # sample rate
f = 2 # the frequency of the signal
x = np.arange(fs) # the points on the x axis for plotting
# compute the value (amplitude) of the sin wave at the for each sample
y = np.sin(2*np.pi*f * (x/fs))
#this instruction can only be used with IPython Notbook.
% matplotlib inline
# showing the exact location of the smaples
plt.stem(x,y, 'r', )
plt.plot(x,y)
OR you can use pandas
:
>>> import pandas as pd
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> df=pd.DataFrame(L)
>>> df[1]
0 2
1 3
2 5
3 4
4 7
5 7
6 8
Name: 1, dtype: int64
>>> df[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>>
Or numpy
:
>>> import numpy as np
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> arr=np.array(L)
>>> arr.T[1]
array([2, 3, 5, 4, 7, 7, 8])
>>> arr.T[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>>
Call this after the print job has returned:
oShell.AppActivate "Adobe Reader"
oShell.SendKeys "%FX"
Use this method:
$_product = wc_get_product( $id );
Official API-docs: wc_get_product
For people that find this question by searching for the error message, you can also see this error if you make a mistake in your @JsonProperty
annotations such that you annotate a List
-typed property with the name of a single-valued field:
@JsonProperty("someSingleValuedField") // Oops, should have been "someMultiValuedField"
public List<String> getMyField() { // deserialization fails - single value into List
return myField;
}
Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s
and a RESET
color to end the coloration.
#include <stdio.h>
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
int main() {
printf(RED "red\n" RESET);
printf(GRN "green\n" RESET);
printf(YEL "yellow\n" RESET);
printf(BLU "blue\n" RESET);
printf(MAG "magenta\n" RESET);
printf(CYN "cyan\n" RESET);
printf(WHT "white\n" RESET);
return 0;
}
This program gives the following output:
This way, it's easy to do something like:
printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");
This line produces the following output:
I use the environment variable CDPATH
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
<div *ngFor="let celeb of singers">
<p [ngClass]="{
'text-success':celeb.country === 'USA',
'text-secondary':celeb.country === 'Canada',
'text-danger':celeb.country === 'Puorto Rico',
'text-info':celeb.country === 'India'
}">{{ celeb.artist }} ({{ celeb.country }})
</p>
</div>
Use the change event of the select:
$('#my_select').change(function()
{
$(this).parents('td').css('background', '#000000');
});
docker-compose -f [COMPOSE_FILE_NAME].yml restart [SERVICE_NAME]
Use Case #1: If the COMPOSE_FILE_NAME is docker-compose.yml
and service is worker
docker-compose restart worker
Use Case #2: If the file name is sample.yml
and service is worker
docker-compose -f sample.yml restart worker
By default docker-compose looks for the docker-compose.yml
if we run the docker-compose
command, else we have flag to give specific file name with -f [FILE_NAME].yml
If notepad is already started, you should write:
// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
//...
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
}
GetProcessesByName
returns an array of processes, so you should get the first one (or find the one you want).
If you want to start notepad
and send the key, you should write:
Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
The only situation in which the code may not work is when notepad
is started as Administrator and your application is not.
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
file.close()
return table
# ID not found; close file and return empty dict
file.close()
return {}
A clean approach I find is by giving an ID
for each radio button and then setting it by using the following statement:
document.getElementById('publicedit').checked = true;
Wikipedia ought to have a good answer, here's my thoughts:
Do not we have an app which can stream the digital movie from iOS devices like iPhone or iPad to be played on a high definition LED or Plasma TV?
I know of an app air video server which can be used to display content played on computer or laptop on iOS device. But is there any app that can do the reverse & play the digital content from iphone to LED tv .
try this:
.test {
position:absolute;
background:blue;
width:200px;
height:200px;
top:40px;
transition:left 1s linear;
left: 0;
}
Try putting it in a span element:
<div id='page' style='width: 600px'>_x000D_
<h1><span style='border:2px black solid; font-size:42px;'>Title</span></h1>_x000D_
</div>
_x000D_
It is quite easy. Here is the API Interface
public interface Api {
@Multipart
@POST("upload")
Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);
}
And you can use the following code to make a call.
private void uploadFile(File file, String desc) {
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
//The gson builder
Gson gson = new GsonBuilder()
.setLenient()
.create();
//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//creating our api
Api api = retrofit.create(Api.class);
//creating a call and calling the upload image method
Call<MyResponse> call = api.uploadImage(requestFile, descBody);
//finally performing the call
call.enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
Source: Retrofit Upload File Tutorial.
First in your terminal:
rails g migration change_date_format_in_my_table
Then in your migration file:
For Rails >= 3.2:
class ChangeDateFormatInMyTable < ActiveRecord::Migration
def up
change_column :my_table, :my_column, :datetime
end
def down
change_column :my_table, :my_column, :date
end
end
Get a file-like object from the request and copy it to a file. This will also avoid reading the whole thing into memory at once.
import shutil
import requests
url = 'http://example.com/img.png'
response = requests.get(url, stream=True)
with open('img.png', 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response
If you ought to spare memory, read char by char and realloc each time. Performance will die, but you'll spare this 10 bytes.
Another good tradeoff is to read in a function (using a local variable) then copying. So the big buffer will be function scoped.
Python lets you put the indented clause on the same line if it's only one line:
if "exam" in example: print "yes!"
def squared(x): return x * x
class MyException(Exception): pass
I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.
Two ways of solving it:
Get the path you want using native python functions, e.g.:
test = os.getcwd() # In case the path in question is your current directory
print(repr(test))
This makes it platform independent and it now works with .encode
. If this is an option for you, it's the more elegant solution.
If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:
test = 'C:\\Windows\\Users\\alexb\\'
print(repr(test))
SELECT *
FROM (
SELECT *
FROM mytable
ORDER BY
dbms_random.value
)
WHERE rownum <= 1000
You can make a directory "fonts" in a root of your project and put your fonts (sans_serif.ttf) file there. Then you can make something like this:
fonts_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'fonts')
font = ImageFont.truetype(os.path.join(fonts_path, 'sans_serif.ttf'), 24)
Re the solution for SqlBulkCopy:
I used the StreamReader to convert and process the text file. The result was a list of my object.
I created a class than takes Datatable
or a List<T>
and a Buffer size (CommitBatchSize
). It will convert the list to a data table using an extension (in the second class).
It works very fast. On my PC, I am able to insert more than 10 million complicated records in less than 10 seconds.
Here is the class:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public class BulkUploadToSql<T>
{
public IList<T> InternalStore { get; set; }
public string TableName { get; set; }
public int CommitBatchSize { get; set; }=1000;
public string ConnectionString { get; set; }
public void Commit()
{
if (InternalStore.Count>0)
{
DataTable dt;
int numberOfPages = (InternalStore.Count / CommitBatchSize) + (InternalStore.Count % CommitBatchSize == 0 ? 0 : 1);
for (int pageIndex = 0; pageIndex < numberOfPages; pageIndex++)
{
dt= InternalStore.Skip(pageIndex * CommitBatchSize).Take(CommitBatchSize).ToDataTable();
BulkInsert(dt);
}
}
}
public void BulkInsert(DataTable dt)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
// make sure to enable triggers
// more on triggers in next post
SqlBulkCopy bulkCopy =
new SqlBulkCopy
(
connection,
SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null
);
// set the destination table name
bulkCopy.DestinationTableName = TableName;
connection.Open();
// write the data in the "dataTable"
bulkCopy.WriteToServer(dt);
connection.Close();
}
// reset
//this.dataTable.Clear();
}
}
public static class BulkUploadToSqlHelper
{
public static DataTable ToDataTable<T>(this IEnumerable<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
}
}
Here is an example when I want to insert a List of my custom object List<PuckDetection>
(ListDetections
):
var objBulk = new BulkUploadToSql<PuckDetection>()
{
InternalStore = ListDetections,
TableName= "PuckDetections",
CommitBatchSize=1000,
ConnectionString="ENTER YOU CONNECTION STRING"
};
objBulk.Commit();
The BulkInsert
class can be modified to add column mapping if required. Example you have an Identity key as first column.(this assuming that the column names in the datatable are the same as the database)
//ADD COLUMN MAPPING
foreach (DataColumn col in dt.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
You can use Nexus to manage 3rd party dependencies as well as dependencies in standard maven repositories.
This will also work in Visual Studio 2010 (Beta 2), as long as you install Paul Harrington's extension to enable the guidelines from the VSGallery or from the extension manager inside VS2010. Since this is version 10.0, you should use the following registry key:
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Text Editor
Also, Paul wrote an extension that adds entries to the editor's context menu for adding/removing the entries without needing to edit the registry directly. You can find it here: http://visualstudiogallery.msdn.microsoft.com/en-us/7f2a6727-2993-4c1d-8f58-ae24df14ea91
$facebook->api('/'.$facebook_uid)
instead of
$facebook->api('/me')
it works.
Try This
$('#twitterSearch').keydown(function(event){
var keyCode = (event.keyCode ? event.keyCode : event.which);
if (keyCode == 13) {
$('#startSearch').trigger('click');
}
});
Hope it helps you
public IList<Splitting> get(Guid companyId, long customrId) {
var res=from c in Customers_data_source
where c.CustomerId = customrId && c.CompanyID == companyId
from s in Splittings_data_srouce
where s.CustomerID = c.CustomerID
select s;
return res.ToList();
}
Find the cqlshrc file usually placed in .cassandra directory.
In that file append,
[csv]
field_size_limit = 1000000000
This comes up high on Google, so I'd like to add some contextual information about the original question (emphasis mine):
Why does Node.js' fs.readFile() return a buffer instead of string?
Even if you as the programmer know it: Node has no idea what's in the file you're trying to read. It could be a text file, but it could just as well be a ZIP archive or a JPG image — Node doesn't know.
Even if Node knew it were to read a text file, it still would have no idea which character encoding is used (i.e. how the bytes in the file map to human-readable characters), because the character encoding itself is not stored in the file.
There are ways to guess the character encoding of text files with more or less confidence (that's what text editors do when opening a file), but you usually don't want your code to rely on guesses without your explicit instruction.
So, because it does not and can not know all these details, Node just reads the file byte for byte, without assuming anything about its contents.
And that's what the returned buffer is: an unopinionated container for raw binary content. How this content should be interpreted is up to you as the developer.
In the module build.gradle, in the task field, I get an error unless I use:
def ndkDir = plugins.getPlugin('com.android.application').sdkHandler.getNdkFolder()
I see people using
def ndkDir = android.plugin.ndkFolder
and
def ndkDir = plugins.getPlugin('com.android.library').sdkHandler.getNdkFolder()
but neither of those worked until I changed it to the plugin I was actually importing.
The following structure in docker-compose.yaml will allow you to have the Dockerfile in a subfolder from the root:
version: '3'
services:
db:
image: postgres:11
environment:
- PGDATA=/var/lib/postgresql/data/pgdata
volumes:
- postgres-data:/var/lib/postgresql/data
ports:
- 127.0.0.1:5432:5432
**web:
build:
context: ".."
dockerfile: dockerfiles/Dockerfile**
command: ...
...
Then, in your Dockerfile, which is in the same directory as docker-compose.yaml, you can do the following:
ENV APP_HOME /home
RUN mkdir -p ${APP_HOME}
# Copy the file to the directory in the container
COPY test.json ${APP_HOME}/test.json
COPY test.py ${APP_HOME}/test.py
# Browse to that directory created above
WORKDIR ${APP_HOME}
You can then run docker-compose from the parent directory like:
docker-compose -f .\dockerfiles\docker-compose.yaml build --no-cache
If your database is in the public schema, it is easy (this assumes you have already created the readonlyuser
)
db=> GRANT SELECT ON ALL TABLES IN SCHEMA public to readonlyuser;
GRANT
db=> GRANT CONNECT ON DATABASE mydatabase to readonlyuser;
GRANT
db=> GRANT SELECT ON ALL SEQUENCES IN SCHEMA public to readonlyuser;
GRANT
If your database is using customschema
, execute the above but add one more command:
db=> ALTER USER readonlyuser SET search_path=customschema, public;
ALTER ROLE
n % x == 0
Means that n can be divided by x. So... for instance, in your case:
boolean isDivisibleBy20 = number % 20 == 0;
Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:
boolean even = (number & 1) == 0;
boolean odd = (number & 1) != 0;
it means 'nothing for the first argument, nothing for the second, and jump by three'. It gets every third item of the sequence sliced. Extended slices is what you want. New in Python 2.3
os.listdir()
- list in the current directory
With listdir in os module you get the files and the folders in the current dir
import os
arr = os.listdir()
print(arr)
>>> ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
You need the ''
arr = os.listdir('')
arr = os.listdir('c:\\files')
glob
from glob
with glob you can specify a type of file to list like this
import glob
txtfiles = []
for file in glob.glob("*.txt"):
txtfiles.append(file)
glob
im a list comprehensionmylist = [f for f in glob.glob("*.txt")]
Getting the full path name with
os.path.abspath
You get the full path in return
import os
files_path = [os.path.abspath(x) for x in os.listdir()]
print(files_path)
>>> ['F:\\documenti\applications.txt', 'F:\\documenti\collections.txt']
Walk: going through sub directories
os.walk returns the root, the directories list and the files list, that is why I unpacked them in r, d, f in the for loop; it, then, looks for other files and directories in the subfolders of the root and so on until there are no subfolders.
import os
# Getting the current work directory (cwd)
thisdir = os.getcwd()
# r=root, d=directories, f = files
for r, d, f in os.walk(thisdir):
for file in f:
if file.endswith(".docx"):
print(os.path.join(r, file))
os.listdir()
: get files in the current directory (Python 2)
In Python 2, if you want the list of the files in the current directory, you have to give the argument as '.' or os.getcwd() in the os.listdir method.
import os
arr = os.listdir('.')
print(arr)
>>> ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
To go up in the directory tree
# Method 1
x = os.listdir('..')
# Method 2
x= os.listdir('/')
Get files:
os.listdir()
in a particular directory (Python 2 and 3)
import os
arr = os.listdir('F:\\python')
print(arr)
>>> ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
Get files of a particular subdirectory with
os.listdir()
import os
x = os.listdir("./content")
os.walk('.')
- current directory
import os
arr = next(os.walk('.'))[2]
print(arr)
>>> ['5bs_Turismo1.pdf', '5bs_Turismo1.pptx', 'esperienza.txt']
next(os.walk('.'))
andos.path.join('dir', 'file')
import os
arr = []
for d,r,f in next(os.walk("F:\\_python")):
for file in f:
arr.append(os.path.join(r,file))
for f in arr:
print(files)
>>> F:\\_python\\dict_class.py
>>> F:\\_python\\programmi.txt
next(os.walk('F:\\')
- get the full path - list comprehension
[os.path.join(r,file) for r,d,f in next(os.walk("F:\\_python")) for file in f]
>>> ['F:\\_python\\dict_class.py', 'F:\\_python\\programmi.txt']
os.walk
- get full path - all files in sub dirs**
x = [os.path.join(r,file) for r,d,f in os.walk("F:\\_python") for file in f]
print(x)
>>> ['F:\\_python\\dict.py', 'F:\\_python\\progr.txt', 'F:\\_python\\readl.py']
os.listdir()
- get only txt files
arr_txt = [x for x in os.listdir() if x.endswith(".txt")]
print(arr_txt)
>>> ['work.txt', '3ebooks.txt']
Using
glob
to get the full path of the files
If I should need the absolute path of the files:
from path import path
from glob import glob
x = [path(f).abspath() for f in glob("F:\\*.txt")]
for f in x:
print(f)
>>> F:\acquistionline.txt
>>> F:\acquisti_2018.txt
>>> F:\bootstrap_jquery_ecc.txt
Using
os.path.isfile
to avoid directories in the list
import os.path
listOfFiles = [f for f in os.listdir() if os.path.isfile(f)]
print(listOfFiles)
>>> ['a simple game.py', 'data.txt', 'decorator.py']
Using
pathlib
from Python 3.4
import pathlib
flist = []
for p in pathlib.Path('.').iterdir():
if p.is_file():
print(p)
flist.append(p)
>>> error.PNG
>>> exemaker.bat
>>> guiprova.mp3
>>> setup.py
>>> speak_gui2.py
>>> thumb.PNG
With list comprehension
:
flist = [p for p in pathlib.Path('.').iterdir() if p.is_file()]
Alternatively, use pathlib.Path()
instead of pathlib.Path(".")
Use glob method in pathlib.Path()
import pathlib
py = pathlib.Path().glob("*.py")
for file in py:
print(file)
>>> stack_overflow_list.py
>>> stack_overflow_list_tkinter.py
Get all and only files with os.walk
import os
x = [i[2] for i in os.walk('.')]
y=[]
for t in x:
for f in t:
y.append(f)
print(y)
>>> ['append_to_list.py', 'data.txt', 'data1.txt', 'data2.txt', 'data_180617', 'os_walk.py', 'READ2.py', 'read_data.py', 'somma_defaltdic.py', 'substitute_words.py', 'sum_data.py', 'data.txt', 'data1.txt', 'data_180617']
Get only files with next and walk in a directory
import os
x = next(os.walk('F://python'))[2]
print(x)
>>> ['calculator.bat','calculator.py']
Get only directories with next and walk in a directory
import os
next(os.walk('F://python'))[1] # for the current dir use ('.')
>>> ['python3','others']
Get all the subdir names with
walk
for r,d,f in os.walk("F:\\_python"):
for dirs in d:
print(dirs)
>>> .vscode
>>> pyexcel
>>> pyschool.py
>>> subtitles
>>> _metaprogramming
>>> .ipynb_checkpoints
os.scandir()
from Python 3.5 and greater
import os
x = [f.name for f in os.scandir() if f.is_file()]
print(x)
>>> ['calculator.bat','calculator.py']
# Another example with scandir (a little variation from docs.python.org)
# This one is more efficient than os.listdir.
# In this case, it shows the files only in the current directory
# where the script is executed.
import os
with os.scandir() as i:
for entry in i:
if entry.is_file():
print(entry.name)
>>> ebookmaker.py
>>> error.PNG
>>> exemaker.bat
>>> guiprova.mp3
>>> setup.py
>>> speakgui4.py
>>> speak_gui2.py
>>> speak_gui3.py
>>> thumb.PNG
Examples:
Ex. 1: How many files are there in the subdirectories?
In this example, we look for the number of files that are included in all the directory and its subdirectories.
import os
def count(dir, counter=0):
"returns number of files in dir and subdirs"
for pack in os.walk(dir):
for f in pack[2]:
counter += 1
return dir + " : " + str(counter) + "files"
print(count("F:\\python"))
>>> 'F:\\\python' : 12057 files'
Ex.2: How to copy all files from a directory to another?
A script to make order in your computer finding all files of a type (default: pptx) and copying them in a new folder.
import os
import shutil
from path import path
destination = "F:\\file_copied"
# os.makedirs(destination)
def copyfile(dir, filetype='pptx', counter=0):
"Searches for pptx (or other - pptx is the default) files and copies them"
for pack in os.walk(dir):
for f in pack[2]:
if f.endswith(filetype):
fullpath = pack[0] + "\\" + f
print(fullpath)
shutil.copy(fullpath, destination)
counter += 1
if counter > 0:
print('-' * 30)
print("\t==> Found in: `" + dir + "` : " + str(counter) + " files\n")
for dir in os.listdir():
"searches for folders that starts with `_`"
if dir[0] == '_':
# copyfile(dir, filetype='pdf')
copyfile(dir, filetype='txt')
>>> _compiti18\Compito Contabilità 1\conti.txt
>>> _compiti18\Compito Contabilità 1\modula4.txt
>>> _compiti18\Compito Contabilità 1\moduloa4.txt
>>> ------------------------
>>> ==> Found in: `_compiti18` : 3 files
Ex. 3: How to get all the files in a txt file
In case you want to create a txt file with all the file names:
import os
mylist = ""
with open("filelist.txt", "w", encoding="utf-8") as file:
for eachfile in os.listdir():
mylist += eachfile + "\n"
file.write(mylist)
Example: txt with all the files of an hard drive
"""
We are going to save a txt file with all the files in your directory.
We will use the function walk()
"""
import os
# see all the methods of os
# print(*dir(os), sep=", ")
listafile = []
percorso = []
with open("lista_file.txt", "w", encoding='utf-8') as testo:
for root, dirs, files in os.walk("D:\\"):
for file in files:
listafile.append(file)
percorso.append(root + "\\" + file)
testo.write(file + "\n")
listafile.sort()
print("N. of files", len(listafile))
with open("lista_file_ordinata.txt", "w", encoding="utf-8") as testo_ordinato:
for file in listafile:
testo_ordinato.write(file + "\n")
with open("percorso.txt", "w", encoding="utf-8") as file_percorso:
for file in percorso:
file_percorso.write(file + "\n")
os.system("lista_file.txt")
os.system("lista_file_ordinata.txt")
os.system("percorso.txt")
All the file of C:\ in one text file
This is a shorter version of the previous code. Change the folder where to start finding the files if you need to start from another position. This code generate a 50 mb on text file on my computer with something less then 500.000 lines with files with the complete path.
import os
with open("file.txt", "w", encoding="utf-8") as filewrite:
for r, d, f in os.walk("C:\\"):
for file in f:
filewrite.write(f"{r + file}\n")
How to write a file with all paths in a folder of a type
With this function you can create a txt file that will have the name of a type of file that you look for (ex. pngfile.txt) with all the full path of all the files of that type. It can be useful sometimes, I think.
import os
def searchfiles(extension='.ttf', folder='H:\\'):
"Create a txt file with all the file of a type"
with open(extension[1:] + "file.txt", "w", encoding="utf-8") as filewrite:
for r, d, f in os.walk(folder):
for file in f:
if file.endswith(extension):
filewrite.write(f"{r + file}\n")
# looking for png file (fonts) in the hard disk H:\
searchfiles('.png', 'H:\\')
>>> H:\4bs_18\Dolphins5.png
>>> H:\4bs_18\Dolphins6.png
>>> H:\4bs_18\Dolphins7.png
>>> H:\5_18\marketing html\assets\imageslogo2.png
>>> H:\7z001.png
>>> H:\7z002.png
(New) Find all files and open them with tkinter GUI
I just wanted to add in this 2019 a little app to search for all files in a dir and be able to open them by doubleclicking on the name of the file in the list.
import tkinter as tk
import os
def searchfiles(extension='.txt', folder='H:\\'):
"insert all files in the listbox"
for r, d, f in os.walk(folder):
for file in f:
if file.endswith(extension):
lb.insert(0, r + "\\" + file)
def open_file():
os.startfile(lb.get(lb.curselection()[0]))
root = tk.Tk()
root.geometry("400x400")
bt = tk.Button(root, text="Search", command=lambda:searchfiles('.png', 'H:\\'))
bt.pack()
lb = tk.Listbox(root)
lb.pack(fill="both", expand=1)
lb.bind("<Double-Button>", lambda x: open_file())
root.mainloop()
The imshow()
function with parameters interpolation='nearest'
and cmap='hot'
should do what you want.
import matplotlib.pyplot as plt
import numpy as np
a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()
first, you need to load URL helper like this type or you can upload within autoload.php file:
$this->load->helper('url');
if (!$user_logged_in)
{
redirect('/account/login', 'refresh');
}
Apparently the (-o-min-device-pixel-ratio: 3/2) is causing problems. On my test site it was causing the right side to be cut off. I found a workaround on github that works for now. Using(-o-min-device-pixel-ratio: ~"3/2") seems to work fine.
This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row)
and check how many indexes there exists.
WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
Log.d("WIDTH: ", String.valueOf(d.getWidth()));
Log.d("HEIGHT: ", String.valueOf(d.getHeight()));
Use the SqlDataAdapter, this would simplify everything.
//Your code to this point
DataTable dt = new DataTable();
using(var cmd = new SqlCommand("usp_GetABCD", sqlcon))
{
using(var da = new SqlDataAdapter(cmd))
{
da.Fill(dt):
}
}
and your DataTable will have the information you are looking for, so long as your stored proceedure returns a data set (cursor).
Sure, this can be done using profiles. You can do something like the following in your parent pom.xml.
...
<modules>
<module>module1</module>
<module>module2</module>
...
</modules>
...
<profiles>
<profile>
<id>ci</id>
<modules>
<module>module1</module>
<module>module2</module>
...
<module>module-integration-test</module>
</modules>
</profile>
</profiles>
...
In your CI, you would run maven with the ci
profile, i.e. mvn -P ci clean install
I really fail to see the use case... If you will type print_var_name($foobar) what's so hard (and different) about typing print("foobar") instead?
Because even if you were to use this in a function, you'd get the local name of the variable...
In any case, here's the reflection manual in case there's something you need in there.
Using pipe:
cat en-tl.100.en | head -10
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value)
no add(value)
.
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
http://php.net/manual/en/function.unlink.php
Unlink can safely remove a single file; just make sure the file you are removing it actually a file and not a directory ('.' or '..')
if (is_file($filepath))
{
unlink($filepath);
}
MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.
It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.
The feature doesn't prevent any other type of data forgery or tampering based attacks.
To use it, decorate the action method or controller with the ValidateAntiForgeryToken
attribute and place a call to @Html.AntiForgeryToken()
in the forms posting to the method.
There was some discussion of this on security.stackexchange.com recently
functions that can be used for arbitrary code execution
Well that reduces the scope a little - but since 'print' can be used to inject javascript (and therefore steal sessions etc) its still somewhat arbitrary.
isn't to list functions that should be blacklisted or otherwise disallowed. Rather, I'd like to have a grep-able list
That's a sensible approach.
Do consider writing your own parser though - very soon you're going to find a grep based approach getting out of control (awk would be a bit better). Pretty soon you're also going to start wishing you'd implemented a whitelist too!
In addition to the obvious ones, I'd recommend flagging up anything which does an include with an argument of anything other than a string literal. Watch out for __autoload() too.
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
Sometimes you must change the name (or check to get it automatically from compiler).
Example:
Filename = amp2-rot.png
It is not working as:
PictureBoxName.Image = resources.GetObject("amp2-rot.png")
It works, just as amp2_rot
for me:
PictureBox_L1.Image = My.Resources.Resource.amp2_rot
In your case it should be:
Select convert(datetime,convert(varchar(10),GRADUATION_DATE,120)) as
'GRADUATION_DATE' from mydb
Not sure why the code above did not work for the library rgl
, but the following link has a great example with the same library.
Run the code in R and you will obtain a beautiful 3d plot that you can turn around in all angles.
http://statisticsr.blogspot.de/2008/10/some-r-functions.html
########################################################################
## another example of 3d plot from my personal reserach, use rgl library
########################################################################
# 3D visualization device system
library(rgl);
data(volcano)
dim(volcano)
peak.height <- volcano;
ppm.index <- (1:nrow(volcano));
sample.index <- (1:ncol(volcano));
zlim <- range(peak.height)
zlen <- zlim[2] - zlim[1] + 1
colorlut <- terrain.colors(zlen) # height color lookup table
col <- colorlut[(peak.height-zlim[1]+1)] # assign colors to heights for each point
open3d()
ppm.index1 <- ppm.index*zlim[2]/max(ppm.index);
sample.index1 <- sample.index*zlim[2]/max(sample.index)
title.name <- paste("plot3d ", "volcano", sep = "");
surface3d(ppm.index1, sample.index1, peak.height, color=col, back="lines", main = title.name);
grid3d(c("x", "y+", "z"), n =20)
sample.name <- paste("col.", 1:ncol(volcano), sep="");
sample.label <- as.integer(seq(1, length(sample.name), length = 5));
axis3d('y+',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3);
axis3d('y',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3)
axis3d('z',pos=c(0, 0, NA))
ppm.label <- as.integer(seq(1, length(ppm.index), length = 10));
axes3d('x', at=c(ppm.index1[ppm.label], 0, 0), abs(round(ppm.index[ppm.label], 2)), cex = 0.3);
title3d(main = title.name, sub = "test", xlab = "ppm", ylab = "samples", zlab = "peak")
rgl.bringtotop();
One line is Chris's answer is wrong.
newFrame.size.height = maximumLabelSize.height;
should be
newFrame.size.height = expectedLabelSize.height;
Other than that, it's the correct solution.
In addition to the above responses, it should be noted that there is, at least in theory, no restriction whatsoever as to what kind of resources are involved in a transaction.
Most of the time, it is just a database, or multiple distinct databases, but it is also conceivable that a printer takes part in a transaction, and can cause that transaction to fail, say in the event of a paper jam.
This worked for me. No need to exclude anything. I just used mockito-core
instead mockito-all
testCompile 'junit:junit:4.12'
testCompile group: 'org.mockito', name: 'mockito-core', version: '3.0.0'
testCompile group: 'org.hamcrest', name: 'hamcrest-library', version: '2.1'
Simply call your Action Method by using Javascript as shown below:
var id = model.Id; //if you want to pass an Id parameter
window.location.href = '@Url.Action("Action", "Controller")/' + id;
Hope this helps...
Here is another REST-only working example for Google Service Accounts accessing G Suite Users and Groups, authenticating through JWT. This was only possible through reflection of Google libraries, since Google documentation of these APIs are beyond terrible. Anyone used to code in MS technologies will have a hard time figuring out how everything goes together in Google services.
$iss = "<name>@<serviceaccount>.iam.gserviceaccount.com"; # The email address of the service account.
$sub = "[email protected]"; # The user to impersonate (required).
$scope = "https://www.googleapis.com/auth/admin.directory.user.readonly https://www.googleapis.com/auth/admin.directory.group.readonly";
$certPath = "D:\temp\mycertificate.p12";
$grantType = "urn:ietf:params:oauth:grant-type:jwt-bearer";
# Auxiliary functions
function UrlSafeEncode([String] $Data) {
return $Data.Replace("=", [String]::Empty).Replace("+", "-").Replace("/", "_");
}
function UrlSafeBase64Encode ([String] $Data) {
return (UrlSafeEncode -Data ([Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Data))));
}
function KeyFromCertificate([System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate) {
$privateKeyBlob = $Certificate.PrivateKey.ExportCspBlob($true);
$key = New-Object System.Security.Cryptography.RSACryptoServiceProvider;
$key.ImportCspBlob($privateKeyBlob);
return $key;
}
function CreateSignature ([Byte[]] $Data, [System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate) {
$sha256 = [System.Security.Cryptography.SHA256]::Create();
$key = (KeyFromCertificate $Certificate);
$assertionHash = $sha256.ComputeHash($Data);
$sig = [Convert]::ToBase64String($key.SignHash($assertionHash, "2.16.840.1.101.3.4.2.1"));
$sha256.Dispose();
return $sig;
}
function CreateAssertionFromPayload ([String] $Payload, [System.Security.Cryptography.X509Certificates.X509Certificate2] $Certificate) {
$header = @"
{"alg":"RS256","typ":"JWT"}
"@;
$assertion = New-Object System.Text.StringBuilder;
$assertion.Append((UrlSafeBase64Encode $header)).Append(".").Append((UrlSafeBase64Encode $Payload)) | Out-Null;
$signature = (CreateSignature -Data ([System.Text.Encoding]::ASCII.GetBytes($assertion.ToString())) -Certificate $Certificate);
$assertion.Append(".").Append((UrlSafeEncode $signature)) | Out-Null;
return $assertion.ToString();
}
$baseDateTime = New-Object DateTime(1970, 1, 1, 0, 0, 0, [DateTimeKind]::Utc);
$timeInSeconds = [Math]::Truncate([DateTime]::UtcNow.Subtract($baseDateTime).TotalSeconds);
$jwtClaimSet = @"
{"scope":"$scope","email_verified":false,"iss":"$iss","sub":"$sub","aud":"https://oauth2.googleapis.com/token","exp":$($timeInSeconds + 3600),"iat":$timeInSeconds}
"@;
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certPath, "notasecret", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable);
$jwt = CreateAssertionFromPayload -Payload $jwtClaimSet -Certificate $cert;
# Retrieve the authorization token.
$authRes = Invoke-WebRequest -Uri "https://oauth2.googleapis.com/token" -Method Post -ContentType "application/x-www-form-urlencoded" -UseBasicParsing -Body @"
assertion=$jwt&grant_type=$([Uri]::EscapeDataString($grantType))
"@;
$authInfo = ConvertFrom-Json -InputObject $authRes.Content;
$resUsers = Invoke-WebRequest -Uri "https://www.googleapis.com/admin/directory/v1/users?domain=<required_domain_name_dont_trust_google_documentation_on_this>" -Method Get -Headers @{
"Authorization" = "$($authInfo.token_type) $($authInfo.access_token)"
}
$users = ConvertFrom-Json -InputObject $resUsers.Content;
$users.users | ft primaryEmail, isAdmin, suspended;
Number only regex (Updated)
var reg = new RegExp('[^0-9]','g');
Enterprise Architect will build a UML diagram from imported source code.
I hide this by set console setting
Console settings
-> User messages only
Using &
is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.
FOR /r %%X IN (*.txt) DO (
ECHO %%X
DEL %%X
)
Placement of (
and )
matters. The round brackets after DO
must be placed on the same line, otherwise the batch file will be incorrect.
See if /?|find /V ""
for details.