Options A, B and D seem to be in the same category since they only influence the initial start time, they do warmup of the website like compilation and loading of libraries in memory.
Using C, setting the idle timeout, should be enough so that subsequent requests to the server are served fast (restarting the app pool takes quite some time - in the order of seconds).
As far as I know, the timeout exists to save memory that other websites running in parallel on that machine might need. The price being that one time slow load time.
Besides the fact that the app pool gets shutdown in case of user inactivity, the app pool will also recycle by default every 1740 minutes (29 hours).
From technet:
Internet Information Services (IIS) application pools can be periodically recycled to avoid unstable states that can lead to application crashes, hangs, or memory leaks.
As long as app pool recycling is left on, it should be enough. But if you really want top notch performance for most components, you should also use something like the Application Initialization Module you mentioned.
The second one causes a new char array to be created, and all chars from the String to be copied to this new char array, so I would guess that the first one is faster (and less memory-hungry).
Is it as optional functionality.
If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.
If you will provide restore mechanism then your purchase manager will see restored transaction.
If app should distinguish this options then you should provide functionality for restoring previously purchased products.
<table>
<tbody>
<tr>
<td>
<select name="test" style="color: red;">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
Maybe a simpler solution is to set an overlay in front of your map using FrameLayout
or RelativeLayout
and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapActivity" >
<fragment xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="vertical"
class="com.google.android.gms.maps.SupportMapFragment"/>
<RadioGroup
android:id="@+id/radio_group_list_selector"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#80000000"
android:padding="4dp" >
<RadioButton
android:id="@+id/radioPopular"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="@string/Popular"
android:gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioAZ"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/AZ"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioCategory"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/Category"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioNearBy"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/NearBy"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton3"
android:textColor="@color/textcolor_radiobutton" />
</RadioGroup>
</FrameLayout>
In Swift 2.2 you may have to cast your array to NSArray to use componentsJoinedByString(",")
let stringWithCommas = (yourArray as NSArray).componentsJoinedByString(",")
Old post, I know.
This is also possible using CSS @import url
:
@import url(http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300ita??lic,400italic,500,500italic,700,700italic,900italic,900);
html, body, html * {
font-family: 'Roboto', sans-serif;
}
The reason that you get the 404 File Not Found
error, is that your path to CSS given as a value to the href
attribute is missing context path.
An HTTP request URL contains the following parts:
http://[host]:[port][request-path]?[query-string]
The request path is further composed of the following elements:
Context path: A concatenation of a forward slash (/) with the context
root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]
Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).
Path info: The part of the request path that is not part of the context path or the servlet path.
Read more here.
There are several solutions to your problem, here are some of them:
<c:url>
tag from JSTLIn my Java web applications I usually used <c:url>
tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).
If you say, that your CSS is located inside WebContent folder, then this should work:
<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />
The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):
7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.
NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.
An alternative solution is using Expression Language (EL) to add application context:
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />
Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.
<c:set>
tag from JSTLDISCLAIMER
The idea of this solution was taken from here.
To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set>
tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.
<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />
IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />
), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.
The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.
We need a class that implements ServletContextListener interface. Here is an example of such class:
package com.example.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
sc.setAttribute("ctx", sc.getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent event) {}
}
Now in a JSP we can access this global variable using EL:
<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />
NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
...
<listener>
<listener-class>com.example.listener.AppContextListener</listener-class>
</listener>
...
</webapp>
As suggested by user @gavenkoa you can also use scriptlets like this:
<%= request.getContextPath() %>
For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.
I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.
You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.
System.Environment.TickCount and the System.Diagnostics.Stopwatch class are two that work well for finer resolution and straightforward usage.
See Also:
The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.
When working to create Cross Browser Favicons (including touch icons) there are several things to consider.
The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->
To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon"
for IE to recognize the icon it needs the word shortcut
which is not standard. Also we wrap the .ico
favicon in a IE conditional comment because Chrome and Safari will use the .ico
file if it is present, despite other options available, not what we would like.
The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.
For the rest of the browsers we are going to use the standard way to cite a favicon:
<link rel="icon" href="path/to/favicon.png">
This icon should be 196x196 pixels in size to cover all devices that may use this icon.
To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
Using rel="apple-touch-icon-precomposed"
will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon"
. This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed"
.
As a note: Chrome for Android states:
The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).
Custom Tiles for IE 11+ on Windows 8.1+
IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.
Microsoft recommends creating a few tiles at the following size:
Small: 128 x 128
Medium: 270 x 270
Wide: 558 x 270
Large: 558 x 558
These should be transparent images as we will define a color background next.
Once these images are created you should create an xml file called browserconfig.xml
with the following code:
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square70x70logo src="images/smalltile.png"/>
<square150x150logo src="images/mediumtile.png"/>
<wide310x150logo src="images/widetile.png"/>
<square310x310logo src="images/largetile.png"/>
<TileColor>#009900</TileColor>
</tile>
</msapplication>
</browserconfig>
Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head
:
<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />
For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.
Putting it all together:
To put it all together the above code would look like this:
<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->
<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. -->
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">
Windows Phone Live Tiles
If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:
Here are detailed instructions from Microsoft but here is a synopsis:
Step 1
Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.
Step 2
Add a hidden overlay of this image. Here is example code from Microsoft:
<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
<img src="customtile.png" width="320" height="320" />
<div style='margin-top: 40px'>
Add text/graphic asking user to pin to start using the menu...
</div>
</div>
Step 3
You then can add thew following line to add a pin to start link:
<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>
Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.
Step 4
Next you add some JS to toggle the overlay visibility
<script>
function ToggleTileOverlay() {
var newVisibility = (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
document.getElementById('TileOverlay').style.visibility = newVisibility;
}
</script>
Note on Sizes
I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.
Further Reading
For those who would like more details see the links below:
ThreadLocal
is useful, when you want to have some state that should not be shared amongst different threads, but it should be accessible from each thread during its whole lifetime.
As an example, imagine a web application, where each request is served by a different thread. Imagine that for each request you need a piece of data multiple times, which is quite expensive to compute. However, that data might have changed for each incoming request, which means that you can't use a plain cache. A simple, quick solution to this problem would be to have a ThreadLocal
variable holding access to this data, so that you have to calculate it only once for each request. Of course, this problem can also be solved without the use of ThreadLocal
, but I devised it for illustration purposes.
That said, have in mind that ThreadLocal
s are essentially a form of global state. As a result, it has many other implications and should be used only after considering all the other possible solutions.
The first answer doesn't reflect the current Container vs Presenter paradigm.
If you need to do something, like validate a password, you'd likely have a function that does it. You'd be passing that function to your reusable view as a prop.
So, the correct way to do it is to write a ValidatorContainer, which will have that function as a property, and wrap the form in it, passing the right props in to the child. When it comes to your view, your validator container wraps your view and the view consumes the containers logic.
Validation could be all done in the container's properties, but it you're using a 3rd party validator, or any simple validation service, you can use the service as a property of the container component and use it in the container's methods. I've done this for restful components and it works very well.
If there's a bit more configuration necessary, you can use a Provider/Consumer model. A provider is a high level component that wraps somewhere close to and underneath the top application object (the one you mount) and supplies a part of itself, or a property configured in the top layer, to the context API. I then set my container elements to consume the context.
The parent/child context relations don't have to be near each other, just the child has to be descended in some way. Redux stores and the React Router function in this way. I've used it to provide a root restful context for my rest containers (if I don't provide my own).
(note: the context API is marked experimental in the docs, but I don't think it is any more, considering what's using it).
//An example of a Provider component, takes a preconfigured restful.js_x000D_
//object and makes it available anywhere in the application_x000D_
export default class RestfulProvider extends React.Component {_x000D_
constructor(props){_x000D_
super(props);_x000D_
_x000D_
if(!("restful" in props)){_x000D_
throw Error("Restful service must be provided");_x000D_
}_x000D_
}_x000D_
_x000D_
getChildContext(){_x000D_
return {_x000D_
api: this.props.restful_x000D_
};_x000D_
}_x000D_
_x000D_
render() {_x000D_
return this.props.children;_x000D_
}_x000D_
}_x000D_
_x000D_
RestfulProvider.childContextTypes = {_x000D_
api: React.PropTypes.object_x000D_
};
_x000D_
A further way I haven't tried, but seen used, is to use middleware in conjunction with Redux. You define your service object outside the application, or at least, higher than the redux store. During store creation, you inject the service into the middleware and the middleware handles any actions that affect the service.
In this way, I could inject my restful.js object into the middleware and replace my container methods with independent actions. I'd still need a container component to provide the actions to the form view layer, but connect() and mapDispatchToProps have me covered there.
The new v4 react-router-redux uses this method to impact the state of the history, for example.
//Example middleware from react-router-redux_x000D_
//History is our service here and actions change it._x000D_
_x000D_
import { CALL_HISTORY_METHOD } from './actions'_x000D_
_x000D_
/**_x000D_
* This middleware captures CALL_HISTORY_METHOD actions to redirect to the_x000D_
* provided history object. This will prevent these actions from reaching your_x000D_
* reducer or any middleware that comes after this one._x000D_
*/_x000D_
export default function routerMiddleware(history) {_x000D_
return () => next => action => {_x000D_
if (action.type !== CALL_HISTORY_METHOD) {_x000D_
return next(action)_x000D_
}_x000D_
_x000D_
const { payload: { method, args } } = action_x000D_
history[method](...args)_x000D_
}_x000D_
}
_x000D_
The most direct way to get a list of columns of certain dtype e.g. 'object':
df.select_dtypes(include='object').columns
For example:
>>df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
>>df.dtypes
A int64
B float64
C object
D object
E int64
dtype: object
To get all 'object' dtype columns:
>>df.select_dtypes(include='object').columns
Index(['C', 'D'], dtype='object')
For just the list:
>>list(df.select_dtypes(include='object').columns)
['C', 'D']
What am I doing incorrectly?
You have to convert html to javascript object, and then as a second step to json throug JSON.Stringify.
How can I receive a json object in the controller?
View:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://raw.githubusercontent.com/marioizquierdo/jquery.serializeJSON/master/jquery.serializejson.js"></script>
var obj = $("#form1").serializeJSON({ useIntKeysAsArrayIndex: true });
$.post("http://localhost:52161/Default/PostRawJson/", { json: JSON.stringify(obj) });
<form id="form1" method="post">
<input name="OrderDate" type="text" /><br />
<input name="Item[0][Id]" type="text" /><br />
<input name="Item[1][Id]" type="text" /><br />
<button id="btn" onclick="btnClick()">Button</button>
</form>
Controller:
public void PostRawJson(string json)
{
var order = System.Web.Helpers.Json.Decode(json);
var orderDate = order.OrderDate;
var secondOrderId = order.Item[1].Id;
}
You can just specify the python version when running a program:
for python 2:
python filename.py
for python 3:
python3 filename.py
There are two cases in which the CloneNotSupportedException
will be thrown:
Cloneable
(assuming that the actual cloning eventually defers to Object
's clone method). If the class you are writing this method in implements Cloneable
, this will never happen (since any sub-classes will inherit it appropriately).Cloneable
.The latter case cannot occur in your class (as you're directly calling the superclass' method in the try
block, even if invoked from a subclass calling super.clone()
) and the former should not since your class clearly should implement Cloneable
.
Basically, you should log the error for sure, but in this particular instance it will only happen if you mess up your class' definition. Thus treat it like a checked version of NullPointerException
(or similar) - it will never be thrown if your code is functional.
In other situations you would need to be prepared for this eventuality - there is no guarantee that a given object is cloneable, so when catching the exception you should take appropriate action depending on this condition (continue with the existing object, take an alternative cloning strategy e.g. serialize-deserialize, throw an IllegalParameterException
if your method requires the parameter by cloneable, etc. etc.).
Edit: Though overall I should point out that yes, clone()
really is difficult to implement correctly and difficult for callers to know whether the return value will be what they want, doubly so when you consider deep vs shallow clones. It's often better just to avoid the whole thing entirely and use another mechanism.
You can get such a problem when you are two different commands
on same connection - especially calling the second command in a loop
. That is calling the second command for each record returned from the first command. If there are some 10,000 records returned by the first command, this issue will be more likely.
I used to avoid such a scenario by making it as a single command.. The first command returns all the required data and load it into a DataTable.
Note: MARS
may be a solution - but it can be risky and many people dislike it.
Reference
Basically the answer lies in what really happens when a module is required via require
statement. Assuming this is the first time the module is being required.
For example:
var x = require('file1.js');
contents of file1.js:
module.exports = '123';
When the above statement is executed, a Module
object is created. Its constructor function is:
function Module(id, parent) {
this.id = id;
this.exports = {};
this.parent = parent;
if (parent && parent.children) {
parent.children.push(this);
}
this.filename = null;
this.loaded = false;
this.children = [];
}
As you see each module object has a property with name exports
. This is what is eventually returned as part of require
.
Next step of require is to wrap the contents of file1.js into an anonymous function like below:
(function (exports, require, module, __filename, __dirname) {
//contents from file1.js
module.exports = '123;
});
And this anonymous function is invoked the following way, module
here refers to the Module
Object created earlier.
(function (exports, require, module, __filename, __dirname) {
//contents from file1.js
module.exports = '123;
}) (module.exports,require, module, "path_to_file1.js","directory of the file1.js");
As we can see inside the function, exports
formal argument refers to module.exports
. In essence it's a convenience provided to the module programmer.
However this convenience need to be exercised with care. In any case if trying to assign a new object to exports ensure we do it this way.
exports = module.exports = {};
If we do it following way wrong way, module.exports
will still be pointing to the object created as part of module instance.
exports = {};
As as result adding anything to the above exports object will have no effect to module.exports object and nothing will be exported or returned as part of require.
We can use case statement Like this
select Name,EmailId,gender=case
when gender='M' then 'F'
when gender='F' then 'M'
end
from [dbo].[Employees]
WE can also it as follow.
select Name,EmailId,case gender
when 'M' then 'F'
when 'F' then 'M'
end
from [dbo].[Employees]
How do you send the message?
The classes in the System.Net.Mail
namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials
property.
Solutions proposed by the other members don't work for me.
But I found this :
to escape a dot in java regexp write [.]
Extend TextView and override these methods:
CharSequence origText = "";
int maxLines = 2;
@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
origText = text;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
CharSequence text = origText;
onPreDraw();
while(getLineCount() > maxLines) {
text = text.subSequence(0, text.length()-1);
super.setText(text + "...");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
onPreDraw();
}
}
Evaluating "1,2,3" results in (1, 2, 3)
, a tuple
. As you've discovered, tuples are immutable. Convert to a list before processing.
For me the problem with the R class has been related to automatically organized imports.
As AndroidStudio has the option to allow the automatic imports, it took the wrong R class and thats why the ids have not been found and Gradle was throwing errors!
So check if the import to the R class is referencing to the one you need.
The above would very well work, but it seems you have missed the jQuery typecast for the dropdown text. Other than that it would be advisable to use .val()
to set text for an input text type element. With these changes the code would look like the following:
$('#txtEntry2').val($('#ddlCodes option:selected').text());
One reason it is not preferable to write the string like 'string +"Value"+ string'
is because of Localization. In cases where localization is occurring we want the localized string to be correctly formatted, which could be very different from the language being coded in.
For example we need to show the following error in different languages:
MessageBox.Show(String.Format(ErrorManager.GetError("PIDV001").Description, proposalvalue.ProposalSource)
where
'ErrorCollector.GetError("ERR001").ErrorDescription'
returns a string like "Your ID {0} is not valid"
. This message must be localized in many languages. In that case we can't use + in C#. We need to follow string.format.
default_scope
This works for Rails 4+:
class Book < ActiveRecord::Base
default_scope { order(created_at: :desc) }
end
For Rails 2.3, 3, you need this instead:
default_scope order('created_at DESC')
For Rails 2.x:
default_scope :order => 'created_at DESC'
Where created_at
is the field you want the default sorting to be done on.
Note: ASC is the code to use for Ascending and DESC is for descending (desc
, NOT dsc
!).
scope
Once you're used to that you can also use scope
:
class Book < ActiveRecord::Base
scope :confirmed, :conditions => { :confirmed => true }
scope :published, :conditions => { :published => true }
end
For Rails 2 you need named_scope
.
:published
scope gives you Book.published
instead of
Book.find(:published => true)
.
Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed
.
With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries.
You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this:
scope :recent_books, lambda
{ |since_when| where("created_at >= ?", since_when) }
# Note the `where` is making use of AREL syntax added in Rails 3.
Finally you can disable default scope with:
Book.with_exclusive_scope { find(:all) }
or even better:
Book.unscoped.all
which will disable any filter (conditions) or sort (order by).
Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+
So
... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are!
They are like having def self.method_name ...code... end
but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you!
In fact they are Class level methods as they operate on the 1 set of 'all' records.
Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') }
.
As a side note, when used incorrectly, default_scope can be misused/abused.
This is mainly about when it gets used for actions like where
's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results.
For where
selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published
where published
is a named scope.
In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach.
Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code. This only means that inside the method the variables can not be reassigned.
Note that if you have a final object, you can still change the attributes of the object. This is because objects in Java really are pointers to objects. And only the pointer is copied (and will be final in your method), not the actual object.
Before truncating the tables you have to remove all foreign keys. Use this script to generate final scripts to drop and recreate all foreign keys in database. Please set the @action variable to 'CREATE' or 'DROP'.
On BSD systems and Android you can also use fgetln
:
#include <stdio.h>
char *
fgetln(FILE *stream, size_t *len);
Like so:
size_t line_len;
const char *line = fgetln(stdin, &line_len);
The line
is not null terminated and contains \n
(or whatever your platform is using) in the end. It becomes invalid after the next I/O operation on stream. You are allowed to modify the returned line
buffer.
Ear files provide more options to configure the interaction with the application server.
For example: if the hibernate version of the application server is older than the one provided by your dependencies, you can add the following to ear-deployer-jboss-beans.xml for JBOSS to isolate classloaders and avoid conflicts:
<bean name="EARClassLoaderDeployer" class="org.jboss.deployment.EarClassLoaderDeployer">
<property name="isolated">true</property>
</bean>
or to src/main/application/META-INF/jboss-app.xml :
<?xml version="1.0"?>
<jboss-app>
<loader-repository>
loader=nameofyourear.ear
<loader-repository-config>java2ParentDelegation=false</loader-repository-config>
</loader-repository>
</jboss-app>
This will make sure that there is no classloader conflict between your application and the application server.
Normally the classloader mechanism works like this:
When a class loading request is presented to a class loader, it first asks its parent class loader to fulfill the request. The parent, in turn, asks its parent for the class until the request reaches the top of the hierarchy. If the class loader at the top of the hierarchy cannot fulfill the request, then the child class loader that called it is responsible for loading the class.
By isolating the classloaders, your ear classloader will not look in the parent (=JBoss / other AS classloader). As far is I know, this is not possible with war files.
It seems to me that when it displays the "For development purposes only", one cannot see the map configurations as well while developing(or rather playing around with the configurations). In my case I have not enabled billing to be associated with the API I am using and I am thinking that's the reason why its behaving this way.
Relating to 'SSL certificate problem: unable to get local issuer certificate' error. It is important to note that this applies to the system sending the CURL request, and NOT the server receiving the request.
Download the latest cacert.pem from https://curl.haxx.se/ca/cacert.pem
Add the following line to php.ini: (if this is shared hosting and you don't have access to php.ini then you could add this to .user.ini in public_html).
curl.cainfo="/path/to/downloaded/cacert.pem"
Make sure you enclose the path within double quotation marks!!!
By default, the FastCGI process will parse new files every 300 seconds (if required you can change the frequency by adding a couple of files as suggested here https://ss88.uk/blog/fast-cgi-and-user-ini-files-the-new-htaccess/).
Beginner, not too elegant, but shows the basic steps and deductions in JavaScript
/* Array Four Million Numbers */
var j = [];
var x = [1,2];
var even = [];
for (var i = 1;i<4000001;i++){
j.push(i);
}
// Array Even Million
i = 1;
while (i<4000001){
var k = j[i] + j[i-1];
j[i + 1] = k;
if (k < 4000001){
x.push(k);
}
i++;
}
var total = 0;
for (w in x){
if (x[w] %2 === 0){
even.push(x[w]);
}
}
for (num in even){
total += even[num];
}
console.log(x);
console.log(even);
console.log(total);
you can also make it overflow: auto
and give a maximum fixed height and width that way, when the text or whatever is in there, overflows it'll show only the required scrollbar
You can't expect ObjectInputStream
to automagically convert text into objects. The hexadecimal 54657374
is "Test"
as text. You must be sending it directly as bytes.
$('.login').toggle(
function(){
$('#panel').animate({
height: "150",
padding:"20px 0",
backgroundColor:'#000000',
opacity:.8
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
},
function(){
$('#panel').animate({
height: "0",
padding:"0px 0",
opacity:.2
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
});
Doesn't the error exactly tell you what's wrong? You're calling requestWindowFeature
and setFeatureInt
after you're calling setContentView
.
By the way, why are you calling setContentView
twice?
int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);
$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.In case anyone is wondering, I untangled the MS terminology:
Target = (active directory) target
Active directory target = target server running the domain controller
Domain controller = server that verifies your login information
Principal name = your windows username
SSPI = security support provider interface
Security support provider interface = software interface that manages "authenticated
communications" and allows SSPs like TLS to allow SSL, among others
SSP = security support provider (SSPI implementation)
TLS/SSL = you should already know this
= Can't verify your password.
If you need a fully qualified domain name and have no HTTP request, on Linux, you could use:
var child_process = require("child_process");
child_process.exec("hostname -f", function(err, stdout, stderr) {
var hostname = stdout.trim();
});
I always use something like this in a configuration file:
// Toggle this to change the setting
define('DEBUG', true);
// You want all errors to be triggered
error_reporting(E_ALL);
if(DEBUG == true)
{
// You're developing, so you want all errors to be shown
display_errors(true);
// Logging is usually overkill during development
log_errors(false);
}
else
{
// You don't want to display errors on a production environment
display_errors(false);
// You definitely want to log any occurring
log_errors(true);
}
This allows easy toggling between debug settings. You can improve this further by checking on which server the code is running (development, test, acceptance, and production) and change your settings accordingly.
Note that no errors will be logged if error_reporting is set to 0, as cleverly remarked by Korri.
Add a random query string to the src
You could either do this manually by incrementing the querystring each time you make a change:
<script src="test.js?version=1"></script>
Or if you are using a server side language, you could automatically generate this:
ASP.NET:
<script src="test.js?rndstr=<%= getRandomStr() %>"></script>
More info on cache-busting can be found here:
https://curtistimson.co.uk/post/front-end-dev/what-is-cache-busting/
This would work fine.
Push-Location $PSScriptRoot
Write-Host CurrentDirectory $CurDir
In java 8, it's convenient to use the new date lib and getEpochSecond
method to get the timestamp (it's in second)
Instant.now().getEpochSecond();
For ExpressJs router:
router.post('/login', async(req, res) => {
return res.send({redirect: '/yoururl'});
})
Client-side:
success: function (response) {
if (response.redirect) {
window.location = response.redirect
}
},
What levi said about passing it into the constructor is correct, but you could also use an object.
I think what Veverke is trying to say is that you could easily use the delete
keyword on an object to achieve the same effect.
I think you're confused by the terminology; properties are components of the object that you can use as named indices (if you want to think of it that way).
Try something like this:
var obj = {
"bob": "dole",
"mr.": "peabody",
"darkwing": "duck"
};
Then, you could just do this:
delete obj["bob"];
The structure of the object would then be this:
{
"mr.": "peabody",
"darkwing": "duck"
}
Which has the same effect.
You should absolutely use isEmpty()
. Computing the size()
of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there's no optimization for size()
which can't also make isEmpty()
faster, whereas the reverse is not the case.
For example, suppose you had a linked list structure which didn't cache the size (whereas LinkedList<E>
does). Then size()
would become an O(N) operation, whereas isEmpty()
would still be O(1)
.
Additionally of course, using isEmpty()
states what you're actually interested in more clearly.
If you have multiple sub-projects then you need to add the resources folder to each project's run configuration class path like so:
Ensure the new path is top of the entries and then the runtime will check that path first for any resources (before checking sub-paths)
Change name
attribute in pubspec.yaml
(line 1)
For the name of apk, change android:label
in AndroidManifest.xml
From the MySQL 5.5 documentation:
One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.
Previously, at most one TIMESTAMP column per table could be automatically initialized or updated to the current date and time. This restriction has been lifted. Any TIMESTAMP column definition can have any combination of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses. In addition, these clauses now can be used with DATETIME column definitions. For more information, see Automatic Initialization and Updating for TIMESTAMP and DATETIME.
@PeterMajeed's comment in the accepted answer helped me out with a related problem. I am not using the portable library, but have the same build error on a fresh Windows Server 2012 install, where I'm running TeamCity.
Installing the Microsoft .NET Framework 4.5.1 Developer Pack took care of the issue (after having separately installed the MS Build Tools).
You are out of luck, I think. THe problem is not a SQL level problem as all other answers seem to focus on, but simply one of the user interface. Management Studio is not meant to be a general purpose / generic data access interface. It is not there to be your interface, but your administrative area, and it has serious limitations handling binary data and large test data - because people using it within the specified usage profile will not run into this problem.
Presenting large text data is simply not the planned usage.
Your only choice would be a table valued function that takes the text input and cuts it rows for every line, so that Management Studio gets a list of rows, not a single row.
Generally, a parameter is a string value that is most commonly known for being sent from the client to the server (e.g. a form post) and retrieved from the servlet request. The frustrating exception to this is ServletContext initial parameters which are string parameters that are configured in web.xml and exist on the server.
An attribute is a server variable that exists within a specified scope i.e.:
application
, available for the life of the entire applicationsession
, available for the life of the sessionrequest
, only available for the life of the requestpage
(JSP only), available for the current JSP page only I solved the issue by following this link
namespace System.Web.Mvc
{
public sealed class JsonDotNetValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return null;
var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
var bodyText = reader.ReadToEnd();
return String.IsNullOrEmpty(bodyText) ? null : new DictionaryValueProvider<object>(JsonConvert.DeserializeObject<ExpandoObject>(bodyText, new ExpandoObjectConverter()), CultureInfo.CurrentCulture);
}
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
//Remove and JsonValueProviderFactory and add JsonDotNetValueProviderFactory
ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());
}
If Tuple has no key repetitions, it's Simple.
tup = [("A",0),("B",3),("C",5)]
dic = dict(tup)
print(dic)
If tuple has key repetitions.
tup = [("A",0),("B",3),("C",5),("A",9),("B",4)]
dic = {}
for i, j in tup:
dic.setdefault(i,[]).append(j)
print(dic)
In ES6/ES2015 you can use string literal syntax called template literals. Template strings use backtick character instead of single quote ' or double quote marks ". They also preserve new line and tab
const roleName = 'test1';_x000D_
const role_ID = 'test2';_x000D_
const modal_ID = 'test3';_x000D_
const related = 'test4';_x000D_
_x000D_
console.log(`_x000D_
roleName = ${roleName}_x000D_
role_ID = ${role_ID}_x000D_
modal_ID = ${modal_ID}_x000D_
related = ${related}_x000D_
`);
_x000D_
The following works for me, although I did not test every single device there is to test :-)
$('body, html').css('overflow-y', 'hidden');
$('html, body').animate({
scrollTop:0
}, 0);
If you just need the indexed columns EXEC sp_helpindex 'TABLE_NAME'
You can actually use C# generics for this to make it real easy:
var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
file.RemoveAt(12);
File.WriteAllLines("C:\\path", file.ToArray());
This only line helped me (Angular 1.4.8):
$httpProvider.defaults.headers.common['Pragma'] = 'no-cache';
UPD: The problem is IE11 does aggressive caching. When I was looking into Fiddler I noticed that in F12 mode requests are sending "Pragma=no-cache" and endpoint is requested every time I visit a page. But in normal mode endpoint was requested only once at the first time when I visited the page.
It sounds like you want a StackPanel
where the final element uses up all the remaining space. But why not use a DockPanel
? Decorate the other elements in the DockPanel
with DockPanel.Dock="Top"
, and then your help control can fill the remaining space.
XAML:
<DockPanel Width="200" Height="200" Background="PowderBlue">
<TextBlock DockPanel.Dock="Top">Something</TextBlock>
<TextBlock DockPanel.Dock="Top">Something else</TextBlock>
<DockPanel
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Height="Auto"
Margin="10">
<GroupBox
DockPanel.Dock="Right"
Header="Help"
Width="100"
Background="Beige"
VerticalAlignment="Stretch"
VerticalContentAlignment="Stretch"
Height="Auto">
<TextBlock Text="This is the help that is available on the news screen."
TextWrapping="Wrap" />
</GroupBox>
<StackPanel DockPanel.Dock="Left" Margin="10"
Width="Auto" HorizontalAlignment="Stretch">
<TextBlock Text="Here is the news that should wrap around."
TextWrapping="Wrap"/>
</StackPanel>
</DockPanel>
</DockPanel>
If you are on a platform without DockPanel
available (e.g. WindowsStore), you can create the same effect with a grid. Here's the above example accomplished using grids instead:
<Grid Width="200" Height="200" Background="PowderBlue">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<TextBlock>Something</TextBlock>
<TextBlock>Something else</TextBlock>
</StackPanel>
<Grid Height="Auto" Grid.Row="1" Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<GroupBox
Width="100"
Height="Auto"
Grid.Column="1"
Background="Beige"
Header="Help">
<TextBlock Text="This is the help that is available on the news screen."
TextWrapping="Wrap"/>
</GroupBox>
<StackPanel Width="Auto" Margin="10" DockPanel.Dock="Left">
<TextBlock Text="Here is the news that should wrap around."
TextWrapping="Wrap"/>
</StackPanel>
</Grid>
</Grid>
You are missing, that \ is the escape character.
Look here: http://docs.python.org/reference/lexical_analysis.html at 2.4.1 "Escape Sequence"
Most importantly \n is a newline character. And \\ is an escaped escape character :D
>>> a = 'a\\\\nb'
>>> a
'a\\\\nb'
>>> print a
a\\nb
>>> a.replace('\\\\', '\\')
'a\\nb'
>>> print a.replace('\\\\', '\\')
a\nb
I Found Solution Of You Question But In Stack Not Allow to Upload Video See the link below it show better explain
Here's an example where I found the replace( ) function helpful for giving me insight. The problem required a long integer vector be changed into a character vector and with its integers replaced by given character values.
## figuring out replace( )
(test <- c(rep(1,3),rep(2,2),rep(3,1)))
which looks like
[1] 1 1 1 2 2 3
and I want to replace every 1 with an A and 2 with a B and 3 with a C
letts <- c("A","B","C")
so in my own secret little "dirty-verse" I used a loop
for(i in 1:3)
{test <- replace(test,test==i,letts[i])}
which did what I wanted
test
[1] "A" "A" "A" "B" "B" "C"
In the first sentence I purposefully left out that the real objective was to make the big vector of integers a factor vector and assign the integer values (levels) some names (labels).
So another way of doing the replace( ) application here would be
(test <- factor(test,labels=letts))
[1] A A A B B C
Levels: A B C
Is not possbile!
The only way is to obfuscate javascript or minify your javascript which makes it hard for the end user to reverse engineer. however its not impossible to reverse engineer.
You don't need to test if $?
is not 0
. The shell provides &&
and ||
so you can easily branch based on implicit result of that test:
some_command && {
# executes this block of code,
# if some_command would result in: $? -eq 0
} || {
# executes this block of code,
# if some_command would result in: $? -ne 0
}
You can remove either branch, depending on what you want. So if you just want to test for failure (i.e. $? -ne 0
):
some_command_returning_nonzero || {
# executes this block of code when: $? -ne 0
# and nothing if the command succeeds: $? -eq 0
}
However, the code you provided in the question works, as is. I'm confused that you got syntax errors & concluded that $?
was a string. It's most likely that the errant code causing the syntax error was not provided with the question. This is especially evident because you claim that no one else's solutions work either. When this happens, you have to re-evaluate your assumptions.
NB: The code above may give confusing results if the code inside the braces returns an error. In that case simply use the if command instead, like this:
if some_command; then
# executes this block of code,
# if some_command would result in: $? -eq 0
else
# executes this block of code,
# if some_command would result in: $? -ne 0
fi
The best way is to check the type, because undefined
/null
/false
are a tricky thing in JS.
So:
if(typeof obj !== "undefined") {
// obj is a valid variable, do something here.
}
Note that typeof
always returns a string, and doesn't generate an error if the variable doesn't exist at all.
comm.Parameters.Add("person", "Myname");
You should be able to do this by checking the value of $_SERVER['HTTPS']
(it should only be set when using https).
function json2array(json){
var result = [];
var keys = Object.keys(json);
keys.forEach(function(key){
result.push(json[key]);
});
return result;
}
See this complete explanation: http://book.mixu.net/node/ch5.html
Only you want to set default value parameter. This calling third overloading method.
dt.Columns.Add("MyRow", type(System.Int32),0);
As simple as that.
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
dataObj = JSON.parse(str);
def post(self,request):
serializer = ProductSerializer(data=request.DATA, files=request.FILES)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
sudo yum install python36 python36-devel python36-libs python36-tools
if using python36, this is the best path for set up. Corrected this error for me on an aws ec2 instance
public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)
I am also new to Android , so i might be wrong. But as per my understanding while using this for listview creation 2nd argument is the layout of list items. A layout consists of many views (image view,text view etc). With 3rd argument you are specifying in which view or textview you want the text to be displayed.
I haven't found any way to do that in Android Studio, but I access the db with a remote shell instead of pulling the file each time.
Find all info here: http://developer.android.com/tools/help/sqlite3.html
1- Go to your platform-tools folder in a command prompt
2- Enter the command adb devices
to get the list of your devices
C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb devices
List of devices attached
emulator-xxxx device
3- Connect a shell to your device:
C:\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb -s emulator-xxxx shell
4a- You can bypass this step on rooted device
run-as <your-package-name>
4b- Navigate to the folder containing your db file:
cd data/data/<your-package-name>/databases/
5- run sqlite3 to connect to your db:
sqlite3 <your-db-name>.db
6- run sqlite3 commands that you like eg:
Select * from table1 where ...;
Note: Find more commands to run below.
There are a few steps to see the tables in an SQLite database:
List the tables in your database:
.tables
List how the table looks:
.schema tablename
Print the entire table:
SELECT * FROM tablename;
List all of the available SQLite prompt commands:
.help
It can be done, I found it elsewhere on the web...this is no way my work ! :)
Option Explicit
' Import
Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long
Private Declare Function SetDlgItemText Lib "user32" _
Alias "SetDlgItemTextA" _
(ByVal hDlg As Long, _
ByVal nIDDlgItem As Long, _
ByVal lpString As String) As Long
Private Declare Function SetWindowsHookEx Lib "user32" _
Alias "SetWindowsHookExA" _
(ByVal idHook As Long, _
ByVal lpfn As Long, _
ByVal hmod As Long, _
ByVal dwThreadId As Long) As Long
Private Declare Function UnhookWindowsHookEx Lib "user32" _
(ByVal hHook As Long) As Long
' Handle to the Hook procedure
Private hHook As Long
' Hook type
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5
' Constants
Public Const IDOK = 1
Public Const IDCANCEL = 2
Public Const IDABORT = 3
Public Const IDRETRY = 4
Public Const IDIGNORE = 5
Public Const IDYES = 6
Public Const IDNO = 7
Public Sub MsgBoxSmile()
' Set Hook
hHook = SetWindowsHookEx(WH_CBT, _
AddressOf MsgBoxHookProc, _
0, _
GetCurrentThreadId)
' Run MessageBox
MsgBox "Smiling Message Box", vbYesNo, "Message Box Hooking"
End Sub
Private Function MsgBoxHookProc(ByVal lMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long
If lMsg = HCBT_ACTIVATE Then
SetDlgItemText wParam, IDYES, "Yes :-)"
SetDlgItemText wParam, IDNO, "No :-("
' Release the Hook
UnhookWindowsHookEx hHook
End If
MsgBoxHookProc = False
End Function
You're looking for the zip builtin function. From the docs:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
How about:
firstNonNull = FluentIterable.from(
Lists.newArrayList( a, b, c, ... ) )
.firstMatch( Predicates.notNull() )
.or( someKnownNonNullDefault );
Java ArrayList conveniently allows null entries and this expression is consistent regardless of the number of objects to be considered. (In this form, all the objects considered need to be of the same type.)
This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.
You could use the regular expression library which accepts the Posix standard [[:ASCII:]] definition.
One thing to add, the url is case sensitive. Note that:
apps.facebook.com/HELLO
is different in the linter's eyes then
apps.facebook.com/hello
Be sure to use the exact site url that was entered in the developer settings for the app. The linter will return the properties otherwise but will not refresh the cache.
This is an updated solution for HTML 5 if anyone is interested & not fond of "floating".
Table works great in this case as you can set the fixed width to the table & table-cell.
.content-container{
display: table;
width: 300px;
}
.content .right{
display: table-cell;
background-color:green;
width: 100px;
}
http://jsfiddle.net/EAEKc/596/ original source code from @merkuro
There is not a Google Chrome extension comparable to Selenium IDE.
Scirocco is only a partial (and reportedly unreliable) implementation.
There is another plugin, the Bug Buster Test Recorder, but it only works with their service. I don't know it's effectiveness.
Sahi and TestComplete can also record, but neither are free, and are not browser plugins.
iMacros is a plugin that allows record and playback, but is not geared towards testing, and is not compatible with Selenium.
It sounds like there is a demand for a tool like this, and Firefox is becoming unsupported by Selenium. So, while I know Stack Overflow isn't the forum for this, anyone interested in helping make it happen, let me know.
I'd be interested in what the limitations are and why it hasn't been done. Is it just that the official Selenium team doesn't want to support it, or is there a technical limitation?
Add your php folder path to the System PATH and everything should work fine. It will also fix some other extensions that are broken.
I took a few answers mentioned above and compiled this one, which can also generate a nice description for each target and it works for targets with variables too.
Example Makefile:
APPS?=app1 app2
bin: $(APPS:%=%.bin)
@# Help: A composite target that relies only on other targets
$(APPS:%=%.bin): %.bin:
echo "build binary"
@# Help: A target with variable name, value = $*
test:
echo $(MAKEFLAGS)
echo "starting test"
@# Help: A normal target without variables
# A target without any help description
clean:
echo $(MAKEFLAGS)
echo "Cleaning..."
MAKEOVERRIDES =
help:
@printf "%-20s %s\n" "Target" "Description"
@printf "%-20s %s\n" "------" "-----------"
@make -pqR : 2>/dev/null \
| awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' \
| sort \
| egrep -v -e '^[^[:alnum:]]' -e '^$@$$' \
| xargs -I _ sh -c 'printf "%-20s " _; make _ -nB | (grep -i "^# Help:" || echo "") | tail -1 | sed "s/^# Help: //g"'
Example output:
$ make help
Target Description
------ -----------
app1.bin A target with variable name, value = app1
app2.bin A target with variable name, value = app2
bin A composite target that relies only on other targets
clean
test A normal target without variables
How does it work:
The top part of the make help
target works exactly as posted by mklement0 here - How do you get the list of targets in a makefile?.
After getting the list of targets, it runs make <target> -nB
as a dry run for each target and parses the last line that starts with @# Help:
for the description of the target. And that or an empty string is printed in a nicely formatted table.
As you can see, the variables are even expanded within the description as well, which is a huge bonus in my book :).
Assume that we want to get a list of certain images from a PHP server using the POST method.
You have to provide two parameters in the form for the POST method. Here is how you are going to do.
app.controller('gallery-item', function ($scope, $http) {
var url = 'service.php';
var data = new FormData();
data.append("function", 'getImageList');
data.append('dir', 'all');
$http.post(url, data, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function (response) {
// This function handles success
console.log('angular:', response);
}, function (response) {
// this function handles error
});
});
I have tested it on my system and it works.
edit: I just saw you meant in c#. Here is a better way with unmanaged code:
ManagementClass oMClass = new ManagementClass ("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection colMObj = oMCLass.GetInstances();
foreach(ManagementObject objMO in colMObj)
Console.WriteLine(objMO["MacAddress"].ToString());
You have to do:
git branch <branch_name> <commit>
(you were interchanging the branch name and commit)
Or you can do:
git checkout -b <branch_name> <commit>
If in place of you use branch name, you get a branch out of tip of the branch.
Another way of doing it would be:
stuff = Object.assign(stuff, {$(this).attr('value'):$(this).attr('checked')});
Read more here: Object.assign()
Worth noting that ImageGrab only works on MSWindows.
For cross platform compatibility, a person may be best off with using the wxPython library. http://wiki.wxpython.org/WorkingWithImages#A_Flexible_Screen_Capture_App
import wx
wx.App() # Need to create an App instance before doing anything
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem # Release bitmap
bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
Use the css property overflow . For example:
.item{
width : 100px;
overflow:hidden;
}
The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.
I hope this helps.
An <input type=hidden>
element is not a hidden input box. It is simply a form field that has a value set via markup or via scripting, not via user input. You can use it for multi-line data too, e.g.
<input type=hidden name=stuff value=
"Hello
world, how
are you?">
If the value contains the Ascii quotation mark ("), then, as for any HTML attribute, you need to use Ascii apostrophes (') as attribute value delimites or escape the quote as "
, e.g.
<input type=hidden name=stuff value="A "funny" example">
It's an invisible folder. Just hit Command + Shift + G (takes you to the Go to Folder menu item) and type /etc/
.
Then it will take you to inside that folder.
If javascript is accepted as an answer, I made a jQuery plugin to address this issue (for more information about the issue see CSS: Truncate table cells, but fit as much as possible).
To use the plugin just type
$('selector').tableoverflow();
Plugin: https://github.com/marcogrcr/jquery-tableoverflow
Full example: http://jsfiddle.net/Cw7TD/3/embedded/result/
For me (also XAMPP on Windows 7), this is what worked:
<Directory "C:\projects\myfolder\htdocs">`
AllowOverride All
Require all granted
Options Indexes FollowSymLinks
</Directory>`
It is this line that would cause the 403:
Order allow,deny
Use GA 'set' to ensure routes are picked up for Google realtime analytics. Otherwise subsequent calls to GA will not show in the realtime panel.
$scope.$on('$routeChangeSuccess', function() {
$window.ga('set', 'page', $location.url());
$window.ga('send', 'pageview');
});
Google strongly advises this approach generally instead of passing a 3rd param in 'send'. https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
I use this version
<style><%@include file="/WEB-INF/css/style.css"%></style>
Slightly abbreviated could be...
echo date("Y-m-d H:i:s", strtotime($mysqltime));
Please stop writing faulty CSV parsers!
I've seen hundreds of CSV parsers and so called tutorials for them online.
Nearly every one of them gets it wrong!
This wouldn't be such a bad thing as it doesn't affect me but people who try to write CSV readers and get it wrong tend to write CSV writers, too. And get them wrong as well. And these ones I have to write parsers for.
Please keep in mind that CSV (in order of increasing not so obviousness):
"foo","","bar"
or not: "foo",,"bar"
Frodo's Ring
will be 'Frodo''s Ring'
"foo""", """bar", """"
)If you think this is obvious not a problem, then think again. I've seen every single one of these items implemented wrongly. Even in major software packages. (e.g. Office-Suites, CRM Systems)
There are good and correctly working out-of-the-box CSV readers and writers out there:
If you insist on writing your own at least read the (very short) RFC for CSV.
In NetBeans IDE 8.0 you can use a community contributed plugin https://github.com/tusharvjoshi/nbrunwithargs which will allow you to pass arguments while Run Project or Run Single File command.
For passing arguments to Run Project command either you have to set the arguments in the Project properties Run panel, or use the new command available after installing the plugin which says Run with Arguments
For passing command line arguments to a Java file having main method, just right click on the method and choose Run with Arguments command, of this plugin
UPDATE (24 mar 2014) This plugin is now available in NetBeans Plugin Portal that means it can be installed from Plugins dialog box from the available plugins shown from community contributed plugins, in NetBeans IDE 8.0
I have found simpler solution:
$('#clickToCreate').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title to Create"
})
.dialog('open');
});
$('#clickToEdit').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title To Edit"
})
.dialog('open');
});
Hope that helps!
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
SELECT DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0)
This worked perfectly. I actually added a Case statement. Thanks for the post:
SELECT Case(DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0) as Date)
I don't think there's a built-in way to do it without catching exceptions. You could instead use something like this:
public static MyEnum asMyEnum(String str) {
for (MyEnum me : MyEnum.values()) {
if (me.name().equalsIgnoreCase(str))
return me;
}
return null;
}
Edit: As Jon Skeet notes, values()
works by cloning a private backing array every time it is called. If performance is critical, you may want to call values()
only once, cache the array, and iterate through that.
Also, if your enum has a huge number of values, Jon Skeet's map alternative is likely to perform better than any array iteration.
If your main element has some child elements or text, you could make use of it.
Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).
Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.
This element will start acting like his owner is your main element.
HTML
<div class="circle">
<span>Some text</span>
</div>
CSS
.circle {
position: relative; /* or absolute/fixed */
}
.circle:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle:after {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle span {
/* not relative/absolute/fixed */
}
.circle span:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
I've created a new scheme based on my current app.config to get the messages to disappear. I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me.
Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.
String dateStr = "2016-09-17T08:14:03+00:00";
String s = dateStr.replace("Z", "+00:00");
s = s.substring(0, 22) + s.substring(23);
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
Timestamp createdOn = new Timestamp(date.getTime());
mcList.setCreated_on(createdOn);
Java 7 added support for time zone descriptors according to ISO 8601. This can be use in Java 7.
As in most languages the format is
%.2f
you can see more examples here
Edit: I also got this if your concerned about the display of the point in cases of 25.00
{
NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setPositiveFormat:@"0.##"];
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.3]]);
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.0]]);
}
2010-08-22 15:04:10.614 a.out[6954:903] 25.34 2010-08-22 15:04:10.616 a.out[6954:903] 25.3 2010-08-22 15:04:10.617 a.out[6954:903] 25
The response is absolutely no surprise: in fact
In [1]: -5768830964305142685L & 0xffffffff
Out[1]: 1934711907L
so if you want to get reliable responses on ASCII strings, just get the lower 32 bits as uint
. The hash function for strings is 32-bit-safe and almost portable.
On the other side, you can't rely at all on getting the hash()
of any object over which you haven't explicitly defined the __hash__
method to be invariant.
Over ASCII strings it works just because the hash is calculated on the single characters forming the string, like the following:
class string:
def __hash__(self):
if not self:
return 0 # empty
value = ord(self[0]) << 7
for char in self:
value = c_mul(1000003, value) ^ ord(char)
value = value ^ len(self)
if value == -1:
value = -2
return value
where the c_mul
function is the "cyclic" multiplication (without overflow) as in C.
I always thought that for a task that trivial, I wouldn't want to import anything. But i may be wrong, depending on collections.Counter being faster or not.
items = "Whats the simpliest way to add the list items to a dictionary "
stats = {}
for i in items:
if i in stats:
stats[i] += 1
else:
stats[i] = 1
# bonus
for i in sorted(stats, key=stats.get):
print("%d×'%s'" % (stats[i], i))
I think this may be preferable to using count(), because it will only go over the iterable once, whereas count may search the entire thing on every iteration. I used this method to parse many megabytes of statistical data and it always was reasonably fast.
same way you did the fill in, but reverse the indexes:
>>> for j in range(columns):
... for i in range(rows):
... print mylist[i][j],
...
0,0 1,0 2,0 0,1 1,1 2,1
>>>
You would love to read these :-
If you know the network interface (eth0, wlan, tun0 etc):
ifconfig eth0 | grep addr: | awk '{ print $2 }' | cut -d: -f2
JSX:
<select value={ this.state.foo } onChange={this.handleFooChange}>
<option value="A">A</option>
<option value="B">B</option>
</select>
TypeScript:
private handleFooChange = (event: React.FormEvent<HTMLSelectElement>) => {
const element = event.target as HTMLSelectElement;
this.setState({ foo: element.value });
}
I had the same issue and I tried most of the solution provided by other folks but it worked for me with below steps. I have VS 2017.
Steps:
Install-Package EntityFramework -IncludePrerelease
then create a class as
public class MyDBContext : DbContext { public MyDBContext() { } }
and at the last execute
Enable-Migrations -EnableAutomaticMigrations
What didn't work for me:
: Restarting VS.
: only "Enable-Migrations" command, which is without -EnableAutomaticMigrations.
: restoring or updating Nuget Package Manager.
My original error in the beginning was
/* The term 'enable-migration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.At line:1 char:1 + enable-migration + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (enable-migration:String) [], CommandNotFoundException */
Be careful with "/" and "\". Even on Windows the command should be in the form:
\i c:/1.sql
Working example of a download button, to save a cat photo from an url as "cat.jpg":
HTML:
<button onclick="downloadUrl('https://i.imgur.com/AD3MbBi.jpg', 'cat.jpg')">Download</button>
JavaScript:
function downloadUrl(url, filename) {
let xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(e) {
if (this.status == 200) {
const blob = this.response;
const a = document.createElement("a");
document.body.appendChild(a);
const blobUrl = window.URL.createObjectURL(blob);
a.href = blobUrl;
a.download = filename;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(blobUrl);
document.body.removeChild(a);
}, 0);
}
};
xhr.send();
}
You could also look at it from the other way around...
from urlparse import urlparse
[el for el in ['text1', 'FTP://somewhere.com', 'text2', 'http://blah.com:8080/foo/bar#header'] if not urlparse(el).scheme]
I don't know if you even need to wrap it. Won't this work?
SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
FROM availables
INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25'
AND date_add('2009-06-25', INTERVAL 4 DAY)
AND rooms.hostel_id = 5094
GROUP BY availables.bookdate);
If your goal is to return both result sets then you'll need to store it some place temporarily.
I had similar issue and no errors shown in Compilation. I have tried to clean and rebuild without any success. I managed to find the issue by using Invalidate Caches/Restart from file Menu, after the restart I managed to see the compilation error.
Please check the following to be able to install new packages:
1- In Tools -> Global Options -> Packages, uncheck the "Use Internet Explorer library/proxy for HTTP" option,
2- In Tools -> Global Options -> Packages, change the CRAN mirror to "0- Cloud - Rstudio, automatic redirection to servers worldwide"
3- Restart Rstudio.
4- Have fun!
Bootstrap 3 introduced row-no-gutters
in v3.4.0
https://getbootstrap.com/docs/3.4/css/#grid-remove-gutters
You could make a row without gutters, and have a row with gutters inside it for the parts you do want to have a gutter.
I used to do like,
if the activity is not in the foreground
getIntent()
will return null. :=P
Unexpected end of file
means that something else was expected before the PHP parser reached the end of the script.
Judging from your HUGE file, it's probably that you're missing a closing brace (}
) from an if
statement.
Please at least attempt the following things:
;
in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?>
vs <?php echo $this->layouts->print_includes() ?>
. It's not required, so don't use it (or do, just do one or the other).i mange to fix the issue by updating state. when you trigger find or any other query operation on the same record sate has been updated with modified so we need to set status to Detached then you can fire your update change
ActivityEntity activity = new ActivityEntity();
activity.name="vv";
activity.ID = 22 ; //sample id
var savedActivity = context.Activities.Find(22);
if (savedActivity!=null)
{
context.Entry(savedActivity).State = EntityState.Detached;
context.SaveChanges();
activity.age= savedActivity.age;
activity.marks= savedActivity.marks;
context.Entry(activity).State = EntityState.Modified;
context.SaveChanges();
return activity.ID;
}
^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$
should reflect what people usually think of as a well formed decimal number.
The digits before the decimal point can be either a single digit, in which case it can be from 0 to 9, or more than one digits, in which case it cannot start with a 0.
If there are any digits present before the decimal sign, then the decimal and the digits following it are optional. Otherwise, a decimal has to be present followed by at least one digit. Note that multiple trailing 0's are allowed after the decimal point.
grep -E '^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$'
correctly matches the following:
9
0
10
10.
0.
0.0
0.100
0.10
0.01
10.0
10.10
.0
.1
.00
.100
.001
as well as their signed equivalents, whereas it rejects the following:
.
00
01
00.0
01.3
and their signed equivalents, as well as the empty string.
A bit late to the party but you can also use a context manager, if you're opening and closing your file multiple times, or logging data, statistics, etc.
from contextlib import contextmanager
import pandas as pd
@contextmanager
def open_file(path, mode):
file_to=open(path,mode)
yield file_to
file_to.close()
##later
saved_df=pd.DataFrame(data)
with open_file('yourcsv.csv','r') as infile:
saved_df.to_csv('yourcsv.csv',mode='a',header=False)`
Running the following commands solved this for me 1. python manage.py migrate 2. python manage.py makemigrations 3. python manage.py makemigrations appName
Try
safeRunCommand() {
"$@"
if [ $? != 0 ]; then
printf "Error when executing command: '$1'"
exit $ERROR_CODE
fi
}
try this:
var maxid = from i in items
group i by i.clientid int g
select new { id = g.Max(i=>i.ID }
factory_bot sounds like it will do what you are trying to achieve. You can define all the common attributes in the default definition and then override them at creation time. You can also pass an id to the factory:
Factory.define :theme do |t|
t.background_color '0x000000'
t.title_text_color '0x000000',
t.component_theme_color '0x000000'
t.carrier_select_color '0x000000'
t.label_text_color '0x000000',
t.join_upper_gradient '0x000000'
t.join_lower_gradient '0x000000'
t.join_text_color '0x000000',
t.cancel_link_color '0x000000'
t.border_color '0x000000'
t.carrier_text_color '0x000000'
t.public true
end
Factory(:theme, :id => 1, :name => "Lite", :background_color => '0xC7FFD5')
Factory(:theme, :id => 2, :name => "Metallic", :background_color => '0xC7FFD5')
Factory(:theme, :id => 3, :name => "Blues", :background_color => '0x0060EC')
When used with faker it can populate a database really quickly with associations without having to mess about with Fixtures (yuck).
I have code like this in a rake task.
100.times do
Factory(:company, :address => Factory(:address), :employees => [Factory(:employee)])
end
Only using class names is not sufficient in your case.
By.cssSelector(".ban")
has 15 matching nodesBy.cssSelector(".hot")
has 11 matching nodesBy.cssSelector(".ban.hot")
has 5 matching nodesTherefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.
Option 1: Using list items' index (CssSelector or XPath)
Limitations
Example:
driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));
driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5"));
Option 2: Using Selenium's FindElements
, then index them. (CssSelector or XPath)
Limitations
Example:
// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot"));
IWebElement banUsStates = hotBanners[3];
Option 3: Using text (XPath only)
Limitations
Example:
driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));
Option 4: Index the grouped selector (XPath only)
Limitations
Example:
driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));
Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)
Limitations
Example:
driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5"));
Just for the record... I had this problem and after a few hours of trying everything the problem was that the disk was full, and php sessions could not be written into the tmp directory... so if you have this problem check that too...
As of MongoDB 2.4, you can use $setOnInsert (http://docs.mongodb.org/manual/reference/operator/setOnInsert/)
Set 'insertion_date' using $setOnInsert and 'last_update_date' using $set in your upsert command.
To turn your pseudocode into a working example:
now = datetime.utcnow()
for document in update:
collection.update_one(
{"_id": document["_id"]},
{
"$setOnInsert": {"insertion_date": now},
"$set": {"last_update_date": now},
},
upsert=True,
)
Each of the three conditions is evaluated independently[1]:
id != 1 // false
id != 2 // true
id != 3 // true
Then it evaluates false || true || true
, which is true (a || b
is true if either a
or b
is true). I think you want
id != 1 && id != 2 && id != 3
which is only true if the ID is not 1 AND it's not 2 AND it's not 3.
[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.
The other answers only show the changed files.
git log -p DIR
is very useful, if you need the full diff of all changed files in a specific subdirectory.
Example: Show all detailed changes in a specific version range
git log -p 8a5fb..HEAD -- A B
commit 62ad8c5d
Author: Scott Tiger
Date: Mon Nov 27 14:25:29 2017 +0100
My comment
...
@@ -216,6 +216,10 @@ public class MyClass {
+ Added
- Deleted
Use the str_contains
function.
if (str_contains($str, "."))
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
if (strpos($str, '.') !== FALSE)
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
Note that you need to use the !==
operator. If you use !=
or <>
and the '.'
is found at position 0
, the comparison will evaluate to true because 0
is loosely equal to false
.
All of drop down lists disappeared in Build Settings after running the Fix Issue in Xcode 5. Spent several days trying to figure out what was wrong with my provisioning profiles and code signing. Found a link Xcode 4 missing drop down lists in Build Settings and sure enough I needed to re-enabled "Show Values" under the Editor menu. Hopefully this helps anyone else in this predicament.
Also, I had to clear my derived data, clean the solution and quit and reopen Xcode into for the code signing identities to correctly appear. My distribution provisioning profiles where showing up as signed by my developer certificate which was incorrect.
in case u wanna do the validation for "some elements" (not all element) on your form.You can use this method:
$('input[name="element-one"], input[name="element-two"], input[name="element-three"]').valid();
Hope it help everybody :)
EDITED
I have a different approach from other people here, and it an approach that is guaranteed work without dealing with the CookieSyncManager (where you are at the mercy of semantics like "Note that even sync() happens asynchronously").
Essentially, we browse to the correct domain, then we execute javascript from the page context to set cookies for that domain (the same way the page itself would). Two drawbacks to the method are that may introduce an extra round trip time due to the extra http request you have to make; and if your site does not have the equivalent of a blank page, it may flash whatever URL you load first before taking you to the right place.
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.cookie.Cookie;
import android.annotation.SuppressLint;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewFragment {
private static final String BLANK_PAGE = "/blank.html"
private CookieSyncManager mSyncManager;
private CookieManager mCookieManager;
private String mTargetUrl;
private boolean mInitializedCookies;
private List<Cookie> mAllCookies;
public WebViewFragment(Context ctx) {
// We are still required to create an instance of Cookie/SyncManager.
mSyncManager = CookieSyncManager.createInstance(ctx);
mCookieManager = CookieManager.getInstance();
}
@SuppressLint("SetJavaScriptEnabled") public void loadWebView(
String url, List<Cookie> cookies, String domain) {
final WebView webView = ...
webView.setWebViewClient(new CookeWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
mInitializedCookies = false;
mTargetUrl = url;
mAllCookies = cookies;
// This is where the hack starts.
// Instead of loading the url, we load a blank page.
webView.loadUrl("http://" + domain + BLANK_PAGE);
}
public static String buildCookieString(final Cookie cookie) {
// You may want to add the secure flag for https:
// + "; secure"
// In case you wish to convert session cookies to have an expiration:
// + "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
// Note that you cannot set the HttpOnly flag as we are using
// javascript to set the cookies.
return cookie.getName() + "=" + cookie.getValue()
+ "; path=" + cookie.getPath()
+ "; domain=" + cookie.getDomain()
};
public synchronized String generateCookieJavascript() {
StringBuilder javascriptCode = new StringBuilder();
javascriptCode.append("javascript:(function(){");
for (final Cookie cookie : mAllCookies) {
String cookieString = buildCookieString(cookie);
javascriptCode.append("document.cookie=\"");
javascriptCode.append(
StringEscapeUtils.escapeJavascriptString(cookieString));
javascriptCode.append("\";");
}
// We use javascript to load the next url because we do not
// receive an onPageFinished event when this code finishes.
javascriptCode.append("document.location=\"");
javascriptCode.append(
StringEscapeUtils.escapeJavascriptString(mTargetUrl));
javascriptCode.append("\";})();");
return javascriptCode.toString();
}
private class CookieWebViewClient extends WebViewClient {
@Override public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (!mInitializedCookies) {
mInitializedCookies = true;
// Run our javascript code now that the temp page is loaded.
view.loadUrl(generateCookieJavascript());
return;
}
}
}
}
If you trust the domain the cookies are from, you may be able to get away without apache commons, but you have to understand that this can present a XSS risk if you are not careful.
You're using the exec form of ENTRYPOINT. Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, ENTRYPOINT [ "echo", "$HOME" ]
will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: ENTRYPOINT [ "sh", "-c", "echo $HOME" ]
.
When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.(from Dockerfile reference)
In your case, I would use shell form
ENTRYPOINT ./greeting --message "Hello, $ADDRESSEE\!"
So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:
>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"
<html>
<head>
<script language="javascript" type="text/javascript" scr="asd.js"></script>
</head>
<body>
<form name="form1" action="#" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>
</body>
client side scripting
function testJS(){
var name = jQuery("#name").val();
jQuery.load("next.html",function(){
jQuery("#here").html(name);
});
}
jQuery is a js library and it simplifies its programming. So I recommend to use jQuery rathar then js. Here I just took value of input elemnt(id = name) on submit button click event ,then loaded the desired page(next.html), if the load function executes successfully i am calling a function which will put the data in desired place.
jquery load function http://api.jquery.com/load/
Other answer were not working with a generic interface.
This one does, just replace typeof(ISomeInterface) by typeof (T).
List<string> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())
.Where(x => typeof(ISomeInterface).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
.Select(x => x.Name).ToList();
So with
AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())
we get all the assemblies
!x.IsInterface && !x.IsAbstract
is used to exclude the interface and abstract ones and
.Select(x => x.Name).ToList();
to have them in a list.
For the ones developing in Kotlin, there is a sweet method provided by the Anko library that makes the process of displaying a ProgressDialog
a breeze!
Based on that link:
val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")
dialog.show()
//....
dialog.dismiss()
This will show a Progress Dialog with the progress % displayed (for which you have to pass the init
parameter also to calculate the progress).
There is also the indeterminateProgressDialog()
method, which provides the Spinning Circle animation indefinitely until dismissed:
indeterminateProgressDialog("Loading...").show()
Shout out to this blog which led me to this solution.
No - if you want to convert ALL elements of a list, you'll have to touch ALL elements of that list one way or another.
You can specify / write the iteration in different ways (foreach()......, or .ConvertAll() or whatever), but in the end, one way or another, some code is going to iterate over each and every element and convert it.
Marc
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
Closest I can get:
$(function(){_x000D_
$('span').width($('span').width()/2);_x000D_
$('span:nth-child(2)').css('text-indent', -$('span').width());_x000D_
});
_x000D_
body{_x000D_
font-family: arial;_x000D_
}_x000D_
span{_x000D_
display: inline-block;_x000D_
overflow: hidden;_x000D_
}_x000D_
span:nth-child(2){_x000D_
color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span>X</span><span>X</span>
_x000D_
Demo: http://jsfiddle.net/9wxfY/2/
Heres a version that just uses one span: http://jsfiddle.net/9wxfY/4/
If you want to scroll down to the div (id="div1"). Then you can use this code.
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 1500);
guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:
Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.
So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.
I solved my problem just follow this steps:
? Copy .aar package in app/libs.
? Add this in app/build.gradle file:
repositories {
flatDir {
dirs 'libs' //this way we can find the .aar file in libs folder
}
}
? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):
dependencies {
compile(name:'package_name', ext:'aar')
}
So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.
Somehow GenerateConsoleCtrlEvent()
return error if you call it for another process, but you can attach to another console application and send event to all child processes.
void SendControlC(int pid)
{
AttachConsole(pid); // attach to process console
SetConsoleCtrlHandler(NULL, TRUE); // disable Control+C handling for our app
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); // generate Control+C event
}
I was trying things to duplicate the spools you get from sqlplus. I found the following and hope it helps:
Create your sql script file ie:
Please note the echo and serveroutput.
Test_Spool.SQL
Spool 'c:\temp\Test1.txt';
set echo on;
set serveroutput on;
declare
sqlresult varchar2(60);
begin
select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
dbms_output.put_line('The date is ' || sqlresult);
end;
/
Spool off;
set serveroutput off;
set echo off;
Run the script from another worksheet:
@TEST_Spool.SQL
My output from the Test1.txt
set serveroutput on
declare
sqlresult varchar2(60);
begin
select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
dbms_output.put_line('The date is ' || sqlresult);
end;
anonymous block completed
The date is 2016-04-07 09:21:32
Spool of
@RequestMapping
has a String[]
value parameter, so you should be able to specify multiple values like this:
@RequestMapping(value={"", "/", "welcome"})
The highly regarded Joda Time library is also worth a look. This is basis for the new date and time api that is pencilled in for Java 7. The design is neat, intuitive, well documented and avoids a lot of the clumsiness of the original java.util.Date
/ java.util.Calendar
classes.
Joda's DateFormatter
can parse a String to a Joda DateTime
.
Hi i tried this it is working.
$("#change_align").css({"margin-top":"-39px","margin-right":"0px","margin-bottom":"0px","margin-left":"719px"});
It depends where you put this initialisation.
If the array is static as in
char array[100] = {0};
int main(void)
{
...
}
then it is the compiler that reserves the 100 0 bytes in the data segement of the program. In this case you could have omitted the initialiser.
If your array is auto, then it is another story.
int foo(void)
{
char array[100] = {0};
...
}
In this case at every call of the function foo you will have a hidden memset.
The code above is equivalent to
int foo(void)
{
char array[100];
memset(array, 0, sizeof(array));
....
}
and if you omit the initializer your array will contain random data (the data of the stack).
If your local array is declared static like in
int foo(void)
{
static char array[100] = {0};
...
}
then it is technically the same case as the first one.
I had the same error on Debian and all I had to do was:
sudo su
and then run the command again and it worked.
As stated in a similar question, try removing instances of the input-group
class and see if that helps.
refering to bootstrap:
Individual form controls automatically receive some global styling. All textual , , and elements with .form-control are set to width: 100%; by default. Wrap labels and controls in .form-group for optimum spacing.
way mentioned by @dirkgently ( v.begin() + index )
nice and fast for vectors
but std::advance
( v.begin(), index )
most generic way and for random access iterators works constant time too.
EDIT
differences in usage:
std::vector<>::iterator it = ( v.begin() + index );
or
std::vector<>::iterator it = v.begin();
std::advance( it, index );
added after @litb notes.
My Spring boot application has two initializers. One for development and another for production. For development, I use the main method like this:
@SpringBootApplication
public class MyAppInitializer {
public static void main(String[] args) {
SpringApplication.run(MyAppInitializer .class, args);
}
}
My Initializer for production environment extends the SpringBootServletInitializer and looks like this:
@SpringBootApplication
public class MyAppInitializerServlet extends SpringBootServletInitializer{
private static final Logger log = Logger
.getLogger(SpringBootServletInitializer.class);
@Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder builder) {
log.trace("Initializing the application");
return builder.sources(MyAppInitializerServlet .class);
}
}
I use gradle and my build.gradle file applies 'WAR' plugin. When I run it in the development environment, I use bootrun task. Where as when I want to deploy it to production, I use assemble task to generate the WAR and deploy.
I can run like a normal spring application in production without discounting the advantages provided by the inbuilt tomcat while developing. Hope this helps.
Just wishing to avoid the console error, I solved this using a similar approach to Artur's earlier answer, following these steps:
This is not the greatest solution (patched local script to maintain, losing control of where messages are sent) but it solved my issue.
Please see the security warning about removing the targetOrigin URI stated here before using this solution - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
I face the same problem and solved by adding the JAVA_HOME variable with updated version of java in my Ubuntu Machine(16.04). if you are using "Apache Maven 3.3.9" You need to upgrade your JAVA_HOME with java7 or more
Step to Do this
1-sudo vim /etc/environment
2-JAVA_HOME=JAVA Installation Directory (MyCase-/opt/dev/jdk1.7.0_45/)
3-Run echo $JAVA_HOME will give the JAVA_HOME set value
4-Now mvn -version will give the desired output
Apache Maven 3.3.9
Maven home: /usr/share/maven
Java version: 1.7.0_45, vendor: Oracle Corporation
Java home: /opt/dev/jdk1.7.0_45/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.4.0-36-generic", arch: "amd64", family: "unix"
You want to use the null-coalescing operator, which is designed for exactly this purpose.
Using it you end up with this code.
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;
This cannot be done with pure HTML/JS, you will need CSS
CSS:
button {
width: 100%;
height: 100%;
}
Substitute 100% with required size
This can be done in many ways
Though you've already implemented it by now,
you can also use any expect implementation (you'll find alternatives in Perl, Python: pexpect, paramiko, etc..)
In my case, Server had lower version framework than your application. installed latest version framework and it fixed this issue.
Here is the simple solution by StreamEx:
StreamEx.of(list).groupingBy(Function.identity(), MoreCollectors.countingInt());
This has the advantage of reducing the Java stream boilerplate code: collect(Collectors.
For Linux you can retrieve the MAC address using a SIOCGIFHWADDR ioctl.
struct ifreq ifr;
uint8_t macaddr[6];
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0)
return -1;
strcpy(ifr.ifr_name, "eth0");
if (ioctl(s, SIOCGIFHWADDR, (void *)&ifr) == 0) {
if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
memcpy(macaddr, ifr.ifr_hwaddr.sa_data, 6);
return 0;
... etc ...
You've tagged the question "python". I don't know of an existing Python module to get this information. You could use ctypes to call the ioctl directly.
Not for camera but for other files..
In my device I have ES File Explorer
installed and This simply thing works in my case..
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_REQUEST_CODE);
This is not a general solution but might help many of those who just typed "matplotlib surface plot" in Google and landed here.
Suppose you have data = [(x1,y1,z1),(x2,y2,z2),.....,(xn,yn,zn)]
, then you can get three 1-d lists using x, y, z = zip(*data)
. Now you can of course create 3d scatterplot using three 1-d lists.
But, why can't in general this data be used to create surface plot? To understand that consider an empty 3-d plot :
Now, suppose for each possible value of (x, y) on a "discrete" regular grid, you have a z value, then there's no issue & you can in fact get a surface plot:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
x = np.linspace(0, 10, 6) # [0, 2,..,10] : 6 distinct values
y = np.linspace(0, 20, 5) # [0, 5,..,20] : 5 distinct values
z = np.linspace(0, 100, 30) # 6 * 5 = 30 values, 1 for each possible combination of (x,y)
X, Y = np.meshgrid(x, y)
Z = np.reshape(z, X.shape) # Z.shape must be equal to X.shape = Y.shape
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
What's happens when you haven't got z for all possible combinations of (x, y)? Then at the point (at intersection of two black lines on x-y plane on blank plot above), we don't know what is the value of z. It could be anything, we don't know how 'high' or 'low' our surface should be at that point (although it can be approximated using other functions, surface_plot
requires that you supply it arguments where X.shape = Y.shape = Z.shape).
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle("Main Page");
w.show();
return a.exec();
}
NikolaB explained it very well, However example would be helpful to understand, So here is one simple example...
import java.util.concurrent.*;
public class CountDownLatchExample {
public static class ProcessThread implements Runnable {
CountDownLatch latch;
long workDuration;
String name;
public ProcessThread(String name, CountDownLatch latch, long duration){
this.name= name;
this.latch = latch;
this.workDuration = duration;
}
public void run() {
try {
System.out.println(name +" Processing Something for "+ workDuration/1000 + " Seconds");
Thread.sleep(workDuration);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+ "completed its works");
//when task finished.. count down the latch count...
// basically this is same as calling lock object notify(), and object here is latch
latch.countDown();
}
}
public static void main(String[] args) {
// Parent thread creating a latch object
CountDownLatch latch = new CountDownLatch(3);
new Thread(new ProcessThread("Worker1",latch, 2000)).start(); // time in millis.. 2 secs
new Thread(new ProcessThread("Worker2",latch, 6000)).start();//6 secs
new Thread(new ProcessThread("Worker3",latch, 4000)).start();//4 secs
System.out.println("waiting for Children processes to complete....");
try {
//current thread will get notified if all chidren's are done
// and thread will resume from wait() mode.
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All Process Completed....");
System.out.println("Parent Thread Resuming work....");
}
}
As some sugested you can use apache or jax-ws. You can also use tools that generate code from WSDL such as ws-import but in my opinion the best way to consume web service is to create a dynamic client and invoke only operations you want not everything from wsdl. You can do this by creating a dynamic client: Sample code:
String endpointUrl = ...;
QName serviceName = new QName("http://com/ibm/was/wssample/echo/",
"EchoService");
QName portName = new QName("http://com/ibm/was/wssample/echo/",
"EchoServicePort");
/** Create a service and add at least one port to it. **/
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointUrl);
/** Create a Dispatch instance from a service.**/
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName,
SOAPMessage.class, Service.Mode.MESSAGE);
/** Create SOAPMessage request. **/
// compose a request message
MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
// Create a message. This example works with the SOAPPART.
SOAPMessage request = mf.createMessage();
SOAPPart part = request.getSOAPPart();
// Obtain the SOAPEnvelope and header and body elements.
SOAPEnvelope env = part.getEnvelope();
SOAPHeader header = env.getHeader();
SOAPBody body = env.getBody();
// Construct the message payload.
SOAPElement operation = body.addChildElement("invoke", "ns1",
"http://com/ibm/was/wssample/echo/");
SOAPElement value = operation.addChildElement("arg0");
value.addTextNode("ping");
request.saveChanges();
/** Invoke the service endpoint. **/
SOAPMessage response = dispatch.invoke(request);
/** Process the response. **/
U can Install package intl_phone_number_input
dependencies:
intl_phone_number_input: ^0.5.2+2
and try this code:
import 'package:flutter/material.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var darkTheme = ThemeData.dark().copyWith(primaryColor: Colors.blue);
return MaterialApp(
title: 'Demo',
themeMode: ThemeMode.dark,
darkTheme: darkTheme,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(title: Text('Demo')),
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
final TextEditingController controller = TextEditingController();
String initialCountry = 'NG';
PhoneNumber number = PhoneNumber(isoCode: 'NG');
@override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InternationalPhoneNumberInput(
onInputChanged: (PhoneNumber number) {
print(number.phoneNumber);
},
onInputValidated: (bool value) {
print(value);
},
selectorConfig: SelectorConfig(
selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
backgroundColor: Colors.black,
),
ignoreBlank: false,
autoValidateMode: AutovalidateMode.disabled,
selectorTextStyle: TextStyle(color: Colors.black),
initialValue: number,
textFieldController: controller,
inputBorder: OutlineInputBorder(),
),
RaisedButton(
onPressed: () {
formKey.currentState.validate();
},
child: Text('Validate'),
),
RaisedButton(
onPressed: () {
getPhoneNumber('+15417543010');
},
child: Text('Update'),
),
],
),
),
);
}
void getPhoneNumber(String phoneNumber) async {
PhoneNumber number =
await PhoneNumber.getRegionInfoFromPhoneNumber(phoneNumber, 'US');
setState(() {
this.number = number;
});
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
}
here is how to give permission for one user not public,
Direct Query:
Use MyDatabase
Grant execute on [dbo].[My-procedures-name] to [IIS APPPOOL\my-iis-pool]
Go
If you want to append
text or html to span
then you can do it as below.
$('p span#add_here').append('text goes here');
append will add text to span tag at the end.
to replace entire text or html inside of span you can use .text()
or .html()
>>> lst = [1, 2, 3]
>>> print('\n'.join('{}: {}'.format(*k) for k in enumerate(lst)))
0: 1
1: 2
2: 3
Note: you just need to understand that list comprehension or iterating over a generator expression is explicit looping.
You can just use a CheckBox
and set its appearance to Button
:
CheckBox checkBox = new System.Windows.Forms.CheckBox();
checkBox.Appearance = System.Windows.Forms.Appearance.Button;
If your $VARIABLE
is a string containing spaces or other special characters, and single square brackets are used (which is a shortcut for the test
command), then the string may be split out into multiple words. Each of these is treated as a separate argument.
So that one variable is split out into many arguments:
VARIABLE=$(/some/command);
# returns "hello world"
if [ $VARIABLE == 0 ]; then
# fails as if you wrote:
# if [ hello world == 0 ]
fi
The same will be true for any function call that puts down a string containing spaces or other special characters.
Wrap the variable output in double quotes, forcing it to stay as one string (therefore one argument). For example,
VARIABLE=$(/some/command);
if [ "$VARIABLE" == 0 ]; then
# some action
fi
Simple as that. But skip to "Also beware..." below if you also can't guarantee your variable won't be an empty string, or a string that contains nothing but whitespace.
Or, an alternate fix is to use double square brackets (which is a shortcut for the new test
command).
This exists only in bash (and apparently korn and zsh) however, and so may not be compatible with default shells called by /bin/sh
etc.
This means on some systems, it might work from the console but not when called elsewhere, like from cron
, depending on how everything is configured.
It would look like this:
VARIABLE=$(/some/command);
if [[ $VARIABLE == 0 ]]; then
# some action
fi
If your command contains double square brackets like this and you get errors in logs but it works from the console, try swapping out the [[
for an alternative suggested here, or, ensure that whatever runs your script uses a shell that supports [[
aka new test
.
[: unary operator expected
errorIf you're seeing the "too many arguments" error, chances are you're getting a string from a function with unpredictable output. If it's also possible to get an empty string (or all whitespace string), this would be treated as zero arguments even with the above "quick fix", and would fail with [: unary operator expected
It's the same 'gotcha' if you're used to other languages - you don't expect the contents of a variable to be effectively printed into the code like this before it is evaluated.
Here's an example that prevents both the [: too many arguments
and the [: unary operator expected
errors: replacing the output with a default value if it is empty (in this example, 0
), with double quotes wrapped around the whole thing:
VARIABLE=$(/some/command);
if [ "${VARIABLE:-0}" == 0 ]; then
# some action
fi
(here, the action will happen if $VARIABLE is 0, or empty. Naturally, you should change the 0 (the default value) to a different default value if different behaviour is wanted)
Final note: Since [
is a shortcut for test
, all the above is also true for the error test: too many arguments
(and also test: unary operator expected
)
When you get the error message, you have the option to click on "Debug": this will lead you to the line where the error occurred. The Dark Canuck seems to be right, and I guess the error occurs on the line:
Sheets("Sheet1").protect Password:="btfd"
because most probably the "Sheet1" does not exist. However, if you say "It works fine, but when I save the file I get the message: run-time error '9': subscription out of range" it makes me think the error occurs on the second line:
ActiveWorkbook.Save
Could you please check this by pressing the Debug button first? And most important, as Gordon Bell says, why are you using a macro to protect a workbook?
Gradle is in offline mode, which means that it won't go to the network to resolve dependencies.
Go to Preferences > Gradle and uncheck "Offline work".
1.Use git reflog
to get all references update.
2.git reset <id_of_commit_to_which_you_want_restore>
Merge this:
private long previousItemId = 0;
@Override
public long getItemId(int position) {
long nextItemId = random.nextInt(Integer.MAX_VALUE);
while(previousItemId == nextItemId) {
nextItemId = random.nextInt(Integer.MAX_VALUE);
}
previousItemId = nextItemId;
return nextItemId;
}
With this answer:
public class SpinnerInteractionListener
implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
private AdapterView.OnItemSelectedListener onItemSelectedListener;
public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
this.onItemSelectedListener = selectedListener;
}
boolean userSelect = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(userSelect) {
onItemSelectedListener.onItemSelected(parent, view, pos, id);
userSelect = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
if(userSelect) {
onItemSelectedListener.onNothingSelected(parent);
userSelect = false;
}
}
}
private void txtuser_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsLetter(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
OK it's 2019 now, and from Java 11 you have a constructor with Charset:
FileWriter?(String fileName, Charset charset)
Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)
Go to Control Panel -> Programs -> Programs and features
Go to Windows Features and disable Internet Explorer 11
Then click on Display installed updates
Search for Internet explorer
Right-click on Internet Explorer 11 -> Uninstall
Do the same with Internet Explorer 10
I think it will be okay.
You can add them in your htaccess file or vhost configuration.
See here : http://httpd.apache.org/docs/2.2/mod/mod_expires.html
But unless you own those domains .. they are our of your control.
This answer uses the jQuery UI Datepicker, which is a separate include. There are other ways to do this without including jQuery UI.
First, you simply need to add the datepicker
class to the textbox, in addition to form-control
:
<div class="form-group input-group-sm">
@Html.LabelFor(model => model.DropOffDate)
@Html.TextBoxFor(model => model.DropOffDate, new { @class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
@Html.ValidationMessageFor(model => model.DropOffDate)
</div>
Then, to be sure the javascript is triggered after the textbox is rendered, you have to put the datepicker call in the jQuery ready function:
<script type="text/javascript">
$(function () { // will trigger when the document is ready
$('.datepicker').datepicker(); //Initialise any date pickers
});
</script>
My issue was the failure to import numpy into my python files. I was receiving the "ModuleNotFoundError: No module named 'numpy'". I ran into the same issue and I was not referencing python3 on the installation of numpy. I inputted the following into my terminal for OSX and my problems were solved:
python3 -m pip install numpy
Some example, how to use urllib for that things, with some sugar syntax. I know about requests and other libraries, but urllib is standard lib for python and doesn't require anything to be installed separately.
Python 2/3 compatible.
import sys
if sys.version_info.major == 3:
from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, Request, build_opener
from urllib.parse import urlencode
else:
from urllib2 import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, Request, build_opener
from urllib import urlencode
def curl(url, params=None, auth=None, req_type="GET", data=None, headers=None):
post_req = ["POST", "PUT"]
get_req = ["GET", "DELETE"]
if params is not None:
url += "?" + urlencode(params)
if req_type not in post_req + get_req:
raise IOError("Wrong request type \"%s\" passed" % req_type)
_headers = {}
handler_chain = []
if auth is not None:
manager = HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, url, auth["user"], auth["pass"])
handler_chain.append(HTTPBasicAuthHandler(manager))
if req_type in post_req and data is not None:
_headers["Content-Length"] = len(data)
if headers is not None:
_headers.update(headers)
director = build_opener(*handler_chain)
if req_type in post_req:
if sys.version_info.major == 3:
_data = bytes(data, encoding='utf8')
else:
_data = bytes(data)
req = Request(url, headers=_headers, data=_data)
else:
req = Request(url, headers=_headers)
req.get_method = lambda: req_type
result = director.open(req)
return {
"httpcode": result.code,
"headers": result.info(),
"content": result.read()
}
"""
Usage example:
"""
Post data:
curl("http://127.0.0.1/", req_type="POST", data='cascac')
Pass arguments (http://127.0.0.1/?q=show):
curl("http://127.0.0.1/", params={'q': 'show'}, req_type="POST", data='cascac')
HTTP Authorization:
curl("http://127.0.0.1/secure_data.txt", auth={"user": "username", "pass": "password"})
Function is not complete and possibly is not ideal, but shows a basic representation and concept to use. Additional things could be added or changed by taste.
12/08 update
Here is a GitHub link to live updated source. Currently supporting:
authorization
CRUD compatible
automatic charset detection
automatic encoding(compression) detection
You can use the shift keyword (operator?) to iterate through them. Example:
#!/bin/bash
function print()
{
while [ $# -gt 0 ]
do
echo $1;
shift 1;
done
}
print $*;
On top of all the other explanations, I believe you're using equal "="
sign, instead of colon ":"
:
<span style="border:1px solid red;text-align=center">
It should be:
<span style="border:1px solid red;text-align:center">
To add to Preston's answer, here's the complete list of the HttpContent
derived classes available in the standard library:
Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/
There's also a supposed ObjectContent
but I was unable to find it in ASP.NET Core
.
Of course, you could skip the whole HttpContent
thing all together with Microsoft.AspNet.WebApi.Client
extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:
var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
Title = "New Article Title",
Body = "New Article Body"
});
You can't achieve what you want with arrays. Use vectors instead, and read about the std::remove algorithm. Something like:
std::remove(array, array+5, 3)
will work on your array, but it will not shorten it (why -- because it's impossible). With vectors, it'd be something like
v.erase(std::remove(v.begin(), v.end(), 3), v.end())
If push request is shows Rejected, then try first pull from your github account and then try push.
Ex:
In my case it was giving an error-
! [rejected] master -> master (fetch first)
error: failed to push some refs to 'https://github.com/ashif8984/git-github.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
****So what I did was-****
$ git pull
$ git push
And the code was pushed successfully into my Github Account.
public static TargetClassJson downloadPaletteJson(String url) throws IOException {
if (StringUtils.isBlank(url)) {
return null;
}
String genreJson = IOUtils.toString(new URL(url).openStream());
return new Gson().fromJson(genreJson, TargetClassJson.class);
}
Just for completeness: you may also use array_walk
:
array_walk($yourArray, function(&$value)
{
$value = strtolower($value);
});
From PHP docs:
If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.
Or directly via foreach
loop using references:
foreach($yourArray as &$value)
$value = strtolower($value);
Note that these two methods change the array "in place", whereas array_map
creates and returns a copy of the array, which may not be desirable in case of very large arrays.
You can alter a foreign key constraint with delete cascade option as shown below. This will delete chind table rows related to master table rows when deleted.
ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz
FOREIGN KEY (xyz)
REFERENCES ChildTable (xyz) ON DELETE CASCADE