run this command
mvn -U clean install
In interface Builder set table view separator "None"
and those separator lines which are shown after the last cell can be remove by following approach. Best approach is to assign Empty View to tableView FooterView in viewDidLoad
self.tableView.tableFooterView = UIView()
Html.Raw()
returns IHtmlString
, not the ordinary string
. So, you cannot write them in opposite sides of :
operator. Remove that .ToString()
calling
@{int count = 0;}
@foreach (var item in Model.Resources)
{
@(count <= 3 ? Html.Raw("<div class=\"resource-row\">"): Html.Raw(""))
// some code
@(count <= 3 ? Html.Raw("</div>") : Html.Raw(""))
@(count++)
}
By the way, returning IHtmlString
is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString()
would destroy meaning of Html.Raw()
Did you try the substring
function?
string = string.indexOf(0) == '0' ? string.substring(1) : string;
Here's a reference - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring
And you can always do this for multiple 0s:
while(string.indexOf(0) == '0')
{
string = string.substring(1);
}
For the asynchronous dispatch case you describe above, you shouldn't need to check if you're on the main thread. As Bavarious indicates, this will simply be queued up to be run on the main thread.
However, if you attempt to do the above using a dispatch_sync()
and your callback is on the main thread, your application will deadlock at that point. I describe this in my answer here, because this behavior surprised me when moving some code from -performSelectorOnMainThread:
. As I mention there, I created a helper function:
void runOnMainQueueWithoutDeadlocking(void (^block)(void))
{
if ([NSThread isMainThread])
{
block();
}
else
{
dispatch_sync(dispatch_get_main_queue(), block);
}
}
which will run a block synchronously on the main thread if the method you're in isn't currently on the main thread, and just executes the block inline if it is. You can employ syntax like the following to use this:
runOnMainQueueWithoutDeadlocking(^{
//Do stuff
});
You don't need to use echo or grep. You could do this:
ping -oc 100000 8.8.8.8 > /dev/null && say "up" || say "down"
There is also a function in pandas
called factorize
which you can use to automatically do this type of work. It converts labels to numbers: ['male', 'female', 'male'] -> [0, 1, 0]
. See this answer for more information.
Just a note here that you may actually be better off having 3 separate SELECTS for reasons of optimization. If you have one single SELECT then the generated plan will have to project all columns col1, col2, col3, col7, col8 etc, although, depending on the value of the runtime @var, only some are needed. This may result in plans that do unnecessary clustered index lookups because the non-clustered index Doesn't cover all columns projected by the SELECT.
On the other hand 3 separate SELECTS, each projecting the needed columns only may benefit from non-clustered indexes that cover just your projected column in each case.
Of course this depends on the actual schema of your data model and the exact queries, but this is just a heads up so you don't bring the imperative thinking mind frame of procedural programming to the declarative world of SQL.
I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".
It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.
Share a Controller
Two directives can use the same controller by passing the same method to two directives, like so:
app.controller( 'MyCtrl', function ( $scope ) {
// do stuff...
});
app.directive( 'directiveOne', function () {
return {
controller: 'MyCtrl'
};
});
app.directive( 'directiveTwo', function () {
return {
controller: 'MyCtrl'
};
});
Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.
Require a Controller
If you want to share the same instance of a controller, then you use require
.
require
ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel
.
^require
, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.
In either event, you have to use the two directives together for this to work. require
is a way of communicating between components.
Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive
Thank you. I believe that a complete example could be good for anyone else who have the same issue:
import pandas as pd
import numpy as np
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)
x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
df1.to_excel(writer, sheet_name = 'x1')
df2.to_excel(writer, sheet_name = 'x2')
writer.save()
writer.close()
Here I generate an excel file, from my understanding it does not really matter whether it is generated via the "xslxwriter" or the "openpyxl" engine.
When I want to write without loosing the original data then
import pandas as pd
import numpy as np
from openpyxl import load_workbook
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)
x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)
df3.to_excel(writer, sheet_name = 'x3')
df4.to_excel(writer, sheet_name = 'x4')
writer.save()
writer.close()
this code do the job!
I know this question is quite old, but I have not seen this solution here before:
If you rewrite the <body>
tag to.
<body oncontextmenu="return false;">
you can prevent the right click without using javascript.
However, you can't prevent keyboard shortcuts with HTML. For this, you must use Javascript.
I was so confusing first time, but I propose you final working solution for Windows:
1) Open cmd and go to your Java/jdk/bin directory (just press cd ..
to go one folder back and cd NAME_FOLDER
to go one folder forward), in my case, final folder: C:\Program Files\Java\jdk1.8.0_73\bin>
2) Now type this command keytool -list -v -keystore C:\Users\YOUR_WINDOWS_USER\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android
This should work properly this is just an improvement of previous answers.
DECLARE @Counter INT
DECLARE @Counter1 INT
SET @Counter = 0
SET @Counter1 = 0
DECLARE @TotalPrints INT
SET @TotalPrints = (LEN(@QUERY) / 4000) + 1
print @TotalPrints
WHILE @Counter < @TotalPrints
BEGIN
-- Do your printing...
print(substring(@query,@COUNTER1,@COUNTER1+4000))
set @COUNTER1 = @Counter1+4000
SET @Counter = @Counter + 1
END
As all html ids are unique in a valid html document why not search for the ID directly? If you're concerned if they type in an id that isn't a table then you can inspect the tag type that way?
Just an idea!
S
Because the change
event requires an actual browser event initiated by the user instead of via javascript code.
Do this instead:
$("#single").val("Single2").trigger('change');
or
$("#single").val("Single2").change();
The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
That is all the language has to say, as far as C++03 is concerned.
For something simple, you can combine ls with sort. For just a list of file names:
ls -1 | sort
To sort them in reverse order:
ls -1 | sort -r
you can try this way:
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.fragment_container);
or
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
In this if, you check if currentFragment is instance of YourFragment
if (currentFragment instanceof YourFragment) {
Log.v(TAG, "your Fragment is Visible");
}
Database is like container of data with schema, and schemas is layout of the tables there data types, relations and stuff
int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";
hope this help! :)
Here's a nice simple solution i use for smaller files:
NSString *path = [[NSBundle mainBundle] pathForResource:@"Terrain1" ofType:@"txt"];
NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];
NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\r\n"]];
for (NSString* line in lines) {
if (line.length) {
NSLog(@"line: %@", line);
}
}
I accidentally ended up writing almost the same as provided by git-extras. So if you prefer a single custom command instead of installing a bunch of other extra commands, just place this git-pr
file somewhere in your $PATH
and then you can just write:
git pr 42
// or
git pr upstream 42
// or
git pr https://github.com/peerigon/phridge/pull/1
No, you don't need to know any math (except maybe binary/oct/hex/dec representations) for system programming and stuff like that.
I use below sql to exclude the null string and empty string lines.
select * from table where length(nvl(column1,0))>0
Because, the length of empty string is 0.
select length('');
+-----------+--+
| length() |
+-----------+--+
| 0 |
+-----------+--+
Just add a new form and add buttons and a label. Give the value to be shown and the text of the button, etc. in its constructor, and call it from anywhere you want in the project.
In project -> Add Component -> Windows Form and select a form
Add some label and buttons.
Initialize the value in constructor and call it from anywhere.
public class form1:System.Windows.Forms.Form
{
public form1()
{
}
public form1(string message,string buttonText1,string buttonText2)
{
lblMessage.Text = message;
button1.Text = buttonText1;
button2.Text = buttonText2;
}
}
// Write code for button1 and button2 's click event in order to call
// from any where in your current project.
// Calling
Form1 frm = new Form1("message to show", "buttontext1", "buttontext2");
frm.ShowDialog();
A problem with not putting 'return' explicitly at the end is that if one adds additional statements at the end of the method, suddenly the return value is wrong:
foo <- function() {
dosomething()
}
This returns the value of dosomething()
.
Now we come along the next day and add a new line:
foo <- function() {
dosomething()
dosomething2()
}
We wanted our code to return the value of dosomething()
, but instead it no longer does.
With an explicit return, this becomes really obvious:
foo <- function() {
return( dosomething() )
dosomething2()
}
We can see that there is something strange about this code, and fix it:
foo <- function() {
dosomething2()
return( dosomething() )
}
There are also options available in the form of various libraries that can make this process very familiar to people that have used other MVVM frameworks.
https://developer.android.com/topic/libraries/data-binding/
Shows an example of an official library, that allows you to bind buttons like this:
<Button
android:text="Start second activity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@{() -> presenter.showList()}"
/>
An iterative function to free your list:
void freeList(struct node* head)
{
struct node* tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
What the function is doing is the follow:
check if head
is NULL, if yes the list is empty and we just return
Save the head
in a tmp
variable, and make head
point to the next node on your list (this is done in head = head->next
free(tmp)
variable, and head
just points to the rest of the list, go back to step 1 You want the first >
not preceded by a /
. Look here for details on how to do that. It's referred to as negative lookbehind.
However, a naïve implementation of that will end up matching <bar/></foo>
in this example document
<foo><bar/></foo>
Can you provide a little more information on the problem you're trying to solve? Are you iterating through tags programatically?
Shortcut Alt+Enter shows intention actions where you can choose "Add Javadoc".
I see this, although an old question, is a pretty good place to plug my own script:
http://code.google.com/p/js-scroll-table-header/
It just works with no configuration and is really easy to setup.
It looks like you have a typo on your array, it should read:
int my_array[3][3] = {...
You don't have the _
or the {
.
Also my_array[3][3]
is an invalid location. Since computers begin counting at 0
, you are accessing position 4
. (Arrays are weird like that).
If you want just the last element:
printf("%d\n", my_array[2][2]);
If you want the entire array:
for(int i = 0; i < my_array.length; i++) {
for(int j = 0; j < my_array[i].length; j++)
printf("%d ", my_array[i][j]);
printf("\n");
}
While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding
(or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:
sys.stdout.buffer.write(some_bytes_object)
This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.
this is best way to find out last inserted id.
$this->ModelName->getInsertID();
other way is using
$this->ModelName->find('first',array('order'=>'id DESC'))
If you are using lodash, it could be as simple as this:
var arr = _.values(obj);
The previous answers contain a lot of information, but I think there is a philosophical difference that hasn't been pointed out. SOAP was the answer to "how to we create a modern, object-oriented, platform and protocol independent successor to RPC?". REST developed from the question, "how to we take the insights that made HTTP so successful for the web, and use them for distributed computing?"
SOAP is a about giving you tools to make distributed programming look like ... programming. REST tries to impose a style to simplify distributed interfaces, so that distributed resources can refer to each other like distributed html pages can refer to each other. One way it does that is attempt to (mostly) restrict operations to "CRUD" on resources (create, read, update, delete).
REST is still young -- although it is oriented towards "human readable" services, it doesn't rule out introspection services, etc. or automatic creation of proxies. However, these have not been standardized (as I write). SOAP gives you these things, but (IMHO) gives you "only" these things, whereas the style imposed by REST is already encouraging the spread of web services because of its simplicity. I would myself encourage newbie service providers to choose REST unless there are specific SOAP-provided features they need to use.
In my opinion, then, if you are implementing a "greenfield" API, and don't know that much about possible clients, I would choose REST as the style it encourages tends to help make interfaces comprehensible, and easy to develop to. If you know a lot about client and server, and there are specific SOAP tools that will make life easy for both, then I wouldn't be religious about REST, though.
Use CURRENT_TIMESTAMP (or GETDATE() on archaic versions of SQL Server).
Yes, the time complexity of this is O(n^2).
You may consider declaring the variables with moudule level scope. Module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules
For details on Scope of variables
refer this link
Please copy the below code into any module, save the workbook and then run the code.
Here is what code does
The sample subroutine sets the folder path & later the file path. Kindly set them accordingly before you run the code.
I have added a function IsWorkBookOpen to check if workbook is already then set the workbook variable the workbook name else open the workbook which will be assigned to workbook variable accordingly.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
folderPath = ThisWorkbook.Path & "\"
fileNm1 = "file1.xlsx"
fileNm2 = "file2.xlsx"
filePath1 = folderPath & fileNm1
filePath2 = folderPath & fileNm2
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Using Prompt to select the file use below code.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
Dim filePath As String
cmdBrowse_Click filePath, 1
filePath1 = filePath
'reset the variable
filePath = vbNullString
cmdBrowse_Click filePath, 2
filePath2 = filePath
fileNm1 = GetFileName(filePath1, "\")
fileNm2 = GetFileName(filePath2, "\")
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Private Sub cmdBrowse_Click(ByRef filePath As String, num As Integer)
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select workbook " & num
fd.InitialView = msoFileDialogViewSmallIcons
Dim FileChosen As Integer
FileChosen = fd.Show
fd.Filters.Clear
fd.Filters.Add "Excel macros", "*.xlsx"
fd.FilterIndex = 1
If FileChosen <> -1 Then
MsgBox "You chose cancel"
filePath = ""
Else
filePath = fd.SelectedItems(1)
End If
End Sub
Function GetFileName(fullName As String, pathSeparator As String) As String
Dim i As Integer
Dim iFNLenght As Integer
iFNLenght = Len(fullName)
For i = iFNLenght To 1 Step -1
If Mid(fullName, i, 1) = pathSeparator Then Exit For
Next
GetFileName = Right(fullName, iFNLenght - i)
End Function
One option, as explained in another answer, is to use pack_forget
or grid_forget
. Another option is to use lift
and lower
. This changes the stacking order of widgets. The net effect is that you can hide widgets behind sibling widgets (or descendants of siblings). When you want them to be visible you lift
them, and when you want them to be invisible you lower
them.
The advantage (or disadvantage...) is that they still take up space in their master. If you "forget" a widget, the other widgets might readjust their size or orientation, but if you raise or lower them they will not.
Here is a simple example:
import Tkinter as tk
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.frame = tk.Frame(self)
self.frame.pack(side="top", fill="both", expand=True)
self.label = tk.Label(self, text="Hello, world")
button1 = tk.Button(self, text="Click to hide label",
command=self.hide_label)
button2 = tk.Button(self, text="Click to show label",
command=self.show_label)
self.label.pack(in_=self.frame)
button1.pack(in_=self.frame)
button2.pack(in_=self.frame)
def show_label(self, event=None):
self.label.lift(self.frame)
def hide_label(self, event=None):
self.label.lower(self.frame)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:
public function foo(Request $request){
$bodyContent = $request->getContent();
}
Use .on('input'...
to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.
For static and dynamic inputs:
$(document).on('input', '.my-class', function(){
alert('Input changed');
});
For static inputs only:
$('.my-class').on('input', function(){
alert('Input changed');
});
JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/
en api level 14
marker.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.miubicacion, null));
You can use the -Dmaven.wagon.http.ssl.insecure=true
option
Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.
$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0
git-status
on the parent repository will now report a dirty tree:
# On branch dev [...]
#
# modified: submodule (new commits)
Add the submodule directory and commit to store the new pointer.
Just put a space between .area1 and .item, e.g:
.area1 .item
{
color:red;
}
this style applies to elements with class item inside an element with class area1.
You may be looking for the n key.
You will get it by tag type="date"...then it will render beautiful calendar and all...
@Html.TextBoxFor(model => model.EndTime, new { type = "date" })
You can set aliases for the columns that you are selecting:
$query = 'SELECT news.id AS newsId, user.id AS userId, [OTHER FIELDS HERE] FROM news JOIN users ON news.user = user.id'
In my case I forgot to put double curly brace to escape. {{myobject}}
A way to solve this without having to rely on URLs is to add a custom attribute to every partial during $routeProvider
configuration, like this:
$routeProvider.
when('/dashboard', {
templateUrl: 'partials/dashboard.html',
controller: widgetsController,
activetab: 'dashboard'
}).
when('/lab', {
templateUrl: 'partials/lab.html',
controller: widgetsController,
activetab: 'lab'
});
Expose $route
in your controller:
function widgetsController($scope, $route) {
$scope.$route = $route;
}
Set the active
class based on the current active tab:
<li ng-class="{active: $route.current.activetab == 'dashboard'}"></li>
<li ng-class="{active: $route.current.activetab == 'lab'}"></li>
Try the change event and selected selector
$('#jobSel').change(function(){
var optId = $(this).find('option:selected').attr('id')
})
If you didnt know that mojb
is of type MyClass
, then how can you create that variable?
If MyClass is an interface type, or a super type, then there is no need to do a cast.
This is what I use:
function TrimTrailingZeroes($nbr) {
return strpos($nbr,'.')!==false ? rtrim(rtrim($nbr,'0'),'.') : $nbr;
}
N.B. This assumes .
is the decimal separator. It has the advantage that it will work on arbitrarily large (or small) numbers since there is no float cast. It also won't turn numbers into scientific notation (e.g. 1.0E-17).
try this out :)
public static HashMap HashMapFrom(String s){
HashMap base = new HashMap(); //result
int dismiss = 0; //dismiss tracker
StringBuilder tmpVal = new StringBuilder(); //each val holder
StringBuilder tmpKey = new StringBuilder(); //each key holder
for (String next:s.split("")){ //each of vale
if(dismiss==0){ //if not writing value
if (next.equals("=")) //start writing value
dismiss=1; //update tracker
else
tmpKey.append(next); //writing key
} else {
if (next.equals("{")) //if it's value so need to dismiss
dismiss++;
else if (next.equals("}")) //value closed so need to focus
dismiss--;
else if (next.equals(",") //declaration ends
&& dismiss==1) {
//by the way you have to create something to correct the type
Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
base.put(tmpKey.toString(),ObjVal);//declaring
tmpKey = new StringBuilder();
tmpVal = new StringBuilder();
dismiss--;
continue; //next :)
}
tmpVal.append(next); //writing value
}
}
Object objVal = object.valueOf(tmpVal.toString()); //same as here
base.put(tmpKey.toString(), objVal); //leftovers
return base;
}
examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}
I solved this problem pretty elegantly using Package Level Annotations and then making that annotation have as an argument a list of classes.
Find Java classes implementing an interface
Implementations just have to create a package-info.java and put the magic annotation in with the list of classes they want to support.
The proper way is to do a Time.now.getutc.to_i
to get the proper timestamp amount as simply displaying the integer need not always be same as the utc timestamp due to time zone differences.
"AbCd".toLowerCase().contains("abcD".toLowerCase())
TL;DR Just use Lombok's @SneakyThrows
.
Christian Hujer has already explained in detail why throwing checked exceptions from a stream is, strictly speaking, not possible due to Java's limitations.
Some other answers have explained tricks to get around the limitations of the language but still being able to fulfil the requirement of throwing "the checked exception itself, and without adding ugly try/catches to the stream", some of them requiring tens of additional lines of boilerplate.
I am going to highlight another option for doing this that IMHO is far cleaner than all the others: Lombok's @SneakyThrows
. It has been mentioned in passing by other answers but was a bit buried under a lot of unnecessary detail.
The resulting code is as simple as:
public List<Class> getClasses() throws ClassNotFoundException {
List<Class> classes =
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(className -> getClass(className))
.collect(Collectors.toList());
return classes;
}
@SneakyThrows // <= this is the only new code
private Class<?> getClass(String className) {
return Class.forName(className);
}
We just needed one Extract Method
refactoring (done by the IDE) and one additional line for @SneakyThrows
. The annotation takes care of adding all the boilerplate to make sure that you can throw your checked exception without wrapping it in a RuntimeException
and without needing to declare it explicitly.
I can't believe how complex everyone is making this. This is actually very simple. Just paste this into your html (no directive./controller changes required - "bg-info" is a bootstrap class):
<div class="form-group col-md-12">
<div ng-class="{'bg-info': (!transport_type)}" ng-click="transport_type=false">CARS</div>
<div ng-class="{'bg-info': transport_type=='TRAINS'}" ng-click="transport_type='TRAINS'">TRAINS</div>
<div ng-class="{'bg-info': transport_type=='PLANES'}" ng-click="transport_type='PLANES'">PLANES</div>
</div>
Most of the answers here are using inbuilt functions-
Here is my answer if you want to know the whole logic behind this ques:
import java.util.*;
public class SumOfArray {
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
int n = inp.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = inp.nextInt();
}
System.out.println("The sum of the array is :" + sum(arr));
}
static int sum(int[] arr){
int sum = 0;
for (int a = 0; a < arr.length; a++){
sum = sum + arr[a];
}
return sum;
}
}
According to the grammar in the CSP spec, you need to specify schemes as scheme:
, not just scheme
. So, you need to change the image source directive to:
img-src 'self' data:;
Walkthrough: Using Multiple Programming Languages in a Web Site Project http://msdn.microsoft.com/en-us/library/ms366714.aspx
By default, the App_Code folder does not allow multiple programming languages. However, in a Web site project you can modify your folder structure and configuration settings to support multiple programming languages such as Visual Basic and C#. This allows ASP.NET to create multiple assemblies, one for each language. For more information, see Shared Code Folders in ASP.NET Web Projects. Developers commonly include multiple programming languages in Web applications to support multiple development teams that operate independently and prefer different programming languages.
First, Mv = numpy.asarray(M.T)
, which gives you a 4x1 but 2D array.
Then, perform A = Mv[0,:]
, which gives you what you want. You could put them together, as numpy.asarray(M.T)[0,:]
.
solution that worked for me is to change user under which Application Pool is started (ApplicationPoolIdentity obviously has not enough rights to access COM object).
Good luck!
netstat -ano | findstr :3010
taskkill /F /PID
But it won't work for me
then I tried taskkill -PID <processorid> -F
Example:- taskkill -PID 33192 -F
Here 33192 is the processorid and it works
UPDATE financialyear
SET firstsemfrom = dt2.firstsemfrom,
firstsemto = dt2.firstsemto,
secondsemfrom = dt2.secondsemfrom,
secondsemto = dt2.secondsemto
from financialyear dt2
WHERE financialyear.financialyearkey = 141
AND dt2.financialyearkey = 140
I did some development with Mifare Classic (ISO 14443A) cards about 7-8 years ago. You can read and write to all sectors of the card, IIRC the only data you can't change is the serial number. Back then we used a proprietary library from Philips Semiconductors. The command interface to the card was quite alike the ISO 7816-4 (used with standard Smart Cards).
I'd recomment that you look at the OpenPCD platform if you are into development.
This is also of interest regarding the cryptographic functions in some RFID cards.
use it like "whatsapp://send?text=" + encodeURIComponent(your text goes here), it will definitely work.
DispatchQueue.global(qos: .background).async {
sleep(4)
print("Active after 4 sec, and doesn't block main")
DispatchQueue.main.async{
//do stuff in the main thread here
}
}
I recorded a macro making a hiperlink. This resulted.
ActiveCell.FormulaR1C1 = "=HYPERLINK(""[Workbook.xlsx]Sheet1!A1"",""CLICK HERE"")"
The reason is your result
assigned to the returning Task
which represents continuation of your method, and you have a different Task in your method which is running, if you directly assign Task like this you will get your expected results:
var task = Task.Run(() =>
{
for (int i = 10; i < 432543543; i++)
{
// just for a long job
double d3 = Math.Sqrt((Math.Pow(i, 5) - Math.Pow(i, 2)) / Math.Sin(i * 8));
}
return "Foo Completed.";
});
while (task.Status != TaskStatus.RanToCompletion)
{
Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId,task.Status);
}
Console.WriteLine("Result: {0}", task.Result);
Console.WriteLine("Finished.");
Console.ReadKey(true);
The output
:
Consider this for better explanation: You have a Foo
method,let's say it Task A, and you have a Task
in it,let's say it Task B, Now the running task, is Task B, your Task A awaiting for Task B result.And you assing your result variable to your returning Task
which is Task A, because Task B doesn't return a Task, it returns a string
. Consider this:
If you define your result like this:
Task result = Foo(5);
You won't get any error.But if you define it like this:
string result = Foo(5);
You will get:
Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'string'
But if you add an await
keyword:
string result = await Foo(5);
Again you won't get any error.Because it will wait the result (string) and assign it to your result variable.So for the last thing consider this, if you add two task into your Foo Method:
private static async Task<string> Foo(int seconds)
{
await Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
// in here don't return anything
});
return await Task.Run(() =>
{
for (int i = 0; i < seconds; i++)
{
Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
Task.Delay(TimeSpan.FromSeconds(1)).Wait();
}
return "Foo Completed.";
});
}
And if you run the application, you will get the same results.(WaitingForActivation) Because now, your Task A is waiting those two tasks.
Here is my solution, without overdoing it.
private static string AppendAtPosition(string baseString, int position, string character)
{
var sb = new StringBuilder(baseString);
for (int i = position; i < sb.Length; i += (position + character.Length))
sb.Insert(i, character);
return sb.ToString();
}
Console.WriteLine(AppendAtPosition("abcdefghijklmnopqrstuvwxyz", 5, "-"));
In SQL Management Studio you can:
Right click on the result set grid, select 'Save Result As...' and save in.
On a tool bar toggle 'Result to Text' button. This will prompt for file name on each query run.
If you need to automate it, use bcp tool.
I think tir38's answer is the cleanest solution. Have in mind that if you are using android.app.AlerDialog and holo themes your style should look like this
<style name="WrapEverythingDialog" parent=[holo theme ex. android:Theme.Holo.Dialog]>
<item name="windowMinWidthMajor">0dp</item>
<item name="windowMinWidthMinor">0dp</item>
</style>
And if using support.v7.app.AlertDialog or androidx.appcompat.app.AlertDialog with AppCompat theme your style should look like this
<style name="WrapEverythingDialog" parent=[Appcompat theme ex. Theme.AppCompat.Light.Dialog.Alert]>
<item name="android:windowMinWidthMajor">0dp</item>
<item name="android:windowMinWidthMinor">0dp</item>
</style>
You could use <jsp:include>
for this.
<jsp:include page="/servletURL" />
It's however usually the other way round. You call the servlet which in turn forwards to the JSP to display the results. Create a Servlet which does something like following in doGet()
method.
request.setAttribute("result", "This is the result of the servlet call");
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);
and in /WEB-INF/result.jsp
<p>The result is ${result}</p>
Now call the Servlet by the URL which matches its <url-pattern>
in web.xml
, e.g. http://example.com/contextname/servletURL.
Do note that the JSP file is explicitly placed in /WEB-INF
folder. This will prevent the user from opening the JSP file individually. The user can only call the servlet in order to open the JSP file.
If your actual question is "How to submit a form to a servlet?" then you just have to specify the servlet URL in the HTML form action
.
<form action="servletURL" method="post">
Its doPost()
method will then be called.
TreeSet
is ordered.
http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html
change the default node version with nvm alias default 10.15.3
*
(replace mine version with your default version number)
you can check your default lists with nvm list
To help understand what do $#
, $0
and $1
, ..., $n
do, I use this script:
#!/bin/bash
for ((i=0; i<=$#; i++)); do
echo "parameter $i --> ${!i}"
done
Running it returns a representative output:
$ ./myparams.sh "hello" "how are you" "i am fine"
parameter 0 --> myparams.sh
parameter 1 --> hello
parameter 2 --> how are you
parameter 3 --> i am fine
execfile
runs a Python file, but by loading it, not as a script. You can only pass in variable bindings, not arguments.
If you want to run a program from within Python, use subprocess.call
. E.g.
import subprocess
subprocess.call(['./abc.py', arg1, arg2])
An other solution (with the assumption you know your date formats are always YYYY/MM/DD with lead zeros) is the max() and min() function. I figure this is okay given all the other answers assume the yyyy-mm-dd format too and it's the common naming convention for folders in file systems if ever you wanted to make sure they sorted in date order.
As others have said, given the order of the numbers you can compare the strings, no need for strtotime() function.
Examples:
$biggest = max("2018/10/01","2018/10/02");
The advantage being you can stick more dates in there instead of just comparing two.
$biggest = max("2018/04/10","2019/12/02","2016/03/20");
To work out if a date is in between two dates you could compare the result of min() and max()
$startDate="2018/04/10";
$endDate="2018/07/24";
$check="2018/05/03";
if(max($startDate,$check)==min($endDate,$check)){
// It's in the middle
}
It wouldn't work with any other date format, but for that one it does. No need to convert to seconds and no need for date functions.
Personally, I usually go with:
select *
from t1
where date between trunc( :somedate ) -- 00:00:00
and trunc( :somedate ) + .99999 -- 23:59:59
In Java, all public (non-private) variables & functions are Virtual by default. Moreover variables & functions using keyword final are not virtual.
The easiest way I found, summarized in a few pictures:
You could skip a few steps (up to step 4) by simply navigating to chrome://settings/languages
right away.
I read many (most?) of the responses, then developed a bat file that works for me in Win 8.1. Thought I'd share it.
setlocal
set runState=user
whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" > nul && set runState=admin
whoami /groups | findstr /b /c:"Mandatory Label\System Mandatory Level" > nul && set runState=system
echo Running in state: "%runState%"
if not "%runState%"=="user" goto notUser
echo Do user stuff...
goto end
:notUser
if not "%runState%"=="admin" goto notAdmin
echo Do admin stuff...
goto end
:notAdmin
if not "%runState%"=="system" goto notSystem
echo Do admin stuff...
goto end
:notSystem
echo Do common stuff...
:end
Hope someone finds this useful :)
I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20
The support library android-support-v4.jar
is causing this conflict, just delete the library under /libs
folder of your project, don´t be scared, the library is already contained in the library appcompat_v7
, clean and build your project, and your project will work like a charm!
This issue can also raise when you change your system password but not the same updated on your .npmrc file that exist on path C:\Users\user_name, so update your password there too.
please check on it and run npm install first and then npm start.
Be careful, -
has a special meaning with regexp. In a []
, you can put it without problem if it is placed at the end. In your case, ,-:
is taken as from ,
to :
.
Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)
I just removed the head portion in index.html file and it worked fine.This is the head tag in html file
#include <sstream>
// st is input string
int result;
stringstream(st) >> result;
The operation you defined is a "merge" and you cannot do that with cp
. However, if you are not looking for merging and ok to lose the folder bar
then you can simply rm -rf bar
to delete the folder and then mv foo bar
to rename it. This will not take any time as both operations are done by file pointers, not file contents.
The above were really close. Here's my solution:
Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
Dim i As Integer
outClone = inClone.Clone
Dim dv As DataView = inClone.Tables(0).DefaultView
dv.RowFilter = matchStr
Dim dt As New DataTable
dt = dv.ToTable
For i = 0 To dv.Count - 1
outClone.Tables(0).ImportRow(dv.Item(i).Row)
Next
End Sub
Using list comprehension in python and basic map function utility, one can do this also:
chi = [x for x in map(chr,[66,53,0,94])]
I answered my problem with a default width for all columns and cells, like below:
int width = 15; // Where width is number of caracters
sheet.setDefaultColumnWidth(width);
I wrote a batch script a while ago that allows you to pick a file extension to delete. The script will look in the folder it is in and all subfolders for any file with that extension and delete it.
@ECHO OFF
CLS
SET found=0
ECHO Enter the file extension you want to delete...
SET /p ext="> "
IF EXIST *.%ext% ( rem Check if there are any in the current folder :)
DEL *.%ext%
SET found=1
)
FOR /D /R %%G IN ("*") DO ( rem Iterate through all subfolders
IF EXIST %%G CD %%G
IF EXIST *.%ext% (
DEL *.%ext%
SET found=1
)
)
IF %found%==1 (
ECHO.
ECHO Deleted all .%ext% files.
ECHO.
) ELSE (
ECHO.
ECHO There were no .%ext% files.
ECHO Nothing has been deleted.
ECHO.
)
PAUSE
EXIT
Hope this comes in useful to anyone who wants it :)
I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.
public class ReturnData
{
public int totalCount { get; set; }
public List<ExceptionReport> reports { get; set; }
}
public class ExceptionReport
{
public int reportId { get; set; }
public string message { get; set; }
}
string json = JsonConvert.SerializeObject(myReturnData);
Also I tried other solution, but some of the code executed after redirect.
public static void ResponseRedirect(HttpResponse iResponse, string iUrl)
{
ResponseRedirect(iResponse, iUrl, HttpContext.Current);
}
public static void ResponseRedirect(HttpResponse iResponse, string iUrl, HttpContext iContext)
{
iResponse.Redirect(iUrl, false);
iContext.ApplicationInstance.CompleteRequest();
iResponse.BufferOutput = true;
iResponse.Flush();
iResponse.Close();
}
So if need to prevent code execution after redirect
try
{
//other code
Response.Redirect("")
// code not to be executed
}
catch(ThreadAbortException){}//do there id nothing here
catch(Exception ex)
{
//Logging
}
use below code , change proper database name and user name and then take that output and execute in SSMS. FOR SQL 2005 ABOVE
USE <database_name>
select 'GRANT EXECUTE ON ['+name+'] TO [userName] '
from sys.objects
where type ='P'
and is_ms_shipped = 0
Even array2.extend(array1)
will work.
Or try http://twitterbootstrapbuttons.w3masters.nl/. It creates css for buttons based on html color input. Add the css after the bootstrap css. It provides three styles of buttons (light, dark and spin).
When changing element's display
in Javascript, in many cases a suitable option to 'undo' the result of element.style.display = "none"
is element.style.display = ""
. This removes the display
declaration from the style
attribute, reverting the actual value of display
property to the value set in the stylesheet for the document (to the browser default if not redefined elsewhere). But the more reliable approach is to have a class in CSS like
.invisible { display: none; }
and adding/removing this class name to/from element.className
.
Thi is your code :
Driver.findElement(By.xpath(//a[@href ='/docs/configuration']")).click();
You missed the Quotation mark
it should be as below
Driver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();
Hope this helps!
You can use this format as of 4/6/2017.
https://docs.google.com/viewerng/viewer?url=http://yourfile.pdf
Just replace http://yourfile.pdf with the link you use.
As of February 2019, the solution given by @sylvain (at least on my setup) does not work without a small modification: xObject[obj]['/Filter']
is not a value, but a list, thus in order to make the script work, I had to modify the format checking as follows:
import PyPDF2, traceback
from PIL import Image
input1 = PyPDF2.PdfFileReader(open(src, "rb"))
nPages = input1.getNumPages()
print nPages
for i in range(nPages) :
print i
page0 = input1.getPage(i)
try :
xObject = page0['/Resources']['/XObject'].getObject()
except : xObject = []
for obj in xObject:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj].getData()
try :
if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
mode = "RGB"
elif xObject[obj]['/ColorSpace'] == '/DeviceCMYK':
mode = "CMYK"
# will cause errors when saving
else:
mode = "P"
fn = 'p%03d-%s' % (i + 1, obj[1:])
print '\t', fn
if '/FlateDecode' in xObject[obj]['/Filter'] :
img = Image.frombytes(mode, size, data)
img.save(fn + ".png")
elif '/DCTDecode' in xObject[obj]['/Filter']:
img = open(fn + ".jpg", "wb")
img.write(data)
img.close()
elif '/JPXDecode' in xObject[obj]['/Filter'] :
img = open(fn + ".jp2", "wb")
img.write(data)
img.close()
elif '/LZWDecode' in xObject[obj]['/Filter'] :
img = open(fn + ".tif", "wb")
img.write(data)
img.close()
else :
print 'Unknown format:', xObject[obj]['/Filter']
except :
traceback.print_exc()
I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.
I'm omitting the com port settings here:
>>>import serial
>>>ser = serial.Serial(5)
>>>ser.close()
>>>ser.open()
>>>ser.write("1".encode())
1
>>>
I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java):
mention permissions in Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
e.g.
File file=new File(path);
long=file.length();//in Bytes
In case you still need it, have you tried to set the property
self.tableView.tableHeaderView
If you calculate the heigh you need, and set a new view for tableHeaderView
:
CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = newHeight;
self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:frame];
It should work.
It is not entirely clear what your question is, but if you just want to eliminate the double click, while retaining the hover effect for the mouse, my advice is to:
touchstart
and mouseenter
.mouseleave
, touchmove
and click
.In order to simulate a mouse, browsers such as Webkit mobile fire the following events if a user touches and releases a finger on touch screen (like iPad) (source: Touch And Mouse on html5rocks.com):
touchstart
touchmove
touchend
mouseover
mouseenter
mouseover
, mouseenter
or mousemove
event changes the page content, the following events are never fired.mousemove
mousedown
mouseup
click
It does not seem possible to simply tell the webbrowser to skip the mouse events.
What's worse, if a mouseover event changes the page content, the click event is never fired, as explained on Safari Web Content Guide - Handling Events, in particular figure 6.4 in One-Finger Events. What exactly a "content change" is, will depend on browser and version. I've found that for iOS 7.0, a change in background color is not (or no longer?) a content change.
To recap:
touchstart
and mouseenter
.mouseleave
, touchmove
and click
.Note that there is no action on touchend
!
This clearly works for mouse events: mouseenter
and mouseleave
(slightly improved versions of mouseover
and mouseout
) are fired, and add and remove the hover.
If the user actually click
s a link, the hover effect is also removed. This ensure that it is removed if the user presses the back button in the web browser.
This also works for touch events: on touchstart
the hover effect is added. It is '''not''' removed on touchend
. It is added again on mouseenter
, and since this causes no content changes (it was already added), the click
event is also fired, and the link is followed without the need for the user to click again!
The 300ms delay that a browser has between a touchstart
event and click
is actually put in good use because the hover effect will be shown during this short time.
If the user decides to cancel the click, a move of the finger will do so just as normal. Normally, this is a problem since no mouseleave
event is fired, and the hover effect remains in place. Thankfully, this can easily be fixed by removing the hover effect on touchmove
.
That's it!
Note that it is possible to remove the 300ms delay, for example using the FastClick library, but this is out of scope for this question.
I've found the following problems with the following alternatives:
touchend
: This will incorrectly follow the link, even if the user only wanted to scroll or zoom, without the intention of actually clicking the link.touchend
that is used as a if-condition in subsequent mouse events to prevents state changes at that point in time. The variable is reset in the click event. This is a decent solution if you really don't want a hover effect on touch interfaces. Unfortunately, this does not work if a touchend
is fired for another reason and no click event is fired (e.g. the user scrolled or zoomed), and is subsequently trying to following the link with a mouse (i.e on a device with both mouse and touch interface).mouseover
or mousemove
event.See also iPad/iPhone double click problem and Disable hover effects on mobile browsers.
I'm not sure about older versions, but from NEON onward, you can just right click on workspace and select Remove from launcher selection option.
of course this won't remove the original files. It simply removes it from the list of suggested workspaces.
You can use Collections.swap(List<?> list, int i, int j);
Try this css
.clearfix:before, .clearfix:after, .container:before, .container:after, .container-fluid:before, .container-fluid:after, .row:before, .row:after, .form-horizontal .form-group:before, .form-horizontal .form-group:after, .btn-toolbar:before, .btn-toolbar:after, .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after, .nav:before, .nav:after, .navbar:before, .navbar:after, .navbar-header:before, .navbar-header:after, .navbar-collapse:before, .navbar-collapse:after, .pager:before, .pager:after, .panel-body:before, .panel-body:after, .modal-footer:before, .modal-footer:after {
content: " ";
display: table-cell;
}
ul.nav {
float: none;
margin-bottom: 0;
margin-left: auto;
margin-right: auto;
margin-top: 0;
width: 240px;
}
Custom Pipes: When a custom pipe is created, It must be registered in Module and Component that is being used.
export class SummaryPipe implements PipeTransform{
//Implementing transform
transform(value: string, limit?: number): any {
if (!value) {
return null;
}
else {
let actualLimit=limit>0?limit:50
return value.substr(0,actualLimit)+'...'
}
}
}
Add Pipe Decorator
@Pipe({
name:'summary'
})
and refer
import { SummaryPipe } from '../summary.pipe';` //**In Component and Module**
<div>
**{{text | summary}}** //Name should same as it is mentioned in the decorator.
</div>
//summary is the name declared in Pipe decorator
You just need to keep Program Files in double quote & rest of the command don't need any quote.
C:\"Program Files"\IAR Systems\Embedded Workbench 7.0\430\bin\icc430.exe F:\CP00 .....
Even though this question was long time ago, thanks all for the inputs that helping me out a similar problem. I also made a bit modification based on the others' answers here and making multiple inputs/valuables into a Single Object (json); and hope this helps someone.
js:
//example: params={id:'123',name:'foo'};
mapInput.name = "data";
mapInput.value = JSON.stringify(params);
php:
$data=json_decode($_POST['data']);
echo $data->id;
echo $data->name;
There's a plugin for jQuery called 'rich array' discussed in Rich Array jQuery plugin .
Not clear where My_ConnectionString
is coming from in your example, but try this
System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString
like this
Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString)
Updated (11/2017) to take into consideration some comments.
Easy example:
wchar_t buf[256];
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buf, (sizeof(buf) / sizeof(wchar_t)), NULL);
<?php header("Access-Control-Allow-Origin: http://example.com"); ?>
This command disables only first console warning info
Result: console result
Check for any webkit styles being applied to elements like ul, h4 etc. For me it was margin-before and after causing this.
-webkit-margin-before: 1.33em;
-webkit-margin-after: 1.33em;
To solve this, I created a JS library to stream multiple files directly into a zip on the client-side. The main unique feature is that it has no size limits from memory (everything is streamed) nor zip format (it uses zip64 if the contents are more than 4GB).
Since it doesn't do compression, it is also very performant.
There is also an alternative way to use MarkupExtension
in order to use Binding
for a ConverterParameter
. With this solution you can still use the default IValueConverter
instead of the IMultiValueConverter
because the ConverterParameter
is passed into the IValueConverter
just like you expected in your first sample.
Here is my reusable MarkupExtension
:
/// <summary>
/// <example>
/// <TextBox>
/// <TextBox.Text>
/// <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
/// Converter="{StaticResource TestValueConverter}"
/// ConverterParameterBinding="{Binding ConcatSign}" />
/// </TextBox.Text>
/// </TextBox>
/// </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
#region Public Properties
public Binding Binding { get; set; }
public BindingMode Mode { get; set; }
public IValueConverter Converter { get; set; }
public Binding ConverterParameter { get; set; }
#endregion
public ConverterBindableParameter()
{ }
public ConverterBindableParameter(string path)
{
Binding = new Binding(path);
}
public ConverterBindableParameter(Binding binding)
{
Binding = binding;
}
#region Overridden Methods
public override object ProvideValue(IServiceProvider serviceProvider)
{
var multiBinding = new MultiBinding();
Binding.Mode = Mode;
multiBinding.Bindings.Add(Binding);
if (ConverterParameter != null)
{
ConverterParameter.Mode = BindingMode.OneWay;
multiBinding.Bindings.Add(ConverterParameter);
}
var adapter = new MultiValueConverterAdapter
{
Converter = Converter
};
multiBinding.Converter = adapter;
return multiBinding.ProvideValue(serviceProvider);
}
#endregion
[ContentProperty(nameof(Converter))]
private class MultiValueConverterAdapter : IMultiValueConverter
{
public IValueConverter Converter { get; set; }
private object lastParameter;
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (Converter == null) return values[0]; // Required for VS design-time
if (values.Length > 1) lastParameter = values[1];
return Converter.Convert(values[0], targetType, lastParameter, culture);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
if (Converter == null) return new object[] { value }; // Required for VS design-time
return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
}
}
}
With this MarkupExtension
in your code base you can simply bind the ConverterParameter
the following way:
<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
<Setter.Value>
<wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
Converter="{StaticResource AccessLevelToVisibilityConverter}"
ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />
</Setter.Value>
</Setter>
Which looks almost like your initial proposal.
Tested!
In Windows -> control panel -> Region -> Additional Settings -> Time -> Short Time:
Format your time as HH:mm
in the format
hh = 12 hours
HH = 24 hours
mm = minutes
tt = AM or PM
so to get the required result the format should be HH:mm and not hh:mm tt
Adding another answer as this is not covered by any of the answer
To change all buffers to tab
view.
:tab sball
will open all the buffers to tab view. Then we can use any tab related commands
gt or :tabn " go to next tab
gT or :tabp or :tabN " go to previous tab
details at :help tab-page-commands
.
We can instruct vim to open ,as tab view, multiple files by vim -p file1 file2
.
alias vim='vim -p'
will be useful.
The same thing can also be achieved by having following autocommand in ~/.vimrc
au VimEnter * if !&diff | tab all | tabfirst | endif
Anyway to answer the question:
To add to arg list: arga file
,
To delete from arg list: argd pattern
More at :help arglist
If you know that your lists only contain quoted strings, this pyparsing example will give you your list of stripped strings (even preserving the original Unicode-ness).
>>> from pyparsing import *
>>> x =u'[ "A","B","C" , " D"]'
>>> LBR,RBR = map(Suppress,"[]")
>>> qs = quotedString.setParseAction(removeQuotes, lambda t: t[0].strip())
>>> qsList = LBR + delimitedList(qs) + RBR
>>> print qsList.parseString(x).asList()
[u'A', u'B', u'C', u'D']
If your lists can have more datatypes, or even contain lists within lists, then you will need a more complete grammar - like this one on the pyparsing wiki, which will handle tuples, lists, ints, floats, and quoted strings. Will work with Python versions back to 2.4.
public class DisplayInfo {
int screen_height=0, screen_width=0;
WindowManager wm;
DisplayMetrics displaymetrics;
DisplayInfo(Context context) {
getdisplayheightWidth(context);
}
void getdisplayheightWidth(Context context) {
wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
displaymetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(displaymetrics);
screen_height = displaymetrics.heightPixels;
screen_width = displaymetrics.widthPixels;
}
public int getScreen_height() {
return screen_height;
}
public int getScreen_width() {
return screen_width;
}
}
You can write a jQuery function like this to determine if an element is in the viewport.
Include this somewhere after jQuery is included:
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
Sample usage:
$(window).on('resize scroll', function() {
if ($('#Something').isInViewport()) {
// do something
} else {
// do something else
}
});
Note that this only checks the top and bottom positions of elements, it doesn't check if an element is outside of the viewport horizontally.
<% %>
Executes the ruby code within the brackets.
<%= %>
Prints something into erb file.
<%== %>
Equivalent to <%= raw %>
. Prints something verbatim (i.e. w/o escaping) into erb file. (Taken from Ruby on Rails Guides.)
<% -%>
Avoids line break after expression.
<%# %>
Comments out code within brackets; not sent to client (as opposed to HTML comments).
Visit Ruby Doc for more infos about ERB.
First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate
$('.swipeRight').click(function()
{
$('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});
$('.swipeLeft').click(function()
{
$('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});
The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.
See this related thread. Basically, os.environ
is found on import, and os.getenv
is a wrapper to os.environ.get
, at least in CPython.
EDIT: To respond to a comment, in CPython, os.getenv
is basically a shortcut to os.environ.get
; since os.environ
is loaded at import of os
, and only then, the same holds for
os.getenv
.
Suppose your element is entire [object HTMLDocument]
. You can convert it to a String this way:
const htmlTemplate = `<!DOCTYPE html><html lang="en"><head></head><body></body></html>`;
const domparser = new DOMParser();
const doc = domparser.parseFromString(htmlTemplate, "text/html"); // [object HTMLDocument]
const doctype = '<!DOCTYPE html>';
const html = doc.documentElement.outerHTML;
console.log(doctype + html);
_x000D_
as a single line:
long value_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch()).count();
Gradient descent algorithm uses the constant learning rate which you can provide in during the initialization. You can pass various learning rates in a way showed by Mrry.
But instead of it you can also use more advanced optimizers which have faster convergence rate and adapts to the situation.
Here is a brief explanation based on my understanding:
Adam or adaptive momentum is an algorithm similar to AdaDelta. But in addition to storing learning rates for each of the parameters it also stores momentum changes for each of them separately
I'm surprised no one has mentioned filter_input, so here is Alix Axel's answer condensed to one-line:
function get_ip_address(&$keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'])
{
return empty($keys) || ($ip = filter_input(INPUT_SERVER, array_pop($keys), FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE))? $ip : get_ip_address($keys);
}
Assuming int is a 16 bit integer (which depends on the C implementation, most are 32 bit nowadays) the bit representation differs like the following:
5 = 0000000000000101
-5 = 1111111111111011
if binary 1111111111111011 would be set to an unsigned int, it would be decimal 65531.
(This is my third answer because I misunderstood what your code was doing in my original, and then made a small but crucial mistake in my second—hopefully three's a charm.
Edits: Since this seems to be a popular answer, I've made a few modifications to improve its implementation over the years—most not too major. This is so if folks use it as template, it will provide an even better basis.
As others have pointed out, your MemoryError
problem is most likely because you're attempting to read the entire contents of huge files into memory and then, on top of that, effectively doubling the amount of memory needed by creating a list of lists of the string values from each line.
Python's memory limits are determined by how much physical ram and virtual memory disk space your computer and operating system have available. Even if you don't use it all up and your program "works", using it may be impractical because it takes too long.
Anyway, the most obvious way to avoid that is to process each file a single line at a time, which means you have to do the processing incrementally.
To accomplish this, a list of running totals for each of the fields is kept. When that is finished, the average value of each field can be calculated by dividing the corresponding total value by the count of total lines read. Once that is done, these averages can be printed out and some written to one of the output files. I've also made a conscious effort to use very descriptive variable names to try to make it understandable.
try:
from itertools import izip_longest
except ImportError: # Python 3
from itertools import zip_longest as izip_longest
GROUP_SIZE = 4
input_file_names = ["A1_B1_100000.txt", "A2_B2_100000.txt", "A1_B2_100000.txt",
"A2_B1_100000.txt"]
file_write = open("average_generations.txt", 'w')
mutation_average = open("mutation_average", 'w') # left in, but nothing written
for file_name in input_file_names:
with open(file_name, 'r') as input_file:
print('processing file: {}'.format(file_name))
totals = []
for count, fields in enumerate((line.split('\t') for line in input_file), 1):
totals = [sum(values) for values in
izip_longest(totals, map(float, fields), fillvalue=0)]
averages = [total/count for total in totals]
for print_counter, average in enumerate(averages):
print(' {:9.4f}'.format(average))
if print_counter % GROUP_SIZE == 0:
file_write.write(str(average)+'\n')
file_write.write('\n')
file_write.close()
mutation_average.close()
For a hybrid dictionary, I use this:
List<string> keys = new List<string>(dictionary.Count);
keys.AddRange(dictionary.Keys.Cast<string>());
The lazy way: simply uninstall from the Windows installation menu (if you're using Windows), or from the rpm command, provided you first re-install it after creating a distribution package.
For example,
python setup.py bdist_wininst
dist/foo-1.0.win32.exe
("foo" being an example of course).
In Kotlin I have created an extension function for the Context. It takes a @StringRes and optionally you can provide parameters as well.
fun Context.fromHtmlWithParams(@StringRes stringRes: Int, parameter : String? = null) : Spanned {
val stringText = if (parameter.isNullOrEmpty()) {
this.getString(stringRes)
} else {
this.getString(stringRes, parameter)
}
return Html.fromHtml(stringText, Html.FROM_HTML_MODE_LEGACY)
}
Usage
tv_directors.text = context?.fromHtmlWithParams(R.string.directors, movie.Director)
ViewBag is a dynamic type that allow you to dynamically set or get values and allow you to add any number of additional fields without a strongly-typed class They allow you to pass data from controller to view. In controller......
public ActionResult Index()
{
ViewBag.victor = "My name is Victor";
return View();
}
In view
@foreach(string a in ViewBag.victor)
{
.........
}
What I have learnt is that both should have the save dynamic name property ie ViewBag.victor
In case you want a constructor with properties, you need to do the following:
Place your cursor in any empty line in a class;
Press Ctrl + . to trigger the Quick Actions and Refactorings menu;
Select Generate constructor from the drop-down menu;
Pick the members you want to include as constructor parameters. You can order them using the up and down arrows. Choose OK.
The constructor is created with the specified parameters.
public class Application {
private static List<HttpMessageConverter<?>> getMessageConverters() {
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(new MappingJacksonHttpMessageConverter());
return converters;
}
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(getMessageConverters());
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
//Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);
ResponseEntity<Page> response =
restTemplate.exchange("http://graph.facebook.com/skbh86", HttpMethod.GET, entity, Page.class, "1");
Page page = response.getBody();
System.out.println("Name: " + page.getId());
System.out.println("About: " + page.getFirst_name());
System.out.println("Phone: " + page.getLast_name());
System.out.println("Website: " + page.getMiddle_name());
System.out.println("Website: " + page.getName());
}
}
By default, Homebrew installs packages to your /usr/local. Macport commands require sudo to install and upgrade (similar to apt-get in Ubuntu).
For more detail:
This site suggests using Hombrew: http://deephill.com/macports-vs-homebrew/
whereas this site lists the advantages of using Macports: http://arstechnica.com/civis/viewtopic.php?f=19&t=1207907
I also switched from Ubuntu recently, and I enjoy using homebrew (it's simple and easy to use!), but if you feel attached to using sudo, Macports might be the better way to go!
getAttribute() -> It fetches the text that contains one of any attribute in the HTML tag. Suppose there is an HTML tag like
<input name="Name Locator" value="selenium">Hello</input>
Now getAttribute() fetches the data of the attribute of 'value', which is "Selenium".
Returns:
The attribute's current value or null if the value is not set.
driver.findElement(By.name("Name Locator")).getAttribute("value") //
The field value is retrieved by the getAttribute("value") Selenium WebDriver predefined method and assigned to the String object.
getText() -> delivers the innerText of a WebElement. Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.
driver.findElement(By.name("Name Locator")).getText();
'Hello' will appear
You can use this code block for JFrame background color.
JFrame frame = new JFrame("Frame BG color");
frame.setLayout(null);
frame.setSize(1000, 650);
frame.getContentPane().setBackground(new Color(5, 65, 90));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
This appears to be an inside joke at Google. It's also featured in the Google Chrome task manager. It has no purpose, other than some engineers finding it amusing. Which is a purpose by itself, if you will.
Goats Teleported
column.There is even a huge Chromium bug report about too many teleported goats.
The following Chromium source code snippet is stolen from the HN comments.
int TaskManagerModel::GetGoatsTeleported(int index) const {
int seed = goat_salt_ * (index + 1);
return (seed >> 16) & 255;
}
This introduces a new paradigm to HTML/CSS, but using an <input readonly="true">
would allow you to append an input:focus
selector to then alter the background-image
This of course would require applying specific CSS to the input
itself to override browser defaults but it does go to show that click actions can indeed be triggered without the use of Javascript.
Anything after Application.Run( ) will only be executed when the main form closes.
What you could do is handle the VisibleChanged
event as follows:
static Form1 form1;
static Form2 form2;
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
form2 = new Form2();
form1 = new Form1();
form2.Hide();
form1.VisibleChanged += OnForm1Changed;
Application.Run(form1);
}
static void OnForm1Changed( object sender, EventArgs args )
{
if ( !form1.Visible )
{
form2.Show( );
}
}
Summing up all answers :
==
is a bad idea for string comparisons.
It will give you "surprising" results in many cases. Don't trust it.
===
is fine, and will give you the best performance.
strcmp()
should be used if you need to determine which string is "greater", typically for sorting operations.
OP asked specifically about regexes since it would appear there's concern for a number of other characters as well as newlines, but for those just wanting strip out newlines, you don't even need to go to a regex. You can simply do:
select replace(field,E'\n','');
I think this is an SQL-standard behavior, so it should extend back to all but perhaps the very earliest versions of Postgres. The above tested fine for me in 9.4 and 9.2
An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view
Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'
The best way to do this:
ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);
In the default constructor (and any non-default ones if you have any too of course):
public foo() {
Bar = "bar";
}
This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.
Since Hadoop 3.0.0 - Alpha 1 there was a Change in the port configuration:
http://localhost:50070
was moved to
http://localhost:9870
Use PropertyInfo.PropertyType
to get the type of the property.
public bool ValidateData(object data)
{
foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
{
if (propertyInfo.PropertyType == typeof(string))
{
string value = propertyInfo.GetValue(data, null);
if value is not OK
{
return false;
}
}
}
return true;
}
Use position: fixed
instead of position: absolute
.
See here.
var joinedString= string.Join(";", myDict.Select(x => x.Key + "=" + x.Value));
As you can see I only have java 1.7 installed (on a Ubuntu 14.04 machine).
update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
To install Java 8, I did,
sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt-get install openjdk-8-jdk
Afterwards, now I have java 7 and 8,
update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1069 /usr/lib/jvm/java-1.8.0-openjdk-amd64
BONUS ADDED (how to switch between different versions)
sudo update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1071 auto mode 1 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1071 manual mode * 2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1069 manual mode Press enter to keep the current choice[*], or type selection number:
As you can see I'm running open jdk 8. To switch to to jdk 7, press 1
and hit the Enter key. Do the same for javac
as well with, sudo update-alternatives --config javac
.
Check versions to confirm the change: java -version
and javac -version
.
@echo off
title Command Executer
color 1b
echo Command Executer by: YourNameHere
echo #################################
: execute
echo Please Type A Command Here:
set /p cmd=Command:
%cmd%
goto execute
When running Wget with -r
or -p
, but without -N
, -nd
, or -nc
, re-downloading a file will result in the new copy simply overwriting the old.
So adding -nc
will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
W3C doc says regarding "border-radius" property: "supported in IE9+, Firefox, Chrome, Safari, and Opera".
Hence I assume you're testing on IE8 or below.
For "regular elements" there is a solution compatible with IE8 & other old/poor browsers. See below.
HTML:
<div class="myWickedClass">
<span class="myCoolItem">Some text</span> <span class="myCoolItem">Some text</span> <span class="myCoolItem"> Some text</span> <span class="myCoolItem">Some text</span>
</div>
CSS:
.myWickedClass{
padding: 0 5px 0 0;
background: #F7D358 url(../img/roundedCorner_right.png) top right no-repeat scroll;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
font: normal 11px Verdana, Helvetica, sans-serif;
color: #A4A4A4;
}
.myWickedClass > .myCoolItem:first-child {
padding-left: 6px;
background: #F7D358 url(../img/roundedCorner_left.png) 0px 0px no-repeat scroll;
}
.myWickedClass > .myCoolItem {
padding-right: 5px;
}
You need to create both roundedCorner_right.png & roundedCorner_left.png. These are work around for IE8 (& below) to fake the rounded corner feature.
So in this example above we apply the left rounded corner to the first span element in the containing div, & we apply the right rounded corner to the containing div. These images overlap the browser-provided "squary corners" & give the illusion of being part of a rounded element.
The idea for inputs would be to do the same logic. However, input is an empty element, " element is empty, it contains attributes only", in other word, you cannot wrap a span into an input such as <input><span class="myCoolItem"></span></input>
to then use background images like in the previous example.
Hence the solution seems to be to do the opposite: wrap the input into another element. see this answer rounded corners of input elements in IE
Remove last comma. Working example
function truncateText() {_x000D_
var str= document.getElementById('input').value;_x000D_
str = str.replace(/,\s*$/, "");_x000D_
console.log(str);_x000D_
}
_x000D_
<input id="input" value="address line one,"/>_x000D_
<button onclick="truncateText()">Truncate</button>
_x000D_
After a lot of fiddling, got it working (only tested in Webkit) using:
font-family: "HelveticaNeue-CondensedBold";
font-stretch was dropped between CSS2 and 2.1, though is back in CSS3, but is only supported in IE9 (never thought I'd be able to say that about any CSS prop!)
This works because I'm using the postscript name (find the font in Font Book, hit cmd+I), which is non-standard behaviour. It's probably worth using:
font-family: "HelveticaNeue-CondensedBold", "Helvetica Neue";
As a fallback, else other browsers might default to serif if they can't work it out.
I found the following in a small comment in Supperuser.com:
@JacksOnF1re - New information/technique added to my answer. You can actually delete your Copy of prefix using an obscure forward slash technique: ren "Copy of .txt" "////////"
Of How does the Windows RENAME command interpret wildcards? See in this thread, the answer of dbenham.
My problem was slightly different, I wanted to add a Prefix to the file and remove from the beginning what I don't need. In my case I had several hundred of enumerated files such as:
SKMBT_C36019101512510_001.jpg
SKMBT_C36019101512510_002.jpg
SKMBT_C36019101512510_003.jpg
SKMBT_C36019101512510_004.jpg
:
:
Now I wanted to respectively rename them all to (Album 07 picture #):
A07_P001.jpg
A07_P002.jpg
A07_P003.jpg
A07_P004.jpg
:
:
I did it with a single command line and it worked like charm:
ren "SKMBT_C36019101512510_*.*" "/////////////////A06_P*.*"
Note:
"
) the "<Name Scheme>"
is not an option, it does not work otherwise, in our example: "SKMBT_C36019101512510_*.*"
and "/////////////////A06_P*.*"
were quoted.A06_P
actually replaced 2510_
and the SKMBT_C3601910151
was removed, by using exactly the number of slashes /////////////////
(17 characters).I am part of a team investigating the use of Evolutionary Computation (EC) to automatically fix bugs in existing programs. We have successfully repaired a number of real bugs in real world software projects (see this project's homepage).
We have two applications of this EC repair technique.
The first (code and reproduction information available through the project page) evolves the abstract syntax trees parsed from existing C programs and is implemented in Ocaml using our own custom EC engine.
The second (code and reproduction information available through the project page), my personal contribution to the project, evolves the x86 assembly or Java byte code compiled from programs written in a number of programming languages. This application is implemented in Clojure and also uses its own custom built EC engine.
One nice aspect of Evolutionary Computation is the simplicity of the technique makes it possible to write your own custom implementations without too much difficulty. For a good freely available introductory text on Genetic Programming see the Field Guide to Genetic Programming.
The above did not work for me but this did
<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>
When a script generates an html form and that form's action http POSTs back to the same form.
So, I've figured out the issue and it was a combination of bad logic and not being totally familiar with the automake/autotools world. I was adding the correct files to my Makefile.am template, but I wasn't sure which step in our build process actually created the makefile itself. So, I was compiling with an old makefile that had no idea about my new files whatsoever.
Thanks for the responses and the link to the GCC FAQ. I will be sure to read that to avoid this problem occurring for a real reason.
Change your div
into a flex container:
div { display:flex; }
Now there are two methods to center the alignments for all the content:
Method 1:
div { align-items:center; }
Method 2:
div * { margin-top:auto; margin-bottom:auto; }
Try different width and height values on the img
and different font size values on the span
and you'll see they always remain in the middle of the container.
I followed the advice of Simon Gibbs in this answer and found it worked out fine - if you're in a hurry, the "Web Page Editor (optional)" package from the Eclipse update site does the trick.
For the Eclipse-challenged (me) Help > Install New Software > Work with > Expand Web, XML, and Java EE Development > Select "Web Page Editor (optional)" and "next-through" to completion.
I got this error when I was trying to access a url using curl:
curl 'https://example.com:80/some/page'
The solution was to change https
to http
curl 'http://example.com:80/some/page'
You can simply use jQuery UI Dialog
Example:
$(function() {_x000D_
$("#dialog").dialog();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>jQuery UI Dialog - Default functionality</title>_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />_x000D_
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
<link rel="stylesheet" href="/resources/demos/style.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="dialog" title="Basic dialog">_x000D_
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
To use it, simply do something like this:
var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);
The var alteredURL
will be the output you desire.
Hope it helps!
I get exactly the same errors as kryshah with su - postgres
and sudo -u postgres psql
.
DanielM's answer gives also errors.
Answer however from przbabu's comment.
masi$ psql
psql: FATAL: database "masi" does not exist
masi$ psql -U postgres
psql: FATAL: role "postgres" does not exist
masi$ psql postgres
psql (9.4.1)
Type "help" for help.
I think the some part of this problem may be in owner settings in OSX
masi$ ls -al /Users/
total 0
drwxr-xr-x 7 root admin 238 Jul 3 09:50 .
drwxr-xr-x 37 root wheel 1326 Jul 2 19:02 ..
-rw-r--r-- 1 root wheel 0 Sep 10 2014 .localized
drwxrwxrwt 7 root wheel 238 Apr 9 19:49 Shared
drwxr-xr-x 2 root admin 68 Jul 3 09:50 postgres
drwxr-xr-x+ 71 masi staff 2414 Jul 3 09:50 masi
but doing sudo chown -R postgres:staff /Users/postgres
gives chown: invalid user: ‘postgres:staff’
.
In short, this is not the solution the problem. Use the tools provided by the postgres installation to create a user and database.
There are specific commands after postgres installation to add a new user to the database system. After initdb, run the following as described here
createuser --pwprompt postgres
createdb -Opostgres -Eutf8 masi_development
psql -U postgres -W masi_development
To avoid the password request all the time, you have three choices as described here.
Try this little crumpet:
-(void)saveUserSettings{
NSNumber* value;
value = [NSNumber numberWithFloat:self.sensativity];
[[NSUserDefaults standardUserDefaults] setObject:value forKey:@"sensativity"];
}
-(void)loadUserSettings{
NSNumber* value;
value = [[NSUserDefaults standardUserDefaults] objectForKey:@"sensativity"];
if(value == nil){
self.sensativity = 4.0;
}else{
self.sensativity = [value floatValue];
}
}
Treat everything as an object. Seems to work for me.
This will work for original question asked:
DECLARE @Result INT;
SELECT @Result = COUNT(*)
FROM TableName
WHERE Condition
If you don't want to include the full path, you can do
add_executable(main main.cpp)
target_link_libraries(main bingitup)
bingitup
is the same name you'd give a target if you create the static library in a CMake project:
add_library(bingitup STATIC bingitup.cpp)
CMake automatically adds the lib
to the front and the .a
at the end on Linux, and .lib
at the end on Windows.
If the library is external, you might want to add the path to the library using
link_directories(/path/to/libraries/)
Some might encounter this error (I got it while implementing PHP-MySQLi-JSON-Google Chart Example):
You called the draw() method with the wrong type of data rather than a DataTable or DataView.
The solution would be: replace jsapi and just use loader.js with:
google.charts.load('current', {packages: ['corechart']}) and
google.charts.setOnLoadCallback
-- according to the release notes --> The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
if you are in the windows7 platform maybe you should change the NODE_PATH like this:
%AppData%\npm\node_modules
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
Ok what you probably want will be provide to you by result of:
in CSS:
div { column-count: 2; }
in html:
<div> some text, bla bla bla </div>
In CSS you make div to split your paragraph on to column, you can make them 3, 4...
If you want to have many differend paragraf like that, then put id or class in your div:
Unlike the CMD.EXE CHDIR
or CD
command, the PowerShell Set-Location
cmdlet will change drive and directory, both. Get-Help Set-Location -Full
will get you more detailed information on Set-Location
, but the basic usage would be
PS C:\> Set-Location -Path Q:\MyDir
PS Q:\MyDir>
By default in PowerShell, CD
and CHDIR
are alias for Set-Location
.
(Asad reminded me in the comments that if the path contains spaces, it must be enclosed in quotes.)
If you want to validate email then use input with type="email" instead of type="text". AngularJS has email validation out of the box, so no need to use ng-pattern for this.
Here is the example from original documentation:
<script>
function Ctrl($scope) {
$scope.text = '[email protected]';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<br/>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<br>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
For more details read this doc: https://docs.angularjs.org/api/ng/input/input%5Bemail%5D
Live example: http://plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info
UPD:
If you are not satisfied with built-in email validator and you want to use your custom RegExp pattern validation then ng-pattern directive can be applied and according to the documentation the error message can be displayed like this:
The validator sets the pattern error key if the ngModel.$viewValue does not match a RegExp
<script>
function Ctrl($scope) {
$scope.text = '[email protected]';
$scope.emailFormat = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" ng-pattern="emailFormat" required>
<br/><br/>
<span class="error" ng-show="myForm.input.$error.required">
Required!
</span><br/>
<span class="error" ng-show="myForm.input.$error.pattern">
Not valid email!
</span>
<br><br>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.pattern = {{!!myForm.$error.pattern}}</tt><br/>
</form>
Plunker: https://plnkr.co/edit/e4imaxX6rTF6jfWbp7mQ?p=preview
There's also the undocumented value of "none" to disable it entirely.
when you upload your files to the server be careful ,some tomes your images will not appear on the web page and a crashed icon will appear that means your file path is not properly arranged or coded when you have the the following file structure the code should be like this File structure: ->web(main folder) ->images(subfolder)->logo.png(image in the sub folder)the code for the above is below follow this standard
<img src="../images/logo.jpg" alt="image1" width="50px" height="50px">
if you uploaded your files to the web server by neglecting the file structure with out creating the folder web if you directly upload the files then your images will be broken you can't see images,then change the code as following
<img src="images/logo.jpg" alt="image1" width="50px" height="50px">
thank you->vamshi krishnan
The latest way to do this with ES2016 JavaScript
let makeGamePlayer = (name, totalScore, gamesPlayed) => ({
name,
totalScore,
gamesPlayed
})
I think this is simpler for grabbing the array and stripping spaces:
@Value("#{'${my.array}'.replace(' ', '').split(',')}")
private List<String> array;
As already stated ??!??!
is essentially two trigraphs (??!
and ??!
again) mushed together that get replaced-translated to ||
, i.e the logical OR, by the preprocessor.
The following table containing every trigraph should help disambiguate alternate trigraph combinations:
Trigraph Replaces
??( [
??) ]
??< {
??> }
??/ \
??' ^
??= #
??! |
??- ~
Source: C: A Reference Manual 5th Edition
So a trigraph that looks like ??(??)
will eventually map to []
, ??(??)??(??)
will get replaced by [][]
and so on, you get the idea.
Since trigraphs are substituted during preprocessing you could use cpp
to get a view of the output yourself, using a silly trigr.c
program:
void main(){ const char *s = "??!??!"; }
and processing it with:
cpp -trigraphs trigr.c
You'll get a console output of
void main(){ const char *s = "||"; }
As you can notice, the option -trigraphs
must be specified or else cpp
will issue a warning; this indicates how trigraphs are a thing of the past and of no modern value other than confusing people who might bump into them.
As for the rationale behind the introduction of trigraphs, it is better understood when looking at the history section of ISO/IEC 646:
ISO/IEC 646 and its predecessor ASCII (ANSI X3.4) largely endorsed existing practice regarding character encodings in the telecommunications industry.
As ASCII did not provide a number of characters needed for languages other than English, a number of national variants were made that substituted some less-used characters with needed ones.
(emphasis mine)
So, in essence, some needed characters (those for which a trigraph exists) were replaced in certain national variants. This leads to the alternate representation using trigraphs comprised of characters that other variants still had around.
I had the same issue and solved by making sure that 1. when you make the style.css file, make sure you didn't just rename a text file as "style.css", make sure it's really the .css format (e.g, use visual studio code); 2. put that style.css file in the same folder with your .rmd file. Hopefully this works for you.
I found out that, on iPhone 4 with IOS 7, you CAN put a body to the SMS only if you set a phone number in the list of contact of the phone.
So the following will work If 0606060606 is part of my contacts:
<a href="sms:0606060606;body=Hello my friend">Send SMS</a>
By the way, on iOS 6 (iPhone 3GS), it's working with just a body :
<a href="sms:;body=Hello my friend">Send SMS</a>
Optimize your images ... Dont use images larger than 100KB ... Image loading takes too much CPU and cause your app hangs .
function functABC(){
// returns a promise that can be used later.
return $.ajax({
url: 'myPage.php',
data: {id: id}
});
}
functABC().then( response =>
console.log(response);
);
Nice read e.g. here.
This is not "synchronous" really, but I think it achieves what the OP intends.
async
option has since been deprecated):All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify
async: false
like described here
Note, however, that in most cases asynchronous execution (via callback on success) is just fine.
Assuming editText
is you EditText
object:
editText.setEnabled(false);
Xamarin is now owned by Microsoft So it completely free to use on Windows and mac as well.
grep was born to extract things:
grep -Po 'name="\K[^"]*'
test with your data:
kent$ echo '<parameter name="PortMappingEnabled" access="readWrite" type="xsd:boolean"></parameter>
<parameter name="PortMappingLeaseDuration" access="readWrite" activeNotify="canDeny" type="xsd:unsignedInt"></parameter>
<parameter name="RemoteHost" access="readWrite"></parameter>
<parameter name="ExternalPort" access="readWrite" type="xsd:unsignedInt"></parameter>
<parameter name="ExternalPortEndRange" access="readWrite" type="xsd:unsignedInt"></parameter>
<parameter name="InternalPort" access="readWrite" type="xsd:unsignedInt"></parameter>
<parameter name="PortMappingProtocol" access="readWrite"></parameter>
<parameter name="InternalClient" access="readWrite"></parameter>
<parameter name="PortMappingDescription" access="readWrite"></parameter>
'|grep -Po 'name="\K[^"]*'
PortMappingEnabled
PortMappingLeaseDuration
RemoteHost
ExternalPort
ExternalPortEndRange
InternalPort
PortMappingProtocol
InternalClient
PortMappingDescription
Workaround - Open a modal popup window and embed the external URL as an iframe.