You have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
Also, make sure that you do not confuse pip3
with pip
. What I found was that package installed with pip
was not working with python3
and vice-versa.
You can also use functions with $filter('filter')
:
var foo = $filter('filter')($scope.results.subjects, function (item) {
return item.grade !== 'A';
});
Issue resolved.!!! Below are the solutions.
For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar
Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
Issue is that it is failed to decrypt 256 bits of encryption.
I wrote a shellscript that solves this problem for multiple websites: https://github.com/eduardschaeli/wget-image-scraper
(Scrapes images from a list of urls with wget)
using commands module
import commands
"""
Get high load process details
"""
result = commands.getoutput("ps aux | sort -nrk 3,3 | head -n 1")
print result -- python 2x
print (result) -- python 3x
Depends ay which point you wish to "catch" the value.
For instance, if you want to catch the value as soon as the user changes the spinner selected item, use the listener approach (provided by jalopaba)
If you rather catch the value when a user performs the final task like clicking a Submit button, or something, then the answer provided by Rich is better.
If you are on windows. Open your cmd at right folder then first
set node_env={your env name here}
hit enter then you can start your node with
node app.js
it will start with your env setting
For this functionality you are better off not using a lock at all. Try an AtomicReference.
public class Sample {
private final AtomicReference<String> msg = new AtomicReference<String>();
public void setMsg(String x) {
msg.set(x);
}
public String getMsg() {
return msg.getAndSet(null);
}
}
No locks required and the code is simpler IMHO. In any case, it uses a standard construct which does what you want.
If you are using Bootstrap, try using { background-size: cover;
}
for the <div>
maybe give the div a class say <div class="example" style=url('../your_image.jpeg');>
so it becomes
div.example{
background-size: cover}
Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.
if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip
I know, I am already late but let me add my simple and working answer here
const query = {} //your query here
const update = {} //your update in json here
const option = {new: true} //will return updated document
const user = await User.findOneAndUpdate(query , update, option)
I can give you an ok solution and you can go with it, but before I do I'm going to try to explain why Document is not a DependencyProperty
to begin with.
During the lifetime of a RichTextBox
control, the Document
property generally doesn't change. The RichTextBox
is initialized with a FlowDocument
. That document is displayed, can be edited and mangled in many ways, but the underlying value of the Document
property remains that one instance of the FlowDocument
. Therefore, there is really no reason it should be a DependencyProperty
, ie, Bindable. If you have multiple locations that reference this FlowDocument
, you only need the reference once. Since it is the same instance everywhere, the changes will be accessible to everyone.
I don't think FlowDocument
supports document change notifications, though I am not sure.
That being said, here's a solution. Before you start, since RichTextBox
doesn't implement INotifyPropertyChanged
and Document is not a DependencyProperty
, we have no notifications when the RichTextBox
's Document property changes, so the binding can only be OneWay.
Create a class that will provide the FlowDocument
. Binding requires the existence of a DependencyProperty
, so this class inherits from DependencyObject
.
class HasDocument : DependencyObject
{
public static readonly DependencyProperty DocumentProperty =
DependencyProperty.Register("Document",
typeof(FlowDocument),
typeof(HasDocument),
new PropertyMetadata(new PropertyChangedCallback(DocumentChanged)));
private static void DocumentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine("Document has changed");
}
public FlowDocument Document
{
get { return GetValue(DocumentProperty) as FlowDocument; }
set { SetValue(DocumentProperty, value); }
}
}
Create a Window
with a rich text box in XAML.
<Window x:Class="samples.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Flow Document Binding" Height="300" Width="300"
>
<Grid>
<RichTextBox Name="richTextBox" />
</Grid>
</Window>
Give the Window
a field of type HasDocument
.
HasDocument hasDocument;
Window constructor should create the binding.
hasDocument = new HasDocument();
InitializeComponent();
Binding b = new Binding("Document");
b.Source = richTextBox;
b.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(hasDocument, HasDocument.DocumentProperty, b);
If you want to be able to declare the binding in XAML, you would have to make your HasDocument
class derive from FrameworkElement
so that it can be inserted into the logical tree.
Now, if you were to change the Document
property on HasDocument
, the rich text box's Document
will also change.
FlowDocument d = new FlowDocument();
Paragraph g = new Paragraph();
Run a = new Run();
a.Text = "I showed this using a binding";
g.Inlines.Add(a);
d.Blocks.Add(g);
hasDocument.Document = d;
$this->db->where_in('id', ['20','15','22','42','86']);
Reference: where_in
My laziness led me to find the easiest solution that wasn't published as an answer here.
It is based on the great article by luc juggery.
All you need to do in order to gain a full shell to your linux host from within your docker container is:
docker run --privileged --pid=host -it alpine:3.8 \
nsenter -t 1 -m -u -n -i sh
Explanation:
--privileged : grants additional permissions to the container, it allows the container to gain access to the devices of the host (/dev)
--pid=host : allows the containers to use the processes tree of the Docker host (the VM in which the Docker daemon is running) nsenter utility: allows to run a process in existing namespaces (the building blocks that provide isolation to containers)
nsenter (-t 1 -m -u -n -i sh) allows to run the process sh in the same isolation context as the process with PID 1. The whole command will then provide an interactive sh shell in the VM
This setup has major security implications and should be used with cautions (if any).
It's part of C99 and defined in POSIX definition stdbool.h.
You should be using iostream
without the .h
.
Early implementations used the .h
variants but the standard mandates the more modern style.
That's something controlled by your terminal, not by printf
.
printf
simply sends a \t
to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.
is just going to look for a div with class="outer inner", is that correct?
No, '.outer .inner'
will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner'
(no space) would give the results you're thinking of.
'.outer > .inner'
will look for immediate children of an element with the .outer class for elements with the .inner class.
Both '.outer .inner'
and '.outer > .inner'
should work for your example, although the selectors are fundamentally different and you should be wary of this.
Write the queue job information in long format to text file
qstat -f > queue.txt
Grep job names
grep 'Job_Name' queue.txt
A canvas element with some JavaScript would work great.
In fact, Signature Pad (a jQuery plugin) already has this implemented.
if (+(/MSIE\s(\d+)/.exec(navigator.userAgent)||0)[1] < 9) {
// IE8 or less
}
/MSIE\s(\d+)/.exec(navigator.userAgent)
null
so in that case ||0
will switch that null
to 0
[1]
will get major version of IE or undefined
if it was not an IE browser+
will convert it into a number, undefined
will be converted to NaN
NaN
with a number will always return false
I don't know if this is what you're looking for, but you can export the results to Excel like this:
In the results pane, click the top-left cell to highlight all the records, and then right-click the top-left cell and click "Save Results As". One of the export options is CSV.
You might give this a shot too:
INSERT INTO OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\Test.xls;','SELECT productid, price FROM dbo.product')
Lastly, you can look into using SSIS (replaced DTS) for data exports. Here is a link to a tutorial:
http://www.accelebrate.com/sql_training/ssis_2008_tutorial.htm
== Update #1 ==
To save the result as CSV file with column headers, one can follow the steps shown below:
Just use like this somewhere inside the form
@method('PUT')
I know question is specific to MVC4. But since we are way past MVC4 and if anyone looking for ASP.NET Core, you can use:
<partial name="_My_Partial" model="Model.MyInfo" />
I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud
claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)
For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)
For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).
OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud
claim in ID Tokens. (openid-connect-core-1.0)
aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.
furthermore OIDC specifies the azp
claim that is used in conjunction with aud
when aud
has more than one value.
azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.
Nevermind found an answer. Ty the same for anyone who was willing to reply.
WHERE DATEDIFF(mydata,'2008-11-20') >=0;
BalusC is right. Version 1.0.13 is current, but 1.0.9 appears to have the required bundles:
$ jar tf lib/jfreechart-1.0.9.jar | grep LocalizationBundle.properties org/jfree/chart/LocalizationBundle.properties org/jfree/chart/editor/LocalizationBundle.properties org/jfree/chart/plot/LocalizationBundle.properties
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
Source: from this excellent book
The introduction of some new testing facilities in Spring 4.2.RC1 lets one write Spring integration tests that don't rely on the SpringJUnit4ClassRunner
. Check out this part of the documentation.
In your case you could write your Spring integration test and still use mocks like this:
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration("test-app-ctx.xml")
public class FooTest {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
@InjectMocks
TestTarget sut;
@Mock
Foo mockFoo;
@Test
public void someTest() {
// ....
}
}
Note that, from March 15th, 2013, you can move or rename a file directly from GitHub:
(you don't even need to clone that repo, git mv xx
and git push
back to GitHub!)
You can also move files to entirely new locations using just the filename field.
To navigate down into a folder, just type the name of the folder you want to move the file into followed by/
.
The folder can be one that’s already part of your repository, or it can even be a brand-new folder that doesn’t exist yet!
I couldn't resolve this method (admittedly I didn't search for long)
mongoose.mongo.BSONPure.ObjectID.fromHexString
If your schema expects the property to be of type ObjectId, the conversion is implicit, at least this seems to be the case in 4.7.8.
You could use something like this however, which gives a bit more flex:
function toObjectId(ids) {
if (ids.constructor === Array) {
return ids.map(mongoose.Types.ObjectId);
}
return mongoose.Types.ObjectId(ids);
}
You could create a function that reads an integer between 1 and 23 or returns 0 if non-int
e.g.
int getInt()
{
int n = 0;
char buffer[128];
fgets(buffer,sizeof(buffer),stdin);
n = atoi(buffer);
return ( n > 23 || n < 1 ) ? 0 : n;
}
SmtpClient MyMail = new SmtpClient();
MailMessage MyMsg = new MailMessage();
MyMail.Host = "mail.eraygan.com";
MyMsg.Priority = MailPriority.High;
MyMsg.To.Add(new MailAddress(Mail));
MyMsg.Subject = Subject;
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.From = new MailAddress("username", "displayname");
MyMsg.BodyEncoding = Encoding.UTF8;
MyMsg.Body = Body;
MyMail.UseDefaultCredentials = false;
NetworkCredential MyCredentials = new NetworkCredential("username", "password");
MyMail.Credentials = MyCredentials;
MyMail.Send(MyMsg);
In the html file there are three input boxes with userid,username,department respectively.
These inputboxes are used to get the input from the user.
The user can add any number of inputs to the page.
When clicking the button the script will enable the debugger mode.
In javascript, to enable the debugger mode, we have to add the following tag in the javascript.
/************************************************************************\
Tools->Internet Options-->Advanced-->uncheck
Disable script debugging(Internet Explorer)
Disable script debugging(Other)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Dynamic Table</title>
<script language="javascript" type="text/javascript">
// <!CDATA[
function CmdAdd_onclick() {
var newTable,startTag,endTag;
//Creating a new table
startTag="<TABLE id='mainTable'><TBODY><TR><TD style=\"WIDTH: 120px\">User ID</TD>
<TD style=\"WIDTH: 120px\">User Name</TD><TD style=\"WIDTH: 120px\">Department</TD></TR>"
endTag="</TBODY></TABLE>"
newTable=startTag;
var trContents;
//Get the row contents
trContents=document.body.getElementsByTagName('TR');
if(trContents.length>1)
{
for(i=1;i<trContents.length;i++)
{
if(trContents(i).innerHTML)
{
// Add previous rows
newTable+="<TR>";
newTable+=trContents(i).innerHTML;
newTable+="</TR>";
}
}
}
//Add the Latest row
newTable+="<TR><TD style=\"WIDTH: 120px\" >" +
document.getElementById('userid').value +"</TD>";
newTable+="<TD style=\"WIDTH: 120px\" >" +
document.getElementById('username').value +"</TD>";
newTable+="<TD style=\"WIDTH: 120px\" >" +
document.getElementById('department').value +"</TD><TR>";
newTable+=endTag;
//Update the Previous Table With New Table.
document.getElementById('tableDiv').innerHTML=newTable;
}
// ]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<label>UserID</label>
<input id="userid" type="text" /><br />
<label>UserName</label>
<input id="username" type="text" /><br />
<label>Department</label>
<input id="department" type="text" />
<center>
<input id="CmdAdd" type="button" value="Add" onclick="return CmdAdd_onclick()" />
</center>
</div>
<div id="tableDiv" style="text-align:center" >
<table id="mainTable">
<tr style="width:120px " >
<td >User ID</td>
<td>User Name</td>
<td>Department</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Each instantiation and full specialization of std::atomic<> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:
Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by
std::memory_order
.
std::atomic<>
wraps operations that, in pre-C++ 11 times, had to be performed using (for example) interlocked functions with MSVC or atomic bultins in case of GCC.
Also, std::atomic<>
gives you more control by allowing various memory orders that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:
Note that, for typical use cases, you would probably use overloaded arithmetic operators or another set of them:
std::atomic<long> value(0);
value++; //This is an atomic op
value += 5; //And so is this
Because operator syntax does not allow you to specify the memory order, these operations will be performed with std::memory_order_seq_cst
, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.
In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:
std::atomic<long> value {0};
value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints
value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation
Now, your example:
a = a + 12;
will not evaluate to a single atomic op: it will result in a.load()
(which is atomic itself), then addition between this value and 12
and a.store()
(also atomic) of final result. As I noted earlier, std::memory_order_seq_cst
will be used here.
However, if you write a += 12
, it will be an atomic operation (as I noted before) and is roughly equivalent to a.fetch_add(12, std::memory_order_seq_cst)
.
As for your comment:
A regular
int
has atomic loads and stores. Whats the point of wrapping it withatomic<>
?
Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic std::atomic<>
is something that is guaranteed to be atomic on every platform, without additional requirements. Moreover, it allows you to write code like this:
void* sharedData = nullptr;
std::atomic<int> ready_flag = 0;
// Thread 1
void produce()
{
sharedData = generateData();
ready_flag.store(1, std::memory_order_release);
}
// Thread 2
void consume()
{
while (ready_flag.load(std::memory_order_acquire) == 0)
{
std::this_thread::yield();
}
assert(sharedData != nullptr); // will never trigger
processData(sharedData);
}
Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after while
loop exits. That is because:
store()
to the flag is performed after sharedData
is set (we assume that generateData()
always returns something useful, in particular, never returns NULL
) and uses std::memory_order_release
order:
memory_order_release
A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable
sharedData
is used after while
loop exits, and thus after load()
from flag will return a non-zero value. load()
uses std::memory_order_acquire
order:
std::memory_order_acquire
A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread.
This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the release-consume ordering.
There are two ways:
ToTraceString()
. You can add it into your watch window and set a breakpoint to see what the query would be at any given point for any LINQ query.tail -f
. You can learn more about MySQL's logging facilities in the official documentation. For SQL Server, the easiest way is to use the included SQL Server profiler.What is the proper #include for the function 'sleep()'?
sleep()
isn't Standard C, but POSIX so it should be:
#include <unistd.h>
I'm writing logs to the files, which are generate on daily basis (per day one log file is getting generated). This approach is working fine for me :
var (
serverLogger *log.Logger
)
func init() {
// set location of log file
date := time.Now().Format("2006-01-02")
var logpath = os.Getenv(constant.XDirectoryPath) + constant.LogFilePath + date + constant.LogFileExtension
os.MkdirAll(os.Getenv(constant.XDirectoryPath)+constant.LogFilePath, os.ModePerm)
flag.Parse()
var file, err1 = os.OpenFile(logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err1 != nil {
panic(err1)
}
mw := io.MultiWriter(os.Stdout, file)
serverLogger = log.New(mw, constant.Empty, log.LstdFlags)
serverLogger.Println("LogFile : " + logpath)
}
// LogServer logs to server's log file
func LogServer(logLevel enum.LogLevel, message string) {
_, file, no, ok := runtime.Caller(1)
logLineData := "logger_server.go"
if ok {
file = shortenFilePath(file)
logLineData = fmt.Sprintf(file + constant.ColonWithSpace + strconv.Itoa(no) + constant.HyphenWithSpace)
}
serverLogger.Println(logLineData + logLevel.String() + constant.HyphenWithSpace + message)
}
// ShortenFilePath Shortens file path to a/b/c/d.go tp d.go
func shortenFilePath(file string) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == constant.ForwardSlash {
short = file[i+1:]
break
}
}
file = short
return file
}
"shortenFilePath()" method used to get the name of the file from full path of file. and "LogServer()" method is used to create a formatted log statement (contains : filename, line number, log level, error statement etc...)
I'd like to point out a use case for this that is not an anti-pattern, and there is no better way to do it.
This seems to be a missing feature in python.
There are a number of functions, like patch.object
, that take the name of a method or property to be patched or accessed.
Consider this:
patch.object(obj, "method_name", new_reg)
This can potentially start "false succeeding" when you change the name of a method. IE: you can ship a bug, you thought you were testing.... simply because of a bad method name refactor.
Now consider: varname
. This could be an efficient, built-in function. But for now it can work by iterating an object or the caller's frame:
Now your call can be:
patch.member(obj, obj.method_name, new_reg)
And the patch function can call:
varname(var, obj=obj)
This would: assert that the var is bound to the obj and return the name of the member. Or if the obj is not specified, use the callers stack frame to derive it, etc.
Could be made an efficient built in at some point, but here's a definition that works. I deliberately didn't support builtins, easy to add tho:
Feel free to stick this in a package called varname.py
, and use it in your patch.object calls:
patch.object(obj, varname(obj, obj.method_name), new_reg)
Note: this was written for python 3.
import inspect
def _varname_dict(var, dct):
key_name = None
for key, val in dct.items():
if val is var:
if key_name is not None:
raise NotImplementedError("Duplicate names not supported %s, %s" % (key_name, key))
key_name = key
return key_name
def _varname_obj(var, obj):
key_name = None
for key in dir(obj):
val = getattr(obj, key)
equal = val is var
if equal:
if key_name is not None:
raise NotImplementedError("Duplicate names not supported %s, %s" % (key_name, key))
key_name = key
return key_name
def varname(var, obj=None):
if obj is None:
if hasattr(var, "__self__"):
return var.__name__
caller_frame = inspect.currentframe().f_back
try:
ret = _varname_dict(var, caller_frame.f_locals)
except NameError:
ret = _varname_dict(var, caller_frame.f_globals)
else:
ret = _varname_obj(var, obj)
if ret is None:
raise NameError("Name not found. (Note: builtins not supported)")
return ret
In my case the solution was that I had mariadb
installed, which was aliased to mysql
. So all service
commands relating to mysql
were not recognised... I just needed:
service mariadb start
And for good measure:
chkconfig mariadb on
Bundle extras = getIntent().getExtras();
Set<String> ks = extras.keySet();
Iterator<String> iterator = ks.iterator();
while (iterator.hasNext()) {
Log.d("KEY", iterator.next());
}
From this documentation
pandas provides a single function, merge, as the entry point for all standard database join operations between DataFrame objects:
merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=True, suffixes=('_x', '_y'), copy=True, indicator=False)
And :
DataFrame.join
is a convenient method for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame. Here is a very basic example: The data alignment here is on the indexes (row labels). This same behavior can be achieved using merge plus additional arguments instructing it to use the indexes:result = pd.merge(left, right, left_index=True, right_index=True, how='outer')
Usually you can use the .animate() method to manipulate arbitrary CSS properties, but for background colors you need to use the color plugin. Once you include this plugin, you can use something like others have indicated $('div').animate({backgroundColor: '#f00'})
to change the color.
As others have written, some of this can be done using the jQuery UI library as well.
You are probably having a problem with the sort of CSV file that you have.
Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.
You would have to tune it according to your environment.
Sometimes it's more useful to increase the size of the backlog (acceptCount) instead of the maximum number of threads.
Say, instead of
<Connector ... maxThreads="500" acceptCount="50"
you use
<Connector ... maxThreads="300" acceptCount="150"
you can get much better performance in some cases, cause there would be less threads disputing the resources and the backlog queue would be consumed faster.
In any case, though, you have to do some benchmarks to really know what is best.
You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.
There's a good howto here:
https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/
Basically:
If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).
elm.replaceChildren()
It's experimental without wide support, but when executed with no params will do what you're asking for, and it's more efficient than looping through each child and removing it. As mentioned already, replacing innerHTML with an empty string will require HTML parsing on the browser's part.
Documentation here.
If youR data was in A1:C100
then:
Excel - all versions
=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))
Excel - 2007 onwards
=COUNTIFS(A1:A100,"M",C1:C100,"Yes")
On macOS check also the Mail.app settings, which App is selected as default email App / associated with mailto:
links:
If you ever clicked that notification on Gmail, which allows to open links in Gmail instead your App - and after this reset the Chrome handler, you have to edit this manually in your Mail.app Settings.
Using React on my IPad, type="number"
does not work perfectly for me.
For my floating point numbers in the range between 99.99999 - .00000 I use the regular expression (^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)
. The first group (...)
is true for all positive two digit numbers without the floating point (e.g. 23), |
or e.g. .12345 for the second group (...)
. You can adopt it for any positive floating point number by simply changing the range {0,2}
or {0,5}
respectively.
<input
className="center-align"
type="text"
pattern="(^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)"
step="any"
maxlength="7"
validate="true"
/>
To only modify the title's font (and not the font of the axis) I used this:
import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})
The fontdict accepts all kwargs from matplotlib.text.Text.
Neither on SQL2005 nor 2012 does DBCC USEROPTIONS
show is_read_committed_snapshot_on
:
Set Option Value
textsize 2147483647
language us_english
dateformat mdy
datefirst 7
lock_timeout -1
quoted_identifier SET
arithabort SET
ansi_null_dflt_on SET
ansi_warnings SET
ansi_padding SET
ansi_nulls SET
concat_null_yields_null SET
isolation level read committed
This solution is Rails 2 only.
I just investigated this and I think I have a solution. There are two ActiveRecord private methods that you can use:
update_without_callbacks
create_without_callbacks
You're going to have to use send to call these methods. examples:
p = Person.new(:name => 'foo')
p.send(:create_without_callbacks)
p = Person.find(1)
p.send(:update_without_callbacks)
This is definitely something that you'll only really want to use in the console or while doing some random tests. Hope this helps!
for a single line implementation, you can use a lambda expression in a map
map(lambda x:MyModel.objects.get_or_create(name=x), items)
Here, lambda matches each item in items list to x and create a Database record if necessary.
The first argument of strcat() needs to be able to hold enough space for the concatenated string. So allocate a buffer with enough space to receive the result.
char bigEnough[64] = "";
strcat(bigEnough, "TEXT");
strcat(bigEnough, foo);
/* and so on */
strcat() will concatenate the second argument with the first argument, and store the result in the first argument, the returned char* is simply this first argument, and only for your convenience.
You do not get a newly allocated string with the first and second argument concatenated, which I'd guess you expected based on your code.
Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.
Html
<div id="xx"></div>
Javascript:
if (document.getElementById('xx') !=null)
console.log('it exists!');
if (document.getElementById('xxThisisNotAnElementOnThePage') ==null)
console.log('does not exist!');
Change "rw" to "w+"
Or use 'a+' for appending (not erasing existing content)
If you're using Maven, set the <encoding>
explicitly in the compiler plugin's configuration, e.g.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
I found the perfect way to Ignore files in TFS like SVN does.
First of all, select the file that you want to ignore (e.g. the Web.config).
Now go to the menu tab and select:
File Source control > Advanced > Exclude web.config from source control
... and boom; your file is permanently excluded from source control.
If it helps someone you can just use css property
text-decoration-color: red;
This is ugly but avoids allocations:
private static string GetFolderName(string path)
{
var end = -1;
for (var i = path.Length; --i >= 0;)
{
var ch = path[i];
if (ch == System.IO.Path.DirectorySeparatorChar ||
ch == System.IO.Path.AltDirectorySeparatorChar ||
ch == System.IO.Path.VolumeSeparatorChar)
{
if (end > 0)
{
return path.Substring(i + 1, end - i - 1);
}
end = i;
}
}
if (end > 0)
{
return path.Substring(0, end);
}
return path;
}
For the correct and efficient computation of the hash value of a file (in Python 3):
'b'
to the filemode) to avoid character encoding and line-ending conversion issues.readinto()
to avoid buffer churning.Example:
import hashlib
def sha256sum(filename):
h = hashlib.sha256()
b = bytearray(128*1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda : f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
The C/A Browser forum sets what is and is not valid in a certificate, and what CA's should reject.
According to their Baseline Requirements for the Issuance and Management of Publicly-Trusted Certificates document, CAs must, since 2015, not issue certificats where the common name, or common alternate names fields contains a reserved IP or internal name, where reserved IP addresses are IPs that IANA has listed as reserved - which includes all NAT IPs - and internal names are any names that don't resolve on the public DNS.
Public IP addresses CAN be used (and the baseline requirements doc specifies what kinds of checks a CA must perform to ensure the applicant owns the IP).
If your experiencing the same problem while querying a DB2 database, you'll need to use the below query.
SELECT *
FROM OPENQUERY(LINK_DB,'SELECT
CITY,
cast(STATE as varchar(40))
FROM DATABASE')
Change your And
s to AndAlso
s
A standard And
will test both expressions. If comp.Container
is Nothing
, then the second expression will raise a NullReferenceException
because you're accessing a property on a null object.
AndAlso
will short-circuit the logical evaluation. If comp.Container
is Nothing
, then the 2nd expression will not be evaluated.
For a matrix you can use this:
[M,I] = max(A(:))
I is the index of A(:) containing the largest element.
Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.
[I_row, I_col] = ind2sub(size(A),I)
The simplest solution would be open terminal
$ java -version
it shows the following
java version "1.6.0_65"
$ cd /System/Library/Frameworks/JavaVM.framework/Versions
$ ls -l
Below is the last line of output:
lrwxr-xr-x 1 root wheel 59 Feb 12 14:57 CurrentJDK -> /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents
1.6.0.jdk would be the answer
You just need a second inner join that links the ID Number
that you have now to the ID Number
of the third table. Afterwards, replace the ID Number
by the Hall Name
and voilá :)
I was/am in the same boat as you for different reasons (partly educational, partly constraints). I had to re-write all the containers of the standard library and the containers had to conform to the standard. That means, if I swap out my container with the stl version, the code would work the same. Which also meant that I had to re-write the iterators.
Anyway, I looked at EASTL. Apart from learning a ton about containers that I never learned all this time using the stl containers or through my undergraduate courses. The main reason is that EASTL is more readable than the stl counterpart (I found this is simply because of the lack of all the macros and straight forward coding style). There are some icky things in there (like #ifdefs for exceptions) but nothing to overwhelm you.
As others mentioned, look at cplusplus.com's reference on iterators and containers.
To replace anything that starts with "text" until the last character:
text.+(.*)$
Example
text hsjh sdjh sd jhsjhsdjhsdj hsd ^ last character
text.+(\ 123)
Example
text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e ^ ^ From here To here
After reading Paul's answer, I went on digging for more information on https://dev.mysql.com/doc/refman/5.7/en/query-log.html
I found a really useful code by a person. Here's the summary of the context.
(Note: The following code is not mine)
This script is an example to keep the table clean which will help you to reduce your table size. As after a day, there will be about 180k queries of log. ( in a file, it would be 30MB per day)
You need to add an additional column (event_unix) and then you can use this script to keep the log clean... it will update the timestamp into a Unix-timestamp, delete the logs older than 1 day and then update the event_time into Timestamp from event_unix... sounds a bit confusing, but it's working great.
Commands for the new column:
SET GLOBAL general_log = 'OFF';
RENAME TABLE general_log TO general_log_temp;
ALTER TABLE `general_log_temp`
ADD COLUMN `event_unix` int(10) NOT NULL AFTER `event_time`;
RENAME TABLE general_log_temp TO general_log;
SET GLOBAL general_log = 'ON';
Cleanup script:
SET GLOBAL general_log = 'OFF';
RENAME TABLE general_log TO general_log_temp;
UPDATE general_log_temp SET event_unix = UNIX_TIMESTAMP(event_time);
DELETE FROM `general_log_temp` WHERE `event_unix` < UNIX_TIMESTAMP(NOW()) - 86400;
UPDATE general_log_temp SET event_time = FROM_UNIXTIME(event_unix);
RENAME TABLE general_log_temp TO general_log;
SET GLOBAL general_log = 'ON';
Credit goes to Sebastian Kaiser (Original writer of the code).
Hope someone will find it useful as I did.
You can use the below method, which will take your target URL as the only input (Don't forget http://)
void GoToURL(String url){
Uri uri = Uri.parse(url);
Intent intent= new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
My solotion for responsive/dropdown navbar with angular-ui bootstrap (when update to angular 1.5 and, ui-bootrap 1.2.1)
index.html
...
<link rel="stylesheet" href="/css/app.css">
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<input type="checkbox" id="navbar-toggle-cbox">
<div class="navbar-header">
<label for="navbar-toggle-cbox" class="navbar-toggle"
ng-init="navCollapsed = true"
ng-click="navCollapsed = !navCollapsed"
aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</label>
<a class="navbar-brand" href="#">Project name</a>
<div id="navbar" class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">
<ul class="nav navbar-nav">
<li class="active"><a href="/view1">Home</a></li>
<li><a href="/view2">About</a></li>
<li><a href="#">Contact</a></li>
<li uib-dropdown>
<a href="#" uib-dropdown-toggle>Dropdown <b class="caret"></b></a>
<ul uib-dropdown-menu role="menu" aria-labelledby="split-button">
<li role="menuitem"><a href="#">Action</a></li>
<li role="menuitem"><a href="#">Another action</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</nav>
app.css
/* show the collapse when navbar toggle is checked */
#navbar-toggle-cbox:checked ~ .collapse {
display: block;
}
/* the checkbox used only internally; don't display it */
#navbar-toggle-cbox {
display:none
}
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
Yep I would say thirtydot has it, there is no way to do it unless you use a js method. You are talking about a complex set of rendering conditions that you will have to define. e.g. what happens when both cells are getting too big for their apartments you will have to decide who has priority or simply just give them a percentage of the area and if they are overfull they will both take up that area and only if one has whitespace will you stretch your legs in the other cell, either way there is no way to do it with css. Although there are some pretty funky things people do with css that I have not thought of. I really doubt you can do this though.
Simplest and flexible solution is below: Inside ${Tomcat_home}/config/server.xml
Change the autoDeploy="false" deployOnStartup="false" under Host element like below This is must.
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="false" deployOnStartup="false">
Add below line under Host element.
<Context path="" docBase="ServletInAction.war" reloadable="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
With the above approach we can add as many applications under webapps with different context path names.
With the latest release of Google Play Services, v7.8, you have access to the new Mobile Vision API. That's probably the most convenient way to implement barcode scanning now, and it also works offline.
From the Android Barcode API:
The Barcode API detects barcodes in real-time, on device, in any orientation. It can also detect multiple barcodes at once.
It reads the following barcode formats:
- 1D barcodes: EAN-13, EAN-8, UPC-A, UPC-E, Code-39, Code-93, Code-128, ITF, Codabar
- 2D barcodes: QR Code, Data Matrix, PDF-417, AZTEC
It automatically parses QR Codes, Data Matrix, PDF-417, and Aztec values, for the following supported formats:
- URL
- Contact information (VCARD, etc.)
- Calendar event
- Phone
- SMS
- ISBN
- WiFi
- Geo-location (latitude and longitude)
- AAMVA driver license/ID
Just an easy answer for the future which I found easy to use as a starter:
Similar to using end=''
to avoid a new line, you can use sep=''
to avoid the white spaces...for this question here, it would look like this:
print('Value is "', value, '"', sep = '')
May it help someone in the future.
After a series of struggle for passing the data from one form to another i finally found a stable answer. It works like charm.
All you need to do is declare a variable as public static datatype 'variableName'
in one form and assign the value to this variable which you want to pass to another form and call this variable in another form using directly the form name (Don't create object of this form as static variables can be accessed directly) and access this variable value.
Example of such is,
Form1
public static int quantity;
quantity=TextBox1.text; \\Value which you want to pass
Form2
TextBox2.Text=Form1.quantity;\\ Data will be placed in TextBox2
.overlay
didn't have a height or width and no content, and you can't hover over display:none
.
I instead gave the div the same size and position as .image
and changes RGBA
value on hover.
http://jsfiddle.net/Zf5am/566/
.image { position: absolute; border: 1px solid black; width: 200px; height: 200px; z-index:1;}
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; background:rgba(255,0,0,0); z-index: 200; width:200px; height:200px; }
.overlay:hover { background:rgba(255,0,0,.7); }
you can also add inline css for adding image as a background as per below example
<div class="item active" style="background-image: url(../../foo.png);">
Quite a few utility libraries such as YourJS offer functions for determining if something is an array or if something is an integer or a lot of other types as well. YourJS defines isInt by checking if the value is a number and then if it is divisible by 1:
function isInt(x) {
return typeOf(x, 'Number') && x % 1 == 0;
}
The above snippet was taken from this YourJS snippet and thusly only works because typeOf
is defined by the library. You can download a minimalistic version of YourJS which mainly only has type checking functions such as typeOf()
, isInt()
and isArray()
: http://yourjs.com/snippets/build/34,2
Do not create separate lists; create a list of lists:
results = []
with open('inputfile.txt') as inputfile:
for line in inputfile:
results.append(line.strip().split(','))
or better still, use the csv
module:
import csv
results = []
with open('inputfile.txt', newline='') as inputfile:
for row in csv.reader(inputfile):
results.append(row)
Lists or dictionaries are far superiour structures to keep track of an arbitrary number of things read from a file.
Note that either loop also lets you address the rows of data individually without having to read all the contents of the file into memory either; instead of using results.append()
just process that line right there.
Just for completeness sake, here's the one-liner compact version to read in a CSV file into a list in one go:
import csv
with open('inputfile.txt', newline='') as inputfile:
results = list(csv.reader(inputfile))
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.git mergetool
is fully configurable so you can pretty much chose your favourite tool.
The full documentation is here: http://www.kernel.org/pub/software/scm/git/docs/git-mergetool.html
In brief, you can set a default mergetool by setting the user config variable merge.tool
.
If the merge tool is one of the ones supported natively by it you just have to set mergetool.<tool>.path
to the full path to the tool (replace <tool>
by what you have configured merge.tool
to be.
Otherwise, you can set mergetool.<tool>.cmd
to a bit of shell to be eval'ed at runtime with the shell variables $BASE, $LOCAL, $REMOTE, $MERGED
set to the appropriate files. You have to be a bit careful with the escaping whether you directly edit a config file or set the variable with the git config
command.
Something like this should give the flavour of what you can do ('mymerge' is a fictional tool).
git config merge.tool mymerge
git config merge.mymerge.cmd 'mymerge.exe --base "$BASE" "$LOCAL" "$REMOTE" -o "$MERGED"'
Once you've setup your favourite merge tool, it's simply a matter of running git mergetool
whenever you have conflicts to resolve.
The p4merge tool from Perforce is a pretty good standalone merge tool.
Worksheets("Sheet1").Range("A1:A5").Copy
Worksheets("Sheet2").Range("A1").PasteSpecial Transpose:=True
There are may ways to debug Node.JS application as follows:
1) Install devtool and start application with it
npm install devtool -g --save
devtool server.js
this will open in chrome developer mode so you can put a debugger point and test.
2) debug with node-inspector
node-inspector
3) debug with --debug
node --debug app.js
In the interest of coverage. I put forward an implementation using lambda expressions.
C++11
#include <vector>
#include <algorithm>
using namespace std;
vector< MyStruct > values;
sort( values.begin( ), values.end( ), [ ]( const MyStruct& lhs, const MyStruct& rhs )
{
return lhs.key < rhs.key;
});
C++14
#include <vector>
#include <algorithm>
using namespace std;
vector< MyStruct > values;
sort( values.begin( ), values.end( ), [ ]( const auto& lhs, const auto& rhs )
{
return lhs.key < rhs.key;
});
those classes are usually part of servlet.jar
http://www.java2s.com/Code/Jar/wsit/Downloadservletjar.htm
After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.
@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in ==
versus ===
in JavaScript especially when it comes to issues of checking for undefined
and/or null
.
There's a really good article about the difference in two terms here. Basically, understand that if you use ==
instead of ===
, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.
followings programs will execute,"one number is multiple of another" in
#include<stdio.h>
int main
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0)
printf("this is multiple number");
else if (b%a==0);
printf("this is multiple number");
else
printf("this is not multiple number");
return 0;
}
Just use it like it was an object you defined. i.e.
$trends = $json_output->trends;
There are a lot of good answers here, but I only want to add one thing. It sometimes happens that you want to scroll your ScrollView to a specific view of the layout, instead of a full scroll to the top or the bottom.
A simple example: in a registration form, if the user tap the "Signup" button when a edit text of the form is not filled, you want to scroll to that specific edit text to tell the user that he must fill that field.
In that case, you can do something like that:
scrollView.post(new Runnable() {
public void run() {
scrollView.scrollTo(0, editText.getBottom());
}
});
or, if you want a smooth scroll instead of an instant scroll:
scrollView.post(new Runnable() {
public void run() {
scrollView.smoothScrollTo(0, editText.getBottom());
}
});
Obviously you can use any type of view instead of Edit Text. Note that getBottom() returns the coordinates of the view based on its parent layout, so all the views used inside the ScrollView should have only a parent (for example a Linear Layout).
If you have multiple parents inside the child of the ScrollView, the only solution i've found is to call requestChildFocus on the parent view:
editText.getParent().requestChildFocus(editText, editText);
but in this case you cannot have a smooth scroll.
I hope this answer can help someone with the same problem.
Here is one way to “untrack” any files that are would otherwise be ignored under the current set of exclude patterns:
(GIT_INDEX_FILE=some-non-existent-file \
git ls-files --exclude-standard --others --directory --ignored -z) |
xargs -0 git rm --cached -r --ignore-unmatch --
This leaves the files in your working directory but removes them from the index.
The trick used here is to provide a non-existent index file to git ls-files so that it thinks there are no tracked files. The shell code above asks for all the files that would be ignored if the index were empty and then removes them from the actual index with git rm.
After the files have been “untracked”, use git status to verify that nothing important was removed (if so adjust your exclude patterns and use git reset -- path to restore the removed index entry). Then make a new commit that leaves out the “crud”.
The “crud” will still be in any old commits. You can use git filter-branch to produce clean versions of the old commits if you really need a clean history (n.b. using git filter-branch will “rewrite history”, so it should not be undertaken lightly if you have any collaborators that have pulled any of your historical commits after the “crud” was first introduced).
Did something like that once:
CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
('%timeline%'),
('%Placeholders%'),
('%Stages%'),
('%master_stage_1205x465%'),
('%Accessories%'),
('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS
SELECT * FROM chunks
WHERE chunks.file_id IN
(
SELECT DISTINCT
lf.file_id
FROM LargeFiles lf
WHERE lf.file_id NOT IN
(
SELECT DISTINCT
lf.file_id
FROM LargeFiles lf
LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
WHERE e.excl IS NULL
)
);
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0
BEGIN
DELETE TOP (10000) FROM ToBeDeleted;
SET @r = @@ROWCOUNT
END
GO
There is no advantage of using one vs the other, but, there is a specific case where throw
won't work. However, those cases can be fixed.
Any time you are inside of a promise callback, you can use throw
. However, if you're in any other asynchronous callback, you must use reject
.
For example, this won't trigger the catch:
new Promise(function() {
setTimeout(function() {
throw 'or nah';
// return Promise.reject('or nah'); also won't work
}, 1000);
}).catch(function(e) {
console.log(e); // doesn't happen
});
_x000D_
Instead you're left with an unresolved promise and an uncaught exception. That is a case where you would want to instead use reject
. However, you could fix this in two ways.
new Promise(function(resolve, reject) {
setTimeout(function() {
reject('or nah');
}, 1000);
}).catch(function(e) {
console.log(e); // works!
});
_x000D_
function timeout(duration) { // Thanks joews
return new Promise(function(resolve) {
setTimeout(resolve, duration);
});
}
timeout(1000).then(function() {
throw 'worky!';
// return Promise.reject('worky'); also works
}).catch(function(e) {
console.log(e); // 'worky!'
});
_x000D_
This Function takes the URL then returns the image BASE64
function getBase64FromImageUrl(url) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
img.src = url;
}
Call it like this :
getBase64FromImageUrl("images/slbltxt.png")
Focus can be set on interactive elements only... Div only represent a logical section of the page.
Perhaps you can set the borders around div or change it's color to simulate a focus. And yes Visiblity is not focus.
These lines are your problem (or at least one of your problems, if there are more):
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
You reference some static members in the initializers for other static members. This is a bad idea, as the compiler doesn't know in which order to initialize them. The result is that during the initialization of s_bstCommonAppData
, the dependent field s_commonAppData
has not yet been initialized, so you are calling Path.Combine(null, "XXXX")
and this method does not accept null arguments.
You can fix this by making sure that fields used in the initialization of other fields are declared first:
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
Or use a static constructor to explicitly order the assignments:
private static string s_bstCommonAppData;
private static string s_bstUserDataDir;
private static string s_commonAppData;
static Logger()
{
s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
}
If you are looking for a direct approach and using a local
File in that case.
Try
<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>
This is the case of JS
with inline styling where Image
is a local file that you must have imported with a path.
It's better to add "overrides" in your .eslintrc.js config file. For example if you wont to disable camelcase rule for all js files ending on Actions add this code after rules scope in .eslintrc.js.
"rules": {
...........
},
"overrides": [
{
"files": ["*Actions.js"],
"rules": {
"camelcase": "off"
}
}
]
OK, seems this is my final answer. We have 2 actual problems:
1. Print POSIX ID (pthread_t)
You can simply treat pthread_t as array of bytes with hex digits printed for each byte. So you aren't limited by some fixed size type. The only issue is byte order. You probably like if order of your printed bytes is the same as for simple "int" printed. Here is example for little-endian and only order should be reverted (under define?) for big-endian:
#include <pthread.h>
#include <stdio.h>
void print_thread_id(pthread_t id)
{
size_t i;
for (i = sizeof(i); i; --i)
printf("%02x", *(((unsigned char*) &id) + i - 1));
}
int main()
{
pthread_t id = pthread_self();
printf("%08x\n", id);
print_thread_id(id);
return 0;
}
2. Get shorter printable thread ID
In any of proposed cases you should translate real thread ID (posix) to index of some table. But there is 2 significantly different approaches:
2.1. Track threads.
You may track threads ID of all the existing threads in table (their pthread_create() calls should be wrapped) and have "overloaded" id function that get you just table index, not real thread ID. This scheme is also very useful for any internal thread-related debug an resources tracking. Obvious advantage is side effect of thread-level trace / debug facility with future extension possible. Disadvantage is requirement to track any thread creation / destruction.
Here is partial pseudocode example:
pthread_create_wrapper(...)
{
id = pthread_create(...)
add_thread(id);
}
pthread_destruction_wrapper()
{
/* Main problem is it should be called.
pthread_cleanup_*() calls are possible solution. */
remove_thread(pthread_self());
}
unsigned thread_id(pthread_t known_pthread_id)
{
return seatch_thread_index(known_pthread_id);
}
/* user code */
printf("04x", thread_id(pthread_self()));
2.2. Just register new thread ID.
During logging call pthread_self() and search internal table if it know thread. If thread with such ID was created its index is used (or re-used from previously thread, actually it doesn't matter as there are no 2 same IDs for the same moment). If thread ID is not known yet, new entry is created so new index is generated / used.
Advantage is simplicity. Disadvantage is no tracking of thread creation / destruction. So to track this some external mechanics is required.
System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();
Substitute the right encoding above: e.g.
System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();
A more general method to create an arbitrary size data frame is to create a n-by-1 data-frame from a matrix of the same dimension. Then, you can immediately drop the first row:
> v <- data.frame(matrix(NA, nrow=1, ncol=10))
> v <- v[-1, , drop=FALSE]
> v
[1] X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
<0 rows> (or 0-length row.names)
As others have mentioned, you can use document.title = 'My new title'
and React Helmet to update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.
If you are using create-react-app
the initial document title is set in the <title>
tag /public/index.html
file.
You can edit this directly or use a placeholder which will be filled from environmental variables:
/.env
:
REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...
If for some reason I wanted a different title in my development environment -
/.env.development
:
REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...
/public/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
...
<title>%REACT_APP_SITE_TITLE%</title>
...
</head>
<body>
...
</body>
</html>
This approach also means that I can read the site title environmental variable from my application using the global process.env
object, which is nice:
console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!
In your main.xml include the following in your ListView:
android:drawSelectorOnTop="false"
android:listSelector="@android:color/darker_gray"
If you know the data and the action the installed package react on, you simply should add these information to your intent instance before starting it.
If you have access to the AndroidManifest of the other app, you can see all needed information there.
>>> 15 % 4
3
>>>
The modulo gives the remainder after integer division.
With oracle 10.2g:
select level, sequence.NEXTVAL
from dual
connect by level <= (select max(pk) from tbl);
will set the current sequence value to the max(pk) of your table (i.e. the next call to NEXTVAL will give you the right result); if you use Toad, press F5 to run the statement, not F9, which pages the output (thus stopping the increment after, usually, 500 rows). Good side: this solution is only DML, not DDL. Only SQL and no PL-SQL. Bad side : this solution prints max(pk) rows of output, i.e. is usually slower than the ALTER SEQUENCE solution.
You can't replace a letter in a string. Convert the string to a list, replace the letter, and convert it back to a string.
>>> s = list("Hello world")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> s[int(len(s) / 2)] = '-'
>>> s
['H', 'e', 'l', 'l', 'o', '-', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello-World'
Here is the solution:
show full processlist;
to get the process id with status and query itself which causes the database hanging;KILL <pid>;
to kill that process.Sometimes it is not enough to kill each process manually. So, for that we've to go with some trick:
Select concat('KILL ',id,';') from information_schema.processlist where user='user';
to print all processes with KILL
command;|
sign, copy and paste all again into the query console. HIT ENTER. BooM it's done.To list processes holding deleted files a linux system which has no lsof
, here's my trick:
pushd /proc ; for i in [1-9]* ; do ls -l $i/fd | grep "(deleted)" && (echo -n "used by: " ; ps -p $i | grep -v PID ; echo ) ; done ; popd
Using Dapper.Contrib it is as simple as this:
Insert list:
public int Insert(IEnumerable<YourClass> yourClass)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
return conn.Insert(yourClass) ;
}
}
Insert single:
public int Insert(YourClass yourClass)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
return conn.Insert(yourClass) ;
}
}
Update list:
public bool Update(IEnumerable<YourClass> yourClass)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
return conn.Update(yourClass) ;
}
}
Update single:
public bool Update(YourClass yourClass)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
return conn.Update(yourClass) ;
}
}
Source: https://github.com/StackExchange/Dapper/tree/master/Dapper.Contrib
$date = new DateTime(date("Y-m-d"));
$date->modify('+7 day');
$tomorrowDATE = $date->format('Y-m-d');
If you want to do this often, you can create a keybindings file in your Library to map it to a key combination.
In ~/Library create a directory named KeyBindings. Create a file named DefaultKeyBinding.dict inside the directory. You can add key bindings in this format:
{
"x" = (insertText:, "\U23CF");
"y" = (insertText:, "hi"); /* warning: this will change 'y' to 'hi'! */
}
The LHS is the key combination you'll hit to enter the character. You can use the following characters to indicate command keys:
@ - Command
~ - Option
^ - Control
You'll need to look up the unicode for your character (in this case, ? is \U2234). So to type this character whenever you typed Control-M, you'd use
"^m" = (insertText:, "\U2234");
You can find more information here: http://www.hcs.harvard.edu/~jrus/site/cocoa-text.html
A quick way to explain this is to visualize it.
if both i and j are from 0 to N, it's easy to see O(N^2)
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O O
in this case, it's:
O
O O
O O O
O O O O
O O O O O
O O O O O O
O O O O O O O
O O O O O O O O
This comes out to be 1/2 of N^2, which is still O(N^2)
In python this work for me
self.set_your_value = "your value"
def your_method_name(self):
self.driver.find_element_by_name(self.set_your_value).send_keys(Keys.TAB)`
You can try this ! This should work on windows machines.
for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"
Use getColorStateList
like this
setTextColor(resources.getColorStateList(R.color.button_states_color))
instead of getColor
setTextColor(resources.getColor(R.color.button_states_color))
I had the same problem, and
neither umount /path -f
,
neither umount.nfs /path -f
,
neither fuser -km /path
,
works
finally I found a simple solution >.<
sudo /etc/init.d/nfs-common restart
, then lets do the simple umount
;-)
npm i (Package name) --save
Simplily, using above command we ll not need to write package name in your package.json file it ll auto add its name and dependency with version that you ll need at time when you go for production or setup another time.
npm help install
Above command ll help find out more option and correct def.shown in pic
If you do an insert into...select * from...
statement, it's easy to get the 'Invalid Number' error as well.
Let's say you have a table called FUND_ACCOUNT
that has two columns:
AID_YEAR char(4)
OFFICE_ID char(5)
And let's say that you want to modify the OFFICE_ID to be numeric, but that there are existing rows in the table, and even worse, some of those rows have an OFFICE_ID value of ' ' (blank). In Oracle, you can't modify the datatype of a column if the table has data, and it requires a little trickery to convert a ' ' to a 0. So here's how to do it:
CREATE TABLE FUND_ACCOUNT2 AS SELECT * FROM FUND_ACCOUNT;
DELETE FROM FUND_ACCOUNT;
Once there's no data in the original table, alter the data type of its OFFICE_ID column: ALTER TABLE FUND_ACCOUNT MODIFY (OFFICE_ID number);
But then here's the tricky part. Because some rows contain blank OFFICE_ID values, if you do a simple INSERT INTO FUND_ACCOUNT SELECT * FROM FUND_ACCOUNT2
, you'll get the "ORA-01722 Invalid Number" error. In order to convert the ' ' (blank) OFFICE_IDs into 0's, your insert statement will have to look like this:
INSERT INTO FUND_ACCOUNT (AID_YEAR, OFFICE_ID) SELECT AID_YEAR, decode(OFFICE_ID,' ',0,OFFICE_ID) FROM FUND_ACCOUNT2;
In C++20 you'll be able to use std::format
to do this:
std::cout << std::format("a is {:x}; b is {:x}\n", a, b);
Output:
a is 0; b is ff
In the meantime you can use the {fmt} library, std::format
is based on. {fmt} also provides the print
function that makes this even easier and more efficient (godbolt):
fmt::print("a is {:x}; b is {:x}\n", a, b);
Disclaimer: I'm the author of {fmt} and C++20 std::format
.
git clone --filter
from Git 2.19 + shallow clones
This new option might eventually become the final solution to the binary file problem, if the Git and GitHub devs and make it user friendly enough (which they arguably still haven't achieved for submodules for example).
It allows to actually only fetch files and directories that you want for the server, and was introduced together with a remote protocol extension.
With this, we could first do a shallow clone, and then automate which blobs to fetch with the build system for each type of build.
There is even already a --filter=blob:limit<size>
which allows limiting the maximum blob size to fetch.
I have provided a minimal detailed example of how the feature looks like at: How do I clone a subdirectory only of a Git repository?
Removes everything between &
and ;
which all such symbols have. if you juts want to get rid of them.
text.replace(/&.*;/g,'');
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
The typical command is:
docker container ls -f 'status=exited'
However, this will only list one of the possible non-running statuses. Here's a list of all possible statuses:
You can filter on multiple statuses by passing multiple filters on the status:
docker container ls -f 'status=exited' -f 'status=dead' -f 'status=created'
If you are integrating this with an automatic cleanup script, you can chain one command to another with some bash syntax, output just the container id's with -q
, and you can also limit to just the containers that exited successfully with an exit code filter:
docker container rm $(docker container ls -q -f 'status=exited' -f 'exited=0')
For more details on filters you can use, see Docker's documentation: https://docs.docker.com/engine/reference/commandline/ps/#filtering
If you want to use pip
to install required package and import it after installation, you can use this code:
def install_and_import(package):
import importlib
try:
importlib.import_module(package)
except ImportError:
import pip
pip.main(['install', package])
finally:
globals()[package] = importlib.import_module(package)
install_and_import('transliterate')
If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.
The LogRewrite directive as mentioned by Ben is not available anymore in Apache 2.4. You need to use the LogLevel directive instead. E.g.
LogLevel alert rewrite:trace6
See http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging
Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.
You can avoid this problem by
Hibernate.initialize(obj);
Fetch profiles
to select lazy/non-lazy fetching runtimeFurther I would recommend looking at the related
links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.
If you want to insert a large code block with optional line numbers, etc use the Code Macro (available under Macros -> Other).
Solution:
In my case I have succeed with the following solution for converting field ClockInTime from ClockTime collection from string to Date type:
db.ClockTime.find().forEach(function(doc) {
doc.ClockInTime=new Date(doc.ClockInTime);
db.ClockTime.save(doc);
})
You can specify border separately for all borders, for example:
#testdiv{
border-left: 1px solid #000;
border-right: 2px solid #FF0;
}
You can also specify the look of the border, and use separate style for the top, right, bottom and left borders. for example:
#testdiv{
border: 1px #000;
border-style: none solid none solid;
}
Anaconda folder basically resides in C:\Users\\Anaconda. Try setting the PATH to this folder.
Use the style + locale: DateFormat.getDateInstance(int style, Locale locale)
Check http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html
Run the following example to see the differences:
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class DateFormatDemoSO {
public static void main(String args[]) {
int style = DateFormat.MEDIUM;
//Also try with style = DateFormat.FULL and DateFormat.SHORT
Date date = new Date();
DateFormat df;
df = DateFormat.getDateInstance(style, Locale.UK);
System.out.println("United Kingdom: " + df.format(date));
df = DateFormat.getDateInstance(style, Locale.US);
System.out.println("USA: " + df.format(date));
df = DateFormat.getDateInstance(style, Locale.FRANCE);
System.out.println("France: " + df.format(date));
df = DateFormat.getDateInstance(style, Locale.ITALY);
System.out.println("Italy: " + df.format(date));
df = DateFormat.getDateInstance(style, Locale.JAPAN);
System.out.println("Japan: " + df.format(date));
}
}
Output:
United Kingdom: 25-Sep-2017
USA: Sep 25, 2017
France: 25 sept. 2017
Italy: 25-set-2017
Japan: 2017/09/25
You could use the .attr()
function:
$(this).attr('data-fullText')
or if you lowercase the attribute name:
data-fulltext="This is a span element"
then you could use the .data()
function:
$(this).data('fulltext')
The .data()
function expects and works only with lowercase attribute names.
Use the range's NumberFormat
property to force the format of the range like this:
Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
Base on Francisco Daniel's answer I modified some of the Jquery code here's My version. I removed some excess code and use "fa" instead of "far" for the icon. I also remove the "far fa-minus-square" since I can't understand its purpose.
-- Edited --
I added the "draw" event for the button icon to update whenever the table is redrawn or reloaded. Because I noticed when I tried to reload the table using "myTable.ajax.reload()" the button icon is not changing.
https://codepen.io/john-kenneth-larbo/pen/zXeYpz
$(document).ready(function() {_x000D_
let myTable = $('#example').DataTable({_x000D_
columnDefs: [{_x000D_
orderable: false,_x000D_
className: 'select-checkbox',_x000D_
targets: 0,_x000D_
}],_x000D_
select: {_x000D_
style: 'os', // 'single', 'multi', 'os', 'multi+shift'_x000D_
selector: 'td:first-child',_x000D_
},_x000D_
order: [_x000D_
[1, 'asc'],_x000D_
],_x000D_
});_x000D_
_x000D_
myTable.on('select deselect draw', function () {_x000D_
var all = myTable.rows({ search: 'applied' }).count(); // get total count of rows_x000D_
var selectedRows = myTable.rows({ selected: true, search: 'applied' }).count(); // get total count of selected rows_x000D_
_x000D_
if (selectedRows < all) {_x000D_
$('#MyTableCheckAllButton i').attr('class', 'fa fa-square-o');_x000D_
} else {_x000D_
$('#MyTableCheckAllButton i').attr('class', 'fa fa-check-square-o');_x000D_
}_x000D_
_x000D_
});_x000D_
_x000D_
$('#MyTableCheckAllButton').click(function () {_x000D_
var all = myTable.rows({ search: 'applied' }).count(); // get total count of rows_x000D_
var selectedRows = myTable.rows({ selected: true, search: 'applied' }).count(); // get total count of selected rows_x000D_
_x000D_
_x000D_
if (selectedRows < all) {_x000D_
//Added search applied in case user wants the search items will be selected_x000D_
myTable.rows({ search: 'applied' }).deselect();_x000D_
myTable.rows({ search: 'applied' }).select();_x000D_
} else {_x000D_
myTable.rows({ search: 'applied' }).deselect();_x000D_
}_x000D_
});_x000D_
});
_x000D_
<table id="example" class="display" style="width:100%">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>_x000D_
<button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">_x000D_
<i class="far fa-square"></i> _x000D_
</button>_x000D_
</th>_x000D_
<th>Name</th>_x000D_
<th>Position</th>_x000D_
<th>Office</th>_x000D_
<th>Age</th>_x000D_
<th>Salary</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Tiger Nixon</td>_x000D_
<td>System Architect</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>61</td>_x000D_
<td>$320,800</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Garrett Winters</td>_x000D_
<td>Accountant</td>_x000D_
<td>Tokyo</td>_x000D_
<td>63</td>_x000D_
<td>$170,750</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Ashton Cox</td>_x000D_
<td>Junior Technical Author</td>_x000D_
<td>San Francisco</td>_x000D_
<td>66</td>_x000D_
<td>$86,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Cedric Kelly</td>_x000D_
<td>Senior Javascript Developer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>22</td>_x000D_
<td>$433,060</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Airi Satou</td>_x000D_
<td>Accountant</td>_x000D_
<td>Tokyo</td>_x000D_
<td>33</td>_x000D_
<td>$162,700</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Brielle Williamson</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>New York</td>_x000D_
<td>61</td>_x000D_
<td>$372,000</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Herrod Chandler</td>_x000D_
<td>Sales Assistant</td>_x000D_
<td>San Francisco</td>_x000D_
<td>59</td>_x000D_
<td>$137,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Rhona Davidson</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>Tokyo</td>_x000D_
<td>55</td>_x000D_
<td>$327,900</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Colleen Hurst</td>_x000D_
<td>Javascript Developer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>39</td>_x000D_
<td>$205,500</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Sonya Frost</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>23</td>_x000D_
<td>$103,600</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td></td>_x000D_
<td>Jena Gaines</td>_x000D_
<td>Office Manager</td>_x000D_
<td>London</td>_x000D_
<td>30</td>_x000D_
<td>$90,560</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
<tfoot>_x000D_
<tr>_x000D_
<th></th>_x000D_
<th>Name</th>_x000D_
<th>Position</th>_x000D_
<th>Office</th>_x000D_
<th>Age</th>_x000D_
<th>Salary</th>_x000D_
</tr>_x000D_
</tfoot>_x000D_
</table>
_x000D_
This is a very frustrating part of XCode. Like many, I wasted hours on this when I switched to a newer version of xcode (version 8). The solution for me was to open the properties for my project and under the "App Icons and Launch Images" choose the "migrate" option for the icons. This made absolutely no sense to me as I already had all my icons there, but it worked! Unfortunately I now seem to have two copies of my launcher icons in the project though.
the pom.xml for the project I have doesn't have this "http://repo1.maven.org/myurlhere" anywhere in it
All projects have http://repo1.maven.org/ declared as <repository>
(and <pluginRepository>
) by default. This repository, which is called the central repository, is inherited like others default settings from the "Super POM" (all projects inherit from the Super POM). So a POM is actually a combination of the Super POM, any parent POMs and the current POM. This combination is called the "effective POM" and can be printed using the effective-pom
goal of the Maven Help plugin (useful for debugging).
And indeed, if you run:
mvn help:effective-pom
You'll see at least the following:
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Repository Switchboard</name>
<url>http://repo1.maven.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Plugin Repository</name>
<url>http://repo1.maven.org/maven2</url>
</pluginRepository>
</pluginRepositories>
it has the absolute url where the maven repo is for the project but maven is still trying to download from the general maven repo
Maven will try to find dependencies in all repositories declared, including in the central one which is there by default as we saw. But, according to the trace you are showing, you only have one repository defined (the central repository) or maven would print something like this:
Reason: Unable to download the artifact from any repository
url.project:project:pom:x.x
from the specified remote repositories:
central (http://repo1.maven.org/),
another-repository (http://another/repository)
So, basically, maven is unable to find the url.project:project:pom:x.x
because it is not available in central.
But without knowing which project you've checked out (it has maybe specific instructions) or which dependency is missing (it can maybe be found in another repository), it's impossible to help you further.
first, in C:\users\your PC
write npm uninstall -g create-react-app
then, create your project folder with npx create-react-app folder-name
.
jQuery UI has it's own elements, but jQuery alone hasn't.
Working example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
</body>
</html>
A regular expression can be used to offer more control over the whitespace characters that are combined.
To match unicode whitespace:
import re
_RE_COMBINE_WHITESPACE = re.compile(r"\s+")
my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()
To match ASCII whitespace only:
import re
_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")
my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)
Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.
About \s
:
For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.
About re.ASCII
:
Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).
strip()
will remote any leading and trailing whitespaces.
My solution to fix that problem was the following:
Start > search > cmd.exe (Run as administrator)
Inside the Command Prompt (cmd.exe) type:
cd c:/wamp/bin/apache/ApacheX.X.X/bin
httpd.exe -e debug
**Note that the ApacheX.X.X is the version of the Apache wamp is running.
This should output what the apache server is doing. The error that causes Apache from loading should be in there. My problem was that httpd.conf was trying to load a DLL that was missing or was corrupted (php5apache2_4.dll). As soon as I overwrote this file, I restarted Wamp and everything ran smooth.
I used the jQuery.click function to get the desired output:
$('input[name=rate]').click(function(){
console.log('Hey you clicked this: ' + this.value);
if(this.value == 'Fixed Rate'){
rate_value = $('#r1').value;
} else if(this.value =='Variable Rate'){
rate_value = $('#r2').value;
} else if(this.value =='Multi Rate'){
rate_value = $('#r3').value;
}
$('#results').innerHTML = rate_value;
});
Hope it helps.
For better performance you should use:
var numItems = $('div.item').length;
Since it will only look for the div
elements in DOM
and will be quick.
Suggestion: using size()
instead of length
property means one extra step in the processing since SIZE()
uses length
property in the function definition and returns the result.
Make sure nodejs in the PATH is in front of anything that uses node.
driver.findElement(By.id("urid")).sendKeys("drive:\\path\\filename.extension");
PGPORT=5432
PGHOST="my.database.domain.com"
PGUSER="postgres"
PGDB="mydb"
createdb -h $PGHOST -p $PGPORT -U $PGUSER $PGDB
Try nodejs
instead of just node
$ nodejs -v
v0.10.25
You can do this with background-size
:
html {
background: url(images/bg.jpg) no-repeat center center fixed;
background-size: cover;
}
There are a lot of values other than cover
that you can set background-size
to, see which one works for you: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size
Spec: https://www.w3.org/TR/css-backgrounds-3/#the-background-size
It works in all modern browsers: http://caniuse.com/#feat=background-img-opts
I made this work in this way:
<button class="btn" ng-click='toggleClass($event)'>button one</button>
<button class="btn" ng-click='toggleClass($event)'>button two</button>
in your controller:
$scope.toggleClass = function (event) {
$(event.target).toggleClass('active');
}
I think the most robust solution that will insure that it is posted in uppercase is to use the oninput method inline like:
<input oninput="this.value = this.value.toUpperCase()" />
_x000D_
EDIT
Some people have been complaining that the cursor jumps to the end when editing the value, so this slightly expanded version should resolve that
<input oninput="let p=this.selectionStart;this.value=this.value.toUpperCase();this.setSelectionRange(p, p);" />
_x000D_
Here's an example which helps to understand this:
public class Main {
static abstract class A {
abstract void foo();
A() {
System.out.println("Constructing A");
foo();
}
}
static class C extends A {
C() {
System.out.println("Constructing C");
}
void foo() {
System.out.println("Using C");
}
}
public static void main(String[] args) {
C c = new C();
}
}
If you run this code, you get the following output:
Constructing A
Using C
Constructing C
You see? foo()
makes use of C before C's constructor has been run. If foo()
requires C to have a defined state (i.e. the constructor has finished), then it will encounter an undefined state in C and things might break. And since you can't know in A what the overwritten foo()
expects, you get a warning.
you can get filename by uri with simple way
fun get_filename_by_uri(uri : Uri) : String{
contentResolver.query(uri, null, null, null, null).use { cursor ->
cursor?.let {
val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
it.moveToFirst()
return it.getString(nameIndex)
}
}
return ""
}
and easy to read it by using
contentResolver.openInputStream(uri)
None of the many answers fixed the 0xE8008016 Error for me.
But when I chose "Automatic Device Provisioning" in Xcode 4 > Organizer > Devices > Provisioning Profiles, it finally worked.
Lets define the dataframe from your example by
>>> df = pd.DataFrame([[206, 214], [226, 234], [245, 253], [265, 272], [283, 291]],
columns=[1, 2])
>>> df
1 2
0 206 214
1 226 234
2 245 253
3 265 272
4 283 291
Then you could manipulate the index of the second column by
>>> df[2].index = df[2].index+1
and finally re-combine the single columns
>>> pd.concat([df[1], df[2]], axis=1)
1 2
0 206.0 NaN
1 226.0 214.0
2 245.0 234.0
3 265.0 253.0
4 283.0 272.0
5 NaN 291.0
Perhaps not fast but simple to read. Consider setting variables for the column names and the actual shift required.
Edit: Generally shifting is possible by df[2].shift(1)
as already posted however would that cut-off the carryover.
I had the same problem after updating to npm to 5.4.2, npm start giving the same error for most npm commands. Some solution suggest to run it with --no-optional
, but it didn't always work.
Others suggested to downgrade, but I didn't want to downgrade.
I suspected that there was a problem with the installation, not sure what it was.
So I re-updated my npm:
npm i -g npm
and worked fine since then.
Hibernate.dialect
property tells Hibernate to generate the appropriate SQL statements for the chosen database.
A list of available dialects can be found here: http://javamanikandan.blogspot.in/2014/05/sql-dialects-in-hibernate.html
RDBMS Dialect
DB2 org.hibernate.dialect.DB2Dialect
DB2 AS/400 org.hibernate.dialect.DB2400Dialect
DB2 OS390 org.hibernate.dialect.DB2390Dialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
MySQL org.hibernate.dialect.MySQLDialect
MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect
MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect
Oracle (any version) org.hibernate.dialect.OracleDialect
Oracle 9i/10g org.hibernate.dialect.Oracle9Dialect
Sybase org.hibernate.dialect.SybaseDialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect
Microsoft SQL Server org.hibernate.dialect.SQLServerDialect
SAP DB org.hibernate.dialect.SAPDBDialect
Informix org.hibernate.dialect.InformixDialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
Ingres org.hibernate.dialect.IngresDialect
Progress org.hibernate.dialect.ProgressDialect
Mckoi SQL org.hibernate.dialect.MckoiDialect
Interbase org.hibernate.dialect.InterbaseDialect
Pointbase org.hibernate.dialect.PointbaseDialect
FrontBase org.hibernate.dialect.FrontbaseDialect
Firebird org.hibernate.dialect.FirebirdDialect
If you include the library System.Data.Entity
you can use an overload of the Include()
method which takes a lambda expression instead of a string. You can then Select()
over children with Linq expressions rather than string
paths.
return DatabaseContext.Applications
.Include(a => a.Children.Select(c => c.ChildRelationshipType));
Since Compose 1.18 (spec 3.5), you can just override the default network using your own custom name for all Compose YAML files you need. It is as simple as appending the following to them:
networks:
default:
name: my-app
The above assumes you have
version
set to3.5
(or above if they don't deprecate it in 4+).
Other answers have pointed the same; this is a simplified summary.
Add this to your button's click listener:
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
try {
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException exception) {
Toast.makeText(getContext(), "Error text", Toast.LENGTH_SHORT).show();
}
If you have a website url as a variable instead of hardcoded string then don't forget to handle an ActivityNotFoundException and show error. Or you may receive invalid url and app will simply crash. (Pass random string instead of url
variable and see for youself )
Whenever you want to execute an SQL statement that shouldn't return a value or a record set, the ExecuteNonQuery should be used.
So if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement. This sounds very nice, but whenever you use the SQL Server 2005 IDE or Visual Studio to create a stored procedure it adds a small line that ruins everything.
That line is: SET NOCOUNT ON; This line turns on the NOCOUNT feature of SQL Server, which "Stops the message indicating the number of rows affected by a Transact-SQL statement from being returned as part of the results" and therefore it makes the stored procedure always to return -1 when called from the application (in my case a web application).
In conclusion, remove that line from your stored procedure, and you will now get a value indicating the number of rows affected by the statement.
Happy programming!
Having the .htaccess file on the root folder, add this line. Make sure to delete all other useless rules you tried before:
Options -Indexes
Or try:
Options All -Indexes
Maybe you can integrate MuPdf in your application. Here is I've described how to do this: Integrate MuPDF Reader in an app
Well, if you are using jQuery, it's simpler.
if ($.trim(val).length === 0){
// string is invalid
}
Got the same issue. Read this. Disabled the antivirus software (mcaffee). Et voila
Confirmed by the antivirus log:
Blocked by Access Protection rule d:\mingw64\x86_64-w64-mingw32\bin\ld.exe d:\workspace\cpp\bar\foo.exe User-defined Rules:ctx3 Action blocked : Create
You need to iterate through all the enum values in Animal and return the value that matches the description you need.
It's the Return or Enter key on keyboard.
That's pretty much all you need:
mysql> select * from t;
+------+-------+
| id | data |
+------+-------+
| 1 | max |
| 2 | linda |
| 3 | sam |
| 4 | henry |
+------+-------+
4 rows in set (0.02 sec)
mysql> update t set data=concat(data, 'a');
Query OK, 4 rows affected (0.01 sec)
Rows matched: 4 Changed: 4 Warnings: 0
mysql> select * from t;
+------+--------+
| id | data |
+------+--------+
| 1 | maxa |
| 2 | lindaa |
| 3 | sama |
| 4 | henrya |
+------+--------+
4 rows in set (0.00 sec)
Not sure why you'd be having trouble, though I am testing this on 5.1.41
While there are no "official guidelines" I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(...). That way you only need to check and handle the parameters once and only once.
public class Simple {
public Simple() {
this(null);
}
public Simple(Resource r) {
this(r, null);
}
public Simple(Resource r1, Resource r2) {
// Guard statements, initialize resources or throw exceptions if
// the resources are wrong
if (r1 == null) {
r1 = new Resource();
}
if (r2 == null) {
r2 = new Resource();
}
// do whatever with resources
}
}
From a unit testing standpoint, it'll become easy to test the class since you can put in the resources into it. If the class has many resources (or collaborators as some OO-geeks call it), consider one of these two things:
public class SimpleParams {
Resource r1;
Resource r2;
// Imagine there are setters and getters here but I'm too lazy
// to write it out. you can make it the parameter class
// "immutable" if you don't have setters and only set the
// resources through the SimpleParams constructor
}
The constructor in Simple only either needs to split the SimpleParams
parameter:
public Simple(SimpleParams params) {
this(params.getR1(), params.getR2());
}
…or make SimpleParams
an attribute:
public Simple(Resource r1, Resource r2) {
this(new SimpleParams(r1, r2));
}
public Simple(SimpleParams params) {
this.params = params;
}
Make a factory class that initializes the resources for you, which is favorable if initializing the resources is a bit difficult:
public interface ResourceFactory {
public Resource createR1();
public Resource createR2();
}
The constructor is then done in the same manner as with the parameter class:
public Simple(ResourceFactory factory) {
this(factory.createR1(), factory.createR2());
}
Yeah... you can mix and match both ways depending on what is easier for you at the time. Parameter classes and simple factory classes are pretty much the same thing considering the Simple
class that they're used the same way.
The following piece of code allows us to get the status of the network on our Android device
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mtv=findViewById(R.id.textv);
ConnectivityManager connectivityManager=
(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(((Network)connectivityManager.getActiveNetwork())!=null)
mtv.setText("true");
else
mtv.setText("fasle");
}
}
}
Caused by missing (not corrupt) App.Config file. Adding new (Add -> New Item... -> Application Configuration File) fixed it.
Open chrome, go to chrome://settings/languages
On the left, you should see a list of languages. Use mouse to drag the language you want to the top, that will change the order for the values in Accept-language of requests.
If you still don't see the language you prefer, it may be cookies. Go to cookies and clean it up you should be good.
javac -version
in a terminal will do
Check if the first character is '\0'. You should also probably check if your pointer is NULL.
char *c = "";
if ((c != NULL) && (c[0] == '\0')) {
printf("c is empty\n");
}
You could put both of those checks in a function to make it convenient and easy to reuse.
Edit: In the if statement can be read like this, "If c is not zero and the first character of character array 'c' is not '\0' or zero, then...".
The &&
simply combines the two conditions. It is basically like saying this:
if (c != NULL) { /* AND (or &&) */
if (c[0] == '\0') {
printf("c is empty\n");
}
}
You may want to get a good C programming book if that is not clear to you. I could recommend a book called "The C Programming Language".
The shortest version equivalent to the above would be:
if (c && !c[0]) {
printf("c is empty\n");
}
After opening and logging in to MS SQL Server Management studio
...
You're done!
Here is another one, I think. Just for reference. Let's set a variable to be an instantance of class StringVar
If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.
There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.
text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
^^^^^^^^^^^^^^^^^
def depositCallBack(self,event):
text.set('change the value')
It works fine, Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "?????",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
Clean, safe solution in pure standard C:
#include <stdio.h>
#define STRF(x) #x
#define STRINGIFY(x) STRF(x)
/* list of enum constants */
#define TEST_0 hello
#define TEST_1 world
typedef enum
{
TEST_0,
TEST_1,
TEST_N
} test_t;
const char* test_str[]=
{
STRINGIFY(TEST_0),
STRINGIFY(TEST_1),
};
int main()
{
_Static_assert(sizeof test_str / sizeof *test_str == TEST_N,
"Incorrect number of items in enum or look-up table");
printf("%d %s\n", hello, test_str[hello]);
printf("%d %s\n", world, test_str[world]);
test_t x = world;
printf("%d %s\n", x, test_str[x]);
return 0;
}
Output
0 hello
1 world
1 world
Rationale
When solving the core problem "have enum constants with corresponding strings", a sensible programmer will come up with the following requirements:
The first requirement, and maybe also the second, can be fulfilled with various messy macro solutions such as the infamous "x macro" trick, or other forms of macro magic. The problem with such solutions is that they leave you with a completely unreadable mess of mysterious macros - they don't meet the third requirement above.
The only thing needed here is actually to have a string look-up table, which we can access by using the enum variable as index. Such a table must naturally correspond directly to the enum and vice versa. When one of them is updated, the other has to be updated too, or it will not work.
Explanation of the code
Suppose we have an enum like
typedef enum
{
hello,
world
} test_t;
This can be changed to
#define TEST_0 hello
#define TEST_1 world
typedef enum
{
TEST_0,
TEST_1,
} test_t;
With the advantage that these macro constants can now be used elsewhere, to for example generate a string look-up table. Converting a pre-processor constant to a string can be done with a "stringify" macro:
#define STRF(x) #x
#define STRINGIFY(x) STRF(x)
const char* test_str[]=
{
STRINGIFY(TEST_0),
STRINGIFY(TEST_1),
};
And that's it. By using hello
, we get the enum constant with value 0. By using test_str[hello]
we get the string "hello".
To make the enum and look-up table correspond directly, we have to ensure that they contain the very same amount of items. If someone would maintain the code and only change the enum, and not the look-up table, or vice versa, this method won't work.
The solution is to have the enum to tell you how many items it contains. There is a commonly-used C trick for this, simply add an item at the end, which only fills the purpose of telling how many items the enum has:
typedef enum
{
TEST_0,
TEST_1,
TEST_N // will have value 2, there are 2 enum constants in this enum
} test_t;
Now we can check at compile time that the number of items in the enum is as many as the number of items in the look-up table, preferably with a C11 static assert:
_Static_assert(sizeof test_str / sizeof *test_str == TEST_N,
"Incorrect number of items in enum or look-up table");
(There are ugly but fully-functional ways to create static asserts in older versions of the C standard too, if someone insists on using dinosaur compilers. As for C++, it supports static asserts too.)
As a side note, in C11 we can also achieve higher type safety by changing the stringify macro:
#define STRINGIFY(x) _Generic((x), int : STRF(x))
(int
because enumeration constants are actually of type int
, not test_t
)
This will prevent code like STRINGIFY(random_stuff)
from compiling.
You can use round function. Here some example
numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53, 8.13, 3.97, 10.08])
IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.
>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']
…or a shorter try:
library(XML)
library(RCurl)
library(rlist)
theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))
the picked table is the longest one on the page
tables[[which.max(n.rows)]]
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
In my case, this was happening because I used a relative module path in project-level urls.py, INSTALLED_APPS
and apps.py
instead of being rooted in the project root. i.e. absolute module paths throughout, rather than relative modules paths + hacks.
No matter how much I messed with the paths in INSTALLED_APPS
and apps.py
in my app, I couldn't get both runserver
and pytest
to work til all three of those were rooted in the project root.
Folder structure:
|-- manage.py
|-- config
|-- settings.py
|-- urls.py
|-- biz_portal
|-- apps
|-- portal
|-- models.py
|-- urls.py
|-- views.py
|-- apps.py
With the following, I could run manage.py runserver
and gunicorn with wsgi and use portal
app views without trouble, but pytest would error with ModuleNotFoundError: No module named 'apps'
despite DJANGO_SETTINGS_MODULE
being configured correctly.
config/settings.py:
INSTALLED_APPS = [
...
"apps.portal.apps.PortalConfig",
]
biz_portal/apps/portal/apps.py:
class PortalConfig(AppConfig):
name = 'apps.portal'
config/urls.py:
urlpatterns = [
path('', include('apps.portal.urls')),
...
]
Changing the app reference in config/settings.py to biz_portal.apps.portal.apps.PortalConfig
and PortalConfig.name
to biz_portal.apps.portal
allowed pytest to run (I don't have tests for portal
views yet) but runserver
would error with
RuntimeError: Model class apps.portal.models.Business doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
Finally I grepped for apps.portal
to see what's still using a relative path, and found that config/urls.py should also use biz_portal.apps.portal.urls
.
This example works perfectly in Android
In kotlin you can use a lambda expression for this. The Kotlin Array Constructor definition is:
Array(size: Int, init: (Int) -> T)
Which evaluates to:
skillsSummaryDetailLinesArray = Array(linesLen) {
i: Int -> skillsSummaryDetailLines!!.getString(i)
}
Or:
skillsSummaryDetailLinesArray = Array<String>(linesLen) {
i: Int -> skillsSummaryDetailLines!!.getString(i)
}
In this example the field definition was:
private var skillsSummaryDetailLinesArray: Array<String>? = null
Hope this helps
I just encountered the similar problem and found a series of steps did help me. Of course few of them is to Change the network to a stronger,better one.or if you have only one network then try Reconnecting to the network and then simply INVALIDATE/RESTART your android studio. If it still shows the error you need to add the "maven" in repositories and point it out to the link as shown below: maven { url "http://jcenter.bintray.com"}
Finally,Go to *File *Settings *Build,Execution and deployment *Gradle *Android Studio --------And check Enable maven repository option.
After that simply clean and rebuild your APP and you will be good to go.
The accepted answer is correct but it doesn't tell you how to use it. This is how you use indexOf and substring functions together.
String filename = "abc.def.ghi"; // full file name
int iend = filename.indexOf("."); //this finds the first occurrence of "."
//in string thus giving you the index of where it is in the string
// Now iend can be -1, if lets say the string had no "." at all in it i.e. no "." is found.
//So check and account for it.
String subString;
if (iend != -1)
{
subString= filename.substring(0 , iend); //this will give abc
}
You would typically do something like:
protected void btnClose_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}
However, keep in mind that different things will happen in different scenerios.
Firefox won't let you close a window that wasn't opened by you (opened with window.open()
).
IE7 will prompt the user with a "This page is trying to close (Yes | No)" dialog.
In any case, you should be prepared to deal with the window not always closing!
One fix for the 2 above issues is to use:
protected void btnClose_Click(object sender, EventArgs e) {
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}
And create a close.html:
<html><head>
<title></title>
<script language="javascript" type="text/javascript">
var redirectTimerId = 0;
function closeWindow()
{
window.opener = top;
redirectTimerId = window.setTimeout('redirect()', 2000);
window.close();
}
function stopRedirect()
{
window.clearTimeout(redirectTimerId);
}
function redirect()
{
window.location = 'default.aspx';
}
</script>
</head>
<body onload="closeWindow()" onunload="stopRedirect()" style="">
<center><h1>Please Wait...</h1></center>
</body></html>
Note that close.html will redirect to default.aspx if the window does not close after 2 sec for some reason.
Make sure not to miss the explanation of :host-context
which is directly above ::ng-deep
in the angular guide : https://angular.io/guide/component-styles. I missed it up until now and wish I'd seen it sooner.
::ng-deep
is often necessary when you didn't write the component and don't have access to its source, but :host-context
can be a very useful option when you do.
For example I have a black <h1>
header inside a component I designed, and I want the ability to change it to white when it's displayed on a dark themed background.
If I didn't have access to the source I may have to do this in the css for the parent:
.theme-dark widget-box ::ng-deep h1 { color: white; }
But instead with :host-context
you can do this inside the component.
h1
{
color: black; // default color
:host-context(.theme-dark) &
{
color: white; // color for dark-theme
}
// OR set an attribute 'outside' with [attr.theme]="'dark'"
:host-context([theme='dark']) &
{
color: white; // color for dark-theme
}
}
This will look anywhere in the component chain for .theme-dark
and apply the css to the h1 if found. This is a good alternative to relying too much on ::ng-deep
which while often necessary is somewhat of an anti-pattern.
In this case the &
is replaced by the h1
(that's how sass/scss works) so you can define your 'normal' and themed/alternative css right next to each other which is very handy.
Be careful to get the correct number of :
. For ::ng-deep
there are two and for :host-context
only one.
All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.
The python equivalent of NULL
is called None
(good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:
class Node:
def __init__(self): #object initializer to set attributes (fields)
self.val = 0
self.right = None
self.left = None
And then it works pretty much like you would expect:
node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()
Note that unlike in NULL
in C, None
is not a "pointer to nowhere": it is actually the only instance of class NoneType
.
Therefore, as None
is a regular object, you can test for it just like any other object:
if node.left == None:
print("The left node is None/Null.")
Although since None
is a singleton instance, it is considered more idiomatic to use is
and compare for reference equality:
if node.left is None:
print("The left node is None/Null.")
I did have similar problem. For some reason under project properties -> Signing -> Sign ClickOnce manifests was enabled.
I unchecked it and the problem went away.
Bash documentation says that every time $RANDOM
is referenced, a random number between 0 and 32767 is returned. If we sum two consecutive references, we get values from 0 to 65534, which covers the desired range of 63001 possibilities for a random number between 2000 and 65000.
To adjust it to the exact range, we use the sum modulo 63001, which will give us a value from 0 to 63000. This in turn just needs an increment by 2000 to provide the desired random number, between 2000 and 65000. This can be summarized as follows:
port=$((((RANDOM + RANDOM) % 63001) + 2000))
Testing
# Generate random numbers and print the lowest and greatest found
test-random-max-min() {
max=2000
min=65000
for i in {1..10000}; do
port=$((((RANDOM + RANDOM) % 63001) + 2000))
echo -en "\r$port"
[[ "$port" -gt "$max" ]] && max="$port"
[[ "$port" -lt "$min" ]] && min="$port"
done
echo -e "\rMax: $max, min: $min"
}
# Sample output
# Max: 64990, min: 2002
# Max: 65000, min: 2004
# Max: 64970, min: 2000
Correctness of the calculation
Here is a full, brute-force test for the correctness of the calculation. This program just tries to generate all 63001 different possibilities randomly, using the calculation under test. The --jobs
parameter should make it run faster, but it's not deterministic (total of possibilities generated may be lower than 63001).
test-all() {
start=$(date +%s)
find_start=$(date +%s)
total=0; ports=(); i=0
rm -f ports/ports.* ports.*
mkdir -p ports
while [[ "$total" -lt "$2" && "$all_found" != "yes" ]]; do
port=$((((RANDOM + RANDOM) % 63001) + 2000)); i=$((i+1))
if [[ -z "${ports[port]}" ]]; then
ports["$port"]="$port"
total=$((total + 1))
if [[ $((total % 1000)) == 0 ]]; then
echo -en "Elapsed time: $(($(date +%s) - find_start))s \t"
echo -e "Found: $port \t\t Total: $total\tIteration: $i"
find_start=$(date +%s)
fi
fi
done
all_found="yes"
echo "Job $1 finished after $i iterations in $(($(date +%s) - start))s."
out="ports.$1.txt"
[[ "$1" != "0" ]] && out="ports/$out"
echo "${ports[@]}" > "$out"
}
say-total() {
generated_ports=$(cat "$@" | tr ' ' '\n' | \sed -E s/'^([0-9]{4})$'/'0\1'/)
echo "Total generated: $(echo "$generated_ports" | sort | uniq | wc -l)."
}
total-single() { say-total "ports.0.txt"; }
total-jobs() { say-total "ports/"*; }
all_found="no"
[[ "$1" != "--jobs" ]] && test-all 0 63001 && total-single && exit
for i in {1..1000}; do test-all "$i" 40000 & sleep 1; done && wait && total-jobs
For determining how many iterations are needed to get a given probability p/q
of all 63001 possibilities having been generated, I believe we can use the expression below. For example, here is the calculation for a probability greater than 1/2, and here for greater than 9/10.
Via pip
you can specify the package version to install using the following:
pip install opencv-python==2.4.9
However, that package does not seem to be available on pypi.
A little trick for checking available versions:
pip install opencv-python==
Which returns:
Could not find a version that satisfies the requirement opencv-python==
(from versions: 3.1.0.0, 3.1.0.1, 3.1.0.2, 3.1 .0.3, 3.1.0.5, 3.2.0.6, 3.2.0.7) No matching distribution found for opencv-python==
This is one of those instances where jquery actually makes it more complicated than what the DOM already provides.
let { top, bottom, height, width, //etc } = $('#bottom')[0].getBoundingClientRect();
return top;