Here's a different way of doing it.
If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.
filepath = 'textfile.txt'
import os
os.startfile(filepath)
Example:
import os
os.startfile('textfile.txt')
This will open textfile.txt with Notepad if Notepad is associated with .txt files.
When you use the start command to a website it will use the default browser by default but if you want to use a specific browser then use start iexplorer.exe www.website.com
Also you cannot have http://
in the url.
I put an MD5 hash of the file's contents in its URL. That way I can set a very long expiration date, and don't have to worry about users having old JS or CSS.
I also calculate this once per file at runtime (or on file system changes) so there's nothing funny to do at design time or during the build process.
If you're using ASP.NET MVC then you can check out the code in my other answer here.
You can also use sequence unpacking with zip
:
L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
_, res = zip(*L)
print(res)
# (2, 3, 5, 4, 7, 7, 8)
This also creates a tuple _
from the discarded first elements. Extracting only the second is possible, but more verbose:
from itertools import islice
res = next(islice(zip(*L), 1, None))
<form:form method="GET" action="home.do">
<input id="Back" class="sub_but" type="submit" value="Back" />
</form:form>
This is works just fine I had tested it on IE9.
I would like to add a word of warning when you are dealing with C++11-style allocator-aware containers. Swapping and assignment have subtly different semantics.
For concreteness, let us consider a container std::vector<T, A>
, where A
is some stateful allocator type, and we'll compare the following functions:
void fs(std::vector<T, A> & a, std::vector<T, A> & b)
{
a.swap(b);
b.clear(); // not important what you do with b
}
void fm(std::vector<T, A> & a, std::vector<T, A> & b)
{
a = std::move(b);
}
The purpose of both functions fs
and fm
is to give a
the state that b
had initially. However, there is a hidden question: What happens if a.get_allocator() != b.get_allocator()
? The answer is: It depends. Let's write AT = std::allocator_traits<A>
.
If AT::propagate_on_container_move_assignment
is std::true_type
, then fm
reassigns the allocator of a
with the value of b.get_allocator()
, otherwise it does not, and a
continues to use its original allocator. In that case, the data elements need to be swapped individually, since the storage of a
and b
is not compatible.
If AT::propagate_on_container_swap
is std::true_type
, then fs
swaps both data and allocators in the expected fashion.
If AT::propagate_on_container_swap
is std::false_type
, then we need a dynamic check.
a.get_allocator() == b.get_allocator()
, then the two containers use compatible storage, and swapping proceeds in the usual fashion.a.get_allocator() != b.get_allocator()
, the program has undefined behaviour (cf. [container.requirements.general/8].The upshot is that swapping has become a non-trivial operation in C++11 as soon as your container starts supporting stateful allocators. That's a somewhat "advanced use case", but it's not entirely unlikely, since move optimizations usually only become interesting once your class manages a resource, and memory is one of the most popular resources.
Your::Application.routes.draw do
default_url_options :host => "example.com"
# ... snip ...
end
Somewhere in routes.rb
:)
ActiveXObject
is available only on IE browser. So every other useragent will throw an error
On modern browser you could use instead File API or File writer API (currently implemented only on Chrome)
In addition to the locations listed above, the OS X version of Perl also has two more ways:
The /Library/Perl/x.xx/AppendToPath file. Paths listed in this file are appended to @INC at runtime.
The /Library/Perl/x.xx/PrependToPath file. Paths listed in this file are prepended to @INC at runtime.
Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).
json_encode($array,JSON_UNESCAPED_SLASHES);
Check out the documentation on MSDN for the Hashtable class.
Represents a collection of key-and-value pairs that are organized based on the hash code of the key.
Also, keep in mind that this is not thread-safe.
How about using the INSERT ALL statement ?
INSERT ALL
INTO table_name VALUES ()
INTO table_name VALUES ()
...
SELECT Statement;
I remember that the last select statement is mandatory in order to make this request succeed. Don't remember why though. You might consider using PreparedStatement instead as well. lots of advantages !
Farid
Use this :
php -r "readfile('https://getcomposer.org/installer');" | php
This will install composer to the current directory so that you can use php composer.phar
I think you just need 'git show -c $ref'. Trying this on the git repository on a8e4a59 shows a combined diff (plus/minus chars in one of 2 columns). As the git-show manual mentions, it pretty much delegates to 'git diff-tree' so those options look useful.
I think you can use this
$("ul li:nth-child(2)").append("<span> - 2nd!</span>");
It finds the second li in each matched ul and notes it.
My solution is basically a modification of @Termininja's answer, however I have enhanced it a bit and it appears to be more than 5 times faster than the accepted answer.
public static void CopyEntireDirectory(string path, string newPath)
{
Parallel.ForEach(Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories)
,(fileName) =>
{
string output = Regex.Replace(fileName, "^" + Regex.Escape(path), newPath);
if (File.Exists(fileName))
{
Directory.CreateDirectory(Path.GetDirectoryName(output));
File.Copy(fileName, output, true);
}
else
Directory.CreateDirectory(output);
});
}
EDIT: Modifying @Ahmed Sabry to full parallel foreach does produce a better result, however the code uses recursive function and its not ideal in some situation.
public static void CopyEntireDirectory(DirectoryInfo source, DirectoryInfo target, bool overwiteFiles = true)
{
if (!source.Exists) return;
if (!target.Exists) target.Create();
Parallel.ForEach(source.GetDirectories(), (sourceChildDirectory) =>
CopyEntireDirectory(sourceChildDirectory, new DirectoryInfo(Path.Combine(target.FullName, sourceChildDirectory.Name))));
Parallel.ForEach(source.GetFiles(), sourceFile =>
sourceFile.CopyTo(Path.Combine(target.FullName, sourceFile.Name), overwiteFiles));
}
MomentJS has a function to do that:
const start = moment(j.timings.start);
const end = moment(j.timings.end);
const elapsedMinutes = end.diff(start, "minutes");
I would use phpseclib, a pure PHP SSH implementation. An example:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>
There is no newline, just the div
is a block element.
You can make the div
inline by adding display: inline
, which may be what you want.
JavaScript has an eval
function that evaluates a string and executes it as code:
eval(settings.functionName + '(' + t.parentNode.id + ')');
Apart from the client side validation with a Validator, I also recommend doing server side validation as well.
bool isValidEmail(string input)
{
try
{
var email = new System.Net.Mail.MailAddress(input);
return true;
}
catch
{
return false;
}
}
To call GET,POST,DELETE,PUT All kind of request, i have created one common function
function CallAPI($method, $api, $data) {
$url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "GET":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "POST":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
break;
case "PUT":
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
break;
}
$response = curl_exec($curl);
$data = json_decode($response);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check the HTTP Status code
switch ($httpCode) {
case 200:
$error_status = "200: Success";
return ($data);
break;
case 404:
$error_status = "404: API Not found";
break;
case 500:
$error_status = "500: servers replied with an error.";
break;
case 502:
$error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
break;
case 503:
$error_status = "503: service unavailable. Hopefully they'll be OK soon!";
break;
default:
$error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
break;
}
curl_close($curl);
echo $error_status;
die;
}
CALL Delete Method
$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);
CALL Post Method
$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);
CALL Get Method
$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);
CALL Put Method
$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);
Its much better to use java.util.LinkedList, because it's probably much more optimized, than the one that you will write.
The shorter ones are vectorized, meaning they can return a vector, like this:
((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE TRUE FALSE FALSE
The longer form evaluates left to right examining only the first element of each vector, so the above gives
((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE
As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."
So you want to use the long forms only when you are certain the vectors are length one.
You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all
and any
to reduce it to length one for use in control flow statements, like if
.
The functions all
and any
are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse
.
One final difference: the &&
and ||
only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a
; if it didn't short-circuit, as &
and |
don't, it would give an error.
a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found
Finally, see section 8.2.17 in The R Inferno, titled "and and andand".
Try this EDITED:
(SELECT COUNT(motorbike.owner_id),owner.name,transport.type FROM transport,owner,motorbike WHERE transport.type='motobike' AND owner.owner_id=motorbike.owner_id AND transport.type_id=motorbike.motorbike_id GROUP BY motorbike.owner_id)
UNION ALL
(SELECT COUNT(car.owner_id),owner.name,transport.type FROM transport,owner,car WHERE transport.type='car' AND owner.owner_id=car.owner_id AND transport.type_id=car.car_id GROUP BY car.owner_id)
Yes, standard behaviour is the value is only sent if the checkbox is checked. This typically means you need to have a way of remembering what checkboxes you are expecting on the server side since not all the data comes back from the form.
The default value is always "on", this should be consistent across browsers.
This is covered in the W3C HTML 4 recommendation:
Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.
AFAIK you can use [webView sizeThatFits:CGSizeZero]
to figure out it's content size.
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
Try this:
pointer-events:none
Adding above on the specified HTML element will prevents all click, state and cursor options.
<div class="ads">
<button id='noclick' onclick='clicked()'>Try</button>
</div>
This seems like a common misunderstanding. In Oracle's JVM, the permanent generation is not part of the heap. It's a separate space for class definitions and related data. In Java 6 and earlier, interned strings were also stored in the permanent generation. In Java 7, interned strings are stored in the main object heap.
Here is a good post on permanent generation.
I like the descriptions given for each space in Oracle's guide on JConsole:
For the HotSpot Java VM, the memory pools for serial garbage collection are the following.
- Eden Space (heap): The pool from which memory is initially allocated for most objects.
- Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.
- Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.
- Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
- Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
Java uses generational garbage collection. This means that if you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces - Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.
Both the other answers accomplish what you want.
You can use the pivot
functionality to arrange the data in a nice table
df.groupby(['Fruit','Name'],as_index = False).sum().pivot('Fruit','Name').fillna(0)
Name Bob Mike Steve Tom Tony
Fruit
Apples 16.0 9.0 10.0 0.0 0.0
Grapes 35.0 0.0 0.0 87.0 15.0
Oranges 67.0 57.0 0.0 15.0 1.0
In case you don't need javax.el (for example in a JavaSE application), use ParameterMessageInterpolator from Hibernate validator. Hibernate validator is a standalone component, which can be used without Hibernate itself.
Depend on hibernate-validator
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
Use ParameterMessageInterpolator
import javax.validation.Validation;
import javax.validation.Validator;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
private static final Validator VALIDATOR =
Validation.byDefaultProvider()
.configure()
.messageInterpolator(new ParameterMessageInterpolator())
.buildValidatorFactory()
.getValidator();
If you are writing code in Swift it would look as an example like this
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
switch section
{
case 0:
return "Apple Devices"
case 1:
return "Samsung Devices"
default:
return "Other Devices"
}
}
[Belmiro@HP-550 ~]$ uname -a
Linux HP-550 2.6.30.10-105.2.23.fc11.x86_64 #1 SMP Thu Feb 11 07:06:34 UTC 2010
x86_64 x86_64 x86_64 GNU/Linux
[Belmiro@HP-550 ~]$ lsb_release -a
LSB Version: :core-3.1-amd64:core-3.1-noarch:core-3.2-amd64:core-3.2-noarch:deskt
op-3.1-amd64:desktop-3.1-noarch:desktop-3.2-amd64:desktop-3.2-noarch
Distributor ID: Fedora
Description: Fedora release 11 (Leonidas)
Release: 11
Codename: Leonidas
[Belmiro@HP-550 ~]$
If you have to use the:
myLabel.numberOfLines = 0;
property you can also use a standard line break ("\n")
, in code, to force a new line.
You could try this: it's a very good tool, very fast and effective.
A View in Oracle and in other database systems is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. For example, if we frequently issue the following query
SELECT customerid, customername FROM customers WHERE countryid='US';
To create a view use the CREATE VIEW command as seen in this example
CREATE VIEW view_uscustomers
AS
SELECT customerid, customername FROM customers WHERE countryid='US';
This command creates a new view called view_uscustomers. Note that this command does not result in anything being actually stored in the database at all except for a data dictionary entry that defines this view. This means that every time you query this view, Oracle has to go out and execute the view and query the database data. We can query the view like this:
SELECT * FROM view_uscustomers WHERE customerid BETWEEN 100 AND 200;
And Oracle will transform the query into this:
SELECT *
FROM (select customerid, customername from customers WHERE countryid='US')
WHERE customerid BETWEEN 100 AND 200
Benefits of using Views
You can find advanced topics in this article about "How to Create and Manage Views in Oracle."
The thread's a little old. But from the title I thought it had promise for my needs. Unfortunately, my structure didn't lend itself easily to the nth-of-type solution. Here's a Thymeleaf solution.
.back-red {
background-color:red;
}
.back-green {
background-color:green;
}
<div class="container">
<div class="row" th:with="employees=${{'emp-01', 'emp-02', 'emp-03', 'emp-04', 'emp-05', 'emp-06', 'emp-07', 'emp-08', 'emp-09', 'emp-10', 'emp-11', 'emp-12'}}">
<div class="col-md-4 col-sm-6 col-xs-12" th:each="i:${#numbers.sequence(0, #lists.size(employees))}" th:classappend'(${i} % 2) == 0?back-red:back-green"><span th:text="${emplyees[i]}"></span></div>
</div>
</div>
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
private JLabel label;
private JTextField field;
public Test()
{
super("The title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 90));
((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
setLayout(new FlowLayout());
JButton btn = new JButton("Change");
btn.setActionCommand("myButton");
btn.addActionListener(this);
label = new JLabel("flag");
field = new JTextField(5);
add(field);
add(btn);
add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("myButton"))
{
label.setText(field.getText());
}
}
public static void main(String[] args)
{
new Test();
}
}
First things is this is only for advanced developers persons Who all are now beginner to php dont use this function if you are using the huge project in core php use this function
function displayAllRecords($serverName, $userName, $password, $databaseName,$sqlQuery='')
{
$databaseConnectionQuery = mysqli_connect($serverName, $userName, $password, $databaseName);
if($databaseConnectionQuery === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
return false;
}
$resultQuery = mysqli_query($databaseConnectionQuery,$sqlQuery);
$fetchFields = mysqli_fetch_fields($resultQuery);
$fetchValues = mysqli_fetch_fields($resultQuery);
if (mysqli_num_rows($resultQuery) > 0)
{
echo "<table class='table'>";
echo "<tr>";
foreach ($fetchFields as $fetchedField)
{
echo "<td>";
echo "<b>" . $fetchedField->name . "<b></a>";
echo "</td>";
}
echo "</tr>";
while($totalRows = mysqli_fetch_array($resultQuery))
{
echo "<tr>";
for($eachRecord = 0; $eachRecord < count($fetchValues);$eachRecord++)
{
echo "<td>";
echo $totalRows[$eachRecord];
echo "</td>";
}
echo "<td><a href=''><button>Edit</button></a></td>";
echo "<td><a href=''><button>Delete</button></a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No Records Found in";
}
}
All set now Pass the arguments as For Example
$queryStatment = "SELECT * From USERS "; $testing = displayAllRecords('localhost','root','root@123','email',$queryStatment); echo $testing;
Here
localhost
indicates Name of the host
,
root
indicates the username for database
root@123
indicates the password for the database
$queryStatment
for generating Query
hope it helps
d = {"name":"interpolator",
"children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)
Of course, it's unlikely that the order will be exactly preserved ... But that's just the nature of dictionaries ...
you can just hide and show the link as you like
$(link).hide();
$(link).show();
I found this wonderful mapping script (mapper.js) that I have used in the past. What's different about it is you can hover over the map or a link on your page to make the map area highlight. Sadly it's written in javascript and requires a lot of in-line coding in the HTML - I would love to see this script ported over to jQuery :P
Also, check out all the demos! I think this example could almost be made into a simple online game (without using flash) - make sure you click on the different camera angles.
A scripting language is typically:
While a non-scripting language is usually: 1. Statically typed 2. Compiled, with emphasis on performance 3. Requires more boilerplate code, leading to slower prototyping but more readability and long-term maintainability 4. Used for large projects, adapts to many design patterns
But it's more of a historical difference nowadays, in my opinion. Javascript and Perl were written with small, simple scripts in mind, while C++ was written with complex applications in mind; but both can be used either way. And many programming languages, modern and old alike, blur the line anyway (and it was fuzzy in the first place!).
The sad thing is, I've known a few developers who loathes what they perceived as "scripting languages", thinking them to be simpler and not as powerful. My opinion is that old cliche - use the right tool for the job.
According to Gil great answer I solved by Overriding the getItemViewType as explained by Gil. His answer is great and have to be marked as correct. In any case, I add the code to reach the score:
In your recycler adapter:
@Override
public int getItemViewType(int position) {
int viewType = 0;
// add here your booleans or switch() to set viewType at your needed
// I.E if (position == 0) viewType = 1; etc. etc.
return viewType;
}
@Override
public FileViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout_for_first_row, parent, false));
}
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_other_rows, parent, false));
}
By doing this, you can set whatever custom layout for whatever row!
Use FB static method getCurrentProfile() of Profile class to retrieve those info.
Profile profile = Profile.getCurrentProfile();
String firstName = profile.getFirstName());
System.out.println(profile.getProfilePictureUri(20,20));
System.out.println(profile.getLinkUri());
To change only "background" (add corners, change color, ....) you can put it into FrameLayout with wanted background drawable, else you need to make nine patch background for to not lose spinner arrow. Spinner background is transparent.
This is a complete example loading image from URL, creating with PIL, printing the size and resizing...
import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)
from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))
width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)
Works for IE6+, FF 22+, Chrome, Safari, Edge (Only tested in IE9+, but should work for lower versions)
If you need support for pasting HTML or Firefox <= 22, see Solution #2.
<div id='editableDiv' contenteditable='true'>Paste</div>
function handlePaste (e) {
var clipboardData, pastedData;
// Stop data actually being pasted into div
e.stopPropagation();
e.preventDefault();
// Get pasted data via clipboard API
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
// Do whatever with pasteddata
alert(pastedData);
}
document.getElementById('editableDiv').addEventListener('paste', handlePaste);
JSFiddle: https://jsfiddle.net/swL8ftLs/12/
Note that this solution uses the parameter 'Text' for the getData
function, which is non-standard. However, it works in all browsers at the time of writing.
Tested in IE6+, FF 3.5+, Chrome, Safari, Edge
<div id='div' contenteditable='true'>Paste</div>
var editableDiv = document.getElementById('editableDiv');
function handlepaste (e) {
var types, pastedData, savedContent;
// Browsers that support the 'text/html' type in the Clipboard API (Chrome, Firefox 22+)
if (e && e.clipboardData && e.clipboardData.types && e.clipboardData.getData) {
// Check for 'text/html' in types list. See abligh's answer below for deatils on
// why the DOMStringList bit is needed. We cannot fall back to 'text/plain' as
// Safari/Edge don't advertise HTML data even if it is available
types = e.clipboardData.types;
if (((types instanceof DOMStringList) && types.contains("text/html")) || (types.indexOf && types.indexOf('text/html') !== -1)) {
// Extract data and pass it to callback
pastedData = e.clipboardData.getData('text/html');
processPaste(editableDiv, pastedData);
// Stop the data from actually being pasted
e.stopPropagation();
e.preventDefault();
return false;
}
}
// Everything else: Move existing element contents to a DocumentFragment for safekeeping
savedContent = document.createDocumentFragment();
while(editableDiv.childNodes.length > 0) {
savedContent.appendChild(editableDiv.childNodes[0]);
}
// Then wait for browser to paste content into it and cleanup
waitForPastedData(editableDiv, savedContent);
return true;
}
function waitForPastedData (elem, savedContent) {
// If data has been processes by browser, process it
if (elem.childNodes && elem.childNodes.length > 0) {
// Retrieve pasted content via innerHTML
// (Alternatively loop through elem.childNodes or elem.getElementsByTagName here)
var pastedData = elem.innerHTML;
// Restore saved content
elem.innerHTML = "";
elem.appendChild(savedContent);
// Call callback
processPaste(elem, pastedData);
}
// Else wait 20ms and try again
else {
setTimeout(function () {
waitForPastedData(elem, savedContent)
}, 20);
}
}
function processPaste (elem, pastedData) {
// Do whatever with gathered data;
alert(pastedData);
elem.focus();
}
// Modern browsers. Note: 3rd argument is required for Firefox <= 6
if (editableDiv.addEventListener) {
editableDiv.addEventListener('paste', handlepaste, false);
}
// IE <= 8
else {
editableDiv.attachEvent('onpaste', handlepaste);
}
JSFiddle: https://jsfiddle.net/nicoburns/wrqmuabo/23/
The onpaste
event of the div
has the handlePaste
function attached to it and passed a single argument: the event
object for the paste event. Of particular interest to us is the clipboardData
property of this event which enables clipboard access in non-ie browsers. In IE the equivalent is window.clipboardData
, although this has a slightly different API.
See resources section below.
The handlepaste
function:
This function has two branches.
The first checks for the existence of event.clipboardData
and checks whether it's types
property contains 'text/html' (types
may be either a DOMStringList
which is checked using the contains
method, or a string which is checked using the indexOf
method). If all of these conditions are fulfilled, then we proceed as in solution #1, except with 'text/html' instead of 'text/plain'. This currently works in Chrome and Firefox 22+.
If this method is not supported (all other browsers), then we
DocumentFragment
waitForPastedData
functionThe waitforpastedata
function:
This function first polls for the pasted data (once per 20ms), which is necessary because it doesn't appear straight away. When the data has appeared it:
The processpaste
function:
Does arbitrary things with the pasted data. In this case we just alert the data, you can do whatever you like. You will probably want to run the pasted data through some kind of data sanitising process.
Saving and restoring the cursor position
In a real sitution you would probably want to save the selection before, and restore it afterwards (Set cursor position on contentEditable <div>). You could then insert the pasted data at the position the cursor was in when the user initiated the paste action.
Thanks to Tim Down to suggesting the use of a DocumentFragment, and abligh for catching an error in Firefox due to the use of DOMStringList instead of a string for clipboardData.types
You could use the JavaScript "ondrag" event to fire continuously. It is better than "input" due to the following reasons:
Browser support.
Could differentiate between "ondrag" and "change" event. "input" fires for both drag and change.
In jQuery:
$('#sample').on('drag',function(e){
});
Reference: http://www.w3schools.com/TAgs/ev_ondrag.asp
public static void BubbleSort(int[] a)
{
for (int i = 1; i <= a.Length - 1; ++i)
for (int j = 0; j < a.Length - i; ++j)
if (a[j] > a[j + 1])
Swap(ref a[j], ref a[j + 1]);
}
public static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
Here is simple solution with Jquery. It works globally. Have a look on the code.
$('document').on("click", ".clear", function(){
$(this).closest('form').trigger("reset");
})
Add a clear class to a button in every form you need to reset it. For example:
<button class="button clear" type="reset">Clear</button>
>> /dev/null
redirects standard output (stdout
) to /dev/null
, which discards it.
(The >>
seems sort of superfluous, since >>
means append while >
means truncate and write, and either appending to or writing to /dev/null
has the same net effect. I usually just use >
for that reason.)
2>&1
redirects standard error (2
) to standard output (1
), which then discards it as well since standard output has already been redirected.
Very simply: use an XML library. That way it will actually be right instead of requiring detailed knowledge of bits of the XML spec.
When it comes to Google Analytics I found raik's answer at Secure Google tracking cookies very useful. It set secure and samesite to a value.
ga('create', 'UA-XXXXX-Y', {
cookieFlags: 'max-age=7200;secure;samesite=none'
});
Also more info in this blog post
I just changed availability date to a future date. After doing that, I received following message -
You have selected an Available Date in the future. This will remove your currently live version from the App Store until the new date. Changing Available Date affects all versions of the application, both Ready For Sale and In Review.
Which means that the app is removed and no longer available.
NOTE: This answer addresses enterprise-class development in-the-large.
This is an RDBMS issue, not just SQL Server, and the behavior can be very interesting. For one, while it is common for primary keys to be automatically (uniquely) indexed, it is NOT absolute. There are times when it is essential that a primary key NOT be uniquely indexed.
In most RDBMSs, a unique index will automatically be created on a primary key if one does not already exist. Therefore, you can create your own index on the primary key column before declaring it as a primary key, then that index will be used (if acceptable) by the database engine when you apply the primary key declaration. Often, you can create the primary key and allow its default unique index to be created, then create your own alternate index on that column, then drop the default index.
Now for the fun part--when do you NOT want a unique primary key index? You don't want one, and can't tolerate one, when your table acquires enough data (rows) to make the maintenance of the index too expensive. This varies based on the hardware, the RDBMS engine, characteristics of the table and the database, and the system load. However, it typically begins to manifest once a table reaches a few million rows.
The essential issue is that each insert of a row or update of the primary key column results in an index scan to ensure uniqueness. That unique index scan (or its equivalent in whichever RDBMS) becomes much more expensive as the table grows, until it dominates the performance of the table.
I have dealt with this issue many times with tables as large as two billion rows, 8 TBs of storage, and forty million row inserts per day. I was tasked to redesign the system involved, which included dropping the unique primary key index practically as step one. Indeed, dropping that index was necessary in production simply to recover from an outage, before we even got close to a redesign. That redesign included finding other ways to ensure the uniqueness of the primary key and to provide quick access to the data.
to remove only the first of several equal entries
with a lambda
boolean[] done = {false};
String[] arr = Arrays.stream( foo ).filter( e ->
! (! done[0] && Objects.equals( e, item ) && (done[0] = true) ))
.toArray(String[]::new);
can remove null
entries
If str
is null, undefined or 0, this code will set it to "hai"
function(nodeBox, str) {
str = str || "hai";
.
.
.
If you also need to pass 0, you can use:
function(nodeBox, str) {
if (typeof str === "undefined" || str === null) {
str = "hai";
}
.
.
.
import java.util.Stack;
class Practice
{
public static void main(String arr[])
{
Practice prc = new Practice();
TreeNode node1 = (prc).new TreeNode(1);
TreeNode node2 = (prc).new TreeNode(2);
TreeNode node3 = (prc).new TreeNode(3);
TreeNode node4 = (prc).new TreeNode(4);
TreeNode node5 = (prc).new TreeNode(5);
TreeNode node6 = (prc).new TreeNode(6);
TreeNode node7 = (prc).new TreeNode(7);
node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
node3.left = node6;
node3.right = node7;
postOrderIteratively(node1);
}
public static void postOrderIteratively(TreeNode root)
{
Stack<Entry> stack = new Stack<Entry>();
Practice prc = new Practice();
stack.push((prc).new Entry(root, false));
while (!stack.isEmpty())
{
Entry entry = stack.pop();
TreeNode node = entry.node;
if (entry.flag == false)
{
if (node.right == null && node.left == null)
{
System.out.println(node.data);
} else
{
stack.push((prc).new Entry(node, true));
if (node.right != null)
{
stack.push((prc).new Entry(node.right, false));
}
if (node.left != null)
{
stack.push((prc).new Entry(node.left, false));
}
}
} else
{
System.out.println(node.data);
}
}
}
class TreeNode
{
int data;
int leafCount;
TreeNode left;
TreeNode right;
public TreeNode(int data)
{
this.data = data;
}
public int getLeafCount()
{
return leafCount;
}
public void setLeafCount(int leafCount)
{
this.leafCount = leafCount;
}
public TreeNode getLeft()
{
return left;
}
public void setLeft(TreeNode left)
{
this.left = left;
}
public TreeNode getRight()
{
return right;
}
public void setRight(TreeNode right)
{
this.right = right;
}
@Override
public String toString()
{
return "" + this.data;
}
}
class Entry
{
Entry(TreeNode node, boolean flag)
{
this.node = node;
this.flag = flag;
}
TreeNode node;
boolean flag;
@Override
public String toString()
{
return node.toString();
}
}
}
If you want multiple string replacement:
NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo
fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/
If you don't want to use fgets, following method will work for you :-
int readline(FILE *f, char *buffer, size_t len)
{
char c;
int i;
memset(buffer, 0, len);
for (i = 0; i < len; i++)
{
int c = fgetc(f);
if (!feof(f))
{
if (c == '\r')
buffer[i] = 0;
else if (c == '\n')
{
buffer[i] = 0;
return i+1;
}
else
buffer[i] = c;
}
else
{
//fprintf(stderr, "read_line(): recv returned %d\n", c);
return -1;
}
}
return -1;
}
Here is the another solution to hide dynamically a column
define class for both th and td of the column to hide
<table>
<tr>
<th> Column 1 </th>
<th class="dynamic-hidden-col"> Column 2 </th>
<th Column 3 </th>
</tr>
<tr>
<td> Value 1 </td>
<td class="dynamic-hidden-col"> Value 2 </td>
<td> Value 3 </td>
</tr>
<td> row 2 Value 1 </td>
<td class="dynamic-hidden-col"> row 2 Value 2 </td>
<td> row 2 Value 3 </td>
<tr>
</table>
Here is the Jquery script for hide column.
$('#hide-col').click(function () {
$(".dynmic-hidden-col").hide();
});
This way the table column can be hidden dynamically.
use:
opener.document.<id of document>.innerHTML = xmlhttp.responseText;
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
If you're using getline
after cin >> something
, you need to flush the newline out of the buffer in between.
My personal favourite for this if no characters past the newline are needed is cin.sync()
. However, it is implementation defined, so it might not work the same way as it does for me. For something solid, use cin.ignore()
. Or make use of std::ws
to remove leading whitespace if desirable:
int a;
cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
//discard characters until newline is found
//my method: cin.sync(); //discard unread characters
string s;
getline (cin, s); //newline is gone, so this executes
//other method: getline(cin >> ws, s); //remove all leading whitespace
I was getting that behind a corporate proxy.
Solved by:
git config http.sslVerify "false"
In python 3 urllib2 was merged into urllib. See also another Stack Overflow question and the urllib PEP 3108.
To make Python 2 code work in Python 3:
try:
import urllib.request as urllib2
except ImportError:
import urllib2
More correct variant:
{
struct timespec delta = {5 /*secs*/, 135 /*nanosecs*/};
while (nanosleep(&delta, &delta));
}
If it is the basic JavaScript split function, look at documentation, JavaScript split() Method.
Basically, you just do this:
var array = myString.split(' -- ')
Then your two values are stored in the array - you can get the values like this:
var firstValue = array[0];
var secondValue = array[1];
You can always use iptables to delete the rules. If you have a lot of rules, just output them using the following command.
iptables-save > myfile
vi
to edit them from the commend line. Just use the "dd" to delete the lines you no longer want.
iptables-restore < myfile and you're good to go.
REMEMBER THAT IF YOU DON'T CONFIGURE YOUR OS TO SAVE THE RULES TO A FILE AND THEN LOAD THE FILE DURING THE BOOT THAT YOUR RULES WILL BE LOST.
In ES5 supported (or shimmed) browsers...
var keys = Object.keys(myHash);
var values = keys.map(function(v) { return myHash[v]; });
Shims from MDN...
I faced the same problem i just add the singletone instance to get resource as referred by Erick
MainFragmentActivity.defaultInstance().getResources().getString(R.string.app_name);
you can also use
getActivity().getResources().getString(R.string.app_name);
I hope this will help.
<?php
function getBetween($content,$start,$end){
$r = explode($start, $content);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
?>
Example:
<?php
$content = "Try to find the guy in the middle with this function!";
$start = "Try to find ";
$end = " with this function!";
$output = getBetween($content,$start,$end);
echo $output;
?>
This will return "the guy in the middle".
sudo chmod 666 /var/run/docker.sock
this helped me while i was getting error even to log in to the docker But now this works completely fine in my system.
A portable approach that works equally well on Linux or Windows (where there is no /dev/null):
echo | gcc -dM -E -
For c++ you may use (replace c++11
with whatever version you use):
echo | gcc -x c++ -std=c++11 -dM -E -
It works by telling gcc to preprocess stdin (which is produced by echo) and print all preprocessor defines (search for -dletters
). If you want to know what defines are added when you include a header file you can use -dD
option which is similar to -dM but does not include predefined macros:
echo "#include <stdlib.h>" | gcc -x c++ -std=c++11 -dD -E -
Note, however, that empty input still produces lots of defines with -dD
option.
I had this issue happen for me as well...the issue was the packer wasn't running it seemed probably because my default shell was zsh. react-native tires to open a new terminal window and run .../node_modules/react-native/packager/launchPackager.command
but this didn't run. Manually running that (and keeping it running) fixed this for me.
Subtract from another date object
var d = new Date();
d.setHours(d.getHours() - 2);
In TestNG, you use dependsOnMethods and/or dependsOnGroups:
@Test(groups = "a")
public void f1() {}
@Test(groups = "a")
public void f2() {}
@Test(dependsOnGroups = "a")
public void g() {}
In this case, g() will only run after f1() and f2() have completed and succeeded.
You will find a lot of examples in the documentation: http://testng.org/doc/documentation-main.html#test-groups
Just code it like this:
.OwnerJoe {
//other things here
&:before{
content: "Joe's Task: ";
}
}
There are many ways of doing this(listed by priority, specific to the OP's problem)
Option 1: Straight approach - Create multiple functions for each type you expect rather than having one generic function.
public static bool ConfigSettingInt(string settingName)
{
return Convert.ToBoolean(ConfigurationManager.AppSettings[settingName]);
}
Option 2: When you don't want to use fancy methods of conversion - Cast the value to object and then to generic type.
public static T ConfigSetting<T>(string settingName)
{
return (T)(object)ConfigurationManager.AppSettings[settingName];
}
Note - This will throw an error if the cast is not valid(your case). I would not recommend doing this if you are not sure about the type casting, rather go for option 3.
Option 3: Generic with type safety - Create a generic function to handle type conversion.
public static T ConvertValue<T,U>(U value) where U : IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
Note - T is the expected type, note the where constraint here(type of U must be IConvertible to save us from the errors)
This worked on my test file (note the index in VBA starts from zero):
Sub DV_Test()
Dim ValidationList(5) As Variant, i As Integer
For i = 0 To UBound(ValidationList)
ValidationList(i) = i + 1
Next
With Range("A1").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlEqual, Formula1:=Join(ValidationList, ",")
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
I used xlEqual
because that's what I think you are trying to get people to select one of the list.
Delete node_modules
rm -r node_modules
install packages again
npm install
I had a similar problem. It turned out, I was including an old header file of the same name from an old folder. I deleted the old file changed the #include directive to point to my new file and all was good.
To get it to work with Apache, we needed one extra step.
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain_encrypted.key
openssl rsa -in domain_encrypted.key -out domain.key
The final command decrypts the key for use with Apache. The domain.key file should look like this:
-----BEGIN RSA PRIVATE KEY-----
MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3
LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp
YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG
A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq
-----END RSA PRIVATE KEY-----
I'd recommend using Python's with
statement for managing resources that need to be cleaned up. The problem with using an explicit close()
statement is that you have to worry about people forgetting to call it at all or forgetting to place it in a finally
block to prevent a resource leak when an exception occurs.
To use the with
statement, create a class with the following methods:
def __enter__(self)
def __exit__(self, exc_type, exc_value, traceback)
In your example above, you'd use
class Package:
def __init__(self):
self.files = []
def __enter__(self):
return self
# ...
def __exit__(self, exc_type, exc_value, traceback):
for file in self.files:
os.unlink(file)
Then, when someone wanted to use your class, they'd do the following:
with Package() as package_obj:
# use package_obj
The variable package_obj will be an instance of type Package (it's the value returned by the __enter__
method). Its __exit__
method will automatically be called, regardless of whether or not an exception occurs.
You could even take this approach a step further. In the example above, someone could still instantiate Package using its constructor without using the with
clause. You don't want that to happen. You can fix this by creating a PackageResource class that defines the __enter__
and __exit__
methods. Then, the Package class would be defined strictly inside the __enter__
method and returned. That way, the caller never could instantiate the Package class without using a with
statement:
class PackageResource:
def __enter__(self):
class Package:
...
self.package_obj = Package()
return self.package_obj
def __exit__(self, exc_type, exc_value, traceback):
self.package_obj.cleanup()
You'd use this as follows:
with PackageResource() as package_obj:
# use package_obj
Create an extension method?
Console.WriteLine(value.ToGBString());
// ...
public static class DoubleExtensions
{
public static string ToGBString(this double value)
{
return value.ToString(CultureInfo.GetCultureInfo("en-GB"));
}
}
All answers are OK, depending on how academic you want to be. If you wish to follow the Java specifications accurately, use the following:
private static final Pattern DOUBLE_PATTERN = Pattern.compile(
"[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
"([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
"(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
"[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
public static boolean isFloat(String s)
{
return DOUBLE_PATTERN.matcher(s).matches();
}
This code is based on the JavaDocs at Double.
So this is a stupid error message because it doesn't tell you what file it can't find.
Run the command again with the verbose flag gcc -v
to see what gcc is up to.
In my case, it happened it was trying to call cc1plus
. I checked, I don't have that. Installed mingw's C++ compiler and then I did.
Using CSS only:
Right/Left Flippiing: Working Fiddle
.Container
{
height: 200px;
overflow-x: auto;
}
.Content
{
height: 300px;
}
.Flipped
{
direction: rtl;
}
.Content
{
direction: ltr;
}
Top/Bottom Flipping: Working Fiddle
.Container
{
width: 200px;
overflow-y: auto;
}
.Content
{
width: 300px;
}
.Flipped, .Flipped .Content
{
transform:rotateX(180deg);
-ms-transform:rotateX(180deg); /* IE 9 */
-webkit-transform:rotateX(180deg); /* Safari and Chrome */
}
.widget-HomePageSlider .slider-loader-hide {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
z-index: 10000;
background: white;
}
This code works on ROOTED phones if the app is moved to /system/aps
, and they have the following permissions in the manifest:
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
Code
private void turnGpsOn (Context context) {
beforeEnable = Settings.Secure.getString (context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
String newSet = String.format ("%s,%s",
beforeEnable,
LocationManager.GPS_PROVIDER);
try {
Settings.Secure.putString (context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
newSet);
} catch(Exception e) {}
}
private void turnGpsOff (Context context) {
if (null == beforeEnable) {
String str = Settings.Secure.getString (context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (null == str) {
str = "";
} else {
String[] list = str.split (",");
str = "";
int j = 0;
for (int i = 0; i < list.length; i++) {
if (!list[i].equals (LocationManager.GPS_PROVIDER)) {
if (j > 0) {
str += ",";
}
str += list[i];
j++;
}
}
beforeEnable = str;
}
}
try {
Settings.Secure.putString (context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
beforeEnable);
} catch(Exception e) {}
}
As you have noticed, xscale
and yscale
does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)
A complete example showing both x and y scaling:
import numpy as np
import pylab as plt
import matplotlib.ticker as ticker
# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)
# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)
ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')
plt.show()
And finally I have the credits for a picture:
Note that, if you have text.usetex: true
as I have, you may want to enclose the labels in $
, like so: '${0:g}$'
.
You have to use Promise to print or store values of element.
var ExpectedValue:string ="AllTestings.com";
element(by.id("xyz")).getAttribute("value").then(function (Text) {
expect(Text.trim()).toEqual("ExpectedValue", "Wrong page navigated");//Assertion
console.log("Text");//Print here in Console
});
This is just my personal opinion and folks from web API team can probably articulate it better but here is my 2c.
First of all, I think it is not a question of one over another. You can use them both depending on what you want to do in your action method but in order to understand the real power of IHttpActionResult
, you will probably need to step outside those convenient helper methods of ApiController
such as Ok
, NotFound
, etc.
Basically, I think a class implementing IHttpActionResult
as a factory of HttpResponseMessage
. With that mind set, it now becomes an object that need to be returned and a factory that produces it. In general programming sense, you can create the object yourself in certain cases and in certain cases, you need a factory to do that. Same here.
If you want to return a response which needs to be constructed through a complex logic, say lots of response headers, etc, you can abstract all those logic into an action result class implementing IHttpActionResult
and use it in multiple action methods to return response.
Another advantage of using IHttpActionResult
as return type is that it makes ASP.NET Web API action method similar to MVC. You can return any action result without getting caught in media formatters.
Of course, as noted by Darrel, you can chain action results and create a powerful micro-pipeline similar to message handlers themselves in the API pipeline. This you will need depending on the complexity of your action method.
Long story short - it is not IHttpActionResult
versus HttpResponseMessage
. Basically, it is how you want to create the response. Do it yourself or through a factory.
You can use [];
var indexValue = Index[1];
Vim has a branch operator \&
that is useful when searching for a line containing a set of words, in any order. Moreover, extending the set of required words is trivial.
For example,
/.*jack\&.*james
will match a line containing jack
and james
, in any order.
See this answer for more information on usage. I am not aware of any other regex flavor that implements branching; the operator is not even documented on the Regular Expression wikipedia entry.
Ryan Bates uses a nice little bit of code in his Railscast on beta invitations. This produces a 40 character alphanumeric string.
Digest::SHA1.hexdigest([Time.now, rand].join)
The other best solution as below to check empty or not ?
for(var item in listEnumerable)
{
var count=item.Length;
if(count>0)
{
// not empty or null
}
else
{
// empty
}
}
This is a specific issue for Windows Vista, 7, 8 (and presumably newer).
User Account Control (UAC) is a feature in Windows that can help you stay in control of your computer by informing you when a program makes a change that requires administrator-level permission. UAC works by adjusting the permission level of your user account.
This is applied mostly to C:\Program Files. You may have noticed sometimes, that some applications can see files in C:\Program Files that does not exist there. You know why? Windows now tend to have "C:\Program Files" folder customized for every user. For example, old applications store config files (like .ini) in the same folder where the executable files are stored. In the good old days all users had the same configurations for such apps. In nowadays Windows stores configs in the special folder tied to the user account. Thus, now different users may have different configs while application still think that config files are in the same folder with the executables.
XAMPP does not like to have different config for different users. In fact it is not a config file for XAMPP, it is folders where you keep your projects and databases. The idea of XAMPP is to make projects same for all users. This is a source of a conflict with Windows.
All you need is to avoid installing XAMPP into C:\Program Files. Thus XAMPP will always use the original files for all users and there would be no confusion.
I recommend to install XAMPP into the special folder in root directory like in C:\XAMPP. But before you choose the folder you need to click on this warning message.
I was facing the similar issue. My env details - Python 2.7.11 pip 9.0.1 CentOS release 5.11 (Final)
Error on python interpreter -
>>> import mysql.connector
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named mysql.connector
>>>
Use pip to search the available module -
$ pip search mysql-connector | grep --color mysql-connector-python
mysql-connector-python-rf (2.2.2) - MySQL driver written in Python
mysql-connector-python (2.0.4) - MySQL driver written in Python
Install the mysql-connector-python-rf -
$ pip install mysql-connector-python-rf
Verify
$ python
Python 2.7.11 (default, Apr 26 2016, 13:18:56)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>>
Thanks =)
For python3 and later use the next command: $ pip3 install mysql-connector-python-rf
If you do use moment.js you would use the moment().utc() function to convert a moment object to UTC. You can also handle a nice format inside the controller instead of the view by using the moment().format() function. For example:
moment(myDate).utc().format('MM/DD/YYYY')
Here's also nice way to achieve this via UI.
0) Right click on PowerShell icon when on task bar
1) Shift + right click on Windows PowerShell
2) "Run as different user"
You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:
{el1, el2, {el31, el32, el33}, {el41, el42}}
var MainObj = {_x000D_
_x000D_
prop1: "prop1MainObj",_x000D_
_x000D_
Obj1: {_x000D_
prop1: "prop1Obj1",_x000D_
prop2: "prop2Obj1", _x000D_
Obj2: {_x000D_
prop1: "hey you",_x000D_
prop2: "prop2Obj2"_x000D_
}_x000D_
},_x000D_
_x000D_
Obj3: {_x000D_
prop1: "prop1Obj3",_x000D_
prop2: "prop2Obj3"_x000D_
},_x000D_
_x000D_
Obj4: {_x000D_
prop1: true,_x000D_
prop2: 3_x000D_
} _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
Here is what I used for TSQL which took care of the problem that my table name could contain the schema name and possibly the database name:
DECLARE @THETABLE varchar(100);
SET @THETABLE = 'theschema.thetable';
select i.*
from sys.indexes i
where i.object_id = OBJECT_ID(@THETABLE)
and i.name is not NULL;
The use case for this is that I wanted the list of indexes for a named table so I could write a procedure that would dynamically compress all indexes on a table.
I found a combination of these answers gave me the best outcome - allowing me to still position the tooltip and attach it to the relevant container:
$('body').on('mouseenter', '[rel=tooltip]', function(){
var el = $(this);
if (el.data('tooltip') === undefined) {
el.tooltip({
placement: el.data("placement") || "top",
container: el.data("container") || false
});
}
el.tooltip('show');
});
$('body').on('mouseleave', '[rel=tooltip]', function(){
$(this).tooltip('hide');
});
Relevant HTML:
<button rel="tooltip" class="btn" data-placement="bottom" data-container=".some-parent" title="Show Tooltip">
<i class="icon-some-icon"></i>
</button>
The best way, and the right way to do it is using Uri.Authority
field
Load and use Uri like so :
Uri NewUri;
if (Uri.TryCreate([string with your Url], UriKind.Absolute, out NewUri))
{
Console.Writeline(NewUri.Authority);
}
Input : http://support.domain.com/default.aspx?id=12345
Output : support.domain.com
Input : http://www.domain.com/default.aspx?id=12345
output : www.domain.com
Input : http://localhost/default.aspx?id=12345
Output : localhost
If you want to manipulate Url, using Uri object is the good way to do it. https://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx
Simply add a -h
after adding your credentials using a -u -p
, and it will run with elevated privileges.
In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().
Using ForEach:
List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
if(eachCategory.toString().equals("3")){
String name = eachCategory.name();
}
});
Or, using Filter:
When you want to find with code:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
When you want to find with name:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
Hope it helps! I know this is a very old post, but someone can get help.
ok, it's a older post but i'm facing this problem and i have found my personal solution.. maybe can help someone else..
function objToQueryString(obj){
var k = Object.keys(obj);
var s = "";
for(var i=0;i<k.length;i++) {
s += k[i] + "=" + encodeURIComponent(obj[k[i]]);
if (i != k.length -1) s += "&";
}
return s;
};
Eran's answer is good, but I would append to that. You need to watch any interactivity that is not inline to the object (that is, if an onclick event calls a function, it still will), but if there is some javascript or jQuery event handling attached to that ID, it will be basically abandoned:
$("#myId").on("click", function() {});
If the ID is now changed to #myID123, the function attached above will no longer function correctly from my experience.
jakub.g's answer is correct, however an example using grunt seems a bit complex.
So my simpler answer:
- Sending a command line argument to an npm script
Syntax for sending command line arguments to an npm script:
npm run [command] [-- <args>]
Imagine we have an npm start task in our package.json to kick off webpack dev server:
"scripts": {
"start": "webpack-dev-server --port 5000"
},
We run this from the command line with npm start
Now if we want to pass in a port to the npm script:
"scripts": {
"start": "webpack-dev-server --port process.env.port || 8080"
},
running this and passing the port e.g. 5000 via command line would be as follows:
npm start --port:5000
- Using package.json config:
As mentioned by jakub.g, you can alternatively set params in the config of your package.json
"config": {
"myPort": "5000"
}
"scripts": {
"start": "webpack-dev-server --port process.env.npm_package_config_myPort || 8080"
},
npm start
will use the port specified in your config, or alternatively you can override it
npm config set myPackage:myPort 3000
- Setting a param in your npm script
An example of reading a variable set in your npm script. In this example NODE_ENV
"scripts": {
"start:prod": "NODE_ENV=prod node server.js",
"start:dev": "NODE_ENV=dev node server.js"
},
read NODE_ENV in server.js either prod or dev
var env = process.env.NODE_ENV || 'prod'
if(env === 'dev'){
var app = require("./serverDev.js");
} else {
var app = require("./serverProd.js");
}
Try this:
<script type="text/javascript">
$.fn.toggleFuncs = function() {
var functions = Array.prototype.slice.call(arguments),
_this = this.click(function(){
var i = _this.data('func_count') || 0;
functions[i%functions.length]();
_this.data('func_count', i+1);
});
}
$('$showmenu').toggleFuncs(
function() {
$( ".menu" ).toggle( "drop" );
},
function() {
$( ".menu" ).toggle( "drop" );
}
);
</script>
First fuction is an alternative to JQuery deprecated toggle :) . Works good with JQuery 2.0.3 and JQuery UI 1.10.3
There is generally no such thing as the absolute path
to a file (this statement means that there may be more than one in general, hence the use of the definite article the is not appropriate). An absolute path
is any path that start from the root "/" and designates a file without ambiguity independently of the working directory.(see for example wikipedia).
A relative path
is a path that is to be interpreted starting from another directory. It may be the working directory if it is a relative path
being manipulated by an application
(though not necessarily). When it is in a symbolic link in a directory, it is generally intended to be relative to that directory (though the user may have other uses in mind).
Hence an absolute path is just a path relative to the root directory.
A path (absolute or relative) may or may not contain symbolic links. If it does not, it is also somewhat impervious to changes in the linking structure, but this is not necessarily required or even desirable. Some people call canonical path
( or canonical file name
or resolved path
) an absolute path
in which all symbolic links have been resolved, i.e. have been replaced by a path to whetever they link to. The commands realpath
and readlink
both look for a canonical path, but only realpath
has an option for getting an absolute path without bothering to resolve symbolic links (along with several other options to get various kind of paths, absolute or relative to some directory).
This calls for several remarks:
realpath
and readlink
have options to account for that.canonical
. Hence the concept is time (or environment) dependent.canonical path
to a file, for two
reasons:
ro
) on several mount points.Hence, even with the much more restrictive definition of canonical path
, there may be several canonical paths to a file. This also means that the qualifier canonical
is somewhat inadequate since it usually implies a notion of uniqueness.
This expands a brief discussion of the topic in an answer to another similar question at Bash: retrieve absolute path given relative
My conclusion is that realpath
is better designed and much more flexible than readlink
.
The only use of readlink
that is not covered by realpath
is the call without option returning the value of a symbolic link.
.contains()
is perfectly valid and a good way to check.
(http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence))
Since you didn't post the error, I guess d
is either null or you are getting the "Cannot refer to a non-final variable inside an inner class defined in a different method" error.
To make sure it's not null, first check for null in the if statement. If it's the other error, make sure d
is declared as final
or is a member variable of your class. Ditto for c
.
For Fedora:
# Fedora 18 or greater
sudo dnf group install "MinGW cross-compiler"
# Or (not recommended, because of its deprecation)
sudo yum groupinstall -y "MinGW cross-compiler"
I had two request URIs in the Console, http://xxxxx/client/api/spreadsheet/authredirect and http://localhost.
I tried all the top responses to this question and confirmed that none of them were my problem.
I removed localhost from the Console, updated my client_secret.json in my project, and the mismatch error went away.
Use this for windows Server 2008 r2 and Windows Server 2012 R2
Click Start, click Run, type dcomcnfg and then click OK to open Component Services.
In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, click to expand Distributed Transaction Coordinator and then click Local DTC.
Right click Local DTC and click Properties to display the Local DTC Properties dialog box.
Click the Security tab.
Check mark "Network DTC Access" checkbox.
Finally check mark "Allow Inbound" and "Allow Outbound" checkboxes.
Click Apply, OK.
A message will pop up about restarting the service.
Click OK and That's all.
Reference : https://msdn.microsoft.com/en-us/library/dd327979.aspx
Note: Sometimes the network firewall on the Local Computer or the Server could interrupt your connection so make sure you create rules to "Allow Inbound" and "Allow Outbound" connection for C:\Windows\System32\msdtc.exe
The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:
class PetStore: public Farm
{
public :
PetStore()
: Farm() // <---- Call base-class constructor in initialision list
{
idF=0;
};
private:
int idF;
string nameF;
}
Check your encoding, i got something similar once because of the BOM.
Make sure the core.js file is encoded in utf-8 without BOM
The selected answer is only half right. You must compare the arrays both ways to get a complete answer.
const ids_exist = [
'1234',
'5678',
'abcd',
]
const ids_new = [
'1234',
'5678',
'efjk',
'9999',
]
function __uniq_Filter (__array_1, __array_2) {
const one_not_in_two = __array_1.filter(function (obj) {
return __array_2.indexOf(obj) == -1
})
const two_not_in_one = __array_2.filter(function (obj) {
return __array_1.indexOf(obj) == -1
})
return one_not_in_two.concat(two_not_in_one)
}
let uniq_filter = __uniq_Filter(ids_exist, ids_new)
console.log('uniq_filter', uniq_filter) // => [ 'abcd', 'efjk', '9999' ]
another solution:
add src/myproject
to $GOPATH.
Then import "mylib"
will compile.
The solution given by @annoyingmouse works for me.
But to use the checkbox in the header cell, I also had to fix select.dataTables.css.
It seems that they used :
table.dataTable tbody th.select-checkbox
instead of :
table.dataTable thead th.select-checkbox
So I had to add this to my css :
table.dataTable thead th.select-checkbox {
position: relative;
}
table.dataTable thead th.select-checkbox:before,
table.dataTable thead th.select-checkbox:after {
display: block;
position: absolute;
top: 1.2em;
left: 50%;
width: 12px;
height: 12px;
box-sizing: border-box;
}
table.dataTable tbody td.select-checkbox:before,
table.dataTable thead th.select-checkbox:before {
content: ' ';
margin-top: -6px;
margin-left: -6px;
border: 1px solid black;
border-radius: 3px;
}
so simple :
outline-color : blue !important;
the whole CSS for my react-boostrap button is:
.custom-btn { font-size:1.9em; background: #2f5bff; border: 2px solid #78e4ff; border-radius: 3px; padding: 50px 70px; outline-color : blue !important; text-transform: uppercase; user-select: auto; -moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2); -webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2); -webkit-border-radius: 3px; -moz-border-radius: 3px; }
There is no way to get the logs for installing problems.
A good resource start off point would be MSDN as your looking into a microsoft product
Although Clayton's answer will get you there (eventually), in SQL2005/2008/R2/2012 you have a far easier option:
Right-click on the Database, select Tasks
and then Generate Scripts
, which will launch the Script Wizard. This allows you to generate a single script that can recreate the full database including table/indexes & constraints/stored procedures/functions/users/etc. There are a multitude of options that you can configure to customise the output, but most of it is self explanatory.
If you are happy with the default options, you can do the whole job in a matter of seconds.
If you want to recreate the data in the database (as a series of INSERTS) I'd also recommend SSMS Tools Pack (Free for SQL 2008 version, Paid for SQL 2012 version).
what solved the problem for me was to restart simulator ,and reset content and settings.
Considering the particular column Amount
in the above table is of integer type. The following would be a solution :
df['Amount'] = df.Amount.fillna(0).astype(int)
Similarly, you can fill it with various data types like float
, str
and so on.
In particular, I would consider datatype to compare various values of the same column.
At first, you have to install tether, jquery and bootstrap with these commands
npm i -S tether
npm i -S jquery
npm i -S [email protected]
After add these lines in your angular-cli.json (angular.json from version 6 onwards) file
"styles": [
"styles.scss",
"../node_modules/bootstrap/scss/bootstrap-flex.scss"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/tether/dist/js/tether.js",
"../node_modules/bootstrap/dist/js/bootstrap.js"
]
sort
has been replaced in v0.20 by DataFrame.sort_values
and DataFrame.sort_index
. Aside from this, we also have argsort
.
Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.
# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})
df
A B
0 a 7
1 c 9
2 c 3
3 a 5
4 b 2
For example, to sort df
by column "A", use sort_values
with a single column name:
df.sort_values(by='A')
A B
0 a 7
3 a 5
4 b 2
1 c 9
2 c 3
If you need a fresh RangeIndex, use DataFrame.reset_index
.
For example, to sort by both col "A" and "B" in df
, you can pass a list to sort_values
:
df.sort_values(by=['A', 'B'])
A B
3 a 5
0 a 7
4 b 2
2 c 3
1 c 9
df2 = df.sample(frac=1)
df2
A B
1 c 9
0 a 7
2 c 3
3 a 5
4 b 2
You can do this using sort_index
:
df2.sort_index()
A B
0 a 7
1 c 9
2 c 3
3 a 5
4 b 2
df.equals(df2)
# False
df.equals(df2.sort_index())
# True
Here are some comparable methods with their performance:
%timeit df2.sort_index()
%timeit df2.iloc[df2.index.argsort()]
%timeit df2.reindex(np.sort(df2.index))
605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
For example,
idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])
This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc
will do.
df.iloc[idx]
A B
1 c 9
0 a 7
2 c 3
3 a 5
4 b 2
Is the standard procedure not working?
git stash save
git branch xxx HEAD
git checkout xxx
git stash pop
Shorter:
git stash
git checkout -b xxx
git stash pop
One way is to use the carriage return ('\r'
) character to return to the start of the line without advancing to the next line.
for x in range(10):
print(x, end='\r')
print()
from __future__ import print_function
for x in range(10):
print(x, end='\r')
print()
for x in range(10):
print '{}\r'.format(x),
print
for x in range(10):
print '{0}\r'.format(x),
print
In the latter two (Python 2-only) cases, the comma at the end of the print statement tells it not to go to the next line. The last print statement advances to the next line so your prompt won't overwrite your final output.
If you can’t guarantee that the new line of text is not shorter than the existing line, then you just need to add a “clear to end of line” escape sequence, '\x1b[1K'
('\x1b'
= ESC):
for x in range(75):
print(‘*’ * (75 - x), x, end='\x1b[1K\r')
print()
I'm afraid you have to do it manually. Get the date's current day of week, calculate the offset and add the offset to the date.
$current = date("w", $date)
$offset = $day - $current
$new_date = new DateTime($date)
->add(
new DateInterval($offset."D")
)->format('Y-m-d')
That would only happen if PostCode
is missing a space.
You could add conditionality such that all of PostCode
is retrieved should a space not be found as follows
select SUBSTRING(PostCode, 1 ,
case when CHARINDEX(' ', PostCode ) = 0 then LEN(PostCode)
else CHARINDEX(' ', PostCode) -1 end)
I wasn't happy with any of the suggested time pickers, so I created my own with inspiration from Perifer's and the HTML5 spec:
http://github.com/gregersrygg/jquery.timeInput
You can either use the new html5 attributes for time input (step, min, max), or use an options object:
<input type="time" name="myTime" class="time-mm-hh" min="9:00" max="18:00" step="1800" />
<input type="time" name="myTime2" class="time-mm-hh" />
<script type="text/javascript">
$("input[name='myTime']").timeInput(); // use default or html5 attributes
$("input[name='myTime2']").timeInput({min: "6:00", max: "15:00", step: 900}); // 15 min intervals from 6:00 am to 3:00 pm
</script>
Validates input like this:
The HTML5 spec doesn't allow am/pm or localized time syntax, so it only allowes the format hh:mm. Seconds is allowed according to spec, but I have not implemented it yet.
It's very "alpha", so there might be some bugs. Feel free to send me patches/pull requests. Have manually tested in IE 6&8, FF, Chrome and Opera (Latest stable on Linux for the latter ones).
Following is how you can do it using java client.
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.519</version>
</dependency>
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ObjectListing;
public class AmazonS3Service {
private static final String S3_ACCESS_KEY_ID = "ACCESS_KEY";
private static final String S3_SECRET_KEY = "SECRET_KEY";
private static final String S3_ENDPOINT = "S3_URL";
private AmazonS3 amazonS3;
public AmazonS3Service() {
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProtocol(Protocol.HTTPS);
clientConfiguration.setSignerOverride("S3SignerType");
BasicAWSCredentials credentials = new BasicAWSCredentials(S3_ACCESS_KEY_ID, S3_SECRET_KEY);
AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
AmazonS3ClientBuilder.EndpointConfiguration endpointConfiguration = new AmazonS3ClientBuilder.EndpointConfiguration(S3_ENDPOINT, null);
amazonS3 = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider).withClientConfiguration(clientConfiguration)
.withPathStyleAccessEnabled(true).withEndpointConfiguration(endpointConfiguration).build();
}
public int countObjects(String bucketName) {
int count = 0;
ObjectListing objectListing = amazonS3.listObjects(bucketName);
int currentBatchCount = objectListing.getObjectSummaries().size();
while (currentBatchCount != 0) {
count += currentBatchCount;
objectListing = amazonS3.listNextBatchOfObjects(objectListing);
currentBatchCount = objectListing.getObjectSummaries().size();
}
return count;
}
}
This was what I was searching online but unfortunately found not online but while experimenting on python interpreter.
>>> case = "caseCamel"
>>> label = "Case Camel"
>>> list = ["apple", "banana"]
>>>
>>> (case or label) in list
False
>>> list = ["apple", "caseCamel"]
>>> (case or label) in list
True
>>> (case and label) in list
False
>>> list = ["case", "caseCamel", "Case Camel"]
>>> (case and label) in list
True
>>>
and if you have a looong list of variables held in a sublist variable
>>>
>>> list = ["case", "caseCamel", "Case Camel"]
>>> label = "Case Camel"
>>> case = "caseCamel"
>>>
>>> sublist = ["unique banana", "very unique banana"]
>>>
>>> # example for if any (at least one) item contained in superset (or statement)
...
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
False
>>>
>>> sublist[0] = label
>>>
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
True
>>>
>>> # example for whether a subset (all items) contained in superset (and statement)
...
>>> # a bit of demorgan's law
...
>>> next((False for item in sublist if item not in list), True)
False
>>>
>>> sublist[1] = case
>>>
>>> next((False for item in sublist if item not in list), True)
True
>>>
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
True
>>>
>>>
Here is working solution:
Output:
public class XmlTest {
private static final Logger log = LoggerFactory.getLogger(XmlTest.class);
@Test
public void createDefaultBook() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter writer = new StringWriter();
marshaller.marshal(new Book(), writer);
log.debug("Book xml:\n {}", writer.toString());
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "book")
public static class Book {
@XmlElementRef(name = "price")
private Price price = new Price();
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "price")
public static class Price {
@XmlAttribute(name = "drawable")
private Boolean drawable = true; //you may want to set default value here
@XmlValue
private int priceValue = 1234;
public Boolean getDrawable() {
return drawable;
}
public void setDrawable(Boolean drawable) {
this.drawable = drawable;
}
public int getPriceValue() {
return priceValue;
}
public void setPriceValue(int priceValue) {
this.priceValue = priceValue;
}
}
}
Output:
22:00:18.471 [main] DEBUG com.grebski.stack.XmlTest - Book xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
<price drawable="true">1234</price>
</book>
Here is a C# version of the answer given by nirg, which comes from this RPI professor. Note that use of the code from that RPI source requires attribution.
A bounding box check has been added at the top. However, as James Brown points out, the main code is almost as fast as the bounding box check itself, so the bounding box check can actually slow the overall operation, in the case that most of the points you are checking are inside the bounding box. So you could leave the bounding box check out, or an alternative would be to precompute the bounding boxes of your polygons if they don't change shape too often.
public bool IsPointInPolygon( Point p, Point[] polygon )
{
double minX = polygon[ 0 ].X;
double maxX = polygon[ 0 ].X;
double minY = polygon[ 0 ].Y;
double maxY = polygon[ 0 ].Y;
for ( int i = 1 ; i < polygon.Length ; i++ )
{
Point q = polygon[ i ];
minX = Math.Min( q.X, minX );
maxX = Math.Max( q.X, maxX );
minY = Math.Min( q.Y, minY );
maxY = Math.Max( q.Y, maxY );
}
if ( p.X < minX || p.X > maxX || p.Y < minY || p.Y > maxY )
{
return false;
}
// https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html
bool inside = false;
for ( int i = 0, j = polygon.Length - 1 ; i < polygon.Length ; j = i++ )
{
if ( ( polygon[ i ].Y > p.Y ) != ( polygon[ j ].Y > p.Y ) &&
p.X < ( polygon[ j ].X - polygon[ i ].X ) * ( p.Y - polygon[ i ].Y ) / ( polygon[ j ].Y - polygon[ i ].Y ) + polygon[ i ].X )
{
inside = !inside;
}
}
return inside;
}
What Works:
string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);
(result: absolutePath="C:\bling.txt")
What doesn't work
string relativePath = "..\\bling.txt";
Uri baseAbsoluteUri = new Uri("C:\\blah\\");
string absolutePath = new Uri(baseAbsoluteUri, relativePath).AbsolutePath;
(result: absolutePath="C:/blah/bling.txt")
XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}
or you could wrap in foreach loop to print each value
XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
foreach(XmlNode curr in n) {
Console.WriteLine(curr.InnerText);
}
}
Below is an example of multiple figures that I used recently in Latex. You need to call these packages
\usepackage{graphicx}
\usepackage{subfig})
\begin{figure}[H]%
\centering
\subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%
\subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%
\subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
\hfill
\subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%
\subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%
\caption{Multiple figures in latex.}%
\label{fig:MFL}%
\end{figure}
Use:
subA.tick_params(labelsize=6)
Have you checked your folder structure? It seems to me like Express can't find your root directory, which should be a a folder named "site" right under your default directory. Here is how it should look like, according to the tutorial:
node_modules/
.bin/
express/
mongoose/
path/
site/
css/
img/
js/
index.html
package.json
For example on my machine, I started getting the same error as you when I renamed my "site" folder as something else. So I would suggest you check that you have the index.html page inside a "site" folder that sits on the same path as your server.js file.
Hope that helps!
According to spark documentation "where()
is an alias for filter()
"
filter(condition)
Filters rows using the given condition.
where()
is an alias for filter()
.
Parameters: condition – a Column
of types.BooleanType
or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]
>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]
In SQL server 2005 new datatypes were introduced: varchar(max)
and nvarchar(max)
They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar
and nvarchar
. Among these advantages are the ability to use string manipulation functions such as substring().
Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.
In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.
As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.
Just to make a proper answer from the @Eddy Hernandez's comment and which is very correct since Alpine comes with ash not bash.
The question now referes to Starting a shell in the Docker Alpine container which implies using sh
or ash
or /bin/sh
or /bin/ash/
.
Based on the OP's question:
docker run image sh -c "cd /path/to/somewhere && python a.py"
Use margins instead of line-height and then apply float to the buttons. By default they are displaying as inline-block
, so when one is pushed down the hole line is pushed down with him. Float fixes this:
#header button {
float:left;
}
Here's a working jsfidle.
I changed @Eli Bendersky's answer a little bit to use the ctor __init__()
and dtor __del__()
to do the timing, so that it can be used more conveniently without indenting the original code:
class Timer(object):
def __init__(self, name=None):
self.name = name
self.tstart = time.time()
def __del__(self):
if self.name:
print '%s elapsed: %.2fs' % (self.name, time.time() - self.tstart)
else:
print 'Elapsed: %.2fs' % (time.time() - self.tstart)
To use, simple put Timer("blahblah") at the beginning of some local scope. Elapsed time will be printed at the end of the scope:
for i in xrange(5):
timer = Timer("eigh()")
x = numpy.random.random((4000,4000));
x = (x+x.T)/2
numpy.linalg.eigh(x)
print i+1
timer = None
It prints out:
1
eigh() elapsed: 10.13s
2
eigh() elapsed: 9.74s
3
eigh() elapsed: 10.70s
4
eigh() elapsed: 10.25s
5
eigh() elapsed: 11.28s
File > Switch workspace > add the workspace you like > Eclipse will restart using the workspace you wanted.
Since 2020-05-07, the docker-compose spec also defines the "pull_policy" property for a service:
version: '3.7'
services:
my-service:
image: someimage/somewhere
pull_policy: always
The docker-compose spec says:
pull_policy defines the decisions Compose implementations will make when it starts to pull images.
Possible values are (tl;dr, check spec for more details):
Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)
public static void main(String[] args) throws ParseException {
java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
Date date;
date = (Date)formatter.parse(fecha.toString());
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" +
(cal.get(Calendar.MONTH) + 1) +
"/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
}
You can also use Gson to convert an object to a JSONObject and pass it on bundle. For me was the most elegant way I found to do this. I haven't tested how it affects performance.
In Initial Activity
Intent activity = new Intent(MyActivity.this,NextActivity.class);
activity.putExtra("myObject", new Gson().toJson(myobject));
startActivity(activity);
In Next Activity
String jsonMyObject;
Bundle extras = getIntent().getExtras();
if (extras != null) {
jsonMyObject = extras.getString("myObject");
}
MyObject myObject = new Gson().fromJson(jsonMyObject, MyObject.class);
I've been searching for a way to split a string by a separator of any length, so I started writing it from scratch, as existing solutions didn't suit me.
Here is my little algorithm, using only STL:
//use like this
//std::vector<std::wstring> vec = Split<std::wstring> (L"Hello##world##!", L"##");
template <typename valueType>
static std::vector <valueType> Split (valueType text, const valueType& delimiter)
{
std::vector <valueType> tokens;
size_t pos = 0;
valueType token;
while ((pos = text.find(delimiter)) != valueType::npos)
{
token = text.substr(0, pos);
tokens.push_back (token);
text.erase(0, pos + delimiter.length());
}
tokens.push_back (text);
return tokens;
}
It can be used with separator of any length and form, as far as I've tested. Instantiate with either string or wstring type.
All the algorithm does is it searches for the delimiter, gets the part of the string that is up to the delimiter, deletes the delimiter and searches again until it finds it no more.
Hope it helps.
Once application is made live by publishing it then you can't delete it, although Unpublished apps can be deleted using "Delete app" button as shown :
Here is one solution that involves wrapping the lamba in a structure:
template <typename T>
struct LamT
{
static void Go()
{
auto lam = []()
{
T var;
std::cout << "lam, type = " << typeid(var).name() << std::endl;
};
lam();
}
};
To use do:
LamT<int>::Go();
LamT<char>::Go();
#This prints
lam, type = i
lam, type = c
The main issue with this (besides the extra typing) you cannot embed this structure definition inside another method or you get (gcc 4.9)
error: a template declaration cannot appear at block scope
I also tried doing this:
template <typename T> using LamdaT = decltype(
[](void)
{
std::cout << "LambT type = " << typeid(T).name() << std::endl;
});
With the hope that I could use it like this:
LamdaT<int>();
LamdaT<char>();
But I get the compiler error:
error: lambda-expression in unevaluated context
So this doesn't work ... but even if it did compile it would be of limited use because we would still have to put the "using LamdaT" at file scope (because it is a template) which sort of defeats the purpose of lambdas.
function groupBy(data, property) {
return data.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
groupBy(people, 'age');
How does it work? How does it know it's me?
Most sessions set a user-key(called the sessionid) on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key and runs to the server to get your variables.
If you mistakenly clear the cache, then your user-key will also be cleared. You won't be able to get your variables from the server any more since you don't know your id.
Many times when producing HTML email blasts you cannot use style sheets or style /style blocks. All CSS needs to be inline. In the case where you want to adjust the spacing between the bullets I use li style="margin-bottom:8px;" in each bullet item. Customize the pixels value to your liking.
Try following code, it works in my project:
//start ajax request
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
for (var i=0;i<json.length;++i)
{
$('#results').append('<div class="name">'+json[i].name+'</>');
}
}
});
You can pass the data to catboost classifier without encoding. Catboost handles categorical variables itself by performing one-hot and target expanding mean encoding.
I developed a non-matlab software for direct compilation of m-files (TMC Compiler). This is an open-source converter of m-files projects to C. The compiler produces the C code that may be linked with provided open-source run-time library to produce a stand-alone application. The library implements a set of build-in functions; the linear-algebra operations use LAPACK code. It is possible to expand the set of the build-in functions by custom implementation as described in the documentation.
For my case(ubuntu 14.04, fresh installed), I just run the following command and it works!
sudo apt-get install ssh
Following the working sample, I have figured out solution for the case of pure component:
You may consider IaaS for file upload, such as Uploadcare. There is an Angular package for it: https://github.com/uploadcare/angular-uploadcare
Technically it's implemented as a directive, providing different options for uploading, and manipulations for uploaded images within the widget:
<uploadcare-widget
ng-model="object.image.info.uuid"
data-public-key="YOURKEYHERE"
data-locale="en"
data-tabs="file url"
data-images-only="true"
data-path-value="true"
data-preview-step="true"
data-clearable="true"
data-multiple="false"
data-crop="400:200"
on-upload-complete="onUCUploadComplete(info)"
on-widget-ready="onUCWidgetReady(widget)"
value="{{ object.image.info.cdnUrl }}"
/>
More configuration options to play with: https://uploadcare.com/widget/configure/
It looks like you're using ngModel on the same form field as formControlName. Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7
Correct expression is
"source " + (DT_STR,4,1252)DATEPART( "yyyy" , getdate() ) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2) + "-" +
RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".CSV"
Most vanilla JS Ready functions do NOT consider the scenario where the DOMContentLoaded
handler is set after the document is already loaded - Which means the function will never run. This can happen if you look for DOMContentLoaded
within an async
external script (<script async src="file.js"></script>
).
The code below checks for DOMContentLoaded
only if the document's readyState
isn't already interactive
or complete
.
var DOMReady = function(callback) {
document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback());
};
DOMReady(function() {
//DOM ready!
});
If you want to support IE aswell:
var DOMReady = function(callback) {
if (document.readyState === "interactive" || document.readyState === "complete") {
callback();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', callback());
} else if (document.attachEvent) {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading') {
callback();
}
});
}
};
DOMReady(function() {
// DOM ready!
});
To test whether the birthday already passed or not, I define a helper function Date.prototype.getDoY
, which effectively returns the day number of the year. The rest is pretty self-explanatory.
Date.prototype.getDoY = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.floor(((this - onejan) / 86400000) + 1);
};
function getAge(birthDate) {
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
var now = new Date(),
age = now.getFullYear() - birthDate.getFullYear(),
doyNow = now.getDoY(),
doyBirth = birthDate.getDoY();
// normalize day-of-year in leap years
if (isLeap(now.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyNow--;
if (isLeap(birthDate.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyBirth--;
if (doyNow <= doyBirth)
age--; // birthday not yet passed this year, so -1
return age;
};
var myBirth = new Date(2001, 6, 4);
console.log(getAge(myBirth));
You could use grep and sed together. This allows you to search subdirectories recursively.
Linux: grep -r -l <old> * | xargs sed -i 's/<old>/<new>/g'
OS X: grep -r -l <old> * | xargs sed -i '' 's/<old>/<new>/g'
For grep:
-r recursively searches subdirectories
-l prints file names that contain matches
For sed:
-i extension (Note: An argument needs to be provided on OS X)
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).
If all you want to do is calculate the sum of 1,2,3... n then you could use :
int sum = (n * (n + 1)) / 2;
I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else
It's also possible by using rsync
, for example:
rsync -va --delete-after src/ dst/
where:
-v
, --verbose
: increase verbosity-a
, --archive
: archive mode; equals -rlptgoD
(no -H,-A,-X
)--delete-after
: delete files on the receiving side be done after the transfer has completedIf you've root privileges, prefix with sudo
to override potential permission issues.
Just for fun this works in JS 1.8.5
var obj = {a: 1, b: 2, c: 3};
Object.keys(obj)[0]; // "a"
This matches the same order that you would see doing
for (o in obj) { ... }
Not only can you return a function which you have passed into another function as a variable, you can also use it for calculation inside but defining it outside. See this example:
function calculate(a,b,fn) {
var c = a * 3 + b + fn(a,b);
return c;
}
function sum(a,b) {
return a+b;
}
function product(a,b) {
return a*b;
}
document.write(calculate (10,20,sum)); //80
document.write(calculate (10,20,product)); //250
To see the default version of swift installed on your machine then from the command line, type the following :
swift --version
Apple Swift version 4.1.2 (swiftlang-902.0.54 clang-902.0.39.2)
Target: x86_64-apple-darwin17.6.0
This is most likely the version that is included in the app store version of Xcode that you have installed (unless you have changed it).
If you want to determine the actual version of Swift being used by a particular version of Xcode (a beta, for instance) then from the command line, invoke the swift binary within the Xcode bundle and pass it the parameter --version
/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift --version
Apple Swift version 4.2 (swiftlang-1000.0.16.7 clang-1000.10.25.3)
Target: x86_64-apple-darwin17.6.0
If you're on a Mac do brew install geckodriver
and off you go!
To get the timedelta()
, you should subtract 1900-01-01
:
>>> from datetime import datetime
>>> datetime.strptime('01:01:09,000', '%H:%M:%S,%f')
datetime.datetime(1900, 1, 1, 1, 1, 9)
>>> td = datetime.strptime('01:01:09,000', '%H:%M:%S,%f') - datetime(1900,1,1)
>>> td
datetime.timedelta(0, 3669)
>>> td.total_seconds() # 2.7+
3669.0
%H
above implies the input is less than a day, to support the time difference more than a day:
>>> import re
>>> from datetime import timedelta
>>> td = timedelta(**dict(zip("hours minutes seconds milliseconds".split(),
... map(int, re.findall('\d+', '31:01:09,000')))))
>>> td
datetime.timedelta(1, 25269)
>>> td.total_seconds()
111669.0
To emulate .total_seconds()
on Python 2.6:
>>> from __future__ import division
>>> ((td.days * 86400 + td.seconds) * 10**6 + td.microseconds) / 10**6
111669.0
Below is the pagination logic as a function
function Pagination(pageEleArr, numOfEleToDisplayPerPage) {
this.pageEleArr = pageEleArr;
this.numOfEleToDisplayPerPage = numOfEleToDisplayPerPage;
this.elementCount = this.pageEleArr.length;
this.numOfPages = Math.ceil(this.elementCount / this.numOfEleToDisplayPerPage);
const pageElementsArr = function (arr, eleDispCount) {
const arrLen = arr.length;
const noOfPages = Math.ceil(arrLen / eleDispCount);
let pageArr = [];
let perPageArr = [];
let index = 0;
let condition = 0;
let remainingEleInArr = 0;
for (let i = 0; i < noOfPages; i++) {
if (i === 0) {
index = 0;
condition = eleDispCount;
}
for (let j = index; j < condition; j++) {
perPageArr.push(arr[j]);
}
pageArr.push(perPageArr);
if (i === 0) {
remainingEleInArr = arrLen - perPageArr.length;
} else {
remainingEleInArr = remainingEleInArr - perPageArr.length;
}
if (remainingEleInArr > 0) {
if (remainingEleInArr > eleDispCount) {
index = index + eleDispCount;
condition = condition + eleDispCount;
} else {
index = index + perPageArr.length;
condition = condition + remainingEleInArr;
}
}
perPageArr = [];
}
return pageArr;
}
this.display = function (pageNo) {
if (pageNo > this.numOfPages || pageNo <= 0) {
return -1;
} else {
console.log('Inside else loop in display method');
console.log(pageElementsArr(this.pageEleArr, this.numOfEleToDisplayPerPage));
console.log(pageElementsArr(this.pageEleArr, this.numOfEleToDisplayPerPage)[pageNo - 1]);
return pageElementsArr(this.pageEleArr, this.numOfEleToDisplayPerPage)[pageNo - 1];
}
}
}
const p1 = new Pagination(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3);
console.log(p1.elementCount);
console.log(p1.pageEleArr);
console.log(p1.numOfPages);
console.log(p1.numOfEleToDisplayPerPage);
console.log(p1.display(3));
My answer is repeating what others have said before, but I thought I'd add an example, using MySQL
, only because the previous answers were a little bit cryptic to me.
The general form of the command you need to use to update a single row's column:
UPDATE my_table SET my_column='new value' WHERE something='some value';
And here's an example.
BEFORE
mysql> select aet,port from ae;
+------------+-------+
| aet | port |
+------------+-------+
| DCM4CHEE01 | 11112 |
| CDRECORD | 10104 |
+------------+-------+
2 rows in set (0.00 sec)
MAKING THE CHANGE
mysql> update ae set port='10105' where aet='CDRECORD';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
AFTER
mysql> select aet,port from ae;
+------------+-------+
| aet | port |
+------------+-------+
| DCM4CHEE01 | 11112 |
| CDRECORD | 10105 |
+------------+-------+
2 rows in set (0.00 sec)
I had the same problem. In my case it arises, because the lookup-table "country" has an existing record with countryId==0 and a primitive primary key and I try to save a User with a countryID==0. Change the primary key of country to Integer. Now Hibernate can identify new records.
For the recommendation of using wrapper classes as primary key see this stackoverflow question
weights.reshape(a, b)
will return a new tensor with the same data as weights with size (a, b) as in it copies the data to another part of memory.
weights.resize_(a, b)
returns the same tensor with a different shape. However, if the new shape results in fewer elements than the original tensor, some elements will be removed from the tensor (but not from memory). If the new shape results in more elements than the original tensor, new elements will be uninitialized in memory.
weights.view(a, b)
will return a new tensor with the same data as weights with size (a, b)
So, the answers here are all a bit incomplete. The use of a '%20' to encode a space in URLs is explicitly defined in RFC3986, which defines how a URI is built. There is no mention in this specification of using a '+' for encoding spaces - if you go solely by this specification, a space must be encoded as '%20'.
The mention of using '+' for encoding spaces comes from the various incarnations of the HTML specification - specifically in the section describing content type 'application/x-www-form-urlencoded'. This is used for posting form data.
Now, the HTML 2.0 Specification (RFC1866) explicitly said, in section 8.2.2, that the Query part of a GET request's URL string should be encoded as 'application/x-www-form-urlencoded'. This, in theory, suggests that it's legal to use a '+' in the URL in the query string (after the '?').
But... does it really? Remember, HTML is itself a content specification, and URLs with query strings can be used with content other than HTML. Further, while the later versions of the HTML spec continue to define '+' as legal in 'application/x-www-form-urlencoded' content, they completely omit the part saying that GET request query strings are defined as that type. There is, in fact, no mention whatsoever about the query string encoding in anything after the HTML 2.0 spec.
Which leaves us with the question - is it valid? Certainly there's a LOT of legacy code which supports '+' in query strings, and a lot of code which generates it as well. So odds are good you won't break if you use '+'. (And, in fact, I did all the research on this recently because I discovered a major site which failed to accept '%20' in a GET query as a space. They actually failed to decode ANY percent encoded character. So the service you're using may be relevant as well.)
But from a pure reading of the specifications, without the language from the HTML 2.0 specification carried over into later versions, URLs are covered entirely by RFC3986, which means spaces ought to be converted to '%20'. And definitely that should be the case if you are requesting anything other than an HTML document.
You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
And then you can use returned string with Google Gson to map JSON to object of specified class, like this:
String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);
There is a sample of AuthMsg class:
public class AuthMsg {
private int code;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
JSON returned by http://localhost/authmanager.php must look like this:
{"code":1,"message":"Logged in"}
Regards
Have you tried plugin called " Youtube Live Stream Auto Embed"
Its seems to be working. Check it once.
As a sidenote this also works when running a command directly from the search bar in windows.
e.g. directly running ipconfig
will directly close the cmd window after the command has exited.
Using cmd \k <command>
won't - which was what i was trying to do when i found this answer.
It has the added advantage of always recognizing the command you're trying to run. E.g. running echo hello world
from the searchbar won't work because that is not a command, however cmd \k echo hello world
works just fine.
1st: Get personal access token. https://github.com/settings/tokens
2nd: Put account & the token. Example is here:
$ git push
Username for 'https://github.com': # Put your GitHub account name
Password for 'https://{USERNAME}@github.com': # Put your Personal access token
Link on how to create a personal access token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line
Just create your own action.
namespace WpfUtil
{
using System.Reflection;
using System.Windows;
using System.Windows.Interactivity;
/// <summary>
/// Sets the designated property to the supplied value. TargetObject
/// optionally designates the object on which to set the property. If
/// TargetObject is not supplied then the property is set on the object
/// to which the trigger is attached.
/// </summary>
public class SetPropertyAction : TriggerAction<FrameworkElement>
{
// PropertyName DependencyProperty.
/// <summary>
/// The property to be executed in response to the trigger.
/// </summary>
public string PropertyName
{
get { return (string)GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value); }
}
public static readonly DependencyProperty PropertyNameProperty
= DependencyProperty.Register("PropertyName", typeof(string),
typeof(SetPropertyAction));
// PropertyValue DependencyProperty.
/// <summary>
/// The value to set the property to.
/// </summary>
public object PropertyValue
{
get { return GetValue(PropertyValueProperty); }
set { SetValue(PropertyValueProperty, value); }
}
public static readonly DependencyProperty PropertyValueProperty
= DependencyProperty.Register("PropertyValue", typeof(object),
typeof(SetPropertyAction));
// TargetObject DependencyProperty.
/// <summary>
/// Specifies the object upon which to set the property.
/// </summary>
public object TargetObject
{
get { return GetValue(TargetObjectProperty); }
set { SetValue(TargetObjectProperty, value); }
}
public static readonly DependencyProperty TargetObjectProperty
= DependencyProperty.Register("TargetObject", typeof(object),
typeof(SetPropertyAction));
// Private Implementation.
protected override void Invoke(object parameter)
{
object target = TargetObject ?? AssociatedObject;
PropertyInfo propertyInfo = target.GetType().GetProperty(
PropertyName,
BindingFlags.Instance|BindingFlags.Public
|BindingFlags.NonPublic|BindingFlags.InvokeMethod);
propertyInfo.SetValue(target, PropertyValue);
}
}
}
In this case I'm binding to a property called DialogResult on my viewmodel.
<Grid>
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
Cancel
</Button>
</Grid>
I use GateOne from the synocommunity.
Go into settings in Package Center and add http://packages.synocommunity.com/ as a package source. Then you should be able to add it easily via Package Center.
pp does the job too, no gem requiring is required.
@a = Accrual.first ; pp @a
#<Accrual:0x007ff521e5ba50
id: 4,
year: 2018,
Jan: #<BigDecimal:7ff521e58f08,'0.11E2',9(27)>,
Feb: #<BigDecimal:7ff521e585d0,'0.88E2',9(27)>,
Mar: #<BigDecimal:7ff521e58030,'0.0',9(27)>,
Apr: #<BigDecimal:7ff521e53698,'0.88E2',9(27)>,
May: #<BigDecimal:7ff521e52fb8,'0.8E1',9(27)>,
June: #<BigDecimal:7ff521e52900,'0.8E1',9(27)>,
July: #<BigDecimal:7ff521e51ff0,'0.8E1',9(27)>,
Aug: #<BigDecimal:7ff521e51bb8,'0.88E2',9(27)>,
Sep: #<BigDecimal:7ff521e512f8,'0.88E2',9(27)>,
Oct: #<BigDecimal:7ff521e506c8,'0.0',9(27)>,
Nov: #<BigDecimal:7ff521e43d38,'0.888E3',9(27)>,
Dec: #<BigDecimal:7ff521e43478,'0.0',9(27)>,
You can also print two instances of an object:
pp( Accrual.first , Accrual.second)
`
`
`
const cookieCleaner = () => {
return document.cookie.split(";").reduce(function (acc, cookie) {
const eqPos = cookie.indexOf("=");
const cleanCookie = `${cookie.substr(0, eqPos)}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;`;
return `${acc}${cleanCookie}`;
}, "");
}
Note: Doesn't handle paths
Use this to validate google captcha with simple javascript.
This code at the html body:
<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />
This code put at head section on call get_action(this) method form button:
function get_action(form)
{
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
else
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}
The latest version of Eclipse (Luna) and Spring Tool Suite (STS) come pre-packaged with support for Maven, GIT and Java 8.
Below Kotlin code will help
Bottom to Top or Slide to Up
private fun slideUp() {
isMapInfoShown = true
views!!.layoutMapInfo.visible()
val animate = TranslateAnimation(
0f, // fromXDelta
0f, // toXDelta
views!!.layoutMapInfo.height.toFloat(), // fromYDelta
0f // toYDelta
)
animate.duration = 500
animate.fillAfter = true
views!!.layoutMapInfo.startAnimation(animate)
}
Top to Bottom or Slide to Down
private fun slideDown() {
if (isMapInfoShown) {
isMapInfoShown = false
val animate = TranslateAnimation(
0f, // fromXDelta
0f, // toXDelta
0f, // fromYDelta
views!!.layoutMapInfo.height.toFloat() // toYDelta
)
animate.duration = 500
animate.fillAfter = true
views!!.layoutMapInfo.startAnimation(animate)
views!!.layoutMapInfo.gone()
}
}
Kotlin Extensions for Visible and Gone
fun View.visible() {
this.visibility = View.VISIBLE
}
fun View.gone() {
this.visibility = View.GONE
}
More obvious and simple, thread safe example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2){
printf ("Dont' forget to pass arguments!\n");
return(-1);
}
printf ("You have executed the program : %s\n", argv[0]);
for(int i = 1; i < argc; i++){
if(strcmp(argv[i],"--some_definite_parameter") == 0){
printf("You have passed some definite parameter as an argument. And it is \"%s\".\n",argv[i]);
}
else if(strspn(argv[i], "0123456789") == strlen(argv[i])) {
size_t big_digit = 0;
sscanf(argv[i], "%zu%*c",&big_digit);
printf("Your %d'nd argument contains only digits, and it is a number \"%zu\".\n",i,big_digit);
}
else if(strspn(argv[i], "0123456789abcdefghijklmnopqrstuvwxyz./") == strlen(argv[i]))
{
printf("%s - this string might contain digits, small letters and path symbols. It could be used for passing a file name or a path, for example.\n",argv[i]);
}
else if(strspn(argv[i], "ABCDEFGHIJKLMNOPQRSTUVWXYZ") == strlen(argv[i]))
{
printf("The string \"%s\" contains only capital letters.\n",argv[i]);
}
}
}
string = 'http://www.domain.com/?s=some&two=20'
cut_string = string.split('&')
new_string = cut_string[0]
print(new_string)