Compiler knows by type cast. Given a void *x
:
x+1
adds one byte to x
, pointer goes to byte x+1
(int*)x+1
adds sizeof(int)
bytes, pointer goes to byte x + sizeof(int)
(float*)x+1
addres sizeof(float)
bytes,
etc.Althought the first item is not portable and is against the Galateo of C/C++, it is nevertheless C-language-correct, meaning it will compile to something on most compilers possibly necessitating an appropriate flag (like -Wpointer-arith)
The following takes athspk's answer and makes it into one that loops continually until the user types "exit". I've also written a followup answer where I've taken this code and made it testable.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LoopingConsoleInputExample {
public static final String EXIT_COMMAND = "exit";
public static void main(final String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");
while (true) {
System.out.print("> ");
String input = br.readLine();
System.out.println(input);
if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
System.out.println("Exiting.");
return;
}
System.out.println("...response goes here...");
}
}
}
Example output:
Enter some text, or 'exit' to quit
> one
one
...response goes here...
> two
two
...response goes here...
> three
three
...response goes here...
> exit
exit
Exiting.
In your examples there is no functional difference. I find your first example more readable.
The easiest solution is to create a new workspace in eclipse/STS.
File -> Switch Workspace -> Others...
As Pekka stated above
foreach ($array as $key => $value)
Also you might want to try a recursive function
displayRecursiveResults($site);
function displayRecursiveResults($arrayObject) {
foreach($arrayObject as $key=>$data) {
if(is_array($data)) {
displayRecursiveResults($data);
} elseif(is_object($data)) {
displayRecursiveResults($data);
} else {
echo "Key: ".$key." Data: ".$data."<br />";
}
}
}
RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.
Note that the NIB file doesn't wire up all the IBOutlets until the view has been added to the scene. If you're wiring things up manually (which you might be doing if things are in separate NIBs) this is important to keep in mind.
So if my test view controller has an "imageView" wired by a nib, this probably won't work:
testCardViewController.imageView.image = [UIImage imageNamed:@"EmptyCard.png"];
[self.view addSubview:testCardViewController.view];
But this will:
[self.view addSubview:testCardViewController.view];
testCardViewController.imageView.image = [UIImage imageNamed:@"EmptyCard.png"];
Fiddler is great when you are only interested in the http(s) side of the communications. It is also very useful when you are trying to inspect inside a https stream.
You should use $evalAsync or $timeout according to the context.
This is a link with a good explanation:
http://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm
This issue still returns every now and then. I wrote a small PowerShell snippet to automate clearing the relevant cache/temp folder/files for me. I'm sharing it here for future readers:
@(
"$env:TEMP"
"$env:LOCALAPPDATA\Microsoft\UnitTest"
"$env:LOCALAPPDATA\Microsoft\VisualStudio\14.0\1033\SpecificFolderCache.xml"
"$env:LOCALAPPDATA\Microsoft\VisualStudio\14.0\1033\ProjectTemplateMRU.xml"
"$env:LOCALAPPDATA\Microsoft\VisualStudio\14.0\ComponentModelCache"
"$env:LOCALAPPDATA\Microsoft\VisualStudio\14.0\Designer\ShadowCache"
"$env:LOCALAPPDATA\Microsoft\VisualStudio\14.0\ImageLibrary\cache"
"$env:LOCALAPPDATA\Microsoft\VisualStudio Services\6.0\Cache"
"$env:LOCALAPPDATA\Microsoft\WebsiteCache"
"$env:LOCALAPPDATA\NuGet\Cache"
) |% { Remove-Item -Path $_ -Recurse -Force }
Make sure to close Visual Studio beforehand and it's probably a good idea to reboot afterwards.
Deleting the TEMP folder may not be necessary and may in some cases even be undesirable, so I would recommend trying without clearing the TEMP folder first. Just omit the "$env:TEMP"
.
The problem was "solved" after a thorough cleaning of Visual Studio-related temp/cache folders.
Since I did not have the time to go through everything one-by-one and then test in-between, I unfortunately don't know which one actually caused the problem.
These are the exact steps I've taken:
temp
files/foldersManually cleared/deleted the following files/folders:
%USERPROFILE%\AppData\Local\assembly
%USERPROFILE%\AppData\Local\Microsoft\UnitTest
%USERPROFILE%\AppData\Local\Microsoft\VisualStudio\14.0\1033\SpecificFolderCache.xml
%USERPROFILE%\AppData\Local\Microsoft\VisualStudio\14.0\1033\ProjectTemplateMRU.xml
%USERPROFILE%\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache
%USERPROFILE%\AppData\Local\Microsoft\VisualStudio\14.0\Designer\ShadowCache
%USERPROFILE%\AppData\Local\Microsoft\VisualStudio\14.0\ImageLibrary\cache
%USERPROFILE%\AppData\Local\Microsoft\VisualStudio Services\6.0\Cache
%USERPROFILE%\AppData\Local\Microsoft\WebsiteCache
%USERPROFILE%\AppData\Local\NuGet\Cache
%USERPROFILE%\AppData\Local\Temp
Easy task with grep
:
grep -v help filename
Append > newFileName
to redirect output to a new file.
To clarify it, the normal behavior will be printing the lines on screen. To pipe it to a file, the >
can be used. Thus, in this command:
grep -v help filename > newFileName
grep
calls the grep
program, obviously-v
is a flag to inverse the output. By defaulf, grep
prints the lines that match the given pattern. With this flag, it will print the lines that don't match the pattern.help
is the pattern to matchfilename
is the name of the input file>
redirects the output to the following itemnewFileName
the new file where output will be saved.As you may noticed, you will not be deleting things in your file. grep
will read it and another file will be saved, modified accordingly.
UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)
For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:
https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
@WoooHaaaa some third party packages use 'django.middleware.csrf.CsrfViewMiddleware' middleware. for example i use django-rest-oauth and i have problem like you even after disabling those things. maybe these packages responded to your request like my case, because you use authentication decorator and something like this.
I have wondered the same thing. Basically it appears that the html spec has different content types for html and form data. Json only has a single content type.
According to the spec, a POST of json data should have the content-type:
application/json
Relevant portion of the HTML spec
6.7 Content types (MIME types)
...
Examples of content types include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic".17.13.4 Form content types
...
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows
Relevant portion of the JSON spec
- IANA Considerations
The MIME media type for JSON text is application/json.
Here's a simpler solution: install python-chromedrive package, import it in your script, and it's done.
Step by step:
1. pip install chromedriver-binary
2. import the package
from selenium import webdriver
import chromedriver_binary # Adds chromedriver binary to path
driver = webdriver.Chrome()
driver.get("http://www.python.org")
public function getdata(){
$this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, t.id as id');
$this->db->from('tblmaster t');
$this->db->join('country c', 't.country=c.country_id');
$this->db->join('state s', 't.state=s.state_id');
$this->db->join('city ct', 't.city=ct.city_id');
$this->db->order_by('t.id','desc');
$query = $this->db->get();
return $query->result();
}
you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.
You should always consider a non-vba solution first.
Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):
http://www.youtube.com/watch?v=RCLUM0UMLXo
http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx
If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.
If it has to be the latter, then there is need for more details on your specification, regarding performance questions.
You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.
This would look something like that:
Public Sub CopyFilter()
Dim wks As Worksheet
Dim avarTemp() As Variant
'go through each worksheet
For Each wks In ThisWorkbook.Worksheets
avarTemp = wks.UsedRange
For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
'check in the first column in each row
If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
'copy cell
targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
End If
Next i
Next wks
End Sub
Ok, now i have something nice which could come in handy for myself:
Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
Dim avarTemp() As Variant
Dim avarResult() As Variant
Dim i As Long
avarTemp = rng
ReDim avarResult(0)
For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
If avarTemp(i, 1) = "active" Then
avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
'expand our result array
ReDim Preserve avarResult(UBound(avarResult) + 1)
End If
Next i
FILTER = avarResult
End Function
You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)
Here you go.
Add in your application.properties file:
#first db
spring.datasource.url = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
spring.datasource.driverClassName = oracle.jdbc.OracleDriver
#second db ...
spring.secondDatasource.url = [url]
spring.secondDatasource.username = [username]
spring.secondDatasource.password = [password]
spring.secondDatasource.driverClassName = oracle.jdbc.OracleDriver
Add in any class annotated with @Configuration the following methods:
@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix="spring.secondDatasource")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
Set texts with different sizes and styles, and size and style for texts from cells ( with Range)
Sub EmailManuellAbsenden()
Dim ghApp As Object
Dim ghOldBody As String
Dim ghNewBody As String
Set ghApp = CreateObject("Outlook.Application")
With ghApp.CreateItem(0)
.To = Range("B2")
.CC = Range("B3")
.Subject = Range("B4")
.GetInspector.Display
ghOldBody = .htmlBody
ghNewBody = "<font style=""font-family: Calibri; font-size: 11pt;""/font>" & _
"<font style=""font-family: Arial; font-size: 14pt;"">Arial Text 14</font>" & _
Range("B5") & "<br>" & _
Range("B6") & "<br>" & _
"<font style=""font-family: Chiller; font-size: 21pt;"">Ciller 21</font>" &
Range("B5")
.htmlBody = ghNewBody & ghOldBody
End With
End Sub
'Fill B2 to B6 with some letters for testing
'"<font style=""font-family: Calibri; font-size: 15pt;""/font>" = works for all Range Objekts
When adding a directory to github check that the directory does not contain a .git file using "ls -a" if it does remove it. .git files in a directory will cause problems when you are trying to add a that directory in git
Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:
lstDepartment.ClearSelection();
foreach (var item in lstDepartment.Items)
{
if (item.Value == otherDropDownList.SelectedValue)
{
item.Selected = true;
}
}
If you only want to read the first 999,999 (non-header) rows:
read_csv(..., nrows=999999)
If you only want to read rows 1,000,000 ... 1,999,999
read_csv(..., skiprows=1000000, nrows=999999)
nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*
skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file
and for large files, you'll probably also want to use chunksize:
chunksize : int, default None Return TextFileReader object for iteration
CSS
select{
color:red;
}
HTML
<select id="sel" onclick="document.getElementById('sel').style.color='green';">
<option>Select Your Option</option>
<option value="">INDIA</option>
<option value="">USA</option>
</select>
The above code will change the colour of text on click of the select box.
and if you want every option different colour, give separate class or id to all options.
The function component return type is limited to JSXElement | null
in TypeScript. This is a current type limitation, pure React allows more return types.
You can either use a type assertion or Fragments as workaround:
const Aux = (props: AuxProps) => <>props.children</>;
const Aux2 = (props: AuxProps) => props.children as ReactElement;
ReactNode
children: React.ReactNode
might be suboptimal, if the goal is to have strong types for Aux
.
Almost anything can be assigned to current ReactNode
type, which is equivalent to {} | undefined | null
. A safer type for your case could be:
interface AuxProps {
children: ReactElement | ReactElement[]
}
Example:
Given Aux
needs React elements as children
, we accidently added a string
to it. Then above solution would error in contrast to ReactNode
- take a look at the linked playgrounds.
Typed children
are also useful for non-JSX props, like a Render Prop callback.
For anyone attempting something similar using a Dockerfile...
Running in detached mode won't help. The container will always exit (stop running) if the command is non-blocking, this is the case with bash.
In this case, a workaround would be: 1. Commit the resulting image: (container_name = the name of the container you want to base the image off of, image_name = the name of the image to be created docker commit container_name image_name 2. Use docker run to create a new container using the new image, specifying the command you want to run. Here, I will run "bash": docker run -it image_name bash
This would get you the interactive login you're looking for.
If you want to be able to have a SELECT without problems of the parent id having to be lower than child id, a function could be used. It supports also multiple children (as a tree should do) and the tree can have multiple heads. It also ensure to break if a loop exists in the data.
I wanted to use dynamic SQL to be able to pass the table/columns names, but functions in MySQL don't support this.
DELIMITER $$
CREATE FUNCTION `isSubElement`(pParentId INT, pId INT) RETURNS int(11)
DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE isChild,curId,curParent,lastParent int;
SET isChild = 0;
SET curId = pId;
SET curParent = -1;
SET lastParent = -2;
WHILE lastParent <> curParent AND curParent <> 0 AND curId <> -1 AND curParent <> pId AND isChild = 0 DO
SET lastParent = curParent;
SELECT ParentId from `test` where id=curId limit 1 into curParent;
IF curParent = pParentId THEN
SET isChild = 1;
END IF;
SET curId = curParent;
END WHILE;
RETURN isChild;
END$$
Here, the table test
has to be modified to the real table name and the columns (ParentId,Id) may have to be adjusted for your real names.
Usage :
SET @wantedSubTreeId = 3;
SELECT * FROM test WHERE isSubElement(@wantedSubTreeId,id) = 1 OR ID = @wantedSubTreeId;
Result :
3 7 k
5 3 d
9 3 f
1 5 a
SQL for test creation :
CREATE TABLE IF NOT EXISTS `test` (
`Id` int(11) NOT NULL,
`ParentId` int(11) DEFAULT NULL,
`Name` varchar(300) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
insert into test (id, parentid, name) values(3,7,'k');
insert into test (id, parentid, name) values(5,3,'d');
insert into test (id, parentid, name) values(9,3,'f');
insert into test (id, parentid, name) values(1,5,'a');
insert into test (id, parentid, name) values(6,2,'o');
insert into test (id, parentid, name) values(2,8,'c');
EDIT : Here is a fiddle to test it yourself. It forced me to change the delimiter using the predefined one, but it works.
Python 2.7 :
x = None
isinstance(x, type(None))
or
isinstance(None, type(None))
==> True
Use String#trim()
method or String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")
for trim both the end.
For left trim:
String leftRemoved = myString.replaceAll("^\\s+", "");
For right trim:
String rightRemoved = myString.replaceAll("\\s+$", "");
For anyone who tried everything and still getting error,I have a work around.
In the folder where pytest is installed,go to pytest-env folder.
Open pyvenv.cfg file.
In the file change include-system-site-packages from false to true.
home = /usr/bin
include-system-site-packages = true
version = 3.6.6
Hope it works .Don't forget to up vote.
You use u"??".encode('utf8')
to encode an unicode string.
But if you want to represent "??"
, you should decode it. Just like:
"??".decode("utf8")
You will get what you want. Maybe you should learn more about encode & decode.
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
The way you have added a row into the table layout you can add multiple TableRow
instances into your tableLayout
object
tl.addView(row1);
tl.addView(row2);
etc...
You are most likely pushing a string 'NULL'
to the table, rather then an actual NULL
, but other things may be going on as well, an illustration:
mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)
mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)
mysql> show warnings;
+---------+------+------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT * FROM date_test;
+------------+
| pdd |
+------------+
| 0000-00-00 |
+------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
Query OK, 1 row affected (0.15 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)
mysql> SELECT * FROM date_test;
+------------+
| pdd |
+------------+
| 0000-00-00 |
| NULL |
+------------+
2 rows in set (0.00 sec)
SELECT alarm_id
,definition_description
,element_id
,TO_CHAR (alarm_datetime, 'YYYY-MM-DD HH24:MI:SS')
,severity
, problem_text
,status
FROM aircom.alarms
WHERE status = 1
AND TO_char (alarm_datetime,'DD.MM.YYYY HH24:MI:SS') > TO_DATE ('07.09.2008 09:43:00', 'DD.MM.YYYY HH24:MI:SS')
ORDER BY ALARM_DATETIME DESC
In general, to provide your own formula you should use arguments x
and y
that will correspond to values you provided in ggplot()
- in this case x
will be interpreted as x.plot
and y
as y.plot
. You can find more information about smoothing methods and formula via the help page of function stat_smooth()
as it is the default stat used by geom_smooth()
.
ggplot(data,aes(x.plot, y.plot)) +
stat_summary(fun.data=mean_cl_normal) +
geom_smooth(method='lm', formula= y~x)
If you are using the same x and y values that you supplied in the ggplot()
call and need to plot the linear regression line then you don't need to use the formula inside geom_smooth()
, just supply the method="lm"
.
ggplot(data,aes(x.plot, y.plot)) +
stat_summary(fun.data= mean_cl_normal) +
geom_smooth(method='lm')
This expands on the answer by Denis Bubnov.
I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.
{% set count = 0 %}
{% for anchor in items %}
{% if anchor.content['#paragraph'].field_anchor_link.0.value %}
{% set count = count + 1 %}
{% endif %}
{% endfor %}
{% if count > 0 %}
--- build the toc here --
{% endif %}
Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"
Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.
If System.IO.File.Exists(SavePath) Then
'The file exists
Else
'the file doesn't exist
End If
The quickest and easiest way to fix this is to do a find and replace on your date seperator, with the same separator. For example in this case Find "-" and Replace with "-", not sure why this works but you will find all dates are right-aligned as they should be after doing this.
You can use:
$("#tagscloud span").text("Your text here");
The same code will also work for the second case. You could also use:
$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");
Awesome answers! I was able to use Spannable to build rainbow colored text (so this could be repeated for any array of colors). Here's my method, if it helps anyone:
private Spannable buildRainbowText(String pack_name) {
int[] colors = new int[]{Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE};
Spannable word = new SpannableString(pack_name);
for(int i = 0; i < word.length(); i++) {
word.setSpan(new ForegroundColorSpan(colors[i]), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return word;
}
And then I just setText(buildRainboxText(pack_name)); Note that all of the words I pass in are under 15 characters and this just repeats 5 colors 3 times - you'd want to adjust the colors/length of the array for your usage!
Uninstall mysql service through command prompt using the following command.
sc delete mysql
restart XAMPP
To make it simple, let us say that we can use constructor based dependency injection for mandatory dependencies and setter based injection for optional dependencies. It is a rule of thumb!!
Let's say for example.
If you want to instantiate a class you always do it with its constructor. So if you are using constructor based injection, the only way to instantiate the class is through that constructor. If you pass the dependency through constructor it becomes evident that it is a mandatory dependency.
On the other hand, if you have a setter method in a POJO class, you may or may not set value for your class variable using that setter method. It is completely based on your need. i.e. it is optional. So if you pass the dependency through setter method of a class it implicitly means that it is an optional dependency. Hope this is clear!!
intern ? symbol Returns the Symbol corresponding to str, creating the symbol if it did not previously exist
"edition".intern # :edition
Variables can contain single quotes.
myvar=\'....$variable\'
repo forall -c $myvar
Your result object is a jQuery element, not a javascript array. The array you wish must be under .get()
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array. http://api.jquery.com/map/
Given code:
var thetop = 'top';
<something>.stop().animate(
{ thetop : 10 }, 10
);
Translation:
var thetop = 'top';
var config = { thetop : 10 }; // config.thetop = 10
<something>.stop().animate(config, 10);
As you can see, the { thetop : 10 }
declaration doesn't make use of the variable thetop
. Instead it creates an object with a key named thetop
. If you want the key to be the value of the variable thetop
, then you will have to use square brackets around thetop
:
var thetop = 'top';
var config = { [thetop] : 10 }; // config.top = 10
<something>.stop().animate(config, 10);
The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:
var thetop = 'top';
var config = (
obj = {},
obj['' + thetop] = 10,
obj
); // config.top = 10
<something>.stop().animate(config, 10);
See at the bottom of this page at Python wiki, there are at least 2 options to "unescape" html.
LinearLayout YOUR_LinearLayout =(LinearLayout)findViewById(R.id.YOUR_LinearLayout)
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ 100,
/*weight*/ 1.0f
);
YOUR_LinearLayout.setLayoutParams(param);
It is explained pretty well here: Display a view from another controller in ASP.NET MVC
To quote @Womp:
By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\
,
but after that, if it doesn't find the view, it checks in \Views\Shared
.
ASP MVC's idea is "convention over configuration" which means moving the view to the shared folder is the way to go in such cases.
Since 0.14.1, you can now do nlargest
and nsmallest
on a groupby
object:
In [23]: df.groupby('id')['value'].nlargest(2)
Out[23]:
id
1 2 3
1 2
2 6 4
5 3
3 7 1
4 8 1
dtype: int64
There's a slight weirdness that you get the original index in there as well, but this might be really useful depending on what your original index was.
If you're not interested in it, you can do .reset_index(level=1, drop=True)
to get rid of it altogether.
(Note: From 0.17.1 you'll be able to do this on a DataFrameGroupBy too but for now it only works with Series
and SeriesGroupBy
.)
first of all, try to give the format you want to the current date time of your server:
Obtain current date time
$current_date = getdate();
Separate date and time to manage them as you wish:
$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday]; $current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
Compare it depending if you are using donly date or datetime in your DB:
$today = $current_date_only.' '.$current_time_only;
or
$today = $current_date_only;
if($today < $expireDate)
hope it helps
probably the onclick
handler should read onclick='hello();'
instead of onclick=hello();
With regard to Brent.Longborough's answer (appering only on page 2 onward), perhaps you need to set the \thispagestyle{} after \begin{document}. I wonder if the letter class is setting the first page style to empty.
@main:
$ su
$ yum install MySQL-python
and it will be installed (MySQLdb).
You Can Try This._x000D_
<?php_x000D_
$content = str_replace(PHP_EOL, "<br>", $your_content);_x000D_
?>_x000D_
_x000D_
<p><?php echo($content); ?></p>
_x000D_
#include <stdio.h>
#include <conio.h>
int main()
{
int i,j;
int b=0;
for (i=2;i<=100;i++){
for (j=2;j<=i;j++){
if (i%j==0){
break;
}
}
if (i==j)
print f("\n%d",j);
}
getch ();
}
I usually use selectors in my main stylesheet, then make an ie6 specific .js (jquery) file that adds a class to all of the input types. Example:
$(document).ready(function(){
$("input[type='text']").addClass('text');
)};
And then just duplicate my styles in the ie6 specific stylesheet using the classes. That way the actual markup is a little bit cleaner.
On CentOS Linux release 7.5.1804, we were able to make this work by editing /etc/selinux/config and changing the setting of SELINUX like so:
SELINUX=disabled
Assuming you know how big the item in the vector are:
std::vector<int> myArray;
myArray.resize (item_count, 0);
memcpy (&myArray.front(), source, item_count * sizeof(int));
comment out both "Default env_reset" and "Default secure_path ..." in /etc/sudores file works for me
Use BOOST_BINARY (Yes, you can use it in C).
#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);
This macro is expanded to an octal literal during preprocessing.
You didnt specify the platform you use, so I assume it's a Mac ;-)
What I do is use a proxy. I use SquidMan, a standalone implementation of Squid
I start SquidMan on the Mac, then on the iPhone I enter the Proxy params in the General/Wifi Settings.
Then I can watch the HTTP trafic in the Console App, looking at the squid-access.log
If I need more infos, I switch to tcpdump, but I suppose WireShark should work too.
I had a momentary 5 minute lapse and I forgot to specify the form in full like this:
myformName.ActiveForm.TopMost = true;
But what I really wanted was THIS!
this.TopMost = true;
Correct me if I am wrong. By doing
[button setSelected:YES];
you are clearly changing the state of the buttons as selected. So naturally by the code you have provided the image will that for the selected state in your case checked.png
You can follow this pattern also
<form action="/action_page.php">
E-mail: <input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
<input type="submit">
</form>
Ref : In W3Schools
Try to use a
$(window).load
eventor
$(document).ready
because the initial values may be inconstant because of changes that occur during the parsing or during the DOM load.
Yes, that's possible:
$("#id-of-button").click(function() {
var bg_url = $('#div1').css('background-image');
// ^ Either "none" or url("...urlhere..")
bg_url = /^url\((['"]?)(.*)\1\)$/.exec(bg_url);
bg_url = bg_url ? bg_url[2] : ""; // If matched, retrieve url, otherwise ""
alert(bg_url);
});
import pandas as pd
import numpy as np
# example DataFrame
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
# count the NaNs in a column
num_nan_a = df.loc[ (pd.isna(df['a'])) , 'a' ].shape[0]
num_nan_b = df.loc[ (pd.isna(df['b'])) , 'b' ].shape[0]
# summarize the num_nan_b
print(df)
print(' ')
print(f"There are {num_nan_a} NaNs in column a")
print(f"There are {num_nan_b} NaNs in column b")
Gives as output:
a b
0 1.0 NaN
1 2.0 1.0
2 NaN NaN
There are 1 NaNs in column a
There are 2 NaNs in column b
This can happen if you call
.SingleOrDefault()
on an IEnumerable with 2 or more elements.
Alternative solution (you can replace createElement with a your own element)
var mvar = $('.mbox').wrapAll(document.createElement('div')).closest('div').text();
console.log(mvar);
suppose we take a integer in string.
String s="100"; int i=Integer.parseInt(s); or int i=Integer.valueOf(s);
but in your question the number you are trying to do the change is the whole number
String s="10.00";
double d=Double.parseDouble(s);
int i=(int)d;
This way you get the answer of the value which you are trying to get it.
You can add/remove Appender programmatically to Log4j:
ConsoleAppender console = new ConsoleAppender(); //create appender
//configure the appender
String PATTERN = "%d [%p|%c|%C{1}] %m%n";
console.setLayout(new PatternLayout(PATTERN));
console.setThreshold(Level.FATAL);
console.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(console);
FileAppender fa = new FileAppender();
fa.setName("FileLogger");
fa.setFile("mylog.log");
fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
fa.setThreshold(Level.DEBUG);
fa.setAppend(true);
fa.activateOptions();
//add appender to any Logger (here is root)
Logger.getRootLogger().addAppender(fa);
//repeat with all other desired appenders
I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with
Logger.getRootLogger().getLoggerRepository().resetConfiguration();
and start with adding your own. You need log4j in the classpath of course for this to work.
Remark:
You can take any Logger.getLogger(...)
you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).
If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:
Logger fizz = LoggerFactory.getLogger("com.fizz")
will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to
Logger.getLogger("com.fizz").addAppender(newAppender)
then logging from fizz
will be handled by alle the appenders from the root logger and the newAppender
.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.
You are running into CORS issues.
There are several ways to fix/workaround this.
More verbosely, you are trying to access api.serverurl.com from localhost. This is the exact definition of cross domain request.
By either turning it off just to get your work done (OK, but poor security for you if you visit other sites and just kicks the can down the road) you can use a proxy which makes your browser think all requests come from local host when really you have local server that then calls the remote server.
so api.serverurl.com might become localhost:8000/api and your local nginx or other proxy will send to the correct destination.
Now by popular demand, 100% more CORS info....same great taste!
Bypassing CORS is exactly what is shown for those simply learning the front end. https://codecraft.tv/courses/angular/http/http-with-promises/
In Visual Studio:
Properties ->
Advanced ->
Entry Point ->
write just the name of the function you want the program to begin running from, case sensitive, without any brackets and command line arguments.
The answer from Shivam Kotwalia works perfectly. However, the object is imported as a byte type. Sometimes you may need it as a string for performing REGEX or something like that.
I recommend the following code (two lines from Shivam Kotwalia's answer) :
import textract
text = textract.process("path/to/file.extension")
text = text.decode("utf-8")
The last line will convert the object text to a string.
Yes, 1 byte does encode a character (inc spaces etc) from the ASCII set. However in data units assigned to character encoding it can and often requires in practice up to 4 bytes. This is because English is not the only character set. And even in English documents other languages and characters are often represented. The numbers of these are very many and there are very many other encoding sets, which you may have heard of e.g. BIG-5, UTF-8, UTF-32. Most computers now allow for these uses and ensure the least amount of garbled text (which usually means a missing encoding set.) 4 bytes is enough to cover these possible encodings. I byte per character does not allow for this and in use it is larger often 4 bytes per possible character for all encodings, not just ASCII. The final character may only need a byte to function or be represented on screen, but requires 4 bytes to be located in the rather vast global encoding "works".
Using a simple list-comprehension
and the sum
:
>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5
Use the display: inline
CSS property.
Ideal: In the stylesheet:
#container p { display: inline }
Bad/Extreme situation: Inline:
<p style="display:inline">...</p>
If you are using brew with python, unfortunately, pip/pip3 ships with very limited options. You do not have --install-option, --target, --user options as mentioned above.
Note on pip install --user
The normal pip install --user is disabled for brewed Python. This is because of a bug in distutils, because Homebrew writes a distutils.cfg which sets the package prefix. A possible workaround (which puts executable scripts in ~/Library/Python/./bin) is:python -m pip install --user --install-option="--prefix=" <package-name>
You might find this line very cumbersome. I suggest use pyenv for management. If you are using
brew upgrade python python3
Ironically you are actually downgrade pip functionality.
(I post this answer, simply because pip in my mac osx does not have --target option, and I have spent hours fixing it)
For UIViewController
just load your view again -
func rightButtonAction() {
if isEditProfile {
print("Submit Clicked, Call Update profile API")
isEditProfile = false
self.viewWillAppear(true)
} else {
print("Edit Clicked, Call Edit profile API")
isEditProfile = true
self.viewWillAppear(true)
}
}
I am loading my view controller on profile edit and view profile. According to the Bool value isEditProfile
updating the view in viewWillAppear
method.
using System.IO;
this next code contains 2 methods of reading the text, the first will read single lines and stores them in a string variable, the second one reads the whole text and saves it in a string variable(including "\n" (enters))
both should be quite easy to understand and use.
string pathToFile = "";//to save the location of the selected object
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(theDialog.FileName.ToString());
pathToFile = theDialog.FileName;//doesn't need .tostring because .filename returns a string// saves the location of the selected object
}
if (File.Exists(pathToFile))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this
{
//method1
string firstLine = File.ReadAllLines(pathToFile).Skip(0).Take(1).First();//selects first line of the file
string secondLine = File.ReadAllLines(pathToFile).Skip(1).Take(1).First();
//method2
string text = "";
using(StreamReader sr =new StreamReader(pathToFile))
{
text = sr.ReadToEnd();//all text wil be saved in text enters are also saved
}
}
}
To split the text you can use .Split(" ") and use a loop to put the name back into one string. if you don't want to use .Split() then you could also use foreach and ad an if statement to split it where needed.
to add the data to your class you can use the constructor to add the data like:
public Employee(int EMPLOYEENUM, string NAME, string ADRESS, double WAGE, double HOURS)
{
EmployeeNum = EMPLOYEENUM;
Name = NAME;
Address = ADRESS;
Wage = WAGE;
Hours = HOURS;
}
or you can add it using the set by typing .variablename after the name of the instance(if they are public and have a set this will work). to read the data you can use the get by typing .variablename after the name of the instance(if they are public and have a get this will work).
If you want pure swift, we released our internal file. It's pretty simple
For Perfect DateTime
Match in SQL Server
SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC
You need to provide configurations considering your Spring Boot Version and the version of libraries it downloads based on the same.
Use below only if your Spring Boot setup has downloaded Hibernate v4.
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
Hibernate 5 doesn't support above.
If your Spring Boot Setup has downloaded Hibernate v5.x, then prefer below definition:
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
IMPORTANT:
In your Spring Boot application development, you should prefer to use annotation: @SpringBootApplication
which has been super-annotated with: @SpringBootConfiguration and @EnableAutoConfiguration
NOW If your entity classes are in different package than the package in which your Main Class resides, Spring Boot won't scan those packages.
Thus you need to explicitly define Annotation: @EntityScan(basePackages = { "com.springboot.entities" })
This annotation scans JPA based annotated entity classes (and others like MongoDB, Cassandra etc)
NOTE:
"com.springboot.entities" is the custom package name.
Following is the way I had defined Hibernate and JPA based properties at application.properties to create Tables:-
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3333/development?useSSL=true spring.datasource.username=admin
spring.datasource.password=spring.jpa.open-in-view=false
spring.jpa.hibernate.ddl-auto=create
spring.jpa.generate-ddl=true
spring.jpa.hibernate.use-new-id-generator-mappings=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.format_sql=true
I am able to create tables using my above mentioned configuration.
Refer it and change your code wherever applicable.
If you don't like split()
and you don't like matrix()
(with its dangling NAs), there's this:
chunk <- function(x, n) (mapply(function(a, b) (x[a:b]), seq.int(from=1, to=length(x), by=n), pmin(seq.int(from=1, to=length(x), by=n)+(n-1), length(x)), SIMPLIFY=FALSE))
Like split()
, it returns a list, but it doesn't waste time or space with labels, so it may be more performant.
Symbolic or soft link (files or directories, more flexible and self documenting)
# Source Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx
Hard link (files only, less flexible and not self documenting)
# Source Link
ln /home/jake/doc/test/2000/something /home/jake/xxx
More information: man ln
/home/jake/xxx
is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:
cd /home/jake/
ln -s /home/jake/doc/test/2000/something xxx
Try this:
Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse | Where-Object { $_.Attributes -ne "Directory"}
You can also do this without a variable
@{
'foo' = 222
'bar' = 333
'baz' = 444
'qux' = 555
} | % getEnumerator | % {
$_.key
$_.value
}
Basically, you want to loop through each direct descendent of the old-parent node, and move it to the new parent. Any children of a direct descendent will get moved with it.
var newParent = document.getElementById('new-parent');
var oldParent = document.getElementById('old-parent');
while (oldParent.childNodes.length > 0) {
newParent.appendChild(oldParent.childNodes[0]);
}
[<-
with mapply
is a bit faster than sapply
.
> dat[mapply(is.infinite, dat)] <- NA
With mnel's data, the timing is
> system.time(dat[mapply(is.infinite, dat)] <- NA)
# user system elapsed
# 15.281 0.000 13.750
When searching with [data-x=...], watch out, it doesn't work with jQuery.data(..) setter:
$('<b data-x="1">' ).is('[data-x=1]') // this works
> true
$('<b>').data('x', 1).is('[data-x=1]') // this doesn't
> false
$('<b>').attr('data-x', 1).is('[data-x=1]') // this is the workaround
> true
You can use this instead:
$.fn.filterByData = function(prop, val) {
return this.filter(
function() { return $(this).data(prop)==val; }
);
}
$('<b>').data('x', 1).filterByData('x', 1).length
> 1
Perhaps the best way would be to implement your app as a web app. I think you can also make web apps that run direct on the phone, without internet access or a remote server.
Web app, sounds lame? But a lot can be done with DHTML / HTML5 / JavaScript. It's a rare app that requires more power and couldn't be done as a web app. And you get pretty good cross platform with Web / JavaScript - the browsers vary a bit but a good web dev can write one web app that works pretty much everywhere.
Of course if you're writing a high-performance 3D game, the browser might not deliver what you need! maybe in a few years... Apparently some Google hackers ported Quake 2 to HTML5 already!
http://web.appstorm.net/roundups/browsers/10-html5-games-paving-the-way/
global static variables are initialized at compile-time unlike automatic
There are a couple of ways of doing I first did the way Grendal2501 did it. I then did it similar to user15163, you can store the image URL in the firebase and host the image on your firebase host or also Amazon S3;
As well as escaping quotes with backslashes, also see SO question 2911073 which explains how you could alternatively use double-quoting in a @-prefixed string:
string msg = @"I want to learn ""c#""";
In my case a misplaced session.clear()
was causing this problem.
Short snippet for future visitors - how to center horizontal table-cell (+ vertically)
html, body {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.tab {_x000D_
display: table;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center; /* the key */_x000D_
background-color: #EEEEEE;_x000D_
}_x000D_
_x000D_
.content {_x000D_
display: inline-block; /* important !! */_x000D_
width: 100px;_x000D_
background-color: #00FF00;_x000D_
}
_x000D_
<div class="tab">_x000D_
<div class="cell">_x000D_
<div class="content" id="a">_x000D_
<p>Content</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
I believe that your problem is that you're checking for an empty string using double quotes instead of single quotes. Try just changing to:
DELETE FROM table WHERE edit_user=''
IoC concept was initially heard during the procedural programming era. Therefore from a historical context IoC talked about inversion of the ownership of control-flow i.e. who owns the responsibility to invoke the functions in the desired order - whether it's the functions themselves or should you invert it to some external entity.
However once the OOP emerged, people began to talk about IoC in OOP context where applications are concerned with object creation and their relationships as well, apart from the control-flow. Such applications wanted to invert the ownership of object-creation (rather than control-flow) and required a container which is responsible for object creation, object life-cycle & injecting dependencies of the application objects thereby eliminating application objects from creating other concrete object.
In that sense DI is not the same as IoC, since it's not about control-flow, however it's a kind of Io*, i.e. Inversion of ownership of object-creation.
all numbers are stored in binary. if you want a textual representation of a given number in binary, use bin(i)
>>> bin(10)
'0b1010'
>>> 0b1010
10
as @Jérémy Reynaud pointing out, as described in this answer, the safest way to set the left drawable without changing the values of the other drawables (top, right, and bottom) is by using the previous values from the button with setCompoundDrawablesWithIntrinsicBounds:
Drawable leftDrawable = getContext().getResources()
.getDrawable(R.drawable.yourdrawable);
// Or use ContextCompat
// Drawable leftDrawable = ContextCompat.getDrawable(getContext(),
// R.drawable.yourdrawable);
Drawable[] drawables = button.getCompoundDrawables();
button.setCompoundDrawablesWithIntrinsicBounds(leftDrawable,drawables[1],
drawables[2], drawables[3]);
So all your previous drawable will be preserved.
I prefer the other methods already posted, but some people like to use:
case "$HOST" in
user1|node*)
echo "yes";;
*)
echo "no";;
esac
Edit:
I've added your alternates to the case statement above
In your edited version you have too many brackets. It should look like this:
if [[ $HOST == user1 || $HOST == node* ]];
char a[]="string";
int toBeRemoved=2;
memmove(&a[toBeRemoved],&a[toBeRemoved+1],strlen(a)-toBeRemoved);
puts(a);
Try this . memmove will overlap it. Tested.
declare @tab table(FirstName varchar(100))
insert into @tab values('John'),('Sarah'),('George')
SELECT *
FROM @tab
WHERE 'John' in (FirstName)
document.forms[0].elements[0].focus();
This can be refined using a loop to eg. not focus certain types of field, disabled fields and so on. Better may be to add a class="autofocus" to the field you actually do want focused, and loop over forms[i].elements[j] looking for that className.
Anyhow: it's not normally a good idea to do this on every page. When you focus an input the user loses the ability to eg. scroll the page from the keyboard. If unexpected, this can be annoying, so only auto-focus when you're pretty sure that using the form field is going to be what the user wants to do. ie. if you're Google.
You have to use the escaped unicode :
Like
.breadcrumbs a:before {
content: '\0000a0';
}
More info on : http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/
Three options here.
Standard JavaScript answer: Use a framework! Most Ajax frameworks will have abstracted you an easy way to make an XMLHTTPRequest POST.
Make the XMLHTTPRequest request yourself, passing post into the open method instead of get. (More information in Using POST method in XMLHTTPRequest (Ajax).)
Via JavaScript, dynamically create a form, add an action, add your inputs, and submit that.
Access it like any other pointer value:
std::vector<int>* v = new std::vector<int>();
v->push_back(0);
v->push_back(12);
v->push_back(1);
int twelve = v->at(1);
int one = (*v)[2];
// iterate it
for(std::vector<int>::const_iterator cit = v->begin(), e = v->end;
cit != e; ++cit)
{
int value = *cit;
}
// or, more perversely
for(int x = 0; x < v->size(); ++x)
{
int value = (*v)[x];
}
// Or -- with C++ 11 support
for(auto i : *v)
{
int value = i;
}
Use the following statement: SHOW INDEX FROM your_table
And then check the result for the fields: row["Table"], row["Key_name"]
Make sure you write "Key_name" correctly
by using jquery to register .mousemove to document to change the image .css left and top to event.pageX and event.pageY.
example as below http://jsfiddle.net/BfLAh/1/
$(document).mousemove(function(e) {
$("#follow").css({
left: e.pageX,
top: e.pageY
});
});
_x000D_
#follow {
position: absolute;
text-align: center;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follow"><img src="https://placekitten.com/96/140" /><br>Kitteh</br>
</div>
_x000D_
updated to follow slowly
for the orientation , you need to get the current css left and css top and compare with event.pageX and event.pageY , then set the image orientation with
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
for the speed , you can set the jquery .animation duration to certain amount.
As Sven mentioned, x[[[0],[2]],[1,3]]
will give back the 0 and 2 rows that match with the 1 and 3 columns while x[[0,2],[1,3]]
will return the values x[0,1] and x[2,3] in an array.
There is a helpful function for doing the first example I gave, numpy.ix_
. You can do the same thing as my first example with x[numpy.ix_([0,2],[1,3])]
. This can save you from having to enter in all of those extra brackets.
In case the OP really wanted an ICMP-Ping, there are some proposals within the User Contributed Notes to socket_create()
[link], which use raw sockets. Be aware that on UNIX like systems root access is required.
Update: note that the usec
argument has no function on windows. Minimum timeout is 1 second.
In any case, this is the code of the top voted ping function:
function ping($host, $timeout = 1) {
/* ICMP ping packet with a pre-calculated checksum */
$package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
$socket = socket_create(AF_INET, SOCK_RAW, 1);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
socket_connect($socket, $host, null);
$ts = microtime(true);
socket_send($socket, $package, strLen($package), 0);
if (socket_read($socket, 255)) {
$result = microtime(true) - $ts;
} else {
$result = false;
}
socket_close($socket);
return $result;
}
You can use string formatting:
>>> a=42
>>> b="bar"
>>> "The number is %d and the word is %s" % (a,b)
'The number is 42 and the word is bar'
But this is removed in Python 3, you should use "str.format()":
>>> a=42
>>> b="bar"
>>> "The number is {0} and the word is {1}".format(a,b)
'The number is 42 and the word is bar'
When you use --user
option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.
The location of user's packages folder can be found using:
python -m site --user-site
This will print something like:
C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages
When you don't use --user
option with pip, the package gets installed in global folder given by:
python -c "import site; print(site.getsitepackages())"
This will print something like:
['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'
Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.
Here is a Ray Wenderlich tutorial that shows you how to use AutoLayout to dynamically size UITableViewCell
s. I would think it would be the same for UICollectionViewCell
.
Basically, though, you end up dequeueing and configuring a prototype cell and grabbing its height. After reading this article, I decided to NOT implement this method and just write some clear, explicit sizing code.
Here's what I consider the "secret sauce" for the entire article:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [self heightForBasicCellAtIndexPath:indexPath];
}
- (CGFloat)heightForBasicCellAtIndexPath:(NSIndexPath *)indexPath {
static RWBasicCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.tableView dequeueReusableCellWithIdentifier:RWBasicCellIdentifier];
});
[self configureBasicCell:sizingCell atIndexPath:indexPath];
return [self calculateHeightForConfiguredSizingCell:sizingCell];
}
- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell {
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height + 1.0f; // Add 1.0f for the cell separator height
}
Once you've done that, code like the following will get you going:
// ViewController.m
#import "ViewController.h"
#import "CollectionViewCell.h"
@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout> {
}
@property (weak, nonatomic) IBOutlet CollectionViewCell *cell;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor lightGrayColor];
[self.collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(@"viewDidAppear...");
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 50;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 10.0f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
return 10.0f;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return [self sizingForRowAtIndexPath:indexPath];
}
- (CGSize)sizingForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *title = @"This is a long title that will cause some wrapping to occur. This is a long title that will cause some wrapping to occur.";
static NSString *subtitle = @"This is a long subtitle that will cause some wrapping to occur. This is a long subtitle that will cause some wrapping to occur.";
static NSString *buttonTitle = @"This is a really long button title that will cause some wrapping to occur.";
static CollectionViewCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [[NSBundle mainBundle] loadNibNamed:@"CollectionViewCell" owner:self options:nil][0];
});
[sizingCell configureWithTitle:title subtitle:[NSString stringWithFormat:@"%@: Number %d.", subtitle, (int)indexPath.row] buttonTitle:buttonTitle];
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGSize cellSize = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
NSLog(@"cellSize: %@", NSStringFromCGSize(cellSize));
return cellSize;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *title = @"This is a long title that will cause some wrapping to occur. This is a long title that will cause some wrapping to occur.";
static NSString *subtitle = @"This is a long subtitle that will cause some wrapping to occur. This is a long subtitle that will cause some wrapping to occur.";
static NSString *buttonTitle = @"This is a really long button title that will cause some wrapping to occur.";
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
[cell configureWithTitle:title subtitle:[NSString stringWithFormat:@"%@: Number %d.", subtitle, (int)indexPath.row] buttonTitle:buttonTitle];
return cell;
}
@end
The code above (along with a very basic UICollectionViewCell
subclass and associated XIB) gives me this:
This header is getting somehow deprecated. You can read more about it here - X-XSS-Protection
- Chrome has removed their XSS Auditor
- Firefox has not, and will not implement X-XSS-Protection
- Edge has retired their XSS filter
This means that if you do not need to support legacy browsers, it is recommended that you use Content-Security-Policy without allowing unsafe-inline scripts instead.
While I would recommend against this.
But you can use shutdown as client if the target machine has remote shutdown enabled and is in the same workgroup.
Example:
shutdown.exe /s /m \\<target-computer-name> /t 00
replacing <target-computer-name>
with the URI for the target machine,
Otherwise, if you want to trigger this through Apache, you'll need to configure the batch script as a CGI script by putting AddHandler cgi-script .bat
and Options +ExecCGI
into either a local .htaccess
file or in the main configuration for your Apache install.
Then you can just call the .bat
file containing the shutdown.exe
command from your browser.
Refer to following links:
You cannot pass more than three arguments, if you want to pass only 1 argument then use void for the other two arguments.
1. private class DownloadFilesTask extends AsyncTask<URL, Integer, Long>
2. protected class InitTask extends AsyncTask<Context, Integer, Integer>
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
KPBird
The identity
section goes under the system.web
section, not under authentication
:
<system.web>
<authentication mode="Windows"/>
<identity impersonate="true" userName="foo" password="bar"/>
</system.web>
If you want window handles for ALL of your application's Window
s for some reason, you can use the Application.Windows
property to get at all the Windows and then use WindowInteropHandler
to get at their handles as you have already demonstrated.
Use -
new Select(driver.findElement(By.id("gender"))).selectByVisibleText("Germany");
Of course, you need to import org.openqa.selenium.support.ui.Select;
In my case I had a wrong maven directory structure.
Which should be like:
/src/test/java/ com.myproject.server.MyTest
After I fixed that - everything worked like a charm.
Some generic help:
gdb start GDB, with no debugging les
gdb program begin debugging program
gdb program core debug coredump core produced by program
gdb --help describe command line options
First of all, find the directory where the corefile is generated.
Then use ls -ltr
command in the directory to find the latest generated corefile.
To load the corefile use
gdb binary path of corefile
This will load the corefile.
Then you can get the information using the bt
command.
For a detailed backtrace use bt full
.
To print the variables, use print variable-name
or p variable-name
To get any help on GDB, use the help
option or use apropos search-topic
Use frame frame-number
to go to the desired frame number.
Use up n
and down n
commands to select frame n frames up and select frame n frames down respectively.
To stop GDB, use quit
or q
.
If you are using GitHub Desktop
, then just do the following steps:
GitHub Desktop
and all other applications with open files to your current directory path.GitHub Desktop
and click on the blue (!) "repository not found" icon. Then a dialog will open and you will see a "Locate..." button which will open a popup allowing you to direct its path to a new location.You could do:
svn revert -R .
This will not delete any new file not under version control. But you can easily write a shell script to do that like:
for file in `svn status|grep "^ *?"|sed -e 's/^ *? *//'`; do rm $file ; done
There is a workaround to guarantee that one handler happens after another: attach the second handler to a containing element and let the event bubble up. In the handler attached to the container, you can look at event.target and do something if it's the one you're interested in.
Crude, maybe, but it definitely should work.
Put the frame in a VisualBrush:
VisualBrush brush = new VisualBrush { TileMode = TileMode.None };
brush.Visual = frame;
brush.AlignmentX = AlignmentX.Center;
brush.AlignmentY = AlignmentY.Center;
brush.Stretch = Stretch.Uniform;
Put the VisualBrush in GeometryDrawing
GeometryDrawing drawing = new GeometryDrawing();
drawing.Brush = brush;
// Brush this in 1, 1 ratio
RectangleGeometry rect = new RectangleGeometry { Rect = new Rect(0, 0, 1, 1) };
drawing.Geometry = rect;
Now put the GeometryDrawing in a DrawingImage:
new DrawingImage(drawing);
Place this on your source of the image, and voilĂ !
You could do it a lot easier though:
<Image>
<Image.Source>
<BitmapImage UriSource="/yourassembly;component/YourImage.PNG"></BitmapImage>
</Image.Source>
</Image>
And in code:
BitmapImage image = new BitmapImage { UriSource="/yourassembly;component/YourImage.PNG" };
In Loops, I always prefer to use the Cells
class, using the R1C1 reference method, like this:
Cells(rr, col).Formula = ...
This allows me to quickly and easily loop over a Range of cells easily:
Dim r As Long
Dim c As Long
c = GetTargetColumn() ' Or you could just set this manually, like: c = 1
With Sheet1 ' <-- You should always qualify a range with a sheet!
For r = 1 To 10 ' Or 1 To (Ubound(MyListOfStuff) + 1)
' Here we're looping over all the cells in rows 1 to 10, in Column "c"
.Cells(r, c).Value = MyListOfStuff(r)
'---- or ----
'...to easily copy from one place to another (even with an offset of rows and columns)
.Cells(r, c).Value = Sheet2.Cells(r + 3, 17).Value
Next r
End With
I had a slighlty different scenario. My checkboxes were created in dynamic and they were not of same group. But atleast any one of them had to be checked. My approach (never say this is perfect), I created a genric validator for all of them:
jQuery.validator.addMethod("validatorName", function(value, element) {
if (($('input:checkbox[name=chkBox1]:checked').val() == "Val1") ||
($('input:checkbox[name=chkBox2]:checked').val() == "Val2") ||
($('input:checkbox[name=chkBox3]:checked').val() == "Val3"))
{
return true;
}
else
{
return false;
}
}, "Please Select any one value");
Now I had to associate each of the chkbox to this one single validator.
Again I had to trigger the validation when any of the checkboxes were clicked triggering the validator.
$('#piRequest input:checkbox[name=chkBox1]').click(function(e){
$("#myform").valid();
});
The basic syntax for using ternary operator is like this:
(condition) ? (if_true) : (if_false)
For you case it is like this:
number < 0 ? bigInt.sign = 0 : bigInt.sign = 1;
The DATEADD() function adds or subtracts a specified time interval from a date.
DATEADD(datepart,number,date)
datepart(interval) can be hour, second, day, year, quarter, week etc; number (increment int); date(expression smalldatetime)
For example if you want to add 30 days to current date you can use something like this
select dateadd(dd, 30, getdate())
To Substract 30 days from current date
select dateadd(dd, -30, getdate())
[x for x in range(len(testlist)) if testlist[x]==1]
in ts, [].push(bufferPart) is not compatible;
so:
getBufferFromStream(stream: Part | null): Promise<Buffer> {
if (!stream) {
throw 'FILE_STREAM_EMPTY';
}
return new Promise(
(r, j) => {
let buffer = Buffer.from([]);
stream.on('data', buf => {
buffer = Buffer.concat([buffer, buf]);
});
stream.on('end', () => r(buffer));
stream.on('error', j);
}
);
}
I guess an exact answer to your question would be:
Setting an intial size on an ArrayList reduces the nr. of times internal memory re-allocation has to occur. The list is backed by an array. If you specify i.e. initial capacity 0, already at the first insertion of an element the internal array would have to be resized. If you have an approximate idea of how many elements your list would hold, setting the initial capacity would reduce the nr. of memory re-allocations happening while you use the list.
This is portable - at least between ORACLE and PostgreSQL:
select t.* from table t
where not exists(select 1 from table ti where ti.attr > t.attr);
Update The currently suggested way to start a Task is simply using Task.Run()
Task.Run(() => foo());
Note that this method is described as the best way to start a task see here
Previous answer
I like the Task Factory from System.Threading.Tasks. You can do something like this:
Task.Factory.StartNew(() =>
{
// Whatever code you want in your thread
});
Note that the task factory gives you additional convenience options like ContinueWith:
Task.Factory.StartNew(() => {}).ContinueWith((result) =>
{
// Whatever code should be executed after the newly started thread.
});
Also note that a task is a slightly different concept than threads. They nicely fit with the async/await keywords, see here.
Go to AWS Billing, then reports, then AWS Usage reports. Select Amazon Simple Storage Service, then Operation StandardStorage. Then you can download a CSV file that includes a UsageType of StorageObjectCount that lists the item count for each bucket.
The proper way would be to use $_SERVER["PHP_SELF"]
(in conjunction with htmlspecialchars
to avoid possible exploits). You can also just skip the action=
part empty, which is not W3C valid, but currently works in most (all?) browsers - the default is to submit to self if it's empty.
Here is an example form that takes a name and email, and then displays the values you have entered upon submit:
<?php if (!empty($_POST)): ?>
Welcome, <?php echo htmlspecialchars($_POST["name"]); ?>!<br>
Your email is <?php echo htmlspecialchars($_POST["email"]); ?>.<br>
<?php else: ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<input type="submit">
</form>
<?php endif; ?>
I will make it simple,
Major difference is in require, entire JS file is called or imported. Even if you don't need some part of it.
var myObject = require('./otherFile.js'); //This JS file will be imported fully.
Whereas in import you can extract only objects/functions/variables which are required.
import { getDate }from './utils.js';
//Here I am only pulling getDate method from the file instead of importing full file
Another major difference is you can use require
anywhere in the program where as import
should always be at the top of file
There is built in functionality for this using the JavaScriptSerializer Class:
var json = JavaScriptSerializer.Serialize(data);
A single tick represents one hundred nanoseconds or one ten-millionth of a second. FROM MSDN.
So 28 000 000 000 * 1/10 000 000 = 2 800 sec. 2 800 sec /60 = 46.6666min
Or you can do it programmaticly with TimeSpan:
static void Main()
{
TimeSpan ts = TimeSpan.FromTicks(28000000000);
double minutesFromTs = ts.TotalMinutes;
Console.WriteLine(minutesFromTs);
Console.Read();
}
Both give me 46 min and not 480 min...
It was changing the line endings (from Windows CRLF to Unix LF) in the .htaccess
file that fixed it for me.
This worked for me:
<a target="_blank" href="{{ entity.link }}">
<object type="application/x-shockwave-flash" data="{{ entity.file.path }}?clickTAG={{ entity.link }}" width="120" height="600" style="visibility: visible;">
<param name="quality" value="high">
<param name="play" value="true">
<param name="LOOP" value="false">
<param name="wmode" value="transparent">
<param name="allowScriptAccess" value="true">
</object>
</a>
result = spark.createDataFrame([('SpeciesId','int'), ('SpeciesName','string')],["col_name", "data_type"]);
for f in result.collect():
print (f.col_name)
All you need to do is use getCheckedRadioButtonId()
and isChecked()
method,
if(gender.getCheckedRadioButtonId()==-1)
{
Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
}
else
{
// get selected radio button from radioGroup
int selectedId = gender.getCheckedRadioButtonId();
// find the radiobutton by returned id
selectedRadioButton = (RadioButton)findViewById(selectedId);
Toast.makeText(getApplicationContext(), selectedRadioButton.getText().toString()+" is selected", Toast.LENGTH_SHORT).show();
}
https://developer.android.com/guide/topics/ui/controls/radiobutton.html
The truth is: 'you can't' in the sense that you posed the question. NAT happens outside of the protocol. There is no way for your machine's kernel to know how your NAT box is mapping from external to internal IP addresses. Other answers here offer tricks involving methods of talking to outside web sites.
In connection string, the first string is the base in web.config
SchedulingContext is the base parameter of Entity file.
<connectionStrings>
<add name="SchedulingContext" connectionString="Data Source=XXX\SQL2008R2DEV;Initial Catalog=YYY;Persist Security Info=True;User ID=sa;Password=XXX" providerName="System.Data.SqlClient"/>
You may directly write into your css file like this :
.content {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left:50%;_x000D_
transform: translate(-50%,-50%);_x000D_
}
_x000D_
<div class = "content" >_x000D_
_x000D_
<p> some text </p>_x000D_
</div>
_x000D_
The way I'd do this is:
="'"&K2
Ctrl+D
to fill it down to the length of Column K's values.You can stub a static void method like this:
PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());
Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed
More useful, you can capture the value passed to StaticResource.getResource() like this:
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
StaticResource.class, "getResource", captor.capture());
Then you can evaluate the String that was passed to StaticResource.getResource like this:
String resourceName = captor.getValue();
Wow, I found yet another case for this problem. None of the above worked. Eventually I used python's ability to introspect what was being loaded. For python 2.7 this means:
import imp
imp.find_module("cv2")
This turned up a completely unexpected "cv2.pyd" file in an Anaconda DLL directory that wasn't touched by multiple uninstall/install attempts. Python was looking there first and not finding my good installation. I deleted that cv2.pyd file and tried imp.find_module("cv2") again and python immediately found the right file and cv2 started working.
So if none of the other solutions work for you, make sure you use python introspection to see what file python is trying to load.
You should use only one mediaplayer object
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Your only option is to somehow clone the object.
See this stackoverflow question on how you can achieve this.
For simple JSON objects, the simplest way would be:
var newObject = JSON.parse(JSON.stringify(oldObject));
if you use jQuery, you can use:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:
In ES6 or TypeScript (2.1+):
var shallowCopy = { ...oldObject };
var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };
Note that if extraProp
is also a property on oldObject, its value will not be used because the extraProp : "abc"
is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.
You have to declare your functions before main()
(or declare the function prototypes before main()
)
As it is, the compiler sees my_print (my_string);
in main()
as a function declaration.
Move your functions above main()
in the file, or put:
void my_print (char *);
void my_print2 (char *);
Above main()
in the file.
here's my refactored version which accepts multiline/single as an option
public string ShowDialog(string text, string caption, bool isMultiline = false, int formWidth = 300, int formHeight = 200)
{
var prompt = new Form
{
Width = formWidth,
Height = isMultiline ? formHeight : formHeight - 70,
FormBorderStyle = isMultiline ? FormBorderStyle.Sizable : FormBorderStyle.FixedSingle,
Text = caption,
StartPosition = FormStartPosition.CenterScreen,
MaximizeBox = isMultiline
};
var textLabel = new Label
{
Left = 10,
Padding = new Padding(0, 3, 0, 0),
Text = text,
Dock = DockStyle.Top
};
var textBox = new TextBox
{
Left = isMultiline ? 50 : 4,
Top = isMultiline ? 50 : textLabel.Height + 4,
Multiline = isMultiline,
Dock = isMultiline ? DockStyle.Fill : DockStyle.None,
Width = prompt.Width - 24,
Anchor = isMultiline ? AnchorStyles.Left | AnchorStyles.Top : AnchorStyles.Left | AnchorStyles.Right
};
var confirmationButton = new Button
{
Text = @"OK",
Cursor = Cursors.Hand,
DialogResult = DialogResult.OK,
Dock = DockStyle.Bottom,
};
confirmationButton.Click += (sender, e) =>
{
prompt.Close();
};
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmationButton);
prompt.Controls.Add(textLabel);
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : string.Empty;
}
Make sure you have the latest version of Android Studio. The support library is included by default when you create new projects. If you are adding the Support Library to a project that doesn't have it, then you just need to add a single line to your app module's build.gradle file, and then sync gradle.
build.gradle
dependencies {
...
implementation 'com.android.support:appcompat-v7:27.1.1'
}
It should just be that easy, though there may be some things to note:
27.1.1
numbers that I have here to whatever it tells you to. You can also manually check what the latest revision is if you want to.implementation
keyword replaces compile
that was used in Android Studio 2.x. (What's the difference?)constraint-layout
or recyclerview
).For standard OS X installations of MySQL you will find my.cnf located in the /etc/ folder.
Steps to update this variable:
cd /etc/
.sudo vi my.cnf
.sudo find / -name 'my.cnf' 2>1
- this will hide the errors and only report the successfile file location).innodb_buffer_pool_size
, press i
to start making changes.wq
.My approach inherits StackPanel.
Usage:
<Controls:ItemSpacer Grid.Row="2" Orientation="Horizontal" Height="30" CellPadding="15,0">
<Label>Test 1</Label>
<Label>Test 2</Label>
<Label>Test 3</Label>
</Controls:ItemSpacer>
All that's needed is the following short class:
using System.Windows;
using System.Windows.Controls;
using System;
namespace Controls
{
public class ItemSpacer : StackPanel
{
public static DependencyProperty CellPaddingProperty = DependencyProperty.Register("CellPadding", typeof(Thickness), typeof(ItemSpacer), new FrameworkPropertyMetadata(default(Thickness), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnCellPaddingChanged));
public Thickness CellPadding
{
get
{
return (Thickness)GetValue(CellPaddingProperty);
}
set
{
SetValue(CellPaddingProperty, value);
}
}
private static void OnCellPaddingChanged(DependencyObject Object, DependencyPropertyChangedEventArgs e)
{
((ItemSpacer)Object).SetPadding();
}
private void SetPadding()
{
foreach (UIElement Element in Children)
{
(Element as FrameworkElement).Margin = this.CellPadding;
}
}
public ItemSpacer()
{
this.LayoutUpdated += PART_Host_LayoutUpdated;
}
private void PART_Host_LayoutUpdated(object sender, System.EventArgs e)
{
this.SetPadding();
}
}
}
This can be done with only a few lines of jQuery:
$(function(){
// make sure img is hidden - fade in
$('img').hide().fadeIn(2000);
// after 5 second timeout - fade out
setTimeout(function(){$('img').fadeOut(2000);}, 5000);
});?
see the fiddle below for a working example...
Replace \ with / in the path
import os
os.system("D:/xxx1/xxx2XMLnew/otr.bat ")
Yeah, IsNumeric is VB. Usually people use the TryParse() method, though it is a bit clunky. As you suggested, you can always write your own.
int i;
if (int.TryParse(string, out i))
{
}
Try using following command. I haven't tried it but I think it should work.
openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt
The workaround is simple. Just use the Uri().ToString() method and percent-encode white-spaces, if any, afterwards.
string path = new Uri("C:\my example?.txt").ToString().Replace(" ", "%20");
properly returns file:///C:/my%20example?.txt
Note that if you are using cMake version 3.12 or later, variable PythonInterp
and PythonLibs
has been changed into Python
.
So we use:
find_package(Python ${PY_VERSION} REQUIRED)
instead of:
find_package(PythonInterp ${PY_VERSION} REQUIRED)
find_package(PythonLibs ${PY_VERSION} REQUIRED)
see https://cmake.org/cmake/help/v3.12/module/FindPython.html for details.
Maybe this will help
http://www.math.utah.edu/docs/info/gawk_5.html
awk '$3 ~ /snow|snowman/' dummy_file
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
If you are looking for a difference expressed as a combination of years, months, and days, I would suggest this function:
function interval(date1, date2) {_x000D_
if (date1 > date2) { // swap_x000D_
var result = interval(date2, date1);_x000D_
result.years = -result.years;_x000D_
result.months = -result.months;_x000D_
result.days = -result.days;_x000D_
result.hours = -result.hours;_x000D_
return result;_x000D_
}_x000D_
result = {_x000D_
years: date2.getYear() - date1.getYear(),_x000D_
months: date2.getMonth() - date1.getMonth(),_x000D_
days: date2.getDate() - date1.getDate(),_x000D_
hours: date2.getHours() - date1.getHours()_x000D_
};_x000D_
if (result.hours < 0) {_x000D_
result.days--;_x000D_
result.hours += 24;_x000D_
}_x000D_
if (result.days < 0) {_x000D_
result.months--;_x000D_
// days = days left in date1's month, _x000D_
// plus days that have passed in date2's month_x000D_
var copy1 = new Date(date1.getTime());_x000D_
copy1.setDate(32);_x000D_
result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();_x000D_
}_x000D_
if (result.months < 0) {_x000D_
result.years--;_x000D_
result.months+=12;_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
// Be aware that the month argument is zero-based (January = 0)_x000D_
var date1 = new Date(2015, 4-1, 6);_x000D_
var date2 = new Date(2015, 5-1, 9);_x000D_
_x000D_
document.write(JSON.stringify(interval(date1, date2)));
_x000D_
This solution will treat leap years (29 February) and month length differences in a way we would naturally do (I think).
So for example, the interval between 28 February 2015 and 28 March 2015 will be considered exactly one month, not 28 days. If both those days are in 2016, the difference will still be exactly one month, not 29 days.
Dates with exactly the same month and day, but different year, will always have a difference of an exact number of years. So the difference between 2015-03-01 and 2016-03-01 will be exactly 1 year, not 1 year and 1 day (because of counting 365 days as 1 year).
You need to use runat="server"
like this:
<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>
You can use the runat=server attribute with any standard HTML element, and later use it from codebehind.
You need to put -1 to round half down and after that multiply by -1 like the example down bellow.
<script type="text/javascript">
function roundNumber(number, precision, isDown) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = 0;
if (isDown) {
tempNumber = -tempNumber;
roundedTempNumber = Math.round(tempNumber) * -1;
} else {
roundedTempNumber = Math.round(tempNumber);
}
return roundedTempNumber / factor;
}
</script>
<div class="col-sm-12">
<p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
</p>
<p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>
For Python 3.x
import urllib.request
from urllib.error import HTTPError
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
You can use
window.clipboardData.getData('Text')
to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard
Controller:
public JsonResult GetProductsData()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:5136/api/");
//HTTP GET
var responseTask = client.GetAsync("product");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<IList<product>>();
readTask.Wait();
var alldata = readTask.Result;
var rsproduct = from x in alldata
select new[]
{
Convert.ToString(x.pid),
Convert.ToString(x.pname),
Convert.ToString(x.pprice),
};
return Json(new
{
aaData = rsproduct
},
JsonRequestBehavior.AllowGet);
}
else //web api sent error response
{
//log response status here..
var pro = Enumerable.Empty<product>();
return Json(new
{
aaData = pro
},
JsonRequestBehavior.AllowGet);
}
}
}
public JsonResult InupProduct(string id,string pname, string pprice)
{
try
{
product obj = new product
{
pid = Convert.ToInt32(id),
pname = pname,
pprice = Convert.ToDecimal(pprice)
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:5136/api/product");
if(id=="0")
{
//insert........
//HTTP POST
var postTask = client.PostAsJsonAsync<product>("product", obj);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return Json(1, JsonRequestBehavior.AllowGet);
}
else
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
else
{
//update........
//HTTP POST
var postTask = client.PutAsJsonAsync<product>("product", obj);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return Json(1, JsonRequestBehavior.AllowGet);
}
else
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
}
/*context.InUPProduct(Convert.ToInt32(id),pname,Convert.ToDecimal(pprice));
return Json(1, JsonRequestBehavior.AllowGet);*/
}
catch (Exception ex)
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
public JsonResult deleteRecord(int ID)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:5136/api/product");
//HTTP DELETE
var deleteTask = client.DeleteAsync("product/" + ID);
deleteTask.Wait();
var result = deleteTask.Result;
if (result.IsSuccessStatusCode)
{
return Json(1, JsonRequestBehavior.AllowGet);
}
else
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
/* var data = context.products.Where(x => x.pid == ID).FirstOrDefault();
context.products.Remove(data);
context.SaveChanges();
return Json(1, JsonRequestBehavior.AllowGet);*/
}
catch (Exception ex)
{
return Json(0, JsonRequestBehavior.AllowGet);
}
}
$('#test').click(function() {_x000D_
var startDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("01.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
In Bootstrap 4:
class="font-weight-bold"
Or:
<strong>text</strong>
Two different approaches:
I think that #1 is a little more obvious about what's going on, although it can get tedious if you have too many return values. In that case, option #2 works fairly well, although there's some mental overhead involved in making specialized structs for this purpose.
As Michael said:
and
If you are using Ant and trying to build then you need to :
Specify tomcat location by <property name="tomcat-home" value="C:\xampp\tomcat" />
Add tomcat libs to your already defined path for jars by
<path id="libs">
<fileset includes="*.jar" dir="${WEB-INF}/lib" />
<fileset includes="*.jar" dir="${tomcat-home}/bin" />
<fileset includes="*.jar" dir="${tomcat-home}/lib" />
</path>
You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.
WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.
Generally speaking, many configurations files also go into WEB-INF.
As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).
I had the same error and google brought me to this question, so here is what I did, hoping that it helps others in a similar situation.
This is applicable for OS X.
Check in the Terminal which version of OpenSSL I had:
$ python3 -c "import ssl; print(ssl.OPENSSL_VERSION)"
>> OpenSSL 0.9.8zh 14 Jan 2016
As my version of OpenSSL was too old, the accepted answer did not work.
So I had to update OpenSSL. To do this, I updated Python to the latest version (from version 3.5 to version 3.6) with Homebrew, following some of the steps suggested here:
$ brew update
$ brew install openssl
$ brew install python3
Then I was having problems with the PATH and the version of python being used, so I just created a new virtualenv
making sure that the newest version of python was taken:
$ virtualenv webapp --python=python3.6
Issue solved.
I recently went through the exact same experience in my workplace and found most of them knew the theoretical benefits but had to be sold on the benefits to them specifically, so here were the points I used (successfully):
and the big one...
I asked the same question to Xamarin support team, they replied with following:
You can develop an app with Xamarin for commercial usage - there is no extra charge! We only require you to comply with Visual Studio's licensing terms,
which means that in companies of less than 250 employees with less than $1million USD annual revenue, you may use Visual Studio completely free (including Xamarin) for up to 5 developers.
However after you pass those barriers, you would need a Visual Studio license (which includes Xamarin).
Refer the screenshot below.
http://wiki.whatwg.org/wiki/Implementations_in_Web_browsers has information maintained by the WHATWG community (and everyone who drops by and edits it).
Disclaimer: I'm a member of that community.
Apple states about NSSearchPathForDirectoriesInDomains(_:_:_:)
:
You should consider using the
FileManager
methodsurls(for:in:)
andurl(for:in:appropriateFor:create:)
which return URLs, which are the preferred format.
With Swift 5, FileManager
has a method called contentsOfDirectory(at:includingPropertiesForKeys:options:)
. contentsOfDirectory(at:includingPropertiesForKeys:options:)
has the following declaration:
Performs a shallow search of the specified directory and returns URLs for the contained items.
func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: FileManager.DirectoryEnumerationOptions = []) throws -> [URL]
Therefore, in order to retrieve the urls of the files contained in documents directory, you can use the following code snippet that uses FileManager
's urls(for:in:)
and contentsOfDirectory(at:includingPropertiesForKeys:options:)
methods:
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents)
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
As an example, the UIViewController
implementation below shows how to save a file from app bundle to documents directory and how to get the urls of the files saved in documents directory:
import UIKit
class ViewController: UIViewController {
@IBAction func copyFile(_ sender: UIButton) {
// Get file url
guard let fileUrl = Bundle.main.url(forResource: "Movie", withExtension: "mov") else { return }
// Create a destination url in document directory for file
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let documentDirectoryFileUrl = documentsDirectory.appendingPathComponent("Movie.mov")
// Copy file to document directory
if !FileManager.default.fileExists(atPath: documentDirectoryFileUrl.path) {
do {
try FileManager.default.copyItem(at: fileUrl, to: documentDirectoryFileUrl)
print("Copy item succeeded")
} catch {
print("Could not copy file: \(error)")
}
}
}
@IBAction func displayUrls(_ sender: UIButton) {
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: [])
// Print the urls of the files contained in the documents directory
print(directoryContents) // may print [] or [file:///private/var/mobile/Containers/Data/Application/.../Documents/Movie.mov]
} catch {
print("Could not search for urls of files in documents directory: \(error)")
}
}
}
If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.
insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)
There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:
CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int
AS
If you want to know what the ID of the newly inserted record is add
SELECT @@IDENTITY
to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx
You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.
P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.
I think all the above do not answer this question due to following reasons,
but none has told the exact reason behind it & as I believe these kind of questions can be best answered by java community itself as it will have only one & specific answer but let me try my best to answer this as following,
As we know sorting is an expensive operation and there is a basic difference between List & Set/Map that List can have duplicates but Set/Map can not. This is the core reason why we have got a default implementation for Set/Map in form of TreeSet/TreeMap. Internally this is a Red Black Tree with every operation (insert/delete/search) having the complexity of O(log N) where due to duplicates List could not fit in this data storage structure.
Now the question arises we could also choose a default sorting method for List also like MergeSort which is used by Collections.sort(list)
method with the complexity of O(N log N). Community did not do this deliberately since we do have multiple choices for sorting algorithms for non distinct elements like QuickSort, ShellSort, RadixSort...etc. In future there can be more. Also sometimes same sorting algorithm performs differently depending on the data to be sorted. Therefore they wanted to keep this option open and left this on us to choose. This was not the case with Set/Map since O(log N) is the best sorting complexity.
Say you have defined your class like this:
@Data
@AllArgsConstructor(staticName = "of")
private class Pair<P,Q> {
public P first;
public Q second;
}
So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.
Pair<Integer, String> pair = Pair.of(menuItemId, category);
If you define it like this, you will get the error asked for.
Pair<Integer, String> pair = new Pair(menuItemId, category);
Had the same problem. For me it worked to call
viewPage.setAdapter( adapter );
again which caused reinstantiating the pages again.
There is some flickering problem in {{ }} like when you refresh the page then for a short spam of time expression is seen.So we should use ng-bind instead of expression for data depiction.
Eclipse has several C# plugins, the best I've found to date is Emonic . You can target .NET or Mono with the help of it. Both Eclipse and Emonic are open source.
In swift 4
let Totalname = "10.0" //Now it is in string
let floatVal = (Totalname as NSString).floatValue //Now converted to float
Another alternative to your original solution would be to use the escape character \
before the space:
VBoxManage internalcommands sethduuid /home/user/VirtualBox\ VMs/drupal/drupal.vhd
A lot of this has to do with polymorphism. When you assign
X = new Y();
X can be much less 'specific' than Y, but not the other way around. X is just the handle you are accessing Y with, Y is the real instantiated thing,
You get an error here because Integer is a Number, but Number is not an Integer.
ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error
As such, any method of X that you call must be valid for Y. Since X is more generally it probably shares some, but not all of Y's methods. Still, any arguments given must be valid for Y.
In your examples with add, an int (small i) is not a valid Object or Integer.
ArrayList<?> a = new ArrayList<?>();
This is no good because you can't actually instantiate an array list containing ?'s. You can declare one as such, and then damn near anything can follow in new ArrayList<Whatever>();
The Get-ChildItem cmdlet has an -Exclude
parameter that is tempting to use but it doesn't work for filtering out entire directories from what I can tell. Try something like this:
function GetFiles($path = $pwd, [string[]]$exclude) { foreach ($item in Get-ChildItem $path) { if ($exclude | Where {$item -like $_}) { continue } if (Test-Path $item.FullName -PathType Container) { $item GetFiles $item.FullName $exclude } else { $item } } }
You can force the toolbar by wrapping title and level right padding which has default left padding for title. Than put background color to the parent of toolbar and that way part which is cut out by wrapping title is in the same color(white in my example):
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="wrap_content"
android:layout_height="56dp"
android:layout_gravity="center_horizontal"
android:paddingEnd="15dp"
android:paddingRight="15dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:titleTextColor="@color/black"/>
</android.support.design.widget.AppBarLayout>
ORA-12154: TNS:could not resolve the connect identifier specified?
In case the TNS is not defined you can also try this one:
If you are using C#.net 2010
or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:
static string constr = @"Data Source=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
User Id=system ;Password=yourpasswrd";
After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified
then first you have to do restart your system and run your project.
And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:
Oracle Data Provider for .NET 2.0
Oracle Providers for ASP.NET
Oracle Developer Tools for Visual Studio
Oracle Instant Client
And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......
mysql datetime -> GregorianCalendar
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2012-12-13 14:54:30"); // mysql datetime format
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());
GregorianCalendar -> mysql datetime
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = format.format(calendar.getTime());
System.out.println(string);
git clean -fd
didn't help, new files remained. What I did is totally deleting all the working tree and then
git reset --hard
See "How do I clear my local working directory in git?" for advice to add the -x
option to clean:
git clean -fdx
Note -x
flag will remove all files ignored by Git so be careful (see discussion in the answer I refer to).
You should really use the following instead (works in all newer browsers):
window.addEventListener('DOMContentLoaded', init, false);
I use apex_util.string_to_table to parse strings, but you can use a different parser if you wish. Then you can insert the data as in this example:
declare
myString varchar2(2000) :='0.75, 0.64, 0.56, 0.45';
myAmount varchar2(2000) :='0.25, 0.5, 0.65, 0.8';
v_array1 apex_application_global.vc_arr2;
v_array2 apex_application_global.vc_arr2;
begin
v_array1 := apex_util.string_to_table(myString, ', ');
v_array2 := apex_util.string_to_table(myAmount, ', ');
forall i in 1..v_array1.count
insert into mytable (a, b) values (v_array1(i), v_array2(i));
end;
Apex_util is available from Oracle 10G onwards. Prior to this it was called htmldb_util and was not installed by default. If you can't use that you could use the string parser I wrote many years ago and posted here.