See my answer in this thread.
intent.putExtra("Some string",very_large_obj_for_binder_buffer);
You are exceeding the binder transaction buffer by transferring large element(s) from one activity to another activity.
Yet another case where this error will occur, if you're service is defined in a separate javascript file, make sure you reference it! Yes, I know, rookie mistake.
This worked for me in Jupyter nOtebook /Mac Platform /Python 3 :
import sys
!{sys.executable} -m pip install -r requirements.txt
to add to John's answer:
what you want to pass to the shuffle
function is a deck of cards from the class deckOfCards
that you've declared in main; however, the deck of cards or vector<Card> deck
that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:
class deckOfCards
{
private:
vector<Card> deck;
public:
deckOfCards();
static int count;
static int next;
void shuffle(vector<Card>& deck);
Card dealCard();
bool moreCards();
vector<Card>& getDeck() { //GETTER
return deck;
}
};
this will in turn allow you to call your shuffle function from main like this:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck
however, you have more problems, specifically when calling cout
. first, you're calling the dealCard
function wrongly; as dealCard
is a memeber function of a class, you should be calling it like this cardDeck.dealCard();
instead of this dealCard(cardDeck);
.
now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card
by using the following instruction:
cout << cardDeck.dealCard();// deal the cards in the deck
yet, the cout
doesn't know how to print it, as it's not a standard type. this means you should overload your <<
operator to print whatever you want it to print when calling with a Card
type.
I ended up implementing my own adapter to wrap any other adapter and provide methods to add header and footer views.
Created a gist here: HeaderViewRecyclerAdapter.java
The main feature I wanted was a similar interface to a ListView, so I wanted to be able to inflate the views in my Fragment and add them to the RecyclerView
in onCreateView
. This is done by creating a HeaderViewRecyclerAdapter
passing the adapter to be wrapped, and calling addHeaderView
and addFooterView
passing your inflated views. Then set the HeaderViewRecyclerAdapter
instance as the adapter on the RecyclerView
.
An extra requirement was that I needed to be able to easily swap out adapters while keeping the headers and footers, I didn't want to have multiple adapters with multiple instances of these headers and footers. So you can call setAdapter
to change the wrapped adapter leaving the headers and footers intact, with the RecyclerView
being notified of the change.
Just to extend the @Joseph's answer:
After applying these commands your global .gitconfig
file will have the following lines (to speed up the process you can just copy them in the file):
[merge]
tool = kdiff3
[mergetool "kdiff3"]
path = C:/Program Files/KDiff3/kdiff3.exe
trustExitCode = false
[diff]
guitool = kdiff3
[difftool "kdiff3"]
path = C:/Program Files/KDiff3/kdiff3.exe
trustExitCode = false
Next time, from the Take Offline dialog, remember to check the 'Drop All Active Connections' checkbox. I was also on SQL_EXPRESS on local machine with no connections, but this slowdown happened for me unless I checked that checkbox.
Tried everything else then I googled the error I was getting about not being able to find nuget.exe... I thought, well I dont really need that... Turns out I did. Solution I found: Right click on the Solution and click Enable NuGet Package Restore
Private Sub main()
'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=Sheet1!A1:A6"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
You can use git log -L to view the evolution of a range of lines.
For example :
git log -L 15,23:filename.txt
means "trace the evolution of lines 15 to 23 in the file named filename.txt".
To copy an already existing index.html
file into the dist
directory you can simply use the HtmlWebpackPlugin by specifying the source index.html
as a template.
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// ...
plugins: [
new HtmlWebpackPlugin({
template: './path/to/index.html',
})
],
// ...
};
The created dist/index.html
file will be basically the same as your source file with the difference that bundled resources like .js files are injected with <script>
tags by webpack. Minification and further options can be configured and are documented on github.
You can use array.slice(0,1) // First index is removed and array is returned.
You can put your values in ODCIVARCHAR2LIST and then join it as a regular table.
select tabl1.* FROM tabl1 LEFT JOIN
(select column_value txt from table(sys.ODCIVARCHAR2LIST
('%val1%','%val2%','%val3%')
)) Vals ON tabl1.column LIKE Vals.txt WHERE Vals.txt IS NOT NULL
If you are in Visual Code, Ctrl + Click on AppBar function.
Widget demoPage() {
AppBar appBar = AppBar(
title: Text('Demo'),
);
return Scaffold(
appBar: appBar,
body: /*
page body
*/,
);
}
And edit this piece.
app_bar.dart will open and you can find
preferredSize = new Size.fromHeight(kToolbarHeight + (bottom?.preferredSize?.height ?? 0.0)),
Difference of height!
Here is an interesting case: method receieves generic collection and returns generic collection of same base type. For example:
Collection<? extends Assertion> map(Collection<? extends Assertion> assertions);
This method can be mocked with combination of Mockito anyCollectionOf matcher and the Answer.
when(mockedObject.map(anyCollectionOf(Assertion.class))).thenAnswer(
new Answer<Collection<Assertion>>() {
@Override
public Collection<Assertion> answer(InvocationOnMock invocation) throws Throwable {
return new ArrayList<Assertion>();
}
});
I agree httpclient is something of a standard - but I guess you are looking for options so...
Restlet provides a http client specially designed for interactong with Restful web services.
Example code:
Client client = new Client(Protocol.HTTP);
Request r = new Request();
r.setResourceRef("http://127.0.0.1:8182/sample");
r.setMethod(Method.GET);
r.getClientInfo().getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_XML));
client.handle(r).getEntity().write(System.out);
See http://www.restlet.org/ for more details
I'd probably do something like that :
[int]::Parse("35")
But I'm not really a Powershell guy. It uses the static Parse method from System.Int32. It should throw an exception if the string can't be parsed.
109 - mon dd yyyy (In SQL conversion)
The required format is April 1 2009
so
SELECT DATENAME(MONTH, GETDATE()) + RIGHT(CONVERT(VARCHAR(12), GETDATE(), 109), 9)
Result is:
Contrary to what most people here are suggesting, I'd recommend you do use a plugin if you want to animate the move. Just animating scrollTop is not enough for a smooth user experience. See my answer here for the reasoning.
I have tried a number of plugins over the years, but eventually written one myself. You might want to give it a spin: jQuery.scrollable. Using that, the scroll action becomes
$container.scrollTo( targetPosition );
But that's not all. We need to fix the target position, too. The calculation you see in other answers,
$target.offset().top - $container.offset().top + $container.scrollTop()
mostly works but is not entirely correct. It doesn't handle the border of the scroll container properly. The target element is scrolled upwards too far, by the size of the border. Here is a demo.
Hence, a better way to calculate the target position is
var target = $target[0],
container = $container[0];
targetPosition = $container.scrollTop() + target.getBoundingClientRect().top - container.getBoundingClientRect().top - container.clientTop;
Again, have a look at the demo to see it in action.
For a function which returns the target position and works for both window and non-window scroll containers, feel free to use this gist. The comments in there explain how the position is calculated.
In the beginning, I have said it would be best to use a plugin for animated scrolling. You don't need a plugin, however, if you want to jump to the target without a transition. See the answer by @James for that, but make sure you calculate the target position correctly if there is a border around the container.
I believe the admin button will open the default configuration always. It simply contains a link to localhost/xampp
and it doesn't read the server configuration.
If you change the default settings, you know what you changed and you can enter the URL directly in the browser.
RazorSQL vote here too. It is not free, but it's not expensive ($70 for a perpetual license and 1 year of free upgrades).
If you use it for work, it will pay for itself quickly. I was jumping between MySQL GUI tools, SQL Server and Informix DBAccess, some of them through VMs because I use a Mac for development. Having a single tool to connect to any database out there is pretty nice. It is also highly customizable, and very reliable.
You can use sudo ip link delete
to remove the interface.
user2540984, as well as many others have pointed out that you can try increasing your timeout settings. I myself faced a similar issue to this one and tried to change my timeout settings in the /etc/nginx/nginx.conf file, as almost everyone in these threads suggest. This, however, did not help me a single bit; there was no apparent change in NGINX' timeout settings. After many hours of searching, I finally managed to solve my issue.
The solution lies in this forum thread, and what it says is that you should put your timeout settings in /etc/nginx/conf.d/timeout.conf (and if this file doesn't exist, you should create it). I used the same settings as suggested in the thread:
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
This might not be the solution to your particular problem, but if anyone else notices that the timeout changes in /etc/nginx/nginx.conf don't do anything, I hope this answer helps!
In order to get the value of the selected item you can do the following:
this.options[this.selectedIndex].text
Here the different options
of the select are accessed, and the SelectedIndex
is used to choose the selected one, then its text
is being accessed.
Read more about the select DOM here.
Needed this answer myself and from the link provided by David Moye, decided on this and thought it might be of use to others with the same question:
CREATE PROCEDURE ...
AS
BEGIN
BEGIN TRANSACTION
-- lock table "a" till end of transaction
SELECT ...
FROM a
WITH (TABLOCK, HOLDLOCK)
WHERE ...
-- do some other stuff (including inserting/updating table "a")
-- release lock
COMMIT TRANSACTION
END
To center only the specific child :
.parent {_x000D_
height: 100px;_x000D_
background-color: gray;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.child {_x000D_
background-color: white;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
width: 20px;_x000D_
height:20px;_x000D_
margin: auto;_x000D_
_x000D_
}
_x000D_
<div class="parent">_x000D_
<span class="child">hi</span>_x000D_
</div>
_x000D_
OR, you can use flex too, but that would center all children
.parent {_x000D_
height: 100px;_x000D_
background-color: gray;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.child {_x000D_
background-color: white; _x000D_
}
_x000D_
<div class="parent">_x000D_
<span class="child">hi</span>_x000D_
</div>
_x000D_
You can simply call filter
multiple times:
query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
filter(User.lastname.like(searchVar2))
Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic
.
Now, if you were to use an ExpandoObject and reference it through a dynamic
variable, you could add or remove fields on the fly.
edit
Sure you can: just cast it to IDictionary<string, object>
. Then you can use the indexer.
You use the same casting technique to iterate over the fields:
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
foreach (var property in (IDictionary<string, object>)employee)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33
The above code and more can be found by clicking on that link.
if the log4j.xml file is not in the project,and you are using tomcat, try going to tomcat instance and search for log4j. Try changing the consoleAppender level to debug and redeploy the application in tomcat. That might help.
leading 0
means this is octal constant, not the decimal one. and you need an octal to change file mode.
permissions are a bit mask, for example, rwxrwx---
is 111111000
in binary, and it's very easy to group bits by 3 to convert to the octal, than calculate the decimal representation.
0644
(octal) is 0.110.100.100
in binary (i've added dots for readability), or, as you may calculate, 420
in decimal.
In my case,in Chrome DevTools settings, just set "Disable cache (while DevTools is open)" doesn't work, it needs to check "Enable CSS source maps" and "Auto-reload generated CSS",which are listed in source group, to make this cache issue go away.
Yeah Regex is cool, but there are other alternative.
This allows you to edit multiple lines at once. Now you can add *Quotes (") or anything * at start and end of each lines.
You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies Wn=[low, high]
(expressed as the fraction of the Nyquist frequency, which is half the sampling frequency) and the band type btype="band"
.
Here's a script that defines a couple convenience functions for working with a Butterworth bandpass filter. When run as a script, it makes two plots. One shows the frequency response at several filter orders for the same sampling rate and cutoff frequencies. The other plot demonstrates the effect of the filter (with order=6) on a sample time series.
from scipy.signal import butter, lfilter
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = lfilter(b, a, data)
return y
if __name__ == "__main__":
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import freqz
# Sample rate and desired cutoff frequencies (in Hz).
fs = 5000.0
lowcut = 500.0
highcut = 1250.0
# Plot the frequency response for a few different orders.
plt.figure(1)
plt.clf()
for order in [3, 6, 9]:
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)
plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)
plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
'--', label='sqrt(0.5)')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain')
plt.grid(True)
plt.legend(loc='best')
# Filter a noisy signal.
T = 0.05
nsamples = T * fs
t = np.linspace(0, T, nsamples, endpoint=False)
a = 0.02
f0 = 600.0
x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
x += a * np.cos(2 * np.pi * f0 * t + .11)
x += 0.03 * np.cos(2 * np.pi * 2000 * t)
plt.figure(2)
plt.clf()
plt.plot(t, x, label='Noisy signal')
y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
plt.xlabel('time (seconds)')
plt.hlines([-a, a], 0, T, linestyles='--')
plt.grid(True)
plt.axis('tight')
plt.legend(loc='upper left')
plt.show()
Here are the plots that are generated by this script:
It seems as of now, the only solution is still to install SublimeREPL.
To extend on Raghav's answer, it can be quite annoying to have to go into the Tools->SublimeREPL->Python->Run command every time you want to run a script with input, so I devised a quick key binding that may be handy:
To enable it, go to Preferences->Key Bindings - User, and copy this in there:
[
{"keys":["ctrl+r"] ,
"caption": "SublimeREPL: Python - RUN current file",
"command": "run_existing_window_command",
"args":
{
"id": "repl_python_run",
"file": "config/Python/Main.sublime-menu"
}
},
]
Naturally, you would just have to change the "keys" argument to change the shortcut to whatever you'd like.
Auto reload with target of your choice. In this case target is _self
set to every 5 minutes.
300000 milliseconds = 300 seconds = 5 minutes
as 60000 milliseconds = 60 seconds = 1 minute.
This is how you do it:
<script type="text/javascript">
function load()
{
setTimeout("window.open('http://YourPage.com', '_self');", 300000);
}
</script>
<body onload="load()">
Or this if it is the same page to reload itself:
<script type="text/javascript">
function load()
{
setTimeout("window.open(self.location, '_self');", 300000);
}
</script>
<body onload="load()">
In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().
When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that
In response to the original question, I typically add the config file in my test project as a link; you can then use the DeploymentItem attribute to addit to the Out folder of the test run.
[TestClass]
[DeploymentItem("MyProject.Cache.dll.config")]
public class CacheTest
{
.
.
.
.
}
In response to the comments that Assemblies can't be project specific, they can and it provides great flexibility esp. when working with IOC frameworks.
You can achieve your goal by using php date() & explode() functions:
$date = date("2068-06-15");
$date_arr = explode("-", $date);
$yr = $date_arr[0];
echo $yr;
That is it. Happy coding :)
Use below command on UNIX terminal :
java -XshowSettings
This will display all java properties and system settings.
In this look for java.io.tmpdir
value.
u just used attribute
android:background="#ColorCode" for colors
if your image save in drawable folder then used :-
android:background="@drawable/ImageName" for image setting
Try changing the app/config/email.php
smtp
to mail
Let's first see how to detect and save the value of a single cell of interest. Suppose Worksheets(1).Range("B1")
is your cell of interest. In a normal module, use this:
Option Explicit
Public StorageArray(0 to 1) As Variant
' Declare a module-level variable, which will not lose its scope as
' long as the codes are running, thus performing as a storage place.
' This is a one-dimensional array.
' The first element stores the "old value", and
' the second element stores the "new value"
Sub SaveToStorageArray()
' ACTION
StorageArray(0) = StorageArray(1)
' Transfer the previous new value to the "old value"
StorageArray(1) = Worksheets(1).Range("B1").value
' Store the latest new value in Range("B1") to the "new value"
' OUTPUT DEMONSTRATION (Optional)
' Results are presented in the Immediate Window.
Debug.Print "Old value:" & vbTab & StorageArray(0)
Debug.Print "New value:" & vbTab & StorageArray(1) & vbCrLf
End Sub
Then in the module of Worksheets(1):
Option Explicit
Private HasBeenActivatedBefore as Boolean
' Boolean variables have the default value of False.
' This is a module-level variable, which will not lose its scope as
' long as the codes are running.
Private Sub Worksheet_Activate()
If HasBeenActivatedBefore = False then
' If the Worksheet has not been activated before, initialize the
' StorageArray as follows.
StorageArray(1) = Me.Range("B1")
' When the Worksheets(1) is activated, store the current value
' of Range("B1") to the "new value", before the
' Worksheet_Change event occurs.
HasBeenActivatedBefore = True
' Set this parameter to True, so that the contents
' of this if block won't be evaluated again. Therefore,
' the initialization process above will only be executed
' once.
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("B1")) Is Nothing then
Call SaveToStorageArray
' Only perform the transfer of old and new values when
' the cell of interest is being changed.
End If
End Sub
This will capture the change of the Worksheets(1).Range("B1")
, whether the change is due to the user actively selecting that cell on the Worksheet and changing the value, or due to other VBA codes that change the value of Worksheets(1).Range("B1")
.
Since we have declared the variable StorageArray
as public, you can reference its latest value in other modules in the same VBA project.
To expand our scope to the detection and saving the values of multiple cells of interest, you need to:
StorageArray
as a two-dimensional array, with the number of rows equal to the number of cells you are monitoring.Sub SaveToStorageArray
procedure to a more general Sub SaveToStorageArray(TargetSingleCell as Range)
and change the
relevant codes.Private Sub Worksheet_Change
procedure to accommodate the monitoring of those multiple cells.Appendix: For more information on the lifetime of variables, please refer to: https://msdn.microsoft.com/en-us/library/office/gg278427.aspx
Try this piece of code, it worked for me:
$('#year').datepicker({
format: "yyyy",
viewMode: "years",
minViewMode: "years"
});
I hope it will do magic also for you.
this works for ubuntu 15.10:
sudo locale-gen "en_US.UTF-8"
sudo dpkg-reconfigure locales
In Node.js HTTP
module's documentation: http://nodejs.org/api/http.html#http_http_request_options_callback
You can either call http.get('http://eternagame.wikia.com/wiki/EteRNA_Dictionary', callback)
, the URL is then parsed with url.parse()
; or call http.get(options, callback)
, where options
is
{
host: 'eternagame.wikia.com',
port: 8080,
path: '/wiki/EteRNA_Dictionary'
}
Update
As stated in the comment by @EnchanterIO, the port
field is also a separate option; and the protocol http://
shouldn't be included in the host
field. Other answers also recommends the use of https
module if SSL is required.
CSS selector:
Use a CSS selector of img[src='images/toolbar/b_edit.gif']
This says select element(s) with img
tag with attribute src
having value of 'images/toolbar/b_edit.gif'
CSS query:
VBA:
You can apply the selector with the .querySelector
method of document
.
IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click
A "name" (Net, Host, Gateway, or Domain name) is a text string up to 24 characters drawn from the alphabet (A-Z), digits (0-9), minus sign (-), and period (.). Note that periods are only allowed when they serve to delimit components of "domain style names". (See RFC-921, "Domain Name System Implementation Schedule", for background). No blank or space characters are permitted as part of a name. No distinction is made between upper and lower case. The first character must be an alpha character. The last character must not be a minus sign or period. A host which serves as a GATEWAY should have "-GATEWAY" or "-GW" as part of its name. Hosts which do not serve as Internet gateways should not use "-GATEWAY" and "-GW" as part of their names. A host which is a TAC should have "-TAC" as the last part of its host name, if it is a DoD host. Single character names or nicknames are not allowed.
This is provided in http://support.microsoft.com/kb/149044
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseFor a secure alternative, try the Perspectives Firefox add-on
If this link doesn't work try this one: https://addons.mozilla.org/en-US/firefox/addon/perspectives/
An abstract class is a class that you can't create an object from, so it is mostly used for inheriting from.(I am not sure if you can have static methods in it)
An abstract method is a method that the child class must override, it does not have a body, is marked abstract and only abstract classes can have those methods.
kubectl describe pods <name of pod>
will give you some information including the IP
Here is an overview of the many ways that can be done, for my own reference as well as yours :) The functions return a hash of attribute names and their values.
Vanilla JS:
function getAttributes ( node ) {
var i,
attributeNodes = node.attributes,
length = attributeNodes.length,
attrs = {};
for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
return attrs;
}
Vanilla JS with Array.reduce
Works for browsers supporting ES 5.1 (2011). Requires IE9+, does not work in IE8.
function getAttributes ( node ) {
var attributeNodeArray = Array.prototype.slice.call( node.attributes );
return attributeNodeArray.reduce( function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
jQuery
This function expects a jQuery object, not a DOM element.
function getAttributes ( $node ) {
var attrs = {};
$.each( $node[0].attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
} );
return attrs;
}
Underscore
Also works for lodash.
function getAttributes ( node ) {
return _.reduce( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
lodash
Is even more concise than the Underscore version, but only works for lodash, not for Underscore. Requires IE9+, is buggy in IE8. Kudos to @AlJey for that one.
function getAttributes ( node ) {
return _.transform( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
}, {} );
}
Test page
At JS Bin, there is a live test page covering all these functions. The test includes boolean attributes (hidden
) and enumerated attributes (contenteditable=""
).
jCoverflip was just released and is very customizable.
You can also disable a specific rule/rules (rather than all) by specifying them in the enable (open) and disable (close) blocks:
/* eslint-disable no-alert, no-console */
alert('foo');
console.log('bar');
/* eslint-enable no-alert */
via @goofballMagic's link above: http://eslint.org/docs/user-guide/configuring.html#configuring-rules
Actually, none of the given answers are fully cover the request.
As the OP didn't provided a specific use case or types of numbers, I will try to cover all possible cases and permutations.
This number is usually called unsigned integer, but you can also call it a positive non-fractional number, include zero. This includes numbers like 0
, 1
and 99999
.
The Regular Expression that covers this validation is:
/^(0|[1-9]\d*)$/
This number is usually called signed integer, but you can also call it a non-fractional number. This includes numbers like 0
, 1
, 99999
, -99999
, -1
and -0
.
The Regular Expression that covers this validation is:
/^-?(0|[1-9]\d*)$/
As you probably noticed, I have also included -0
as a valid number. But, some may argue with this usage, and tell that this is not a real number (you can read more about Signed Zero here). So, if you want to exclude this number from this regex, here's what you should use instead:
/^-?(0|[1-9]\d*)(?<!-0)$/
All I have added is (?<!-0)
, which means not to include -0
before this assertion. This (?<!...)
assertion called negative lookbehind, which means that any phrase replaces the ...
should not appear before this assertion. Lookbehind has limitations, like the phrase cannot include quantifiers. That's why for some cases I'll be using Lookahead instead, which is the same, but in the opposite way.
Many regex flavors, including those used by Perl and Python, only allow fixed-length strings. You can use literal text, character escapes, Unicode escapes other than
\X
, and character classes. You cannot use quantifiers or backreferences. You can use alternation, but only if all alternatives have the same length. These flavors evaluate lookbehind by first stepping back through the subject string for as many characters as the lookbehind needs, and then attempting the regex inside the lookbehind from left to right.
You can read more bout Lookaround assertions here.
This number is usually called unsigned float or unsigned double, but you can also call it a positive fractional number, include zero. This includes numbers like 0
, 1
, 0.0
, 0.1
, 1.0
, 99999.000001
, 5.10
.
The Regular Expression that covers this validation is:
/^(0|[1-9]\d*)(\.\d+)?$/
Some may say, that numbers like .1
, .0
and .00651
(same as 0.1
, 0.0
and 0.00651
respectively) are also valid fractional numbers, and I cannot disagree with them. So here is a regex that is additionally supports this format:
/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
This number is usually called signed float or signed double, but you can also call it a fractional number. This includes numbers like 0
, 1
, 0.0
, 0.1
, 1.0
, 99999.000001
, 5.10
, -0
, -1
, -0.0
, -0.1
, -99999.000001
, 5.10
.
The Regular Expression that covers this validation is:
/^-?(0|[1-9]\d*)(\.\d+)?$/
For non -0
believers:
/^(?!-0(\.0+)?$)-?(0|[1-9]\d*)(\.\d+)?$/
For those who want to support also the invisible zero representations, like .1
, -.1
, use the following regex:
/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
The combination of non -0
believers and invisible zero believers, use this regex:
/^(?!-0?(\.0+)?$)-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
Some may want to support in their validations, numbers with a scientific character e
, which is by the way, an absolutely valid number, it is created for shortly represent a very long numbers. You can read more about Scientific Notation here. These numbers are usually looks like 1e3
(which is 1000
), 1e-3
(which is 0.001) and are fully supported by many major programming languages (e.g. JavaScript). You can test it by checking if the expression '1e3'==1000
returns true
.
I will divide the support for all the above sections, including numbers with scientific notation.
Whole positive number regex validation, supports numbers like 6e4
, 16e-10
, 0e0
but also regular numbers like 0
, 11
:
/^(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Whole positive and negative number regex validation, supports numbers like -6e4
, -16e-10
, -0e0
but also regular numbers like -0
, -11
and all the whole positive numbers above:
/^-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Whole positive and negative number regex validation for non -0
believers, same as the above, except now it forbids numbers like -0
, -0e0
, -0e5
and -0e-6
:
/^(?!-0)-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Positive number regex validation, supports also the whole numbers above, plus numbers like 0.1e3
, 56.0e-3
, 0.0e10
and 1.010e0
:
/^(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Positive number with invisible zero support regex validation, supports also the above positive numbers, in addition numbers like .1e3
, .0e0
, .0e-5
and .1e-7
:
/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
Negative and positive number regex validation, supports the positive numbers above, but also numbers like -0e3
, -0.1e0
, -56.0e-3
and -0.0e10
:
/^-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Negative and positive number regex validation fro non -0
believers, same as the above, except now it forbids numbers like -0
, -0.00000
, -0.0e0
, -0.00000e5
and -0e-6
:
/^(?!-0(\.0+)?(e|$))-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Negative and positive number with invisible zero support regex validation, supports also the above positive and negative numbers, in addition numbers like -.1e3
, -.0e0
, -.0e-5
and -.1e-7
:
/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
Negative and positive number with the combination of non -0
believers and invisible zero believers, same as the above, but forbids numbers like -.0e0
, -.0000e15
and -.0e-19
:
/^(?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
In many programming languages, string representation of hexadecimal number like 0x4F7A
may be easily cast to decimal number 20346
.
Thus, one may want to support it in his validation script.
The following Regular Expression supports only hexadecimal numbers representations:
/^0x[0-9a-f]+$/i
These final Regular Expressions, support the invisible zero numbers.
/^(-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i
/^((?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i
Hope I covered all number permutations that are supported in many programming languages.
Good luck!
Oh, forgot to mention, that those who want to validate a number includes a thousand separator, you should clean all the commas (,
) first, as there may be any type of separator out there, you can't actually cover them all.
But you can remove them first, before the number validation:
//JavaScript
function clearSeparators(number)
{
return number.replace(/,/g,'');
}
There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.
The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.
I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.
Since globals are module specific, you can add the following function to all imported modules, and then use it to:
addglobals = lambda x: globals().update(x)
Then all you need to pass on current globals is:
import module
module.addglobals(globals())
Visual Studio
windows.h
)Visual Studio Code
<?php
$field = 'display_name';
the_author_meta($field);
?>
Valid values for the $field
parameter include:
You can use a single group for seconds/minutes. The following expression may suit your needs:
([0-9]+)\s*(seconds|minutes)
Use the following class, updated to the last API level: 29.
// License: MIT
// http://opensource.org/licenses/MIT
package net.i2p.android.router.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.telephony.TelephonyManager;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.CancellationException;
/**
* Check device's network connectivity and speed.
*
* @author emil http://stackoverflow.com/users/220710/emil
* @author str4d
* @author rodrigo https://stackoverflow.com/users/5520417/rodrigo
*/
public class ConnectivityAndInternetAccessCheck {
private static ArrayList < String > hosts = new ArrayList < String > () {
{
add("google.com");
add("facebook.com");
add("apple.com");
add("amazon.com");
add("twitter.com");
add("linkedin.com");
add("microsoft.com");
}
};
/**
* Get the network info.
*
* @param context the Context.
* @return the active NetworkInfo.
*/
private static NetworkInfo getNetworkInfo(Context context) {
NetworkInfo networkInfo = null;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
networkInfo = cm.getActiveNetworkInfo();
}
return networkInfo;
}
/**
* Gets the info of all networks
* @param context The context
* @return an array of @code{{@link NetworkInfo}}
*/
private static NetworkInfo[] getAllNetworkInfo(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getAllNetworkInfo();
}
/**
* Gives the connectivity manager
* @param context The context
* @return the @code{{@link ConnectivityManager}}
*/
private static ConnectivityManager getConnectivityManager(Context context) {
return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
/**
* Check if there is any connectivity at all.
*
* @param context the Context.
* @return true if we are connected to a network, false otherwise.
*/
public static boolean isConnected(Context context) {
boolean isConnected = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ConnectivityManager connectivityManager = ConnectivityAndInternetAccessCheck.getConnectivityManager(context);
Network[] networks = connectivityManager.getAllNetworks();
networksloop: for (Network network: networks) {
if (network == null) {
isConnected = false;
} else {
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if(networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)){
isConnected = true;
break networksloop;
}
else {
isConnected = false;
}
}
}
} else {
NetworkInfo[] networkInfos = ConnectivityAndInternetAccessCheck.getAllNetworkInfo(context);
networkinfosloop: for (NetworkInfo info: networkInfos) {
// Works on emulator and devices.
// Note the use of isAvailable() - without this, isConnected() can
// return true when Wifi is disabled.
// http://stackoverflow.com/a/2937915
isConnected = info != null && info.isAvailable() && info.isConnected();
if (isConnected) {
break networkinfosloop;
}
}
}
return isConnected;
}
/**
* Check if there is any connectivity to a Wifi network.
*
* @param context the Context.
* @return true if we are connected to a Wifi network, false otherwise.
*/
public static boolean isConnectedWifi(Context context) {
boolean isConnectedWifi = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ConnectivityManager connectivityManager = ConnectivityAndInternetAccessCheck.getConnectivityManager(context);
Network[] networks = connectivityManager.getAllNetworks();
networksloop: for (Network network: networks) {
if (network == null) {
isConnectedWifi = false;
} else {
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if(networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)){
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
isConnectedWifi = true;
break networksloop;
} else {
isConnectedWifi = false;
}
}
}
}
} else {
NetworkInfo[] networkInfos = ConnectivityAndInternetAccessCheck.getAllNetworkInfo(context);
networkinfosloop: for (NetworkInfo n: networkInfos) {
isConnectedWifi = n != null && n.isAvailable() && n.isConnected() && n.getType() == ConnectivityManager.TYPE_WIFI;
if (isConnectedWifi) {
break networkinfosloop;
}
}
}
return isConnectedWifi;
}
/**
* Check if there is any connectivity to a mobile network.
*
* @param context the Context.
* @return true if we are connected to a mobile network, false otherwise.
*/
public static boolean isConnectedMobile(Context context) {
boolean isConnectedMobile = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ConnectivityManager connectivityManager = ConnectivityAndInternetAccessCheck.getConnectivityManager(context);
Network[] allNetworks = connectivityManager.getAllNetworks();
networksloop: for (Network network: allNetworks) {
if (network == null) {
isConnectedMobile = false;
} else {
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if(networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)){
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
isConnectedMobile = true;
break networksloop;
} else {
isConnectedMobile = false;
}
}
}
}
} else {
NetworkInfo[] networkInfos = ConnectivityAndInternetAccessCheck.getAllNetworkInfo(context);
networkinfosloop: for (NetworkInfo networkInfo: networkInfos) {
isConnectedMobile = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
if (isConnectedMobile) {
break networkinfosloop;
}
}
}
return isConnectedMobile;
}
/**
* Check if there is fast connectivity.
*
* @param context the Context.
* @return true if we have "fast" connectivity, false otherwise.
*/
public static boolean isConnectedFast(Context context) {
boolean isConnectedFast = false;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
NetworkInfo[] networkInfos = ConnectivityAndInternetAccessCheck.getAllNetworkInfo(context);
networkInfosloop:
for (NetworkInfo networkInfo: networkInfos) {
isConnectedFast = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected() && isConnectionFast(networkInfo.getType(), networkInfo.getSubtype());
if (isConnectedFast) {
break networkInfosloop;
}
}
} else {
throw new UnsupportedOperationException();
}
return isConnectedFast;
}
/**
* Check if the connection is fast.
*
* @param type the network type.
* @param subType the network subtype.
* @return true if the provided type/subtype combination is classified as fast.
*/
private static boolean isConnectionFast(int type, int subType) {
if (type == ConnectivityManager.TYPE_WIFI) {
return true;
} else if (type == ConnectivityManager.TYPE_MOBILE) {
switch (subType) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_CDMA:
return false; // ~ 14-64 kbps
case TelephonyManager.NETWORK_TYPE_EDGE:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return true; // ~ 400-1000 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return true; // ~ 600-1400 kbps
case TelephonyManager.NETWORK_TYPE_GPRS:
return false; // ~ 100 kbps
case TelephonyManager.NETWORK_TYPE_HSDPA:
return true; // ~ 2-14 Mbps
case TelephonyManager.NETWORK_TYPE_HSPA:
return true; // ~ 700-1700 kbps
case TelephonyManager.NETWORK_TYPE_HSUPA:
return true; // ~ 1-23 Mbps
case TelephonyManager.NETWORK_TYPE_UMTS:
return true; // ~ 400-7000 kbps
/*
* Above API level 7, make sure to set android:targetSdkVersion
* to appropriate level to use these
*/
case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11
return true; // ~ 1-2 Mbps
case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
return true; // ~ 5 Mbps
case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
return true; // ~ 10-20 Mbps
case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
return false; // ~25 kbps
case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
return true; // ~ 10+ Mbps
// Unknown
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
default:
return false;
}
} else {
return false;
}
}
public ArrayList < String > getHosts() {
return hosts;
}
public void setHosts(ArrayList < String > hosts) {
this.hosts = hosts;
}
//TODO Debug on devices
/**
* Checks that Internet is available by pinging DNS servers.
*/
private static class InternetConnectionCheckAsync extends AsyncTask < Void, Void, Boolean > {
private Context context;
/**
* Creates an instance of this class
* @param context The context
*/
public InternetConnectionCheckAsync(Context context) {
this.setContext(context);
}
/**
* Cancels the activity if the device is not connected to a network.
*/
@Override
protected void onPreExecute() {
if (!ConnectivityAndInternetAccessCheck.isConnected(getContext())) {
cancel(true);
}
}
/**
* Tells whether there is Internet access
* @param voids The list of arguments
* @return True if Internet can be accessed
*/
@Override
protected Boolean doInBackground(Void...voids) {
return isConnectedToInternet(getContext());
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
/**
* The context
*/
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
} //network calls shouldn't be called from main thread otherwise it will throw //NetworkOnMainThreadException
/**
* Tells whether Internet is reachable
* @return true if Internet is reachable, false otherwise
* @param context The context
*/
public static boolean isInternetReachable(Context context) {
try {
return new InternetConnectionCheckAsync(context).execute().get();
} catch (CancellationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* Tells whether there is Internet connection
* @param context The context
* @return @code {true} if there is Internet connection
*/
private static boolean isConnectedToInternet(Context context) {
boolean isAvailable = false;
if (!ConnectivityAndInternetAccessCheck.isConnected(context)) {
isAvailable = false;
} else {
try {
foreachloop: for (String h: new ConnectivityAndInternetAccessCheck().getHosts()) {
if (isHostAvailable(h)) {
isAvailable = true;
break foreachloop;
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
return isAvailable;
}
/**
* Checks if the host is available
* @param hostName
* @return
* @throws IOException
*/
private static boolean isHostAvailable(String hostName) throws IOException {
try (Socket socket = new Socket()) {
int port = 80;
InetSocketAddress socketAddress = new InetSocketAddress(hostName, port);
socket.connect(socketAddress, 3000);
return true;
} catch (UnknownHostException unknownHost) {
return false;
}
}
}
for (i>0; i--;)
is probably wrong and should be
for (; i>0; i--)
instead. Note where I put the semicolons. The condition goes in the middle, not at the start.
With Windows 2012 R2 (Win 8.1) and up, you also have the "official" Import-PfxCertificate cmdlet
Here are some essential parts of code (an adaptable example):
Invoke-Command -ComputerName $Computer -ScriptBlock {
param(
[string] $CertFileName,
[string] $CertRootStore,
[string] $CertStore,
[string] $X509Flags,
$PfxPass)
$CertPath = "$Env:SystemRoot\$CertFileName"
$Pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
# Flags to send in are documented here: https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509keystorageflags%28v=vs.110%29.aspx
$Pfx.Import($CertPath, $PfxPass, $X509Flags) #"Exportable,PersistKeySet")
$Store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList $CertStore, $CertRootStore
$Store.Open("MaxAllowed")
$Store.Add($Pfx)
if ($?)
{
"${Env:ComputerName}: Successfully added certificate."
}
else
{
"${Env:ComputerName}: Failed to add certificate! $($Error[0].ToString() -replace '[\r\n]+', ' ')"
}
$Store.Close()
Remove-Item -LiteralPath $CertPath
} -ArgumentList $TempCertFileName, $CertRootStore, $CertStore, $X509Flags, $Password
Based on mao47's code and some research, I wrote up a little article and a simple cmdlet for importing/pushing PFX certificates to remote computers.
Here's my article with more details and complete code that also works with PSv2 (default on Server 2008 R2 / Windows 7), so long as you have SMB enabled and administrative share access.
you can use the return
statement without any parameter to exit a function
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
return
do much much more...
or raise an exception if you want to be informed of the problem
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
raise Exception("cause of the problem")
do much much more...
ffmpeg -codecs
should give you all the info about the codecs available.
You will see some letters next to the codecs:
Codecs:
D..... = Decoding supported
.E.... = Encoding supported
..V... = Video codec
..A... = Audio codec
..S... = Subtitle codec
...I.. = Intra frame-only codec
....L. = Lossy compression
.....S = Lossless compression
Enqueue
and Dequeue
tend to be operations on a queue, a data structure that does exactly what it sounds like it does.
You enqueue items at one end and dequeue at the other, just like a line of people queuing up for tickets to the latest Taylor Swift concert (I was originally going to say Billy Joel but that would date me severely).
There are variations of queues such as double-ended ones where you can enqueue and dequeue at either end but the vast majority would be the simpler form:
+---+---+---+
enqueue -> | 3 | 2 | 1 | -> dequeue
+---+---+---+
That diagram shows a queue where you've enqueued the numbers 1, 2 and 3 in that order, without yet dequeuing any.
By way of example, here's some Python code that shows a simplistic queue in action, with enqueue
and dequeue
functions. Were it more serious code, it would be implemented as a class but it should be enough to illustrate the workings:
import random
def enqueue(lst, itm):
lst.append(itm) # Just add item to end of list.
return lst # And return list (for consistency with dequeue).
def dequeue(lst):
itm = lst[0] # Grab the first item in list.
lst = lst[1:] # Change list to remove first item.
return (itm, lst) # Then return item and new list.
# Test harness. Start with empty queue.
myList = []
# Enqueue or dequeue a bit, with latter having probability of 10%.
for _ in range(15):
if random.randint(0, 9) == 0 and len(myList) > 0:
(itm, myList) = dequeue(myList)
print(f"Dequeued {itm} to give {myList}")
else:
itm = 10 * random.randint(1, 9)
myList = enqueue(myList, itm)
print(f"Enqueued {itm} to give {myList}")
# Now dequeue remainder of list.
print("========")
while len(myList) > 0:
(itm, myList) = dequeue(myList)
print(f"Dequeued {itm} to give {myList}")
A sample run of that shows it in operation:
Enqueued 70 to give [70]
Enqueued 20 to give [70, 20]
Enqueued 40 to give [70, 20, 40]
Enqueued 50 to give [70, 20, 40, 50]
Dequeued 70 to give [20, 40, 50]
Enqueued 20 to give [20, 40, 50, 20]
Enqueued 30 to give [20, 40, 50, 20, 30]
Enqueued 20 to give [20, 40, 50, 20, 30, 20]
Enqueued 70 to give [20, 40, 50, 20, 30, 20, 70]
Enqueued 20 to give [20, 40, 50, 20, 30, 20, 70, 20]
Enqueued 20 to give [20, 40, 50, 20, 30, 20, 70, 20, 20]
Dequeued 20 to give [40, 50, 20, 30, 20, 70, 20, 20]
Enqueued 80 to give [40, 50, 20, 30, 20, 70, 20, 20, 80]
Dequeued 40 to give [50, 20, 30, 20, 70, 20, 20, 80]
Enqueued 90 to give [50, 20, 30, 20, 70, 20, 20, 80, 90]
========
Dequeued 50 to give [20, 30, 20, 70, 20, 20, 80, 90]
Dequeued 20 to give [30, 20, 70, 20, 20, 80, 90]
Dequeued 30 to give [20, 70, 20, 20, 80, 90]
Dequeued 20 to give [70, 20, 20, 80, 90]
Dequeued 70 to give [20, 20, 80, 90]
Dequeued 20 to give [20, 80, 90]
Dequeued 20 to give [80, 90]
Dequeued 80 to give [90]
Dequeued 90 to give []
Since the time the question was asked, the draft for the const
keyword is already a living standard as part of ECMAScript 2015. Also the current version of Node.js supports const declarations without the --harmony
flag.
With the above said you can now run node app.js
, with app.js
:
'use strict';
const MB = 1024 * 1024;
...
getting both the syntax sugar and the benefits of strict mode.
I had a similar problem where I needed to only show a value from another Excel cell if the font was black. I created this function: `Option Explicit
Function blackFont(r As Range) As Boolean If r.Font.Color = 0 Then blackFont = True Else blackFont = False End If
End Function `
In my cell I have this formula:
=IF(blackFont(Y51),Y51," ")
This worked well for me to test for a black font and only show the value in the Y51 cell if it had a black font.
On the contrary, I do think working with list
makes it easy to automate such things.
Here is one solution (I stored your four dataframes in folder temp/
).
filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)
It is important to store the full path for your files (as I did with full.names
), otherwise you have to paste the working directory, e.g.
filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")
will work too. Note that I used substr
to extract file names while discarding full path.
You can access your summary tables as follows:
> res$`df4.csv`
A B
Min. :0.00 Min. : 1.00
1st Qu.:1.25 1st Qu.: 2.25
Median :3.00 Median : 6.00
Mean :3.50 Mean : 7.00
3rd Qu.:5.50 3rd Qu.:10.50
Max. :8.00 Max. :16.00
If you really want to get individual summary tables, you can extract them afterwards. E.g.,
for (i in 1:length(res))
assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])
Updated for Swift 3
William Hu's Swift answer is good, but it helps me to have some simple yet detailed steps when learning to do something for the first time. The example below is my test project while learning to make a UITableView
with variable cell heights. I based it on this basic UITableView example for Swift.
The finished project should look like this:
It can be just a Single View Application.
Add a new Swift file to your project. Name it MyCustomCell. This class will hold the outlets for the views that you add to your cell in the storyboard. In this basic example we will only have one label in each cell.
import UIKit
class MyCustomCell: UITableViewCell {
@IBOutlet weak var myCellLabel: UILabel!
}
We will connect this outlet later.
Open ViewController.swift and make sure you have the following content:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// These strings will be the data for the table view cells
let animals: [String] = [
"Ten horses: horse horse horse horse horse horse horse horse horse horse ",
"Three cows: cow, cow, cow",
"One camel: camel",
"Ninety-nine sheep: sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep baaaa sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep sheep",
"Thirty goats: goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat goat "]
// Don't forget to enter this in IB also
let cellReuseIdentifier = "cell"
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// delegate and data source
tableView.delegate = self
tableView.dataSource = self
// Along with auto layout, these are the keys for enabling variable cell height
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
cell.myCellLabel.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Important Note:
It is the following two lines of code (along with auto layout) that make the variable cell height possible:
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
Add a Table View to your view controller and use auto layout to pin it to the four sides. Then drag a Table View Cell onto the Table View. And onto the Prototype cell, drag a Label. Use auto layout to pin the label to the four edges of the content view of the Table View Cell.
Important note:
Custom class name and Identifier
Select the Table View Cell and set the custom class to be MyCustomCell
(the name of the class in the Swift file we added). Also set the Identifier to be cell
(the same string that we used for the cellReuseIdentifier
in the code above.
Zero Lines for Label
Set the number of lines to 0
in your Label. This means multi-line and allows the label to resize itself based on its content.
Hook Up the Outlets
tableView
variable in the ViewController
code. myCellLabel
variable in the MyCustomCell
class.You should be able to run your project now and get cells with variable heights.
If you are not pinning the leading and trailing (left and right) edges, you may also need to set the label's preferredMaxLayoutWidth
so that it knows when to line wrap. For example, if you had added a Center Horizontally constraint to the label in the project above rather than pin the leading and trailing edges, then you would need to add this line to the tableView:cellForRowAtIndexPath
method:
cell.myCellLabel.preferredMaxLayoutWidth = tableView.bounds.width
Try adding --user-install
instead of using sudo
:
gem install mygem --user-install
You're declaring (some of) your event handlers incorrectly:
$('.menuOption').click(function( event ){ // <---- "event" parameter here
event.preventDefault();
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.
edit — to clarify: you have to provide some parameter name; using event
makes it clear what you intend, but you can call it e
or cupcake
or anything else.
Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.
call waitfor(.005)
Sub WaitFor(NumOfSeconds As Single)
Dim SngSec as Single
SngSec=Timer + NumOfSeconds
Do while timer < sngsec
DoEvents
Loop
End sub
source Timing Delays in VBA
String lines[] =String.split( System.lineSeparator())
This will help you. Don't forget to add the JAR HttpClient.jar
to the classpath.
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class MainSendRequest {
static String url =
"http://localhost:8080/HttpRequestSample/RequestSend.jsp";
public static void main(String[] args) {
//Instantiate an HttpClient
HttpClient client = new HttpClient();
//Instantiate a GET HTTP method
PostMethod method = new PostMethod(url);
method.setRequestHeader("Content-type",
"text/xml; charset=ISO-8859-1");
//Define name-value pairs to set into the QueryString
NameValuePair nvp1= new NameValuePair("firstName","fname");
NameValuePair nvp2= new NameValuePair("lastName","lname");
NameValuePair nvp3= new NameValuePair("email","[email protected]");
method.setQueryString(new NameValuePair[]{nvp1,nvp2,nvp3});
try{
int statusCode = client.executeMethod(method);
System.out.println("Status Code = "+statusCode);
System.out.println("QueryString>>> "+method.getQueryString());
System.out.println("Status Text>>>"
+HttpStatus.getStatusText(statusCode));
//Get data as a String
System.out.println(method.getResponseBodyAsString());
//OR as a byte array
byte [] res = method.getResponseBody();
//write to file
FileOutputStream fos= new FileOutputStream("donepage.html");
fos.write(res);
//release connection
method.releaseConnection();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $
represents the jQuery Function, and is actually a shorthand alias for jQuery
. (Unlike in most languages, the $
symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
This will avoid the need for grepping off log entries from the output:
mvn -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive exec:exec -q
So I was trying to solve a similar problem with connecting to a totally different server on my own LAN so that when power is interrupted and then restored that my server comes back online and other systems can still have connectivity with automation. However, my problem was DHCP giving my server a diff IP on occasion. This thread answered my problem with the NAMESERVER that windows have natively. I was connecting directly to my servers IP add http://192.168.1.5 through a batch file to initialize the connection but when power problems happen it would not connect. I changed the .bat file to point at http://DESKTOP-actualnamewhereserver:port and done. Problem solved. IF I don't change my computers names then when DHCP hands DESKTOP-actualnamewhereserver a new IP address it will still identify as its own name on the LAN and therefore be able to accept the connection regardless of it's IP Address. Simply give the other people on your wireless LAN the name of your pc hosting the Apache server and lets say its name is DESKTOP-DOUGHFACTORYHUT they will type http://DOUGHFACTORYHUT:80 or whatever port number your apache config is set to host at like LOCALHOST:80 which essentially are the same thing attached to your local Dynamic IP address assigned by DHCP or STATIC IP you have set to the server.
Since you want the trailing string from the input, you can use %n
(number of characters consumed thus far) to get the position at which the trailing string starts. This avoids memory copies and buffer sizing issues, but comes at the cost that you may need to do them explicitly if you wanted a copy.
const char *input = "19 cool kid";
int age;
int nameStart = 0;
sscanf(input, "%d %n", &age, &nameStart);
printf("%s is %d years old\n", input + nameStart, age);
outputs:
cool kid is 19 years old
Though answers above were very helpful, I've spent a day to make them work, facing various exceptions like "broken channel", "rsa key unknown" and "packet corrupt".
Below is a working reusable class for SFTP FILES UPLOAD/DOWNLOAD using JSch library.
Upload usage:
SFTPFileCopy upload = new SFTPFileCopy(true, /path/to/sourcefile.png", /path/to/destinationfile.png");
Download usage:
SFTPFileCopy download = new SFTPFileCopy(false, "/path/to/sourcefile.png", "/path/to/destinationfile.png");
The class code:
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JOptionPane;
import menue.Menue;
public class SFTPFileCopy1 {
public SFTPFileCopy1(boolean upload, String sourcePath, String destPath) throws FileNotFoundException, IOException {
Session session = null;
Channel channel = null;
ChannelSftp sftpChannel = null;
try {
JSch jsch = new JSch();
//jsch.setKnownHosts("/home/user/.putty/sshhostkeys");
session = jsch.getSession("login", "mysite.com", 22);
session.setPassword("password");
UserInfo ui = new MyUserInfo() {
public void showMessage(String message) {
JOptionPane.showMessageDialog(null, message);
}
public boolean promptYesNo(String message) {
Object[] options = {"yes", "no"};
int foo = JOptionPane.showOptionDialog(null,
message,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo == 0;
}
};
session.setUserInfo(ui);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
sftpChannel = (ChannelSftp) channel;
if (upload) { // File upload.
byte[] bufr = new byte[(int) new File(sourcePath).length()];
FileInputStream fis = new FileInputStream(new File(sourcePath));
fis.read(bufr);
ByteArrayInputStream fileStream = new ByteArrayInputStream(bufr);
sftpChannel.put(fileStream, destPath);
fileStream.close();
} else { // File download.
byte[] buffer = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(sourcePath));
OutputStream os = new FileOutputStream(new File(destPath));
BufferedOutputStream bos = new BufferedOutputStream(os);
int readCount;
while ((readCount = bis.read(buffer)) > 0) {
bos.write(buffer, 0, readCount);
}
bis.close();
bos.close();
}
} catch (Exception e) {
System.out.println(e);
} finally {
if (sftpChannel != null) {
sftpChannel.exit();
}
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
public static abstract class MyUserInfo
implements UserInfo, UIKeyboardInteractive {
public String getPassword() {
return null;
}
public boolean promptYesNo(String str) {
return false;
}
public String getPassphrase() {
return null;
}
public boolean promptPassphrase(String message) {
return false;
}
public boolean promptPassword(String message) {
return false;
}
public void showMessage(String message) {
}
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo) {
return null;
}
}
}
Spinner don't support Hint, i recommend you to make a custom spinner adapter.
check this link : https://stackoverflow.com/a/13878692/1725748
I had a co-worker with this exact problem last week. He fixed it by installing the x64 version of Eclipse and the x64 JDK.
Edit: he reused his old workspace after installing the necessary plugins, so that should not be much of an issue
This is badly formed HTML. You need to either have a single id or space separated classes. Either way if you're new I'd look into jQuery.
<div id="sub1">some text</div>
or
<div class="sub1 sub2 sub3">some text</div>
If you had the following HTML:
<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Some welcome message</div>
$(document).ready(function() {
$('#sub1').hover(
function() { $('#welcome').show(); },
function() { $('#welcome').hide(); }
);
});
you'd probably want to include the events on your html:
<div id="sub1" onmouseover="showWelcome();" onmouseout="hideWelcome();">some text</div>
then your javascript would have these two functions
function showWelcome()
{
var welcome = document.getElementById('welcome');
welcome.style.display = 'block';
}
function hideWelcome()
{
var welcome = document.getElementById('welcome');
welcome.style.display = 'none';
}
Please note: this javascript doesn't take cross browser issues into consideration. for this you'd need to elaborate on your code, just another reason to use jquery.
I just had the same problem and ended up doing:
git rebase -i HEAD~N
(N is the number of commits git will show you)
That prompts your text editor and then you can remove the commit you want by deleting the line associated with it.
Use another flex container to fix the min-height
issue in IE10 and IE11:
HTML
<div class="ie-fixMinHeight">
<div id="page">
<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
</div>
</div>
CSS
.ie-fixMinHeight {
display:flex;
}
#page {
min-height:100vh;
width:100%;
display:flex;
flex-direction:column;
}
#content {
flex-grow:1;
}
See a working demo.
body
because it
screws up elements inserted via jQuery plugins (autocomplete, popup,
etc.).height:100%
or height:100vh
on your container because the footer will stick at the bottom of window and won't adapt to long content.flex-grow:1
rather than flex:1
cause IE10 and IE11 default values for flex
are 0 0 auto
and not 0 1 auto
.Ignoring the span stuff that other people have dealt with, to properly handle dictionary suggestions I found the following code works.
The source grows as the suggestion grows so we have to look at how many characters it's actually expecting us to replace before we return anything.
If we don't have any invalid characters, return null so that the default replacement occurs.
Otherwise we need to extract out the valid characters from the substring that's ACTUALLY going to be placed into the EditText.
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
boolean includesInvalidCharacter = false;
StringBuilder stringBuilder = new StringBuilder();
int destLength = dend - dstart + 1;
int adjustStart = source.length() - destLength;
for(int i=start ; i<end ; i++) {
char sourceChar = source.charAt(i);
if(Character.isLetterOrDigit(sourceChar)) {
if(i >= adjustStart)
stringBuilder.append(sourceChar);
} else
includesInvalidCharacter = true;
}
return includesInvalidCharacter ? stringBuilder : null;
}
};
also, make sure the server is listening for ur mobile device! for example, by default jekyll only answers requests made by the host machine. this solved my problem:
Connect to a locally built Jekyll Server using mobile devices in the LAN
In addition to the nested approach above, you can accomplish the application of theLIMIT
using JOIN
on the same table:
UPDATE `table_name`
INNER JOIN (SELECT `id` from `table_name` order by `id` limit 0,100) as t2 using (`id`)
SET `name` = 'test'
In my experience the mysql query optimizer is happier with this structure.
WITH pivot_data AS
(
SELECT customerid, -- Grouping Column
dbcolumnname, -- Spreading Column
data -- Aggregate Column
FROM pivot2
)
SELECT customerid, [firstname], [middlename], [lastname]
FROM pivot_data
PIVOT (max(data) FOR dbcolumnname IN ([firstname],[middlename],[lastname])) AS p;
Got the same kind of error but my package was absolutely correct. When I just closed and opened my editor, the error disappears. Hope this might help in some scenarios.
I have a nice simple lib here that allows you to use sealed traits/classes as enum values without having to maintain your own list of values. It relies on a simple macro that is not dependent on the buggy knownDirectSubclasses
.
In the most shared hosts you can't set it.
On a VPS or dedicated server, you can set it, but everything has its price.
On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)
If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.
If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.
For Windows Use this class
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency !== false) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}
Recompile without optimizations (-O0 on gcc).
Open vscode.
Press ctrl,.
The setting is "editor.fontFamily"
.
On Linux to get a list of fonts (and their names which you have to use) run this in another shell:
fc-list | awk '{$1=""}1' | cut -d: -f1 | sort| uniq
You can specify a list of fonts, to have fallback values in case a font is missing.
You typically have to do this in a single syscall, or else you will get a race condition.
This will open for reading and writing, creating the file if necessary.
FILE *fp = fopen("scores.dat", "ab+");
If you want to read it and then write a new version from scratch, then do it as two steps.
FILE *fp = fopen("scores.dat", "rb");
if (fp) {
read_scores(fp);
}
// Later...
// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
error();
write_scores(fp);
Use text/csv
as the content type.
To me this kind of seemingly simple problem is what Python is all about. Especially if you're coming from a language like C++, where simple text parsing can be a pain in the butt, you'll really appreciate the functionally unit-wise solution that python can give you. I'd keep it really simple with a couple of built-in functions and some generator expressions.
You'll need open(name, mode)
, myfile.readlines()
, mystring.split()
, int(myval)
, and then you'll probably want to use a couple of generators to put them all together in a pythonic way.
# This opens a handle to your file, in 'r' read mode
file_handle = open('mynumbers.txt', 'r')
# Read in all the lines of your file into a list of lines
lines_list = file_handle.readlines()
# Extract dimensions from first line. Cast values to integers from strings.
cols, rows = (int(val) for val in lines_list[0].split())
# Do a double-nested list comprehension to get the rest of the data into your matrix
my_data = [[int(val) for val in line.split()] for line in lines_list[1:]]
Look up generator expressions here. They can really simplify your code into discrete functional units! Imagine doing the same thing in 4 lines in C++... It would be a monster. Especially the list generators, when I was I C++ guy I always wished I had something like that, and I'd often end up building custom functions to construct each kind of array I wanted.
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.
Source: Reading and Writing Files
If you're running Python 3.3 or better, you can use the clear()
method of list
, which is parallel to clear()
of dict
, set
, deque
and other mutable container types:
alist.clear() # removes all items from alist (equivalent to del alist[:])
As per the linked documentation page, the same can also be achieved with alist *= 0
.
To sum up, there are four equivalent ways to clear a list in-place (quite contrary to the Zen of Python!):
alist.clear() # Python 3.3+
del alist[:]
alist[:] = []
alist *= 0
This could be more helpfull....
$("element").prop("id", "modifiedId");
//for boolean
$("element").prop("disabled", true);
//also you can remove attribute
$('#someid').removeProp('disabled');
Build your own script to install global dependencies. It doesn't take much. package.json is quite expandable.
const {execSync} = require('child_process');
JSON.parse(fs.readFileSync('package.json'))
.globalDependencies.foreach(
globaldep => execSync('npm i -g ' + globaldep)
);
Using the above, you can even make it inline, below!
Look at preinstall below:
{
"name": "Project Name",
"version": "0.1.0",
"description": "Project Description",
"main": "app.js",
"scripts": {
"preinstall": "node -e \"const {execSync} = require('child_process'); JSON.parse(fs.readFileSync('package.json')).globalDependencies.foreach(globaldep => execSync('npm i -g ' + globaldep));\"",
"build": "your transpile/compile script",
"start": "node app.js",
"test": "./node_modules/.bin/mocha --reporter spec",
"patch-release": "npm version patch && npm publish && git add . && git commit -m \"auto-commit\" && git push --follow-tags"
},
"dependencies": [
},
"globalDependencies": [
"[email protected]",
"ionic",
"potato"
],
"author": "author",
"license": "MIT",
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^5.2.0"
},
"bin": {
"app": "app.js"
}
}
The authors of node may not admit package.json is a project file. But it is.
MySQL also has IF()
:
SELECT
id, action_heading,
IF(action_type='Income',action_amount,0) income,
IF(action_type='Expense', action_amount, 0) expense
FROM tbl_transaction
There are a couple of simple one-liners you can use to do this.
1) Set a "style" attribute on the element:
element.setAttribute('style', 'display:inline !important');
or...
2) Modify the cssText
property of the style
object:
element.style.cssText = 'display:inline !important';
Either will do the job.
===
BTW - if you want a useful tool to manipulate !important
rules in elements, I've written a jQuery plugin called "important": http://github.com/premasagar/important
double degree = fmodf((atan2(x, y) * (180.0 / M_PI)) + 360, 360);
This will return degree from 0°-360° counter-clockwise, 0° is at 3 o'clock.
If you ever need to send GET
request to an IP
as well as a Domain
(Other answers did not mention you can specify a port
variable), you can make use of this function:
function getCode(host, port, path, queryString) {
console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")
// Construct url and query string
const requestUrl = url.parse(url.format({
protocol: 'http',
hostname: host,
pathname: path,
port: port,
query: queryString
}));
console.log("(" + host + path + ")" + "Sending GET request")
// Send request
console.log(url.format(requestUrl))
http.get(url.format(requestUrl), (resp) => {
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
console.log("GET chunk: " + chunk);
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log("GET end of response: " + data);
});
}).on("error", (err) => {
console.log("GET Error: " + err);
});
}
Don't miss requiring modules at the top of your file:
http = require("http");
url = require('url')
Also bare in mind that you may use https
module for communicating over secured network. so these two lines would change:
https = require("https");
...
https.get(url.format(requestUrl), (resp) => { ......
<style type="text/css">
img {
background-image: url('/images/default.png')
}
</style>
Be sure to enter dimensions of image and whether you want the image to tile or not.
#dimScreen{
position:fixed;
top:0px;
left:0px;
width:100%;
height:100%;
}
As of September 2016 (VSCode 1.6), this is now officially supported.
Add the following to your settings.json
file:
"editor.formatOnSave": true
I also have same problem and in my case I injected reducer properly but still I couldn't type in field. It turns out if you are using immutable
you have to use redux-form/immutable
.
import {reducer as formReducer} from 'redux-form/immutable';
const reducer = combineReducers{
form: formReducer
}
import {Field, reduxForm} from 'redux-form/immutable';
/* your component */
Notice that your state should be like state->form
otherwise you have to explicitly config the library also the name for state should be form
.
see this issue
With Bootstrap 3 you can use 'hidden.bs.modal' event handler to delete any modal-related data, forcing the popup to reload next time:
$('#modal').on('hidden.bs.modal', function() {
$(this).removeData('bs.modal');
});
Be aware that passing an Object with named properties as Ken suggested adds the cost of allocating and releasing the temporary object to every call. Passing normal arguments by value or reference will generally be the most efficient. For many applications though the performance is not critical but for some it can be.
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
res.next()
method will take the pointer to the next row. and in your code you are using it twice, first for the if condition (cursor moves to first row) then for while condition (cursor moves to second row).
So when you access your results, it starts from second row. So shows one row less in results.
you can try this :
if(!res.next()){
System.out.println("No Data Found");
}
else{
do{
//your code
}
while(res.next());
}
There are many ways to wait in Unity. It is really simple but I think it's worth covering most ways to do these:
1.With a coroutine and WaitForSeconds
.
The is by far the simplest way. Put all the code that you need to wait for some time in a coroutine function then you can wait with WaitForSeconds
. Note that in coroutine function, you call the function with StartCoroutine(yourFunction)
.
Example below will rotate 90 deg, wait for 4 seconds, rotate 40 deg and wait for 2 seconds, and then finally rotate rotate 20 deg.
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
yield return new WaitForSeconds(4);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
yield return new WaitForSeconds(2);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
2.With a coroutine and WaitForSecondsRealtime
.
The only difference between WaitForSeconds
and WaitForSecondsRealtime
is that WaitForSecondsRealtime
is using unscaled time to wait which means that when pausing a game with Time.timeScale
, the WaitForSecondsRealtime
function would not be affected but WaitForSeconds
would.
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
yield return new WaitForSecondsRealtime(4);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
yield return new WaitForSecondsRealtime(2);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
Wait and still be able to see how long you have waited:
3.With a coroutine and incrementing a variable every frame with Time.deltaTime
.
A good example of this is when you need the timer to display on the screen how much time it has waited. Basically like a timer.
It's also good when you want to interrupt the wait/sleep with a boolean
variable when it is true. This is where yield break;
can be used.
bool quit = false;
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
float counter = 0;
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
float waitTime = 4;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
//Wait for a frame so that Unity doesn't freeze
//Check if we want to quit this function
if (quit)
{
//Quit function
yield break;
}
yield return null;
}
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
waitTime = 2;
//Reset counter
counter = 0;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
//Check if we want to quit this function
if (quit)
{
//Quit function
yield break;
}
//Wait for a frame so that Unity doesn't freeze
yield return null;
}
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
You can still simplify this by moving the while
loop into another coroutine function and yielding it and also still be able to see it counting and even interrupt the counter.
bool quit = false;
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
float waitTime = 4;
yield return wait(waitTime);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
waitTime = 2;
yield return wait(waitTime);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
IEnumerator wait(float waitTime)
{
float counter = 0;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
if (quit)
{
//Quit function
yield break;
}
//Wait for a frame so that Unity doesn't freeze
yield return null;
}
}
Wait/Sleep until variable changes or equals to another value:
4.With a coroutine and the WaitUntil
function:
Wait until a condition becomes true
. An example is a function that waits for player's score to be 100
then loads the next level.
float playerScore = 0;
int nextScene = 0;
void Start()
{
StartCoroutine(sceneLoader());
}
IEnumerator sceneLoader()
{
Debug.Log("Waiting for Player score to be >=100 ");
yield return new WaitUntil(() => playerScore >= 10);
Debug.Log("Player score is >=100. Loading next Leve");
//Increment and Load next scene
nextScene++;
SceneManager.LoadScene(nextScene);
}
5.With a coroutine and the WaitWhile
function.
Wait while a condition is true
. An example is when you want to exit app when the escape key is pressed.
void Start()
{
StartCoroutine(inputWaiter());
}
IEnumerator inputWaiter()
{
Debug.Log("Waiting for the Exit button to be pressed");
yield return new WaitWhile(() => !Input.GetKeyDown(KeyCode.Escape));
Debug.Log("Exit button has been pressed. Leaving Application");
//Exit program
Quit();
}
void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
6.With the Invoke
function:
You can call tell Unity to call function in the future. When you call the Invoke
function, you can pass in the time to wait before calling that function to its second parameter. The example below will call the feedDog()
function after 5
seconds the Invoke
is called.
void Start()
{
Invoke("feedDog", 5);
Debug.Log("Will feed dog after 5 seconds");
}
void feedDog()
{
Debug.Log("Now feeding Dog");
}
7.With the Update()
function and Time.deltaTime
.
It's just like #3 except that it does not use coroutine. It uses the Update
function.
The problem with this is that it requires so many variables so that it won't run every time but just once when the timer is over after the wait.
float timer = 0;
bool timerReached = false;
void Update()
{
if (!timerReached)
timer += Time.deltaTime;
if (!timerReached && timer > 5)
{
Debug.Log("Done waiting");
feedDog();
//Set to false so that We don't run this again
timerReached = true;
}
}
void feedDog()
{
Debug.Log("Now feeding Dog");
}
There are still other ways to wait in Unity but you should definitely know the ones mentioned above as that makes it easier to make games in Unity. When to use each one depends on the circumstances.
For your particular issue, this is the solution:
IEnumerator showTextFuntion()
{
TextUI.text = "Welcome to Number Wizard!";
yield return new WaitForSeconds(3f);
TextUI.text = ("The highest number you can pick is " + max);
yield return new WaitForSeconds(3f);
TextUI.text = ("The lowest number you can pick is " + min);
}
And to call/start the coroutine function from your start or Update function, you call it with
StartCoroutine (showTextFuntion());
I made API sending data via form on website to prosperworks based on @Rocket Hazmat, @dbau and @maraca code. I hope, it will help somebody:
<?php
if(isset($_POST['submit'])) {
//form's fields name:
$name = $_POST['nameField'];
$email = $_POST['emailField'];
//API url:
$url = 'https://api.prosperworks.com/developer_api/v1/leads';
//JSON data(not exact, but will be compiled to JSON) file:
//add as many data as you need (according to prosperworks doc):
$data = array(
'name' => $name,
'email' => array('email' => $email)
);
//sending request (according to prosperworks documentation):
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n".
"X-PW-AccessToken: YOUR_TOKEN_HERE\r\n".
"X-PW-Application:developer_api\r\n".
"X-PW-UserEmail: YOUR_EMAIL_HERE\r\n",
'method' => 'POST',
'content' => json_encode($data)
)
);
//engine:
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
//compiling to JSON (as wrote above):
$resultData = json_decode($result, TRUE);
//display what was sent:
echo '<h2>Sent: </h2>';
echo $resultData['published'];
//dump var:
var_dump($result);
}
?>
<html>
<head>
</head>
<body>
<form action="" method="POST">
<h1><?php echo $msg; ?></h1>
Name: <input type="text" name="nameField"/>
<br>
Email: <input type="text" name="emailField"/>
<input type="submit" name="submit" value="Send"/>
</form>
</body>
</html>
Method 1:
df = df.withColumnRenamed("new_column_name", "old_column_name")
Method 2: If you want to do some computation and rename the new values
df = df.withColumn("old_column_name", F.when(F.col("old_column_name") > 1, F.lit(1)).otherwise(F.col("old_column_name"))
df = df.drop("new_column_name", "old_column_name")
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
Use watch to see when a variable is written to, rwatch when it is read and awatch when it is read/written from/to, as noted above. However, please note that to use this command, you must break the program, and the variable must be in scope when you've broken the program:
Use the watch command. The argument to the watch command is an expression that is evaluated. This implies that the variabel you want to set a watchpoint on must be in the current scope. So, to set a watchpoint on a non-global variable, you must have set a breakpoint that will stop your program when the variable is in scope. You set the watchpoint after the program breaks.
For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" />
element.
This question already mentions, and links to other Stack Overflow questions regarding this topic.
string = string.split("\\");
In JavaScript, the backslash is used to escape special characters, such as newlines (\n
). If you want to use a literal backslash, a double backslash has to be used.
So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\")
will show a dialog containing two backslashes.
For Visual Studio 2019 (v16.2.4) I was only able to find this file here:
C:\Users\\Documents\IISExpress\config\applicationhost.config
Hope this helps as I wasn't able to find the .vs folder location as mentioned in the above suggestions.
For iOS 13+
in SceneDelegate:
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options
connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: windowScene)
let storyboard = UIStoryboard(name: "Main", bundle: nil) // Where "Main" is the storyboard file name
let vc = storyboard.instantiateViewController(withIdentifier: "ViewController") // Where "ViewController" is the ID of your viewController
window?.rootViewController = vc
window?.makeKeyAndVisible()
}
Easy — just use Font Awesome 5's default fa-[size]x
classes. You can scale icons up to 10x of the parent element's font-size
Read the docs about icon sizing.
Examples:
<span class="fas fa-info-circle fa-6x"></span>
<span class="fas fa-info-circle fa-7x"></span>
<span class="fas fa-info-circle fa-8x"></span>
<span class="fas fa-info-circle fa-9x"></span>
<span class="fas fa-info-circle fa-10x"></span>
Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);
Yes, this is possible:
List<BigDecimal> bdList = new ArrayList<>();
//populate list
BigDecimal result = bdList.stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
What it does is:
List<BigDecimal>
.Stream<BigDecimal>
Call the reduce method.
3.1. We supply an identity value for addition, namely BigDecimal.ZERO
.
3.2. We specify the BinaryOperator<BigDecimal>
, which adds two BigDecimal
's, via a method reference BigDecimal::add
.
I see that you have added new data, therefore the new answer will become:
List<Invoice> invoiceList = new ArrayList<>();
//populate
Function<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());
BigDecimal result = invoiceList.stream()
.map(totalMapper)
.reduce(BigDecimal.ZERO, BigDecimal::add);
It is mostly the same, except that I have added a totalMapper
variable, that has a function from Invoice
to BigDecimal
and returns the total price of that invoice.
Then I obtain a Stream<Invoice>
, map it to a Stream<BigDecimal>
and then reduce it to a BigDecimal
.
Now, from an OOP design point I would advice you to also actually use the total()
method, which you have already defined, then it even becomes easier:
List<Invoice> invoiceList = new ArrayList<>();
//populate
BigDecimal result = invoiceList.stream()
.map(Invoice::total)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Here we directly use the method reference in the map
method.
I would prefer storing keys and values on separate arrays. This i often more practical. Structures of arrays are perfect replacement to array of structures. As most of the time you have to process only a subset of your data (in this cases keys or values, operation only with only one of the two arrays would be more efficient than operating with half of the two arrays together.
But in case this way is not possible, I would suggest to use arrays sorted by column instead of by row. In this way you would have the same benefit as having two arrays, but packed only in one.
import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
names = 0
values = 1
array = np.empty(shape=(2, len(result)), dtype=float)
array[names] = result.keys()
array[values] = result.values()
But my favorite is this (simpler):
import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}
arrays = {'names': np.array(result.keys(), dtype=float),
'values': np.array(result.values(), dtype=float)}
Compilation from jonearles' answer, http://kishantha.blogspot.com/2010/03/oracle-enterprise-manager-console.html and http://blog.flimatech.com/2011/07/17/changing-oracle-password-in-11g-using-alter-user-identified-by-values/ (Oracle 11g):
To stop this happening in the future do the following.
ALTER PROFILE DEFAULT LIMIT FAILED_LOGIN_ATTEMPTS UNLIMITED PASSWORD_LIFE_TIME UNLIMITED;
To reset users' status, run the query:
select
'alter user ' || su.name || ' identified by values'
|| ' ''' || spare4 || ';' || su.password || ''';'
from sys.user$ su
join dba_users du on ACCOUNT_STATUS like 'EXPIRED%' and su.name = du.username;
and execute some or all of the result set.
I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.
<?php
include 'nav.php';
/*
Download PhpMailer from the following link:
https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
Extract the PHPMailer-master folder into your xampp->htdocs folder
Make changes in the following code and its done :-)
You will receive the mail with the name Root User.
To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
And change the name here:
public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some //other folder
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP(); // telling the class to use SMTP
$rec1="[email protected]"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject = "Eventbook";
$mail->Body = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo //Fill in the document.location thing
'<script type="text/javascript">
if(confirm("Your mail has been sent"))
document.location = "/";
</script>';
}
?>
Updating the config didn't work for me, but I was able to edit the binding programmatically:
private YourAPIClient GetClient()
{
Uri baseAddress = new Uri(APIURL);
var binding = new BasicHttpBinding();
binding.MaxReceivedMessageSize = 20000000;
binding.MaxBufferSize = 20000000;
binding.MaxBufferPoolSize = 20000000;
binding.AllowCookies = true;
var readerQuotas = new XmlDictionaryReaderQuotas();
readerQuotas.MaxArrayLength = 20000000;
readerQuotas.MaxStringContentLength = 20000000;
readerQuotas.MaxDepth = 32;
binding.ReaderQuotas = readerQuotas;
if (baseAddress.Scheme.ToLower() == "https")
binding.Security.Mode = BasicHttpSecurityMode.Transport;
var client = new YourAPIClient(binding, new EndpointAddress(baseAddress));
return client;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.test {
background: #ff4040;
color: #fff;
display: block;
font-size: 15px;
}
</style>
</head>
<body>
<div class="test"> one </div>
<div class="test"> two </div>
<div class="test"> three </div>
<div class="test"> four </div>
<div class="test"> five </div>
<div class="test"> six </div>
<div class="test"> seven </div>
<div class="test"> eight </div>
<div class="test"> nine </div>
<div class="test"> ten </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//get total length by class
var numItems = $('.test').length;
//get last three count
var numItems3=numItems-3;
var i = 0;
$('.test').each(function(){
i++;
if(i>numItems3)
{
$(this).attr("class","");
}
})
});
</script>
</body>
</html>
You may also which to use aggregate initialization from a braced initialization list for situations like these.
#include <vector>
using namespace std;
struct subject {
string name;
int marks;
int credits;
};
int main() {
vector<subject> sub {
{"english", 10, 0},
{"math" , 20, 5}
};
}
Sometimes however, the members of a struct may not be so simple, so you must give the compiler a hand in deducing its types.
So extending on the above.
#include <vector>
using namespace std;
struct assessment {
int points;
int total;
float percentage;
};
struct subject {
string name;
int marks;
int credits;
vector<assessment> assessments;
};
int main() {
vector<subject> sub {
{"english", 10, 0, {
assessment{1,3,0.33f},
assessment{2,3,0.66f},
assessment{3,3,1.00f}
}},
{"math" , 20, 5, {
assessment{2,4,0.50f}
}}
};
}
Without the assessment
in the braced initializer the compiler will fail when attempting to deduce the type.
The above has been compiled and tested with gcc in c++17. It should however work from c++11 and onward. In c++20 we may see the designator syntax, my hope is that it will allow for for the following
{"english", 10, 0, .assessments{
{1,3,0.33f},
{2,3,0.66f},
{3,3,1.00f}
}},
source: http://en.cppreference.com/w/cpp/language/aggregate_initialization
In R, try:
x <- 'foo[bar]baz'
str_replace(x, ".*?\\[(.*?)\\].*", "\\1")
[1] "bar"
Definitely compact
is the best approach for solving this task. However, we can achieve the same result just with a simple subtraction:
[1, nil, 3, nil, nil] - [nil]
=> [1, 3]
In my opinion the simplest and most elegant way to achieve what you need is this:
ip route get 8.8.8.8 | tr -s ' ' | cut -d' ' -f7
ip route get [host]
- gives you the gateway used to reach a remote host e.g.:
8.8.8.8 via 192.168.0.1 dev enp0s3 src 192.168.0.109
tr -s ' '
- removes any extra spaces, now you have uniformity e.g.:
8.8.8.8 via 192.168.0.1 dev enp0s3 src 192.168.0.109
cut -d' ' -f7
- truncates the string into ' 'space separated fields, then selects the field #7 from it e.g.:
192.168.0.109
The shortest,
git config -l
shows all inherited values from: system, global and local
I feel your pain ... yet another date time format... just what you needed!
Using Web Api 2 you can use route attributes to specify parameters.
so with attributes on your class and your method you can code up a REST URL using this utc format you are having trouble with (apparently its ISO8601, presumably arrived at using startDate.toISOString())
[Route(@"daterange/{startDate:regex(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$)}/{endDate:regex(^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$)}")]
[HttpGet]
public IEnumerable<MyRecordType> GetByDateRange(DateTime startDate, DateTime endDate)
.... BUT, although this works with one date (startDate), for some reason it doesnt work when the endDate is in this format ... debugged for hours, only clue is exception says it doesnt like colon ":" (even though web.config is set with :
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" requestPathInvalidCharacters="" />
</system.web>
So, lets make another date format (taken from the polyfill for the ISO date format) and add it to the Javascript date (for brevity, only convert up to minutes):
if (!Date.prototype.toUTCDateTimeDigits) {
(function () {
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
Date.prototype.toUTCDateTimeDigits = function () {
return this.getUTCFullYear() +
pad(this.getUTCMonth() + 1) +
pad(this.getUTCDate()) +
'T' +
pad(this.getUTCHours()) +
pad(this.getUTCMinutes()) +
'Z';
};
}());
}
Then when you send the dates to the Web API 2 method, you can convert them from string to date:
[RoutePrefix("api/myrecordtype")]
public class MyRecordTypeController : ApiController
{
[Route(@"daterange/{startDateString}/{endDateString}")]
[HttpGet]
public IEnumerable<MyRecordType> GetByDateRange([FromUri]string startDateString, [FromUri]string endDateString)
{
var startDate = BuildDateTimeFromYAFormat(startDateString);
var endDate = BuildDateTimeFromYAFormat(endDateString);
...
}
/// <summary>
/// Convert a UTC Date String of format yyyyMMddThhmmZ into a Local Date
/// </summary>
/// <param name="dateString"></param>
/// <returns></returns>
private DateTime BuildDateTimeFromYAFormat(string dateString)
{
Regex r = new Regex(@"^\d{4}\d{2}\d{2}T\d{2}\d{2}Z$");
if (!r.IsMatch(dateString))
{
throw new FormatException(
string.Format("{0} is not the correct format. Should be yyyyMMddThhmmZ", dateString));
}
DateTime dt = DateTime.ParseExact(dateString, "yyyyMMddThhmmZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
return dt;
}
so the url would be
http://domain/api/myrecordtype/daterange/20140302T0003Z/20140302T1603Z
Hanselman gives some related info here:
http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?
Yes.. it is, take a look at this project. Websockets can easily handle HD videostreaming.. However, you should go for Adaptive Streaming. I explain here how you could implement it.
Currently we're working on a webbased instant messaging application with chat, filesharing and video/webcam support. With some bits and tricks we got streaming media through websockets (used HTML5 Media Capture to get the stream from our webcams).
You need to build a stream API
and a Media Stream Transceiver
to control the related media processing and transport.
It defines an XML Namespace.
In your example, the Namespace Prefix is "android" and the Namespace URI is "http://schemas.android.com/apk/res/android"
In the document, you see elements like: <android:foo />
Think of the namespace prefix as a variable with a short name alias for the full namespace URI. It is the equivalent of writing <http://schemas.android.com/apk/res/android:foo />
with regards to what it "means" when an XML parser reads the document.
NOTE: You cannot actually use the full namespace URI in place of the namespace prefix in an XML instance document.
Check out this tutorial on namespaces: http://www.sitepoint.com/xml-namespaces-explained/
An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.
function checkHttpStatus(url) {
$.ajax({
type: "GET",
data: {},
url: url,
error: function(response) {
alert(url + " returns a " + response.status);
}, success() {
alert(url + " Good link");
}
});
}
@throw([NSException exceptionWith…])
Xcode recognizes @throw
statements as function exit points, like return
statements. Using the @throw
syntax avoids erroneous "Control may reach end of non-void function" warnings that you may get from [NSException raise:…]
.
Also, @throw
can be used to throw objects that are not of class NSException.
I was also having a similar problem. Finally found one solution at https://techmeals.com/fe/questions/htmlcss/4/How-to-customize-the-select-drop-down-in-css-which-works-for-all-the-browsers
Note:
1) For Firefox support there is special CSS handling for SELECT element's parent, please take a closer look.
2) Download the down.png from Down.png
CSS code
/* For Firefox browser we need to style for SELECT element parent. */
@-moz-document url-prefix() {
/* Please note this is the parent of "SELECT" element */
.select-example {
background: url('https://techmeals.com/external/images/down.png');
background-color: #FFFFFF;
border: 1px solid #9e9e9e;
background-size: auto 6px;
background-repeat: no-repeat;
background-position: 96% 13px;
}
}
/* IE specific styles */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active)
{
select.my-select-box {
padding: 0 0 0 5px;
}
}
/* IE specific styles */
@supports (-ms-accelerator:true) {
select.my-select-box {
padding: 0 0 0 5px;
}
}
select.my-select-box {
outline: none;
background: #fff;
-moz-appearance: window;
-webkit-appearance: none;
border-radius: 0px;
text-overflow: "";
background-image: url('https://techmeals.com/external/images/down.png');
background-size: auto 6px;
background-repeat: no-repeat;
background-position: 96% 13px;
cursor: pointer;
height: 30px;
width: 100%;
border: 1px solid #9e9e9e;
padding: 0 15px 0 5px;
padding-right: 15px\9; /* This will be apllied only to IE 7, IE 8 and IE 9 as */
*padding-right: 15px; /* This will be apllied only to IE 7 and below. */
_padding-right: 15px; /* This will be apllied only to IE 6 and below. */
}
HTML code
<div class="select-example">
<select class="my-select-box">
<option value="1">First Option</option>
<option value="2">Second Option</option>
<option value="3">Third Option</option>
<option value="4">Fourth Option</option>
</select>
</div>
The Following:
.show-grid [class*="span"] {
means that all child elements of '.show-grid' with a class that CONTAINS the word 'span' in it will acquire those CSS properties.
<div class="show-grid">
<div class="span">.span</div>
<div class="span6">span6</div>
<div class="attention-span">attention</div>
<div class="spanish">spanish</div>
<div class="mariospan">mariospan</div>
<div class="espanol">espanol</div>
<div>
<div class="span">.span</div>
</div>
<p class="span">span</p>
<span class="span">I do GET HIT</span>
<span>I DO NOT GET HIT since I need a class of 'span'</span>
</div>
<div class="span">I DO NOT GET HIT since I'm outside of .show-grid</span>
All of the elements get hit except for the <span>
by itself.
In Regards to Bootstrap:
span6
: this was Bootstrap 2's scaffolding technique which divided a section into a horizontal grid, based on parts of 12. Thus span6
would have a width of 50%..col-*
classes (e.g. col-sm-6
), which also specifies a media breakpoint to handle responsiveness when the window shrinks below a certain size. Check Bootstrap 4.1 and Bootstrap 3.3.7 for more documentation. I would recommend going with a later Bootstrap nowadaysI found a pretty simple way to do this. Use a button to open it using an on click
listener to start the function openc()
, like this:
String fileloc;
private void openc()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try
{
f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
fileloc = Uri.fromFile(f)+"";
Log.d("texts", "openc: "+fileloc);
startActivityForResult(takePictureIntent, 3);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK) {
Log.d("texts", "onActivityResult: "+fileloc);
// fileloc is the uri of the file so do whatever with it
}
}
You can do whatever you want with the uri
location string. For instance, I send it to an image cropper to crop the image.
Look in your configuration file and search for the error_log setting. Or use phpinfo() to find this setting.
Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like
INSERT INTO HISTORICAL_CAR_STATS (
HISTORICAL_CAR_STATS_ID,
YEAR,
MONTH,
MAKE,
MODEL,
REGION,
AVG_MSRP,
CNT)
SELECT MY_SEQ.nextval,
year,
month,
make,
model,
region,
avg_msrp,
cnt
FROM (SELECT '2010' year,
'12' month,
'ALL' make,
'ALL' model,
REGION,
sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
sum(cnt) cnt
FROM HISTORICAL_CAR_STATS
WHERE YEAR = '2010'
AND MONTH = '12'
AND MAKE != 'ALL'
GROUP BY REGION)
If you are at the root of your working directory, you can do git checkout -- .
to check-out all files in the current HEAD and replace your local files.
You can also do git reset --hard
to reset your working directory and replace all changes (including the index).
In addition to @Aleksandr Tukallo's answer, you could also obtain the output and error message (if occurs). Compressing a folder using tar
is explained pretty well on the following answer.
import traceback
import subprocess
try:
cmd = ['tar', 'czfj', output_filename, file_to_archive]
output = subprocess.check_output(cmd).decode("utf-8").strip()
print(output)
except Exception:
print(f"E: {traceback.format_exc()}")
Based on Darren Cooks answer which also works if you moved your finger over another element.
See Find element finger is on during a touchend event
jQuery(function() {
FastClick.attach(document.body);
});
// Prevent sticky hover effects for buttons on touch devices
// From https://stackoverflow.com/a/17234319
//
//
// Usage:
// <a href="..." touch-focus-fix>..</a>
//
// Refactored from a directive for better performance and compability
jQuery(document.documentElement).on('touchend', function(event) {
'use strict';
function fix(sourceElement) {
var el = $(sourceElement).closest('[touch-focus-fix]')[0];
if (!el) {
return;
}
var par = el.parentNode;
var next = el.nextSibling;
par.removeChild(el);
par.insertBefore(el, next);
}
fix(event.target);
var changedTouch = event.originalEvent.changedTouches[0];
// http://www.w3.org/TR/2011/WD-touch-events-20110505/#the-touchend-event
if (!changedTouch) {
return;
}
var touchTarget = document.elementFromPoint(changedTouch.clientX, changedTouch.clientY);
if (touchTarget && touchTarget !== event.target) {
fix(touchTarget);
}
});
you can try something like this
set the parent to rotate
and the image to scale
so that the rotate
and scale
time can be different
div {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
width: 120px;_x000D_
height: 120px;_x000D_
margin: -60px 0 0 -60px;_x000D_
-webkit-animation: spin 2s linear infinite;_x000D_
}_x000D_
.image {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
width: 120px;_x000D_
height: 120px;_x000D_
margin: -60px 0 0 -60px;_x000D_
-webkit-animation: scale 4s linear infinite;_x000D_
}_x000D_
@-webkit-keyframes spin {_x000D_
100% {_x000D_
transform: rotate(180deg);_x000D_
}_x000D_
}_x000D_
@-webkit-keyframes scale {_x000D_
100% {_x000D_
transform: scale(2);_x000D_
}_x000D_
}
_x000D_
<div>_x000D_
<img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120" />_x000D_
</div>
_x000D_
You can set the image to be background image and have a transparent foreground image.
We can do that using @lru_cache
decorator and setrecursionlimit()
method:
import sys
from functools import lru_cache
sys.setrecursionlimit(15000)
@lru_cache(128)
def fib(n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
return fib(n - 2) + fib(n - 1)
print(fib(14000))
3002468761178461090995494179715025648692747937490792943468375429502230242942284835863402333575216217865811638730389352239181342307756720414619391217798542575996541081060501905302157019002614964717310808809478675602711440361241500732699145834377856326394037071666274321657305320804055307021019793251762830816701587386994888032362232198219843549865275880699612359275125243457132496772854886508703396643365042454333009802006384286859581649296390803003232654898464561589234445139863242606285711591746222880807391057211912655818499798720987302540712067959840802106849776547522247429904618357394771725653253559346195282601285019169360207355179223814857106405285007997547692546378757062999581657867188420995770650565521377874333085963123444258953052751461206977615079511435862879678439081175536265576977106865074099512897235100538241196445815568291377846656352979228098911566675956525644182645608178603837172227838896725425605719942300037650526231486881066037397866942013838296769284745527778439272995067231492069369130289154753132313883294398593507873555667211005422003204156154859031529462152953119957597195735953686798871131148255050140450845034240095305094449911578598539658855704158240221809528010179414493499583473568873253067921639513996596738275817909624857593693291980841303291145613566466575233283651420134915764961372875933822262953420444548349180436583183291944875599477240814774580187144637965487250578134990402443365677985388481961492444981994523034245619781853365476552719460960795929666883665704293897310201276011658074359194189359660792496027472226428571547971602259808697441435358578480589837766911684200275636889192254762678512597000452676191374475932796663842865744658264924913771676415404179920096074751516422872997665425047457428327276230059296132722787915300105002019006293320082955378715908263653377755031155794063450515731009402407584683132870206376994025920790298591144213659942668622062191441346200098342943955169522532574271644954360217472458521489671859465232568419404182043966092211744372699797375966048010775453444600153524772238401414789562651410289808994960533132759532092895779406940925252906166612153699850759933762897947175972147868784008320247586210378556711332739463277940255289047962323306946068381887446046387745247925675240182981190836264964640612069909458682443392729946084099312047752966806439331403663934969942958022237945205992581178803606156982034385347182766573351768749665172549908638337611953199808161937885366709285043276595726484068138091188914698151703122773726725261370542355162118164302728812259192476428938730724109825922331973256105091200551566581350508061922762910078528219869913214146575557249199263634241165352226570749618907050553115468306669184485910269806225894530809823102279231750061652042560772530576713148647858705369649642907780603247428680176236527220826640665659902650188140474762163503557640566711903907798932853656216227739411210513756695569391593763704981001125
PHP CLI SAPI is using different php.ini
than CGI or Apache module.
Find line ;extension=php_openssl.dll
in wamp/bin/php/php#.#.##/php.ini
and uncomment it by removing the semicolon (;
) from the beginning of the line.
This worked for me- -go to the report manager, check site settings-> Security -> New Role Assignment-> add the user
-Also, go to Datasets in report manager -> your report dataset -> Security -> New Role Assignment -> add the user with the required role.
Thanks!
document.getElementsByClassName('btn-pageMenu')
delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display
(if it's the first element from that list you want to change.
If you want to change style.display
for all nodes loop through the list:
var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
elems[i].style.display = 'block';
}
to be complete: if you use jquery it is as simple as:
?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????
template <typename T>
void remove(std::vector<T>& vec, size_t pos)
{
std::vector<T>::iterator it = vec.begin();
std::advance(it, pos);
vec.erase(it);
}
I may have a workaround.
Was having the same issue, where I am loading lots of items (via the file system) into a ListView
via an AsyncTask
. Had the onPreExecute()
firing up a ProgressDialog
, and then both onPostExecute()
and onCancelled()
(called when the task is cancelled explicitly via AsyncTask.cancel()
) closing it via .cancel()
.
Got the same "java.lang.IllegalArgumentException: View not attached to window manager" error when I was killing the dialog in the onCancelled()
method of the AsyncTask
(I'd seen this done in the excellent Shelves app).
The workaround was to create a public field in the AsyncTask
that contains the ProgressDialog
:
public ProgressDialog mDialog;
Then, in onDestroy()
when I cancel my AsyncTask
, I can also kill the associated dialog via:
AsyncTask.mDialog.cancel();
Calling AsyncTask.cancel()
DOES trigger onCancelled()
in the AsyncTask
, but for some reason by the time that method is called, the View has already been destroyed and thus cancelling the dialog is failing.
It prevents JSON hijacking, a major JSON security issue that is formally fixed in all major browsers since 2011 with ECMAScript 5.
Contrived example: say Google has a URL like mail.google.com/json?action=inbox
which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a <script>
tag. The URL is visited with your cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.
The while(1);
or &&&BLAH&&&
prevents this: an AJAX request at mail.google.com
will have full access to the text content, and can strip it away. But a <script>
tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.
This does not address the issue of cross-site request forgery.
One solution is to set tis widget color property to Colors.transparent. For instance:
IconButton(
icon: Image.asset("myImage.png",
color: Colors.transparent,
),
onPressed: () {},
),
Yes, Java bytecode (and source code) is platform independent, assuming you use platform independent libraries. 32 vs. 64 bit shouldn't matter.
Update
All modern browsers now support the unprefixed event:
element.addEventListener('transitionend', callback, false);
https://caniuse.com/#feat=css-transitions
I was using the approach given by Pete, however I have now started using the following
$(".myClass").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd',
function() {
//do something
});
Alternatively if you use bootstrap then you can simply do
$(".myClass").one($.support.transition.end,
function() {
//do something
});
This is becuase they include the following in bootstrap.js
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'transition' : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
$(function () {
$.support.transition = transitionEnd()
})
}(jQuery);
Note they also include an emulateTransitionEnd function which may be needed to ensure a callback always occurs.
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false, $el = this
$(this).one($.support.transition.end, function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
Be aware that sometimes this event doesn’t fire, usually in the case when properties don’t change or a paint isn’t triggered. To ensure we always get a callback, let’s set a timeout that’ll trigger the event manually.
Yet another solution (Monday is the first day):
select
to_char(sysdate - to_char(sysdate, 'd') + 2, 'yyyymmdd') first_day_of_week
, to_char(sysdate - to_char(sysdate, 'd') + 8, 'yyyymmdd') last_day_of_week
from
dual
UrlScan can also remove the server header by using AlternateServerName=
under [options]
.
import datetime
a = '2010-01-31'
datee = datetime.datetime.strptime(a, "%Y-%m-%d")
datee.month
Out[9]: 1
datee.year
Out[10]: 2010
datee.day
Out[11]: 31
Here's a much newer Kotlin solution for this which is much simpler than many of the answers written here, it uses anonymous class.
val items = mutableListOf<String>()
inner class ItemHolder(view: View): RecyclerView.ViewHolder(view) {
var textField: TextView = view.findViewById(android.R.id.text1) as TextView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
rvitems.layoutManager = LinearLayoutManager(context)
rvitems.adapter = object : RecyclerView.Adapter<ItemHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
return ItemHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
holder.textField.text = items[position]
holder.textField.setOnClickListener {
Toast.makeText(context, "Clicked $position", Toast.LENGTH_SHORT).show()
}
}
}
}
I took the liberty to use android.R.layout.simple_list_item_1 as it's simpler. I wanted to simplify it even further and put ItemHolder as an inner class but couldn't quite figure out how to reference it in a type in the outer class parameter.
I had this problem when running some script in cygwin. Fixed by running dos2unix
on the script, with proper description of problem and solution given in that answer
Here is an efficient solution when there is a large set of inputs (i.e. 25 to 30)
I made efficiency gains in two ways:
This solution works with negative numbers, decimal amounts, and repeated input values. Due to the wonky way that floating point decimal math works in most languages, you will want to keep your input set to only a few decimal places or you may have some unpredictable behavior.
On my old 2012-era desktop computer the given code processes 25 input values in about 0.8 seconds in javascript/node.js, and 3.4 seconds in C#.
let numbers = [-0.47, -0.35, -0.19, 0.23, 0.36, 0.47, 0.51, 0.59, 0.63, 0.79, 0.85,
0.91, 0.99, 1.02, 1.17, 1.25, 1.39, 1.44, 1.59, 1.60, 1.79, 1.88, 1.99, 2.14, 2.31];
let target = 24.16;
displaySubsetsThatSumTo(target, numbers);
function displaySubsetsThatSumTo(target, numbers)
{
let wheel = [0];
let resultsCount = 0;
let sum = 0;
const start = new Date();
do {
sum = incrementWheel(0, sum, numbers, wheel);
//Use subtraction comparison due to javascript float imprecision
if (sum != null && Math.abs(target - sum) < 0.000001) {
//Found a subset. Display the result.
console.log(numbers.filter(function(num, index) {
return wheel[index] === 1;
}).join(' + ') + ' = ' + target);
resultsCount++;
}
} while (sum != null);
const end = new Date();
console.log('--------------------------');
console.log(`Processed ${numbers.length} numbers in ${(end - start) / 1000} seconds (${resultsCount} results)`);
}
function incrementWheel(position, sum, numbers, wheel) {
if (position === numbers.length || sum === null) {
return null;
}
wheel[position]++;
if (wheel[position] === 2) {
wheel[position] = 0;
sum -= numbers[position];
if (wheel.length < position + 2) {
wheel.push(0);
}
sum = incrementWheel(position + 1, sum, numbers, wheel);
}
else {
sum += numbers[position];
}
return sum;
}
-----------------------------------------------------------------
Alternate, more efficient version using Gray Code binary counting
technique as suggested in comment
-----------------------------------------------------------------
const numbers = [-0.47, -0.35, -0.19, 0.23, 0.36, 0.47, 0.51,
0.59, 0.63, 0.79, 0.85, 0.91, 0.99, 1.02, 1.17, 1.25,
1.39, 1.44, 1.59, 1.60, 1.79, 1.88, 1.99, 2.14, 2.31];
const target = 24.16;
displaySubsetsThatSumTo(target, numbers);
function displaySubsetsThatSumTo(target, numbers)
{
let resultsCount = 0;
let sum = 0;
let wheel = []; //binary counter
let changeEvery = []; //how often each binary digit flips
let nextChange = []; //when each binary digit will next flip
for(let i = 0; i < numbers.length; i++) {
//Initialize wheel and wheel-update data. Using Gray Code binary counting technique,
// whereby only one binary digit in the wheel changes on each iteration. Then only
// a single sum operation is required each iteration.
wheel.push(0);
changeEvery.push(2 ** (numbers.length - i));
nextChange.push(2 ** (numbers.length - i - 1));
}
const start = new Date();
const numIterations = 2 ** numbers.length;
for (counter = 1; counter < numIterations; counter++) {
for (let i = nextChange.length - 1; i >= 0; i--) {
if(nextChange[i] === counter) {
nextChange[i] += changeEvery[i];
if (wheel[i] === 1) {
wheel[i] = 0;
sum -= numbers[i];
}
else {
wheel[i] = 1;
sum += numbers[i];
}
break;
}
}
//Use subtraction comparison due to javascript float imprecision
if (Math.abs(target - sum) < 0.000001) {
//Found a subset. Display the result.
console.log(numbers.filter((num, index) => wheel[index] === 1)
.join(' + ') + ' = ' + target);
resultsCount++;
}
}
const end = new Date();
console.log('--------------------------');
console.log(`Processed ${numbers.length} numbers in ${(end - start) / 1000} seconds (${resultsCount} results)`);
}
public class Program
{
static void Main(string[] args)
{
double[] numbers = { -0.47, -0.35, -0.19, 0.23, 0.36, 0.47, 0.51, 0.59, 0.63, 0.79, 0.85,
0.91, 0.99, 1.02, 1.17, 1.25, 1.39, 1.44, 1.59, 1.60, 1.79, 1.88, 1.99, 2.14, 2.31 };
double target = 24.16;
DisplaySubsetsThatSumTo(target, numbers);
}
private static void DisplaySubsetsThatSumTo(double Target, double[] numbers)
{
var stopwatch = new System.Diagnostics.Stopwatch();
bool[] wheel = new bool[numbers.Length];
int resultsCount = 0;
double? sum = 0;
stopwatch.Start();
do
{
sum = IncrementWheel(0, sum, numbers, wheel);
//Use subtraction comparison due to double type imprecision
if (sum.HasValue && Math.Abs(sum.Value - Target) < 0.000001F)
{
//Found a subset. Display the result.
Console.WriteLine(string.Join(" + ", numbers.Where((n, idx) => wheel[idx])) + " = " + Target);
resultsCount++;
}
} while (sum != null);
stopwatch.Stop();
Console.WriteLine("--------------------------");
Console.WriteLine($"Processed {numbers.Length} numbers in {stopwatch.ElapsedMilliseconds / 1000.0} seconds ({resultsCount} results). Press any key to exit.");
Console.ReadKey();
}
private static double? IncrementWheel(int Position, double? Sum, double[] numbers, bool[] wheel)
{
if (Position == numbers.Length || !Sum.HasValue)
{
return null;
}
wheel[Position] = !wheel[Position];
if (!wheel[Position])
{
Sum -= numbers[Position];
Sum = IncrementWheel(Position + 1, Sum, numbers, wheel);
}
else
{
Sum += numbers[Position];
}
return Sum;
}
}
-0.35 + 0.23 + 0.36 + 0.47 + 0.51 + 0.59 + 0.63 + 0.79 + 0.85 + 0.91 + 0.99 + 1.02 + 1.17 + 1.25 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
0.23 + 0.51 + 0.59 + 0.63 + 0.79 + 0.85 + 0.99 + 1.02 + 1.17 + 1.25 + 1.39 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
-0.47 + 0.23 + 0.47 + 0.51 + 0.59 + 0.63 + 0.79 + 0.85 + 0.99 + 1.02 + 1.17 + 1.25 + 1.39 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
-0.19 + 0.36 + 0.51 + 0.59 + 0.63 + 0.79 + 0.91 + 0.99 + 1.02 + 1.17 + 1.25 + 1.39 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
-0.47 + -0.19 + 0.36 + 0.47 + 0.51 + 0.59 + 0.63 + 0.79 + 0.91 + 0.99 + 1.02 + 1.17 + 1.25 + 1.39 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
0.23 + 0.47 + 0.51 + 0.63 + 0.85 + 0.91 + 0.99 + 1.02 + 1.17 + 1.25 + 1.39 + 1.44 + 1.59 + 1.6 + 1.79 + 1.88 + 1.99 + 2.14 + 2.31 = 24.16
--------------------------
Processed 25 numbers in 0.823 seconds (6 results)
You need to loop over loadDT.Columns
, like this:
foreach (DataColumn column in loadDT.Columns)
{
Console.Write("Item: ");
Console.Write(column.ColumnName);
Console.Write(" ");
Console.WriteLine(row[column]);
}
Take a look at Enumerable#each_slice:
foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
If time_created is a unix timestamp (int), you should be able to use something like this:
DELETE FROM locks WHERE time_created < (UNIX_TIMESTAMP() - 600);
(600 seconds = 10 minutes - obviously)
Otherwise (if time_created is mysql timestamp), you could try this:
DELETE FROM locks WHERE time_created < (NOW() - INTERVAL 10 MINUTE)
Or if you're using EnterpriseLibrary rather than standard ADO.NET...
Database db = DatabaseFactory.CreateDatabase();
using (DbCommand cmd = db.GetStoredProcCommand("usp_GetNewSeqVal"))
{
db.AddInParameter(cmd, "SeqName", DbType.String, "SeqNameValue");
db.AddParameter(cmd, "RetVal", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);
db.ExecuteNonQuery(cmd);
var result = (int)cmd.Parameters["RetVal"].Value;
}
I know that the question has been answered, but I hope my solution helps other people.
stopPropagation
caused problems in my case, because I needed the click
event for something else. Moreover, not every element should cause the div to be closed when clicked.
My solution:
$(document).click(function(e) {
if (($(e.target).closest("#mydiv").attr("id") != "mydiv") &&
$(e.target).closest("#div-exception").attr("id") != "div-exception") {
alert("Clicked outside!");
}
});
May be the link will Help bcz u might have to implement the code in Appdelegate in app run in background method .. Also consult the developer.apple.com site for application class Here is link for runing app in background
The issue is it is missing Dynamic Web Module facet definition. Run the following at command line
mvn eclipse:eclipse -Dwtpversion=2.0
After build is success, refresh the project and you will be add the web project to server.
An addition to the other answers that didn't work for me: In my case the error occurred due to permission errors. The project got deployed while the tomcat was running as root, later when started as tomcat user I got the error from the question title.
Solution in my case was to set the right permissions, e.x. on a unix system:
cd <tomcat-dir>
chown -R <tomcat-user> *
For number input or numeric keyboard you can use keyboardType: TextInputType.number
TextFormField(
decoration: InputDecoration(labelText:'Amount'),
controller: TextEditingController(
),
validator: (value) {
if (value.isEmpty) {
return 'Enter Amount';
}
},
keyboardType: TextInputType.number
)
check this if it works it works fine for me
<script>
var windowObjectReference;
var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width=400,height=350";
function openRequestedPopup() {
windowObjectReference = window.open("http://www.flyingedge.in/", "CNN_WindowName", strWindowFeatures);
}
</script>
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
If you want to remove all -
you can use:
.replace(new RegExp('-', 'g'),"")
As Kaboing mentioned, MAXDOP(n)
actually controls the number of CPU cores that are being used in the query processor.
On a completely idle system, SQL Server will attempt to pull the tables into memory as quickly as possible and join between them in memory. It could be that, in your case, it's best to do this with a single CPU. This might have the same effect as using OPTION (FORCE ORDER)
which forces the query optimizer to use the order of joins that you have specified. IN some cases, I have seen OPTION (FORCE PLAN)
reduce a query from 26 seconds to 1 second of execution time.
Books Online goes on to say that possible values for MAXDOP
are:
0 - Uses the actual number of available CPUs depending on the current system workload. This is the default value and recommended setting.
1 - Suppresses parallel plan generation. The operation will be executed serially.
2-64 - Limits the number of processors to the specified value. Fewer processors may be used depending on the current workload. If a value larger than the number of available CPUs is specified, the actual number of available CPUs is used.
I'm not sure what the best usage of MAXDOP
is, however I would take a guess and say that if you have a table with 8 partitions on it, you would want to specify MAXDOP(8)
due to I/O limitations, but I could be wrong.
Here are a few quick links I found about MAXDOP
:
In Windows you can use a Powershell Script with CompareObject
compare-object -IncludeEqual -ExcludeDifferent -PassThru (get-content A.txt) (get-content B.txt)> MATCHING.txt | Out-Null #Find Matching Lines
CompareObject:
In addition to kieran's answer, apparently, modern browsers have an Object.keys
function. In this case, you could do this:
Object.keys(jsonArray).length;
More details in this answer on How to list the properties of a javascript object
So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :
var values = {name: 'misko', gender: 'male'};
Angular will take each value one by one the first one is name, the second is gender.
If your object to iterate on is an array (also possible), like this :
[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
{ "Name" : "Linda", "Password" : "lindatheQueen" }]
Angular.forEach will take one by one starting by the first object, then the second object.
For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :
var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male
So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'
If this time you display an array, like this :
var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
{ "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]
So then value is your object (collection), and key is the index of your array since :
[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
{ "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
1: { "Name" : "Linda", "Password" : "lindatheQueen" }}
I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/
The problem seems to come from the fact $http.get()
is an asynchronous request.
You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach
without waiting the answer of your JSON.
You need to include the loop in the success function
var app = angular.module('testModule', [])
.controller('testController', ['$scope', '$http', function($scope, $http){
$http.get('Data/info.json').then(function(data){
$scope.data = data;
angular.forEach($scope.data, function(value, key){
if(value.Password == "thomasTheKing")
console.log("username is thomas");
});
});
});
This should work.
The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.
You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.
Based on Haim's answer I created a PHP code to test and display all the differences between two databases. This will also display if a table is present in source or test databases. You have to change with your details the <> variables content.
<?php
$User = "<DatabaseUser>";
$Pass = "<DatabasePassword>";
$SourceDB = "<SourceDatabase>";
$TestDB = "<DatabaseToTest>";
$link = new mysqli( "p:". "localhost", $User, $Pass, "" );
if ( mysqli_connect_error() ) {
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
mysqli_set_charset( $link, "utf8" );
mb_language( "uni" );
mb_internal_encoding( "UTF-8" );
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $SourceDB .'";';
$SourceDB_Content = query( $link, $sQuery );
if ( !is_array( $SourceDB_Content) ) {
echo "Table $SourceDB cannot be accessed";
exit(0);
}
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $TestDB .'";';
$TestDB_Content = query( $link, $sQuery );
if ( !is_array( $TestDB_Content) ) {
echo "Table $TestDB cannot be accessed";
exit(0);
}
$SourceDB_Tables = array();
foreach( $SourceDB_Content as $item ) {
$SourceDB_Tables[] = $item["TABLE_NAME"];
}
$TestDB_Tables = array();
foreach( $TestDB_Content as $item ) {
$TestDB_Tables[] = $item["TABLE_NAME"];
}
//var_dump( $SourceDB_Tables, $TestDB_Tables );
$LookupTables = array_merge( $SourceDB_Tables, $TestDB_Tables );
$NoOfDiscrepancies = 0;
echo "
<table border='1' width='100%'>
<tr>
<td>Table</td>
<td>Found in $SourceDB (". count( $SourceDB_Tables ) .")</td>
<td>Found in $TestDB (". count( $TestDB_Tables ) .")</td>
<td>Test result</td>
<tr>
";
foreach( $LookupTables as $table ) {
$FoundInSourceDB = in_array( $table, $SourceDB_Tables ) ? 1 : 0;
$FoundInTestDB = in_array( $table, $TestDB_Tables ) ? 1 : 0;
echo "
<tr>
<td>$table</td>
<td><input type='checkbox' ". ($FoundInSourceDB == 1 ? "checked" : "") ."></td>
<td><input type='checkbox' ". ($FoundInTestDB == 1 ? "checked" : "") ."></td>
<td>". compareTables( $SourceDB, $TestDB, $table ) ."</td>
</tr>
";
}
echo "
</table>
<br><br>
No of discrepancies found: $NoOfDiscrepancies
";
function query( $link, $q ) {
$result = mysqli_query( $link, $q );
$errors = mysqli_error($link);
if ( $errors > "" ) {
echo $errors;
exit(0);
}
if( $result == false ) return false;
else if ( $result === true ) return true;
else {
$rset = array();
while ( $row = mysqli_fetch_assoc( $result ) ) {
$rset[] = $row;
}
return $rset;
}
}
function compareTables( $source, $test, $table ) {
global $link;
global $NoOfDiscrepancies;
$sQuery = "
SELECT column_name,ordinal_position,data_type,column_type FROM
(
SELECT
column_name,ordinal_position,
data_type,column_type,COUNT(1) rowcount
FROM information_schema.columns
WHERE
(
(table_schema='$source' AND table_name='$table') OR
(table_schema='$test' AND table_name='$table')
)
AND table_name IN ('$table')
GROUP BY
column_name,ordinal_position,
data_type,column_type
HAVING COUNT(1)=1
) A;
";
$result = query( $link, $sQuery );
$data = "";
if( is_array( $result ) && count( $result ) > 0 ) {
$NoOfDiscrepancies++;
$data = "<table><tr><td>column_name</td><td>ordinal_position</td><td>data_type</td><td>column_type</td></tr>";
foreach( $result as $item ) {
$data .= "<tr><td>". $item["column_name"] ."</td><td>". $item["ordinal_position"] ."</td><td>". $item["data_type"] ."</td><td>". $item["column_type"] ."</td></tr>";
}
$data .= "</table>";
return $data;
}
else {
return "Checked but no discrepancies found!";
}
}
?>
The is not
operator is preferred over negating the result of is
for stylistic reasons. "if x is not None:
" reads just like English, but "if not x is None:
" requires understanding of the operator precedence and does not read like english.
If there is a performance difference my money is on is not
, but this almost certainly isn't the motivation for the decision to prefer that technique. It would obviously be implementation-dependent. Since is
isn't overridable, it should be easy to optimise out any distinction anyhow.
Use OnClicklistener
or you can use android:onClick="myMethod"
in your button's xml code from which you going to open a new layout. So when that button is clicked your myMethod function will be called automatically. Your myMethod
function in class look like this.
public void myMethod(View v) {
Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
}
And in that SecondActivity.class set new layout in contentview.
You can try this way:-
Give a class say header
to the header rows, use nextUntil to get all rows beneath the clicked header until the next header.
$('.header').click(function(){
$(this).nextUntil('tr.header').slideToggle(1000);
});
<table border="0">
<tr class="header">
<td colspan="2">Header</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
Another Example:
$('.header').click(function(){
$(this).find('span').text(function(_, value){return value=='-'?'+':'-'});
$(this).nextUntil('tr.header').slideToggle(100); // or just use "toggle()"
});
You can also use promise to toggle the span icon/text after the toggle is complete in-case of animated toggle.
$('.header').click(function () {
var $this = $(this);
$(this).nextUntil('tr.header').slideToggle(100).promise().done(function () {
$this.find('span').text(function (_, value) {
return value == '-' ? '+' : '-'
});
});
});
Or just with a css pseudo element to represent the sign of expansion/collapse, and just toggle a class on the header.
CSS:-
.header .sign:after{
content:"+";
display:inline-block;
}
.header.expand .sign:after{
content:"-";
}
JS:-
$(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
try as this code.
$.ajax({
type: "POST",
url: "http://rt.ja.com/includes/register.php?submit=1",
data: "username="+username+"&email="+email+"&password="+password+"&passconf="+passconf,
success: function(html)
{
//alert(html);
$('#userError').html(html);
$("#userError").html(userChar);
$("#userError").html(userTaken);
}
});
i think this will work definitely..
you can also use .serialize() function for sending data via jquery Ajax..
i.e: data : $("#registerSubmit").serialize()
Thanks.
I'm afraid you can't easily do an in-place sort of a DataTable like it sounds like you want to do.
What you can do is create a new DataTable from a DataView that you create from your original DataTable. Apply whatever sorts and/or filters you want on the DataView and then create a new DataTable from the DataView using the DataView.ToTable method:
DataView dv = ft.DefaultView;
dv.Sort = "occr desc";
DataTable sortedDT = dv.ToTable();
You just need to annotate your service class UserServiceImpl
with annotation:
@Service("userService")
Spring container will take care of the life cycle of this class as it register as service.
Then in your controller you can auto wire (instantiate) it and use its functionality:
@Autowired
UserService userService;
I find that Wikipedia can be a great source of information about such tools, especially for comparison tables. There's a page on UML tools. See in particular the reverse engineered languages column.
Basically the same solution as provided by Rutger Kassies, but using a more pythonic syntax:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
data = np.arange(250, 260)
for ax, d in zip(axs.ravel(), data):
ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
ax.set_title(str(d))
To get Ant running on your Mac in 5 minutes, follow these steps.
Open up your terminal.
Perform these commands in order:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install ant
If you don't have Java installed yet, you will get the following error: "Error: An unsatisfied requirement failed this build."
Run this command next: brew cask install java
to fix this.
The installation will resume.
Check your version of by running this command:
ant -version
And you're ready to go!
The answer here(scrolling in $(document).ready
) doesn't work if there is a video in the page. In that case the page is scrolled after this event is fired, overriding our work.
Best answer should be:
$(window).on('beforeunload', function(){
$(window).scrollTop(0);
});
I am using android studio 2.2.3 and I am able to change theme by following steps