Another simple way I found for using in LAN is
ssh [username@ip] uname -n
If you need to login command line will be
sshpass -p "[password]" ssh [username@ip] uname -n
Working solution ~2018
I've found that, providing you have an access token, you can perform the following request in your browser:
https://api.instagram.com/v1/users/self?access_token=[VALUE]
In fact, access token contain the User ID (the first segment of the token):
<user-id>.1677aaa.aaa042540a2345d29d11110545e2499
You can get an access token by using this tool provided by Pixel Union.
a ||= b
Signifies if any value is present in 'a' and you dont want to alter it the keep using that value, else if 'a' doesnt have any value, use value of 'b'.
Simple words, if left hand side if not null, point to existing value, else point to value at right side.
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
Try this,
if(thisSession.hasOwnProperty('merchant_id')){
}
the JS Object thisSession
should be like
{
amt: "10.00",
email: "[email protected]",
merchant_id: "sam",
mobileNo: "9874563210",
orderID: "123456",
passkey: "1234"
}
you can find the details here
Neither databases, nor tablespaces nor data files belong to any user. Are you coming to this from an MS SQL background?
select tablespace_name,
file_name
from dba_tablespaces
order by tablespace_name,
file_name;
According to spark documentation "where()
is an alias for filter()
"
filter(condition)
Filters rows using the given condition.
where()
is an alias for filter()
.
Parameters: condition – a Column
of types.BooleanType
or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]
>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]
As Strings are immutable, when you do:
String a = "xyz"
while creating the string, the JVM searches in the pool of strings if there already exists a string value "xyz"
, if so 'a'
will simply be a reference of that string and no new String object is created.
But if you say:
String a = new String("xyz")
you force JVM to create a new String
reference, even if "xyz"
is in its pool.
For more information read this.
Did you check the string concatenation function? Something like:
update table_c set column_a = column_b || column_c
should work. More here
As others said, class variables are shared between a given class and its subclasses. Class instance variables belong to exactly one class; its subclasses are separate.
Why does this behavior exist? Well, everything in Ruby is an object—even classes. That means that each class has an object of the class Class
(or rather, a subclass of Class
) corresponding to it. (When you say class Foo
, you're really declaring a constant Foo
and assigning a class object to it.) And every Ruby object can have instance variables, so class objects can have instance variables, too.
The trouble is, instance variables on class objects don't really behave the way you usually want class variables to behave. You usually want a class variable defined in a superclass to be shared with its subclasses, but that's not how instance variables work—the subclass has its own class object, and that class object has its own instance variables. So they introduced separate class variables with the behavior you're more likely to want.
In other words, class instance variables are sort of an accident of Ruby's design. You probably shouldn't use them unless you specifically know they're what you're looking for.
I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...
Here is how removed special characters.
I simply applied regex
Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters
' Configure the regex object
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)
One reason why you might prefer to use a JOIN
rather than NOT IN
is that if the Values in the NOT IN
clause contain any NULL
s you will always get back no results. If you do use NOT IN
remember to always consider whether the sub query might bring back a NULL value!
RE: Question in Comments
'x' NOT IN (NULL,'a','b')
= 'x' <> NULL and 'x' <> 'a' and 'x' <> 'b'
= Unknown and True and True
= Unknown
This is because the original A activity is already being destroyed by the time you start it from B, C or D. Therefore, onCreate will be called in stead of onNewIntent(). One way of solving this is to always destroy the existing A(using FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_NEW_TASK conjunction when startActivity) before starting a new A, so onCreate will always be called, and you put the code of onNewIntent() into onCreate by checking if getIntent() is the intent you started with.
You can remove the duplicated values and keep the list order of insertion with one line of code, Python 3.8.2
mylist = ['b', 'b', 'a', 'd', 'd', 'c'] results = list({value:"" for value in mylist}) print(results) >>> ['b', 'a', 'd', 'c'] results = list(dict.fromkeys(mylist)) print(results) >>> ['b', 'a', 'd', 'c']
Comment as an answer:
if (timetime[0].value)
This works because any variable in JS can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.
Have you tried Aptana? It's based on Eclipse and they have a sweet Rails plugin.
There is no Text
property in the WPF RichTextBox control. Here is one way to get all of the text out:
TextRange range = new TextRange(myRTB.Document.ContentStart, myRTB.Document.ContentEnd);
string allText = range.Text;
Object.create is not yet standard on several browsers, for example IE8, Opera v11.5, Konq 4.3 do not have it. You can use Douglas Crockford's version of Object.create for those browsers but this doesn't include the second 'initialisation object' parameter used in CMS's answer.
For cross browser code one way to get object initialisation in the meantime is to customise Crockford's Object.create. Here is one method:-
Object.build = function(o) {
var initArgs = Array.prototype.slice.call(arguments,1)
function F() {
if((typeof o.init === 'function') && initArgs.length) {
o.init.apply(this,initArgs)
}
}
F.prototype = o
return new F()
}
This maintains Crockford prototypal inheritance, and also checks for any init method in the object, then runs it with your parameter(s), like say new man('John','Smith'). Your code then becomes:-
MY_GLOBAL = {i: 1, nextId: function(){return this.i++}} // For example
var userB = {
init: function(nameParam) {
this.id = MY_GLOBAL.nextId();
this.name = nameParam;
},
sayHello: function() {
console.log('Hello '+ this.name);
}
};
var bob = Object.build(userB, 'Bob'); // Different from your code
bob.sayHello();
So bob inherits the sayHello method and now has own properties id=1 and name='Bob'. These properties are both writable and enumerable of course. This is also a much simpler way to initialise than for ECMA Object.create especially if you aren't concerned about the writable, enumerable and configurable attributes.
For initialisation without an init method the following Crockford mod could be used:-
Object.gen = function(o) {
var makeArgs = arguments
function F() {
var prop, i=1, arg, val
for(prop in o) {
if(!o.hasOwnProperty(prop)) continue
val = o[prop]
arg = makeArgs[i++]
if(typeof arg === 'undefined') break
this[prop] = arg
}
}
F.prototype = o
return new F()
}
This fills the userB own properties, in the order they are defined, using the Object.gen parameters from left to right after the userB parameter. It uses the for(prop in o) loop so, by ECMA standards, the order of property enumeration cannot be guaranteed the same as the order of property definition. However, several code examples tested on (4) major browsers show they are the same, provided the hasOwnProperty filter is used, and sometimes even if not.
MY_GLOBAL = {i: 1, nextId: function(){return this.i++}}; // For example
var userB = {
name: null,
id: null,
sayHello: function() {
console.log('Hello '+ this.name);
}
}
var bob = Object.gen(userB, 'Bob', MY_GLOBAL.nextId());
Somewhat simpler I would say than Object.build since userB does not need an init method. Also userB is not specifically a constructor but looks like a normal singleton object. So with this method you can construct and initialise from normal plain objects.
By alphabetical-order I assume the order to be : A|a < B|b < C|c... Hope this is what @Nick is(or was) looking for and the answer follows the above assumption.
I would suggest to have a class implement compare method of Comparator-interface as :
public int compare(Object o1, Object o2) {
return o1.toString().compareToIgnoreCase(o2.toString());
}
and from the calling method invoke the Arrays.sort method with custom Comparator as :
Arrays.sort(inputArray, customComparator);
Observed results: input Array : "Vani","Kali", "Mohan","Soni","kuldeep","Arun"
output(Alphabetical-order) is : Arun, Kali, kuldeep, Mohan, Soni, Vani
Output(Natural-order by executing Arrays.sort(inputArray) is : Arun, Kali, Mohan, Soni, Vani, kuldeep
Thus in case of natural ordering, [Vani < kuldeep] which to my understanding of alphabetical-order is not the thing desired.
for more understanding of natural and alphabetical/lexical order visit discussion here
You could just set the width to auto. Then the width of the div will equal 0 if it has no content.
width:auto;
Assuming Java (JDK + JRE) is installed in your system, do the following steps:
C:>echo %path%
C:\Program Files (x86)\Java\jdk1.6.0_27\bin;%CATALINA_HOME%\bin;
C:>echo %classpath%
C:\Program Files (x86)\Java\jdk1.6.0_27\lib\tools.jar;
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;
C:>echo %CATALINA_HOME%
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0;
C:>echo %JAVA_HOME%
C:\Program Files (x86)\Java\jdk1.6.0_27;
Now you can test whether Tomcat is setup correctly, by typing the following commands in your command prompt:
C:/>javap javax.servlet.ServletException
C:/>javap javax.servlet.http.HttpServletRequest
It should show a bunch of classes
Now start Tomcat service by double clicking on 'Tomcat7.exe' under 'C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\bin'.
Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.
<script type="text/javascript">
function handleClick(evt) {
var node = evt.target || evt.srcElement;
if (node.name == 'edit') {
node.value = "Modify";
}
}
</script>
<table id="table1" border="1" onclick="handleClick(event);">
<thead>
<tr>
<th>Select
</thead>
<tbody>
<tr>
<td>
<form name="f1" action="#" >
<input id="edit1" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f2" action="#" >
<input id="edit2" type="submit" name="edit" value="Edit">
</form>
<tr>
<td>
<form name="f3" action="#" >
<input id="edit3" type="submit" name="edit" value="Edit">
</form>
</tbody>
</table>
You can try the Boost Tokenizer library, in particular the Escaped List Separator
No one has mentioned the obvious:
var myCallback = function() { console.log("name or age changed"); };
$scope.$watch("name", myCallback);
$scope.$watch("age", myCallback);
This might mean a little less polling. If you watch both name + age
(for this) and name
(elsewhere) then I assume Angular will effectively look at name
twice to see if it's dirty.
It's arguably more readable to use the callback by name instead of inlining it. Especially if you can give it a better name than in my example.
And you can watch the values in different ways if you need to:
$scope.$watch("buyers", myCallback, true);
$scope.$watchCollection("sellers", myCallback);
$watchGroup
is nice if you can use it, but as far as I can tell, it doesn't let you watch the group members as a collection or with object equality.
If you need the old and new values of both expressions inside one and the same callback function call, then perhaps some of the other proposed solutions are more convenient.
There are many cases in which gaps are desired in a chart.
I am currently trying to make a plot of flow rate in a heating system vs. the time of day. I have data for two months. I want to plot only vs. the time of day from 00:00 to 23:59, which causes lines to be drawn between 23:59 and 00:01 of the next day which extend across the chart and disturb the otherwise regular daily variation.
Using the NA() formula (in German NV()) causes Excel to ignore the cells, but instead the previous and following points are simply connected, which has the same problem with lines across the chart.
The only solution I have been able to find is to delete the formulas from the cells which should create the gaps.
Using an IF formula with "" as its value for the gaps makes Excel interpret the X-values as string labels (shudder) for the chart instead of numbers (and makes me swear about the people who wrote that requirement).
good question, i try so many way, but it is curry and boring, until i find shortcut.
only two shortcut, but i think safari is more convenient for that.
<span id="span">HOI</span>
<script>
var span = document.getElementById("span");
console.log(span);
span.style.fontSize = "25px";
span.innerHTML = "String";
</script>
You have two errors in your code:
document.getElementById
-
This retrieves the element with an Id that is "span", you did not specify an id on the span-element.
Capitals in Javascript - Also you forgot the capital of Size.
'In Visual Basic
Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml
Dim FilePath ="C:\MyFolderName" & "\" & FileName 'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.
If System.IO.File.Exists(FilePath) Then
MsgBox("The file exists")
Else
MsgBox("the file doesn't exist")
End If
[[ $1 =~ ^-?[0-9]+$ ]] && echo "number"
Don't forget -
to include negative numbers!
You can use it like this: http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview
Like you found, filter
accepts predicate function which accepts item
by item from the array.
So, you just have to create an predicate function based on the given criteria
.
In this example, criteriaMatch
is a function which returns a predicate
function which matches the given criteria
.
template:
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
{{ item }}
</div>
scope:
$scope.criteriaMatch = function( criteria ) {
return function( item ) {
return item.name === criteria.name;
};
};
you can use this simple script
private SecureString SecureStringConverter(string pass)
{
SecureString ret = new SecureString();
foreach (char chr in pass.ToCharArray())
ret.AppendChar(chr);
return ret;
}
$(document).ready(function() {
$('a[data-toggle="tab"]').on( 'shown.bs.tab', function (e) {
// var target = $(e.target).attr("href"); // activated tab
// alert (target);
$($.fn.dataTable.tables( true ) ).css('width', '100%');
$($.fn.dataTable.tables( true ) ).DataTable().columns.adjust().draw();
} );
});
It works for me, with "autoWidth": false,
For anyone looking also for a solution for authentication, I would add on the scoped packages solution that you can have multiple lines in your .npmrc
file:
//internal-npm.example.com:8080/:_authToken=xxxxxxxxxxxxxxx
//registry.npmjs.org/:_authToken=yyyyyyyyyy
Each line represents a different NPM registry
I used glob.iglob
for a directory structure similar to
data
+---train
¦ +---subfolder1
¦ | ¦ file111.png
¦ | ¦ file112.png
¦ | ¦ ...
¦ |
¦ +---subfolder2
¦ ¦ file121.png
¦ ¦ file122.png
¦ ¦ ...
+---test
¦ file221.png
¦ file222.png
Both of the following options return 4 (as expected, i.e. does not count the subfolders themselves)
len(list(glob.iglob("data/train/*/*.png", recursive=True)))
sum(1 for i in glob.iglob("data/train/*/*.png"))
Create specific .yml files in the resources directory for each and every environment(Eg: dev,qa,stg etc.) that you need to run the application. image of .yml files in resources directory
If you are using spring-boot-maven-plugin 2.0.5.RELEASE in your pom.xml file you can add the profiles within the dependency tag as follows. image of pom.xml spring-boot-maven-plugin (you can configure multiple profiles using multiple profile tags)
Then you can use the following commands to build and run the project.
1) mvn clean install
2) mvn spring-boot:run -Dspring-boot.run.default==qa
Then you will see that the default profile is set as qa while running the project. displaying the default profile when running the application
The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes.
To get rid of the hash, we can use the router's history mode, which leverages the history.pushState
API to achieve URL navigation without a page reload:
import {routes} from './routes'; //import the routes from routes.js
const router = new VueRouter({
routes,
mode: "history",
});
new Vue({
el: '#app',
router,
render: h => h(App)
});
routes.js
import ComponentName from './ComponentName';
export const routes = [
{
path:'/your-path'
component:ComponentName
}
]
The user has the ability to kill his own programs, using kill or Control+C, but I get the impression that's not what happened, and that the user complained to you.
root has the ability to kill programs of course, but if someone has root on your machine and is killing stuff you have bigger problems.
If you are not the sysadmin, the sysadmin may have set up quotas on CPU, RAM, ort disk usage and auto-kills processes that exceed them.
Other than those guesses, I'm not sure without more info about the program.
&& ; || are logical operators.... short circuit
& ; | are boolean logical operators.... Non-short circuit
Moving to differences in execution on expressions. Bitwise operators evaluate both sides irrespective of the result of left hand side. But in the case of evaluating expressions with logical operators, the evaluation of the right hand expression is dependent on the left hand condition.
For Example:
int i = 25;
int j = 25;
if(i++ < 0 && j++ > 0)
System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);
This will print i=26 ; j=25, As the first condition is false the right hand condition is bypassed as the result is false anyways irrespective of the right hand side condition.(short circuit)
int i = 25;
int j = 25;
if(i++ < 0 & j++ > 0)
System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);
But, this will print i=26; j=26,
You can explicitly get back Identity columns using SqlServer's OUTPUT clause: Assuming you have an identity/auto-increment column called ID:
$sql='INSERT INTO [xyz].[myTable] (Field1, Field2, Field3) OUTPUT Inserted.ID VALUES (1, 2, '3')';
Note that in Perl DBI you would then execute the INSERT statement, just like it was a SELECT. And capture the output like it was a SELECT
$sth->execute($sql);
@row=$sth->fetchrow_array; #Only 1 val in 1 row returned
print "Inserted ID: ", $row[0], "\n";
Presumably this is preferable because it doesn't require another request.
pandas is built on top of numpy so you need to have numpy to use the data manipulation feature, so install numpy first.
pip install numpy
Best way to do this, just call CallingFragmentName fragment = (CallingFragmentName) viewPager .getAdapter() .instantiateItem(viewPager, viewPager.getCurrentItem()); It will re-instantiate your calling Fragment, so that it will not throw null pointer exception and call any method of that fragment.
I too solved this issue in my own project by solving this particular line in my code. I added the following.
[DatabaseGenerated(DatabaseGeneratedOption.None)]
After realizing my mistake I then went and changed it to
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
This further ensures that the field named "Id" increments in value each time a new row is inserted in the database
Similar to the others:
cols <- c("premium","change","newprice")
colnames(dataframe) <- cols
Quite simple and easy to modify.
I took some time to check it in detail. I created an icon whose images have sizes of 16, 24, 32, 40, 48, 64, 96, 128 and 256. Then I checked which image is shown. All these were done with normal 96dpi. If using a larger DPI, the larger sizes may be used (only checked this a bit in Windows 7). The results:
Windows XP:
Windows 7:
Windows Runtime: (from here)
So the result: Windows XP uses 16, 32, 48-size icons, while Windows 7 (and presumably also Vista) also uses 256-size icons. All other intermediate icon sizes are ignored (they may be used in some area which I didn't check).
I also checked in Windows 7 what happens if icon sizes are missing:
The missing sizes are generated (obviously). With sizes of 16, 32, and 48, if one is missing, downscaling is preferred. So if we have icons with size 16 and 48, the 32 icon is created from the 48 icon. The 256 icon is only used for these if no other sizes are available! So if the icons are size 16 and 256, the other sizes are upscaled from the 16 icon!
Additionally, if the 256 icon is not there, the (possibly generated) 48 icon is used, but not resized anymore. So we have a (possibly large) empty area with the 48 icon in the middle.
Note that the default desktop icon size in XP was 32x32, while in Windows 7 it is 48x48. As a consequence, for Windows 7 it is relatively important to have a 48 icon. Otherwise, it is upscaled from a smaller icon, which may look quite ugly.
Just a note about Windows XP compatibility: If you reuse the icon as window icon, then note that this can crash your application if you use a compressed 256 icon. The solution is to either not compress the icon or create a second version without the (compressed) 256 icon. See here for more info.
Guess I'm too late...
Came across the same problem today; here is my solution using FileSystemObject
:
Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String
fileSpec = "C:\Temp\test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll
strContents = Replace(strContents, "XXXXX", "YYYY")
objTS.Close
Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close
All answers so far use find
, so here's one with just the shell. No need for external tools in your case:
for dir in /tmp/*/ # list directories in the form "/tmp/dirname/"
do
dir=${dir%*/} # remove the trailing "/"
echo "${dir##*/}" # print everything after the final "/"
done
What about creating an extension method?
public static class NullableExtensions
{
public static bool TryParse(this DateTime? dateTime, string dateString, out DateTime? result)
{
DateTime tempDate;
if(! DateTime.TryParse(dateString,out tempDate))
{
result = null;
return false;
}
result = tempDate;
return true;
}
}
Another way to drop the index is to use a list comprehension:
df.columns = [col[1] for col in df.columns]
b c
0 1 2
1 3 4
This strategy is also useful if you want to combine the names from both levels like in the example below where the bottom level contains two 'y's:
cols = pd.MultiIndex.from_tuples([("A", "x"), ("A", "y"), ("B", "y")])
df = pd.DataFrame([[1,2, 8 ], [3,4, 9]], columns=cols)
A B
x y y
0 1 2 8
1 3 4 9
Dropping the top level would leave two columns with the index 'y'. That can be avoided by joining the names with the list comprehension.
df.columns = ['_'.join(col) for col in df.columns]
A_x A_y B_y
0 1 2 8
1 3 4 9
That's a problem I had after doing a groupby and it took a while to find this other question that solved it. I adapted that solution to the specific case here.
Multitiple inheritance is not possible in C#, however it can be simulated using interfaces, see Simulated Multiple Inheritance Pattern for C#.
The basic idea is to define an interface for the members on class B
that you wish to access (call it IB
), and then have C
inherit from A
and implement IB
by internally storing an instance of B
, for example:
class C : A, IB
{
private B _b = new B();
// IB members
public void SomeMethod()
{
_b.SomeMethod();
}
}
There are also a couple of other alternaitve patterns explained on that page.
I will suppose your JPanel contains JTextField, for the sake of the demo.
Those components provides JTextComponent#setMargin()
method which seems to be what you're looking for.
If you're looking for an empty border of any size around your text, well, use EmptyBorder
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if (range.length==0) {
if ([text isEqualToString:@"\n"]) {
[txtView resignFirstResponder];
if(textView.returnKeyType== UIReturnKeyGo){
[self PreviewLatter];
return NO;
}
return NO;
}
} return YES;
}
Easy workaround that I always use
let list = document.getElementsByClassName("events");
let listArr = Array.from(list)
After this you can run any desired Array methods on the selection
listArr.map(item => console.log(item.id))
listArr.forEach(item => console.log(item.id))
listArr.reverse()
You can modify a sheet via code by taking these actions
In code this would be:
Sub UnProtect_Modify_Protect()
ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="Password"
'Unprotect
ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify
ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password"
'Protect
End Sub
The weakness of this method is that if the code is interrupted and error handling does not capture it, the worksheet could be left in an unprotected state.
The code could be improved by taking these actions
The code to do this would be:
Sub Re-Protect_Modify()
ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
UserInterfaceOnly:=True
'Protect, even if already protected
ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify
End Sub
This code renews the protection on the worksheet, but with the ‘UserInterfaceOnly’ set to true. This allows VBA code to modify the worksheet, while keeping the worksheet protected from user input via the UI, even if execution is interrupted.
This setting is lost when the workbook is closed and re-opened. The worksheet protection is still maintained.
So the 'Re-protection' code needs to be included at the start of any procedure that attempts to modify the worksheet or can just be run once when the workbook is opened.
To navigate to the parent component regardless of the number of parameters in the current route or the parent route: Angular 6 update 1/21/19
let routerLink = this._aRoute.parent.snapshot.pathFromRoot
.map((s) => s.url)
.reduce((a, e) => {
//Do NOT add last path!
if (a.length + e.length !== this._aRoute.parent.snapshot.pathFromRoot.length) {
return a.concat(e);
}
return a;
})
.map((s) => s.path);
this._router.navigate(routerLink);
This has the added bonus of being an absolute route you can use with the singleton Router.
(Angular 4+ for sure, probably Angular 2 too.)
you could do it with a template, if the matrix size is known at compile-time :
template <int width, int height>
class Matrix{
double data[height][width];
//...member functions
};
If many of the above options seem too complex or not what you are looking for here is another approach using node-dir - https://github.com/fshost/node-dir
npm install node-dir
Here is a somple function to list all .xml files searching in subdirectories
import * as nDir from 'node-dir' ;
listXMLs(rootFolderPath) {
let xmlFiles ;
nDir.files(rootFolderPath, function(err, items) {
xmlFiles = items.filter(i => {
return path.extname(i) === '.xml' ;
}) ;
console.log(xmlFiles) ;
});
}
I'm little late to the party, but for anyone like me that came from a Google search and didn't find the right answer. Don't get me wrong there are good answers here, but not exactly what I was looking for, without further ado, here is what I did:
$(document).ready(function() {
var $deleteButton = $('.deleteItem');
$deleteButton.on('click', function(event) {
event.preventDefault();
var $button = $(this);
if(confirm('Are you sure about this ?')) {
var $item = $button.closest('tr.item');
$item.addClass('removed-item')
.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
$(this).remove();
});
}
});
});
_x000D_
/**
* Credit to Sara Soueidan
* @link https://github.com/SaraSoueidan/creative-list-effects/blob/master/css/styles-4.css
*/
.removed-item {
-webkit-animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards;
-o-animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards;
animation: removed-item-animation .6s cubic-bezier(.55,-0.04,.91,.94) forwards
}
@keyframes removed-item-animation {
from {
opacity: 1;
-webkit-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1)
}
to {
-webkit-transform: scale(0);
-ms-transform: scale(0);
-o-transform: scale(0);
transform: scale(0);
opacity: 0
}
}
@-webkit-keyframes removed-item-animation {
from {
opacity: 1;
-webkit-transform: scale(1);
transform: scale(1)
}
to {
-webkit-transform: scale(0);
transform: scale(0);
opacity: 0
}
}
@-o-keyframes removed-item-animation {
from {
opacity: 1;
-o-transform: scale(1);
transform: scale(1)
}
to {
-o-transform: scale(0);
transform: scale(0);
opacity: 0
}
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>id</th>
<th>firstname</th>
<th>lastname</th>
<th>@twitter</th>
<th>action</th>
</tr>
</thead>
<tbody>
<tr class="item">
<td>1</td>
<td>Nour-Eddine</td>
<td>ECH-CHEBABY</td>
<th>@__chebaby</th>
<td><button class="btn btn-danger deleteItem">Delete</button></td>
</tr>
<tr class="item">
<td>2</td>
<td>John</td>
<td>Doe</td>
<th>@johndoe</th>
<td><button class="btn btn-danger deleteItem">Delete</button></td>
</tr>
<tr class="item">
<td>3</td>
<td>Jane</td>
<td>Doe</td>
<th>@janedoe</th>
<td><button class="btn btn-danger deleteItem">Delete</button></td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
_x000D_
Both the answers provided above work fine.
Sometimes it's as simple as adding: '-ms-' in front of the style Like -ms-flex-flow: row wrap; to get it to work also.
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
File format
This tool parses .CRX version 2 format documented by Google. In general, .CRX file format consist of few parts:
Magic header
Version of file format
Public Key information and a package signature
Zipped contents of the extension source code
Magic header is a signature of the file telling that this file is Chrome Extension. Using this header the operating system can determine the actual type of the file (MIME type is application/x-chrome-extension), and how should it be treaten (is it executable? is it a text file?). Then the window system can show beautiful icon to the user.
In .CRX files the magic header has a constant value Cr24 or 0x43723234.
The version is provided by vendor. The version bytes are 0x02000000.
The next part of the file contains the length of the public key information and the length of a digital signature.
All .CRX packages distributed via Chrome WebStore should have public key information and digital signature in order to make possible for browser to check that the package has been transmitted without modifications and that no additions or replacements were made.
After all of the header stuff, typically ending up on 307'th byte, comes the code of extension, stored as zip-archive. So the remainder of the .crx file is the well-known .zip archive.
.crx file opened in the hex editor called HexFiend (on Mac) The header part of a .crx file selected on the picture above. Obviously, you can extract the remaining .zip archive "by hand" using any simple hex editor. In this example, we use handy HexFiend editor on Mac.
The CRX Extractor loads a file provided, checks a magic header, version and trims the file, so only .zip archive remains. Then it returns obtained .zip archive to user.
Do you have Adobe PDFL or Acrobat Professional? You can use preflight operation if you do.
Within your onDropDownChange
handler, just make a jQuery AJAX call, passing in any data you need to pass up to your URL. You can handle successful and failure calls with the success
and error
options. In the success
option, use the data contained in the data
argument to do whatever rendering you need to do. Remember these are asynchronous by default!
function onDropDownChange(e) {
var url = '/Home/Index/' + e.value;
$.ajax({
url: url,
data: {}, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function(data) { alert('got here with data'); },
error: function() { alert('something bad happened'); }
});
}
jQuery's AJAX documentation is here.
These instructions apply if you installed using the official Jenkins Mac installer from http://jenkins-ci.org/
Execute uninstall script from terminal:
'/Library/Application Support/Jenkins/Uninstall.command'
or use Finder to navigate into that folder and double-click on Uninstall.command.
Finally delete last configuration bits which might have been forgotten:
sudo rm -rf /var/root/.jenkins ~/.jenkins
If the uninstallation script cannot be found (older Jenkins version), use following commands:
sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins "/Library/Application Support/Jenkins" /Library/Documentation/Jenkins
and if you want to get rid of all the jobs and builds:
sudo rm -rf /Users/Shared/Jenkins
and to delete the jenkins user and group (if you chose to use them):
sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins
These commands are also invoked by the uninstall script in newer Jenkins versions, and should be executed too:
sudo rm -f /etc/newsyslog.d/jenkins.conf
pkgutil --pkgs | grep 'org\.jenkins-ci\.' | xargs -n 1 sudo pkgutil --forget
If you are usgin Mysql a date column can be passed a String representation of this date
so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement
here is the code illustration:
private String converUtilDateToSqlDate(java.util.Date utilDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sqlDate = sdf.format(utilDate);
return sqlDate;
}
String date = converUtilDateToSqlDate(otherTransaction.getTransDate());
//then pass this date in you sql statement
The general rule I follow is not to include any header file unless I have to. So unless I am storing the object of a class as a member variable of my class I won't include it, I'll just use the forward declaration.
https://codepen.io/anon/pen/YQxbZJ
The HTML
<div id="rates">
<input type="radio" id="x1" name="rate" value="Fixed Rate"> Fixed Rate
<input type="radio" id="x2" name="rate" value="Variable Rate"
checked="checked"> Variable Rate
<input type="radio" id="x3" name="rate" value="Multi Rate" > Multi Rate
</div>
<button id="rdio"> Check Radio </button>
<div id="check">
</div>
The JS
var x ,y;
var x = document.getElementById("check");
function boom()
{
if (document.getElementById("x1").checked)
y = document.getElementById("x1").value;
else if(document.getElementById("x2").checked)
y = document.getElementById("x2").value;
else if (document.getElementById("x3").checked)
y = document.getElementById("x3").value;
else
y = "kuch nhi;"
x.innerHTML = y;
}
var z = document.getElementById('rdio');
z.addEventListener("click", boom);`
First, Jonathan's point about vectorizing is correct. If your getWellID() function is vectorized, then you can skip the loop and just use cat or write.csv:
write.csv(data.frame(wellid=getWellID(well$name, well$plate),
value1=well$value1, value2=well$value2), file=outputFile)
If getWellID() isn't vectorized, then Jonathan's recommendation of using by
or knguyen's suggestion of apply
should work.
Otherwise, if you really want to use for
, you can do something like this:
for(i in 1:nrow(dataFrame)) {
row <- dataFrame[i,]
# do stuff with row
}
You can also try to use the foreach
package, although it requires you to become familiar with that syntax. Here's a simple example:
library(foreach)
d <- data.frame(x=1:10, y=rnorm(10))
s <- foreach(d=iter(d, by='row'), .combine=rbind) %dopar% d
A final option is to use a function out of the plyr
package, in which case the convention will be very similar to the apply function.
library(plyr)
ddply(dataFrame, .(x), function(x) { # do stuff })
If you are using angular-cli, there is yet another option:
Angular CLI provides environment files in src/environments
(default ones are environment.ts
(dev) and environment.prod.ts
(production)).
Note that you need to provide the config parameters in all environment.*
files, e.g.,
environment.ts:
export const environment = {
production: false,
apiEndpoint: 'http://localhost:8000/api/v1'
};
environment.prod.ts:
export const environment = {
production: true,
apiEndpoint: '__your_production_server__'
};
and use them in your service (the correct environment file is chosen automatically):
api.service.ts
// ... other imports
import { environment } from '../../environments/environment';
@Injectable()
export class ApiService {
public apiRequest(): Observable<MyObject[]> {
const path = environment.apiEndpoint + `/objects`;
// ...
}
// ...
}
Read more on application environments on Github (Angular CLI version 6) or in the official Angular guide (version 7).
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
For simple cases like this, TimeUnit should be used. TimeUnit usage is a bit more explicit about what is being represented and is also much easier to read and write when compared to doing all of the arithmetic calculations explicitly. For example, to calculate the number days from milliseconds, the following statement would work:
long days = TimeUnit.MILLISECONDS.toDays(milliseconds);
For cases more advanced, where more finely grained durations need to be represented in the context of working with time, an all encompassing and modern date/time API should be used. For JDK8+, java.time is now included (here are the tutorials and javadocs). For earlier versions of Java joda-time is a solid alternative.
Save sub object first and then call final repository save method.
@PostMapping("/save")
public String save(@ModelAttribute("shortcode") @Valid Shortcode shortcode, BindingResult result) {
Shortcode existingShortcode = shortcodeService.findByShortcode(shortcode.getShortcode());
if (existingShortcode != null) {
result.rejectValue(shortcode.getShortcode(), "This shortode is already created.");
}
if (result.hasErrors()) {
return "redirect:/shortcode/create";
}
**shortcode.setUser(userService.findByUsername(shortcode.getUser().getUsername()));**
shortcodeService.save(shortcode);
return "redirect:/shortcode/create?success";
}
I was able to get mine working using the following Client Credentials:
Authorized JavaScript origins
http://localhost
Authorized redirect URIs
http://localhost:8090/oauth2callback
Note: I used port 8090 instead of 8080, but that doesn't matter as long as your python script uses the same port as your client_secret.json file.
Reference: Python Quickstart
Use the %r
for debugging, since it displays the "raw" data of the variable,
but the others are used for displaying to users.
That's how %r
formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging. Here \n
used to display to users doesn't work. %r
shows the representation if the raw data of the variable.
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: %r" % months
Output:
Here are the months: '\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'
Check this example from Learn Python the Hard Way.
You can use the intl
package (installer) to format dates.
For en_US
formats, it's quite simple:
import 'package:intl/intl.dart';
main() {
final DateTime now = DateTime.now();
final DateFormat formatter = DateFormat('yyyy-MM-dd');
final String formatted = formatter.format(now);
print(formatted); // something like 2013-04-20
}
There are many options for formatting. From the docs:
ICU Name Skeleton
-------- --------
DAY d
ABBR_WEEKDAY E
WEEKDAY EEEE
ABBR_STANDALONE_MONTH LLL
STANDALONE_MONTH LLLL
NUM_MONTH M
NUM_MONTH_DAY Md
NUM_MONTH_WEEKDAY_DAY MEd
ABBR_MONTH MMM
ABBR_MONTH_DAY MMMd
ABBR_MONTH_WEEKDAY_DAY MMMEd
MONTH MMMM
MONTH_DAY MMMMd
MONTH_WEEKDAY_DAY MMMMEEEEd
ABBR_QUARTER QQQ
QUARTER QQQQ
YEAR y
YEAR_NUM_MONTH yM
YEAR_NUM_MONTH_DAY yMd
YEAR_NUM_MONTH_WEEKDAY_DAY yMEd
YEAR_ABBR_MONTH yMMM
YEAR_ABBR_MONTH_DAY yMMMd
YEAR_ABBR_MONTH_WEEKDAY_DAY yMMMEd
YEAR_MONTH yMMMM
YEAR_MONTH_DAY yMMMMd
YEAR_MONTH_WEEKDAY_DAY yMMMMEEEEd
YEAR_ABBR_QUARTER yQQQ
YEAR_QUARTER yQQQQ
HOUR24 H
HOUR24_MINUTE Hm
HOUR24_MINUTE_SECOND Hms
HOUR j
HOUR_MINUTE jm
HOUR_MINUTE_SECOND jms
HOUR_MINUTE_GENERIC_TZ jmv
HOUR_MINUTE_TZ jmz
HOUR_GENERIC_TZ jv
HOUR_TZ jz
MINUTE m
MINUTE_SECOND ms
SECOND s
For non-en_US
dates, you need to explicitly load in the locale. See the DateFormat
docs for more info. The date_symbol_data_local.dart
contains all of the formats for each country/language, if you would like a more in-depth look.
Yes this is good. Tutorials are not always consize and neat. Not only that, creating local variables is waste of space and inefficient
Highlight the 7th line. Paintbrush the format for the first 7 lines a few times. Then do a bigger chunk of paintbrush copying the format until you are done. Every 7th line should be highlighted. Filter by color and then copy and paste (paste the values) from the highlighted cells into a new sheet.
In TortiseSVN settings
right-click menu >> settings >> Saved data >> Authentication data [Clear]
The side effect is that it clears out all authentication data and you have to re-enter your own username/password.
I had the same issue, I resolved it using some javascript.
<script type="text/javascript">
var theHeight = $("#PrimaryContent").height() + 100;
$('#SecondaryContent').height(theHeight);
</script>
A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull
command:
git pull --rebase
You can check the WebClient
documentation for a C# sample that adds a User-Agent to your WebClient
and here for a sample for Windows Phone.
This is the sample for C#:
WebClient client = new WebClient ();
// Add a user agent header in case the
// requested URI contains a query.
client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; " +
"Windows NT 5.2; .NET CLR 1.0.3705;)");
This is a sample for Windows Phone (Silverlight):
request.Headers["UserAgent"] = "appname";
// OR
request.UserAgent = "appname";
its simple go to the folder where your all java code is saved say E:/javaFolder and then javadoc *.java
example
E:\javaFolder> javadoc *.java
WARNING: setting this value too high may cause your system to experience a significant hiccup. The higher the value you set, the more virtual memory is allocated to the screen process when initiating the screen session. I set my ~/.screenrc to "defscrollback 123456789" and when I initiated a screen, my entire system froze up for a good 10 minutes before coming back to the point that I was able to kill the screen process (which was consuming 16.6GB of VIRT mem by then).
timedelta
accepts minus(-) time values. so it could be simple as below
import datetime
enter = datetime.time(hour=1, minute=30)
exit = datetime.time(hour=2, minute=0)
duration = datetime.timedelta(hours=exit.hour-enter.hour, minutes=exit.minute-enter.minute)
# duration = datetime.timedelta(hours=1, minutes=-30)
result
>>> duration
datetime.timedelta(seconds=1800)
$(this).closest('ul').attr('id');
The orderBy
filter performs a stable sorting as of Angular 1.4.5. (See the GitHub pull request https://github.com/angular/angular.js/pull/12408.)
So it is sufficient to use a constant predicate and reverse
set to true
:
<div ng-repeat="friend in friends | orderBy:0:true">{{friend.name}}</div>
I'm surprised no one mentioned the HTML entities  
and  
which produce horizontal white space equivalent to the characters n and m, respectively. If you want to accumulate horizontal white space quickly, those are more efficient than
.
 
 
Along with <space>
and  
, these are the five entities HTML provides for horizontal white space.
Note that except for
, all entities allow breaking. Whatever text surrounds them will wrap to a new line if it would otherwise extend beyond the container boundary. With
it would wrap to a new line as a block even if the text before
could fit on the previous line.
Depending on your use case, that may be desired or undesired. For me, unless I'm dealing with things like names (John
Doe), addresses or references (see eq.
5), breaking as a block is usually undesired.
For large arrays or arrays that will be variable sized you should probably use:
Enumerable.Repeat(true, 1000000).ToArray();
For small array you can use the collection initialization syntax in C# 3:
bool[] vals = new bool[]{ false, false, false, false, false, false, false };
The benefit of the collection initialization syntax, is that you don't have to use the same value in each slot and you can use expressions or functions to initialize a slot. Also, I think you avoid the cost of initializing the array slot to the default value. So, for example:
bool[] vals = new bool[]{ false, true, false, !(a ||b) && c, SomeBoolMethod() };
Another working solution for IE specific styling is
<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">
And then your selector
html[data-useragent*='MSIE 10.0'] body .my-class{
margin-left: -0.4em;
}
The xargs
command takes white space characters (tabs, spaces, new lines) as delimiters.
You can narrow it down only for the new line characters ('\n') with -d
option like this:
ls *.mp3 | xargs -d '\n' mplayer
It works only with GNU xargs.
For BSD systems, use the -0
option like this:
ls *.mp3 | xargs -0 mplayer
This method is simpler and works with the GNU xargs as well.
For MacOS:
ls *.mp3 | tr \\n \\0 | xargs -0 mplayer
Another option would be using flexbox.
While it's not supported by IE8 and IE9, you could consider:
Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:
html {_x000D_
height: 100%;_x000D_
}_x000D_
html body {_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
width: 100%;_x000D_
overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
background-color: #4C4;_x000D_
min-height: 50px;_x000D_
width: 100%;_x000D_
}_x000D_
footer {_x000D_
background-color: #4C4;_x000D_
min-height: 30px;_x000D_
width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
My case: Seeing the same INFO message.
Centos 6.2 x86_64 Tomcat 6.0.24
This fixed the problem for me:
yum install tomcat-native
boom!
Right click on a file → Ignore → Ignore everything beneath.
If the Ignore option is grayed out then:
[Javascript] After a bit of jiggery pokery, this worked for me:
let dateEvents = (
{
'Count': 2,
'Items': [
{
'LastPostedDateTime': {
"S": "10/16/2019 11:04:59"
}
},
{
'LastPostedDateTime': {
"S": "10/30/2019 21:41:39"
}
}
],
}
);
console.log('dateEvents', dateEvents);
The problem I needed to solve was that I might have any number of events and they would all have the same name: LastPostedDateTime all that is different is the date and time.
coord_flip()
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
qplot(cut, carat, data = diamonds, geom = "boxplot") +
coord_flip()
str_wrap()
# wrap text to no more than 15 spaces
library(stringr)
diamonds$cut2 <- str_wrap(diamonds$cut, width = 15)
qplot(cut2, carat, data = diamonds, geom = "boxplot") +
coord_flip()
In Ch 3.9 of R for Data Science, Wickham and Grolemund speak to this exact question:
coord_flip()
switches the x and y axes. This is useful (for example), if you want horizontal boxplots. It’s also useful for long labels: it’s hard to get them to fit without overlapping on the x-axis.
There are at least three different types of logging:
The logging BEFORE the program is executed, which only logs IF the cronjob TRIED to execute the command. That one is located in /var/log/syslog, as already mentioned by @Matthew Lock.
The logging of errors AFTER the program tried to execute, which can be sent to an email or to a file, as mentioned by @Spliffster. I prefer logging to a file, because with email THEN you have a NEW source of problems, and its checking if email sending and reception is working perfectly. Sometimes it is, sometimes it's not. For example, in a simple common desktop machine in which you are not interested in configuring an smtp, sometimes you will prefer logging to a file:
* * * * COMMAND_ABSOLUTE_PATH > /ABSOLUTE_PATH_TO_LOG 2>&1
There are some common sources of problems with cronjobs: * The ABSOLUTE PATH of the binary to be executed. When you run it from your shell, it might work, but the cron process seems to use another environment, and hence it doesn't always find binaries if you don't use the absolute path. * The LIBRARIES used by a binary. It's more or less the same previous point, but make sure that, if simply putting the NAME of the command, is referring to exactly the binary which uses the very same library, or better, check if the binary you are referring with the absolute path is the very same you refer when you use the console directly. The binaries can be found using the locate command, for example:
$locate python
Be sure that the binary you will refer, is the very same the binary you are calling in your shell, or simply test again in your shell using the absolute path that you plan to put in the cronjob.
You should mention the content type as well to omit the file accessing issue.
import os
image='fly.png'
s3_filestore_path = 'images/fly.png'
filename, file_extension = os.path.splitext(image)
content_type_dict={".png":"image/png",".html":"text/html",
".css":"text/css",".js":"application/javascript",
".jpg":"image/png",".gif":"image/gif",
".jpeg":"image/jpeg"}
content_type=content_type_dict[file_extension]
s3 = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'),
region_name='ap-south-1',
aws_access_key_id=S3_KEY,
aws_secret_access_key=S3_SECRET)
s3.put_object(Body=image, Bucket=S3_BUCKET, Key=s3_filestore_path, ContentType=content_type)
The RestTemplate getForObject()
method does not support setting headers. The solution is to use the exchange()
method.
So instead of restTemplate.getForObject(url, String.class, param)
(which has no headers), use
HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.GET, entity, String.class, param);
Finally, use response.getBody()
to get your result.
This question is similar to this question.
UPDATE: As a commenter pointed out, the problem I outline below was fixed some time before this post. However, I knew of the HP-SSH project and I asked the author to weigh in. As they explain in the (rightfully) most upvoted answer, encryption is not the source of the problem. Yay for email and people smarter than myself!
Wow, a year-old question with nothing but incorrect answers. However, I must admit that I assumed the slowdown was due to encryption when I asked myself the same question. But ask yourself the next logical question: how quickly can your computer encrypt and decrypt data? If you think that rate is anywhere near the 4.5Mb/second reported by the OP (.5625MBs or roughly half the capacity of a 5.5" floppy disk!) smack yourself a few times, drink some coffee, and ask yourself the same question again.
It apparently has to do with what amounts to be an oversight in the packet size selection, or at least that's what the author of LIBSSH2 says,
The nature of SFTP and its ACK for every small data chunk it sends, makes an initial naive SFTP implementation suffer badly when sending data over high latency networks. If you have to wait a few hundred milliseconds for each 32KB of data then there will never be fast SFTP transfers. This sort of naive implementation is what libssh2 has offered up until and including libssh2 1.2.7.
So the speed hit is due to tiny packet sizes x mandatory ack responses for each packet, which is clearly insane.
The High Performance SSH/SCP (HP-SSH) project provides an OpenSSH patch set which apparently improves the internal buffers as well as parallelizing encryption. Note, however, that even the non-parallelized versions ran at speeds above the 40Mb/s unencrypted speeds obtained by some commenters. The fix involves changing the way in which OpenSSH was calling the encryption libraries, NOT the cipher and there is zero difference in speed between AES128 and AES256. Encryption takes some time, but it is marginal. It might have mattered back in the 90's but (like the speed of Java vs C) it just doesn't matter anymore.
With the inspiration from Roy Tinker's comment, I ended up using a simple extension method on the Uri class that keeps my code concise and clean:
using System.Web;
public static class HttpExtensions
{
public static Uri AddQuery(this Uri uri, string name, string value)
{
var httpValueCollection = HttpUtility.ParseQueryString(uri.Query);
httpValueCollection.Remove(name);
httpValueCollection.Add(name, value);
var ub = new UriBuilder(uri);
ub.Query = httpValueCollection.ToString();
return ub.Uri;
}
}
Usage:
Uri url = new Uri("http://localhost/rest/something/browse").
AddQuery("page", "0").
AddQuery("pageSize", "200");
Edit - Standards compliant variant
As several people pointed out, httpValueCollection.ToString()
encodes Unicode characters in a non-standards-compliant way. This is a variant of the same extension method that handles such characters by invoking HttpUtility.UrlEncode
method instead of the deprecated HttpUtility.UrlEncodeUnicode
method.
using System.Web;
public static Uri AddQuery(this Uri uri, string name, string value)
{
var httpValueCollection = HttpUtility.ParseQueryString(uri.Query);
httpValueCollection.Remove(name);
httpValueCollection.Add(name, value);
var ub = new UriBuilder(uri);
// this code block is taken from httpValueCollection.ToString() method
// and modified so it encodes strings with HttpUtility.UrlEncode
if (httpValueCollection.Count == 0)
ub.Query = String.Empty;
else
{
var sb = new StringBuilder();
for (int i = 0; i < httpValueCollection.Count; i++)
{
string text = httpValueCollection.GetKey(i);
{
text = HttpUtility.UrlEncode(text);
string val = (text != null) ? (text + "=") : string.Empty;
string[] vals = httpValueCollection.GetValues(i);
if (sb.Length > 0)
sb.Append('&');
if (vals == null || vals.Length == 0)
sb.Append(val);
else
{
if (vals.Length == 1)
{
sb.Append(val);
sb.Append(HttpUtility.UrlEncode(vals[0]));
}
else
{
for (int j = 0; j < vals.Length; j++)
{
if (j > 0)
sb.Append('&');
sb.Append(val);
sb.Append(HttpUtility.UrlEncode(vals[j]));
}
}
}
}
}
ub.Query = sb.ToString();
}
return ub.Uri;
}
I think this solution is handy if you can test the value of the error field later. This is also applicable by creating a temporary table and returning a list of errors.
DROP PROCEDURE IF EXISTS $procName;
DELIMITER //
CREATE PROCEDURE $procName($params)
BEGIN
DECLARE error INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET error = 1;
SELECT
$fields
FROM $tables
WHERE $where
ORDER BY $sorting LIMIT 1
INTO $vars;
IF error = 0 THEN
SELECT $vars;
ELSE
SELECT 1 AS error;
SET @error = 0;
END IF;
END//
CALL $procName($effp);
For me there was no default constructor defined for the POJOs I was trying to use. creating default constructor fixed it.
public class TeamCode {
@Expose
private String value;
public String getValue() {
return value;
}
**public TeamCode() {
}**
public TeamCode(String value) {
this.value = value;
}
@Override
public String toString() {
return "TeamCode{" +
"value='" + value + '\'' +
'}';
}
public void setValue(String value) {
this.value = value;
}
}
Just change the directory to another one and come back. Probably that one has been deleted or moved.
Something i find pretty cool, which is that if your list is only 2 items long:
ls = ['a', 'b']
dict([ls])
>>> {'a':'b'}
Remember, dict accepts any iterable containing an iterable where each item in the iterable must itself be an iterable with exactly two objects.
In C, NAN
is declared in <math.h>
.
In C++, std::numeric_limits<double>::quiet_NaN()
is declared in <limits>
.
But for checking whether a value is NaN, you can't compare it with another NaN value. Instead use isnan()
from <math.h>
in C, or std::isnan()
from <cmath>
in C++.
Why aren't you doing this:
[chr(x) for x in [66,53,0,94]]
It's called a list comprehension. You can find plenty of information on Google, but here's the link to the Python (2.6) documentation on list comprehensions. You might be more interested in the Python 3 documenation, though.
As explained in the different asnwers already, sys.argv
contains the command line arguments that called your Python script.
However, Python comes with libraries that help you parse command line arguments very easily. Namely, the new standard argparse. Using argparse
would spare you the need to write a lot of boilerplate code.
You can do it with 1 printf
:
System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname);
You can use the converse approach to achieve the same result - start from the composite and then remove styling using the unset
keyword. For example, if you start with the following sample composition:
.composite {
color: red;
margin-left: 50px;
background-color: green
}
you can then increase selector specificity to selectively remove styles using unset
:
.composite.no-color {
color: unset
}
.composite.no-margin-left {
margin-left: unset
}
.composite.no-background-color {
background-color: unset
}
Here is a JSFiddle demonstrating this approach.
One benefit of this approach is that because the specificity
of the compound selectors is higher than the composite itself, you do not need all of the combinations of classes to achieve the desired results for multiple combinations:
/* Multi-unset compound selector combinations, such as the one that follows, ARE NOT NECESSARY because of the higher specificity of each individual compound selectors listed above. This keeps things simple. */
.composite.no-background-color.no-color.no-margin-left {
background-color: unset;
color: unset;
margin-left: unset
}
Furthermore, at 96% support for the unset
keyword, browser coverage is excellent.
check the command : NA!=NA
: you'll get the result NA
, hence the error message.
You have to use the function is.na
for your if
statement to work (in general, it is always better to use this function to check for NA
values) :
comments = c("no","yes",NA)
for (l in 1:length(comments)) {
if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"
d = dict.fromkeys(a, 0)
a
is the list, 0
is the default value. Pay attention not to set the default value to some mutable object (i.e. list or dict), because it will be one object used as value for every key in the dictionary (check here for a solution for this case). Numbers/strings are safe.
Use prepared statements, they have methods to set correctly parameters for each native Java type.
As with @kidbrax's answer, you can use the +
to add days. To get this to work I had to explicitly declare my cell data as being a date:
A1: =DATE(2014, 03, 28)
A2: =A1+1
Value of A2 is now 29th March 2014
If you download XML file and open it for example in Notepad++ you'll see that encoding is set to something else than UTF8 - I'v had the same problem with xml made myself, and it was just te encoding in the editor :)
String <?xml version="1.0" encoding="UTF-8"?>
don't set up the encoding of the document, it's only info for validator or another resource.
You can do it using write() :
#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()
The directory 'node_modules' may not be in current directory, so you should resolve the path dynamically.
var bootstrap_dir = require.resolve('bootstrap')
.match(/.*\/node_modules\/[^/]+\//)[0];
app.use('/scripts', express.static(bootstrap_dir + 'dist/'));
I would suggest this:
e.pageX - this.getBoundingClientRect().left
this comes because you add some property to one of your model and you did not update-Database
. to solve this you have to remove it from model or you have to add-migration anyProperName
with that properties and Update-database
.
Using the first for
-loop you manually enumerate through the array by increasing an index to the length of the array, then getting the value at the current index manually.
The latter syntax is added in Java 5 and enumerates an array by using an Iterator
instance under the hoods. You then have only access to the object (not the index) and you won't be able to adjust the array while enumerating.
It's convenient when you just want to perform some actions on all objects in an array.
To resolve this problem:
That's all.
I'm thinking unload is called all but at hard exist in 4.7. But, if you are playing around with older versions of .Net, try doing this in your loading method:
e.Handled = true;
I don't think older versions will unload until loading is handled. Just posting because I see others still asking this question, and haven't seen this proposed as a solution. I only touch .Net a few times a year, and ran into this a few years back. But, I wonder if it's as simple as unload not being called until loading has finished. Seems like it works for me, but again in newer .Net it seems to always call unload even if loading isn't marked as handled.
Nick Vogt at H3XED posted this syntax: https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080
Take this link and replace the expression "VIDEOID" with the (shortened/shared) ID of the video.
Exapmple for ID: i3jNECZ3ybk looks like this: ... /v/i3jNECZ3ybk?version=3&vq=hd1080
What you get as a result is the standalone 1080p video but not in the Tube environment.
There was an answer here: Secure distribution of NodeJS applications. Raynos said: V8 allows you to pre-compile JavaScript.
To check that the file you're trying to open actually exists, you can change directories in terminal using cd
. To change to ~/Desktop/sass/css
: cd ~/Desktop/sass/css
. To see what files are in the directory: ls
.
If you want information about either of those commands, use the man
page: man cd
or man ls
, for example.
Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.
On Mac OS X, you can also use open
to open a finder window: open .
will open the current directory in finder. (open ~/Desktop/sass/css
will open the ~/Desktop/sass/css
).
Install the NUnit and NunitTestAdapter package to your test projects from Manage Nunit packages. to perform the same: 1 Right-click on menu Project ? click "Manage NuGet Packages". 2 Go to the "Browse" tab -> Search for the Nunit (or any other package which you want to install) 3 Click on the Package -> A side screen will open "Select the project and click on the install.
Perform your tasks (Add code) If your project is a Console application then a play/run button is displayed on the top click on that any your application will run and If your application is a class library Go to the Test Explorer and click on "Run All" option.
Based on Bluefeet's accepted response with an added nuance using OVER()
:
SELECT distributor_id,
COUNT(*) total,
SUM(case when level = 'exec' then 1 else 0 end) OVER() ExecCount,
SUM(case when level = 'personal' then 1 else 0 end) OVER () PersonalCount
FROM yourtable
GROUP BY distributor_id
Using OVER()
with nothing in the () will give you the total count for the whole dataset.
Docker with BRIDGE network. for Ubuntu 16.04 with display manager lightdm:
cd /etc/lightdm/lightdm.conf.d
sudo nano user.conf
[Seat:*]
xserver-allow-tcp=true
xserver-command=X -listen tcp
you can use more private permissions
xhost +
docker run --volume="$HOME/.Xauthority:/root/.Xauthority:rw" --env="DISPLAY=$HOST_IP_IN_BRIDGE_NETWORK:0" --net=bridge $container_name
You also should set border:none
to that css class.
The answers here work for just 2 cells, but as soon as those columns have more in them it can lead to a bit more complexity. I think I've found a generalized solution for any number of cells in multiple columns.
#Goals Get a vertical sequence of tags on mobile to arrange themselves in whatever order the design calls for on tablet/desktop. In this concrete example, one tag must enter flow earlier than it normally would, and another later than it normally would.
##Mobile
[1 headline]
[2 image]
[3 qty]
[4 caption]
[5 desc]
##Tablet+
[2 image ][1 headline]
[ ][3 qty ]
[ ][5 desc ]
[4 caption][ ]
[ ][ ]
So headline needs to shuffle right on tablet+, and technically, so does desc - it sits above the caption tag that precedes it on mobile. You'll see in a moment 4 caption is in trouble too.
Let's assume every cell could vary in height, and needs to be flush top-to-bottom with its next cell (ruling out weak tricks like a table).
As with all Bootstrap Grid problems step 1 is to realize the HTML has to be in mobile-order, 1 2 3 4 5, on the page. Then, determine how to get tablet/desktop to reorder itself in this way - ideally without Javascript.
The solution to get 1 headline
and 3 qty
to sit to the right not the left is to simply set them both pull-right
. This applies CSS float: right
, meaning they find the first open space they'll fit to the right. You can think of the browser's CSS processor working in the following order: 1 fits in to the right top corner. 2 is next and is regular (float: left
), so it goes to top-left corner. Then 3, which is float: right
so it leaps over underneath 1.
But this solution wasn't enough for 4 caption
; because the right 2 cells are so short 2 image
on the left tends to be longer than the both of them combined. Bootstrap Grid is a glorified float hack, meaning 4 caption
is float: left
. With 2 image
occupying so much room on the left, 4 caption
attempts to fit in the next available space - often the right column, not the left where we wanted it.
The solution here (and more generally for any issue like this) was to add a hack tag, hidden on mobile, that exists on tablet+ to push caption out, that then gets covered up by a negative margin - like this:
[2 image ][1 headline]
[ ][3 qty ]
[ ][4 hack ]
[5 caption][6 desc ^^^]
[ ][ ]
http://jsfiddle.net/b9chris/52VtD/16633/
HTML:
<div id=headline class="col-xs-12 col-sm-6 pull-right">Product Headline</div>
<div id=image class="col-xs-12 col-sm-6">Product Image</div>
<div id=qty class="col-xs-12 col-sm-6 pull-right">Qty, Add to cart</div>
<div id=hack class="hidden-xs col-sm-6">Hack</div>
<div id=caption class="col-xs-12 col-sm-6">Product image caption</div>
<div id=desc class="col-xs-12 col-sm-6 pull-right">Product description</div>
CSS:
#hack { height: 50px; }
@media (min-width: @screen-sm) {
#desc { margin-top: -50px; }
}
So, the generalized solution here is to add hack tags that can disappear on mobile. On tablet+ the hack tags allow displayed tags to appear earlier or later in the flow, then get pulled up or down to cover up those hack tags.
Note: I've used fixed heights for the sake of the simple example in the linked jsfiddle, but the actual site content I was working on varies in height in all 5 tags. It renders properly with relatively large variance in tag heights, especially image and desc.
Note 2: Depending on your layout, you may have a consistent enough column order on tablet+ (or larger resolutions), that you can avoid use of hack tags, using margin-bottom
instead, like so:
Note 3: This uses Bootstrap 3. Bootstrap 4 uses a different grid set, and won't work with these examples.
Best thing to use is HTMLAgilityPack. You can also look into using Fizzler or CSQuery depending on your needs for selecting the elements from the retrieved page. Using LINQ or Regukar Expressions is just to error prone, especially when the HTML can be malformed, missing closing tags, have nested child elements etc.
You need to stream the page into an HtmlDocument object and then select your required element.
// Call the page and get the generated HTML
var doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlNode.ElementsFlags["br"] = HtmlAgilityPack.HtmlElementFlag.Empty;
doc.OptionWriteEmptyNodes = true;
try
{
var webRequest = HttpWebRequest.Create(pageUrl);
Stream stream = webRequest.GetResponse().GetResponseStream();
doc.Load(stream);
stream.Close();
}
catch (System.UriFormatException uex)
{
Log.Fatal("There was an error in the format of the url: " + itemUrl, uex);
throw;
}
catch (System.Net.WebException wex)
{
Log.Fatal("There was an error connecting to the url: " + itemUrl, wex);
throw;
}
//get the div by id and then get the inner text
string testDivSelector = "//div[@id='test']";
var divString = doc.DocumentNode.SelectSingleNode(testDivSelector).InnerHtml.ToString();
[EDIT] Actually, scrap that. The simplest method is to use FizzlerEx, an updated jQuery/CSS3-selectors implementation of the original Fizzler project.
Code sample directly from their site:
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
//get the page
var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html");
var page = document.DocumentNode;
//loop through all div tags with item css class
foreach(var item in page.QuerySelectorAll("div.item"))
{
var title = item.QuerySelector("h3:not(.share)").InnerText;
var date = DateTime.Parse(item.QuerySelector("span:eq(2)").InnerText);
var description = item.QuerySelector("span:has(b)").InnerHtml;
}
I don't think it can get any simpler than that.
>>> x='$120'
>>> import string
>>> a=string.maketrans('','')
>>> ch=a.translate(a, string.digits)
>>> int(x.translate(a, ch))
120
I know this thread has been answered, but another solution that may be useful for some, particularly to those with multiple pages where they want to have this button, is to give the input an id and place the code in a JavaScript file. You can then place the code for the button on multiple pages, taking up less space in your code.
For the button:
<input type="button" id="cancel_edit" value="Cancel"></input>
in the JavaScript file:
$("#cancel_edit").click(function(){
window.open('','_parent','');
window.close();
});
Try this
import ("strconv")
value := "123"
number,err := strconv.ParseUint(value, 10, 32)
finalIntNum := int(number) //Convert uint64 To int
Aggregate is where you protect your invariants and force consistency by limiting its access thought aggregate root. Do not forget, aggregate should design upon your project business rules and invariants, not database relationship. you should not inject any repository and no queries are not allowed.
With python 3 you can reverse the string in-place meaning it won't get assigned to another variable. First you have to convert the string into a list and then leverage the reverse()
function.
https://docs.python.org/3/tutorial/datastructures.html
def main():
my_string = ["h","e","l","l","o"]
print(reverseString(my_string))
def reverseString(s):
print(s)
s.reverse()
return s
if __name__ == "__main__":
main()
You have your ssh clone
statement wrong: git clone username [email protected]:root/test.git
That statement would try to clone a repository named username
into the location relative to your current path, [email protected]:root/test.git
.
You want to leave out username
:
git clone [email protected]:root/test.git
Since Spring 3.0 you also can throw an Exception declared with @ResponseStatus
annotation:
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
...
}
@Controller
public class SomeController {
@RequestMapping.....
public void handleCall() {
if (isFound()) {
// whatever
}
else {
throw new ResourceNotFoundException();
}
}
}
While I agree that the accepted answer is usually the best solution and definitely easier to use, I noticed no one displayed the proper usage of the iterator. So here is a quick example:
Iterator<Object> it = arrayList.iterator();
while(it.hasNext())
{
Object obj = it.next();
//Do something with obj
}
I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.
1) Create environment variable in your environment.ts
export const environment = {
...
// runtime variables
isContentLoading: false,
isDeployNeeded: false
}
2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template
import { environment } from 'environments/environment';
@Component(...)
export class TestComponent {
...
env = environment;
}
3) Use it in template...
<app-spinner *ngIf='env.isContentLoading'></app-spinner>
in *.ts ...
env.isContentLoading = false
(or just environment.isContentLoading in case you don't need it for template)
You can create your own set of globals within environment.ts like so:
export const globals = {
isContentLoading: false,
isDeployNeeded: false
}
and import directly these variables (y)
This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:
<table>
<tr>
<td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
Hello World
</td>
</tr>
</table>
Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.
If the gif is displayed but not animating, see reference links at very bottom of this answer.
Displaying the gif + overlay, however, is easier than you might think.
All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.
So, when the button is pressed, just unhide those two divs. That's it!
$("#button").click(function() {_x000D_
$('#myOverlay').show();_x000D_
$('#loadingGIF').show();_x000D_
setTimeout(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
},2500);_x000D_
});_x000D_
/* Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
You might enjoy playing with the new backdrop-filter:blur(_px)
css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)
References:
http://www.paulirish.com/2007/animated-gif-not-animating/
Animated GIF while loading page does not animate
https://wordpress.org/support/topic/animated-gif-not-working
Your code below is zooming the map to fit the specified bounds:
addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);
If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
}
If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one. I usually push the markers into an array (for later use) and test the length of that array.
If you will only ever have one marker, don't use fitBounds. Call setCenter
, setZoom
with the marker position and your desired zoom level.
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(your desired zoom);
}
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
_x000D_
<html>
<head>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
<script type="text/javascript">
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(5);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
addMarker(27.703402, 85.311668, 'New Road');
// center = bounds.getCenter();
// map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
_x000D_
Reference the jquery min version that includes ajax:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I meet this question when i use intellij 15.0,then i update to 15.02 version. after that, I edit configurations and reset the Default JRE to my own JRE.It works well for me;
I can speak from experience. Even if your ASP.net website only uses .NET libraries supported by Mono you are going to have a hard time getting it to run if its anything beyond Hello World.
You won't have to re-write much code but you will spend hours/days/weeks dealing with little issues with mod_mono/xsp/apache configuration and file permissions and error handling and all the little things that go into a large website. (Be prepared to spend a lot of time asking questions on serverfault :) )
The problem is that a lot of people don't use Mono for ASP.net websites and so there aren't as many people reporting bugs so a lot of things that are minor bugs go un-fixed for a long time.
Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:
$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);
Output:
Array
(
[0] => 4
)
Now:
$key = 4;
$value = $array[$key];
print $value;
Output:
Hello There
Not being a developer I found a solution in running multiple ps commands in one line. E.g:
powershell "& 'c:\path with spaces\to\executable.exe' -arguments ; second command ; etc
By placing a " (double quote) before the & (ampersand) it executes the executable. In none of the examples I have found this was mentioned. Without the double quotes the ps prompt opens and waits for input.
You should take a look to Quartz it's a java framework wich works with EE and SE editions and allows to define jobs to execute an specific time
Even if this thread is old is the first on Google, so I'll post an Oracle equivalent to the function implemented here, using regular expressions.
Is fairly faster than nested replace(), and much cleaner.
To replace strings 'a','b','c' with 'd' in a string column from a given table
select regexp_replace(string_col,'a|b|c','d') from given_table
It is nothing else than a regular expression for several static patterns with 'or' operator.
Beware of regexp special characters!
I imagine that you define your image something like this:
<img id="image_portrait" src="" alt="chef etat" width="120" height="135" />
You can simply load/update image for this tag and chage/set atts (width,height):
var imagelink;
var height;
var width;
$("#image_portrait").attr("src", imagelink);
$("#image_portrait").attr("width", width);
$("#image_portrait").attr("height", height);
At first glance one really wants to use New-PSDrive
supplying it credentials.
> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user
New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.
The documentation states that you can provide a PSCredential
object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.
Therefore you can either use net use
or the WScript.Network
object, calling the MapNetworkDrive
function:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")
Apparently with newer versions of PowerShell, the New-PSDrive
cmdlet works to map network shares with credentials!
New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist
The best way using background with gradient as it does not increase app size of your app images are poison for android app so try to use it less instead of using one color as a background you can use multiple colors in one background.
To send a message to a user you first need a User
instance representing the user you want to send the message to.
User
instance from a message the user sent by
doing message.autor
User
instance from a user id with client.fetchUser
Once you got a user instance you can send the message with .send
client.on('message', (msg) => {
if (!msg.author.bot) msg.author.send('ok ' + msg.author.id);
});
client.fetchUser('487904509670337509', false).then((user) => {
user.send('heloo');
});
Execute the code below to update n number of rows, where Parent ID is the id you want to get the data from and Child ids are the ids u need to be updated so it's just u need to add the parent id and child ids to update all the rows u need using a small script.
UPDATE [Table]
SET couloumn1= (select couloumn1 FROM Table WHERE IDCouloumn = [PArent ID]),
couloumn2= (select couloumn2 FROM Table WHERE IDCouloumn = [PArent ID]),
couloumn3= (select couloumn3 FROM Table WHERE IDCouloumn = [PArent ID]),
couloumn4= (select couloumn4 FROM Table WHERE IDCouloumn = [PArent ID]),
WHERE IDCouloumn IN ([List of child Ids])
Tried these but for my purposes in MS SQL Server 2005 the following was most useful, which I found at xaprb
declare @result varchar(8000);
set @result = '';
select @result = @result + name + ' '
from master.dbo.systypes;
select rtrim(@result);
@Mark as you mentioned it was the space character that caused issues for me.
Name:
x:Name:
Using both directives in XAML for one FrameworkElement or FrameworkContentElement will cause an exception: if the XAML is markup compiled, the exception will occur on the markup compile, otherwise it occurs on load.
Another way could be as follows:-
#extracting numeric columns from iris datset
(iris[sapply(iris, is.numeric)])
the tip of your current branch is behind its remote counterpart
means that there have been changes on the remote branch that you don’t have locally. and git tells you import new changes from REMOTE
and merge it with your code and then push
it to remote.
You can use this command to force changes to server with local repo ().
git push -f origin master
with -f
tag you will override Remote Brach code
with your code.
The answer below comes from here(with old javascript syntax(no arrow function, support IE 10+)): https://stackoverflow.com/a/52809105/9168962
(function() {
if (typeof window.CustomEvent === "function") return false; // If not IE
function CustomEvent(event, params) {
params = params || {bubbles: false, cancelable: false, detail: null};
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
window.CustomEvent = CustomEvent;
})();
(function() {
history.pushState = function (f) {
return function pushState() {
var ret = f.apply(this, arguments);
window.dispatchEvent(new CustomEvent("pushState"));
window.dispatchEvent(new CustomEvent("locationchange"));
return ret;
};
}(history.pushState);
history.replaceState = function (f) {
return function replaceState() {
var ret = f.apply(this, arguments);
window.dispatchEvent(new CustomEvent("replaceState"));
window.dispatchEvent(new CustomEvent("locationchange"));
return ret;
};
}(history.replaceState);
window.addEventListener("popstate", function() {
window.dispatchEvent(new CustomEvent("locationchange"));
});
})();
If you want to avoid using write()
or writelines()
and joining the strings with a newline yourself, you can pass all of your lines to print()
, and the newline delimiter and your file handle as keyword arguments. This snippet assumes your strings do not have trailing newlines.
print(line1, line2, sep="\n", file=f)
You don't need to put a special newline character is needed at the end, because print()
does that for you.
If you have an arbitrary number of lines in a list, you can use list expansion to pass them all to print()
.
lines = ["The Quick Brown Fox", "Lorem Ipsum"]
print(*lines, sep="\n", file=f)
It is OK to use "\n"
as the separator on Windows, because print()
will also automatically convert it to a Windows CRLF newline ("\r\n"
).
Seems like a lazy way to always know that your WHERE clause is already defined and allow you to keep adding conditions without having to check if it is the first one.
Assume that, if you want to remove NAT rules,
List the appended IPtables using the command below,
# sudo iptables -L -t nat -v
Chain PREROUTING (policy ACCEPT 18 packets, 1382 bytes)
pkts bytes target prot opt in out source destination
7 420 DNAT tcp -- any any anywhere saltmaster tcp dpt:http to:172.31.5.207:80
0 0 DNAT tcp -- eth0 any anywhere anywhere tcp dpt:http to:172.31.5.207:8080
If you would like to remove the nat rule from the IPtables, just execute the command,
# sudo iptables -F -t nat -v
Flushing chain `PREROUTING'
Flushing chain `INPUT'
Flushing chain `OUTPUT'
Flushing chain `POSTROUTING'
Then, you can verify that,
# sudo iptables -L -t nat -v
JAVA_HOME should be like this C:\PROGRA~1\Java\jdk
Hope this will work!
If you need to do this on a running container you can use docker exec (added in 1.3).
First, find the container's name or ID:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b9b7400ddd8f ubuntu:latest "/bin/bash" 2 seconds ago Up 2 seconds elated_hodgkin
In the example above we can either use b9b7400ddd8f
or elated_hodgkin
.
If you wanted to copy everything in /tmp/somefiles
on the host to /var/www
in the container:
$ cd /tmp/somefiles
$ tar -cv * | docker exec -i elated_hodgkin tar x -C /var/www
We can then exec /bin/bash
in the container and verify it worked:
$ docker exec -it elated_hodgkin /bin/bash
root@b9b7400ddd8f:/# ls /var/www
file1 file2
You need to join
the two tables and then filter the result in where
clause:
SELECT country.name as country, country.headofstate
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'
This solved my problem.
I just downloaded https://dl.google.com/android/repository/tools_r25.2.5-macosx.zip214 and overwrite the tools folder at ~/Library/Android/sdk/tools
If you call it like this: $ python myfile.py var1 var2 var3
import sys
var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]
Similar to arrays you also have sys.argv[0]
which is always the current working directory.
I wrote a short convenience function for posting JSON.
$.postJSON = function(url, data, success, args) {
args = $.extend({
url: url,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: success
}, args);
return $.ajax(args);
};
$.postJSON('test/url', data, function(result) {
console.log('result', result);
});
Here is how I did it using React and CJSX (Coffee JSX) based on Vitim.us solution.
Using componentWillReceiveProps
I was able to detect every property changes. Then I just check whether the url has changed between the future props and the current one. And voilà.
@propTypes =
element: React.PropTypes.shape({
version: React.PropTypes.number
params:
React.PropTypes.shape(
url: React.PropTypes.string.isRequired
filename: React.PropTypes.string.isRequired
title: React.PropTypes.string.isRequired
ext: React.PropTypes.string.isRequired
).isRequired
}).isRequired
componentWillReceiveProps: (nextProps) ->
element = ReactDOM.findDOMNode(this)
audio = element.querySelector('audio')
source = audio.querySelector('source')
# When the url changes, we refresh the component manually so it reloads the loaded file
if nextProps.element.params?.filename? and
nextProps.element.params.url isnt @props.element.params.url
source.src = nextProps.element.params.url
audio.load()
I had to do it this way, because even a change of state or a force redraw didn't work.
I didn't have much luck with many of these solutions on all browsers. This is the solution that worked for me.
For router changes:
router.events.subscribe((val) => {
setTimeout(() => {
if (this.searchElement) {
this.searchElement.nativeElement.focus();
}
}, 1);
})
Then ngAfterViewInit()
for the onload scenario.
You don't need to use "display: table". The reason your margin: 0 auto centering attempt doesn't work is because you didn't specify a width.
This will work just fine:
.wrap {
background: #aaa;
margin: 0 auto;
width: some width in pixels since it's the container;
}
You don't need to specify display: block since that div will be block by default. You can also probably lose the overflow: hidden.
Try to minimize the use of <br>
as much as you possibly can. HTML is supposed to carry content and structure, <br>
is neither. A simple workaround is to wrap your input elements in <p>
elements, like so:
<form name="publish" id="publish" action="publishprocess.php" method="post">
<p><input type="text" id="title" name="title" size="60" maxlength="110" value="<?php echo $title ?>" /> - Title</p>
<p><input type="text" id="contact" name="contact" size="24" maxlength="30" value="<?php echo $contact ?>" /> - Contact</p>
<p>Task description (you may include task description, requirements on bidders, time requirements, etc):</p>
<p><textarea name="detail" id="detail" rows="7" cols="60" style="font-family:Arial, Helvetica, sans-serif"><?php echo $detail ?></textarea></p>
<p><input type="text" id="price" name="price" size="10" maxlength="20" value="<?php echo $price ?>" /> - Price</p>
<p><input class="tagvalidate" type="text" id="tag" name="tag" size="40" maxlength="60" value="<?php echo $tag ?>" /> - Skill or Knowledge Tags</p>
<p>Combine multiple words into single-words, space to separate up to 3 tags (example:photoshop quantum-physics computer-programming)</p>
<p>District Restriction:<?php echo $locationtext.$cityname; ?></p>
<p><input type="submit" id="submit" value="Submit" /></p>
</form>
If you hit git stash
when you have changes in the working copy (not in the staging area), git will create a stashed object and pushes onto the stack of stashes (just like you did git checkout -- .
but you won't lose changes). Later, you can pop from the top of the stack.
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
Here was my solution:
In the constructors add these two lines:
this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;
In your form, add this method:
protected override void OnPaintBackground(PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.LimeGreen, e.ClipRectangle);
}
Be warned, not only is this form fully transparent inside the frame, but you can also click through it. However, it might be cool to draw an image onto it and make the form able to be dragged everywhere to create a custom shaped form.
The ConverterParameter
property can not be bound because it is not a dependency property.
Since Binding
is not derived from DependencyObject
none of its properties can be dependency properties. As a consequence, a Binding can never be the target object of another Binding.
There is however an alternative solution. You could use a MultiBinding
with a multi-value converter instead of a normal Binding:
<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
<Setter.Value>
<MultiBinding Converter="{StaticResource AccessLevelToVisibilityConverter}">
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=FindAncestor,
AncestorType=UserControl}"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
The multi-value converter gets an array of source values as input:
public class AccessLevelToVisibilityConverter : IMultiValueConverter
{
public object Convert(
object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.All(v => (v is bool && (bool)v))
? Visibility.Visible
: Visibility.Hidden;
}
public object[] ConvertBack(
object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
Source: from this excellent book
This works for large tables:
CREATE Temporary table duplicates AS select max(id) as id, url from links group by url having count(*) > 1;
DELETE l from links l inner join duplicates ld on ld.id = l.id WHERE ld.id IS NOT NULL;
To delete oldest change max(id)
to min(id)
You can use tomcat plugin with gradle. For more information, you here.
apply plugin: 'tomcat'
dependencies {
classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:1.2.4'
}
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
[tomcatRun, tomcatRunWar, tomcatStop]*.stopPort = 8090
[tomcatRun, tomcatRunWar, tomcatStop]*.stopKey = 'stfu'
tomcatRunWar.contextPath = "/$rootProject.name"
tomcatRunWar.ajpPort = 8000
if (checkBeforeRun.toBoolean()) {
tomcatRunWar { dependsOn += ['check'] }
}
ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
BH's answer of installing Java 6u45 was very close... still got the popup on reboot...BUT after uninstalling Java 6u45, rebooted, no warning! Thank you BH! Then installed the latest version, 8u151-i586, rebooted no warning.
I added lines in PATH as above, didn't do anything.
My system: Windows 7, 64 bit. Warning was for No JVM, 32 bit Java not found. Yes, I could have installed the 64 bit version, but 32bit is more compatible with all programs.
As Collectors.toMap(keyMapper, valueMapper)
uses a throwing merger to handle multiple entries with the same key it is easy:
List<User> users = new LinkedList<>();
users.add(new User(1, "User1"));
users.add(new User(2, "User2"));
users.add(new User(3, "User3"));
int id = 1;
User match = Optional.ofNullable(users.stream()
.filter(user -> user.getId() == id)
.collect(Collectors.toMap(User::getId, Function.identity()))
.get(id)).get();
You will get a IllegalStateException
for duplicate keys. But at the end I am not sure if the code would not be even more readable using an if
.
Ok. So finally I was able to log the post data and return a 200. It's kind of a hacky solution that I'm not too proud of which basically overrides the natural behavior for error_page, but my inexperience of nginx plus timelines lead me to this solution:
location /bk {
if ($request_method != POST) {
return 405;
}
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
proxy_pass $scheme://127.0.0.1:$server_port/success;
log_format my_tracking $request_body;
access_log /mnt/logs/nginx/my_tracking.access.log my_tracking;
}
location /success {
return 200;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /var/www/nginx-default;
log_format my_tracking $request_body;
access_log /mnt/logs/nginx/my_tracking.access.log my_tracking_2;
}
Now according to that config, it would seem that the proxy pass would return a 200 all the time. Occasionally I would get 500 but when I threw in an error_log to see what was going on, all of my request_body data was in there and I couldn't see a problem. So I caught that and wrote to the same log. Since nginx doesn't like the same name for the tracking variable, I just used my_tracking_2 and wrote to the same log as when it returns a 200. Definitely not the most elegant solution and I welcome any better solution. I've seen the post module, but in my scenario, I couldn't recompile from source.
You can build your own contextmanager
to check if the exception was raised.
import contextlib
@contextlib.contextmanager
def raises(exception):
try:
yield
except exception as e:
assert True
else:
assert False
And then you can use raises
like this:
with raises(Exception):
print "Hola" # Calls assert False
with raises(Exception):
raise Exception # Calls assert True
If you are using pytest
, this thing is implemented already. You can do pytest.raises(Exception)
:
Example:
def test_div_zero():
with pytest.raises(ZeroDivisionError):
1/0
And the result:
pigueiras@pigueiras$ py.test
================= test session starts =================
platform linux2 -- Python 2.6.6 -- py-1.4.20 -- pytest-2.5.2 -- /usr/bin/python
collected 1 items
tests/test_div_zero.py:6: test_div_zero PASSED
Another way similar to the yglodt's
In application.properties:
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
And in your configuration class:
@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
return hemf.getSessionFactory();
}
Then you can autowire the SessionFactory in your services as usual:
@Autowired
private SessionFactory sessionFactory;
using Newtonsoft.Json;
Class1 obj1 = new Class1();
Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));
public class Class1
{
public static explicit operator Class2(Class1 obj)
{
return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
}
}
Which then allows you to do something like
Class1 obj1 = new Class1();
Class2 obj2 = (Class2)obj1;
As I've always described it:
A Library is a tool.
A Framework is a way of life.
A library you can use whatever tiny part helps you. A Framework you must commit your entire project to.
I think you need to examine some of the issues you have encountered as a developer where you pulled your hair out after you had to revise your code for the 10th time because of a yet another design change. You probably have a list of projects where you felt that there was a lot of rework and pain.
From that list you can derive the scenarios that the Design Patterns intend to solve. Has there been a time where you needed to perform the same series of actions on different sets of data? Will you need to be able to future capability to an application but want to avoid reworking all your logic for existing classes? Start with those scenarios and return to the catalog of patterns and their respective problems they are supposed to solve. You are likely to see some matches between the GoF and your library of projects.
@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS
<style type="text/css">
#nav-ask{ display:none; }
</style>
or if you already have a "hideMe" CSS Class:
<script type="text/javascript">
if(document.getElementById && document.createTextNode)
{
if(document.getElementById('nav-ask'))
{
document.getElementById('nav-ask').className='hideMe';
}
}
</script>
Update
This is mainly to query the container not to update as building images is the way to be done
I had the same issue so I created docker-run, a very simple command-line tool that runs inside a docker container to update packages in other running containers.
It uses docker-py to communicate with running docker containers and update packages or run any arbitrary single command
Examples:
docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run exec
by default this will run date
command in all running containers and return results but you can issue any command e.g. docker-run exec "uname -a"
To update packages (currently only using apt-get):
docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run update
You can create and alias and use it as a regular command line e.g.
alias docker-run='docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run'
This is a simple way from XML only
spanCount for number of columns
layoutManager for making it grid or linear(Vertical or Horizontal)
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/personListRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Did you try
"
or \x22
instead of
\"
?
It's all in the "magic" syntax of calling a method:
object.property();
When you get the property from the object and call it in one go, the object will be the context for the method. If you call the same method, but in separate steps, the context is the global scope (window) instead:
var f = object.property;
f();
When you get the reference of a method, it's no longer attached to the object, it's just a reference to a plain function. The same happens when you get the reference to use as a callback:
this.saveNextLevelData(this.setAll);
That's where you would bind the context to the function:
this.saveNextLevelData(this.setAll.bind(this));
If you are using jQuery you should use the $.proxy
method instead, as bind
is not supported in all browsers:
this.saveNextLevelData($.proxy(this.setAll, this));
Set Jquery in scope
$scope.$ = $;
and call in html
ng-click="$('#novoModelo').modal('show')"
With Cinchoo ETL - an open source library, you can easily convert CSV file to DataTable with few lines of code.
using (var p = new ChoCSVReader(** YOUR CSV FILE **)
.WithFirstLineHeader()
)
{
var dt = p.AsDataTable();
}
For more information, please visit codeproject article.
Hope it helps.
Remove numbering on x-axis or y-axis:
plot(1:10, xaxt='n')
plot(1:10, yaxt='n')
If you want to remove the labels as well:
plot(1:10, xaxt='n', ann=FALSE)
plot(1:10, yaxt='n', ann=FALSE)
try picasso
nice and finishes in one statement
Picasso.with(context)
.load(ImageURL)
.resize(width,height).into(imageView);
tutorial: https://youtu.be/DxRqxsEPc2s
(note: Picasso.with()
has been renamed to Picasso.get()
in the latest release)