You can find an introduction to file dialogs in the Java Tutorials. Java2s also has some example code.
You need to look at the return value of the call to showConfirmDialog
. I.E.:
int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
// Saving code here
}
You were testing against dialogButton
, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton
would never have been anything other than JOptionPane.YES_NO_OPTION
.
Per the Javadoc for showConfirmDialog
:
Returns: an integer indicating the option selected by the user
I couldn't do it on a Galaxy S3 (non rooted).
For me it would hang saying...
restaring in tcp mode
So i found this series of commands quite useful.
First disconnect your device, start from scratch (cmd in admin mode and all the stuff).
connect your device and write in CMD/Terminal:
adb kill-server
control should return as normal. Now type and enter
adb tcpip 5555
you will see..
- daemon not running. starting it now on port 5037 *
- daemon started successfully * restarting in TCP mode port: 5555
and then connect device with
adb connect <IP>
That's how it worked for me after a lot of hassle!
UPDATE FOR ANDROID STUDIO
I noticed this doesn't work sometimes, even after correctly repeating steps a number of times. Catch was; sometimes ADB is yet not initialized by Studio unless, Android Tab at the bottom is opened and you see "Initializing Android Studio".
You can grab the demo source code from here: http://abhinavsingh.com/blog/2008/05/gmail-type-attachment-how-to-make-one/
It is ready to use, or you can modify to suit your application needs. Hope it helps :)
The syntax may not be as pythonic as one might like, but it is a powerful library.
https://docs.python.org/2/library/decimal.html
from decimal import *
print(int(Decimal(2.3).quantize(Decimal('1.'), rounding=ROUND_UP)))
If your console does not show (base)
after running conda activate base
, then try running:
conda init
Then running conda activate <your_env>
should show the name of (<your_env>)
at the beginning of the shell prompt.
This worked for me on Windows. My PATH environment variable was set properly so conda activate base
did not raise any error but quietly failed.
From version 1.9 Easier and official way of getting json
from django.http import JsonResponse
from django.forms.models import model_to_dict
return JsonResponse( model_to_dict(modelinstance) )
Cursor might used for retrieving data row by row basis.its act like a looping statement(ie while or for loop). To use cursors in SQL procedures, you need to do the following: 1.Declare a cursor that defines a result set. 2.Open the cursor to establish the result set. 3.Fetch the data into local variables as needed from the cursor, one row at a time. 4.Close the cursor when done.
for ex:
declare @tab table
(
Game varchar(15),
Rollno varchar(15)
)
insert into @tab values('Cricket','R11')
insert into @tab values('VollyBall','R12')
declare @game varchar(20)
declare @Rollno varchar(20)
declare cur2 cursor for select game,rollno from @tab
open cur2
fetch next from cur2 into @game,@rollno
WHILE @@FETCH_STATUS = 0
begin
print @game
print @rollno
FETCH NEXT FROM cur2 into @game,@rollno
end
close cur2
deallocate cur2
SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
ORDER BY COUNT(*) DESC
You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations
Update
The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:
The Java Language Specification, section 15.10, states:
An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7).
and
The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.
The closest you can do is use an unchecked cast, either from the raw type, as you have done, or from an unbounded wildcard:
HashMap<String, String>[] responseArray = (Map<String, String>[]) new HashMap<?,?>[games.size()];
Your version is clearly better :-)
You can use the % character to 'escape' characters that aren't allowed in URLs. See [RFC 1738].
A table of ASCII values on http://www.asciitable.com/.
You can see &
is 26 in hexadecimal - so you need M%26M.
for i in A:
print('\t'.join(map(str, i)))
To display the Json data using Robin Hartman code. You need to add, the below line.
The code he gave gives you Object, object. this code retrieves the data in a better way.
result.innerText =JSON.stringify(data);
If you want to use column names to select the columns, simply use .()
, which is an alias for list()
:
library(data.table)
dt <- data.table(a = 1:2, b = 2:3, c = 3:4)
dt[ , .(b, c)] # select the columns b and c
# Result:
# b c
# 1: 2 3
# 2: 3 4
Make #site_nav_global_primary
positioned as fixed and set width to 100 % and desired height.
As it says on man git, you can use --no-pager
on any command.
I use it on:
git --no-pager diff
git --no-pager log --oneline --graph --decorate --all -n 10
Then use an alias to avoid using (and remembering) long commands.
Re Jonathan Wood's suggestion. I don't have the option of wrapping tables with a new div as i'm using a CMS. Using JQuery here's what i did:
$( "table" ).wrap( "<div class='table-overflow'></div>" );
This wraps table elements with a new div with the class "table-overflow".
You can then simply add the following definition in your css file:
.table-overflow { overflow: auto; }
JSON:-
For POST request using json object it can be configured by selecting
Body -> raw -> application/json
Form Data(For Normal content POST):- multipart/form-data
For normal POST request (using multipart/form-data) it can be configured by selecting
Body -> form-data
This is the effect that we're trying to achieve:
The classes that need to be applied changed with the release of Bootstrap 3.1.0 and again with the release of Bootstrap 4. If one of the below solutions doesn't seem to be working double check the version number of Bootstrap that you're importing and try a different one.
You can use the pull-right
class to line the right hand side of the menu up with the caret:
<li class="dropdown">
<a class="dropdown-toggle" href="#">Link</a>
<ul class="dropdown-menu pull-right">
<li>...</li>
</ul>
</li>
Fiddle: http://jsfiddle.net/joeczucha/ewzafdju/
As of v3.1.0, we've deprecated .pull-right on dropdown menus. To right-align a menu, use .dropdown-menu-right. Right-aligned nav components in the navbar use a mixin version of this class to automatically align the menu. To override it, use .dropdown-menu-left.
You can use the dropdown-right
class to line the right hand side of the menu up with the caret:
<li class="dropdown">
<a class="dropdown-toggle" href="#">Link</a>
<ul class="dropdown-menu dropdown-menu-right">
<li>...</li>
</ul>
</li>
Fiddle: http://jsfiddle.net/joeczucha/1nrLafxc/
The class for Bootstrap 4 are the same as Bootstrap > 3.1.0, just watch out as the rest of the surrounding markup has changed a little:
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#">
Link
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#">...</a>
</div>
</li>
DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.
TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back ... As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.
From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands
You could use inline styles and define the width in the <th>
tag. Make it so that the sum of the widths = 100%.
<tr>
<th style="width:10%">Size</th>
<th style="width:30%">Bust</th>
<th style="width:50%">Waist</th>
<th style="width:10%">Hips</th>
</tr>
Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.
You don't need to install sqlite3
module. It is included in the standard library (since Python 2.5).
.yaml
is apparently the official extension, because some applications fail when using .yml
. On the other hand I am not familiar with any applications which use YAML code, but fail with a .yaml
extension.
I just stumbled across this, as I was used to writing .yml
in Ansible and Docker Compose. Out of habit I used .yml
when writing Netplan files which failed silently. I finally figured out my mistake. The author of a popular Ansible Galaxy role for Netplan makes the same assumption in his code:
- name: Capturing Existing Configurations
find:
paths: /etc/netplan
patterns: "*.yml,*.yaml"
register: _netplan_configs
Yet any files with a .yml
extension get ignored by Netplan in the same way as files with a .bak
extension. As Netplan is very quiet, and gives no feedback whatsoever on success, even with netplan apply --debug
, a config such as 01-netcfg.yml
will fail silently without any meaningful feedback.
Try this option.
update that coding part in Page_Load event before catching IsPostback
TextBox1.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('ctl00_ContentPlaceHolder1_Button1').click();return false;}} else {return true}; ");
I found the above link incredibly helpful as it corrected my C# classes by generating them from the JSON that was actually returned.
Then I called :
JsonConvert.DeserializeObject<RootObject>(jsonString);
and everything worked as expected.
I remote into the computer using Enter-PSsession pcName then I type Get-PSDrive
That will list all drives and space used and remaining. If you need to see all the info formated, pipe it to FL like this: Get-PSdrive | FL *
why not simply:
./aaa.sh 2>&1 | tee -a log
This simply redirects stderr
to stdout
, so tee echoes both to log and to screen. Maybe I'm missing something, because some of the other solutions seem really complicated.
Note: Since bash version 4 you may use |&
as an abbreviation for 2>&1 |
:
./aaa.sh |& tee -a log
[id^='someId']
will match all ids starting with someId
.
[id$='someId']
will match all ids ending with someId
.
[id*='someId']
will match all ids containing someId
.
If you're looking for the name
attribute just substitute id
with name
.
If you're talking about the tag name of the element I don't believe there is a way using querySelector
OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:
UPDATE table1
SET col1 = subquery.col2,
col2 = subquery.col3
FROM (
SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3
FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;
You can know list of all ports running in system along with its details (pid, address etc.) :
netstat -tulpn
You can know details of a particular port number by providing port number in following command :
sudo netstat -lutnp | grep -w '{port_number}'
ex: sudo netstat -lutnp | grep -w '8080' Details will be provided like this :
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
if you want to kill a process using pid then : kill -9 {PID}
if you want to kill a process using port number : fuser -n tcp {port_number}
use sudo
if you are not able to access any.
You can't use a switch statement for this as the case values cannot be evaluated expressions. For this you have to use an an if/else ...
public static void Output<T>(IEnumerable<T> dataSource) where T : class
{
dataSourceName = (typeof(T).Name);
if(string.Compare(dataSourceName, typeof(CustomerDetails).Name.ToString(), true)==0)
{
var t = 123;
}
else if (/*case 2 conditional*/)
{
//blah
}
else
{
//default case
Console.WriteLine("Test");
}
}
I also took the liberty of tidying up your conditional statement. There is no need to cast to string after calling ToString()
. This will always return a string anyway. When comparing strings for equality, bare in mind that using the == operator will result in a case sensitive comparison. Better to use string compare = 0 with the last argument to set case sensitive on/off.
The -L
merely gives the path where to find the .a
or .so
file. What you're looking for is to add -lmine
to the LIBS
variable.
Make that -static -lmine
to force it to pick the static library (in case both static and dynamic library exist).
Addition: Suppose the path to the file has been conveyed to the linker (or compiler driver) via -L
you can also specifically tell it to link libfoo.a
by giving -l:libfoo.a
. Note that in this case the name includes the conventional lib
-prefix. You can also give a full path this way. Sometimes this is the better method to "guide" the linker to the right location.
Hi you can achieve your result with use of <marquee behavior="alternate"></marquee>
HTML
<div class="wrapper">
<marquee behavior="alternate"><span class="marquee">This is a marquee!</span></marquee>
</div>
CSS
.wrapper{
max-width: 400px;
background: green;
height: 40px;
text-align: right;
}
.marquee {
background: red;
white-space: nowrap;
-webkit-animation: rightThenLeft 4s linear;
}
see the demo:- http://jsfiddle.net/gXdMc/6/
Yet another way to do it is to build a regex with named capture groups over the format string and then use that regex to extract the day, month and year from the date string:
function parseDate(dateStr, format) {_x000D_
const regex = format.toLocaleLowerCase()_x000D_
.replace(/\bd+\b/, '(?<day>\\d+)')_x000D_
.replace(/\bm+\b/, '(?<month>\\d+)')_x000D_
.replace(/\by+\b/, '(?<year>\\d+)')_x000D_
_x000D_
const parts = new RegExp(regex).exec(dateStr) || {};_x000D_
const { year, month, day } = parts.groups || {};_x000D_
return parts.length === 4 ? new Date(year, month-1, day) : undefined;_x000D_
}_x000D_
_x000D_
const printDate = x => console.log(x ? x.toLocaleDateString() : x);_x000D_
_x000D_
printDate(parseDate('05/11/1896', 'dd/mm/YYYY'));_x000D_
printDate(parseDate('07-12-2000', 'dd-mm-yy'));_x000D_
printDate(parseDate('07:12:2000', 'dd:mm:yy'));_x000D_
printDate(parseDate('2017/6/3', 'yy/MM/dd'));_x000D_
printDate(parseDate('2017-6-15', 'y-m-d'));_x000D_
printDate(parseDate('2015 6 25', 'y m d'));_x000D_
printDate(parseDate('2015625', 'y m d')); // bad format
_x000D_
In TASM (x86 assembly) it can look like this:
cmp BL, BH
je EQUAL ; BL = BH
jg GREATER ; BL > BH
jmp LESS ; BL < BH
in this case it compares two 8bit numbers that we temporarily store in the higher and the lower part of the register B. Alternatively you might also consider using jbe
(if BL <= BH) or jge
/jae
(if BL >= BH).
Hopefully someone finds it helpful :)
The thing that worked for me (and that I took from another stackoverflow response), is to set the flag:
Response.TrySkipIisCustomErrors = true;
Machines don't understand English or any other languages, they understand only byte code, which they have to be compiled (e.g., C/C++, Java) or interpreted (e.g., Ruby, Python), the .pyc is a cached version of the byte code. https://www.geeksforgeeks.org/difference-between-compiled-and-interpreted-language/ Here is a quick read on what is the difference between compiled language vs interpreted language, TLDR is interpreted language does not require you to compile all the code before run time and thus most of the time they are not strict on typing etc.
You can try this ! This should work on windows machines.
for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"
$ cat exampleScript.sh
#!/bin/bash
name="karthik";
echo $name;
bash -x exampleScript.sh
Output is as follows:
If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.
You could reimplement the default repr this way:
def __repr__(self):
return '<%s.%s object at %s>' % (
self.__class__.__module__,
self.__class__.__name__,
hex(id(self))
)
There is a undocumented timeout between when you first redirect the user to the google authentication page (and get back a code), and when you take the returned code and post it to the token url. It works fine for me with the actual google supplied client_id as opposed to an "undocumented email address". I just needed to start the process again.
The following way will work even if you are working on a relative layout. Follow the following steps:
Go to styles.xml and then under the theme just added, add these two attributes:
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">false</item>
My theme setting for the dialog is as under:
<style name="DialogTheme" parent="Theme.AppCompat.Dialog" >
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">match_parent</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">false</item>
Make sure that the theme has a parent as Theme.AppCompat.Dialog Another way would be just make a new style in styles.xml and change it as per the code above.
Go to your Dialog Fragment class and in the onCreate() method, set the style of your Dialog as:
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL,R.style.DialogTheme); }
So within the render
method comments are allowed but in order to use them within JSX, you have to wrap them in braces and use multi-line style comments.
<div className="dropdown">
{/* whenClicked is a property not an event, per se. */}
<Button whenClicked={this.handleClick} className="btn-default" title={this.props.title} subTitleClassName="caret"></Button>
<UnorderedList />
</div>
You can read more about how comments work in JSX here
MySQL function NOW()
returns the current timestamp. The only way I found for PHP is using the following code.
$curr_timestamp = date('Y-m-d H:i:s');
Add this is your xml: android:autoLink="phone"
The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.
When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.
Just one extra option, if you want to revert the default behaviour for all textareas in the application, you could add the following to your CSS:
textarea:not([resize="true"]) {
resize: none !important;
}
And do the following to enable where you want resizing:
<textarea resize="true"></textarea>
Have in mind this solution might not work in all browsers you may want to support. You can check the list of support for resize
here: http://caniuse.com/#feat=css-resize
Here's an idea. Imagine an HSV cylinder
Define the upper and lower limits you want for the Brightness and Saturation. This defines a square cross section ring within the space.
Now, scatter N points randomly within this space.
Then apply an iterative repulsion algorithm on them, either for a fixed number of iterations, or until the points stabilise.
Now you should have N points representing N colours that are about as different as possible within the colour space you're interested in.
Hugo
You are missing an echo. Each time that you want to show the value of a variable to HTML you need to echo it.
<input type="text" name="idtest" value="<?php echo $idtest; ?>" >
Note: Depending on the value, your echo is the function you use to escape it like htmlspecialchars.
You would need to use Javascript for this. You can set the style of the background-image
for the body like so.
var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';
Just make sure you replace the URL with the actual URL.
These links explain it with examples
http://dotnetperls.com/openfiledialog
http://www.geekpedia.com/tutorial67_Using-OpenFileDialog-to-open-files.html
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
Because the operating system may not do so. The flush operation forces the file data into the file cache in RAM, and from there it's the OS's job to actually send it to the disk.
This is still a matplotlib object. Try this:
# <your code here>
locs, labels = plt.xticks()
plt.setp(labels, rotation=45)
UPDATE 3:
::ng-deep
is also deprecated which means you should not do this at all anymore. It is unclear how this affects things where you need to override styles in child components from a parent component. To me it seems odd if this gets removed completely because how would this affect things as libraries where you need to override styles in a library component?
Comment if you have any insight in this.
UPDATE 2:
Since /deep/
and all other shadow piercing selectors are now deprecated. Angular dropped ::ng-deep
which should be used instead for a broader compatibility.
UPDATE:
If using Angular-CLI you need to use /deep/
instead of >>>
or else it will not work.
ORIGINAL:
After going to Angular2's Github page and doing a random search for "style" I found this question: Angular 2 - innerHTML styling
Which said to use something that was added in 2.0.0-beta.10
, the >>>
and ::shadow
selectors.
(>>>) (and the equivalent/deep/) and ::shadow were added in 2.0.0-beta.10. They are similar to the shadow DOM CSS combinators (which are deprecated) and only work with encapsulation: ViewEncapsulation.Emulated which is the default in Angular2. They probably also work with ViewEncapsulation.None but are then only ignored because they are not necessary. These combinators are only an intermediate solution until more advanced features for cross-component styling is supported.
So simply doing:
:host >>> .child {}
In parent
's stylesheet file solved the issue. Please note, as stated in the quote above, this solution is only intermediate until more advanced cross-component styling is supported.
Wow - I don't see a single person in 6 years suggesting that we check first to see if stack
is available before using it! The worst thing you can do in an error handler is throw an error because of calling something that doesn't exist.
As others have said, while stack
is mostly safe to use now it is not supported in IE9 or earlier.
I log my unexpected errors and a stack trace is pretty essential. For maximum support I first check to see if Error.prototype.stack
exists and is a function. If so then it is safe to use error.stack
.
window.onerror = function (message: string, filename?: string, line?: number,
col?: number, error?: Error)
{
// always wrap error handling in a try catch
try
{
// get the stack trace, and if not supported make our own the best we can
var msg = (typeof Error.prototype.stack == 'function') ? error.stack :
"NO-STACK " + filename + ' ' + line + ':' + col + ' + message;
// log errors here or whatever you're planning on doing
alert(msg);
}
catch (err)
{
}
};
Edit: It appears that since stack
is a property and not a method you can safely call it even on older browsers. I'm still confused because I was pretty sure checking Error.prototype
worked for me previously and now it doesn't - so I'm not sure what's going on.
FORMAT()
is slower than CONVERT()
. This answer is slightly better than @jpx's answer because it only does a replace on the time part of the date.
112 = yyyymmdd - no format change needed
108 = hh:mm:ss - remove :
SELECT CONVERT(VARCHAR, GETDATE(), 112) +
REPLACE(CONVERT(VARCHAR, GETDATE(), 108), ':', '')
Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...
create or replace procedure temp_proc is
begin
DBMS_OUTPUT.ENABLE(1000000);
DBMS_OUTPUT.PUT_LINE('Test');
end;
...and call it in a PLSQL block...
begin
temp_proc;
end;
...as SQL is non-procedural.
When you remove a cell of your tableview, you also have to remove your array object at index x.
I think you can remove it by using a swipe gesture. The table view will call the Delegate:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
[dataSourceArray removeObjectAtIndex:indexPath.row];
}
}
After removing the object. You have to reload the tableview use. Add the following line in your code:
[tableView reloadData];
after that, you have deleted the row successfully. And when you reload the view or adding data to the DataSource the object will not be there anymore.
For all other is the answer from Kurbz correct.
I only wanted to remind you that the delegate function won't be enough if you want to remove the object from the DataSource array.
I hope I have helped you out.
addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));
This will add ONE class or MULTIPLE classes :
addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"
The pathlib library (included with >= Python 3.4) makes it very concise and intuitive to append the path of the parent directory to the PYTHONPATH:
import sys
from pathlib import Path
sys.path.append(str(Path('.').absolute().parent))
Concise without regular expressions, but HTTPResponseCode=> httpresponse_code:
def from_camel(name):
"""
ThisIsCamelCase ==> this_is_camel_case
"""
name = name.replace("_", "")
_cas = lambda _x : [_i.isupper() for _i in _x]
seq = zip(_cas(name[1:-1]), _cas(name[2:]))
ss = [_x + 1 for _x, (_i, _j) in enumerate(seq) if (_i, _j) == (False, True)]
return "".join([ch + "_" if _x in ss else ch for _x, ch in numerate(name.lower())])
You also use this below to expand the memory
export _JAVA_OPTIONS="-Xms512m -Xmx1024m -Xss512m -XX:MaxPermSize=1024m"
Xmx
specifies the maximum memory allocation pool for a Java virtual machine (JVM)
Xms
specifies the initial memory allocation pool.
Xss
setting memory size of thread stack
XX:MaxPermSize
: the maximum permanent generation size
Starting pandas 1.0.0, we have pandas.DataFrame.convert_dtypes
. You can even control what types to convert!
In [40]: df = pd.DataFrame(
...: {
...: "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
...: "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
...: "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
...: "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
...: "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
...: "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
...: }
...: )
In [41]: dff = df.copy()
In [42]: df
Out[42]:
a b c d e f
0 1 x True h 10.0 NaN
1 2 y False i NaN 100.5
2 3 z NaN NaN 20.0 200.0
In [43]: df.dtypes
Out[43]:
a int32
b object
c object
d object
e float64
f float64
dtype: object
In [44]: df = df.convert_dtypes()
In [45]: df.dtypes
Out[45]:
a Int32
b string
c boolean
d string
e Int64
f float64
dtype: object
In [46]: dff = dff.convert_dtypes(convert_boolean = False)
In [47]: dff.dtypes
Out[47]:
a Int32
b string
c object
d string
e Int64
f float64
dtype: object
Use a comparison function:
bool compareByLength(const data &a, const data &b)
{
return a.word.size() < b.word.size();
}
and then use std::sort
in the header #include <algorithm>
:
std::sort(info.begin(), info.end(), compareByLength);
You need to follow these steps before the token authentication
Create a Cluster Admin service account
kubectl create serviceaccount dashboard -n default
Add the cluster binding rules to your dashboard account
kubectl create clusterrolebinding dashboard-admin -n default --clusterrole=cluster-admin --serviceaccount=default:dashboard
Get the secret token with this command
kubectl get secret $(kubectl get serviceaccount dashboard -o jsonpath="{.secrets[0].name}") -o jsonpath="{.data.token}" | base64 --decode
Choose token authentication in the Kubernetes dashboard login page
Now you can able to login
you're comparing the result against a string ('false') not the built-in negative constant (false)
just use
if(ValidateForm() == false) {
or better yet
if(!ValidateForm()) {
also why are you calling validateForm twice?
I assume this was not a valid option when this was originally asked, but you can now use document.getElementsByClassName('');
. For example:
var elements = document.getElementsByClassName(names); // or:
var elements = rootElement.getElementsByClassName(names);
See the MDN documentation for more.
For Android Studio (or IntelliJ IDEA),
If everything looks OK in your project and that you're still receiving the error in all your layouts, try to 'Invalidate caches & restart'.
Wait until Android Studio has finished to create all the caches & indexes.
I keep visiting this page anytime I google "remove duplicates form mysql" but for my theIGNORE solutions don't work because I have an InnoDB mysql tables
this code works better anytime
CREATE TABLE tableToclean_temp LIKE tableToclean;
ALTER TABLE tableToclean_temp ADD UNIQUE INDEX (fontsinuse_id);
INSERT IGNORE INTO tableToclean_temp SELECT * FROM tableToclean;
DROP TABLE tableToclean;
RENAME TABLE tableToclean_temp TO tableToclean;
tableToclean = the name of the table you need to clean
tableToclean_temp = a temporary table created and deleted
int main()
{
char input[100];
gets(input);
char str[101];
strcpy(str, " ");
strcat(str, input);
char *p = str;
while(*p) {
if(*p == ' ' && isalpha(*(p+1)) != 0)
printf("%c",*(p+1));
p++;
}
return 0;
}
Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)
The error message is actually correct if not obvious. It says that your DOCTYPE must have a SYSTEM identifier. I assume yours only has a public identifier.
You'll get the error with (for instance):
<!DOCTYPE persistence PUBLIC
"http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
You won't with:
<!DOCTYPE persistence PUBLIC
"http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" "">
Notice ""
at the end in the second one -- that's the system identifier. The error message is confusing: it should say that you need a system identifier, not that you need a space between the publicId and the (non-existent) systemId.
By the way, an empty system identifier might not be ideal, but it might be enough to get you moving.
My personal opinion: Go for Swing together with the NetBeans platform.
If you need advanced components (more than NetBeans offers) you can easily integrate SwingX without problems (or JGoodies) as the NetBeans platform is completely based on Swing.
I would not start a large desktop application (or one that is going to be large) without a good platform that is build upon the underlying UI framework.
The other option is SWT together with the Eclipse RCP, but it's harder (though not impossible) to integrate "pure" Swing components into such an application.
The learning curve is a bit steep for the NetBeans platform (although I guess that's true for Eclipse as well) but there are some good books around which I would highly recommend.
Actually, you only need to use the default
argument to add_argument
as in this test.py
script:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--example', default=1)
args = parser.parse_args()
print(args.example)
test.py --example
% 1
test.py --example 2
% 2
Details are here.
You can use IIF for a similar result.
Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html
SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer
FROM MyTable;
echo "<script>
window.location.href='admin/ahm/panel';
alert('There are no fields to generate a report');
</script>";
Try out this way it works...
First assign the window with the new page where the alert box must be displayed then show the alert box.
You can use year()
function in sql to get the year from the specified date.
Syntax:
YEAR ( date )
For more information check here
$content = $_POST['content_name'];
$lines = explode("\n", $content);
foreach( $lines as $index => $line )
{
$lines[$index] = $line . '<br/>';
}
// $lines contains your lines
How are you running the file? Is it from the command line or from an IDE? The directory that your executable is in is not necessarily your working directory.
Try using the full path name in the fopen
and see if that fixes it. If so, then the problem is as described.
For example:
file = fopen("c:\\MyDirectory\\TestFile1.txt", "r");
file = fopen("/full/path/to/TestFile1.txt", "r");
Or open up a command window and navigate to the directory where your executable is, then run it manually.
As an aside, you can insert a simple (for Windows or Linux/UNIX/BSD/etc respectively):
system ("cd")
system("pwd")
before the fopen
to show which directory you're actually in.
IEquatable<T>
can be a much easier way to do this with modern frameworks.
You get a nice simple bool Equals(T other)
function and there's no messing around with casting or creating a separate class.
public class Person : IEquatable<Person>
{
public Person(string name, string hometown)
{
this.Name = name;
this.Hometown = hometown;
}
public string Name { get; set; }
public string Hometown { get; set; }
// can't get much simpler than this!
public bool Equals(Person other)
{
return this.Name == other.Name && this.Hometown == other.Hometown;
}
public override int GetHashCode()
{
return Name.GetHashCode(); // see other links for hashcode guidance
}
}
Note you DO have to implement GetHashCode
if using this in a dictionary or with something like Distinct
.
PS. I don't think any custom Equals methods work with entity framework directly on the database side (I think you know this because you do AsEnumerable) but this is a much simpler method to do a simple Equals for the general case.
If things don't seem to be working (such as duplicate key errors when doing ToDictionary) put a breakpoint inside Equals to make sure it's being hit and make sure you have GetHashCode
defined (with override keyword).
I have added dataType: 'jsonp' and it works!
$.ajax({
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
url: '',
success: function(jsondata){
}
})
JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More
Casting for inclusion is just as important as casting for exclusion for a C++ programmer. Type casting is not the same as with RTTI in the sense that you can cast an object to any type and the resulting pointer will not be nil.
Try this!
List<String> x = new ArrayList<String>(Arrays.asList("xyz", "abc"));
It's a good practice to declare the ArrayList
with interface List
if you don't have to invoke the specific methods.
using
memset(members, 0, 255);
in general
memset(members, 0, sizeof members);
if the array is in scope, or
memset(members, 0, nMembers * (sizeof members[0]) );
if you only have the pointer value, and nMembers is the number of elements in the array.
EDIT Of course, now the requirement has changed from the generic task of clearing an array to purely resetting a string, memset
is overkill and just zeroing the first element suffices (as noted in other answers).
EDIT In order to use memset, you have to include string.h.
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
Use repr
and eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
Note that eval
is not safe if the source of string is unknown, prefer ast.literal_eval
for safer conversion:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])
help on repr
:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
The other answers here fail to spell out a full solution for regex versions which don't support non-greedy matching. The greedy quantifiers (.*?
, .+?
etc) are a Perl 5 extension which isn't supported in traditional regular expressions.
If your stopping condition is a single character, the solution is easy; instead of
a(.*?)b
you can match
a[^ab]*b
i.e specify a character class which excludes the starting and ending delimiiters.
In the more general case, you can painstakingly construct an expression like
start(|[^e]|e(|[^n]|n(|[^d])))end
to capture a match between start
and the first occurrence of end
. Notice how the subexpression with nested parentheses spells out a number of alternatives which between them allow e
only if it isn't followed by nd
and so forth, and also take care to cover the empty string as one alternative which doesn't match whatever is disallowed at that particular point.
Of course, the correct approach in most cases is to use a proper parser for the format you are trying to parse, but sometimes, maybe one isn't available, or maybe the specialized tool you are using is insisting on a regular expression and nothing else.
Try this:
var frm = document.getElementById('search-theme-form') || null;
if(frm) {
frm.action = 'whatever_you_need.ext'
}
Sometimes you get broken code, when using dex2jar
/apktool
, most notably in loops. To avoid this, use jadx, which decompiles dalvik bytecode into java source code, without creating a .jar
/.class
file first as dex2jar
does (apktool uses dex2jar I think). It is also open-source and in active development. It even has a GUI, for GUI-fanatics. Try it!
#1- Run this to configure the region once and for all:
aws configure set region us-east-1 --profile admin
Change admin
next to the profile if it's different.
Change us-east-1
if your region is different.
#2- Run your command again:
aws ecs list-container-instances --cluster default
I believe a good answer is already provided, but I would like to add an easy-to-follow diagram of the different 3 life-cycles (build
, clean
, and site
) and the phases in each.
The phases in bold - are the main phases commonly used.
Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
My favorite datetime parser is DateTime::Format::ISO8601 Once you've got that working, you'll have a DateTime object, easily convertable to epoch seconds with epoch()
$date_field = date('Y-m-d',strtotime($_POST['date_field']));
$sql = mysql_query("INSERT INTO user_date (column_name,column_name,column_name) VALUES('',$name,$date_field)") or die (mysql_error());
Just use look-arounds to solve this:
(?<=^|,)garp(?=$|,)
The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.
Use -D property=value rather than -D property = value (eliminate extra whitespaces). Thus -D mapred.reduce.tasks=value would work fine.
Setting number of map tasks doesnt always reflect the value you have set since it depends on split size and InputFormat used.
Setting the number of reduces will definitely override the number of reduces set on cluster/client-side configuration.
If you are running inside a Python console, do this:
img = cv2.imread("yourimage.jpg")
cv2.imshow("img", img); cv2.waitKey(0); cv2.destroyAllWindows()
Then if you press Enter on the image, it will successfully close the image and you can proceed running other commands.
Try below code :
Assign the path of the folder to variable FolderPath
before running the below code.
Sub sample()
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Documents and Settings\Santosh\Desktop"
path = FolderPath & "\*.xls"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("Q8").Value = count
'MsgBox count & " : files found in folder"
End Sub
If you still can't access the management console after a fresh install, check if the management console was enabled. To enable it:
Go to the RabbitMQ command prompt.
Type:
rabbitmq-plugins enable rabbitmq_management
SQL Query: (group by & count of distinct)
select city,count(distinct(emailId)) from TransactionDetails group by city;
Equivalent mongo query would look like this:
db.TransactionDetails.aggregate([
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} }
]);
Had the same issue where query:
SELECT * FROM 'column' WHERE 'column' IS NULL;
returned no values. Seems to be an issue with MyISAM and the same query on the data in InnoDB returned expected results.
Went with:
SELECT * FROM 'column' WHERE 'column' = ' ';
Returned all expected results.
I was solving this leetcode problem and I came across this beautiful solution by a user named Zitao Wang.
The problem goes like this for each element in the given array find the product of all the remaining numbers without making use of divison and in O(n)
time
The standard solution is:
Pass 1: For all elements compute product of all the elements to the left of it
Pass 2: For all elements compute product of all the elements to the right of it
and then multiplying them for the final answer
His solution uses only one for loop by making use of. He computes the left product and right product on the fly using ~
def productExceptSelf(self, nums):
res = [1]*len(nums)
lprod = 1
rprod = 1
for i in range(len(nums)):
res[i] *= lprod
lprod *= nums[i]
res[~i] *= rprod
rprod *= nums[~i]
return res
SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || "tag_name" || '%';
tag_name
should be in quotation otherwise it will give error as tag_name doest not exist
The previous answer does not take into account a change in the NIB (XIB) structure that occurred between 2.0 and 2.1 of the iPhone SDK. User contents now start at index 0 instead of 1.
You can use the 2.1 macro which is valid for all version 2.1 and above (that's two underscores before IPHONE:
// Cited from previous example
NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:@"QPickOneView" owner:self options:nil];
int startIndex;
#ifdef __IPHONE_2_1
startIndex = 0;
#else
startIndex = 1;
#endif
QPickOneView* myView = [ nibViews objectAtIndex: startIndex];
myView.question = question;
We use a technique similar to this for most of our applications.
Barney
If I can add my $0.02, I prefer using PascalCase as enum values in C.
In C, they are basically global, and PEER_CONNECTED gets really tiring as opposed to PeerConnected.
Breath of fresh air.
Literally, it makes me breathe easier.
In Java, it is possible to use raw enum names as long as you static import them from another class.
import static pkg.EnumClass.*;
Now, you can use the unqualified names, that you qualified in a different way already.
I am currently (thinking) about porting some C code to Java and currently 'torn' between choosing Java convention (which is more verbose, more lengthy, and more ugly) and my C style.
PeerConnected would become PeerState.CONNECTED except in switch statements, where it is CONNECTED.
Now there is much to say for the latter convention and it does look nice but certain "idiomatic phrases" such as if (s == PeerAvailable)
become like if (s == PeerState.AVAILABLE)
and nostalgically, this is a loss of meaning to me.
I think I still prefer the Java style because of clarity but I have a hard time looking at the screaming code.
Now I realize PascalCase is already widely used in Java but very confusing it would not really be, just a tad out of place.
In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.
I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:
DBCC TRACEON(1222, -1);
A quick search yielded this tutorial:
http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/
Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.
Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:
Disclaimer: I work for SQL Sentry.
var date = moment('2016-10-19', 'DD-MM-YYYY', true);
You should add a third argument when invoking moment
that enforces strict parsing. Here is the relevant portion of the moment documentation http://momentjs.com/docs/#/parsing/string-format/ It is near the end of the section.
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
You forgot to return the map. this code will resolve the issue.
Be sure to declare HttpHeaders without null values.
this.http.get('url', {headers: new HttpHeaders({'a': a || '', 'b': b || ''}))
Otherwise, if you try to add a null value to HttpHeaders it will give you an error.
If your entity is mapped through annotations, add the following code to your configuration;
configuration.addAnnotatedClass(theEntityPackage.EntityClassName.class);
For example;
configuration.addAnnotatedClass(com.foo.foo1.Products.class);
if your entity is mapped with xml file, use addClass instead of addAnnotatedClass.
As an example;
configuration.addClass(com.foo.foo1.Products.class);
Ping me if you need more help.
I find a way to avoid styling my own choose file button.
Because I'm using flowjs for resumable upload, I'm able to use the "flow-btn" directive from ng-flow, which gives a choose file button with material design style.
Note that wrapping the input element inside a md-button won't work.
A simple shell function (no sed needed) should do the trick of interpreting '5X5'
$ function calc { bc -l <<< ${@//[xX]/*}; };
$ calc 5X5
25
$ calc 5x5
25
$ calc '5*5'
25
try this
single function for all radio have class "radio-button"
work in chrome and FF
$('.radio-button').on("click", function(event){_x000D_
$('.radio-button').prop('checked', false);_x000D_
$(this).prop('checked', true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
I managed to hit this error when simply creating a table! There was obviously no contention problem on a table that didn't yet exist. The CREATE TABLE
statement contained a CONSTRAINT fk_name FOREIGN KEY
clause referencing a well-populated table. I had to:
You can do these..
Instead of calling the function, bind the value to the function:
this.props.removeTaskFunction.bind(this, todo)
MDN ref: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
So, I would like to explain the scenario where I had to make use of this solution. Basically, I wanted to undo the background-color attribute set by another CSS. The expected end result was to make it look as though the original CSS had never applied the background-color attribute . Setting background-color:transparent;
made that effective.
Maybe some folk are making the same mistake I did? Which was... I had set a width for the input boxes, because they were mostly of type 'text' , but then forgotten to over-ride that width for checkboxes - so my checkbox was trying to occupy a lot of excess width and so it was tough to align a label beside it.
.checkboxlabel {
width: 100%;
vertical-align: middle;
}
.checkbox {
width: 20px !important;
}
<label for='acheckbox' class='checkboxlabel'>
<input name="acheckbox" id='acheckbox' type="checkbox" class='checkbox'>Contact me</label>
Gives clickable labels and and proper alignment as far back as IE6 (using a class selector) and in late versions of Firefox, Safari and Chrome
You can use ILIKE
. i.e.
SELECT id FROM groups where name ILIKE 'administrator'
Here is an alternative way if the data frame just contains numbers.
apply(as.matrix.noquote(SFI),2,as.numeric)
_x000D_
but the most reliable way of converting a data frame to a matrix is using data.matrix()
function.
If you are here because of the Liquibase error saying:
Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short
and you are using
not {
indexExists()
}
precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342
We can try to execute an above check using bare sqlCheck
(Postgres):
SELECT COUNT(i.relname)
FROM
pg_class t,
pg_class i,
pg_index ix
WHERE
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and t.relkind = 'r'
and t.relname = 'tableName'
and i.relname = 'indexName';
where tableName
- is an index table name and indexName
- is an index name
Simply use! grep -v
multiple times.
[root@server]# cat file
1
2
3
4
5
[root@server]# cat file |grep -v 3
1
2
4
5
[root@server]# cat file |grep -v 3 |grep -v 5
1
2
4
You should create a map of actions using the statusCode
setting:
$.ajax({
statusCode: {
400: function() {
alert('400 status code! user error');
},
500: function() {
alert('500 status code! server error');
}
}
});
Reference (Scroll to: 'statusCode')
EDIT (In response to comments)
If you need to take action based on the data returned in the response body (which seems odd to me), you will need to use error:
instead of statusCode:
error:function (xhr, ajaxOptions, thrownError){
switch (xhr.status) {
case 404:
// Take action, referencing xhr.responseText as needed.
}
}
As an update to The Minister's answer, you can now do this with es2015:
function Tuple(...args) {
args.forEach((val, idx) =>
Object.defineProperty(this, "item"+idx, { get: () => val })
)
}
var t = new Tuple("a", 123)
console.log(t.item0) // "a"
t.item0 = "b"
console.log(t.item0) // "a"
$arr=array('test','go for it');
$a='test';
foreach($arr as $val){
$output = 'test';
if($val === $a) $output = "";
echo $output;
}
echo "finish";
combining your statements, i think this would give you your wished result. clean and simple, without having too much statements.
for the ugly and good looking code, my recomandation would be:
function myfunction(){
if( !process_x() || !process_y() || !process_z()) {
clean_all_processes();
return;
}
/*do all the stuff you need to do*/
}
somewhere in your normal code
myfunction();
<script>
function SetBack(dir) {
document.getElementById('body').style.backgroundImage=dir;
}
SetBack('url(myniftybg.gif)');
</script>
Proper font pre-loading is a big hole in the HTML5 spec. I've gone through all of this stuff and the most reliable solution I've found is to use Font.js:
http://pomax.nihongoresources.com/pages/Font.js/
You can use it to load fonts using the same API you use to load images
var anyFont = new Font();
anyFont.src = "fonts/fileName.otf";
anyFont.onload = function () {
console.log("font loaded");
}
It's much simpler and more lightweight than Google's hulking Webfont Loader
Here's the github repo for Font.js:
It is also possible to symlink the datadir. At least in macOS, dev environment.
(homebrew) e. g.
# make sure you're not overwriting anything important, backup existing data
mv /usr/local/var/mysql [your preferred data directory]
ln -s [your preferred data directory] /usr/local/var/mysql
Restart mysql.
This is a bit confusing, but follow these steps to save the session.
To open the session, double click on particular saved session.
Add target="_blank"
to the <form>
tag.
Vagrant-lxc is a plugin for Vagrant that let's you use LXC to provision Vagrant. It does not have all the features that the default vagrant VM (VirtualBox) has but it should allow you more flexibility than docker containers. There is a video in the link showing its capabilities that is worth watching.
As a "Show tables" might be slow on larger databases, I recommend using "DESCRIBE " and check if you get true/false as a result
$tableExists = mysqli_query("DESCRIBE `myTable`");
Instead of using a %, the units vh set it to a percent of the viewport (browser window) size.
I was able to set a modal with an image and text beneath to be responsive to the browser window size using vh.
If you just want the content to scroll, you could leave out the part that limits the size of the modal body.
/*When the modal fills the screen it has an even 2.5% on top and bottom*/
/*Centers the modal*/
.modal-dialog {
margin: 2.5vh auto;
}
/*Sets the maximum height of the entire modal to 95% of the screen height*/
.modal-content {
max-height: 95vh;
overflow: scroll;
}
/*Sets the maximum height of the modal body to 90% of the screen height*/
.modal-body {
max-height: 90vh;
}
/*Sets the maximum height of the modal image to 69% of the screen height*/
.modal-body img {
max-height: 69vh;
}
This will give you exactly the strings that you asked for:
string s = "String goes here";
string lineAlignedRight = String.Format("{0,27}", s);
string lineAlignedCenter = String.Format("{0,-27}",
String.Format("{0," + ((27 + s.Length) / 2).ToString() + "}", s));
string lineAlignedLeft = String.Format("{0,-27}", s);
try $conn = mysql_connect("localhost", "root")
or $conn = mysql_connect("localhost", "root", "")
I think that what you are looking for is the Strategy Pattern.
This can be implemented in a number of ways, which have been mentionned in other answers to this question, such as:
WebElement selectgender = driver.findElement(By.id("gender"));
selectgender.sendKeys("Male");
InstanceID.getInstance(getApplicationContext()).getToken(authorizedEntity,scope)
authorizedEntity is the project number of the server
just as a .crt file is in .pem format, a .key file is also stored in .pem format. Assuming that the cert is the only thing in the .crt file (there may be root certs in there), you can just change the name to .pem. The same goes for a .key file. Which means of course that you can rename the .pem file to .key.
Which makes gtrig's answer the correct one. I just thought I'd explain why.
I had raised a support ticket against Github and got a response confirming the fact that ALL pages are public. I've now requested them to add a note to help.github.com/pages.
LocalDate.parse(
"19/05/2009" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
The other Answers with java.util.Date
, java.sql.Date
, and SimpleDateFormat
are now outdated.
LocalDate
The modern way to do date-time is work with the java.time classes, specifically LocalDate
. The LocalDate
class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter
To parse, or generate, a String representing a date-time value, use the DateTimeFormatter
class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );
Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate
, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.
You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.
DateTimeFormatter f =
DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );
Dump to console.
System.out.println( "ld: " + ld + " | output: " + output );
ld: 2009-05-19 | output: mardi 19 mai 2009
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Normal Class
: A Java class
Java Beans
:
Pojo
:
Plain Old Java Object is a Java object not bound by any restriction other than those forced by the Java Language Specification. I.e., a POJO should not have to
Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress)
, which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformation
namespace contains a class called PingReply
that has properties designed to translate the ICMP
response and deliver useful information about the pinged server such as:
The following is a simple example using WinForms
to demonstrate how ping works in c#. By providing a valid IP address in textBox1
and clicking button1
, we are creating an instance of the Ping
class, a local variable PingReply
, and a string to store the IP or URL address. We assign PingReply
to the ping Send
method, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Success
status. Finally, we extract from PingReply
the information we need to display for the user, which is described above.
using System;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace PingTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Ping p = new Ping();
PingReply r;
string s;
s = textBox1.Text;
r = p.Send(s);
if (r.Status == IPStatus.Success)
{
lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
+ " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
}
}
private void textBox1_Validated(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
{
MessageBox.Show("Please use valid IP or web address!!");
}
}
}
}
display:table-row;
will also get rid of the indentation but will remove the bullets.
Additionally to nargs
, you might want to use choices
if you know the list in advance:
>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')
For me the scrollTop way did not work, but I found other:
element.style.display = 'none';
setTimeout(function() { element.style.display = 'block' }, 100);
Did not check the minimum time for reliable css rendering though, 100ms might be overkill.
Horrible Answers Galore
Ozgur Ozcitak
When you cast from signed to unsigned (and vice versa) the internal representation of the number does not change. What changes is how the compiler interprets the sign bit.
This is completely wrong.
Mats Fredriksson
When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.
This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.
smh
Your addition operation causes the int to be converted to an unsigned int.
Wrong. Maybe it does and maybe it doesn't.
Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)
Wrong. It is either undefined behavior if it causes overflow or the value is preserved.
Anonymous
The value of i is converted to unsigned int ...
Wrong. Depends on the precision of an int relative to an unsigned int.
Taylor Price
As was previously answered, you can cast back and forth between signed and unsigned without a problem.
Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.
Now I can finally answer the question.
Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 [1]. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.
Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.
What is precision?
Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.
[Gotchas]
The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.
[1] The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.
Don't forget to convert your object into Json first using Gson()
val fromUserJson = Gson().toJson(notificationRequest.fromUser)
Then you can easily convert it back into an object using this awesome library
val fromUser = Gson().fromJson(fromUserJson, User::class.java)
Borrowing directly from Gordon's very comprehensive answer, I note that your question mentions being page-specific in forcing HTTPS/SSL connections.
function forceHTTPS(){
$httpsURL = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if( count( $_POST )>0 )
die( 'Page should be accessed with HTTPS, but a POST Submission has been sent here. Adjust the form to point to '.$httpsURL );
if( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS']!=='on' ){
if( !headers_sent() ){
header( "Status: 301 Moved Permanently" );
header( "Location: $httpsURL" );
exit();
}else{
die( '<script type="javascript">document.location.href="'.$httpsURL.'";</script>' );
}
}
}
Then, as close to the top of these pages which you want to force to connect via PHP, you can require()
a centralised file containing this (and any other) custom functions, and then simply run the forceHTTPS()
function.
I have not implemented this kind of solution personally (I have tended to use the PHP solution, like the one above, for it's simplicity), but the following may be, at least, a good start.
RewriteEngine on
# Check for POST Submission
RewriteCond %{REQUEST_METHOD} !^POST$
# Forcing HTTPS
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{SERVER_PORT} 80
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_secure [OR]
RewriteCond %{REQUEST_URI} ^something_else_secure
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
# Forcing HTTP
RewriteCond %{HTTPS} =on [OR]
RewriteCond %{SERVER_PORT} 443
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_public [OR]
RewriteCond %{REQUEST_URI} ^something_else_public
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
SELECT
a AS [blabla a],
b [blabla b],
CASE c
WHEN 1 THEN 'aaa'
WHEN 2 THEN 'bbb'
ELSE 'unknown'
END AS [my alias],
d AS [blabla d]
FROM mytable
I know its quite late to answer this, but I guess it will help anyone ahead.
Well using CSS3 FlexBox. It can be acheived.
Make you header as display:flex
and divide its entire width into 3 parts. In the first part I have placed the logo, the searchbar in second part and buttons container in last part.
apply justify-content: between
to the header container and flex-grow:1
to the searchbar.
That's it. The sample code is below.
#header {_x000D_
background-color: #323C3E;_x000D_
justify-content: space-between;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#searchBar, img{_x000D_
align-self: center;_x000D_
}_x000D_
_x000D_
#searchBar{_x000D_
flex-grow:1;_x000D_
background-color: orange;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
#searchBar input {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.button {_x000D_
padding: 22px;_x000D_
}_x000D_
_x000D_
.buttonsHolder{_x000D_
display:flex;_x000D_
}
_x000D_
<div id="header" class="d-flex justify-content-between">_x000D_
<img src="img/logo.png" />_x000D_
<div id="searchBar">_x000D_
<input type="text" />_x000D_
</div>_x000D_
<div class="buttonsHolder">_x000D_
<div class="button orange inline" id="myAccount">_x000D_
My Account_x000D_
</div>_x000D_
<div class="button red inline" id="basket">_x000D_
Basket (2)_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
The simplest way:
my_list = [1,2,3,4,5]
df['new_column'] = pd.Series(my_list).values
Edit:
Don't forget that the length of the new list should be the same of the corresponding Dataframe.
dynamic_cast
only supports pointer and reference types. It returns NULL
if the cast is impossible if the type is a pointer or throws an exception if the type is a reference type. Hence, dynamic_cast
can be used to check if an object is of a given type, static_cast
cannot (you will simply end up with an invalid value).
C-style (and other) casts have been covered in the other answers.
Change .text
to .textContent
to get/set the text content.
Or since you're dealing with a single text node, use .firstChild.data
in the same manner.
Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById
.
function toggleText(button_id)
{
var el = document.getElementById(button_id);
if (el.firstChild.data == "Lock")
{
el.firstChild.data = "Unlock";
}
else
{
el.firstChild.data = "Lock";
}
}
Or even more compact like this:
function toggleText(button_id) {
var text = document.getElementById(button_id).firstChild;
text.data = text.data == "Lock" ? "Unlock" : "Lock";
}
Using the library Datejs you can accomplish this quite elegantly, with its toString
format specifiers: http://jsfiddle.net/TeRnM/1/.
var date = new Date(1324339200000);
date.toString("MMM dd"); // "Dec 20"
If you are looking for features that notebooks in JupyterLab have that traditional Jupyter Notebooks do not, check out the JupyterLab notebooks documentation. There is a simple video showing how to use each of the features in the documentation link.
JupyterLab notebooks have the following features and more:
Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.
Look below at the working code. Copy and paste it.
import (
"bytes"
"encoding/json" // Encoding and Decoding Package
"fmt"
)
var messeging = `{
"say":"Hello",
"sendMsg":{
"user":"ANisus",
"msg":"Trying to send a message"
}
}`
type SendMsg struct {
User string `json:"user"`
Msg string `json:"msg"`
}
type Chat struct {
Say string `json:"say"`
SendMsg *SendMsg `json:"sendMsg"`
}
func main() {
/** Clean way to solve Json Decoding in Go */
/** Excellent solution */
var chat Chat
r := bytes.NewReader([]byte(messeging))
chatErr := json.NewDecoder(r).Decode(&chat)
errHandler(chatErr)
fmt.Println(chat.Say)
fmt.Println(chat.SendMsg.User)
fmt.Println(chat.SendMsg.Msg)
}
func errHandler(err error) {
if err != nil {
fmt.Println(err)
return
}
}
try putting a delay on the last color fade.
$("p#44.test").delay(3000).css("background-color","red");
What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!
collecting from Mozilla Documentation:
The NodeSelector interface This specification adds two new methods to any objects implementing the Document, DocumentFragment, or Element interfaces:
querySelector
Returns the first matching Element node within the node's subtree. If no matching node is found, null is returned.
querySelectorAll
Returns a NodeList containing all matching Element nodes within the node's subtree, or an empty NodeList if no matches are found.
and
Note: The NodeList returned by
querySelectorAll()
is not live, which means that changes in the DOM are not reflected in the collection. This is different from other DOM querying methods that return live node lists.
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
In my case, I was getting this error because I had an input named x
and I was creating (without realizing it) a local variable called x
. I thought I was trying to access an element of the input x
(which was an array), while I was actually trying to access an element of the local variable x
(which was a scalar).
Below is just for reference of numeric unique random id...
it may help you...
$query=mysql_query("select * from collectors_repair");
$row=mysql_num_rows($query);
$ind=0;
if($row>0)
{
while($rowids=mysql_fetch_array($query))
{
$already_exists[$ind]=$rowids['collector_repair_reportid'];
}
}
else
{
$already_exists[0]="nothing";
}
$break='false';
while($break=='false'){
$rand=mt_rand(10000,999999);
if(array_search($rand,$alredy_exists)===false){
$break='stop';
}else{
}
}
echo "random number is : ".$echo;
and you can add char with the code like -> $rand=mt_rand(10000,999999) .$randomchar; // assume $radomchar contains char;
This is slighly more OS independent way:
# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)
# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))
You have empty $_POST
. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.
You need something like that:
$json = file_get_contents('php://input');
$obj = json_decode($json);
Also you have wrong code for testing JSON-communication...
CURLOPT_POSTFIELDS
tells curl
to encode your parameters as application/x-www-form-urlencoded
. You need JSON-string here.
UPDATE
Your php code for test page should be like that:
$data_string = json_encode($data);
$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
Also on your web-service page you should remove one of the lines header('Content-type: application/json');
. It must be called only once.
css cannot be directly applied for the alignment of the anchor tag. The css (text-align:center;) should be applied to the parent div/element for the alignment effect to take place on the anchor tag.
The find one is good but I think you can use anotherway, especially if you need to now how many seconds is the file old
date -d "now - $( stat -c "%Y" $filename ) seconds" +%s
using GNU date
use request.getContextPath()
instead of ${pageContext.request.contextPath}
in JSP expression language.
<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);
output: willPrintMyProjectcontextPath
In my react-native project, this error is generated in the react-native-fbsdk
. Updating the react-native-fbsdk/android/build.gradle
as following fixes the issue.
compileSdkVersion 26
buildToolsVersion "26.0.1"
To delete records whose names are duplicate
;WITH CTE AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) AS T FROM @YourTable
)
DELETE FROM CTE WHERE T > 1
Be very careful: NULL is a macro used mainly for pointers. The standard way of terminating a string is:
char *buffer;
...
buffer[end_position] = '\0';
This (below) works also but it is not a big difference between assigning an integer value to a int/short/long array and assigning a character value. This is why the first version is preferred and personally I like it better.
buffer[end_position] = 0;
loadXMLDoc JS function should return false, otherwise it will result in postback.
In plain node.js:
const http = require('http')
const fs = require('fs')
const path = require('path')
process.on('uncaughtException', err => console.error('uncaughtException', err))
process.on('unhandledRejection', err => console.error('unhandledRejection', err))
const publicFolder = process.argv.length > 2 ? process.argv[2] : '.'
const port = process.argv.length > 3 ? process.argv[3] : 8080
const mediaTypes = {
zip: 'application/zip',
jpg: 'image/jpeg',
html: 'text/html',
/* add more media types */
}
const server = http.createServer(function(request, response) {
console.log(request.method + ' ' + request.url)
const filepath = path.join(publicFolder, request.url)
fs.readFile(filepath, function(err, data) {
if (err) {
response.statusCode = 404
return response.end('File not found or you made an invalid request.')
}
let mediaType = 'text/html'
const ext = path.extname(filepath)
if (ext.length > 0 && mediaTypes.hasOwnProperty(ext.slice(1))) {
mediaType = mediaTypes[ext.slice(1)]
}
response.setHeader('Content-Type', mediaType)
response.end(data)
})
})
server.on('clientError', function onClientError(err, socket) {
console.log('clientError', err)
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
})
server.listen(port, '127.0.0.1', function() {
console.log('? Development server is online.')
})
This is a simple node.js server that only serves requested files in a certain directory.
Usage:
node server.js folder port
folder
may be absolute or relative depending on the server.js
location. The default value is .
which is the directory you execute node server.js
command.
port
is 8080 by default but you can specify any port available in your OS.
In your case, I would do:
cd D:\Folder
node server.js
You can browse the files under D:\Folder
from a browser by typing http://127.0.0.1:8080/somefolder/somefile.html
Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).
Example:
var divMapLoaded = false;
$("#container").scroll(function() {
if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
$("#map-iframe").html("<iframe id=\"map-iframe\" " +
"width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
"marginheight=\"0\" marginwidth=\"0\" " +
"src=\"http://www.google.it/maps?t=m&cid=0x3e589d98063177ab&ie=UTF8&iwloc=A&brcurrent=5,0,1&ll=41.123115,16.853177&spn=0.005617,0.009943&output=embed\"" +
"></iframe>");
divMapLoaded = true;
}
The elements of a sequence need to be indented at the same level. Assuming you want two jobs (A and B) each with an ordered list of key value pairs, you should use:
jobs:
- - name: A
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
- - name: B
- schedule: "0 0/5 * 1/1 * ? *"
- - type: mongodb.cluster
- config:
- host: mongodb://localhost:27017/admin?replicaSet=rs
- minSecondaries: 2
- minOplogHours: 100
- maxSecondaryDelay: 120
Converting the sequences of (single entry) mappings to a mapping as @Tsyvarrev does is also possible, but makes you lose the ordering.
You can think of Python global variables as "module" variables - and as such they are much more useful than the traditional "global variables" from C.
A global variable is actually defined in a module's __dict__
and can be accessed from outside that module as a module attribute.
So, in your example:
# ../myproject/main.py
# Define global myList
# global myList - there is no "global" declaration at module level. Just inside
# function and methods
myList = []
# Imports
import subfile
# Do something
subfile.stuff()
print(myList[0])
And:
# ../myproject/subfile.py
# Save "hey" into myList
def stuff():
# You have to make the module main available for the
# code here.
# Placing the import inside the function body will
# usually avoid import cycles -
# unless you happen to call this function from
# either main or subfile's body (i.e. not from inside a function or method)
import main
main.mylist.append("hey")
You can add an atrribute in linearLayout : android:scrollbars="vertical"
To add view to a layout, you can use addView
method of the ViewGroup
class. For example,
TextView view = new TextView(getActivity());
view.setText("Hello World");
ViewGroup Layout = (LinearLayout) getActivity().findViewById(R.id.my_layout);
layout.addView(view);
There are also a number of remove methods. Check the documentation of ViewGroup. One simple way to remove view from a layout can be like,
layout.removeAllViews(); // then you will end up having a clean fresh layout
For windows users:
cd “C:\Program Files\Oracle\VirtualBox”
VBoxManage modifyhd “C:\Users\Chris\VirtualBox VMs\Windows 7\Windows 7.vdi” --resize 81920
http://www.howtogeek.com/124622/how-to-enlarge-a-virtual-machines-disk-in-virtualbox-or-vmware/
No, HTTP does not define any limit. However most web servers do limit size of headers they accept. For example in Apache default limit is 8KB, in IIS it's 16K. Server will return 413 Entity Too Large
error if headers size exceeds that limit.
Related question: How big can a user agent string get?
Use a tab character (\t) to separate the fields.
What we usually do with e-mail, preventing spam-folders as the end destination, is using either Gmail as the smtp server or Mandrill as the smtp server.
On the last entry; this is another trick:
SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_schema = ... and table_name = ...
To get the full calendar name from the month number, you can use calendar.month_name. Please see the documentation for more details: https://docs.python.org/2/library/calendar.html
month_no = 1
month = calendar.month_name[month_no]
# month provides "January":
print(month)
IFrame is just an "internal frame". The reason why it can be considered less secure (than not using any kind of frame at all) is because you can include content that does not originate from your domain.
All this means is that you should trust whatever you include in an iFrame or a regular frame.
Frames and IFrames are equally secure (and insecure if you include content from an untrusted source).
You should also make sure you have set appropriate Project Facets Java version. Module Properties -> Project Facets -> Java 1.6 should be checked
You can simply assign it a new value as follows,
window.location.hash
Let me point out an extremely interesting method of calculating an inverse square root 1/sqrt(x) which is a legend in the world of game design because it is mind-boggingly fast. Or wait, read the following post:
http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/
PS: I know you just want the square root but the elegance of quake overcame all resistance on my part :)
By the way, the above mentioned article also talks about the boring Newton-Raphson approximation somewhere.
Right Click Project -> New -> Folder -> Folder Name: src -> Finish
I would use Winamp to do this. Create a playlist of files you want to merge into one, select Disk Writer output plugin, choose filename and you're done. The file you will get will be correct MP3 file and you can set bitrate etc.
SELECT Priority, COALESCE(cnt, 0)
FROM (
SELECT 1 AS Priority
UNION ALL
SELECT 2 AS Priority
UNION ALL
SELECT 3 AS Priority
UNION ALL
SELECT 4 AS Priority
UNION ALL
SELECT 5 AS Priority
) p
LEFT JOIN
(
SELECT Priority, COUNT(*) AS cnt
FROM jobs
GROUP BY
Priority
) j
ON j.Priority = p.Priority
If any of you happen to use WAMP then at least in the current version (3.0.6 x64) there's a file located in <your-wamp-dir>\alias\phpmyadmin.conf
which overrides some of your php.ini options.
Edit this part:
# To import big file you can increase values
php_admin_value upload_max_filesize 512M
php_admin_value post_max_size 512M
php_admin_value max_execution_time 600
php_admin_value max_input_time 600
For Angular 10:
Failing to do step 2 will trigger this error!
Make sure to RESTART ng serve !!!
Something like this may work...
@{
var base64 = Convert.ToBase64String(Model.ByteArray);
var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
}
<img src="@imgSrc" />
As mentioned in the comments below, please use the above armed with the knowledge that although this may answer your question it may not solve your problem. Depending on your problem this may be the solution but I wouldn't completely rule out accessing the database twice.
A simple solution is to use writeFile :
require("fs").writeFile(
somepath,
arr.map(function(v){ return v.join(', ') }).join('\n'),
function (err) { console.log(err ? 'Error :'+err : 'ok') }
);
In c++ (distant, dusty memory) I think it was a little easier to look at the code and understand arrays than it is in Java sometimes. Both are row major. This illustration worked for me in helping to understand.
Given this code for a 2d array of strings...
String[][] messages;
messages = new String[][] {
{"CAT","DOG","YIN","BLACK","HIGH","DAY"},
{"kitten","puppy","yang","white","low","night"}
};
int row = messages.length;
int col = messages[0].length;
Naming my ints as if it were a 2d array (row, col) we see the values.
row = (int) 2
col = (int) 6
The last two lines of code, where we try to determine size and set them to row
and col
does not look all that intuitive and its not necessarily right.
What youre really dealing with here is this (note new variable names to illustrate):
int numOfArraysIn = messages.length;
int numOfElementsIn0 = messages[0].length;
int numOfElementsIn1 = messages[1].length;
Where messages.length
tells you messages
holds two arrays. An array of arrays.
AND then messages[x].length
yields the size of each of the individual arrays 0
1
inside messages
.
numOfArraysIn = (int) 2
numOfElementsIn0 = (int) 6
numOfElementsIn1 = (int) 6
When we print with a for each loop....
for (String str : messages[0])
System.out.print(str);
for (String str : messages[1])
System.out.print(str);
CATDOGYINBLACKHIGHDAYkittenpuppyyangwhitelownight
Trying to drop the brackets and print like this gives an error
for (String str : messages)
System.out.print(str);
incompatible types: String[] cannot be converted to String
The above is important to understand while setting up loops that use .length
to limit the step thru the array.
How about
<a href="url"><input type="button" value="Cancel"></a>
Example:
perfdb-# \df information_schema.*;
List of functions
Schema | Name | Result data type | Argument data types | Type
information_schema | _pg_char_max_length | integer | typid oid, typmod integer | normal
information_schema | _pg_char_octet_length | integer | typid oid, typmod integer | normal
information_schema | _pg_datetime_precision| integer | typid oid, typmod integer | normal
.....
information_schema | _pg_numeric_scale | integer | typid oid, typmod integer | normal
information_schema | _pg_truetypid | oid | pg_attribute, pg_type | normal
information_schema | _pg_truetypmod | integer | pg_attribute, pg_type | normal
(11 rows)