You need the public key in your gpg key ring. To import the public key into your public keyring, place the public key block in a text file with a .gpg extension, and then issue the following command:
gpg --import <your-file>.gpg
The entity that encrypted the file should provide you with such a block. For example, ftp://ftp.gnu.org/gnu/gnu-keyring.gpg has the block for gnu.org.
For an even more in-depth explanation see Verifying files with GPG, without a .sig or .asc file?
ALTER TABLE myTable ALTER COLUMN myColumn {DataType} NULL
where {DataType}
is the current data type of that column (For example int
or varchar(10)
)
To complete Johannes's answer, you can check this thread, which mentions another cause (the first one being installing the 32bit client instead of the 64 one) (emphasis mine):
Only more recent versions of TSVN and TCVS are able to share overlay icons, and since Explorer has a limit of 14 overlay images in total with extraneous overlay icons simply not showing up you might have too many...
If it's overlay icons are showing up you'd have to actually be using the 32-bit Windows Explorer, which of course means you'll have to also install a 32-bit version of TSVN.
The issue might come up when one install also first TortoiseVCS, because:
Looking at what got installed in the filesystem and the registry, it looks like they tried to do what I do with my Shell extensions - install both 64 and 32 -bit versions, so that nobody says "I don't see my overlays/menus"! ;)
Unfortunately, it looks like the registry entries for 32-bit got hosed, so the 32-bit extension DLL, even though present, does not have the correct registry entries.
If in doubt I suggest to deinstall TCVS and TSVN.
Then install TSVN.
Maybe after installation reboot twice, not only once.
And if they still don't show up go to software control panel and choose to repair the installation. That did the trick for me with when upgrading from the previous to the current version.You should probably install the TortoiseXYZ variant you plan to use mainly first, to improve its chances to fall into one of those limited number of overlay icons slots before the TortoiseXYZ variant you use less.
Always keep these limited number of overlay icon slots in mind when trying to analyze malfunctions.
The above answer are interesting and very helpful when using Ruby as shell script. For me, I does not use Ruby as my daily language and I prefer to use ruby as flow control only and still use bash to do the tasks.
Some helper function can be used for testing execution result
#!/usr/bin/env ruby
module ShellHelper
def test(command)
`#{command} 2> /dev/null`
$?.success?
end
def execute(command, raise_on_error = true)
result = `#{command}`
raise "execute command failed\n" if (not $?.success?) and raise_on_error
return $?.success?
end
def print_exit(message)
print "#{message}\n"
exit
end
module_function :execute, :print_exit, :test
end
With helper, the ruby script could be bash alike:
#!/usr/bin/env ruby
require './shell_helper'
include ShellHelper
print_exit "config already exists" if test "ls config"
things.each do |thing|
next if not test "ls #{thing}/config"
execute "cp -fr #{thing}/config_template config/#{thing}"
end
Try this code if state object has sub objects like this.state.class.fee
. We can pass values using following code:
this.setState({ class: Object.assign({}, this.state.class, { [element]: value }) }
You can actually download all font format variants directly from Google and include them in your css to serve from your server. That way you don't have to concern about Google tracking your site's users. However, the downside maybe slowing down your own serving speed. Fonts are quite demanding on resources. I have not done any tests in this issue yet, and wonder if anyone has similar thoughts.
Here you can find every thing you need:
http://web.eecs.umich.edu/~sugih/courses/eecs487/glut-howto/#win
Do you want to find elements that contain "match", or that equal "match"?
This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2
):
//*[text()='match']
This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2
):
//*[normalize-space(text())='match']
This will find all elements that contain 'match' in the text node value (matches random2
and random3
):
//*[contains(text(),'match')]
This XPATH 2.0 solution uses the matches()
function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^
) or a word boundary (i.e. \W
) and terminated by the end of the string (i.e. $
) or a word boundary. The third parameter i
evaluates the regex pattern case-insensitive. (matches random2
)
//*[matches(text(),'(^|\W)match($|\W)','i')]
For me the easiest solution was this:
map.fitBounds(bounds);
function set_zoom() {
if(map.getZoom()) {map.setZoom(map.getZoom() - 1);}
else {setTimeout(set_zoom, 5);}
}
setTimeout(set_zoom, 5);
On OS X, you need to take into account existing window decorations. They add 22 pixels to the height. So on a JFrame, you need to tell the program this:
frame.setSize(width, height + 22);
For Google Places Autocomplete V3, the best solution for this is two API requests.
Here is the fiddle
The reason why none of the other answers sufficed is because they either used jquery to mimic events (hacky) or used either Geocoder or Google Places Search box which does not always match autocomplete results. Instead, what we will do is is uses Google's Autocomplete Service as detailed here with only javascript (no jquery)
Below is detailed the most cross browser compatible solution using native Google APIs to generate the autocomplete box and then rerun the query to select the first option.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&language=en"></script>
Javascript
// For convenience, although if you are supporting IE8 and below
// bind() is not supported
var $ = document.querySelector.bind(document);
function autoCallback(predictions, status) {
// *Callback from async google places call
if (status != google.maps.places.PlacesServiceStatus.OK) {
// show that this address is an error
pacInput.className = 'error';
return;
}
// Show a successful return
pacInput.className = 'success';
pacInput.value = predictions[0].description;
}
function queryAutocomplete(input) {
// *Uses Google's autocomplete service to select an address
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({
input: input,
componentRestrictions: {
country: 'us'
}
}, autoCallback);
}
function handleTabbingOnInput(evt) {
// *Handles Tab event on delivery-location input
if (evt.target.id == "pac-input") {
// Remove active class
evt.target.className = '';
// Check if a tab was pressed
if (evt.which == 9 || evt.keyCode == 9) {
queryAutocomplete(evt.target.value);
}
}
}
// ***** Initializations ***** //
// initialize pac search field //
var pacInput = $('#pac-input');
pacInput.focus();
// Initialize Autocomplete
var options = {
componentRestrictions: {
country: 'us'
}
};
var autocomplete = new google.maps.places.Autocomplete(pacInput, options);
// ***** End Initializations ***** //
// ***** Event Listeners ***** //
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var result = autocomplete.getPlace();
if (typeof result.address_components == 'undefined') {
queryAutocomplete(result.name);
} else {
// returns native functionality and place object
console.log(result.address_components);
}
});
// Tabbing Event Listener
if (document.addEventListener) {
document.addEventListener('keydown', handleTabbingOnInput, false);
} else if (document.attachEvent) { // IE8 and below
document.attachEvent("onsubmit", handleTabbingOnInput);
}
// search form listener
var standardForm = $('#search-shop-form');
if (standardForm.addEventListener) {
standardForm.addEventListener("submit", preventStandardForm, false);
} else if (standardForm.attachEvent) { // IE8 and below
standardForm.attachEvent("onsubmit", preventStandardForm);
}
// ***** End Event Listeners ***** //
HTML
<form id="search-shop-form" class="search-form" name="searchShopForm" action="/impl_custom/index/search/" method="post">
<label for="pac-input">Delivery Location</label>
<input id="pac-input" type="text" placeholder="Los Angeles, Manhattan, Houston" autocomplete="off" />
<button class="search-btn btn-success" type="submit">Search</button>
</form>
The only gripe is that the native implementation returns a different data structure although the information is the same. Adjust accordingly.
Below mentioned code snippet should help :
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
// iPhone device
}
else if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
// iPad device
}
else {
// Other device i.e. iPod
}
I think you should make a class for this anonymous type. That'd be the most sensible thing to do in my opinion. But if you really don't want to, you could use dynamics:
public void LogEmployees (IEnumerable<dynamic> list)
{
foreach (dynamic item in list)
{
string name = item.Name;
int id = item.Id;
}
}
Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.
Should be easy like this :
Get-ComputerInfo | select windowsversion
import csv
with open(..., 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
Edit: this only works with python 2.x.
To make it work with python 3.x replace wb
with w
(see this SO answer)
with open(..., 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
Thanks All, I found how to do it, which is the same as Dave and Sergey:
I am using QT Creator:
In the main GUI window create using the drag drop GUI and create label (e.g. "myLabel")
In the callback of the button (clicked) do the following using the (*ui) pointer to the user interface window:
void MainWindow::on_pushButton_clicked()
{
QImage imageObject;
imageObject.load(imagePath);
ui->myLabel->setPixmap(QPixmap::fromImage(imageObject));
//OR use the other way by setting the Pixmap directly
QPixmap pixmapObject(imagePath");
ui->myLabel2->setPixmap(pixmapObject);
}
This code shows the example how to prevent entering non digit symbols.
angular.module('app').
directive('onlyDigits', function () {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined) return '';
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput !== inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
You can define a DB class as below. Also, as andrewf suggested, use a context manager for cursor access.I'd define it as a member function. This way it keeps the connection open across multiple transactions from the app code and saves unnecessary reconnections to the server.
import pyodbc
class MS_DB():
""" Collection of helper methods to query the MS SQL Server database.
"""
def __init__(self, username, password, host, port=1433, initial_db='dev_db'):
self.username = username
self._password = password
self.host = host
self.port = str(port)
self.db = initial_db
conn_str = 'DRIVER=DRIVER=ODBC Driver 13 for SQL Server;SERVER='+ \
self.host + ';PORT='+ self.port +';DATABASE='+ \
self.db +';UID='+ self.username +';PWD='+ \
self._password +';'
print('Connected to DB:', conn_str)
self._connection = pyodbc.connect(conn_str)
pyodbc.pooling = False
def __repr__(self):
return f"MS-SQLServer('{self.username}', <password hidden>, '{self.host}', '{self.port}', '{self.db}')"
def __str__(self):
return f"MS-SQLServer Module for STP on {self.host}"
def __del__(self):
self._connection.close()
print("Connection closed.")
@contextmanager
def cursor(self, commit: bool = False):
"""
A context manager style of using a DB cursor for database operations.
This function should be used for any database queries or operations that
need to be done.
:param commit:
A boolean value that says whether to commit any database changes to the database. Defaults to False.
:type commit: bool
"""
cursor = self._connection.cursor()
try:
yield cursor
except pyodbc.DatabaseError as err:
print("DatabaseError {} ".format(err))
cursor.rollback()
raise err
else:
if commit:
cursor.commit()
finally:
cursor.close()
ms_db = MS_DB(username='my_user', password='my_secret', host='hostname')
with ms_db.cursor() as cursor:
cursor.execute("SELECT @@version;")
print(cur.fetchall())
Here's my approach using Swift 2 and Xcode 7.3. This example will use a single ViewController to load two .xib files -- one for a UITableView and one for the UITableCellView.
For this example you can drop a UITableView right into an empty TableNib.xib file. Inside, set the file's owner to your ViewController class and use an outlet to reference the tableView.
and
Now, in your view controller, you can delegate the tableView as you normally would, like so
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
...
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Table view delegate
self.tableView.delegate = self
self.tableView.dataSource = self
...
To create your Custom cell, again, drop a Table View Cell object into an empty TableCellNib.xib file. This time, in the cell .xib file you don't have to specify an "owner" but you do need to specify a Custom Class and an identifier like "TableCellId"
Create your subclass with whatever outlets you need like so
class TableCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
}
Finally... back in your View Controller, you can load and display the entire thing like so
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// First load table nib
let bundle = NSBundle(forClass: self.dynamicType)
let tableNib = UINib(nibName: "TableNib", bundle: bundle)
let tableNibView = tableNib.instantiateWithOwner(self, options: nil)[0] as! UIView
// Then delegate the TableView
self.tableView.delegate = self
self.tableView.dataSource = self
// Set resizable table bounds
self.tableView.frame = self.view.bounds
self.tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
// Register table cell class from nib
let cellNib = UINib(nibName: "TableCellNib", bundle: bundle)
self.tableView.registerNib(cellNib, forCellReuseIdentifier: self.tableCellId)
// Display table with custom cells
self.view.addSubview(tableNibView)
}
The code shows how you can simply load and display a nib file (the table), and second how to register a nib for cell use.
Hope this helps!!!
You could still use that event. Just check that the sender argument is the control you actually care about and if so, run the event code.
The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n
, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n
on input, and conversely on output.
From the C99 standard (the N869 draft document), §7.19.2/2,
A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.
And in §7.19.3/2
Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.
About use of fseek
, in §7.19.9.2/4:
For a text stream, either
offset
shall be zero, oroffset
shall be a value returned by an earlier successful call to theftell
function on a stream associated with the same file andwhence
shall beSEEK_SET
.
About use of ftell
, in §17.19.9.4:
The
ftell
function obtains the current value of the file position indicator for the stream pointed to bystream
. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by thefseek
function for returning the file position indicator for the stream to its position at the time of theftell
call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.
I think that’s the most important, but there are some more details.
You can
declare var require: any
Or, for more comprehensive support, use DefinitelyTyped's require.d.ts
Also, instead of var mongoose = require('mongoose')
, you could try the following
import mongoose from 'mongoose' // or
import mongoose = require('mongoose')
If you want to pass props to a component inside a route, the simplest way is by utilizing the render
, like this:
<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />
You can access the props inside the DetailPage
using:
this.props.match
this.props.globalStore
The {...props}
is needed to pass the original Route's props, otherwise you will only get this.props.globalStore
inside the DetailPage
.
the file is a native DLL which means you can't add it to a .NET project via Add Reference... you can use it via DllImport (see http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx)
I know there's an easier way that this, but darned if I can find it...
jcomeau@intrepid:~$ python -c 'import os; print(os.path.abspath("cat.wav"))'
/home/jcomeau/cat.wav
jcomeau@intrepid:~$ ls $PWD/cat.wav
/home/jcomeau/cat.wav
Could be a bug with concurrent GC http://support.microsoft.com/kb/2679415
From the perspective of managing complexity, a primary software engineering objective, we want to avoid propagating unnecessary cyclomatic complexity to the clients of an API. Returning a null to the client is like returning them the cyclomatic complexity cost of another code branch.
(This corresponds to a unit testing burden. You would need to write a test for the null return case, in addition to the empty collection return case.)
If its possible uninstall wamp then run installation as administrator then change you mysql.conf file like that
<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Allow,Deny
Allow from all
Allow from all
</Directory>
Not: Before I reinstall as admin the solution above didn't work for me
Use SQL*Loader. It takes a little setting up, but if this isn't a one off, its worth it.
Create Table
SQL> create table ldr_test (id number(10) primary key, description varchar2(20));
Table created.
SQL>
Create CSV
oracle-2% cat ldr_test.csv
1,Apple
2,Orange
3,Pear
oracle-2%
Create Loader Control File
oracle-2% cat ldr_test.ctl
load data
infile 'ldr_test.csv'
into table ldr_test
fields terminated by "," optionally enclosed by '"'
( id, description )
oracle-2%
Run SQL*Loader command
oracle-2% sqlldr <username> control=ldr_test.ctl
Password:
SQL*Loader: Release 9.2.0.5.0 - Production on Wed Sep 3 12:26:46 2008
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Commit point reached - logical record count 3
Confirm insert
SQL> select * from ldr_test;
ID DESCRIPTION
---------- --------------------
1 Apple
2 Orange
3 Pear
SQL>
SQL*Loader has alot of options, and can take pretty much any text file as its input. You can even inline the data in your control file if you want.
Here is a page with some more details -> SQL*Loader
@Hammer response worked for me, im using to control a floating action button
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
android.app.Fragment currentFragment = getFragmentManager().findFragmentById(R.id.content_frame);
Log.d("VIE",String.valueOf(currentFragment));
if (currentFragment instanceof PerfilFragment) {
PerfilEdit(view, fab);
}
}
});
The result is same for all options. Redirect.
<meta>
in HTML:
window.location
in JS:
if (1 === 1) { window.location.href = 'http://example.com'; }
.header('Location:')
in PHP:
header()
must be the first command in php script, before output any other. If you try output some before header, will receive an Warning: Cannot modify header information - headers already sent
If you're using Postgres, you can use array_agg
like
SELECT userid,MAX(adate),(array_agg(value ORDER BY adate DESC))[1] as value
FROM YOURTABLE
GROUP BY userid
I'm not familiar with Oracle. This is what I came up with
SELECT
userid,
MAX(adate),
SUBSTR(
(LISTAGG(value, ',') WITHIN GROUP (ORDER BY adate DESC)),
0,
INSTR((LISTAGG(value, ',') WITHIN GROUP (ORDER BY adate DESC)), ',')-1
) as value
FROM YOURTABLE
GROUP BY userid
Both queries return the same results as the accepted answer. See SQLFiddles:
This error comes when using the following command in Windows. You can simply run the following command by removing the dot '.'
and the slash '/'
.
Instead of writing:
D:\Gesture Recognition\Gesture Recognition\Debug>./"Gesture Recognition.exe"
Write:
D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"
If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny
is actually a good name):
def getAny(dic, keys, default=None):
return (keys or default) and dic.get(keys[0],
getAny( dic, keys[1:], default=default))
or even better, without recursion and more clear:
def getAny(dic, keys, default=None):
for k in keys:
if k in dic:
return dic[k]
return default
Then that could be used in a way similar to the dict.get method, like:
getAny(myDict, keySet)
and even have a default result in case of no keys found at all:
getAny(myDict, keySet, "not found")
I had the same problem. Turns out the project I was referencing did not get build. When I went to the build configuration manager in visual studio and enabled the reference project , the issue got resolved.
As of Pandas 0.18 one way to do this is to use the sort_index
method of the grouped data.
Here's an example:
np.random.seed(1)
n=10
df = pd.DataFrame({'mygroups' : np.random.choice(['dogs','cats','cows','chickens'], size=n),
'data' : np.random.randint(1000, size=n)})
grouped = df.groupby('mygroups', sort=False).sum()
grouped.sort_index(ascending=False)
print grouped
data
mygroups
dogs 1831
chickens 1446
cats 933
As you can see, the groupby column is sorted descending now, indstead of the default which is ascending.
As theEye's answer it is not an answer to this question, but as I also came here looking for the error im posting my case as others might find this also useful:
I got this error message when I was by error trying to calculate a value of two different types.
In my case I was trying to divide a CGFloat
by a Double
"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"
No need to use scan
, if we need only one result.
No need to use Python's match
, when we have Ruby's String[regexp,#]
.
See: http://ruby-doc.org/core/String.html#method-i-5B-5D
Note: str[regexp, capture] ? new_str or nil
For me the major difference is all the ancilliary files that TFS will add to your solution (.vssscc) to 'support' TFS - we've had recent issues with these files ending up mapped to the wrong branch, which lead to some interesting debugging...
For those working in Titanium Studio, the item is a little different: It's under the "Titanium Studio" Themes tab.
The color to change is the "Selection" one in the top right.
Not all parameters are supported by all cameras - actually, they are one of the most troublesome part of the OpenCV library. Each camera type - from android cameras to USB cameras to professional ones offer a different interface to modify its parameters. There are many branches in OpenCV code to support as many of them, but of course not all possibilities are covered.
What you can do is to investigate your camera driver, write a patch for OpenCV and send it to code.opencv.org. This way others will enjoy your work, the same way you enjoy others'.
There is also a possibility that your camera does not support your request - most USB cams are cheap and simple. Maybe that parameter is just not available for modifications.
If you are sure the camera supports a given param (you say the camera manufacturer provides some code) and do not want to mess with OpenCV, you can wrap that sample code in C++ with boost::python, to make it available in Python. Then, enjoy using it.
You can use the >> operator. This will append data from a command to the end of a text file.
To test this try running:
echo "Hi this is a test" >> textfile.txt
Do this a couple of times and then run:
cat textfile.txt
You'll see your text has been appended several times to the textfile.txt file.
This is the sort of code that we shouldn't be doing ourselves. Use libraries for the mundane stuff, save your brain for the hard stuff.
In this case, I recommend using FilenameUtils.removeExtension() from Apache Commons IO
You can also set a default value for the variable, so you don't need to use two "[", which amounts to two processes ("[" is actually a program) instead of one.
It goes by this syntax: ${VARIABLE:-default}.
The whole thing has to be thought in such a way that this "default" value is something distinct from a "valid" value/content.
If that's not possible for some reason you probably need to add a step like checking if there's a value at all, along the lines of "if [ -z $VARIABLE ] ; then echo "the variable needs to be filled"", or "if [ ! -z $VARIABLE ] ; then #everything is fine, proceed with the rest of the script".
Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:
In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75
Doing some rough math:
75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB
So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.
If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.
You can achieve by data-*
attribute like data-replace="replaceTarget,replaceBy"
so with help of jQuery to get replaceTarget
& replaceBy
value by .split()
method after getting values then use .replaceWith()
method.
This data-*
attribute technique to easily manage any tag replacement without changing below (common code for all tag replacement).
I hope below snippet will help you lot.
$(document).on('click', '[data-replace]', function(){_x000D_
var replaceTarget = $(this).attr('data-replace').split(',')[0];_x000D_
var replaceBy = $(this).attr('data-replace').split(',')[1];_x000D_
$(replaceTarget).replaceWith($(replaceBy).html($(replaceTarget).html()));_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<p id="abc">Hello World #1</p>_x000D_
<a href="#" data-replace="#abc,<h1/>">P change with H1 tag</a>_x000D_
<hr>_x000D_
<h2 id="xyz">Hello World #2</h2>_x000D_
<a href="#" data-replace="#xyz,<p/>">H1 change with P tag</a>_x000D_
<hr>_x000D_
<b id="bold">Hello World #2</b><br>_x000D_
<a href="#" data-replace="#bold,<i/>">B change with I tag</a>_x000D_
<hr>_x000D_
<i id="italic">Hello World #2</i><br>_x000D_
<a href="#" data-replace="#italic,<b/>">I change with B tag</a>
_x000D_
Use the snippet below as a solution for the cited challenge;
yum install openssl
yum install openssl-devel
Tested and proved effective on CentOS version 5.4 with keepalived version 1.2.7.
A quicker way if you are using React 16.3 and above is by creating a ref in the constructor, then attaching it to the component you wish to use with as shown below.
...
constructor(props){
...
//create a ref
this.someRefName = React.createRef();
}
onScroll(){
let offsetTop = this.someRefName.current.offsetTop;
}
render(){
...
<Component ref={this.someRefName} />
}
ALTER TABLE [dbo].[Employee] ADD DEFAULT ('N') FOR [CityBorn]
Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.
To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source
Add a file to your repository like this:
mvn install:install-file \
-Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID
-DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
-Dpackaging=jar \
-DlocalRepositoryPath=/var/www/html/mavenRepository
If your domain is example.com
and the root directory of the web server is located at /var/www/html/
, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>
.
If you'd like to turn this on by default for ALL ObjectMapper instances in a process, here's a little hack that will set the default value of INDENT_OUTPUT to true:
val indentOutput = SerializationFeature.INDENT_OUTPUT
val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
defaultStateField.setAccessible(true)
defaultStateField.set(indentOutput, true)
In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).
My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null
, for example).
Then I instantiate my table in the on load method
$(function () {
//.... some code here
table = $("#detailReportTable").DataTable();
.... more code here
});
and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:
function getOrderDetail() {
table.clear();
table.destroy();
...
$.ajax({
//.....api call here
});
....
table = $("#detailReportTable").DataTable();
}
I hope someone finds this useful!
The most concise and intuitive way would be:
var selectElement = document.getElementById('ageselect');_x000D_
_x000D_
for (var age = 12; age <= 100; age++) {_x000D_
selectElement.add(new Option(age));_x000D_
}
_x000D_
Your age: <select id="ageselect"><option value="">Please select</option></select>
_x000D_
You can also differentiate the name and the value or add items at the start of the list with additional parameters to the used functions:
HTMLSelect?Element?.add(item[, before]);
new Option(text, value, defaultSelected, selected);
Assuming you have a field for DateTime
, you could have your query look like this:
SELECT *
FROM TABLE
WHERE DateTime > (GetDate() + 90)
If Template is not set (i.e. ==null), this error will be raised, too.
More comments:
If you know the parameter value by the time you add parameters, you can also use AddWithValue
The EXEC is not required. You can reference the @template parameter in the SELECT directly.
Yeah, it is quite vague.
You should use it whenever for readers of the documentation of your method it may be useful to also look at some other method. If the documentation of your methodA says "Works like methodB but ...", then you surely should put a link.
An alternative to @see
would be the inline {@link ...}
tag:
/**
* ...
* Works like {@link #methodB}, but ...
*/
When the fact that methodA calls methodB is an implementation detail and there is no real relation from the outside, you don't need a link here.
Dont forget of to use --force:
npm cache clean --force
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;
Here is the working sample fiddle
Just remove additional \r\n and "|" from your reg ex.
There are two ways for delete Database
You need to download the Native Development Kit.
Here's what I use. In my case, certain ftp servers (pure-ftpd for one) will always prompt for the username even with the -i parameter, and catch the "user username" command as the interactive password. What I do it enter a few NOOP (no operation) commands until the ftp server times out, and then login:
open ftp.example.com
noop
noop
noop
noop
noop
noop
noop
noop
user username password
...
quit
Check the items in forEach
<c:forEach items="${pools}" var="pool">
${pool.name}
</c:forEach>
Some times items="${pools}" has an extra space or it acts like string, retyping it should solve the issue.
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
Here is a very good explanation of why using Laravel's Database Seeder is preferable to using Migrations: https://web.archive.org/web/20171018135835/http://laravelbook.com/laravel-database-seeding/
Although, following the instructions on the official documentation is a much better idea because the implementation described at the above link doesn't seem to work and is incomplete. http://laravel.com/docs/migrations#database-seeding
BackgroundTint works as color filter.
Try seeing the difference by comment tint/background and check the output when both are set.
the correct procedure to resolve this warning, as other people write, is to go inside your project Properties and click on Java Build Path located on the left. Now you will find inside the Libraries Window the J2SE 1.5, double click on this one and a new window will give you the possibility to choose the correct Excecution Environment. Now select your version and the warning will disappear.
Add list-style-position: inside
to the ul
element. (example)
The default value for the list-style-position
property is outside
.
ul {_x000D_
text-align: center;_x000D_
list-style-position: inside;_x000D_
}
_x000D_
<ul>_x000D_
<li>one</li>_x000D_
<li>two</li>_x000D_
<li>three</li>_x000D_
</ul>
_x000D_
Another option (which yields slightly different results) would be to center the entire ul
element:
.parent {_x000D_
text-align: center;_x000D_
}_x000D_
.parent > ul {_x000D_
display: inline-block;_x000D_
}
_x000D_
<div class="parent">_x000D_
<ul>_x000D_
<li>one</li>_x000D_
<li>two</li>_x000D_
<li>three</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Use the left
function:
QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "
Also have a look at mid()
if you want more control.
Step 1: Set the proxy npm set proxy http://username:password@companyProxy:8080
npm set https-proxy http://username:password@companyProxy:8080
npm config set strict-ssl false -g
NOTES: No special characters in password except @ allowed.
I need to click the link who's href has substring "long" in it. How can I do this?
With the beauty of CSS selectors.
your statement would be...
driver.findElement(By.cssSelector("a[href*='long']")).click();
This means, in english,
Find me any 'a' elements, that have the
href
attribute, and that attributecontains
'long'
You can find a useful article about formulating your own selectors for automation effectively, as well as a list of all the other equality operators. contains
, starts with
, etc... You can find that at: http://ddavison.io/css/2014/02/18/effective-css-selectors.html
I had same problem. I wanted to edit ENUM values in table structure. Problem was because of rows that was saved before and new ENUM values doesn't contain saved values.
Solution was updating old saved rows in MySql table.
Here's one way:
create table #work
(
something decimal(8,3) not null
)
insert #work values ( 0 )
insert #work values ( 12345.6789 )
insert #work values ( 3.1415926 )
insert #work values ( 45 )
insert #work values ( 9876.123456 )
insert #work values ( -12.5678 )
select convert(varchar,convert(decimal(8,2),something))
from #work
if you want it right-aligned, something like this should do you:
select str(something,8,2) from #work
You haven't defined struct stasher_file
by your first definition. What you have defined is an nameless struct type and a variable stasher_file
of that type. Since there's no definition for such type as struct stasher_file
in your code, the compiler complains about incomplete type.
In order to define struct stasher_file
, you should have done it as follows
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
Note where the stasher_file
name is placed in the definition.
I think you can do something like
image.center = [[imageView window] center];
Just to add couple cents to this.
The "delete_by_query" mentioned at the top is still available as a plugin in elasticsearch 2.x.
Although in the latest upcoming version 5.x it will be replaced by "delete by query api"
Even i face similar problem after I did some modification in code related to Cursor.
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
Cursor c = (Cursor)adapter.getItem(info.position);
long id = c.getLong(...);
String tempCity = c.getString(...);
//c.close();
...
}
After i commented out //c.close(); It is working fine. Try out at your end and update Initial setup is as... I have a list view in Fragment, and trying to delete and item from list via contextMenu.
For styles wp_register_style( 'namespace', 'http://locationofcss.com/mycss.css' );
Then use: wp_enqueue_style('namespace');
wherever you want the css to load.
Scripts are as above but the quicker way for loading jquery is just to use enqueue loaded in an init for the page you want it to load on: wp_enqueue_script('jquery');
Unless of course you want to use the google repository for jquery.
You can also conditionally load the jquery library that your script is dependent on:
wp_enqueue_script('namespaceformyscript', 'http://locationofscript.com/myscript.js', array('jquery'));
Update Sept. 2017
I wrote this answer a while ago. I should clarify that the best place to enqueue your scripts and styles is within the wp_enqueue_scripts
hook. So for example:
add_action('wp_enqueue_scripts', 'callback_for_setting_up_scripts');
function callback_for_setting_up_scripts() {
wp_register_style( 'namespace', 'http://locationofcss.com/mycss.css' );
wp_enqueue_style( 'namespace' );
wp_enqueue_script( 'namespaceformyscript', 'http://locationofscript.com/myscript.js', array( 'jquery' ) );
}
The wp_enqueue_scripts
action will set things up for the "frontend". You can use the admin_enqueue_scripts
action for the backend (anywhere within wp-admin) and the login_enqueue_scripts
action for the login page.
Well there is quick to run a html which needs permission or blocked by CORS Just simply open the folder using VSCODE and install an extension called "live server"
And then just click on the bottom which says go live, thats it. Screenshot
java.* packages are the core Java language packages, meaning that programmers using the Java language had to use them in order to make any worthwhile use of the java language.
javax.* packages are optional packages, which provides a standard, scalable way to make custom APIs available to all applications running on the Java platform.
According to Mozilla MDN: "The X-Forwarded-For (XFF) header is a de-facto standard header for identifying the originating IP address of a client."
They publish clear information in their X-Forwarded-For article.
I faced this issue when I integrated spring boot with spring mvc. I solved it by just adding these dependencies.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
VBA stands for Visual Basic for Applications and so is the small "for applications" scripting brother of VB. VBA is indeed available in Excel, but also in the other office applications.
With VB, one can create a stand-alone windows application, which is not possible with VBA.
It is possible for developers however to "embed" VBA in their own applications, as a scripting language to automate those applications.
Edit: From the VBA FAQ:
Q. What is Visual Basic for Applications?
A. Microsoft Visual Basic for Applications (VBA) is an embeddable programming environment designed to enable developers to build custom solutions using the full power of Microsoft Visual Basic. Developers using applications that host VBA can automate and extend the application functionality, shortening the development cycle of custom business solutions.
Note that VB.NET is even another language, which only shares syntax with VB.
The following code is basic on @DTing‘s answer and what I learn from class, which uses a while loop to insert (indicated in the code).
class Node:
def __init__(self, val):
self.l_child = None
self.r_child = None
self.data = val
def binary_insert(root, node):
y = None
x = root
z = node
#while loop here
while x is not None:
y = x
if z.data < x.data:
x = x.l_child
else:
x = x.r_child
z.parent = y
if y == None:
root = z
elif z.data < y.data:
y.l_child = z
else:
y.r_child = z
def in_order_print(root):
if not root:
return
in_order_print(root.l_child)
print(root.data)
in_order_print(root.r_child)
r = Node(3)
binary_insert(r, Node(7))
binary_insert(r, Node(1))
binary_insert(r, Node(5))
in_order_print(r)
Simply replace image/jpeg
with application/octet-stream
. The client would not recognise the URL as an inline-able resource, and prompt a download dialog.
A simple JavaScript solution would be:
//var img = reference to image
var url = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream');
window.open(url);
// Or perhaps: location.href = url;
// Or even setting the location of an <iframe> element,
Another method is to use a blob:
URI:
var img = document.images[0];
img.onclick = function() {
// atob to base64_decode the data-URI
var image_data = atob(img.src.split(',')[1]);
// Use typed arrays to convert the binary data to a Blob
var arraybuffer = new ArrayBuffer(image_data.length);
var view = new Uint8Array(arraybuffer);
for (var i=0; i<image_data.length; i++) {
view[i] = image_data.charCodeAt(i) & 0xff;
}
try {
// This is the recommended method:
var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
} catch (e) {
// The BlobBuilder API has been deprecated in favour of Blob, but older
// browsers don't know about the Blob constructor
// IE10 also supports BlobBuilder, but since the `Blob` constructor
// also works, there's no need to add `MSBlobBuilder`.
var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
bb.append(arraybuffer);
var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
}
// Use the URL object to create a temporary URL
var url = (window.webkitURL || window.URL).createObjectURL(blob);
location.href = url; // <-- Download!
};
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.
FOR /d %%K in ("n:\test*") DO (
FOR /d %%J in ("%%K*") DO (
FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"
)
)
FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"
I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged
We can also use SQL kind of expression inside filter :
Note -> Here I am showing two conditions and a date range for future reference :
ordersDf.filter("order_status = 'PENDING_PAYMENT' AND order_date BETWEEN '2013-07-01' AND '2013-07-31' ")
I'm not sure what you're doing, but this will go from JSON to CSV using JavaScript. This is using the open source JSON library, so just download JSON.js into the same folder you saved the code below into, and it will parse the static JSON value in json3
into CSV and prompt you to download/open in Excel.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSON to CSV</title>
<script src="scripts/json.js" type="text/javascript"></script>
<script type="text/javascript">
var json3 = { "d": "[{\"Id\":1,\"UserName\":\"Sam Smith\"},{\"Id\":2,\"UserName\":\"Fred Frankly\"},{\"Id\":1,\"UserName\":\"Zachary Zupers\"}]" }
DownloadJSON2CSV(json3.d);
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
line += array[i][index] + ',';
}
// Here is an example where you would wrap the values in double quotes
// for (var index in array[i]) {
// line += '"' + array[i][index] + '",';
// }
line.slice(0,line.Length-1);
str += line + '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + escape(str))
}
</script>
</head>
<body>
<h1>This page does nothing....</h1>
</body>
</html>
Just to improve YCR's answer:
1) I added black lines on x and y axis. Otherwise they are made transparent too.
2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.
Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.
MyTheme_transparent <- theme(
panel.background = element_rect(fill = "transparent"), # bg of the panel
plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
panel.grid.major = element_blank(), # get rid of major grid
panel.grid.minor = element_blank(), # get rid of minor grid
legend.background = element_rect(fill = "transparent"), # get rid of legend bg
legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
axis.line = element_line(colour = "black") # adding a black line for x and y axis
)
One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:
> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function
Had you used the 'new' keyword, it would have looked like this:
> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016
Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:
el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function
The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).
# now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')
JSX tags (<Component/>
) are clearly not standard javascript and have no special meaning if you put them inside a naked <script>
tag for example. Hence all React files that contain them are JSX and not JS.
By convention, the entry point of a React application is usually .js instead of .jsx even though it contains React components. It could as well be .jsx. Any other JSX files usually have the .jsx extension.
In any case, the reason there is ambiguity is because ultimately the extension does not matter much since the transpiler happily munches any kinds of files as long as they are actually JSX.
My advice would be: don't worry about it.
As others have pointed out, the %
(remainder) operator is not the same as the mathematical
mod
modulus operation/function.
mod
vs%
The
x mod n
function mapsx
ton
in the range of[0,n)
.
Whereas thex % n
operator mapsx
ton
in the range of(-n,n)
.
In order to have a method to use the mathematical modulus operation and not
care about the sign in front of x
one can use:
((x % n) + n) % n
Maybe this picture helps understand it better (I had a hard time wrapping my head around this first)
I don't know if this has changed. But from my experience. nested elements have a maximum opacity equal to the fathers.
Which mean:
<div id="a">
<div id="b">
</div></div>
Div#a has 0.6 opacity
div#b has 1 opacity
Has #b is within #a then it's maximum opacity is always 0.6
If #b would have 0.5 opacity. In reallity it would be 0.6*0.5 == 0.3 opacity
Type a value in one cell (EX:B4 CELL). For temporary use this formula in other cell (once done delete it). =CONCAT(XY,B4) . click and drag till the value you need. Copy the whole column and right click paste only values (second option).
I tried and it's working as expected.
you can use app:layout_constraintVertical_weight
it same as layout_weight
in linearlayout
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/button5"
app:layout_constraintVertical_weight="1"/>
<Button
android:id="@+id/button5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintLeft_toRightOf="@+id/button4"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintVertical_weight="1"/>
</android.support.constraint.ConstraintLayout>
NOTE: app:layout_constraintVertical_weight
(app:layout_constraintHorizontal_weight
) will work with android:layout_width="0dp"
(android:layout_height="0dp"
From a related SO question: Format a number with commas but without decimals in SQL Server 2008 R2?
SELECT CONVERT(varchar, CAST(1112 AS money), 1)
This was tested in SQL Server 2008 R2.
There is some progress for Visual studio 2013 developers :-D woot woot! See blog post Visual Studio Installer Projects Extension.
Link and information were retrieved from Brian Harry's blog post Creating installers with Visual Studio.
There are three YAML capable packages. Syck (pip install syck
) which implements the YAML 1.0 specification from 2002; PyYAML (pip install pyyaml
) which follows the YAML 1.1 specification from 2004; and ruamel.yaml which follows the latest (YAML 1.2, from 2009) specification.
You can install the YAML 1.2 compatible package with pip install ruamel.yaml
or if you are running a modern version of Debian/Ubuntu (or derivative) with:
sudo apt-get install python-ruamel.yaml
My solution if you work with the Trunk/
and Release/
workflow:
Right click on Trunk/
which you will be creating your Branch from:
Select Branch/Tag:
Type in location of your new branch, commit message, and any externals (if your repository has them):
Consider using the decorator pattern http://en.wikipedia.org/wiki/Decorator_pattern
You can change the decorator at runtime with one that has different properties when an event occurs.
Sure, use the .format method. E.g.,
print('{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d} {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d} {:7.2f}'.format('zz', 42, 123.34))
will print
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
10s
format a string with 10 spaces, left justified by default
3d
format an integer reserving 3 spaces, right justified by default
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
Update for f-string mode. E.g.,
text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d} {other_number:7.2f}')
For right alignment
print(f'{text:>10} {number:3d} {other_number:7.2f}')
As of now, Google official Text-to-Speech service is available at https://cloud.google.com/text-to-speech/
It's free for the first 4 million characters.
Read this https://docs.djangoproject.com/en/dev/howto/static-files/:
For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.
And try:
~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp
Then add 'myapp'
to INSTALLED_APPS
(myprj/settings.py
).
~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html
Edit myprj/urls.py
:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
class HelloView(TemplateView):
template_name = "hello.html"
urlpatterns = patterns('',
url(r'^$', HelloView.as_view(), name='hello'),
)
And run it:
~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver
It works!
Transferring a file using TortoiseSVN:
Step:1 Please Select the files which you want to move, Right-click and drag the files to the folder which you to move them to, A window will popup after follow the below instruction
Step 2: After you click the above the commit the file as below mention
There is a generic method to give CMake directions about where to find libraries.
When looking for a library, CMake looks first in the following variables:
CMAKE_LIBRARY_PATH
and LD_LIBRARY_PATH
for librariesCMAKE_INCLUDE_PATH
and INCLUDE_PATH
for includesIf you declare your Boost files in one of the environment variables, CMake will find it. Example:
export CMAKE_LIBRARY_PATH="/stuff/lib.boost.1.52/lib:$CMAKE_LIBRARY_PATH"
export CMAKE_INCLUDE_PATH="/stuff/lib.boost.1.52/include:$CMAKE_INCLUDE_PATH"
If it's too cumbersome, you can also use a nice installing tool I wrote that will do everything for you: C++ version manager
Use Parameter Binding as describe completely here : http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:
public class ThreadProvider implements CustomInterface{
...
}
Then in your controller try this:
@Controller
public class ChiusuraController {
@Autowired
private CustomInterface chiusuraProvider;
}
The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider
extend ThreadProvider
Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).
When you DID extend from ThreadProvider
assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider
type.
If you absolutely need to use ChisuraProvider
you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:
<aop:aspectj-autoproxy proxy-target-class="true"/>
Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb
You can compare an array like the below mentioned if the array has some values
it('should check if the array are equal', function() {
var mockArr = [1, 2, 3];
expect(mockArr ).toEqual([1, 2, 3]);
});
But if the array that is returned from some function has more than 1 elements and all are zero then verify by using
expect(mockArray[0]).toBe(0);
Since HTML5 is still in the works and doesn't have consistant support across any browsers yet, my guess is that it's going to be quite a while before you get a WYSIWYG HTML5 Editor.
In the mean time, get used to editting your markup by hand in a good text editor like Notepad++ or TextEdit.
The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH
clause. See this article for one example of translating a CONNECT BY
into a WITH
(technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.
Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:
CREATE TABLE emp(empid INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(10),
salary DECIMAL(9, 2),
mgrid INTEGER);
where mgrid
references an employee's manager's empid
, the task is, get the names of everybody who reports directly or indirectly to Joan
. In Oracle, that's a simple CONNECT
:
SELECT name
FROM emp
START WITH name = 'Joan'
CONNECT BY PRIOR empid = mgrid
In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):
WITH n(empid, name) AS
(SELECT empid, name
FROM emp
WHERE name = 'Joan'
UNION ALL
SELECT nplus1.empid, nplus1.name
FROM emp as nplus1, n
WHERE n.empid = nplus1.mgrid)
SELECT name FROM n
Oracle's START WITH
clause becomes the first nested SELECT
, the base case of the recursion, to be UNION
ed with the recursive part which is just another SELECT
.
SQL Server's specific flavor of WITH
is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.
Here is a solution where you set the ylabel of one of the plots and adjust the position of it so it is centered vertically. This way you avoid problems mentioned by KYC.
import numpy as np
import matplotlib.pyplot as plt
def set_shared_ylabel(a, ylabel, labelpad = 0.01):
"""Set a y label shared by multiple axes
Parameters
----------
a: list of axes
ylabel: string
labelpad: float
Sets the padding between ticklabels and axis label"""
f = a[0].get_figure()
f.canvas.draw() #sets f.canvas.renderer needed below
# get the center position for all plots
top = a[0].get_position().y1
bottom = a[-1].get_position().y0
# get the coordinates of the left side of the tick labels
x0 = 1
for at in a:
at.set_ylabel('') # just to make sure we don't and up with multiple labels
bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
bboxes = bboxes.inverse_transformed(f.transFigure)
xt = bboxes.x0
if xt < x0:
x0 = xt
tick_label_left = x0
# set position of label
a[-1].set_ylabel(ylabel)
a[-1].yaxis.set_label_coords(tick_label_left - labelpad,(bottom + top)/2, transform=f.transFigure)
length = 100
x = np.linspace(0,100, length)
y1 = np.random.random(length) * 1000
y2 = np.random.random(length)
f,a = plt.subplots(2, sharex=True, gridspec_kw={'hspace':0})
a[0].plot(x, y1)
a[1].plot(x, y2)
set_shared_ylabel(a, 'shared y label (a. u.)')
I nuked everything Java, JDK, and oracle. I was running Java 8 on OSX El Capitan
Other answers were missing tons of stuff. This answer covers a lot more bases.
Good bye, shovelware.
sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.Helper-Tool.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist
sudo rm -rf /System/Library/Frameworks/JavaVM.framework
sudo rm -rf /var/db/receipts/com.oracle.jdk8u65.bom
sudo rm -rf /var/db/receipts/com.oracle.jdk8u65.plist
sudo rm -rf /var/db/receipts/com.oracle.jre.bom
sudo rm -rf /var/db/receipts/com.oracle.jre.plist
sudo rm -rf /var/root/Library/Preferences/com.oracle.javadeployment.plist
sudo rm -rf ~/Library/Preferences/com.oracle.java.JavaAppletPlugin.plist
sudo rm -rf ~/Library/Preferences/com.oracle.javadeployment.plist
sudo rm -rf ~/.oracle_jre_usage
why don't you store your values in HTML5 storage objects such as sessionStorage
or localStorage
, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.
To store values for a session:
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')
or more permanently:
localStorage.getItem('label')
localStorage.setItem('label', 'value')
So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..
Starting the OracleServiceXXX from the services.msc worked for me in Windows.
As with all css properties that contain hyphens, their corresponding names in JS is to remove the hyphen and make the following letter capital: backgroundColor
alert(myDiv.style.backgroundColor);
In addition to Ishan's answer, if you want to draw programatically without user interaction, you can edit the class just a little like this.
public class DrawingCanvas extends View {
private Paint mPaint;
private Path mPath;
private boolean isUserInteractionEnabled = false;
public DrawingCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
mPath = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isUserInteractionEnabled) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPath.moveTo(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
mPath.lineTo(event.getX(), event.getY());
invalidate();
break;
case MotionEvent.ACTION_UP:
break;
}
}
return true;
}
public void moveCursorTo(float x, float y) {
mPath.moveTo(x, y);
}
public void makeLine(float toX, float toY) {
mPath.lineTo(toX, toY);
}
public void setUserInteractionEnabled(boolean userInteractionEnabled) {
isUserInteractionEnabled = userInteractionEnabled;
}
}
And then use it like
drawingCanvas.setUserInteractionEnabled(true) // to enable user interaction
drawingCanvas.setUserInteractionEnabled(true) // to disable user interaction
To Draw programatically
drawingCanvas.moveCursorTo(70f, 70f) // Move the cursor (Define starting point)
drawingCanvas.makeLine(200f, 200f) // End point (To where you need to draw)
If you intend to use the default VB6 Collection
, then the easiest you can do is:
col1.add array("first key", "first string"), "first key"
col1.add array("second key", "second string"), "second key"
col1.add array("third key", "third string"), "third key"
Then you can list all values:
Dim i As Variant
For Each i In col1
Debug.Print i(1)
Next
Or all keys:
Dim i As Variant
For Each i In col1
Debug.Print i(0)
Next
I think that concat
method and +
should be mentioned here as well:
assert_eq!(
("My".to_owned() + " " + "string"),
["My", " ", "string"].concat()
);
and there is also concat!
macro but only for literals:
let s = concat!("test", 10, 'b', true);
assert_eq!(s, "test10btrue");
Thanks for enlightening us Cypawer.
I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi
and it worked flawlessly.
We can clear EditText data in two ways
First One setting EditText is empty like below line
editext.setText("");
Second one clearing EditText data like this
editText.getText().clear();
I suggest second way
Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:
using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
if (stream != null)
{
stream.ReadTimeout = Timeout.Infinite;
using (var reader = new StreamReader(stream, Encoding.UTF8, false))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line != String.Empty)
{
Console.WriteLine("Count {0}", count++);
}
Console.WriteLine(line);
}
}
}
}
Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.
Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id
and date
.
ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);
Then when inserting a record add the condition when a conflict is encountered:
INSERT INTO funds (`fund_id`, `date`, `price`)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:
INSERT INTO funds (`fund_id`, `date`, `price`)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value
This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.
This appears to be caused by a long-standing (since 2004) bug (#6295) in MySQL, titled
Triggers are not processed for NOT NULL columns.
It was allegedly fixed in version 5.7.1 of MySQL (Changelog, last entry) in 2013, making MySQL behave as “per the SQL standard” (ibid).
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
File.Delete(filePath);
Or in a single line:
Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), File.Delete);
A quick fix is to add the _CRT_SECURE_NO_WARNINGS definition to your project's settings
Right-click your C++ and chose the "Properties" item to get to the properties window.
Now follow and expand to, "Configuration Properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".
In the "Preprocessor definitions" add
_CRT_SECURE_NO_WARNINGS
but it would be a good idea to add
_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
as to inherit predefined definitions
IMHO & for the most part this is a good approach.
The for
attribute of the <label>
tag should be equal to the id
attribute of the related element to bind them together.
You can using the exists
if (pricePublicList.Exists(x => x.Size == 200))
{
//code
}
PHP is not what you are looking for, check out mod_rewrite
Generate a number during the build and write it to a file. Whenever you make a release, commit that file with the comment "Build 147" (or whatever the build number currently is). Don't commit the file during normal development. This way, you can easily map between build numbers and versions in Git.
Verify current version of python by:
$ python --version
then check python is symbolic link to which file.
$ ll /usr/bin/python
Output Ex:
lrwxrwxrwx 1 root root 9 Jun 16 2014 /usr/bin/python -> python2.7*
Check other available versions of python:
$ ls /usr/bin/python*
Output Ex:
/usr/bin/python /usr/bin/python2.7-config /usr/bin/python3.4 /usr/bin/python3.4m-config /usr/bin/python3.6m /usr/bin/python3m
/usr/bin/python2 /usr/bin/python2-config /usr/bin/python3.4-config /usr/bin/python3.6 /usr/bin/python3.6m-config /usr/bin/python3m-config
/usr/bin/python2.7 /usr/bin/python3 /usr/bin/python3.4m /usr/bin/python3.6-config /usr/bin/python3-config /usr/bin/python-config
If want to change current version of python to 3.6 version edit file ~/.bashrc:
vim ~/.bashrc
add below line in the end of file and save:
alias python=/usr/local/bin/python3.6
To install pip for python 3.6
$ sudo apt-get install python3.6 python3.6-dev
$ sudo curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python3.6
$ sudo easy_install pip
On Success, check current version of pip:
$ pip3 -V
Output Ex:
pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.6)
As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)
EDIT 1:
Following your comment, I run a test table:
mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)
Insertion:
mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)
EDIT 2:
So, aparently you want to insert a NULL value to pdd
field as your comment states ?
You can do that in 2 ways like this:
Method 1:
mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)
Method 2:
mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)
EDIT 3:
You failed to change the default value of pdd
field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)
mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3 Duplicates: 0 Warnings: 1
At this time (mid 2019), with JupyterLab 1.0 release, as a user, I think we should adopt JupyterLab for daily use. And from the JupyterLab official documentation:
The current release of JupyterLab is suitable for general daily use.
and
JupyterLab will eventually replace the classic Jupyter Notebook. Throughout this transition, the same notebook document format will be supported by both the classic Notebook and JupyterLab.
Note that JupyterLab has a extensible modular architecture. So in the old days, there is just one Jupyter Notebook, and now with JupyterLab (and in the future), Notebook is just one of the core applications in JupyterLab (along with others like code Console, command-line Terminal, and a Text Editor).
A couple of suggestions
The ACE driver isn't installed by default. It's also a 64 bit driver, so it might be worth disabling 32bit in your app pool. I've known 64 bit drivers not work when 32 bit is enabled.(eg the ISAPI filter which connects IIS to Tomcat).
The older JET driver is 32bit. It is included by default. If you could save a copy of your database as a .mdb file then using the JET driver might be a workaround
You need to check out the attr
method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src
with the string specified in the 2nd parameter.
A better way to approach replacing a series of images source would be to loop through each and check it's source.
Example:
$('img').each(function () {
var curSrc = $(this).attr('src');
if ( curSrc === 'http://example.com/smith.gif' ) {
$(this).attr('src', 'http://example.com/johnson.gif');
}
if ( curSrc === 'http://example.com/williams.gif' ) {
$(this).attr('src', 'http://example.com/brown.gif');
}
});
When I want to take into account extra characters like your commas (in my case each token may be entered with quotes), I'd do a string.replace() to change the other delimiters to blanks and then split on whitespace.
The problem is that in IE (which is what I presume you're testing in), the <iframe>
element has a document
property that refers to the document containing the iframe, and this is getting used before the contentDocument
or contentWindow.document
properties. What you need is:
function GetDoc(x) {
return x.contentDocument || x.contentWindow.document;
}
Also, document.all
is not available in all browsers and is non-standard. Use document.getElementById()
instead.
As always, you should question whether you truly need a mutable map.
Immutable maps are trivial to build:
val map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
Mutable maps are no different when first being built:
val map = collection.mutable.Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
In both of these cases, inference will be used to determine the correct type parameters for the Map instance.
You can also hold an immutable map in a var
, the variable will then be updated with a new immutable map instance every time you perform an "update"
var map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
If you don't have any initial values, you can use Map.empty:
val map : Map[String, String] = Map.empty //immutable
val map = Map.empty[String,String] //immutable
val map = collection.mutable.Map.empty[String,String] //mutable
Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.
I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.
Java
int temp = a ? b : c;
Equivalent to Kotlin:
var temp = if (a) b else c
Cong Ma does a good job of explaining what __getitem__
is used for - but I want to give you an example which might be useful.
Imagine a class which models a building. Within the data for the building it includes a number of attributes, including descriptions of the companies that occupy each floor :
Without using __getitem__
we would have a class like this :
class Building(object):
def __init__(self, floors):
self._floors = [None]*floors
def occupy(self, floor_number, data):
self._floors[floor_number] = data
def get_floor_data(self, floor_number):
return self._floors[floor_number]
building1 = Building(4) # Construct a building with 4 floors
building1.occupy(0, 'Reception')
building1.occupy(1, 'ABC Corp')
building1.occupy(2, 'DEF Inc')
print( building1.get_floor_data(2) )
We could however use __getitem__
(and its counterpart __setitem__
) to make the usage of the Building class 'nicer'.
class Building(object):
def __init__(self, floors):
self._floors = [None]*floors
def __setitem__(self, floor_number, data):
self._floors[floor_number] = data
def __getitem__(self, floor_number):
return self._floors[floor_number]
building1 = Building(4) # Construct a building with 4 floors
building1[0] = 'Reception'
building1[1] = 'ABC Corp'
building1[2] = 'DEF Inc'
print( building1[2] )
Whether you use __setitem__
like this really depends on how you plan to abstract your data - in this case we have decided to treat a building as a container of floors (and you could also implement an iterator for the Building, and maybe even the ability to slice - i.e. get more than one floor's data at a time - it depends on what you need.
Another option is using eval and parse, as in
d = 5
for (i in 1:10){
eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}
If your Activity extends ListActivity, you can simply override the OnListItemClick()
method like so:
/** {@inheritDoc} */
@Override
protected void onListItemClick(ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
// TODO : Logic
}
Select the height constraint from the Interface builder and take an outlet of it. So, when you want to change the height of the view you can use the below code.
yourHeightConstraintOutlet.constant = someValue
yourView.layoutIfNeeded()
Method updateConstraints()
is an instance method of UIView
. It is helpful when you are setting the constraints programmatically. It updates constraints for the view. For more detail click here.
There are two ways :
using .htaccess : Options -Indexes
create blank index.html
A few years ago it was said that update()
and digest()
were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:
var crypto = require('crypto');
var text = 'I love cupcakes';
var secret = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1'; //consider using sha256
var hash, hmac;
// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);
hmac.write(text); // write in to the stream
hmac.end(); // can't read from the stream until you call end()
hash = hmac.read().toString('hex'); // read out hmac digest
console.log("Method 1: ", hash);
// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);
Tested on node v6.2.2 and v7.7.2
See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.
Yes, it's possible. But first read, "What happens when I change my username?"
To change your username, click your profile picture in the top right corner, then click Settings
. On the left side, click Account
. Then click Change username
.
You can use
formname.textboxname.value="delete";
Or if you're using dotnet Core,
add to your .csproj file
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
</ItemGroup>
And
dotnet restore
function trbl(e, relative) {
var r = $(e).get(0).getBoundingClientRect(); relative = $(relative);
return {
t : r.top + relative['scrollTop'] (),
r : r.right + relative['scrollLeft'](),
b : r.bottom + relative['scrollTop'] (),
l : r.left + relative['scrollLeft']()
}
}
// Example
trbl(e, window);
figlegend may be what you're looking for: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figlegend
Example here: http://matplotlib.org/examples/pylab_examples/figlegend_demo.html
Another example:
plt.figlegend( lines, labels, loc = 'lower center', ncol=5, labelspacing=0. )
or:
fig.legend( lines, labels, loc = (0.5, 0), ncol=5 )
It seems mysql handles the type casting gracefully with SELECT statements. The shop_id field is of type varchar but the select statements works
select * from shops where shop_id = 26244317283;
But when you try updating the fields
update stores set store_url = 'https://test-url.com' where shop_id = 26244317283;
It fails with error Truncated incorrect DOUBLE value: '1t5hxq9'
You need to put the shop_id 26244317283 in quotes '26244317283' for the query to work since the field is of type varchar not int
update stores set store_url = 'https://test-url.com' where shop_id = '26244317283';
If you want to match starting from the beginning of the word, use:
\b\w{3,}
\b: word boundary
\w: word character
{3,}: three or more times for the word character
https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html
The time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:
- Connecting: (3)
- Sending query to server: (2)
- Parsing query: (2)
- Inserting row: (1 × size of row)
- Inserting indexes: (1 × number of indexes)
- Closing: (1)
From this it should be obvious, that sending one large statement will save you an overhead of 7 per insert statement, which in further reading the text also says:
If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements.
I tried both the 32-bit and 64-bit installers of both Oracle and IBM Java on Windows, and the presence of C:\Windows\SysWOW64\java.exe seems to be a reliable way to determine that 32-bit Java is available. I haven't tested older versions of these installers, but this at least looks like it should be a reliable way to test, for the most recent versions of Java.
Here is some code which extends Object with rad(deg)
, deg(rad)
and also two more useful functions: getAngle(point1,point2)
and getDistance(point1,point2)
where a point needs to have a x
and y
property.
Object.prototype.rad = (deg) => Math.PI/180 * deg;
Object.prototype.deg = (rad) => 180/Math.PI * rad;
Object.prototype.getAngle = (point1, point2) => Math.atan2(point1.y - point2.y, point1.x - point2.x);
Object.prototype.getDistance = (point1, point2) => Math.sqrt(Math.pow(point1.x-point2.x, 2) + Math.pow(point1.y-point2.y, 2));
Use cURL. This function is an alternative to file_get_contents
.
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
I had a similar problem now were I was using a bash script to dump some data. I ended up creating a symbolic link in the script folder with out any spaces in it. I then pointed my script to the symbolic link and that works fine.
To create your link. ln -s [TARGET DIRECTORY OR FILE] ./[SHORTCUT]
Mau or may not be of use.
You can create a .timer
systemd unit file to control the execution of your .service
unit file.
So for example, to wait for 1 minute after boot-up before starting your foo.service
, create a foo.timer
file in the same directory with the contents:
[Timer]
OnBootSec=1min
It is important that the service is disabled (so it doesn't start at boot), and the timer enabled, for all this to work (thanks to user tride for this):
systemctl disable foo.service
systemctl enable foo.timer
You can find quite a few more options and all information needed here: https://wiki.archlinux.org/index.php/Systemd/Timers
If you know you are going to return two objects, you can also use a generic pair:
public class Pair<A,B> {
public final A a;
public final B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
};
Edit A more fully formed implementation of the above:
package util;
public class Pair<A,B> {
public static <P, Q> Pair<P, Q> makePair(P p, Q q) {
return new Pair<P, Q>(p, q);
}
public final A a;
public final B b;
public Pair(A a, B b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((a == null) ? 0 : a.hashCode());
result = prime * result + ((b == null) ? 0 : b.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("rawtypes")
Pair other = (Pair) obj;
if (a == null) {
if (other.a != null) {
return false;
}
} else if (!a.equals(other.a)) {
return false;
}
if (b == null) {
if (other.b != null) {
return false;
}
} else if (!b.equals(other.b)) {
return false;
}
return true;
}
public boolean isInstance(Class<?> classA, Class<?> classB) {
return classA.isInstance(a) && classB.isInstance(b);
}
@SuppressWarnings("unchecked")
public static <P, Q> Pair<P, Q> cast(Pair<?, ?> pair, Class<P> pClass, Class<Q> qClass) {
if (pair.isInstance(pClass, qClass)) {
return (Pair<P, Q>) pair;
}
throw new ClassCastException();
}
}
Notes, mainly around rustiness with Java & generics:
a
and b
are immutable. makePair
static method helps you with boiler plate typing, which the diamond operator in Java 7 will make less annoying. There's some work to make this really nice re: generics, but it should be ok-ish now. (c.f. PECS)hashcode
and equals
are generated by eclipse.cast
method is ok, but doesn't seem quite right.isInstance
are necessary.The MySQL documentation you cite actually says a little bit more than you mention. It also says,
A “
'
” inside a string quoted with “'
” may be written as “''
”.
(Also, you linked to the MySQL 5.0 version of Table 8.1. Special Character Escape Sequences, and the current version is 5.6 — but the current Table 8.1. Special Character Escape Sequences looks pretty similar.)
I think the Postgres note on the backslash_quote (string)
parameter is informative:
This controls whether a quote mark can be represented by
\'
in a string literal. The preferred, SQL-standard way to represent a quote mark is by doubling it (''
) but PostgreSQL has historically also accepted\'
. However, use of\'
creates security risks...
That says to me that using a doubled single-quote character is a better overall and long-term choice than using a backslash to escape the single-quote.
Now if you also want to add choice of language, choice of SQL database and its non-standard quirks, and choice of query framework to the equation, then you might end up with a different choice. You don't give much information about your constraints.
So this function gets rid of most of a specified listener type on an element:
function removeListenersFromElement(element, listenerType){
const listeners = getEventListeners(element)[listenerType];
let l = listeners.length;
for(let i = l-1; i >=0; i--){
removeEventListener(listenerType, listeners[i].listener);
}
}
There have been a few rare exceptions where one can't be removed for some reason.
iframe is also vulnerable to Cross Frame Scripting:
NSString * formattedname;
NSString * firstname;
NSString * middlename;
NSString * lastname;
firstname = @"My First Name";
middlename = @"My Middle Name";
lastname = @"My Last Name";
formattedname = [NSString stringWithFormat:@"My Full Name: %@ %@ %@", firstname, middlename, lastname];
NSLog(@"\n\nHere is the Formatted Name:\n%@\n\n", formattedname);
/*
Result:
Here is the Formatted Name:
My Full Name: My First Name My Middle Name My Last Name
*/
We can add an extension to create an empty list
public static IEnumerable<T> Nullable<T>(this IEnumerable<T> obj)
{
if (obj == null)
return new List<T>();
else
return obj;
}
And use like this
foreach (model in models.Nullable())
{
....
}
I ended up with the following function ...
function HasNoteProperty(
[object]$testObject,
[string]$propertyName
)
{
$members = Get-Member -InputObject $testObject
if ($members -ne $null -and $members.count -gt 0)
{
foreach($member in $members)
{
if ( ($member.MemberType -eq "NoteProperty" ) -and `
($member.Name -eq $propertyName) )
{
return $true
}
}
return $false
}
else
{
return $false;
}
}
Suppose you want to check a boolean. If true, do something. Else, do something else. You can write:
if(condition==true){
}
else{ //else means this checks for the opposite of what you checked at if
}
instead of that, you can do it simply like:
if(condition){ //this will check if condition is true
}
else{
}
Inversely. If you were to do something if condition was false and do something else if condition was true. Then you would write:
if(condition!=true){ //if(condition=false)
}
else{
}
But following the simple path. We do:
if(!condition){ //it reads out as: if condition is not true. Which means if condition is false right?
}
else{
}
Think about it. You'll get it in no time.
For someone who needs quick reference of C# Escape Sequences that can be used in string
literals:
\t Horizontal tab (ASCII code value: 9)
\n Line feed (ASCII code value: 10)
\r Carriage return (ASCII code value: 13)
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\x12 ASCII character in hexadecimal notation (e.g. for 0x12)
\x1234 Unicode character in hexadecimal notation (e.g. for 0x1234)
It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline
which gets adjusted to current OS settings. With .Net Core it gets really important.
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'
Referring to the article https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4
So the mechanics behind change detection actually works in a way that both change detection and verification digests are performed synchronously. That means, if we update properties asynchronously the values will not be updated when the verification loop is running and we will not get ExpressionChanged...
error. The reason we get this error is, during the verification process, Angular sees different values then what it recorded during change detection phase. So to avoid that....
1) Use changeDetectorRef
2) use setTimeOut. This will execute your code in another VM as a macro-task. Angular will not see these changes during verification process and you will not get that error.
setTimeout(() => {
this.isLoading = true;
});
3) If you really want to execute your code on same VM use like
Promise.resolve(null).then(() => this.isLoading = true);
This will create a micro-task. The micro-task queue is processed after the current synchronous code has finished executing hence the update to the property will happen after the verification step.
On my quest for the truth I discovered that there are actually very few "acceptable" reasons to use a Singleton.
One reason that tends to come up over and over again on the internets is that of a "logging" class (which you mentioned). In this case, a Singleton can be used instead of a single instance of a class because a logging class usually needs to be used over and over again ad nauseam by every class in a project. If every class uses this logging class, dependency injection becomes cumbersome.
Logging is a specific example of an "acceptable" Singleton because it doesn't affect the execution of your code. Disable logging, code execution remains the same. Enable it, same same. Misko puts it in the following way in Root Cause of Singletons, "The information here flows one way: From your application into the logger. Even though loggers are global state, since no information flows from loggers into your application, loggers are acceptable."
I'm sure there are other valid reasons as well. Alex Miller, in "Patterns I Hate", talks of service locators and client side UI's also being possibly "acceptable" choices.
Read more at Singleton I love you, but you're bringing me down.
Which particular version of Ubuntu is this and is this Ubuntu Server Edition?
Recent Ubuntu Server Editions (such as 10.04) ship with AppArmor and MySQL's profile might be in enforcing mode by default. You can check this by executing sudo aa-status
like so:
# sudo aa-status
5 profiles are loaded.
5 profiles are in enforce mode.
/usr/lib/connman/scripts/dhclient-script
/sbin/dhclient3
/usr/sbin/tcpdump
/usr/lib/NetworkManager/nm-dhcp-client.action
/usr/sbin/mysqld
0 profiles are in complain mode.
1 processes have profiles defined.
1 processes are in enforce mode :
/usr/sbin/mysqld (1089)
0 processes are in complain mode.
If mysqld is included in enforce mode, then it is the one probably denying the write. Entries would also be written in /var/log/messages
when AppArmor blocks the writes/accesses. What you can do is edit /etc/apparmor.d/usr.sbin.mysqld
and add /data/
and /data/*
near the bottom like so:
...
/usr/sbin/mysqld {
...
/var/log/mysql/ r,
/var/log/mysql/* rw,
/var/run/mysqld/mysqld.pid w,
/var/run/mysqld/mysqld.sock w,
**/data/ r,
/data/* rw,**
}
And then make AppArmor reload the profiles.
# sudo /etc/init.d/apparmor reload
WARNING: the change above will allow MySQL to read and write to the /data directory. We hope you've already considered the security implications of this.
An inline-block covers the whole line (from left to right), so a margin left and/or right won't work here. What you need is a block, a block has borders on the left and the right so can be influenced by margins.
This is how it works for me:
#content {
display: block;
margin: 0 auto;
}
Here's the trick I found that works better than MagicTextView's stroke IMO
@Override
protected void onDraw(Canvas pCanvas) {
int textColor = getTextColors().getDefaultColor();
setTextColor(mOutlineColor); // your stroke's color
getPaint().setStrokeWidth(10);
getPaint().setStyle(Paint.Style.STROKE);
super.onDraw(pCanvas);
setTextColor(textColor);
getPaint().setStrokeWidth(0);
getPaint().setStyle(Paint.Style.FILL);
super.onDraw(pCanvas);
}
Ok, here is the JS code:
var data = JSON.parse('{"c":{"a":{"name":"cable - black","value":2}}}')
for (var event in data) {
var dataCopy = data[event];
for (data in dataCopy) {
var mainData = dataCopy[data];
for (key in mainData) {
if (key.match(/name|value/)) {
alert('key : ' + key + ':: value : ' + mainData[key])
}
}
}
}?
I've been asking myself related questions over and over again, then got lost in formal languages... but just to help you out a little I'd like to share some findings:
I recommend to give a look at advanced CMS
Typo3
for PHP
(I know there is a lot of stuff but thats the one I think is most mature)
Plone
in Python
If you find out that the web in 2013 should work different then, start from scratch. That would mean to put together a team of highly skilled/experienced people to build a new CMS. May be you'd like to give a look at polymer for that purpose.
If it comes to coding and multilingual websites / native language support, I think every programmer should have a clue about unicode. If you don't know unicode you'll most certainly mess up your data. Do not go with the thousands of ISO codes. They'll only save you some memory. But you can do literally everything with UTF-8 even store chinese chars. But for that you'd need to store either 2 or 4 byte chars that makes it basically a utf-16 or utf-32.
If it's about URL encoding, again there you shouldn't mix encodings and be aware that at least for the domainname there are rules defined by different lobbies that provide applications like a browser. e.g. a Domain could be very similar like:
?ankofamerica.com or bankofamerica.com samesamebutdifferent ;)
Of course you need the filesystem to work with all encodings. Another plus for unicode using utf-8 filesystem.
If its about translations, think about the structure of documents. e.g. a book or an article. You have the docbook
specifications to understand about those structures. But in HTML its just about content blocks. So you'd like to have a translation on that level, also on webpage level or domain level.
So if a block doesn't exist its just not there, if a webpage doesn't exist you'll get redirected to the upper navigation level. If a domain should be completely different in navigation structure, then.. its a complete different structure to manage.
This can already be done with Typo3.
If its about frameworks, the most mature ones I know, to do the general stuff like MVC(buzzword I really hate it! Like "performance" If you want to sell something, use the word performance and featurerich and you sell... what the hell) is Zend
. It has proven to be a good thing to bring standards to php chaos coders. But, typo3 also has a Framework besides the CMS. Recently it has been redeveloped and is called flow3 now. The frameworks of course cover database abstraction, templating and concepts for caching, but have individual strengths.
If its about caching... that can be awefully complicated / multilayered. In PHP you'll think about accellerator, opcode, but also html, httpd, mysql, xml, css, js ... any kinds of caches. Of course some parts should be cached and dynamic parts like blog answers shouldn't. Some should be requested over AJAX with generated urls. JSON, hashbangs etc.
Then, you'd like to have any little component on your website to be accessed or managed only by certain users, so conceptually that plays a big role.
Also you'd like to make statistics, maybe have distributed system / a facebook of facebooks etc. any software to be built on top of your over the top cms ... so you need different type of databases inmemory, bigdata, xml, whatsoever.
well, I think thats enough for now. If you haven't heard of either typo3 / plone or mentioned frameworks, you have enough to study. On that path you'll find a lot of solutions for questions you haven't asked yet.
If then you think, lets make a new CMS because its 2013 and php is about to die anyway, then you r welcome to join any other group of developers hopefully not getting lost.
Good luck!
And btw. how about people will not having any websites anymore in the future? and we'll all be on google+? I hope developers become a little more creative and do something usefull(to not be assimilated by the borgle)
//// Edit /// Just a little thought for your existing application:
If you have a php mysql CMS and you wanted to embed multilang support. you could either use your table with an aditional column for any language or insert the translation with an object id and a language id in the same table or create an identical table for any language and insert objects there, then make a select union if you want to have them all displayed. For the database use utf8 general ci and of course in the front/backend use utf8 text/encoding. I have used url path segments for urls in the way you already explaned like
domain.org/en/about you can map the lang ID to your content table. anyway you need to have a map of parameters for your urls so you'd like to define a parameter to be mapped from a pathsegment in your URL that would be e.g.
domain.org/en/about/employees/IT/administrators/
lookup configuration
pageid| url
1 | /about/employees/../..
1 | /../about/employees../../
map parameters to url pathsegment ""
$parameterlist[lang] = array(0=>"nl",1=>"en"); // default nl if 0
$parameterlist[branch] = array(1=>"IT",2=>"DESIGN"); // default nl if 0
$parameterlist[employertype] = array(1=>"admin",1=>"engineer"); //could be a sql result
$websiteconfig[]=$userwhatever;
$websiteconfig[]=$parameterlist;
$someparameterlist[] = array("branch"=>$someid);
$someparameterlist[] = array("employertype"=>$someid);
function getURL($someparameterlist){
// todo foreach someparameter lookup pathsegment
return path;
}
per say, thats been covered already in upper post.
And to not forget, you'd need to "rewrite" the url to your generating php file that would in most cases be index.php
With props to Rick (second comment down in the blog post mentioned), here's the MSDN article on httpOnlyCookies.
Bottom line is that you just add the following section in your system.web section in your web.config:
<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />
Just wanted to add a bit of info, since I haven't seen it posted yet.
You'll very often see code in C headers like so:
#ifdef __cplusplus
extern "C" {
#endif
// all of your legacy C code here
#ifdef __cplusplus
}
#endif
What this accomplishes is that it allows you to use that C header file with your C++ code, because the macro "__cplusplus" will be defined. But you can also still use it with your legacy C code, where the macro is NOT defined, so it won't see the uniquely C++ construct.
Although, I have also seen C++ code such as:
extern "C" {
#include "legacy_C_header.h"
}
which I imagine accomplishes much the same thing.
Not sure which way is better, but I have seen both.
The below code provides the results which replaces NULL to zero in the output.
Table creation and data insertion:
create table test_table
(
date nvarchar(10),
category char(3),
amount money
)
insert into test_table values ('1/1/2012','ABC',1000.00)
insert into test_table values ('2/1/2012','DEF',500.00)
insert into test_table values ('2/1/2012','GHI',800.00)
insert into test_table values ('2/10/2012','DEF',700.00)
insert into test_table values ('3/1/2012','ABC',1100.00)
Query to generate the exact results which also replaces NULL with zeros:
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
@PivotColumnNames AS NVARCHAR(MAX),
@PivotSelectColumnNames AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat
--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(category) + ', 0) AS '
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT date, ' + @PivotSelectColumnNames + '
FROM test_table
pivot(sum(amount) for category in (' + @PivotColumnNames + ')) as pvt';
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
OUTPUT :
ieshims.dll
is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as CreateProcess
) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. wer.dll
is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.
I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway.
You can also do it on the worksheet level captured in the worksheet's change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect...
Private Sub Worksheet_Change(ByVal Target As Range)
'set your criteria here
If Target.Column = 1 Then
'must disable events if you change the sheet as it will
'continually trigger the change event
Application.EnableEvents = False
Application.Undo
Application.EnableEvents = True
MsgBox "You cannot do that!"
End If
End Sub
Here's a rewrite of the accepted answer that ideally clarifies the advantages/risks of possible approaches:
You're trying to cherry pick fd9f578, which was a merge with two parents.
Instead of cherry-picking a merge, the simplest thing is to cherry pick the commit(s) you actually want from each branch in the merge.
Since you've already merged, it's likely all your desired commits are in your list. Cherry-pick them directly and you don't need to mess with the merge commit.
The way a cherry-pick works is by taking the diff that a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying the changeset to your current branch.
If a commit has two or more parents, as is the case with a merge, that commit also represents two or more diffs. The error occurs because of the uncertainty over which diff should apply.
If you determine you need to include the merge vs cherry-picking the related commits, you have two options:
(More complicated and obscure; also discards history) you can indicate which parent should apply.
Use the -m
option to do so. For example, git cherry-pick -m 1 fd9f578
will use the first parent listed in the merge as the base.
Also consider that when you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m
into that one commit. You lose all their history, and glom together all their diffs. Your call.
(Simpler and more familiar; preserves history) you can use git merge
instead of git cherry-pick
.
git merge
, it will attempt to apply all commits that exist on the branch you are merging, and list them individually in your git log.The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
This is not your answer and this is an alternate way to process the form submission
$('.signinform').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'index.php/user/signin', // target element(s) to be updated with server response
dataType:'json',
success : function(response){ console.log(response); alert(response)}
});
});
Try Demo Here
var list ={}; var count= Object.keys(list).length;
Assuming a and b are the dictionaries you want to merge:
c = {key: value for (key, value) in (a.items() + b.items())}
To convert your string to python dictionary you use the following:
import json
my_dict = json.loads(json_str)
Update: full code using strings:
# test cases for jsonStringA and jsonStringB according to your data input
jsonStringA = '{"error_1395946244342":"valueA","error_1395952003":"valueB"}'
jsonStringB = '{"error_%d":"Error Occured on machine %s in datacenter %s on the %s of process %s"}' % (timestamp_number, host_info, local_dc, step, c)
# now we have two json STRINGS
import json
dictA = json.loads(jsonStringA)
dictB = json.loads(jsonStringB)
merged_dict = {key: value for (key, value) in (dictA.items() + dictB.items())}
# string dump of the merged dict
jsonString_merged = json.dumps(merged_dict)
But I have to say that in general what you are trying to do is not the best practice. Please read a bit on python dictionaries.
Alternative solution:
jsonStringA = get_my_value_as_string_from_somewhere()
errors_dict = json.loads(jsonStringA)
new_error_str = "Error Ocurred in datacenter %s blah for step %s blah" % (datacenter, step)
new_error_key = "error_%d" % (timestamp_number)
errors_dict[new_error_key] = new_error_str
# and if I want to export it somewhere I use the following
write_my_dict_to_a_file_as_string(json.dumps(errors_dict))
And actually you can avoid all these if you just use an array to hold all your errors.
// 2015/09/27 15:07:53
System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 15:07:53
System.out.println( new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 09/28/2015
System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()));
// 20150928_161823
System.out.println( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) );
// Mon Sep 28 16:24:28 CEST 2015
System.out.println( Calendar.getInstance().getTime() );
// Mon Sep 28 16:24:51 CEST 2015
System.out.println( new Date(System.currentTimeMillis()) );
// Mon Sep 28
System.out.println( new Date().toString().substring(0, 10) );
// 2015-09-28
System.out.println( new java.sql.Date(System.currentTimeMillis()) );
// 14:32:26
Date d = new Date();
System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 );
// 2015-09-28 17:12:35.584
System.out.println( new Timestamp(System.currentTimeMillis()) );
// Java 8
// 2015-09-28T16:16:23.308+02:00[Europe/Belgrade]
System.out.println( ZonedDateTime.now() );
// Mon, 28 Sep 2015 16:16:23 +0200
System.out.println( ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) );
// 2015-09-28
System.out.println( LocalDate.now(ZoneId.of("Europe/Paris")) ); // rest zones id in ZoneId class
// 16
System.out.println( LocalTime.now().getHour() );
// 2015-09-28T16:16:23.315
System.out.println( LocalDateTime.now() );
I think you can use asset('/')
I've created a component that solves this problem:
Here's a solution for those that may still be struggling. You want to add a mouseover
event on the 'parent' element of the child element(s) you want detected. The below code shows you how to go about it.
const wrapper = document.getElementById('wrapper') //parent element
const position = document.getElementById("displaySelection")
wrapper.addEventListener('mousemove', function(e) {
let elementPointed = document.elementFromPoint(e.clientX, e.clientY)
console.log(elementPointed)
});
You can build DFA using simple modular arithmetics.
We can interpret w
which is a string of k-ary numbers using a following rule
V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])
V[|w|]
is a number that w
is representing. If modify this rule to find w mod N
, the rule becomes this.
V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N
and each V[i]
is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.
See an example.
k = 2, N = 5
| V | (V*2 + 0) mod 5 | (V*2 + 1) mod 5 |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |
k = 3, N = 5
| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |
Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.
The header just denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. That's what HTTP headers are for, they tell the recipient what kind of content they're (supposedly) dealing with.
Content-type: application/json; charset=utf-8
designates the content to be in JSON format, encoded in the UTF-8 character encoding. Designating the encoding is somewhat redundant for JSON, since the default (only?) encoding for JSON is UTF-8. So in this case the receiving server apparently is happy knowing that it's dealing with JSON and assumes that the encoding is UTF-8 by default, that's why it works with or without the header.
Does this encoding limit the characters that can be in the message body?
No. You can send anything you want in the header and the body. But, if the two don't match, you may get wrong results. If you specify in the header that the content is UTF-8 encoded but you're actually sending Latin1 encoded content, the receiver may produce garbage data, trying to interpret Latin1 encoded data as UTF-8. If of course you specify that you're sending Latin1 encoded data and you're actually doing so, then yes, you're limited to the 256 characters you can encode in Latin1.
Language independent version.
@Echo Off
Set ServiceName=Jenkins
SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
echo %ServiceName% not running
echo Start %ServiceName%
Net start "%ServiceName%">nul||(
Echo "%ServiceName%" wont start
exit /b 1
)
echo "%ServiceName%" started
exit /b 0
)||(
echo "%ServiceName%" working
exit /b 0
)
I just used getLocaleString() function for my application. It should adapt the timeformat common to the locale, so no +0200 etc. Ofcourse, there will be less possibility for controlling the width of your string then.
var str = (new Date(1400167800)).toLocaleString();
Here's a list of API links to get your stats:
Facebook: https://api.facebook.com/method/links.getStats?urls=%%URL%%&format=json
Reddit:http://buttons.reddit.com/button_info.json?url=%%URL%%
LinkedIn: http://www.linkedin.com/countserv/count/share?url=%%URL%%&format=json
Digg: http://widgets.digg.com/buttons/count?url=%%URL%%
Delicious: http://feeds.delicious.com/v2/json/urlinfo/data?url=%%URL%%
StumbleUpon: http://www.stumbleupon.com/services/1.01/badge.getinfo?url=%%URL%%
Pinterest: http://widgets.pinterest.com/v1/urls/count.json?source=6&url=%%URL%%
Edit: Removed the Twitter endpoint, since that one has been deprecated.
Edit: Facebook REST API is deprecated
The user Klaro suggested to restore the old visibility classes, which is a good idea. Unfortunately, their solution did not work in my project.
I think that it is a better idea to restore the old mixin of bootstrap, because it is covering all breakpoints which can be individually defined by the user.
Here is the code:
// Restore Bootstrap 3 "hidden" utility classes.
@each $bp in map-keys($grid-breakpoints) {
.hidden-#{$bp}-up {
@include media-breakpoint-up($bp) {
display: none !important;
}
}
.hidden-#{$bp}-down {
@include media-breakpoint-down($bp) {
display: none !important;
}
}
.hidden-#{$bp}-only{
@include media-breakpoint-only($bp){
display:none !important;
}
}
}
In my case, I have inserted this part in a _custom.scss
file which is included at this point in the bootstrap.scss
:
/*!
* Bootstrap v4.0.0-beta (https://getbootstrap.com)
* Copyright 2011-2017 The Bootstrap Authors
* Copyright 2011-2017 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
@import "functions";
@import "variables";
@import "mixins";
@import "custom"; // <-- my custom file for overwriting default vars and adding the snippet from above
@import "print";
@import "reboot";
[..]