I would ALWAYS go with both the alt
and the title
attributes. Many developers have been using this pattern now for over 20 years to deal with IE and other issues. So this is not new knowledge. Its just been rediscovered by new developers that didn't bother to learn from the past.
In addition, in HTML5 you should start using the new HTML5 picture
element wrapped in figure
with full WPA-ARIA attributes for greater accessibility, as well as support of assistive technologies, screen readers, and the like. Because this element is not supported in many older browsers...BUT degrades gracefully...I recommend the following HTML design pattern now for images in HTML:
<figure aria-labelledby="picturecaption2">
<picture id="picture2">
<source srcset="image.webp" type="image/webp" media="(min-width: 800px)" />
<source srcset="image.gif" type="image/gif" />
<img id="image2" style="height:auto;max-width: 100%;" src="image.jpg" width="255" height="200" alt="image:The World Wide Web" title="The World Wide Web" loading="lazy" no-referrer="no-referrer" onerror="this.onerror=null;" />
</picture>
<figcaption id="picturecaption2"><small>"My Cool Picture" [<a href="http://creativecommons.org/licenses/" target="_blank">A License</a>] , via <a href="https://commons.wikimedia.org/wiki/" target="_blank">Wikimedia Commons</a></small></figcaption>
</figure>
The code above has many extra "goodies" beside alt
and title
, including ARIA attributes, support for WebP, a media query supporting higher resolution imagery, and a nice fallback pattern supporting older image formats. It shows a fully decorated image example that uses new technologies while still supporting old ones with progressive design patterns.
REMEMBER...ALWAYS SUPPORT THE OLD BROWSERS!
"title" is widely implemented in browsers. Try:
<a href="#" title="hello">asf</a>
UPDATE: As of compose file version 3.5:
This now works:
version: "3.5"
services:
proxy:
image: hello-world
ports:
- "80:80"
networks:
- proxynet
networks:
proxynet:
name: custom_network
docker-compose up -d
will join a network called 'custom_network'. If it doesn't exist, it will be created!
root@ubuntu-s-1vcpu-1gb-tor1-01:~# docker-compose up -d
Creating network "custom_network" with the default driver
Creating root_proxy_1 ... done
Now, you can do this:
version: "2"
services:
web:
image: hello-world
networks:
- my-proxy-net
networks:
my-proxy-net:
external:
name: custom_network
This will create a container that will be on the external network.
I can't find any reference in the docs yet but it works!
Try casting your column to a numeric like:
SELECT ROUND(cast(some_column as numeric),2) FROM table
To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).
file://///server/path/to/file.txt
Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:
For security purposes, Mozilla applications block links to local files (and directories) from remote files.
And less directly, from Google:
Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.
The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.
This technique worked for me:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.put(url, entity);
I hope this helps
Add a reference to Microsoft.VisualBasic to your project.
Then insert the using statement
using Microsoft.VisualBasic;
Use the defined constant vbCrLf:
private const string myString = "abc" + Constants.vbCrLf;
Hi @donaldhughes I'm new on it too, and I use to do this: 1 - Create a class to get my Connection String 2 - Call the connection string class in a Using
Look:
DapperConnection.cs
public class DapperConnection
{
public IDbConnection DapperCon {
get
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["Default"].ToString());
}
}
}
DapperRepository.cs
public class DapperRepository : DapperConnection
{
public IEnumerable<TBMobileDetails> ListAllMobile()
{
using (IDbConnection con = DapperCon )
{
con.Open();
string query = "select * from Table";
return con.Query<TableEntity>(query);
}
}
}
And it works fine.
Gotcha!
You have to use RegisterStartupScript
instead of RegisterClientScriptBlock
Here My Example.
MasterPage:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
Inherits="prueba.MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function confirmCallBack() {
var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');
alert(a.value);
}
</script>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
WebForm1.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>
WebForm1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace prueba
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);
}
}
}
This is a bit of a Unix vs Linux battle. Most if not all Linux distributions have bash installed and ksh optional. Most Unix systems, like Solaris, AIX and HPUX have ksh as default.
Personally I always use ksh, I love the vi completion and I pretty much use Solaris for everything.
If you want to reset bootstrap page with button click using jQuery :
function resetForm(){
var validator = $( "#form_ID" ).validate();
validator.resetForm();
}
Using above code you also have change the field colour as red to normal.
If you want to reset only fielded value then :
$("#form_ID")[0].reset();
You can also use /dev/urandom:
grep -m1 -ao '[0-9]' /dev/urandom | sed s/0/10/ | head -n1
It was written above: in my case it was just out of memory on device storage. Add more empty space - and error will disappear
Probably your best bet with this kind of scenario is to use jQuery's change method to find the currently selected value, like so:
$('#aioConceptName').change(function(){
//get the selected val using jQuery's 'this' method and assign to a var
var selectedVal = $(this).val();
//perform the rest of your operations using aforementioned var
});
I prefer this method because you can then perform functions for each selected option in a given select field.
Hope that helps!
Your foldername is scripts
?
Change
<script src="../Script/login.js">
to
<script src='scripts/login.js' type='text/javascript'></script>
You can view these with Process Explorer from sysinternals. Use the "Find -> Find Handle or DLL..." option and enter the pattern "\Device\NamedPipe\". It will show you which processes have which pipes open.
GlobalStrings.AddRange(localStrings);
That works.
Documentation: List<T>.AddRange(IEnumerable<T>)
.
I use another way:
$('#showModal').on('hidden.bs.modal', function() {
$('#easyModal').on('shown.bs.modal', function() {
$('body').addClass('modal-open');
});
});
a rapid response not tested on several brosers, works on gg chrome / win
-> On focus event -> show/hide password
<input type="password" name="password">
script jQuery
// show on focus
$('input[type="password"]').on('focusin', function(){
$(this).attr('type', 'text');
});
// hide on focus Out
$('input[type="password"]').on('focusout', function(){
$(this).attr('type', 'password');
});
I would prefer using JConsole for application monitoring, and it does have graphical view. If you’re using JDK 5.0 or above then it’s the best. Please refer to this using jconsole page for more details.
I have been primarily using it for GC tuning and finding bottlenecks.
The getPosts()
function seems to be expecting $con
to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.
If some users of the code have different language settings format might not work. Thus I use the following code that gives the time stamp in format "yyymmdd hhMMss" regardless of language.
Function TimeStamp()
Dim iNow
Dim d(1 To 6)
Dim i As Integer
iNow = Now
d(1) = Year(iNow)
d(2) = Month(iNow)
d(3) = Day(iNow)
d(4) = Hour(iNow)
d(5) = Minute(iNow)
d(6) = Second(iNow)
For i = 1 To 6
If d(i) < 10 Then TimeStamp = TimeStamp & "0"
TimeStamp = TimeStamp & d(i)
If i = 3 Then TimeStamp = TimeStamp & " "
Next i
End Function
That's simple. You can set option to display only week days in toLocaleDateString() to get the names. For example:
(new Date()).toLocaleDateString('en-US',{ weekday: 'long'}) will return only the day of the week. And (new Date()).toLocaleDateString('en-US',{ month: 'long'}) will return only the month of the year.
This would be a good example of something that's trivial to do with tables and hard (if not impossible, at least in a cross-browser sense) to do with CSS.
If both the columns were fixed width, this would be easy.
If one of the columns was fixed width, this would be slightly harder but entirely doable.
With both columns variable width, IMHO you need to just use a two-column table.
I wrote this test that keeps on adding 'a'
to parameter until the browser fails
C# part:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ParamTest(string x)
{
ViewBag.TestLength = 0;
if (!string.IsNullOrEmpty(x))
{
System.IO.File.WriteAllLines("c:/result.txt",
new[] {Request.UserAgent, x.Length.ToString()});
ViewBag.TestLength = x.Length + 1;
}
return View();
}
View:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var text = "a";
for (var i = 0; i < parseInt(@ViewBag.TestLength)-1; i++) {
text += "a";
}
document.location.href = "http://localhost:50766/Home/ParamTest?x=" + text;
});
</script>
PART 1
On Chrome I got:
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
2046
It then blew up with:
HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.
Same on Internet Explorer 8 and Firefox
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
2046
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
2046
PART 2
I went easy mode and added additional limits to IISExpress applicationhost.config
and web.config
setting maxQueryStringLength="32768"
.
Chrome failed with message 'Bad Request - Request Too Long
HTTP Error 400. The size of the request headers is too long.
after 7744 characters.
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
7744
PART 3
<headerLimits>
<add header="Content-type" sizeLimit="32768" />
</headerLimits>
which didn't help at all. I finally decided to use fiddler to remove the referrer from header.
static function OnBeforeRequest(oSession: Session) {
if (oSession.url.Contains("localhost:50766")) {
oSession.RequestHeaders.Remove("Referer");
}
Which did nicely.
Chrome: got to 15613 characters. (I guess it's a 16K limit for IIS)
And it failed again with:
<BODY><h2>Bad Request - Request Too Long</h2>
<hr><p>HTTP Error 400. The size of the request headers is too long.</p>
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
15613
Firefox:
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
15708
Internet Explorer 8 failed with iexplore.exe crashing.
After 2505
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)
2505
Android Emulator
Mozilla/5.0 (Linux; Android 5.1; Android SDK built for x86 Build/LKY45) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36
7377
Internet Explorer 11
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)
4043
Internet Explorer 10
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)
4043
Internet Explorer 9
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
4043
You can use the mapKeys lodash function for that. Just one line of code!
Please refer to this complete code sample (copy paste this into repl.it or similar):
import _ from 'lodash';
// or commonjs:
// const _ = require('lodash');
let a = [{ id: 23, title: 'meat' }, { id: 45, title: 'fish' }, { id: 71, title: 'fruit' }]
let b = _.mapKeys(a, 'id');
console.log(b);
// b:
// { '23': { id: 23, title: 'meat' },
// '45': { id: 45, title: 'fish' },
// '71': { id: 71, title: 'fruit' } }
I have had a similar scenario in Laravel and solved it in the following way.
The password contains characters from at least three of the following five categories:
First, we need to create a regular expression and validate it.
Your regular expression would look like this:
^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$
I have tested and validated it on this site. Yet, perform your own in your own manner and adjust accordingly. This is only an example of regex, you can manipluated the way you want.
So your final Laravel code should be like this:
'password' => 'required|
min:6|
regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/|
confirmed',
Update As @NikK in the comment mentions, in Laravel 5.5 and newer the the password value should encapsulated in array Square brackets like
'password' => ['required',
'min:6',
'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/',
'confirmed']
I have not testing it on Laravel 5.5 so I am trusting @NikK hence I have moved to working with c#/.net these days and have no much time for Laravel.
Note:
Some online references
Regarding your custom validation message for the regex rule in Laravel, here are a few links to look at:
Just to say in my example the situation was a dialog box that then verified the check box before closing dialog. None of above and How to check whether a checkbox is checked in jQuery? and jQuery if checkbox is checked did not appear to work either.
In the end
<input class="cb" id="rd" type="checkbox">
<input class="cb" id="fd" type="checkbox">
var fd=$('.cb#fd').is(':checked');
var rd= $('.cb#rd').is(':checked');
This worked so calling the class then the ID. rather than just the ID. It may be due to the nested DOM elements on this page causing the issue. The workaround was above.
If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:
sys.path.insert(1, path_to_dev_pyworkbooks)
This could be important since 3rd party code may rely on sys.path documentation conformance:
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.
Okay, I don't foresee any more answers on this one, so what I ended up going with for now is just a solution for rectangular images. I've used the following NinePatch:
along with the appropriate padding in XML:
<ImageView
android:id="@+id/image_test"
android:background="@drawable/drop_shadow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6px"
android:paddingTop="4px"
android:paddingRight="8px"
android:paddingBottom="9px"
android:src="@drawable/pic1"
/>
to get a fairly good result:
Not ideal, but it'll do.
you can't use aliases from select list inside the WHERE clause (because of the Order of Evaluation of a SELECT statement)
also you cannot use OVER
clause inside WHERE clause - "You can specify analytic functions with this clause in the select list or ORDER BY clause." (citation from docs.oracle.com)
select *
from (select
staff_id, site_id, pay_level, date,
max(date) over (partition by staff_id) max_date
from owner.table
where end_enrollment_date is null
)
where date = max_date
use gcc -B lib_path_containing_crt?.o
#include <vector>
#include <numeric>
#include <sstream>
#include <iterator>
void Trim(std::string& inputString)
{
std::istringstream stringStream(inputString);
std::vector<std::string> tokens((std::istream_iterator<std::string>(stringStream)), std::istream_iterator<std::string>());
inputString = std::accumulate(std::next(tokens.begin()), tokens.end(),
tokens[0], // start with first element
[](std::string a, std::string b) { return a + " " + b; });
}
use this link, it will automatically convert any path you give to any format https://pathconverter-pp.azurewebsites.net
I think the problem you're having is that in some earlier commit, you've accidentally added .DS_Store
files to the repository. Of course, once a file is tracked in your repository, it will continue to be tracked even if it matches an entry in an applicable .gitignore file.
You have to manually remove the .DS_Store
files that were added to your repository. You can use
git rm --cached .DS_Store
Once removed, git should ignore it. You should only need the following line in your root .gitignore
file: .DS_Store
. Don't forget the period!
git rm --cached .DS_Store
removes only .DS_Store
from the current directory. You can use
find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch
to remove all .DS_Stores
from the repository.
Felt tip: Since you probably never want to include .DS_Store
files, make a global rule. First, make a global .gitignore
file somewhere, e.g.
echo .DS_Store >> ~/.gitignore_global
Now tell git to use it for all repositories:
git config --global core.excludesfile ~/.gitignore_global
This page helped me answer your question.
There is an easier approach:
x = tf.Variable(0)
x = x + 1
print x.eval()
Updated version of HCD's solution which avoids conflict:
var y = $j(window).scrollTop();
$j("html, body").animate({ scrollTop: y + $j(window).height() }, 600);
something like so might work:
<script type="text/javascript">
$(document).ready(function(){
var $input = $("<input name='myField' type='text'>");
$('#section2').append($input);
});
</script>
<form>
<div id="section1"><!-- some controls--></div>
<div id="section2"><!-- for dynamic controls--></div>
</form>
While playing around with the answers I found here to become familiar with it I twisted Nuoji's solution a bit so that I could understand it faster when looking at it in the future.
public static String stringToBinary(String str, boolean pad ) {
byte[] bytes = str.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
binary.append(Integer.toBinaryString((int) b));
if(pad) { binary.append(' '); }
}
return binary.toString();
}
This formula will give the column based on a range (i.e., A1), where range is a single cell. If a multi-cell range is given it will return the top-left cell. Note, both cell references must be the same:
MID(CELL("address",A1),2,SEARCH("$",CELL("address",A1),2)-2)
How it works:
CELL("property","range") returns a specific value of the range depending on the property used. In this case the cell address. The address property returns a value $[col]$[row], i.e. A1 -> $A$1. The MID function parses out the column value between the $ symbols.
It's notable to understand that if you'd like to conditionally add attributes you can also add a dynamic declaration:
<input v-bind="attrs" />
where attrs is declared as an object:
data() {
return {
attrs: {
required: true,
type: "text"
}
}
}
Which will result in:
<input required type="text"/>
Ideal in cases with multiple attributes.
You start new activities with intents. One method to send data to an intent is to pass a class that implements parcelable in the intent. Take note you are passing a copy of the class.
http://developer.android.com/reference/android/os/Parcelable.html
Here I have an onItemClick. I create intent and putExtra an entire class into the intent. The class I'm sending has implemented parcelable. Tip: You only need implement the parseable over what is minimally needed to re-create the class. Ie maybe a filename or something simple like a string something that a constructor can use to create the class. The new activity can later getExtras and it is essentially creating a copy of the class with its constructor method.
Here I launch the kmlreader class of my app when I recieve an onclick in the listview.
Note: below summary is a list of the class that I am passing so get(position) returns the class infact it is the same list that populates the listview
List<KmlSummary> summary = null;
...
public final static String EXTRA_KMLSUMMARY = "com.gosylvester.bestrides.util.KmlSummary";
...
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
lastshownitem = position;
Intent intent = new Intent(context, KmlReader.class);
intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
summary.get(position));
startActivity(intent);
}
later in the new activity I pull out the parseable class with
kmlSummary = intent.getExtras().getParcelable(
ImageTextListViewActivity.EXTRA_KMLSUMMARY);
//note:
//KmlSummary implements parcelable.
//there is a constructor method for parcel in
// and a overridden writetoparcel method
// these are really easy to setup.
public KmlSummary(Parcel in) {
this._id = in.readInt();
this._description = in.readString();
this._name = in.readString();
this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
in.readDouble());
this._resrawid = in.readInt();
this._resdrawableid = in.readInt();
this._pathstring = in.readString();
String s = in.readString();
this.set_isThumbCreated(Boolean.parseBoolean(s));
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeInt(this._id);
arg0.writeString(this._description);
arg0.writeString(this._name);
arg0.writeDouble(this.get_bounds().southwest.latitude);
arg0.writeDouble(this.get_bounds().southwest.longitude);
arg0.writeDouble(this.get_bounds().northeast.latitude);
arg0.writeDouble(this.get_bounds().northeast.longitude);
arg0.writeInt(this._resrawid);
arg0.writeInt(this._resdrawableid);
arg0.writeString(this.get_pathstring());
String s = Boolean.toString(this.isThumbCreated());
arg0.writeString(s);
}
Good Luck Danny117
The following converts decimal to Binary with Time Complexity : O(n) Linear Time and with out any java inbuilt function
private static int decimalToBinary(int N) {
StringBuilder builder = new StringBuilder();
int base = 2;
while (N != 0) {
int reminder = N % base;
builder.append(reminder);
N = N / base;
}
return Integer.parseInt(builder.reverse().toString());
}
It tells the compiler the boundary to align objects in a structure to. For example, if I have something like:
struct foo {
char a;
int b;
};
With a typical 32-bit machine, you'd normally "want" to have 3 bytes of padding between a
and b
so that b
will land at a 4-byte boundary to maximize its access speed (and that's what will typically happen by default).
If, however, you have to match an externally defined structure you want to ensure the compiler lays out your structure exactly according to that external definition. In this case, you can give the compiler a #pragma pack(1)
to tell it not to insert any padding between members -- if the definition of the structure includes padding between members, you insert it explicitly (e.g., typically with members named unusedN
or ignoreN
, or something on that order).
You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do
for (var i = myArray.length - 1; i >= 0; i--) { console.log(eval(myArray[i])); };
More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.
var result = {}; for (var i = myArray.length - 1; i >= 0; i--) { result[myArray[i]] = eval(myArray[i]); };
I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via
window['myVarName'] = 'namingCollisionsAreFun';
(per comment)
What you are trying to deserialize to a Dictionary is actually a Javascript object serialized to JSON. In Javascript, you can use this object as an associative array, but really it's an object, as far as the JSON standard is concerned.
So you would have no problem deserializing what you have with a standard JSON serializer (like the .net ones, DataContractJsonSerializer and JavascriptSerializer) to an object (with members called AppName, AnotherAppName, etc), but to actually interpret this as a dictionary you'll need a serializer that goes further than the Json spec, which doesn't have anything about Dictionaries as far as I know.
One such example is the one everybody uses: JSON .net
There is an other solution if you don't want to use an external lib, which is to convert your Javascript object to a list before serializing it to JSON.
var myList = [];
$.each(myObj, function(key, value) { myList.push({Key:key, Value:value}) });
now if you serialize myList to a JSON object, you should be capable of deserializing to a List<KeyValuePair<string, ValueDescription>>
with any of the aforementioned serializers. That list would then be quite obvious to convert to a dictionary.
Note: ValueDescription being this class:
public class ValueDescription
{
public string Description { get; set; }
public string Value { get; set; }
}
In Java 8, which is still in the development phase as of February 2014, you could use default methods to achieve a sort of C++-like multiple inheritance. You could also have a look at this tutorial which shows a few examples that should be easier to start working with than the official documentation.
You can list the tags on remote repository with ls-remote
, and then check if it's there. Supposing the remote reference name is origin
in the following.
git ls-remote --tags origin
And you can list tags local with tag
.
git tag
You can compare the results manually or in script.
There are two syntax errors in your ternary conditional:
if
. Check the correct syntax here.You are missing a parenthesis in your code. If you format it like this:
{(this.props.schema.collectionName.length < 0 ?
(<Expandable></Expandable>)
: (<h1>hejsan</h1>)
)}
Hope this works!
Since you want to optimize time moving from one page to another in a UIWebView, does it not mean you really are looking to optimize the Javascript used in loading these pages?
To that end, I'd look at a WebKit profiler like that talked about here:
http://www.alertdebugging.com/2009/04/29/building-a-better-javascript-profiler-with-webkit/
Another approach would be to start at a high level, and think how you can design the web pages in question to minimize load times using AJAX style page loading instead of refreshing the whole webview each time.
Don't modify strings.
Work with them as lists; turn them into strings only when needed.
>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'
Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings.
Have you tried using Firebug to inspect the rendered HTML, and to see exactly what css is being applied to the various elements? That should pick up css errors like the ones mentioned above, and you can see what styles are being inherited and from where - it is an invaluable too in any css debugging.
Since Java 8 you can use the Math.floorMod() method:
Math.floorMod(-1, 2); //== 1
Note: If the modulo-value (here 2
) is negative, all output values will be negative too. :)
The accepted answer did not work for me for several reasons:
-i
with a zero length extensionc\
command is weird and I couldn't get it to workSo here is the solution I came up with which I think should work for most cases:
function escape_slashes {
sed 's/\//\\\//g'
}
function change_line {
local OLD_LINE_PATTERN=$1; shift
local NEW_LINE=$1; shift
local FILE=$1
local NEW=$(echo "${NEW_LINE}" | escape_slashes)
sed -i .bak '/'"${OLD_LINE_PATTERN}"'/s/.*/'"${NEW}"'/' "${FILE}"
mv "${FILE}.bak" /tmp/
}
So the sample usage to fix the problem posed:
change_line "TEXT_TO_BE_REPLACED" "This line is removed by the admin." yourFile
Try moving <uses-permission>
outside the <application>
tag.
In my case, My principal was kafka/[email protected]
I got below lines in the terminal:
>>> KrbKdcReq send: #bytes read=190
>>> KdcAccessibility: remove kerberos.niroshan.com
>>> KDCRep: init() encoding tag is 126 req type is 13
>>>KRBError:
cTime is Thu Oct 05 03:42:15 UTC 1995 812864535000
sTime is Fri May 31 06:43:38 UTC 2019 1559285018000
suSec is 111309
error code is 7
error Message is Server not found in Kerberos database
cname is kafka/[email protected]
sname is kafka/[email protected]
msgType is 30
After hours of checking, I just found the below line has a wrong value in kafka_2.12-2.2.0/server.properties
listeners=SASL_PLAINTEXT://kafka.com:9092
Also I got two entries of kafka.niroshan.com
and kafka.com
for same IP address.
I changed it to as listeners=SASL_PLAINTEXT://kafka.niroshan.com:9092
Then it worked!
According to the below link, the principal should contain the Fully Qualified Domain Name (FQDN) of each host and it should be matched with the principal.
https://docs.oracle.com/cd/E19253-01/816-4557/planning-25/index.html
You can use the re
module for regexes, but regexes are probably overkill for what you want. I might try something like
z.write(article[:article.index("</html>") + 7]
This is much cleaner, and should be much faster than a regex based solution.
mkdir C:\VTS 2> NUL
create a folder called VTS
and output A subdirectory or file TEST already exists
to NUL
.
or
(C:&(mkdir "C:\VTS" 2> NUL))&
change the drive letter to C:
, mkdir
, output error to NUL
and run the next command.
function truncateString(str, length) {
return str.length > length ? str.substring(0, length - 3) + '...' : str
}
Bubble Sort is not online (it cannot sort a stream of inputs without knowing how many items there will be) because it does not really keep track of a global maximum of the sorted elements. When an item is inserted you will need to start the bubbling from the very beginning
the case above is for a new project. I hit upon this error while editing a fork of a well established library.
the typedef was included in the file I was editing but the struct wasn't.
The end result being that I was attempting to edit the struct in the wrong place.
If you run into this in a similar way look for other places where the struct is edited and try it there.
@koby's answer doesn't work for me, so I make a little change.
cd ~/.ssh
chmod 700 id_rsa.pub
This works well for me on Mac.
Building upon the answers of the others, here is a one-liner solution that sets the tag date to when it actually happened, uses annotated tag and requires no git checkout
:
tag="v0.1.3" commit="8f33a878" bash -c 'GIT_COMMITTER_DATE="$(git show --format=%aD $commit)" git tag -a $tag -m $tag $commit'
git push --tags origin master
where tag
is set to the desired tag string, and commit
to the commit hash.
There is a much easier way to run PHP, no configuration needed:
Ctrl+Alt+N
F1
and then select/type Run Code
, Run Code
in editor context menuRun Code
button in editor title menuRun Code
button in context menu of file explorerBesides, you could select part of the PHP code and run the code snippet. Very convenient!
if (File.Exists(path))
{
File.Delete(path);
}
That specifies the how many digits you want it to show.
integer value or * that specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when * is used, the width is specified by an additional argument of type int. If the value of the argument is negative, it results with the - flag specified and positive field width.
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
Late answer, but this is what I use to find and replace inside a text file:
with open("test.txt") as r:
text = r.read().replace("THIS", "THAT")
with open("test.txt", "w") as w:
w.write(text)
If you only have TypeScript installed for Visual Studio then:
tsc -v
and hit EnterVisual Studio 2017 versions 15.3 and above bind the TypeScript version to individual projects, as this answer points out:
- Right click on the project node in Solution Explorer
- Click Properties
- Go to the TypeScript Build tab
I find the syntax of the previous answers to be redundant and difficult to remember. Pandas introduced the query()
method in v0.13 and I much prefer it. For your question, you could do df.query('col == val')
Reproduced from http://pandas.pydata.org/pandas-docs/version/0.17.0/indexing.html#indexing-query
In [167]: n = 10
In [168]: df = pd.DataFrame(np.random.rand(n, 3), columns=list('abc'))
In [169]: df
Out[169]:
a b c
0 0.687704 0.582314 0.281645
1 0.250846 0.610021 0.420121
2 0.624328 0.401816 0.932146
3 0.011763 0.022921 0.244186
4 0.590198 0.325680 0.890392
5 0.598892 0.296424 0.007312
6 0.634625 0.803069 0.123872
7 0.924168 0.325076 0.303746
8 0.116822 0.364564 0.454607
9 0.986142 0.751953 0.561512
# pure python
In [170]: df[(df.a < df.b) & (df.b < df.c)]
Out[170]:
a b c
3 0.011763 0.022921 0.244186
8 0.116822 0.364564 0.454607
# query
In [171]: df.query('(a < b) & (b < c)')
Out[171]:
a b c
3 0.011763 0.022921 0.244186
8 0.116822 0.364564 0.454607
You can also access variables in the environment by prepending an @
.
exclude = ('red', 'orange')
df.query('color not in @exclude')
First convert your Chart.js canvas to base64 string.
var url_base64 = document.getElementById('myChart').toDataURL('image/png');
Set it as a href attribute for anchor tag.
link.href = url_base64;
<a id='link' download='filename.png'>Save as Image</a>
Above shown methods did not work for me, may be i am using bit old jquery, then finally the below shown code snippet works for - posting just in case somebody in my same position
$('#textBox').live('keydown', function(e) {
if (e.keyCode == 9) {
e.preventDefault();
alert('tab');
}
});
I think the selected answer is not correct, as the original question is "how to add a new validator after create the formControl".
As far as I know, that's not possible. The only thing you can do, is create the array of validators dynamicaly.
But what we miss is to have a function addValidator() to not override the validators already added to the formControl. If anybody has an answer for that requirement, would be nice to be posted here.
pip can install a package ignoring the cache, like this
pip --no-cache-dir install scipy
typeof works very well for me in most case. You can try using an if statement
if(typeof x === 'string' || typeof x === 'number') {
console.log("Your statement");
}
where x is any variable name of your choice
There is another way , if you want to get sub string before and after a character
String s ="123dance456";
String[] split = s.split("dance");
String firstSubString = split[0];
String secondSubString = split[1];
check this post- how to find before and after sub-string in a string
import the ReactiveForms Module to your components module
Running the @neverever415 answer I got:
Failure [DELETE_FAILED_INTERNAL_ERROR]
In this case check that you wrote a right package name, maybe it is a debug version like com.package_name.debug
:
adb shell pm uninstall com.package_name.debug
For anyone who finds themselves with the following problem (grouping by ensuring zero and null values are treated as equals)...
SELECT AccountNumber, Amount AS MyAlias
FROM Transactions
GROUP BY AccountNumber, ISNULL(Amount, 0)
(I.e. SQL Server complains that you haven't included the field Amount in your Group By or aggregate function)
...remember to place the exact same function in your SELECT...
SELECT AccountNumber, ISNULL(Amount, 0) AS MyAlias
FROM Transactions
GROUP BY AccountNumber, ISNULL(Amount, 0)
I understand that your main problem is that you need to calculate d=b-a
but your arrays have different sizes. There is no need for an intermediate padded c
You can solve this without padding:
import numpy as np
a = np.array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
b = np.array([[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.]])
d = b.copy()
d[:a.shape[0],:a.shape[1]] -= a
print d
Output:
[[ 2. 2. 2. 2. 2. 3.]
[ 2. 2. 2. 2. 2. 3.]
[ 2. 2. 2. 2. 2. 3.]
[ 3. 3. 3. 3. 3. 3.]]
POP UP WINDOWS IN APPLET
hi guys i was searching pop up windows in applet all over the internet but could not find answer for windows.
Although it is simple i am just helping you. Hope you will like it as it is in simpliest form. here's the code :
Filename: PopUpWindow.java
for java file and we need html file too.
For applet let us take its popup.html
CODE:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class PopUpWindow extends Applet{
public void init(){
Button open = new Button("open window");
add(open);
Button close = new Button("close window");
add(close);
Frame f = new Frame("pupup win");
f.setSize(200,200);
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!f.isShowing()) {
f.setVisible(true);
}
}
});
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(f.isShowing()) {
f.setVisible(false);
}
}
});
}
}
/*
<html>
<body>
<APPLET CODE="PopUpWindow" width="" height="">
</APPLET>
</body>
</html>
*/
to run:
$javac PopUpWindow.java && appletviewer popup.html
Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.
If you need generate numbers with intervals, it can be just like that:
Integer[] arr = new Integer[((int) (Math.random() * (16 - 30) + 30))];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
System.out.println(Arrays.toString(arr));`
The result:
[1, 10, 2, 4, 9, 8, 7, 13, 18, 17, 5, 21, 12, 16, 23, 20, 6, 0, 22, 14, 24, 15, 3, 11, 19]
Note:
If you need that the zero does not leave you could put an "if"
The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
%x
is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.
%02x
means if your provided value is less than two digits then 0
will be prepended.
You provided value 16843009
and it has been converted to 1010101
which a hex value.
Using truncate()
, the solution could be
import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
#convert to string:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
f.truncate()
Either use padding
, height
or  
for width to take effect with empty div
EDIT:
Non zero min-height
also works great
Java converts Integer to int and back automatically (unless you are still with Java 1.4).
VB6/VBA uses deterministic approach to destoying objects. Each object stores number of references to itself. When the number reaches zero, the object is destroyed.
Object variables are guaranteed to be cleaned (set to Nothing
) when they go out of scope, this decrements the reference counters in their respective objects. No manual action required.
There are only two cases when you want an explicit cleanup:
When you want an object to be destroyed before its variable goes out of scope (e.g., your procedure is going to take long time to execute, and the object holds a resource, so you want to destroy the object as soon as possible to release the resource).
When you have a circular reference between two or more objects.
If objectA
stores a references to objectB
, and objectB
stores a reference to objectA
, the two objects will never get destroyed unless you brake the chain by explicitly setting objectA.ReferenceToB = Nothing
or objectB.ReferenceToA = Nothing
.
The code snippet you show is wrong. No manual cleanup is required. It is even harmful to do a manual cleanup, as it gives you a false sense of more correct code.
If you have a variable at a class level, it will be cleaned/destroyed when the class instance is destructed. You can destroy it earlier if you want (see item 1.
).
If you have a variable at a module level, it will be cleaned/destroyed when your program exits (or, in case of VBA, when the VBA project is reset). You can destroy it earlier if you want (see item 1.
).
Access level of a variable (public vs. private) does not affect its life time.
I had already enabled "Allow less secure apps" and my SMPT python program was working perfectly!
But next day it stared giving me "Bad Credentials error (SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted)". I was using the exact same credentials as before and the less secure apps option was also enabled..!
Changed my password again but that also did not help.
Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:
https://accounts.google.com/DisplayUnlockCaptcha
Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.
Note: Had to try multipe times to get this option enabled. Once enabled, I tried connecting after 30mins and it worked..!!!
Hope this helps.
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
This can be done in the SSMS GUI as well. I show a default date below but the default value can be whatever, of course.
(getdate())
or 'abc'
or 0
or whatever value you want in Default Value or Binding field as pictured below:For any special characters you should use '\'. So, for matching parentheses - /\(/
Go to Windows-> Preference-> Maven -> User settings
Select settings.xml of Maven
Restart Eclipse
The solution below has a "SEO friendlier" version:
function hyphenize($string) {
$dict = array(
"I'm" => "I am",
"thier" => "their",
// Add your own replacements here
);
return strtolower(
preg_replace(
array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
array( '-', '' ),
// the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
cleanString(
str_replace( // preg_replace can be used to support more complicated replacements
array_keys($dict),
array_values($dict),
urldecode($string)
)
)
)
);
}
function cleanString($text) {
$utf8 = array(
'/[áàâãªä]/u' => 'a',
'/[ÁÀÂÃÄ]/u' => 'A',
'/[ÍÌÎÏ]/u' => 'I',
'/[íìîï]/u' => 'i',
'/[éèêë]/u' => 'e',
'/[ÉÈÊË]/u' => 'E',
'/[óòôõºö]/u' => 'o',
'/[ÓÒÔÕÖ]/u' => 'O',
'/[úùûü]/u' => 'u',
'/[ÚÙÛÜ]/u' => 'U',
'/ç/' => 'c',
'/Ç/' => 'C',
'/ñ/' => 'n',
'/Ñ/' => 'N',
'/–/' => '-', // UTF-8 hyphen to "normal" hyphen
'/[’‘‹›‚]/u' => ' ', // Literally a single quote
'/[“”«»„]/u' => ' ', // Double quote
'/ /' => ' ', // nonbreaking space (equiv. to 0x160)
);
return preg_replace(array_keys($utf8), array_values($utf8), $text);
}
The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.
After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru
"behaved better" than viaggi-economy-per
(the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).
There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.
In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict
needs to be hand tailored, of course.
A simple approach:
// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped
$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);
// Replace sequences of spaces with hyphen
$str = preg_replace('/ */', '-', $str);
// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)
// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);
// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything
Note that you might have to first urldecode()
the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.
So the finished function along with test cases:
function hyphenize($string) {
return
## strtolower(
preg_replace(
array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
array('-', ''),
## cleanString(
urldecode($string)
## )
)
## )
;
}
print implode("\n", array_map(
function($s) {
return $s . ' becomes ' . hyphenize($s);
},
array(
'Never%20gonna%20give%20you%20up',
"I'm not the man I was",
"'Légeresse', dit sa majesté",
)));
Never%20gonna%20give%20you%20up becomes never-gonna-give-you-up
I'm not the man I was becomes im-not-the-man-I-was
'Légeresse', dit sa majesté becomes legeresse-dit-sa-majeste
To handle UTF-8 I used a cleanString
implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.
The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.
You may also need to enable ReferralChasing on the DirectorySearcher - http://msdn.microsoft.com/en-us/library/ms180884(VS.80).aspx.
You can use jquery load for that.
<script type="text/javascript">
$(document).ready(function(e) {
$('#header').load('name.html',function(){alert('loaded')});
});
</script>
Don't forget to include jquery library befor above code.
For running it on any CPU either 62 bit or 32 bit follow these steps: Right click on the name of the project in Solution Explorer> Properties>Build and have these under Configuration: Active(Release), Platform:Active(Any CPU) and Target:x86. and just beside the Run button Select option Release and Any CPU from the options. And then Save it and Run.
Try to replace the
padding: 2px 30px 2px 2px;
with
padding: 2px 2px 2px 2px;
It should work.
It's HTTP Activation feature of .NET framework Windows Process Activation feature is required too
I know, I am tooooo late to post an answer, but hoping that it might help someone. Plus, I just solved this issue I had with my tests. This is what I had in my test:
My test class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "path-to-context" })
@Transactional
public class MyIntegrationTest
Context xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
I still had the problem that, the database was not being cleaned up automatically.
Issue was resolved when I added following property to BasicDataSource
<property name="defaultAutoCommit" value="false" />
Hope it helps.
The former is fastest. Turns out that val
is immutable, and so a new string object is created with String.ToLowerCase(), rather than just direct comparison with the string comparer. Creating a new string object can be costly if you're doing this many times a second.
scrollView.setContentOffset(CGPoint(x: y, y: x), animated: true)
A lot of correct answers, but I haven't found this one: Collections cannot be sorted, you can only iterate through them.
Now you can iterate over them and create a new sorted something
. Follow the answers here for that.
This is almost certainly much slower than any other version given here, but it was fun to write.
static bool ByteArrayEquals(byte[] a1, byte[] a2)
{
return a1.Zip(a2, (l, r) => l == r).All(x => x);
}
declare @dt datetime
set @dt = '09-22-2007 15:07:38.850'
select dateadd(mi, datediff(mi, 0, @dt), 0)
select dateadd(hour, datediff(hour, 0, @dt), 0)
will return
2007-09-22 15:07:00.000
2007-09-22 15:00:00.000
The above just truncates the seconds and minutes, producing the results asked for in the question. As @OMG Ponies pointed out, if you want to round up/down, then you can add half a minute or half an hour respectively, then truncate:
select dateadd(mi, datediff(mi, 0, dateadd(s, 30, @dt)), 0)
select dateadd(hour, datediff(hour, 0, dateadd(mi, 30, @dt)), 0)
and you'll get:
2007-09-22 15:08:00.000
2007-09-22 15:00:00.000
Before the date data type was added in SQL Server 2008, I would use the above method to truncate the time portion from a datetime to get only the date. The idea is to determine the number of days between the datetime in question and a fixed point in time (0
, which implicitly casts to 1900-01-01 00:00:00.000
):
declare @days int
set @days = datediff(day, 0, @dt)
and then add that number of days to the fixed point in time, which gives you the original date with the time set to 00:00:00.000
:
select dateadd(day, @days, 0)
or more succinctly:
select dateadd(day, datediff(day, 0, @dt), 0)
Using a different datepart (e.g. hour
, mi
) will work accordingly.
Just to throw in my 2 cents. My issue was solved by opening Task Manager and killing the application. It was running in the background without any indication that it was running at all (no item in the task bar, no ui, nothing), but I am not sure why this happened. Obviously the debugger was not running and I only had a single instance of VS opened at the time. It amazes me that this is still happening in this VS 2017.
Perhaps I can add a build step that looks for the application running the background and kills it before starting the new one.
<html>
<input type="text" placeholder ="username" id="userinput">
<br>
<input type="password" placeholder="password">
<br>
<button type="submit" onclick="myfunc()" id="demo">click me</button>
<script type="text/javascript">
function myfunc() {
var input = document.getElementById('userinput');
alert(input.value);
}
</script>
</html>
After going through all the answers I thought i will add two simple options
If you already accessed the record using FirstOrDefault() with tracking enabled (without using .AsNoTracking() function as it will disable tracking) and updated some fields then you can simply call context.SaveChanges()
In other case either you have entity posted to server using HtppPost or you disabled tracking for some reason then you should call context.Update(entityName) before context.SaveChanges()
1st option will only update the fields you changed but 2nd option will update all the fields in the database even though none of the field values were actually updated :)
It is called the Conditional Operator (which is a ternary operator).
It has the form of: condition
? value-if-true
: value-if-false
Think of the ?
as "then" and :
as "else".
Your code is equivalent to
if (max != 0)
hsb.s = 255 * delta / max;
else
hsb.s = 0;
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
You might find Perl or Python useful to get data from the serial port. To send data to the server, the solution could be easy if the server is (let's say) an HTTP application or even a popular database. The solution would be not so easy if it is some custom/proprietary TCP application.
var string = 'test- _ 0Test';
string.match(/^[-_ a-zA-Z0-9]+$/)
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}
... prints -2
and 12
.
-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \
as \\
in a Java String though. So, \d+ matches 1 or more digits.
In server applications the stacktrace blows up your stdout/stderr file. It may become larger and larger and is filled with useless data because usually you have no context and no timestamp and so on.
e.g. catalina.out when using tomcat as container
To uninstall the Node.js module:
npm uninstall <module_name>
This will remove the module from folder node_modules, but not from file package.json. So when we do npm install again it will download the module.
So to remove the module from file package.json, use:
npm uninstall <module_name> --save
This also deletes the dependency from file package.json.
And if you want to uninstall any globally module you can use:
npm -g uninstall <module_name> --save
This will delete the dependency globally.
The View::make
function takes 3 arguments which according to the documentation are:
public View make(string $view, array $data = array(), array $mergeData = array())
In your case, the compact('selections')
is a 4th argument. It doesn't pass to the view and laravel throws an exception.
On the other hand, you can use with()
as many time as you like. Thus, this will work:
return View::make('gameworlds.mygame')
->with(compact('fixtures'))
->with(compact('teams'))
->with(compact('selections'));
Just for grins, and in case somebody else runs into a similar error:
I got the infamous "missing separator" error because I had invoked a rule defining a function as
($eval $(call function,args))
rather than
$(eval $(call function,args))
i.e. ($
rather than $(
.
If the other class is compiled as a library (i.e. a dll) and this is how you want it, you should add a reference from visual studio, browse and point to to the dll file.
If what you want is to incorporate the OtherClassFile.cs into your project, and the namespace is already identical, you can:
Open YourProjectName.csproj file, and look for this section:
<ItemGroup>
<Compile Include="ExistingClass1.cs" />
<Compile Include="ExistingClass2.cs" />
...
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
Check that the .cs file that you want to add is in the project folder (same folder as all the existing classes in the solution).
Add an entry inside as below, save and open the project.
<Compile Include="OtherClassFile.cs" />
Your class, will now appear and behave as part of the project. No using is needed. This can be done multiple files in one shot.
Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.
Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.
When you do -
for word in string:
You are not iterating through the words in the string, you are iterating through the characters in the string. To iterate through the words, you would first need to split the string into words , using str.split()
, and then iterate through that . Example -
my_string = "this is a string"
for word in my_string.split():
print (word)
Please note, str.split()
, without passing any arguments splits by all whitespaces (space, multiple spaces, tab, newlines, etc).
Here ya go - works just any other iterable:
d = {'param' : 'test'}
def f(dictionary):
for key in dictionary:
print key
f(d)
I've used a few different methods to copy Amazon S3 data to a local machine, including s3cmd
, and by far the easiest is Cyberduck.
All you need to do is enter your Amazon credentials and use the simple interface to download, upload, sync any of your buckets, folders or files.
The way to do this using the Extention Methods, instead of the linq query syntax would be like this:
var results = workOrders.Join(plans,
wo => wo.WorkOrderNumber,
p => p.WorkOrderNumber,
(order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);
For people who searched for php multidimensional array get values
and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach
, which is array_column
For example, if I only want to get hotel_name
from the below array, and form to another array:
$hotels = [
[
'hotel_name' => 'Hotel A',
'info' => 'Hotel A Info',
],
[
'hotel_name' => 'Hotel B',
'info' => 'Hotel B Info',
]
];
I can do this using array_column
:
$hotel_name = array_column($hotels, 'hotel_name');
print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']
For the actual answer for this question, it can also be beautified by array_column
and call_user_func_array('array_merge', $twoDimensionalArray);
Let's make the data in PHP:
$hotels = [
[
'hotel_name' => 'Hotel A',
'info' => 'Hotel A Info',
'rooms' => [
[
'room_name' => 'Luxury Room',
'bed' => 2,
'boards' => [
'board_id' => 1,
'price' => 200
]
],
[
'room_name' => 'Non Luxy Room',
'bed' => 4,
'boards' => [
'board_id' => 2,
'price' => 150
]
],
]
],
[
'hotel_name' => 'Hotel B',
'info' => 'Hotel B Info',
'rooms' => [
[
'room_name' => 'Luxury Room',
'bed' => 2,
'boards' => [
'board_id' => 3,
'price' => 900
]
],
[
'room_name' => 'Non Luxy Room',
'bed' => 4,
'boards' => [
'board_id' => 4,
'price' => 300
]
],
]
]
];
And here's the calculation:
$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');
foreach($boards as $board){
$board_id = $board['board_id'];
$price = $board['price'];
echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}
Which will give you the following result:
Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300
From python3k, the startup need the encodings module, which can be found in PYTHONHOME\Lib directory. In fact, the API Py_Initialize () do the init and import the encodings module. Make sure PYTHONHOME\Lib is in sys.path and check the encodings module is there.
I have MAC OS X Yosemite, Android Studio 1.0.1, JDK 1.8, and Cordova 4.1.2
When I tried to add the android project:
cordova platforms add android
I received the message: ANDROID_HOME is not set and "android" command not in your PATH
Based in cforcloud's answer... 'Error: the command "android" failed' using cordova and http://developer.android.com/sdk/installing/index.html?pkg=studio I used the following:
export ANDROID_HOME="/Users/<user_name>/Library/Android/sdk"
export ANDROID_TOOLS="/Users/<user_name>/Library/Android/sdk/tools/"
export ANDROID_PLATFORM_TOOLS="/Users/<user_name>/Library/Android/sdk/platform-tools/"
PATH=$PATH:$ANDROID_HOME:$ANDROID_TOOLS:$ANDROID_PLATFORM_TOOLS
echo $PATH
When I tried to create the android project, I received this message:
Creating android project...
/Users/lg/.cordova/lib/npm_cache/cordova-android/3.6.4/package/bin/node_modules/q/q.js:126
throw e;
^
Error: Please install Android target "android-19".
I ran Android SDK Manager, and installed Android 4.4.2 (API 19) (everything but Glass Development Kit Preview). It worked for me.
===
This is the content of my .bash_profile file.
export PATH=$PATH:/usr/local/bin
export JAVA_HOME=`/usr/libexec/java_home -v 1.8`
launchctl setenv STUDIO_JDK /library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk
export ANDROID_HOME="/Users/<UserName>/Library/Android/sdk"
export ANDROID_TOOLS="/Users/<UserName>/Library/Android/sdk/tools"
export ANDROID_PLATFORM_TOOLS="/Users/<UserName>/Library/Android/sdk/platform-tools"
PATH=$PATH:$ANDROID_HOME:$ANDROID_TOOLS:$ANDROID_PLATFORM_TOOLS
To edit .bash_profile using Terminal, I use nano. It is easy to understand.
cd
nano .bash_profile
I hope it helps.
You need a Flask view that will receive POST data and an HTML form that will send it.
from flask import request
@app.route('/addRegion', methods=['POST'])
def addRegion():
...
return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
Project file path: <input type="text" name="projectFilePath"><br>
<input type="submit" value="Submit">
</form>
It's simple
input {border:0;outline:0;}
input:focus {outline:none!important;}
Like this:
#!/bin/bash
a=2462620
b=2462620
if [ "$a" -eq "$b" ]; then
echo "They're equal";
fi
Integers can be compared with these operators:
-eq # equal
-ne # not equal
-lt # less than
-le # less than or equal
-gt # greater than
-ge # greater than or equal
See this cheatsheet: https://devhints.io/bash#conditionals
Just add this to the top of your bat file:
set "params=%*"
cd /d "%~dp0" && ( if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs" ) && fsutil dirty query %systemdrive% 1>nul 2>nul || ( echo Set UAC = CreateObject^("Shell.Application"^) : UAC.ShellExecute "cmd.exe", "/k cd ""%~sdp0"" && %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" && "%temp%\getadmin.vbs" && exit /B )
It will elevate to admin and also stay in the correct directory. Tested on Windows 10.
There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.
With the new App Launcher YOUR APPS (not chrome extensions) stored in Users/[yourusername]/Applications/Chrome Apps/
The closest you say... Let me think... This must be fork() I guess :)
For details see Does Interix implement fork()?
Finally I got work around to the above problem. angular-strap has exactly the same feature that I am expecting. Just by applying date-format="MM/dd/yyyy" date-type="string"
I got my expected behavior of updating ng-model in given format.
<div class="bs-example" style="padding-bottom: 24px;" append-source>
<form name="datepickerForm" class="form-inline" role="form">
<!-- Basic example -->
<div class="form-group" ng-class="{'has-error': datepickerForm.date.$invalid}">
<label class="control-label"><i class="fa fa-calendar"></i> Date <small>(as date)</small></label>
<input type="text" autoclose="true" class="form-control" ng-model="selectedDate" name="date" date-format="MM/dd/yyyy" date-type="string" bs-datepicker>
</div>
<hr>
{{selectedDate}}
</form>
</div>
here is working plunk link
This example works great.
<button onclick="genPDF()">Generate PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script>
function genPDF() {
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');
doc.save('Test.pdf');
}
</script>
Try wrapping the createtable();
statement in a <script>
tag:
<table>
<tr>
<th>Balance</th>
<th>Fee</th>
</tr>
<script>createtable();</script>
</table>
I would avoid using document.write() and use the DOM if I were you though.
Or try defining the array as an object. (var cars = {};) Then there is no need to convert to json. This might not be practical in your example but worked well for me.
I'm also struck with this same problem, finally i got simple solution. just added one line to action bar style.
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:textColorPrimary">@color/colorAccent</item>
<item name="android:colorBackground">@color/colorAppWhite</item>
</style>
"android:colorBackground" is enough to change option menu background
Try this code. Call it before making any http requests. The code will use the proxy from your Internet Explorer Settings - one thing though, I use proxy.Credentials = ....
because my proxy server is an NTLM authenticated Internet Acceleration Server. Give it a whizz.
static void setProxy()
{
WebProxy proxy = (WebProxy)WebProxy.GetDefaultProxy();
if(proxy.Address != null)
{
proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
WebRequest.DefaultWebProxy = new System.Net.WebProxy(proxy.Address, proxy.BypassProxyOnLocal, proxy.BypassList, proxy.Credentials);
}
}
Works in all modern browsers
.rotate{
animation: loading 3s linear infinite;
@keyframes loading {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
}
valgrind --log-file="filename"
Within a ServiceWorker
or Worker
, replace window
with self
:
self[method_prefix + method_name](arg1, arg2);
Workers have no access to the DOM, therefore window
is an invalid reference. The equivalent global scope identifier for this purpose is self
.
You can also edit the config.xml file in your JENKINS_HOME directory. Use c32hedge's response as a reference and set the workspace location to whatever you want between the tags
You can center any number of child in a FrameLayout
.
<FrameLayout
>
<child1
....
android:layout_gravity="center"
.....
/>
<Child2
....
android:layout_gravity="center"
/>
</FrameLayout>
So the key is
adding
android:layout_gravity="center"
in the child views.
I centered a CustomView and a TextView on a FrameLayout
like this
Code:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<com.airbnb.lottie.LottieAnimationView
android:layout_width="180dp"
android:layout_height="180dp"
android:layout_gravity="center"
app:lottie_fileName="red_scan.json"
app:lottie_autoPlay="true"
app:lottie_loop="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:textSize="10dp"
android:textStyle="bold"
android:padding="10dp"
android:text="Networks Available: 1\n click to see all"
android:gravity="center" />
</FrameLayout>
Result:
For binding Dynamic Data in a DropDownList you can do the following:
Create ViewBag in Controller like below
ViewBag.ContribTypeOptions = yourFunctionValue();
now use this value in view like below:
@Html.DropDownListFor(m => m.ContribType,
new SelectList(@ViewBag.ContribTypeOptions, "ContribId",
"Value", Model.ContribTypeOptions.First().ContribId),
"Select, please")
Why not just create a 1dp high view with a background color? Then it can be easily placed where you want.
Something like this should work
var yesterday = DateTime.Now.Date.AddDays(-1);
DateTime.Now
gives you the current date and time.
If your looking to remove the the time element then adding .Date
constrains it to the date only ie time is 00:00:00
.
Finally .AddDays(-1)
removes 1 day to give you yesterday.
std::string -> wchar_t[]
with safe mbstowcs_s
function:
auto ws = std::make_unique<wchar_t[]>(s.size() + 1);
mbstowcs_s(nullptr, ws.get(), s.size() + 1, s.c_str(), s.size());
This is from my sample code
You can change vagrant default machine name by changing value of config.vm.define
.
Here is the simple Vagrantfile which uses getopts and allows you to change the name dynamically:
# -*- mode: ruby -*-
require 'getoptlong'
opts = GetoptLong.new(
[ '--vm-name', GetoptLong::OPTIONAL_ARGUMENT ],
)
vm_name = ENV['VM_NAME'] || 'default'
begin
opts.each do |opt, arg|
case opt
when '--vm-name'
vm_name = arg
end
end
rescue
end
Vagrant.configure(2) do |config|
config.vm.define vm_name
config.vm.provider "virtualbox" do |vbox, override|
override.vm.box = "ubuntu/wily64"
# ...
end
# ...
end
So to use different name, you can run for example:
vagrant --vm-name=my_name up --no-provision
Note: The --vm-name
parameter needs to be specified before up
command.
or:
VM_NAME=my_name vagrant up --no-provision
One solution is to use the command line;
mysql -h yourhostname -u username -p databasename < yoursqlfile.sql
Just ensure the path to the SQL file to import is stated explicitly.
In my case, I used this;
mysql -h localhost -u root -p databasename < /home/ejalee/dumps/mysqlfile.sql
Voila! you are good to go.
I would suggest you override the addClass function. You can do it this way:
// Create a closure
(function(){
// Your base, I'm in it!
var originalAddClassMethod = jQuery.fn.addClass;
jQuery.fn.addClass = function(){
// Execute the original method.
var result = originalAddClassMethod.apply( this, arguments );
// call your function
// this gets called everytime you use the addClass method
myfunction();
// return the original result
return result;
}
})();
// document ready function
$(function(){
// do stuff
});
use below statement if safe_mode
is off
set_time_limit(0);
MSTest does not support that feature, but you can implement your own attribute to achieve that.
Have a look at Enabling parameterized tests in MSTest using PostSharp.
Go into your directory and click on 'Settings' next to the little cog. There is a field to rename your directory.
What worked for me is performing Refresh all Gradle projects
from the Gradle
toolbar from the right menu.
PFB the screenshot from Android Studio.
Gradle
toolbar from the right menu.Refresh
iconThis resolved the issue for me.
margin: all_four_margin
by providing 50% to all_four_margin will place the element at the center
style="margin: 50%"
you can apply it for following too
margin: top right bottom left
margin: top right&left bottom
margin: top&bottom right&left
by giving appropriate % we get the element wherever we want.
Here is a version I came up with if you want to style words or individual characters at their index in react/javascript.
replaceAt( yourArrayOfIndexes, yourString/orArrayOfStrings )
Working example: https://codesandbox.io/s/ov7zxp9mjq
function replaceAt(indexArray, [...string]) {
const replaceValue = i => string[i] = <b>{string[i]}</b>;
indexArray.forEach(replaceValue);
return string;
}
And here is another alternate method
function replaceAt(indexArray, [...string]) {
const startTag = '<b>';
const endTag = '</b>';
const tagLetter = i => string.splice(i, 1, startTag + string[i] + endTag);
indexArray.forEach(tagLetter);
return string.join('');
}
And another...
function replaceAt(indexArray, [...string]) {
for (let i = 0; i < indexArray.length; i++) {
string = Object.assign(string, {
[indexArray[i]]: <b>{string[indexArray[i]]}</b>
});
}
return string;
}
You're going to have to either use JS or write a function/method in whatever non-markup language you're using to do this. For instance you could write something that will save the status to a cookie or session variable then check for it on page load. If you want to do it without reloading the page then JS is going to be your only option.
I try to explain it more understandably than the referred PostgreSQL documentation.
Neither TIMESTAMP
variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:
TIMESTAMP WITHOUT TIME ZONE
stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30'
, then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00'
and '2011-07-01 06:30:30+05'
are the same as just '2011-07-01 06:30:30'
.
For Java developers: it's analogous to java.time.LocalDateTime
.
TIMESTAMP WITH TIME ZONE
stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The
input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30'
) it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'
). The output is displayed converted to the current time zone of the PostgreSQL session.
For Java developers: It's analogous to java.time.Instant
(with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime
(or to java.util.Date
or java.sql.Timestamp
of course).
Some say that both TIMESTAMP
variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE
is stored like a TIMESTAMP WITH TIME ZONE
, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)
In my case.. following steps resolved:
There was a column value which was set to "Update" - replaced it with Edit (non sql keyword) There was a space in one of the column names (removed the extra space or trim)
geonames is nice. an export tool based on geonames:
https://github.com/yosoyadri/GeoNames-XML-Builder
there's also the excellent pycountry module:
One liner:
var yesterday = new Date(Date.now() - 864e5); // 864e5 == 86400000 == 24*60*60*1000
i.e. <div tooltip={{ obj.somePropertyThatMayChange }} ...></div>
I had an issue with dynamic tooltips that were not always updating with the view. For example, I was doing something like this:
<div ng-repeat="person in people">
<span data-toggle="tooltip" data-placement="top" title="{{ person.tooltip }}">
{{ person.name }}
</span>
</div>
And activating it as so:
$timeout(function() {
$(document).tooltip({ selector: '[data-toggle="tooltip"]'});
}, 1500)
However, as my people array would change my tooltips wouldn't always update. I tried every fix in this thread and others with no luck. The glitch seemed to only be happening around 5% of the time, and was nearly impossible to repeat.
Unfortunately, these tooltips are mission critical for my project, and showing an incorrect tooltip could be very bad.
Bootstrap was copying the value of the title
property to a new attribute, data-original-title
and removing the title
property (sometimes) when I would activate the toooltips. However, when my title={{ person.tooltip }}
would change the new value would not always be updated into the property data-original-title
. I tried deactivating the tooltips and reactivating them, destroying them, binding to this property directly... everything. However each of these either didn't work or created new issues; such as the title
and data-original-title
attributes both being removed and un-bound from my object.
Perhaps the most ugly code I've ever pushed, but it solved this small but substantial problem for me. I run this code each time the tooltip is update with new data:
$timeout(function() {
$('[data-toggle="tooltip"]').each(function(index) {
// sometimes the title is blank for no apparent reason. don't override in these cases.
if ($(this).attr("title").length > 0) {
$( this ).attr("data-original-title", $(this).attr("title"));
}
});
$timeout(function() {
// finally, activate the tooltips
$(document).tooltip({ selector: '[data-toggle="tooltip"]'});
}, 500);
}, 1500);
What's happening here in essence is:
title
s to be updated. title
property that is not empty (i.e. it has changed), copy it to the data-original-title
property so it will be picked up by Bootstrap's toolips.Hope this long answer helps someone who may have been struggling as I was.
A possible solution using Boost might be:
#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t "));
This approach might be even faster than the stringstream
approach. And since this is a generic template function it can be used to split other types of strings (wchar, etc. or UTF-8) using all kinds of delimiters.
See the documentation for details.
A simple and up to date solution is to use the React React useRef hook that stores a reference to the component/element, combined with a useEffect hook, which fires at component renders.
import React, {useState, useEffect, useRef} from 'react';
export default App = () => {
const [width, setWidth] = useState(0);
const elementRef = useRef(null);
useEffect(() => {
setWidth(elementRef.current.getBoundingClientRect().width);
}, []); //empty dependency array so it only runs once at render
return (
<div ref={elementRef}>
{width}
</div>
)
}
I approached the same problem yesterday and found a module called [natsort][1], which solves your problem. Use:
from natsort import natsorted # pip install natsort
# Example list of strings
a = ['1', '10', '2', '3', '11']
[In] sorted(a)
[Out] ['1', '10', '11', '2', '3']
[In] natsorted(a)
[Out] ['1', '2', '3', '10', '11']
# Your array may contain strings
[In] natsorted(['string11', 'string3', 'string1', 'string10', 'string100'])
[Out] ['string1', 'string3', 'string10', 'string11', 'string100']
It also works for dictionaries as an equivalent of sorted
.
[1]: https://pypi.org/project/natsort/
If you want to overwrite only one file:
git fetch
git checkout origin/master <filepath>
If you want to overwrite all changed files:
git fetch
git reset --hard origin/master
(This assumes that you're working on master
locally and you want the changes on the origin's master
- if you're on a branch, substitute that in instead.)
Use:
<script>
function onlyNumber(id){
var DataVal = document.getElementById(id).value;
document.getElementById(id).value = DataVal.replace(/[^0-9]/g,'');
}
</script>
<input type="text" id="1" name="1" onChange="onlyNumber(this.id);">
And if you want to update a value after press key, you can change onChange for onKeypress, onKeyDown or onKeyup. But event onKeypress doesn't running in any browsers.
textBoxName.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
onChange();
}
@Override
public void removeUpdate(DocumentEvent e) {
onChange();
}
@Override
public void changedUpdate(DocumentEvent e) {
onChange();
}
});
But I would not just parse anything the user (maybe on accident) touches on his keyboard into an Integer
. You should catch any Exception
s thrown and make sure the JTextField
is not empty.
"\n" => Newline or Linefeed (semantics)
Unix based systems use just a "\n" to end a line of text.
Here is the way I've found to load all image data for all products in a collection. I am not sure at the moment why its needed to switch from Mage::getModel to Mage::helper and reload the product, but it must be done. I've reverse engineered this code from the magento image soap api, so I'm pretty sure its correct.
I have it set to load products with a vendor code equal to '39' but you could change that to any attribute, or just load all the products, or load whatever collection you want (including the collections in the phtml files showing products currently on the screen!)
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addFieldToFilter(array(
array('attribute'=>'vendor_code','eq'=>'39'),
));
$collection->addAttributeToSelect('*');
foreach ($collection as $product) {
$prod = Mage::helper('catalog/product')->getProduct($product->getId(), null, null);
$attributes = $prod->getTypeInstance(true)->getSetAttributes($prod);
$galleryData = $prod->getData('media_gallery');
foreach ($galleryData['images'] as &$image) {
var_dump($image);
}
}
I know others have answered this already. But a very important factor here that may help other people experiencing similar issue:
You must have an onChange
handler added in your input field (e.g. textField, checkbox, radio, etc). Always handle activity through the onChange
handler.
Example:
<input ... onChange={ this.myChangeHandler} ... />
When you are working with checkbox you may need to handle its checked
state with !!
.
Example:
<input type="checkbox" checked={!!this.state.someValue} onChange={.....} >
Reference: https://github.com/facebook/react/issues/6779#issuecomment-326314716
First find out your IP camera's streaming url, like whether it's RTSP/HTTP etc.
Code changes will be as follows:
cap = cv2.VideoCapture("ipcam_streaming_url")
For example:
cap = cv2.VideoCapture("http://192.168.18.37:8090/test.mjpeg")
You are using the beta version of angular CLI you can do this way.
npm uninstall -g @angular/cli
npm uninstall -g angular/cli
Then type,
npm cache clean
Then go to the AppData folder which is hidden in your users and go to roaming folder which is inside AppData then go to npm folder and delete angular files in there and also go to npm-cache folder and delete angular components in there.After that restart your PC and type
npm install -g @angular/cli@latest
This worked for me ??
I have done it like:
using (StreamReader sr = File.OpenText(jsonFilePath))
{
var myObject = JsonConvert.DeserializeObject<List<YourObject>>(sr.ReadToEnd());
}
also, you can do this with async call like: sr.ReadToEndAsync(). using Newtonsoft.Json as reference.
Hope, this helps.
The easiest way: Just double click on this button and choose "NoTitleBar" ;)
This one helped me,
res.format({
json:function(){
var responseData = {};
responseData['status'] = 200;
responseData['outputPath'] = outputDirectoryPath;
responseData['sourcePath'] = url;
responseData['message'] = 'Scraping of requested resource initiated.';
responseData['logfile'] = logFileName;
res.json(JSON.stringify(responseData));
}
});
(repost from my other response)
Use cli utility keytool from java software distribution for import (and trust!) needed certificates
Sample:
From cli change dir to jre\bin
Check keystore (file found in jre\bin directory)
keytool -list -keystore ..\lib\security\cacerts
Password is changeit
Download and save all certificates in chain from needed server.
Add certificates (before need to remove "read-only" attribute on file ..\lib\security\cacerts
), run:
keytool -alias REPLACE_TO_ANY_UNIQ_NAME -import -keystore.\lib\security\cacerts -file "r:\root.crt"
accidentally I found such a simple tip. Other solutions require the use of InstallCert.Java and JDK
source: http://www.java-samples.com/showtutorial.php?tutorialid=210
Shell calls to reverse (as mentioned above) are very good to debug these problems, but there are two critical conditions:
Yes, it's logical. Yes, it's also confusing because reverse will only throw the exception and won't give you any further hints.
An example of URL pattern:
url(r'^cookies/(?P<hostname>[^/]+)/(?P<url_id>\d+)/$', 'register_site.views.show_cookies', name='show_cookies'),
And then what happens in shell:
>>> from register_site.views import show_cookies
>>> reverse(show_cookies)
NoReverseMatch: Reverse for 'register_site.views.show_cookies' with arguments '()' and keyword arguments '{}' not found.
It doesn't work because I supplied no arguments.
>>> reverse('show_cookies', kwargs={'url_id':123,'hostname': 'aaa'})
'/cookies/aaa/123'
Now it worked, but...
>>> reverse('show_cookies', kwargs={'url_id':'x','hostname': 'www.dupa.com'})
NoReverseMatch: Reverse for 'show_cookies' with arguments '()' and keyword arguments '{'url_id': 'x', 'hostname': 'www.dupa.com'}' not found.
Now it didn't work because url_id didn't match the regexp (expected numeric, supplied string).
You can use reverse with both positional arguments and keyword arguments. The syntax is:
reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None)
As it comes to the url template tag, there's funny thing about it. Django documentation gives example of using quoted view name:
{% url 'news.views.year_archive' yearvar %}
So I used it in a similar way in my HTML template:
{% url 'show_cookies' hostname=u.hostname url_id=u.pk %}
But this didn't work for me. But the exception message gave me a hint of what could be wrong - note the double single quotes around view name:
Reverse for ''show_cookies'' with arguments...
It started to work when I removed the quotes:
{% url show_cookies hostname=u.hostname url_id=u.pk %}
And this is confusing.
Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.
You'll need to unpack the file or use it directly.
If you have a Context, you can use context.getAssets().open("myfoldername/myfilename");
to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).
If you are like me and you somehow have full file paths (I did some glob() pattern matching on required photos so I do pretty much end up with full file paths), and your storage setup is well linked (i.e. such that your paths have the string storage/app/public/
), then you can use my little dirty hack below :p)
public static function hackoutFileFromStorageFolder($fullfilePath) {
if (strpos($fullfilePath, 'storage/app/public/')) {
$fileParts = explode('storage/app/public/', $fullfilePath);
if( count($fileParts) > 1){
return $fileParts[1];
}
}
return '';
}
I had the same issue. However sometimes CMD failed to run my files. That's why i create a temp.bat on my desktop, next this temp.bat is going to run my file, and next the temp file is going to be deleted.
I know this is a bigger code, however worked for me in 100% when even Runtime.getRuntime().exec() failed.
// creating a string for the Userprofile (either C:\Admin or whatever)
String userprofile = System.getenv("USERPROFILE");
BufferedWriter writer = null;
try {
//create a temporary file
File logFile = new File(userprofile+"\\Desktop\\temp.bat");
writer = new BufferedWriter(new FileWriter(logFile));
// Here comes the lines for the batch file!
// First line is @echo off
// Next line is the directory of our file
// Then we open our file in that directory and exit the cmd
// To seperate each line, please use \r\n
writer.write("cd %ProgramFiles(x86)%\\SOME_FOLDER \r\nstart xyz.bat \r\nexit");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
// running our temp.bat file
Runtime rt = Runtime.getRuntime();
try {
Process pr = rt.exec("cmd /c start \"\" \""+userprofile+"\\Desktop\\temp.bat" );
pr.getOutputStream().close();
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
// deleting our temp file
File databl = new File(userprofile+"\\Desktop\\temp.bat");
databl.delete();
If you are using systemd I just found out that you seem to have to add them to the systemd unit file. This on Ubuntu 16. Putting them into the .profile and .bashrc (even the /etc/profile) resulted in the ENV Vars not being available in the juypter notebooks.
I had to edit:
/lib/systemd/system/jupyer-notebook.service
and put in the variable i wanted to read in the unit file like:
Environment=MYOWN_VAR=theVar
and only then could I read it from within juypter notebook.
base is the number that you want to power up, n is the power, we return 1 if n is 0, and we return the base if the n is 1, if the conditions are not met, we use the formula base*(powerN(base,n-1)) eg: 2 raised to to using this formula is : 2(base)*2(powerN(base,n-1)).
public int power(int base, int n){
return n == 0 ? 1 : (n == 1 ? base : base*(power(base,n-1)));
}
As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.
HttpContext.Current
was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.
You can access the current HTTP context via the HttpContext
property on any controller. The closest thing to your original code sample would be to pass HttpContext
into the method you are calling:
public class HomeController : Controller
{
public IActionResult Index()
{
MyMethod(HttpContext);
// Other code
}
}
public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
var host = $"{context.Request.Scheme}://{context.Request.Host}";
// Other code
}
If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext
is passed into your Invoke
method automatically:
public Task Invoke(HttpContext context)
{
// Do something with the current HTTP context...
}
Finally, you can use the IHttpContextAccessor
helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.
Request this interface in your constructor:
public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
You can then access the current HTTP context in a safe way:
var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...
IHttpContextAccessor
isn't always added to the service container by default, so register it in ConfigureServices
just to be safe:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
// if < .NET Core 2.2 use this
//services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Other code...
}
You can use df.plot.scatter, and pass an array to c= argument defining the color of each point:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
colors = np.where(df["key1"]==4,'r','-')
colors[df["key1"]==6] = 'g'
colors[df["key1"]==8] = 'b'
print(colors)
df.plot.scatter(x="one",y="two",c=colors)
plt.show()
Give a look at this link : http://zircote.com/swagger-php/installation.html
If you need another help please feel free to ask.
You can use Web SQL API which is an ordinary SQLite database in your browser and you can open/modify it like any other SQLite databases for example with Lita.
Chrome locates databases automatically according to domain names or extension id. A few months ago I posted on my blog short article on how to delete Chrome's database because when you're testing some functionality it's quite useful.
Here is how one can do it via the global request
helper function.
{{ request()->segment(1) }}
Note: request()
returns the object of the Request
class.
When use method delete in form then must have to set route delete
Route::delete("empresas/eliminar/{id}", "CompaniesController@delete");
Write a new function for settimeout. Pls try this.
class CowtanApp extends Component {
constructor(props){
super(props);
this.state = {
timePassed: false
};
}
componentDidMount() {
this.setTimeout( () => {
this.setTimePassed();
},1000);
}
setTimePassed() {
this.setState({timePassed: true});
}
render() {
if (!this.state.timePassed){
return <LoadingPage/>;
}else{
return (
<NavigatorIOS
style = {styles.container}
initialRoute = {{
component: LoginPage,
title: 'Sign In',
}}/>
);
}
}
}
You can do this:
//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));
//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
if(linkList.get(i).getAttribute("href").contains("long"))
{
linkList.get(i).click();
break;
}
}
in this what we r doing is first we are finding all the <a>
tags and storing them in a list.After
that we are iterating the list one by one to find <a>
tag whose href attribute contains long string. And then we click on that particular <a>
tag and comes out of the loop.
For setting proxy server we need to set APNS
setting. To do this:
Go to Setting
Go to wireless and networks
Go to mobile networks
Go to access point names. Use menu to add new apns
Set Proxy = localhost
Set Port = port that you are using to make proxy server, in my case it is 8989
For setting Name and apn here is the link:
According to your sim
card you can see the table
You could do something using the grep command:
find . | grep -v '(dll|exe)$'
The -v
flag on grep
specifically means "find things that don't match this expression."