I had the same problem, and came up with a template that uses lockfile, a pid file that holds the process id number, and a kill -0 $(cat $pid_file)
check to make aborted scripts not stop the next run.
This creates a foobar-$USERID folder in /tmp where the lockfile and pid file lives.
You can still call the script and do other things, as long as you keep those actions in alertRunningPS
.
#!/bin/bash
user_id_num=$(id -u)
pid_file="/tmp/foobar-$user_id_num/foobar-$user_id_num.pid"
lock_file="/tmp/foobar-$user_id_num/running.lock"
ps_id=$$
function alertRunningPS () {
local PID=$(cat "$pid_file" 2> /dev/null)
echo "Lockfile present. ps id file: $PID"
echo "Checking if process is actually running or something left over from crash..."
if kill -0 $PID 2> /dev/null; then
echo "Already running, exiting"
exit 1
else
echo "Not running, removing lock and continuing"
rm -f "$lock_file"
lockfile -r 0 "$lock_file"
fi
}
echo "Hello, checking some stuff before locking stuff"
# Lock further operations to one process
mkdir -p /tmp/foobar-$user_id_num
lockfile -r 0 "$lock_file" || alertRunningPS
# Do stuff here
echo -n $ps_id > "$pid_file"
echo "Running stuff in ONE ps"
sleep 30s
rm -f "$lock_file"
rm -f "$pid_file"
exit 0
You can either use what SiegeX said above or if you aren't interested in learning/using parameter expansion, you can use:
for filename in $(ls /home/user/);
do
echo $filename
done;
An example of how to implement it:
public bool ValidateSocialSecNumber(string socialSecNumber)
{
//Accepts only 10 digits, no more no less. (Like Mike's answer)
Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)");
if(pattern.isMatch(socialSecNumber))
{
//Do something
return true;
}
else
{
return false;
}
}
You could've also done it in another way by e.g. using Match
and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.
To resize the existing volume mounted
sudo mount -t xfs /dev/sdf /opt/data/
mount: /opt/data: /dev/nvme1n1 already mounted on /opt/data.
sudo xfs_growfs /opt/data/
For line chart, I use the following codes.
First create custom style
.boxx{
position: relative;
width: 20px;
height: 20px;
border-radius: 3px;
}
Then add this on your line options
var lineOptions = {
legendTemplate : '<table>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<tr><td><div class=\"boxx\" style=\"background-color:<%=datasets[i].fillColor %>\"></div></td>'
+'<% if (datasets[i].label) { %><td><%= datasets[i].label %></td><% } %></tr><tr height="5"></tr>'
+'<% } %>'
+'</table>',
multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"
var ctx = document.getElementById("lineChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
document.getElementById('legendDiv').innerHTML = myNewChart.generateLegend();
Don't forget to add
<div id="legendDiv"></div>
on your html where do you want to place your legend. That's it!
If you are adding it as a VM argument, make sure you prefix it with -D
:
-Djava.library.path=blahblahblah...
Go to your dashboard on heroku. Select the app. There is a dynos section. Just pull the sliders for the dynos down, (a decrease in dynos is to the left), to the number of dynos you want to be running. The slider goes to 0. Then save your changes. Boom.
According to the comment below: there is a pencil icon that needs to be clicked to accomplish this. I have not checked - but am putting it here in case it helps.
import groovyx.net.http.HTTPBuilder;
public class HttpclassgetrRoles {
static void main(String[] args){
def baseUrl = new URL('http://test.city.com/api/Cirtxyz/GetUser')
HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
connection.addRequestProperty("Accept", "application/json")
connection.with {
doOutput = true
requestMethod = 'GET'
println content.text
}
}
}
The script manager must be put onto the page before it is used. This would be directly on the page itself, or alternatively, if you are using them, on the Master Page.
The markup would be;
<asp:ScriptManager ID="ScriptManager1" runat="server" LoadScriptsBeforeUI="true"
EnablePartialRendering="true" />
As mentioned in one of the other answers, you can use putc(int c, FILE *stream), putchar(int c) or fputc(int c, FILE *stream) for this purpose.
What's important to note is that using any of the above functions is from some to signicantly faster than using any of the format-parsing functions like printf.
Using printf is like using a machine gun to fire one bullet.
You are going to have to expose and endpoint (URL) in your system which will accept the POST request from the ajax call in jQuery.
Then, when processing that url from PHP, you would call your function and return the result in the appropriate format (JSON most likely, or XML if you prefer).
Depending on the schema/account you are using to connect to the database, I would suspect you are missing a grant to the account you are using to connect to the database.
Connect as PCT account in the database, then grant the account you are using select access for the table.
grant select on pi_int to Account_used_to_connect
Please find the code below for Vlookup
:
Function vlookupVBA(lookupValue, rangeString, colOffset)
vlookupVBA = "#N/A"
On Error Resume Next
Dim table_lookup As range
Set table_lookup = range(rangeString)
vlookupVBA = Application.WorksheetFunction.vlookup(lookupValue, table_lookup, colOffset, False)
End Function
For systemd style init scripts it's really easy. You just add a User= in the [Service] section.
Here is an init script I use for qbittorrent-nox on CentOS 7:
[Unit]
Description=qbittorrent torrent server
[Service]
User=<username>
ExecStart=/usr/bin/qbittorrent-nox
Restart=on-abort
[Install]
WantedBy=multi-user.target
Your specific case can simply be corrected to be working:
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function() { alert(myMessage); };
</script>
This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.
For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there
I suppose that have you noticed that your link is actually an HTTPS link.... It seems that CURL parameters do not include any kind of SSH handling... maybe this could be your problem. Why don't you try with a non-HTTPS link to see what happens (i.e Google Custom Search Engine)...?
You can set the minlength
option to some big value or you can do it by css like this,
.ui-autocomplete { height: 200px; overflow-y: scroll; overflow-x: hidden;}
Change the profiles parameter to "commandline": "%PROGRAMFILES%\\Git\\bin\\bash.exe -l -i"
This works for me and allows for my .bash_profile alias autocomplete scripts to run.
All you have to do set a variable for x then just type this in before the return 0;
cout<<"\nPress any key and hit enter to end...";
cin>>x;
If you use NetBeans IDE right click form then
Properties ->Code -> check out Generate Center
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
This is behavior specified in the Java API's String.valueOf(Object)
method. When you do concatenation, valueOf
is used to get the String
representation. There is a special case if the Object is null
, in which case the string "null"
is used.
public static String valueOf(Object obj)
Returns the string representation of the Object argument.
Parameters: obj - an Object.
Returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
This code defines a function fixed_sum_digits
returning a generator enumerating all six digits numbers such that the sum of digits is 20.
def iter_fun(sum, deepness, myString, Total):
if deepness == 0:
if sum == Total:
yield myString
else:
for i in range(min(10, Total - sum + 1)):
yield from iter_fun(sum + i,deepness - 1,myString + str(i),Total)
def fixed_sum_digits(digits, Tot):
return iter_fun(0,digits,"",Tot)
Try to write it without yield from
. If you find an effective way to do it let me know.
I think that for cases like this one: visiting trees, yield from
makes the code simpler and cleaner.
We can add scroll bar even without using Canvas. I have read it in many other post we can't add vertical scroll bar in frame directly etc etc. But after doing many experiment found out way to add vertical as well as horizontal scroll bar :). Please find below code which is used to create scroll bar in treeView and frame.
f = Tkinter.Frame(self.master,width=3)
f.grid(row=2, column=0, columnspan=8, rowspan=10, pady=30, padx=30)
f.config(width=5)
self.tree = ttk.Treeview(f, selectmode="extended")
scbHDirSel =tk.Scrollbar(f, orient=Tkinter.HORIZONTAL, command=self.tree.xview)
scbVDirSel =tk.Scrollbar(f, orient=Tkinter.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scbVDirSel.set, xscrollcommand=scbHDirSel.set)
self.tree["columns"] = (self.columnListOutput)
self.tree.column("#0", width=40)
self.tree.heading("#0", text='SrNo', anchor='w')
self.tree.grid(row=2, column=0, sticky=Tkinter.NSEW,in_=f, columnspan=10, rowspan=10)
scbVDirSel.grid(row=2, column=10, rowspan=10, sticky=Tkinter.NS, in_=f)
scbHDirSel.grid(row=14, column=0, rowspan=2, sticky=Tkinter.EW,in_=f)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)
I tend to use explicit interface implementation when I want to discourage "programming to an implementation" (Design Principles from Design Patterns).
For example, in an MVP-based web application:
public interface INavigator {
void Redirect(string url);
}
public sealed class StandardNavigator : INavigator {
void INavigator.Redirect(string url) {
Response.Redirect(url);
}
}
Now another class (such as a presenter) is less likely to depend on the StandardNavigator implementation and more likely to depend on the INavigator interface (since the implementation would need to be cast to an interface to make use of the Redirect method).
Another reason I might go with an explicit interface implementation would be to keep a class's "default" interface cleaner. For example, if I were developing an ASP.NET server control, I might want two interfaces:
A simple example follows. It's a combo box control that lists customers. In this example, the web page developer isn't interested in populating the list; instead, they just want to be able to select a customer by GUID or to obtain the selected customer's GUID. A presenter would populate the box on the first page load, and this presenter is encapsulated by the control.
public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {
private readonly CustomerComboBoxPresenter presenter;
public CustomerComboBox() {
presenter = new CustomerComboBoxPresenter(this);
}
protected override void OnLoad() {
if (!Page.IsPostBack) presenter.HandleFirstLoad();
}
// Primary interface used by web page developers
public Guid ClientId {
get { return new Guid(SelectedItem.Value); }
set { SelectedItem.Value = value.ToString(); }
}
// "Hidden" interface used by presenter
IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }
}
The presenter populates the data source, and the web page developer never needs to be aware of its existence.
I wouldn't recommend always employing explicit interface implementations. Those are just two examples where they might be helpful.
This issue is caused by the pipeline mode in your Application Pool setting that your web site is set to.
Short
Simple way (bad practice) Add the following to your web.config. See http://www.iis.net/ConfigReference/system.webServer/validation
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Long If possible, your best bet is to change your application to support the integrated pipelines. There are a number of changes between IIS6 and IIS7.x that will cause this error. You can find details about these changes here http://learn.iis.net/page.aspx/381/aspnet-20-breaking-changes-on-iis-70/.
If you're unable to do that, you'll need to change the App pool which may be more difficult to do depending on your availability to the web server.
Check http://technet.microsoft.com/en-us/library/cc731755(WS.10).aspx for details on changing the App Pool
If you need to create an App Pool with Classic pipelines, take a look at http://technet.microsoft.com/en-us/library/cc731784(WS.10).aspx
If you don't have access to the server to make this change, you'll need to do this through your hosting server and contact them for help.
Feel free to ask questions.
This usually works as well :)
navigateUpTo(new Intent(getBaseContext(), MainActivity.class));
I modified klaus se's method because while it was working for me with small lists, it would hang when the number of items was ~1000 or greater. Instead of pushing the jobs one at a time with the None
stop condition, I load up the input queue all at once and just let the processes munch on it until it's empty.
from multiprocessing import cpu_count, Queue, Process
def apply_func(f, q_in, q_out):
while not q_in.empty():
i, x = q_in.get()
q_out.put((i, f(x)))
# map a function using a pool of processes
def parmap(f, X, nprocs = cpu_count()):
q_in, q_out = Queue(), Queue()
proc = [Process(target=apply_func, args=(f, q_in, q_out)) for _ in range(nprocs)]
sent = [q_in.put((i, x)) for i, x in enumerate(X)]
[p.start() for p in proc]
res = [q_out.get() for _ in sent]
[p.join() for p in proc]
return [x for i,x in sorted(res)]
Edit: unfortunately now I am running into this error on my system: Multiprocessing Queue maxsize limit is 32767, hopefully the workarounds there will help.
Let's say you have a master
branch with files/directories:
> git branch
master
> ls -la # (files and dirs which you may keep in master)
.git
directory1
directory2
file_1
..
file_n
git checkout —orphan new_branch_name
ls -la |awk '{print $9}' |grep -v git |xargs -I _ rm -rf ./_
git rm -rf .
touch new_file
git add new_file
git commit -m 'added first file in the new branch'
git push origin new_branch_name
In step 2, we simply remove all the files locally to avoid confusion with the files on your new branch and those ones you keep in master
branch.
Then, we unlink all those files in step 3. Finally, step 4 and after are working with our new empty branch.
Once you're done, you can easily switch between your branches:
git checkout master
git checkout new_branch
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent we) {
Platform.setImplicitExit(false);
stage.close();
}
});
It is equivalent to hide
. So when you are going to open it next time, you just check if the stage
object is exited or not. If it is exited, you just show()
i.e. (stage.show())
call. Otherwise, you have to start the stage.
Use this script
<script type="text/javascript">
window.onload = function() { window.print(); }
</script>
Here is an alternative that worked for me:
$('div#somediv').css({'width': '70%'});
The reliable solution is catching the ObjectDisposedException.
The solution to write your overridden implementation of the Dispose method doesn't work, since there is a race condition between the thread calling Dispose method and the one accessing to the object: after having checked the hypothetic IsDisposed property , the object could be really disposed, throwing the exception all the same.
Another approach could be exposing a hypothetic event Disposed (like this), which is used to notify about the disposing object to every object interested, but this could be difficoult to plan depending on the software design.
Solution using just POST - no $_SESSION
page1.php
<form action="page2.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
page2.php
<?php
// this page outputs the contents of the textarea if posted
$textarea1 = ""; // set var to avoid errors
if(isset($_POST['textarea1'])){
$textarea1 = $_POST['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
Solution using $_SESSION and POST
page1.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
$textarea1 = "";
if(isset($_POST['textarea1'])){
$_SESSION['textarea1'] = $_POST['textarea1'];
}
?>
<form action="page1.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>
page2.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
// this page outputs the textarea1 from the session IF it exists
$textarea1 = ""; // set var to avoid errors
if(isset($_SESSION['textarea1'])){
$textarea1 = $_SESSION['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
WARNING!!! - This contains no validation!!!
All answers are quite old. Since the beginning of 2013 Mongoose started to support promises gradually for all queries, so that would be the recommended way of structuring several async calls in the required order going forward I guess.
jQuery offers the .hide() method for this purpose. Simply select the element of your choice and call this method afterward. For example:
$('#comanda').hide();
One can also determine how fast the transition runs by providing a duration parameter in miliseconds or string (possible values being 'fast', and 'slow'):
$('#comanda').hide('fast');
In case you want to do something just after the element hid, you must provide a callback as a parameter too:
$('#comanda').hide('fast', function() {
alert('It is hidden now!');
});
In navigateExtra we can pass only some specific name as argument otherwise it showing error like below: For Ex- Here I want to pass customer key in router navigate and I pass like this-
this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});
but it showing some error like below:
Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'
.
Solution: we have to write like this:
this.Router.navigate(['componentname'],{state: {customerkey:response.key}});
Maybe just "border-width" instead of "border-weight"? There is no "border-weight" and this property is just ignored and default width is used instead.
You should not rely on a hard coded build dir name in your script, so the line with ../Compile
must be changed.
It's because it should be up to user where to compile.
Instead of that use one of predefined variables:
http://www.cmake.org/Wiki/CMake_Useful_Variables
(look for CMAKE_BINARY_DIR
and CMAKE_CURRENT_BINARY_DIR
)
A lot of answers are missing the point - most developers are well aware that turning off the cache is inefficient. However, there are many common circumstances where efficiency is unimportant and default cache behavior is badly broken.
These include nested, iterative script testing (the big one!) and broken third party software workarounds. None of the solutions given here are adequate to address such common scenarios. Most web browsers are far too aggressive caching and provide no sensible means to avoid these problems.
Normally you should use __cplusplus
define to detect c++17, but by default microsoft compiler does not define that macro properly, see https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/ - you need to either modify project settings to include /Zc:__cplusplus
switch, or you could use syntax like this:
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
//C++17 specific stuff here
#endif
This button will appear yellow initially. On hover it will turn orange. When you click it, it will turn red. I used :hover and :focus to adapt the style.
(The :active selector is usually used of links (i.e. <a>
tags))
button{_x000D_
background-color:yellow;_x000D_
}_x000D_
_x000D_
button:hover{background-color:orange;}_x000D_
_x000D_
button:focus{background-color:red;}_x000D_
_x000D_
a {_x000D_
color: orange;_x000D_
}_x000D_
_x000D_
a.button{_x000D_
color:green;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
a:visited {_x000D_
color: purple;_x000D_
}_x000D_
_x000D_
a:active {_x000D_
color: blue;_x000D_
}
_x000D_
<button>_x000D_
Hover and Click!_x000D_
</button>_x000D_
<br><br>_x000D_
_x000D_
<a href="#">Hello</a><br><br>_x000D_
<a class="button" href="#">Bye</a>
_x000D_
using System;
using System.IO.Ports;
using System.Threading;
namespace SerialReadTest
{
class SerialRead
{
static void Main(string[] args)
{
Console.WriteLine("Serial read init");
SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
port.Open();
while(true){
Console.WriteLine(port.ReadLine());
}
}
}
}
There is nothing wrong with syntax of
$('#part' + number).html(text);
jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.
In your case you should pass a String to $()
that is
$(<a string>)
Make sure you have access to the variables number
and text
.
To test do:
function(){
alert(number + ":" + text);//or use console.log(number + ":" + text)
$('#part' + number).html(text);
});
If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.
You don't need an IIF() at all here. The comparisons return true or false anyway.
Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.
=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0
But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:
=Sum(
IIF(
Fields!OpeningStock.Value=0 AND
Fields!GrossDispatched.Value=0 AND
Fields!TransferOutToMW.Value=0 AND
Fields!TransferOutToDW.Value=0 AND
Fields!TransferOutToOW.Value=0 AND
Fields!NetDispatched.Value=0 AND
Fields!QtySold.Value=0 AND
Fields!StockAdjustment.Value=0 AND
Fields!ClosingStock.Value=0,
0,
1
)
) = 0
This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.
Since Gson 2.8
, we can create util function like
public <T> List<T> getList(String jsonArray, Class<T> clazz) {
Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
return new Gson().fromJson(jsonArray, typeOfT);
}
Example using
String jsonArray = ...
List<User> user = getList(jsonArray, User.class);
Remove both VALUES and the parenthesis.
INSERT INTO Table2 (LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) FROM Table1 GROUP BY LongIntColumn1
As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.
After 9.2.x. IOS remove this tag check on its' browser.
You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html
i think the assets folder is public, you can access it directly on the browser
unlike other privates folders, drop your json file in the assets folder
There are some good answer above and here is the ES6 Arrow function version
var something = async() => {
let result = await functionThatReturnsPromiseA();
return result + 1;
}
There are several different pieces of information relating to processors that you could get:
These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.
The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):
Make sure to add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.
Physical Processors:
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}
Cores:
int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
coreCount += int.Parse(item["NumberOfCores"].ToString());
}
Console.WriteLine("Number Of Cores: {0}", coreCount);
Logical Processors:
Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);
OR
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}
Processors excluded from Windows:
You can also use Windows API calls in setupapi.dll to discover processors that have been excluded from Windows (e.g. through boot settings) and aren't detectable using the above means. The code below gives the total number of logical processors (I haven't been able to figure out how to differentiate physical from logical processors) that exist, including those that have been excluded from Windows:
static void Main(string[] args)
{
int deviceCount = 0;
IntPtr deviceList = IntPtr.Zero;
// GUID for processor classid
Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");
try
{
// get a list of all processor devices
deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
// attempt to process each item in the list
for (int deviceNumber = 0; ; deviceNumber++)
{
SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();
deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);
// attempt to read the device info from the list, if this fails, we're at the end of the list
if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
{
deviceCount = deviceNumber;
break;
}
}
}
finally
{
if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
}
Console.WriteLine("Number of cores: {0}", deviceCount);
}
[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
[MarshalAs(UnmanagedType.LPStr)]String enumerator,
IntPtr hwndParent,
Int32 Flags);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
Int32 MemberIndex,
ref SP_DEVINFO_DATA DeviceInterfaceData);
[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
public int cbSize;
public Guid ClassGuid;
public uint DevInst;
public IntPtr Reserved;
}
private enum DIGCF
{
DEFAULT = 0x1,
PRESENT = 0x2,
ALLCLASSES = 0x4,
PROFILE = 0x8,
DEVICEINTERFACE = 0x10,
}
What you do here is called a JOIN
(although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.
But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!
If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).
In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):
SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks_id
name price photo
fanta 5 ./images/fanta-1.jpg
dew 4 ./images/dew-1.jpg
In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:
SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id
GROUP BY drinks_id
name price photo
fanta 5 ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew 4 ./images/dew-1.jpg,./images/dew-2.jpg
However, this can get dangerous if you have ,
within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.
JavaScript injection is not at attack on your web application. JavaScript injection simply adds JavaScript code for the browser to execute. The only way JavaScript could harm your web application is if you have a blog posting or some other area in which user input is stored. This could be a problem because an attacker could inject their code and leave it there for other users to execute. This attack is known as Cross-Site Scripting. The worst scenario would be Cross-Site Forgery, which allows attackers to inject a statement that will steal a user's cookie and therefore give the attacker their session ID.
if you are using target sdk as 23 add below code in your build.gradle
android{
compileSdkVersion 23
buildToolsVersion '23.0.1'
useLibrary 'org.apache.http.legacy'
}
and change your buildscript to
classpath 'com.android.tools.build:gradle:1.3.0'
for more info follow this link
You can do it like this:
printf("%.6f", myFloat);
6 represents the number of digits after the decimal separator.
Yet another subtle pitfall, in case you need AllowOverride All
:
Somewhere deep in the fs tree, an old .htaccess
having
Options Indexes
instead of
Options +Indexes
was all it took to nonchalantly disable the FollowSymLinks
set in the server config, and cause a mysterious 403 here.
lst = ["a", "b", "a", "c", "c", "a", "c"]
temp=set(lst)
result={}
for i in temp:
result[i]=lst.count(i)
print result
Output:
{'a': 3, 'c': 3, 'b': 1}
$.each(obj, function(index, value) {
$('#looking_for_job_titles').tagsinput('add', value);
console.log(value);
});
I tried many ways mentioned here, especially the preference - editor - general - code completion - show documentation popup in.. isn't working in version 2019.2.2
Finally, i am just using F1
while caret is on the type/method and it displays the documentation nicely. This is not ideal but helpful.
See my select for paginator
SELECT TOP @limit * FROM (
SELECT ROW_NUMBER() OVER (ORDER BY colunx ASC) offset, * FROM (
-- YOU SELECT HERE
SELECT * FROM mytable
) myquery
) paginator
WHERE offset > @offset
This solves the pagination ;)
You're a little confused about how objects work in JavaScript. The object's reference is the value of the variable. There is no unserialized value. When you create an object, its structure is stored in memory and the variable it was assigned to holds a reference to that structure.
Even if what you're asking was provided in some sort of easy, native language construct it would still technically be cloning.
JavaScript is really just pass-by-value... it's just that the value passed might be a reference to something.
String str = "cat";
char[] cArray = str.toCharArray();
With ES6 external modules this can be achieved like so:
// privately scoped array
let arr = [];
export let ArrayModule = {
add: x => arr.push(x),
print: () => console.log(arr),
}
This prevents the use of internal modules and namespaces which is considered bad practice by TSLint [1] [2], allows private and public scoping and prevents the initialisation of unwanted class objects.
This : /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i
is not working for below Gmail case
[email protected] [email protected]
Below Regex will cover all the E-mail Points: I have tried the all Possible Points and my Test case get also pass because of below regex
I found this Solution from this URL:
/(?:((?:[\w-]+(?:\.[\w-]+)*)@(?:(?:[\w-]+\.)*\w[\w-]{0,66})\.(?:[a-z]{2,6}(?:\.[a-z]{2})?));*)/g
You get that error because you haven't saved your file, save it for example "holamundo.py" then run it Ctrl + B
Setting
onPressed: null // disables click
and
onPressed: () => yourFunction() // enables click
Much faster:
import time
def get_primes(n):
m = n+1
#numbers = [True for i in range(m)]
numbers = [True] * m #EDIT: faster
for i in range(2, int(n**0.5 + 1)):
if numbers[i]:
for j in range(i*i, m, i):
numbers[j] = False
primes = []
for i in range(2, m):
if numbers[i]:
primes.append(i)
return primes
start = time.time()
primes = get_primes(10000)
print(time.time() - start)
print(get_primes(100))
You can try to add @Transactional annotation to your bean or method (if declaration of all variables places in method).
random.sample implement it.
>>> random.sample([1, 2, 3, 4, 5], 3) # Three samples without replacement
[4, 1, 5]
What's the difference?
/[a-zA-Z0-9]/
is a character class which matches one character that is inside the class. It consists of three ranges.
/a-zA-Z0-9/
does mean the literal sequence of those 9 characters.
Which chars from
.!@#$%^&*()_+-=
are needed to be escaped?
Inside a character class, only the minus (if not at the end) and the circumflex (if at the beginning). Outside of a charclass, .$^*+()
have a special meaning and need to be escaped to match literally.
allows only the
a-zA-Z0-9
characters and.!@#$%^&*()_+-=
Put them in a character class then, let them repeat and require to match the whole string with them by anchors:
var regex = /^[a-zA-Z0-9!@#$%\^&*)(+=._-]*$/
What is the difference between logger.debug and logger.info?
These are only some default level already defined. You can define your own levels if you like. The purpose of those levels is to enable/disable one or more of them, without making any change in your code.
When logger.debug will be printed ??
When you have enabled the debug or any higher level in your configuration.
Another excellent plugin: http://documentcloud.github.com/visualsearch/
Best Utility in terms of speed is Nmap.
write @ cmd prompt:
Nmap -sn -oG ip.txt 192.168.1.1-255
this will just ping all the ip addresses in the range given and store it in simple text file
It takes just 2 secs to scan 255 hosts using Nmap.
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lower case alphabet character")
else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
else:
print("Non Space Special Character")
Note also that vertical-align:top;
is often necessary for correct table cell appearance.
As @dgorissen said, Jython is the easiest solution.
Just install Jython from the homepage.
Then:
javaaddpath('/path-to-your-jython-installation/jython.jar')
import org.python.util.PythonInterpreter;
python = PythonInterpreter; %# takes a long time to load!
python.exec('import some_module');
python.exec('result = some_module.run_something()');
result = python.get('result');
See the documentation for some examples.
Beware: I never actually worked with Jython and it seems that the standard library one may know from CPython is not fully implemented in Jython!
Small examples I tested worked just fine, but you may find that you have to prepend your Python code directory to sys.path
.
Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore).
Instead, since in your example tag
is the unique key, use:
INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;
on duplicate key produces:
Query OK, 0 rows affected (0.07 sec)
for the first question, it is correct you are filtering out nulls and hence count is zero.
for the second replacing: use like below:
val options = Map("path" -> "...\\ex.csv", "header" -> "true")
val dfNull = spark.sqlContext.load("com.databricks.spark.csv", options)
scala> dfNull.show
+----------+----------+-------+--------+----------+-----------+---------+
| user_id| event_id|invited|day_diff|interested|event_owner|friend_id|
+----------+----------+-------+--------+----------+-----------+---------+
| 4236494| 110357109| 0| -1| 0| 937597069| null|
| 78065188| 498404626| 0| 0| 0| 2904922087| null|
| 282487230|2520855981| 0| 28| 0| 3749735525| null|
| 335269852|1641491432| 0| 2| 0| 1490350911| null|
| 437050836|1238456614| 0| 2| 0| 991277599| null|
| 447244169|2095085551| 0| -1| 0| 1579858878| a|
| 516353916|1076364848| 0| 3| 1| 3597645735| b|
| 528218683|1151525474| 0| 1| 0| 3433080956| c|
| 531967718|3632072502| 0| 1| 0| 3863085861| null|
| 627948360|2823119321| 0| 0| 0| 4092665803| null|
| 811791433|3513954032| 0| 2| 0| 415464198| null|
| 830686203| 99027353| 0| 0| 0| 3549822604| null|
|1008893291|1115453150| 0| 2| 0| 2245155244| null|
|1239364869|2824096896| 0| 2| 1| 2579294650| d|
|1287950172|1076364848| 0| 0| 0| 3597645735| null|
|1345896548|2658555390| 0| 1| 0| 2025118823| null|
|1354205322|2564682277| 0| 3| 0| 2563033185| null|
|1408344828|1255629030| 0| -1| 1| 804901063| null|
|1452633375|1334001859| 0| 4| 0| 1488588320| null|
|1625052108|3297535757| 0| 3| 0| 1972598895| null|
+----------+----------+-------+--------+----------+-----------+---------+
dfNull.withColumn("friend_idTmp", when($"friend_id".isNull, "1").otherwise("0")).drop($"friend_id").withColumnRenamed("friend_idTmp", "friend_id").show
+----------+----------+-------+--------+----------+-----------+---------+
| user_id| event_id|invited|day_diff|interested|event_owner|friend_id|
+----------+----------+-------+--------+----------+-----------+---------+
| 4236494| 110357109| 0| -1| 0| 937597069| 1|
| 78065188| 498404626| 0| 0| 0| 2904922087| 1|
| 282487230|2520855981| 0| 28| 0| 3749735525| 1|
| 335269852|1641491432| 0| 2| 0| 1490350911| 1|
| 437050836|1238456614| 0| 2| 0| 991277599| 1|
| 447244169|2095085551| 0| -1| 0| 1579858878| 0|
| 516353916|1076364848| 0| 3| 1| 3597645735| 0|
| 528218683|1151525474| 0| 1| 0| 3433080956| 0|
| 531967718|3632072502| 0| 1| 0| 3863085861| 1|
| 627948360|2823119321| 0| 0| 0| 4092665803| 1|
| 811791433|3513954032| 0| 2| 0| 415464198| 1|
| 830686203| 99027353| 0| 0| 0| 3549822604| 1|
|1008893291|1115453150| 0| 2| 0| 2245155244| 1|
|1239364869|2824096896| 0| 2| 1| 2579294650| 0|
|1287950172|1076364848| 0| 0| 0| 3597645735| 1|
|1345896548|2658555390| 0| 1| 0| 2025118823| 1|
|1354205322|2564682277| 0| 3| 0| 2563033185| 1|
|1408344828|1255629030| 0| -1| 1| 804901063| 1|
|1452633375|1334001859| 0| 4| 0| 1488588320| 1|
|1625052108|3297535757| 0| 3| 0| 1972598895| 1|
+----------+----------+-------+--------+----------+-----------+---------+
Use Ctrl+0 to change focus to the sidebar.
echo '<pre>';
foreach($data as $entry){
foreach($entry as $entry2){
echo $entry2.'<br />';
}
}
I just did it like this:
<a href="@Url.Action("Index","Home")#features">Features</a>
The config file in the accepted answer works for me in VS2012. However, for me it only works when I do the following:
If I follow those steps I can use a shared package folder.
Here's how to do it using default ACLs, at least under Linux.
First, you might need to enable ACL support on your filesystem. If you are using ext4 then it is already enabled. Other filesystems (e.g., ext3) need to be mounted with the acl
option. In that case, add the option to your /etc/fstab
. For example, if the directory is located on your root filesystem:
/dev/mapper/qz-root / ext3 errors=remount-ro,acl 0 1
Then remount it:
mount -oremount /
Now, use the following command to set the default ACL:
setfacl -dm u::rwx,g::rwx,o::r /shared/directory
All new files in /shared/directory
should now get the desired permissions. Of course, it also depends on the application creating the file. For example, most files won't be executable by anyone from the start (depending on the mode argument to the open(2) or creat(2) call), just like when using umask. Some utilities like cp
, tar
, and rsync
will try to preserve the permissions of the source file(s) which will mask out your default ACL if the source file was not group-writable.
Hope this helps!
import os
abs_path = 'C://a/b/c'
rel_path = './folder'
os.chdir(abs_path)
os.chdir(rel_path)
You can use both with os.chdir(abs_path) or os.chdir(rel_path), there's no need to call os.getcwd() to use a relative path.
Fast forward to 2018 and C++17.
static_assert 'works' at compile time only
using namespace std::literals;
namespace STANDARD {
constexpr
inline
auto
compiletime_static_string_view_constant() {
// make and return string view literal
// will stay the same for the whole application lifetime
// will exhibit standard and expected interface
// will be usable at both
// runtime and compile time
// by value semantics implemented for you
auto when_needed_ = "compile time"sv;
return when_needed_ ;
}
};
Above is a proper and legal standard C++ citizen. It can get readily involved in any and all std:: algorithms, containers, utilities and a such. For example:
// test the resilience
auto return_by_val = []() {
auto return_by_val = []() {
auto return_by_val = []() {
auto return_by_val = []() {
return STANDARD::compiletime_static_string_view_constant();
};
return return_by_val();
};
return return_by_val();
};
return return_by_val();
};
// actually a run time
_ASSERTE(return_by_val() == "compile time");
// compile time
static_assert(
STANDARD::compiletime_static_string_view_constant()
== "compile time"
);
Enjoy the standard C++
use javascript inbuild functions escape and unescape
for example
var escapedData = escape("hel'lo");
output = "%27hel%27lo%27" which can be used in the attribute.
again to read the value from the attr
var unescapedData = unescape("%27hel%27lo%27")
output = "'hel'lo'"
This will be helpful if you have huge json stringify data to be used in the attribute
Maven absolutely was designed for this type of dependency.
mvn package
won't install anything in your local repository it just packages the project and leaves it in the target folder.
Do mvn install
in parent project (A), with this all the sub-modules will be installed in your computer's Maven repository, if there are no changes you just need to compile/package the sub-module (B) and Maven will take the already packaged and installed dependencies just right.
You just need to a mvn install
in the parent project if you updated some portion of the code.
Try below one:
svn copy http://svn.example.com/repos/calc/trunk@rev-no
http://svn.example.com/repos/calc/branches/my-calc-branch
-m "Creating a private branch of /calc/trunk." --parents
No slash "\" between the svn URLs.
Try the MIT simile timeline which could be made into a chart - http://simile.mit.edu/timeline/
or the final one, http://code.google.com/p/gchart/
Your example creates multiple key: value pairs if using fromkeys
. If you don't want this, you can use one key and create an alias for the key. For example if you are using a register map, your key can be the register address and the alias can be register name. That way you can perform read/write operations on the correct register.
>>> mydict = {}
>>> mydict[(1,2)] = [30, 20]
>>> alias1 = (1,2)
>>> print mydict[alias1]
[30, 20]
>>> mydict[(1,3)] = [30, 30]
>>> print mydict
{(1, 2): [30, 20], (1, 3): [30, 30]}
>>> alias1 in mydict
True
I had the same problem after testing Visual Studio Code with remote-ssh plugin. During the setup of the remote host the software did ask me where to store the config-file. I thought a good place is the '.ssh-folder' (Linux-system) as it was a ssh-remote configuration. It turned out to be a bad idea. The next day, after a new start of the computer I couldn't logon via ssh on the remote server. The error message was 'Could not resolve hostname:....... Name or service not known'. What happen was that the uninstall from VSC did not delete this config-file and of course it was than disturbing the usual process. An 'rm' later the problem was solved (I did delete this config-file).
HTTPS secures the transmission of the message over the network and provides some assurance to the client about the identity of the server. This is what's important to your bank or online stock broker. Their interest in authenticating the client is not in the identity of the computer, but in your identity. So card numbers, user names, passwords etc. are used to authenticate you. Some precautions are then usually taken to ensure that submissions haven't been tampered with, but on the whole whatever happens over in the session is regarded as having been initiated by you.
WS-Security offers confidentiality and integrity protection from the creation of the message to it's consumption. So instead of ensuring that the content of the communications can only be read by the right server it ensures that it can only be read by the right process on the server. Instead of assuming that all the communications in the securely initiated session are from the authenticated user each one has to be signed.
There's an amusing explanation involving naked motorcyclists here:
So WS-Security offers more protection than HTTPS would, and SOAP offers a richer API than REST. My opinion is that unless you really need the additional features or protection you should skip the overhead of SOAP and WS-Security. I know it's a bit of a cop-out but the decisions about how much protection is actually justified (not just what would be cool to build) need to be made by those who know the problem intimately.
You cannot load NPM modules without uploading a .zip
file, but you can actually get this process down to two quick command lines.
Here's how:
Put your Lambda function file(s) in a separate directory. This is because you install npm
packages locally for Lambda and you want to be able to isolate and test what you will upload to Lambda.
Install your NPM packages locally with npm install packageName
while you're in your separate Lambda directory you created in step #1.
Make sure your function works when running locally: node lambdaFunc.js
(you can simply comment out the two export.handler
lines in your code to adapt your code to run with Node locally).
Go to the Lambda's directory and compress the contents, make sure not to include the directory itself.
zip -r lambdaFunc.zip .
If you have the aws-cli
installed, which I suggest having if you want to make your life easier, you can now enter this command:
aws lambda update-function-code --function-name lambdaFunc \
--zip-file fileb://~/path/to/your/lambdaFunc.zip
(no quotes around the lambdaFunc part above in case you wonder as I did)
Now you can click test in the Lambda console.
I suggest adding a short alias for both of the above commands. Here's what I have in mine for the much longer Lambda update command:
alias up="aws lambda update-function-code --function-name lambdaFunc \
--zip-file fileb://~/path/to/your/lambdaFunc.zip"
I use django 1.7+ and python 2.7+, the solution above dose not work. And the input value in the form can be got use POST as below (use the same form above):
if form.is_valid():
data = request.POST.get('my_form_field_name')
print data
Hope this helps.
There's actually a pretty good implementation of a class decorator here:
https://github.com/agiliq/Django-parsley/blob/master/parsley/decorators.py
I actually think this is a pretty interesting implementation. Because it subclasses the class it decorates, it will behave exactly like this class in things like isinstance
checks.
It has an added benefit: it's not uncommon for the __init__
statement in a custom django Form to make modifications or additions to self.fields
so it's better for changes to self.fields
to happen after all of __init__
has run for the class in question.
Very clever.
However, in your class you actually want the decoration to alter the constructor, which I don't think is a good use case for a class decorator.
I had to do this to get it to work:
$pair = "$($user):$($pass)"
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($Pair))
$headers = @{ Authorization = "Basic $encodedCredentials" }
Invoke-WebRequest -Uri $url -Method Get -Headers $headers -OutFile Config.html
You don't need a batch file, just do this from powershell :
powershell -C "gci | % {rni $_.Name ($_.Name -replace 'Vacation2010', 'December')}"
This is an old question but none of the previous answers has addressed the real issue, i.e. that fact that the problem is with the question itself.
First, if the probabilities have been already calculated, i.e. the histogram aggregated data is available in a normalized way then the probabilities should add up to 1. They obviously do not and that means that something is wrong here, either with terminology or with the data or in the way the question is asked.
Second, the fact that the labels are provided (and not intervals) would normally mean that the probabilities are of categorical response variable - and a use of a bar plot for plotting the histogram is best (or some hacking of the pyplot's hist method), Shayan Shafiq's answer provides the code.
However, see issue 1, those probabilities are not correct and using bar plot in this case as "histogram" would be wrong because it does not tell the story of univariate distribution, for some reason (perhaps the classes are overlapping and observations are counted multiple times?) and such plot should not be called a histogram in this case.
Histogram is by definition a graphical representation of the distribution of univariate variable (see Histogram | NIST/SEMATECH e-Handbook of Statistical Methods & Histogram | Wikipedia) and is created by drawing bars of sizes representing counts or frequencies of observations in selected classes of the variable of interest. If the variable is measured on a continuous scale those classes are bins (intervals). Important part of histogram creation procedure is making a choice of how to group (or keep without grouping) the categories of responses for a categorical variable, or how to split the domain of possible values into intervals (where to put the bin boundaries) for continuous type variable. All observations should be represented, and each one only once in the plot. That means that the sum of the bar sizes should be equal to the total count of observation (or their areas in case of the variable widths, which is a less common approach). Or, if the histogram is normalised then all probabilities must add up to 1.
If the data itself is a list of "probabilities" as a response, i.e. the observations are probability values (of something) for each object of study then the best answer is simply plt.hist(probability)
with maybe binning option, and use of x-labels already available is suspicious.
Then bar plot should not be used as histogram but rather simply
import matplotlib.pyplot as plt
probability = [0.3602150537634409, 0.42028985507246375,
0.373117033603708, 0.36813186813186816, 0.32517482517482516,
0.4175257731958763, 0.41025641025641024, 0.39408866995073893,
0.4143222506393862, 0.34, 0.391025641025641, 0.3130841121495327,
0.35398230088495575]
plt.hist(probability)
plt.show()
with the results
matplotlib in such case arrives by default with the following histogram values
(array([1., 1., 1., 1., 1., 2., 0., 2., 0., 4.]),
array([0.31308411, 0.32380469, 0.33452526, 0.34524584, 0.35596641,
0.36668698, 0.37740756, 0.38812813, 0.39884871, 0.40956928,
0.42028986]),
<a list of 10 Patch objects>)
the result is a tuple of arrays, the first array contains observation counts, i.e. what will be shown against the y-axis of the plot (they add up to 13, total number of observations) and the second array are the interval boundaries for x-axis.
One can check they they are equally spaced,
x = plt.hist(probability)[1]
for left, right in zip(x[:-1], x[1:]):
print(left, right, right-left)
Or, for example for 3 bins (my judgment call for 13 observations) one would get this histogram
plt.hist(probability, bins=3)
with the plot data "behind the bars" being
The author of the question needs to clarify what is the meaning of the "probability" list of values - is the "probability" just a name of the response variable (then why are there x-labels ready for the histogram, it makes no sense), or are the list values the probabilities calculated from the data (then the fact they do not add up to 1 makes no sense).
use parseInt
var total = parseInt(a) + parseInt(b);
$('#total_price').val(total);
#change-avatar-file
is a file input
#change-avatar-file
is a img tag (the target of jcrop)
The "key" is FR.onloadend Event
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
$('#change-avatar-file').change(function(){
var currentImg;
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
$('#avatar-change-img').attr( "src", e.target.result );
currentImg = e.target.result;
};
FR.readAsDataURL( this.files[0] );
FR.onloadend = function(e){
//console.log( $('#avatar-change-img').attr( "src"));
var jcrop_api;
$('#avatar-change-img').Jcrop({
bgFade: true,
bgOpacity: .2,
setSelect: [ 60, 70, 540, 330 ]
},function(){
jcrop_api = this;
});
}
}
});
When I need to restart an activity, I use following code. Though it is not recommended.
Intent intent = getIntent();
finish();
startActivity(intent);
There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also:
This is the best and easiest code:
public class test
{
public static void main(String str[])
{
String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSON = jsonObject.getJSONObject("stat");
System.out.println(newJSON.toString());
jsonObject = new JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("rcv"));
System.out.println(jsonObject.getJSONArray("argv"));
}
}
The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.
You can download the zip. And then create a package
in your project with org.json as name. and paste all the downloaded codes there, and have fun.
I feel this to be the best and the most easiest JSON Decoding.
How are you opening the rendered Markdown?
If you host it over HTTP, i.e. you access it via http://
or https://
, most modern browsers will refuse to open local links, e.g. with file://
. This is a security feature:
For security purposes, Mozilla applications block links to local files (and directories) from remote files. This includes linking to files on your hard drive, on mapped network drives, and accessible via Uniform Naming Convention (UNC) paths. This prevents a number of unpleasant possibilities, including:
- Allowing sites to detect your operating system by checking default installation paths
- Allowing sites to exploit system vulnerabilities (e.g.,
C:\con\con
in Windows 95/98)- Allowing sites to detect browser preferences or read sensitive data
There are some workarounds listed on that page, but my recommendation is to avoid doing this if you can.
One way to do it is list the log for your branch and count the lines.
git log <branch_name> --oneline | wc -l
Maybe the most intuitive solution is probably to use the stringr
function str_remove
which is even easier than str_replace
as it has only 1 argument instead of 2.
The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern)
.
See example:
strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")
[1] "_1121" "_1432" "_1121"
You can convert the URL
to a String
and use it to create a new File
. e.g.
URL url = new URL("http://google.com/pathtoaimage.jpg");
File f = new File(url.getFile());
SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.
I would say to just grab the underlying RDD
. In Scala:
df.rdd.isEmpty
in Python:
df.rdd.isEmpty()
That being said, all this does is call take(1).length
, so it'll do the same thing as Rohan answered...just maybe slightly more explicit?
Perhaps you need to read about interactive usage of Matplotlib. However, if you are going to build an app, you should be using the API and embedding the figures in the windows of your chosen GUI toolkit (see examples/embedding_in_tk.py
, etc).
In an elevated Command Prompt write this :
To disable:
bcdedit /set hypervisorlaunchtype off
To enable:
bcdedit /set hypervisorlaunchtype auto
(From comments - restart to take effect)
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
The reason might be because the IPython module is not in your PYTHONPATH.
If you donwload IPython and then do python setup.py install
The setup doesn't add the module IPython to your python path. You might want to add it to your PYTHONPATH manually. It should work after you do :
export PYTHONPATH=/pathtoIPython:$PYTHONPATH
Add this line in your .bashrc or .profile to make it permanent.
I would expect either:
// Makes sure item is at newIndex after the operation
T item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);
... or:
// Makes sure relative ordering of newIndex is preserved after the operation,
// meaning that the item may actually be inserted at newIndex - 1
T item = list[oldIndex];
list.RemoveAt(oldIndex);
newIndex = (newIndex > oldIndex ? newIndex - 1, newIndex)
list.Insert(newIndex, item);
... would do the trick, but I don't have VS on this machine to check.
Given a first selector: SelectorA, you can find the next match of SelectorB as below:
Example with mouseover to change border-with:
$("SelectorA").on("mouseover", function() {
var i = $(this).find("SelectorB")[0];
$(i).css({"border" : "1px"});
});
}
General use example to change border-with:
var i = $("SelectorA").find("SelectorB")[0];
$(i).css({"border" : "1px"});
Are you asking about the Collections class versus the classes which implement the Collection interface?
If so, the Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.
The Collection interface defines methods common to structures which hold other objects. List and Set are subinterfaces of Collection, and ArrayList and HashSet are examples of concrete collections.
With the current version of Visual Studio Code as of this writing (1.22.1), you can find your settings in
~/.config/Code/User
on Linux (in my case, an, Ubuntu derivative)C:\Users\username\AppData\Roaming\Code\User
on Windows 10~/Library/Application Support/Code/User/
on Mac OS X (thank you, Christophe De Troyer)The files are settings.json
and keybindings.json
. Simply copy them to the target machine.
Your extensions are in
~/.vscode/extensions
on Linux and Mac OS XC:\Users\username\.vscode\extensions
on Windows 10 (e.g., essentially the same place)Alternately, just go to the Extensions, show installed extensions, and install those on your target installation. For me, copying the extensions worked just fine, but it may be extension-specific, particularly if moving between platforms, depending on what the extension does.
Something is wrong with your Python/Computer.
a = iter(list(range(10)))
for i in a:
print(i)
next(a)
>>>
0
2
4
6
8
Works like expected.
Tested in Python 2.7 and in Python 3+ . Works properly in both
If you will try to load such a large file through phpmyadmin then you would need to change upload_file_size in php.ini to your requirements and then after uploading you will have to revert it back. What will happen? If you would like to load a 3GB file. You will have to change those parameters in php.ini again.
The best solution to solve this issue to open command prompt in windows.
Find path of wamp mysql directory.
Usually, it is C:/wamp64/bin/mysql/mysqlversion/bin/mysql.exe
Execute mysql -u root
You will be in mysql command prompt
Switch database with use command.
mysql> use database_name
mysql> source [file_path]
In case of Windows, here is the example.
mysql> source C:/sqls/sql1GB.sql
That's it. If you will have a database over 10GB or 1000GB. This method will still work for you.
Hey you can do this with java/com integration. By accessing WMI features you can get all the information.
This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:
<button type="submit" onclick="return false"> Register </button>
This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.
I like the jQuery function extension. However, the this refers to the jQuery object not the DOM object. So I've modified it a little to make it even better (can update in multiple textboxes / textareas at once).
jQuery.fn.extend({
insertAtCaret: function(myValue){
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
});
}
});
This works really well. You can insert into multiple places at once, like:
$('#element1, #element2, #element3, .class-of-elements').insertAtCaret('text');
I think you should use "textAlign" instead of "text-align".
The following worked for me.
var temp = ctx.Set<DbTable>()
.GroupBy(g => new { g.id })
.ToDictionary(d => d.Key.id);
import re
ab = re.compile("^([A-Z]{1}[0-9]{1})+$")
ab.match(string)
I believe that should work for an uppercase, number pattern.
You could do the following:
.interrupt
the working threads if they wait for data in some blocking call)writeBatch
in your case) to finish, by calling the Thread.join()
method on the working threads.Some sketchy code:
static volatile boolean keepRunning = true;
In run() you change to
for (int i = 0; i < N && keepRunning; ++i)
writeBatch(pw, i);
In main() you add:
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
keepRunning = false;
mainThread.join();
}
});
That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.
From the docs:
When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.
That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.
webview.loadDataWithBaseURL(null, text, "text/html", "UTF-8", null);
You can simply call:
public static void triggerRebirth(Context context, Intent nextIntent) {
Intent intent = new Intent(context, YourClass.class);
intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(KEY_RESTART_INTENT, nextIntent);
context.startActivity(intent);
if (context instanceof Activity) {
((Activity) context).finish();
}
Runtime.getRuntime().exit(0);
}
Which is used in the ProcessPhoenix library
As an alternative:
Here's a bit improved version of @Oleg Koshkin answer.
If you really want to restart your activity including a kill of the current process, try following code. Place it in a HelperClass or where you need it.
public static void doRestart(Context c) {
try {
//check if the context is given
if (c != null) {
//fetch the packagemanager so we can get the default launch activity
// (you can replace this intent with any other activity if you want
PackageManager pm = c.getPackageManager();
//check if we got the PackageManager
if (pm != null) {
//create the intent with the default start activity for your application
Intent mStartActivity = pm.getLaunchIntentForPackage(
c.getPackageName()
);
if (mStartActivity != null) {
mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//create a pending intent so the application is restarted after System.exit(0) was called.
// We use an AlarmManager to call this intent in 100ms
int mPendingIntentId = 223344;
PendingIntent mPendingIntent = PendingIntent
.getActivity(c, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
//kill the application
System.exit(0);
} else {
Log.e(TAG, "Was not able to restart application, mStartActivity null");
}
} else {
Log.e(TAG, "Was not able to restart application, PM null");
}
} else {
Log.e(TAG, "Was not able to restart application, Context null");
}
} catch (Exception ex) {
Log.e(TAG, "Was not able to restart application");
}
}
This will also reinitialize jni classes and all static instances.
=VLOOKUP(Left(A1,1),B$2:B$22,2,FALSE)
Left is because you are starting the word/alphanumeric text from the left. the number "1" which i have placed is after lookup value in this case "A1" is because my search includes the formula for 1st character. If second character is asked it would be (A1,2) quite simple really :)
You can also use
Update-Package -reinstall
to restore the NuGet packages on the Package Management Console in Visual Studio.
$(Split-Path "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv" -leaf)
This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.
Summary compiled from the above document:
* = contains the feature SQLEXPR SQLEXPRWT SQLEXPRADV ---------------------------------------------------------------------------- > SQL Server Core * * * > SQL Server Management Studio - * * > Distributed Replay – Admin Tool - * * > LocalDB - * * > SQL Server Data Tools (SSDT) - - * > Full-text and semantic search - - * > Specification of language in query - - * > some of Reporting services features - - *
@Der Hochstapler thanks for the solution.
but in IONIC 4 some customization in project config.xml work for me
Add a line in Widget tag
<widget id="com.my.awesomeapp" version="1.0.0"
xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cdv="http://cordova.apache.org/ns/1.0">
after this, in the Platform tag for android customize some lines check below
add usesCleartextTraffic=true after networkSecurityConfig and resource-file tags
<platform name="android">
<edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:networkSecurityConfig="@xml/network_security_config" />
</edit-config>
<resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" />
<edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application">
<application android:usesCleartextTraffic="true" />
</edit-config>
</platform>
Update 2018
You should be able to just set it using CSS like this..
.dropdown-menu {
min-width:???px;
}
This works in both Bootstrap 3 and Bootstrap 4.0.0 (demo).
A no extra CSS option in Bootstrap 4 is using the sizing utils to change the width. For example, here the w-100 (width:100%) class is used for the dropdown menu to fill the width of it's parent....
<ul class="dropdown-menu w-100">
<li><a class="nav-link" href="#">Choice1</a></li>
<li><a class="nav-link" href="#">Choice2</a></li>
<li><a class="nav-link" href="#">Choice3</a></li>
</ul>
I use Git with Visual Studio for my port of Protocol Buffers to C#. I don't use the GUI - I just keep a command line open as well as Visual Studio.
For the most part it's fine - the only problem is when you want to rename a file. Both Git and Visual Studio would rather that they were the one to rename it. I think that renaming it in Visual Studio is the way to go though - just be careful what you do at the Git side afterwards. Although this has been a bit of a pain in the past, I've heard that it actually should be pretty seamless on the Git side, because it can notice that the contents will be mostly the same. (Not entirely the same, usually - you tend to rename a file when you're renaming the class, IME.)
But basically - yes, it works fine. I'm a Git newbie, but I can get it to do everything I need it to. Make sure you have a git ignore file for bin and obj, and *.user.
CSS
.achievements-wrapper { height: 300px; overflow: auto; }
HTML
<div class="span3 achievements-wrapper">
<h2>Achievements left</h2>
<table class="table table-striped">
...
</table>
</div>
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
The new
keyword is for creating new object instances. And yes, javascript is a dynamic programming language, which supports the object oriented programming paradigm. The convention about the object naming is, always use capital letter for objects that are supposed to be instantiated by the new keyword.
obj = new Element();
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
For this issue need to add the partition for date column values, If last partition 20201231245959, then inserting the 20210110245959 values, this issue will occurs.
For that need to add the 2021 partition into that table
ALTER TABLE TABLE_NAME ADD PARTITION PARTITION_NAME VALUES LESS THAN (TO_DATE('2021-12-31 24:59:59', 'SYYYY-MM-DD HH24:MI:SS', 'NLS_CALENDAR=GREGORIAN')) NOCOMPRESS
# >>> conda init >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$(CONDA_REPORT_ERRORS=false '/anaconda3/bin/conda' shell.bash hook 2> /dev/null)" if [ $? -eq 0 ]; then
\eval "$__conda_setup" else
if [ -f "/anaconda3/etc/profile.d/conda.sh" ]; then
. "/anaconda3/etc/profile.d/conda.sh"
CONDA_CHANGEPS1=false conda activate base
else
\export PATH="/anaconda3/bin:$PATH"
fi fi unset __conda_setup
# <<< conda init <<<
look to the List AddRange
method here
Just create new package and move Classes to created package.
(default package) means that is no package.
doAnswer
and thenReturn
do the same thing if:
Let's mock this BookService
public interface BookService {
String getAuthor();
void queryBookTitle(BookServiceCallback callback);
}
You can stub getAuthor() using doAnswer
and thenReturn
.
BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return "Joshua";
}
}).when(service).getAuthor();
Note that when using doAnswer
, you can't pass a method on when
.
// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());
So, when would you use doAnswer
instead of thenReturn
? I can think of two use cases:
Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.
BookServiceCallback callback = new BookServiceCallback() {
@Override
public void onSuccess(String bookTitle) {
assertEquals("Effective Java", bookTitle);
}
};
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
callback.onSuccess("Effective Java");
// return null because queryBookTitle is void
return null;
}
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:
List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));
Using doAnswer we can stub it safely.
List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));
Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn
.
List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("new").show();
$("new").hide();
Yes you can solve this error by changing the port number of glassfish because the WAMP SERVER or ORACLE database software uses a port number 8080, so there is a conflict of port number.
1)open a path like C:\GlassFish_Server\glassfish\domains\domain1\config\domain.xml.
2)find out the 8080 port number with the help of ctrl+F. You will get the following code...
<network-listener protocol="http-listener-1" port="8080" name="http-listener-1" thread-pool="http-thread-pool" transport="tcp">
3) Change that port number from 8080 to 9090 or 1234 or whatever you like..
4) Save it. Open a Netbeans IDE goto the glassfish server .
5) Right click on the server -> select refresh option.
6) to check the port no. which is given by u just right click on the server-> property.
7) Start the Glassfish server . Yehhh the error is gone...
With Linq...
string s = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
var count = s.Split(new[] {',', ':'}).Count(s => s == "true" );
In TortoiseSVN, you can also Shift + right-click to get a menu that includes "Delete (keep local)".
const state.contactList = [{
name: 'jane',
email: '[email protected]'
},{},{},...]
const fileredArray = state.contactsList.filter((contactItem) => {
const regex = new RegExp(`${action.payload}`, 'gi');
return contactItem.nameProperty.match(regex) ||
contactItem.emailProperty.match(regex);
});
// contactList: all the contacts stored in state
// action.payload: whatever typed in search field
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
OK. If you don't want to use the correct way ng-options
, you can add ng-selected
attribute with a condition check logic for the option
directive to to make the pre-select work.
<select ng-model="filterCondition.operator">
<option ng-selected="{{operator.value == filterCondition.operator}}"
ng-repeat="operator in operators"
value="{{operator.value}}">
{{operator.displayName}}
</option>
</select>
IOError: [Errno 13] Permission denied: 'juliodantas2015.json'
tells you everything you need to know: though you successfully made your python program executable with your chmod
, python can't open that juliodantas2015.json'
file for writing. You probably don't have the rights to create new files in the folder you're currently in.
If you are using cpp11 (enable with the -std=c++0x
flag if needed), then you can simply initialize the vector like this:
// static std::vector<std::string> v;
v = {"haha", "hehe"};
I've run into the very same issue, when mistakenly named variable with the very same name, as function.
So this:
isLive = isLive(data);
failed, generating OP's mentioned error message.
Fix to this was as simple as changing above line to:
isItALive = isLive(data);
I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.
Using same version for both socket.io and socket.io-client fixed my issue.
If you just want to see the changes in the latest commit, simply git show
will give you that.
If you don't want to, or can't, use RelativeLayout, you can wrap the button in a LinearLayout with orientation "vertical" and width "fill_parent".
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="35dp">
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textColor="#404040"
android:layout_marginLeft="10dp"
android:textSize="20sp"
android:layout_marginTop="9dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:background="@drawable/stitch_button"
android:layout_marginLeft="10dp"
android:text="@string/add"
android:layout_gravity="right"
android:layout_marginRight="15dp" />
</LinearLayout>
</LinearLayout>
This is because if the LinearLayout's orientation is horizontal, gravity will only affect the views vertically. And if the orientation is 'vertical', gravity will only affect the views horizontally. See here for more details on the LinearLayout orientation/gravity explanation.
I think you can use JSON.stringify:
// after your each loop
JSON.stringify(values);
The first and foremost condition that needs to be met is that both the parent and iframe should belong to the same origin. Once that is done the child can invoke the parent using window.opener method and the parent can do the same for the child as mentioned above
CPython actually implements the datetime module using both a pure-Python Lib/datetime.py and a C-optimized Modules/_datetimemodule.c. The C-optimized version cannot be patched but the pure-Python version can.
At the bottom of the pure-Python implementation in Lib/datetime.py is this code:
try:
from _datetime import * # <-- Import from C-optimized module.
except ImportError:
pass
This code imports all the C-optimized definitions and effectively replaces all the pure-Python definitions. We can force CPython to use the pure-Python implementation of the datetime module by doing:
import datetime
import importlib
import sys
sys.modules["_datetime"] = None
importlib.reload(datetime)
By setting sys.modules["_datetime"] = None
, we tell Python to ignore the C-optimized module. Then we reload the module which causes the import from _datetime
to fail. Now the pure-Python definitions remain and can be patched normally.
If you're using Pytest then include the snippet above in conftest.py and you can patch datetime
objects normally.
// begginers
@Component({
selector: 'custom-comp',
template: ` <div class="my-class" (click)="onClick()">CLICK ME</div> `,
})
export class CustomComp {
onClick = () => console.log('click event');
}
// pros
@Component({
selector: 'custom-comp',
template: ` CLICK ME `,
})
export class CustomComp {
@HostBinding('class') class = 'my-class';
@HostListener('click') onClick = () => console.log('click event');
}
// experts
@Component({
selector: 'custom-comp',
template: ` CLICK ME `,
host: {
class: 'my-class',
'(click)': 'onClick()',
},
})
export class CustomComp {}
------------------------------------------------
The 1st way will result in:
<custom-comp>
<div class="my-class" (click)="onClick()">
CLICK ME
<div>
</custom-comp>
The last 2 ways will result in:
<custom-comp class="my-class" (click)="onClick()">
CLICK ME
</custom-comp>
I was able to get the full text (99,208 chars) out of a NVARCHAR(MAX) column by selecting (Results To Grid) just that column and then right-clicking on it and then saving the result as a CSV file. To view the result open the CSV file with a text editor (NOT Excel). Funny enough, when I tried to run the same query, but having Results to File enabled, the output was truncated using the Results to Text limit.
The work-around that @MartinSmith described as a comment to the (currently) accepted answer didn't work for me (got an error when trying to view the full XML result complaining about "The '[' character, hexadecimal value 0x5B, cannot be included in a name").
dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp
You would use it like this:
var date = Date.parse(dat1);
I did this with some sort of Java keymap. If you do that, you do not need to loop over your objects array every time.
<?php
//This is your array with objects
$object1 = (object) array('id'=>123,'name'=>'Henk','age'=>65);
$object2 = (object) array('id'=>273,'name'=>'Koos','age'=>25);
$object3 = (object) array('id'=>685,'name'=>'Bram','age'=>75);
$firstArray = Array($object1,$object2);
var_dump($firstArray);
//create a new array
$secondArray = Array();
//loop over all objects
foreach($firstArray as $value){
//fill second key value
$secondArray[$value->id] = $value->name;
}
var_dump($secondArray);
echo $secondArray['123'];
output:
array (size=2)
0 =>
object(stdClass)[1]
public 'id' => int 123
public 'name' => string 'Henk' (length=4)
public 'age' => int 65
1 =>
object(stdClass)[2]
public 'id' => int 273
public 'name' => string 'Koos' (length=4)
public 'age' => int 25
array (size=2)
123 => string 'Henk' (length=4)
273 => string 'Koos' (length=4)
Henk
You have to change the extends Activity to extends AppCompactActivity then try set and getSupportActionBar()
Use the 'EntireColumn' property, that's what it is there for. C# snippet, but should give you a good indication of how to do this:
string rangeQuery = "A1:A1";
Range range = workSheet.get_Range(rangeQuery, Type.Missing);
range = range.EntireColumn;
You can use the username variable: %USERNAME%
On small device : 4 columns x 3 (= 12) ==> col-sm-3
On extra small : 3 columns x 4 (= 12) ==> col-xs-4
<footer class="row">
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 1</li>
<li>Text 2</li>
<li>Text 3</li>
</ul>
</nav>
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 4</li>
<li>Text 5</li>
<li>Text 6</li>
</ul>
</nav>
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 7</li>
<li>Text 8</li>
<li>Text 9</li>
</ul>
</nav>
<nav class="hidden-xs col-sm-3">
<ul class="list-unstyled">
<li>Text 10</li>
<li>Text 11</li>
<li>Text 12</li>
</ul>
</nav>
</footer>
As you say, hidden-xs is not enough, you have to combine xs and sm class.
Here is links to the official doc about available responsive classes and about the grid system.
Have in head :
IMHO the accepted answer is correct but misses some 'teaching' as it does not explain how to come up with the answer. For all deprecated classes look at the JavaDoc (if you do not have it either download it or go online), it will hint at which class to use to replace the old code. Of course it will not tell you everything, but this is a start. Example:
...
*
* @deprecated (4.3) use {@link HttpClientBuilder}. <----- THE HINT IS HERE !
*/
@ThreadSafe
@Deprecated
public class DefaultHttpClient extends AbstractHttpClient {
Now you have the class to use, HttpClientBuilder
, as there is no constructor to get a builder instance you may guess that there must be a static method instead: create
. Once you have the builder you can also guess that as for most builders there is a build method, thus:
org.apache.http.impl.client.HttpClientBuilder.create().build();
AutoClosable:
As Jules hinted in the comments, the returned class implements java.io.Closable
, so if you use Java 7 or above you can now do:
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {...}
The advantage is that you do not have to deal with finally and nulls.
Other relevant info
Also make sure to read about connection pooling and set the timeouts.
set "CMD=C:\Program Files (x86)\PDFtk\bin\pdftk"
echo cmd /K ""%CMD%" %D% output trimmed.pdf"
start cmd /K ""%CMD%" %D% output trimmed.pdf"
this worked for me in a batch file
The best solution is to override the click functionality:
public void _click(WebElement element){
boolean flag = false;
while(true) {
try{
element.click();
flag=true;
}
catch (Exception e){
flag = false;
}
if(flag)
{
try{
element.click();
}
catch (Exception e){
System.out.printf("Element: " +element+ " has beed clicked, Selenium exception triggered: " + e.getMessage());
}
break;
}
}
}
You can verify where your Setting.xml
is by pressing shortcut Ctrl+3
, you will see Quick Access
on top right side of Eclipse
, then search setting.xml
in searchbox. If you got setting.xml it will show up in search. Click that, and it will open the window showing directory path wherever it is stored. Your Maven Global Settings should be as such:
Global Setting
C:\maven\apache-maven-3.5.0\conf\settings.xml
User Setting
%userprofile%\\.m2\setting.xml
You can use global setting usually and leave the second option user setting
untouched. Store your setting.xml in Global Setting
It's quite simple:
if(new Date(fit_start_time) <= new Date(fit_end_time))
{//compare end <=, not >=
//your code here
}
Comparing 2 Date
instances will work just fine. It'll just call valueOf
implicitly, coercing the Date
instances to integers, which can be compared using all comparison operators. Well, to be 100% accurate: the Date
instances will be coerced to the Number
type, since JS doesn't know of integers or floats, they're all signed 64bit IEEE 754 double precision floating point numbers.
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
Use 'event.currentTarget.performance.navigation.type' to determine the type of navigation. This is working in IE, FF and Chrome.
function CallbackFunction(event) {
if(window.event) {
if (window.event.clientX < 40 && window.event.clientY < 0) {
alert("back button is clicked");
}else{
alert("refresh button is clicked");
}
}else{
if (event.currentTarget.performance.navigation.type == 2) {
alert("back button is clicked");
}
if (event.currentTarget.performance.navigation.type == 1) {
alert("refresh button is clicked");
}
}
}
TextField( minLines: 1, maxLines: 5, maxLengthEnforced: true)
Synchronized locks does not offer any mechanism of waiting queue in which after the execution of one thread any thread running in parallel can acquire the lock. Due to which the thread which is there in the system and running for a longer period of time never gets chance to access the shared resource thus leading to starvation.
Reentrant locks are very much flexible and has a fairness policy in which if a thread is waiting for a longer time and after the completion of the currently executing thread we can make sure that the longer waiting thread gets the chance of accessing the shared resource hereby decreasing the throughput of the system and making it more time consuming.
I think it depends on what OS you are using, Vista is much harder to attach to Services, because of the separation between sessions.
The two options I've used in the past are:
Hope this helps.
SOAP (communication protocol) for communication between applications. Uses HTTP (port 80) or SMTP ( port 25 or 2525 ), for message negotiation and transmission.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waist2height); {
final EditText edit = (EditText)findViewById(R.id.editText);
final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);
if(rb1.isChecked()){
edit.setVisibility(View.VISIBLE);
}
else if(rb2.isChecked()){
edit.setVisibility(View.INVISIBLE);
}
}
Add base64decoder jar and try these imports:
import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;
There is an algorithm std::merge
from C++17, which is very easy to use when the input vectors are sorted,
Below is the example:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
//DATA
std::vector<int> v1{2,4,6,8};
std::vector<int> v2{12,14,16,18};
//MERGE
std::vector<int> dst;
std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(dst));
//PRINT
for(auto item:dst)
std::cout<<item<<" ";
return 0;
}
Had the same Issue, and didn't wanna use any plugins just for deep cloning:
static deepClone(object): any {
const cloneObj = (<any>object.constructor());
const attributes = Object.keys(object);
for (const attribute of attributes) {
const property = object[attribute];
if (typeof property === 'object') {
cloneObj[attribute] = this.deepClone(property);
} else {
cloneObj[attribute] = property;
}
}
return cloneObj;
}
Credits: I made this function more readable, please check the exceptions to its functionality below
Yes, you can, you did it in the question itself: <html myAttri="myVal"/>
.
As another aside, the git-stash command is a godsend when trying to git with git-svn dcommits.
A typical process:
svn-dcommit
The solution (requires git 1.5.3+):
git stash; git svn dcommit ; git stash apply
if you really want to use CSS, use following property which will make field non-editable.
pointer-events: none;
This is generally what the indexOf() method is for. You would say:
return arrValues.indexOf('Sam') > -1
Using python 64 bit solves lot of problems.
It worked for me by executing "python37 -m pip install openpyxl"
You can replace target-action with a closure (block in Objective-C) by adding a helper closure wrapper (ClosureSleeve) and adding it as an associated object to the control so it gets retained. That way you can pass any parameters.
class ClosureSleeve {
let closure: () -> ()
init(attachTo: AnyObject, closure: @escaping () -> ()) {
self.closure = closure
objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
}
@objc func invoke() {
closure()
}
}
extension UIControl {
func addAction(for controlEvents: UIControlEvents, action: @escaping () -> ()) {
let sleeve = ClosureSleeve(attachTo: self, closure: action)
addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
}
}
Usage:
button.addAction(for: .touchUpInside) {
self.switchToNewsDetails(parameter: i)
}
You can use https://appery.io/ It is the same phonegap but in very convinient wrapper
Anaconda comes with the conda
package manager which is designed to handle these kinds of upgrades. Start by updating conda itself to get the most recent package lists:
conda update conda
And then install the version of scikit-learn you want
conda install scikit-learn=0.17
All necessary dependencies will be upgraded as well. If you have trouble with conda on Windows, there are some relevant FAQ here: http://docs.continuum.io/anaconda/faq
It is little tricky when you try to combine optional parameter and default value for that parameter. Like this,
func test(param: Int? = nil)
These two are completely opposite ideas. When you have an optional type parameter but you also provide default value to it, it is no more an optional type now since it has a default value. Even if the default is nil, swift simply removes the optional binding without checking what the default value is.
So it is always better not to use nil as default value.
If you have Unicode/nChar/nVarChar values you are concatenating, then SQL Server will implicitly convert your string to nVarChar(4000), and it is unfortunately too dumb to realize it will truncate your string or even give you a Warning that data has been truncated for that matter!
When concatenating long strings (or strings that you feel could be long) always pre-concatenate your string building with CAST('' as nVarChar(MAX)) like so:
SET @Query = CAST('' as nVarChar(MAX))--Force implicit conversion to nVarChar(MAX)
+ 'SELECT...'-- some of the query gets set here
+ '...'-- more query gets added on, etc.
What a pain and scary to think this is just how SQL Server works. :(
I know other workarounds on the web say to break up your code into multiple SET/SELECT assignments using multiple variables, but this is unnecessary given the solution above.
For those who hit an 8000 character max, it was probably because you had no Unicode so it was implicitly converted to VarChar(8000).
Explanation:
What's happening behind the scenes is that even though the variable you are assigning to uses (MAX), SQL Server will evaluate the right-hand side of the value you are assigning first and default to nVarChar(4000) or VarChar(8000) (depending on what you're concatenating). After it is done figuring out the value (and after truncating it for you) it then converts it to (MAX) when assigning it to your variable, but by then it is too late.
Have you tried loading the socket.io script not from a relative URL?
You're using:
<script src="socket.io/socket.io.js"></script>
And:
socket.connect('http://127.0.0.1:8080');
You should try:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
And:
socket.connect('http://localhost:8080');
Switch localhost:8080
with whatever fits your current setup.
Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).