Despite the original question being posted five years ago, the problem still persists and is rather annoying.
The general solution is thorough analysis of all referenced assemblies to understand what's going wrong. To make this task easier I made a tool (a Visual Studio extension) which allows selecting a .NET assembly (a .dll
or .exe
file) to get a graph of all the referenced assemblies while highlighting conflicting or missing references.
The tool is available in Visual Studio Gallery: https://marketplace.visualstudio.com/vsgallery/051172f3-4b30-4bbc-8da6-d55f70402734
The solution is to put the scripts in an outside js file (lets called 'yourDynamic.js') and re-register de file everytime you refresh the updatepanel.
I use this in the updatepanel_prerender event:
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "UpdatePanel1_PreRender", _
"<script type='text/javascript' id='UpdatePanel1_PreRender'>" & _
"include('yourDynamic.js');" & _
"removeDuplicatedScript('UpdatePanel1_PreRender');</script>" _
, False)
In the page or in some other include you will need this javascript:
// Include a javascript file inside another one.
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('src'))
{
if(scripts[x].getAttribute('src').indexOf(filename) != -1)
{
head.removeChild(scripts[x]);
break;
}
}
}
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('id'))
{
if(scripts[x].getAttribute('id').indexOf(id) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
clearAjaxNetJunk();
}
// Evoids the update panel auto generated scripts to grow to inifity. X-(
function clearAjaxNetJunk()
{
var knowJunk = 'Sys.Application.add_init(function() {';
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].textContent)
{
if(scripts[x].textContent.indexOf(knowJunk) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
}
Pretty cool, ah...jejeje This part of what i posted some time ago here.
Hope this help... :)
For drawable resource
you can use standard android images :
http://androiddrawables.com/Menu.html
For example :
android:background="@android:drawable/ic_menu_close_clear_cancel"
One cheeky solution :
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
HTML :
<form id="form1" runat="server">
<div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
Print me I am in 1st Div
</div>
<div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
I am not going to print
</div>
<input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>
Though the first approach is advocated as 'the angular like' approach, I feel this adds overheads.
Consider if I want to use this myservice.foo function in 10 different controllers. I will have to specify this 'myService' dependency and then $scope.callFoo scope property in all ten of them. This is simply a repetition and somehow violates the DRY principle.
Whereas, if I use the $rootScope approach, I specify this global function gobalFoo only once and it will be available in all my future controllers, no matter how many.
I've figured out how to work around this issue without mixing parent and sub scope data.
Set a ng-if
on the the ng-include
element and set it to a scope variable.
For example :
<div ng-include="{{ template }}" ng-if="show"/>
In your controller, when you have set all the data you need in your sub scope, then set show to true
. The ng-include
will copy at this moment the data set in your scope and set it in your sub scope.
The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.
Max
If you are not averse to using find
, I like its -prune
feature:
find [directory] \
-name "pattern_to_exclude" -prune \
-o -name "another_pattern_to_exclude" -prune \
-o -name "pattern_to_INCLUDE" -print0 \
| xargs -0 -I FILENAME grep -IR "pattern" FILENAME
On the first line, you specify the directory you want to search. .
(current directory) is a valid path, for example.
On the 2nd and 3rd lines, use "*.png"
, "*.gif"
, "*.jpg"
, and so forth. Use as many of these -o -name "..." -prune
constructs as you have patterns.
On the 4th line, you need another -o
(it specifies "or" to find
), the patterns you DO want, and you need either a -print
or -print0
at the end of it. If you just want "everything else" that remains after pruning the *.gif
, *.png
, etc. images, then use
-o -print0
and you're done with the 4th line.
Finally, on the 5th line is the pipe to xargs
which takes each of those resulting files and stores them in a variable FILENAME
. It then passes grep
the -IR
flags, the "pattern"
, and then FILENAME
is expanded by xargs
to become that list of filenames found by find
.
For your particular question, the statement may look something like:
find . \
-name "*.png" -prune \
-o -name "*.gif" -prune \
-o -name "*.svn" -prune \
-o -print0 | xargs -0 -I FILES grep -IR "foo=" FILES
You can use VBA - something like
Range("A1:A6").Interior.Color = RGB(127,187,199)
Just pass in the cell value.
I am getting day
, month
and year
using dedicated functions moment().date(), moment().month() and moment().year() of momentjs
.
let day = moment('2014-07-28', 'YYYY/MM/DD').date();_x000D_
let month = 1 + moment('2014-07-28', 'YYYY/MM/DD').month();_x000D_
let year = moment('2014-07-28', 'YYYY/MM/DD').year();_x000D_
_x000D_
console.log(day);_x000D_
console.log(month);_x000D_
console.log(year);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
_x000D_
I don't know why there are 48 upvotes for @Chris Schmitz answer which is not 100% correct.
Month is in form of array and starts from 0 so to get exact value we should use 1 + moment().month()
Of course: simply use os.chdir(..)
.
This image explains normal script tag, async and defer
Async scripts are executed as soon as the script is loaded, so it doesn't guarantee the order of execution (a script you included at the end may execute before the first script file )
Defer scripts guarantees the order of execution in which they appear in the page.
Ref this link : http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
Before using v-html
, you have to make sure that the element which you escape is sanitized in case you allow user input, otherwise you expose your app to xss vulnerabilities.
More info here: https://vuejs.org/v2/guide/security.html
I highly encourage you that instead of using v-html
to use this npm package
Add removeSelf
to directly call on a view. If attached to a parent, it will be removed. This makes your code more declarative, and thus readable.
myView.removeSelf()
fun View?.removeSelf() {
this ?: return
val parent = parent as? ViewGroup ?: return
parent.removeView(this)
}
Here are 3 options for how to programmatically add a view to a ViewGroup
.
// Built-in
myViewGroup.addView(myView)
// Reverse addition
myView.addTo(myViewGroup)
fun View?.addTo(parent: ViewGroup?) {
this ?: return
parent ?: return
parent.addView(this)
}
// Null-safe extension
fun ViewGroup?.addView(view: View?) {
this ?: return
view ?: return
addView(view)
}
Assuming that you do not want to change orig
, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:
from itertools import chain
dest = dict(chain(orig.items(), extra.items()))
Or without itertools:
dest = dict(list(orig.items()) + list(extra.items()))
Note that you only need to pass the result of items()
into list()
on Python 3, on 2.x dict.items()
already returns a list so you can just do dict(orig.items() + extra.items())
.
As a more general use case, say you have a larger list of dicts that you want to combine into a single dict, you could do something like this:
from itertools import chain
dest = dict(chain.from_iterable(map(dict.items, list_of_dicts)))
I found some elegant solution on MSDN
System.Console.Write('\uXXXX') //XXXX is hex Unicode for character
This simple program writes ? right on the screen.
using System;
public class Test
{
public static void Main()
{
Console.Write('\u2103'); //? character code
}
}
I had this issue while using Python installed with sudo make altinstall
on Opensuse linux. It seems that the compiled libraries are installed in /usr/local/lib64
but Python is looking for them in /usr/local/lib
.
I solved it by creating a dynamic link to the relevant directory in /usr/local/lib
sudo ln -s /usr/local/lib64/python3.8/lib-dynload/ /usr/local/lib/python3.8/lib-dynload
I suspect the better thing to do would be to specify libdir
as an argument to configure
(at the start of the build process) but I haven't tested it that way.
Open you rails console
ActiveRecord::Base.connection.execute("drop table table_name")
Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?
As so:
Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each element In sArray
XLSMToXLSX(element)
Next element
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub
Sub XLSMToXLSX(ByVal file As String)
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsx" Then
Workbooks.Open Filename:=myPath & WorkFile
Application.DisplayAlerts = False
Application.EnableEvents = False
ActiveWorkbook.SaveAs Filename:= _
modifiedFileName, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, _
ConflictResolution:=xlLocalSessionChanges
Application.DisplayAlerts = True
Application.EnableEvents = True
ActiveWorkbook.Close
End If
WorkFile = Dir()
Loop
End Sub
If its working when you are using a browser and then passing on your username and password for the first time - then this means that once authentication is done Request header of your browser is set with required authentication values, which is then passed on each time a request is made to hosting server.
So start with inspecting Request Header (this could be done using Web Developers tools), Once you established whats required in header then you could pass this within your HttpWebRequest Header.
Example with Digest Authentication:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
namespace NUI
{
public class DigestAuthFixer
{
private static string _host;
private static string _user;
private static string _password;
private static string _realm;
private static string _nonce;
private static string _qop;
private static string _cnonce;
private static DateTime _cnonceDate;
private static int _nc;
public DigestAuthFixer(string host, string user, string password)
{
// TODO: Complete member initialization
_host = host;
_user = user;
_password = password;
}
private string CalculateMd5Hash(
string input)
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hash = MD5.Create().ComputeHash(inputBytes);
var sb = new StringBuilder();
foreach (var b in hash)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
private string GrabHeaderVar(
string varName,
string header)
{
var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
var matchHeader = regHeader.Match(header);
if (matchHeader.Success)
return matchHeader.Groups[1].Value;
throw new ApplicationException(string.Format("Header {0} not found", varName));
}
private string GetDigestHeader(
string dir)
{
_nc = _nc + 1;
var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
var digestResponse =
CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));
return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
"algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
_user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
}
public string GrabResponse(
string dir)
{
var url = _host + dir;
var uri = new Uri(url);
var request = (HttpWebRequest)WebRequest.Create(uri);
// If we've got a recent Auth header, re-use it!
if (!string.IsNullOrEmpty(_cnonce) &&
DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
{
request.Headers.Add("Authorization", GetDigestHeader(dir));
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// Try to fix a 401 exception by adding a Authorization header
if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
_realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
_nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
_qop = GrabHeaderVar("qop", wwwAuthenticateHeader);
_nc = 0;
_cnonce = new Random().Next(123400, 9999999).ToString();
_cnonceDate = DateTime.Now;
var request2 = (HttpWebRequest)WebRequest.Create(uri);
request2.Headers.Add("Authorization", GetDigestHeader(dir));
response = (HttpWebResponse)request2.GetResponse();
}
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
Then you could call it:
DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);
if Url is: http://xyz.rss.com/folder/rss then domain: http://xyz.rss.com (domain part) dir: /folder/rss (rest of the url)
you could also return it as stream and use XmlDocument Load() method.
A good way for looping on an enumerable JavaScript object which could be awesome and common for ReactJS is using Object.keys
or Object.entries
with using map
function. like below:
// assume items:
const items = {
first: { name: 'phone', price: 400 },
second: { name: 'tv', price: 300 },
third: { name: 'sofa', price: 250 },
};
For looping and show some UI on ReactJS
act like below:
~~~
<div>
{Object.entries(items).map(([key, ({ name, price })]) => (
<div key={key}>
<span>name: {name}</span>
<span>price: {price}</span>
</div>
))}
</div>
Actually, I use the destructuring assignment twice, once for getting key
once for getting name
and price
.
Adding a reference to System.Net.Http.Formatting.dll may cause DLL mismatch issues. Right now, System.Net.Http.Formatting.dll appears to reference version 4.5.0.0 of Newtonsoft.Json.DLL, whereas the latest version is 6.0.0.0. That means you'll need to also add a binding redirect to avoid a .NET Assembly exception if you reference the latest Newtonsoft NuGet package or DLL:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
So an alternative solution to adding a reference to System.Net.Http.Formatting.dll is to read the response as a string and then desearalize yourself with JsonConvert.DeserializeObject(responseAsString). The full method would be:
public async Task<T> GetHttpResponseContentAsType(string baseUrl, string subUrl)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(subUrl);
response.EnsureSuccessStatusCode();
var responseAsString = await response.Content.ReadAsStringAsync();
var responseAsConcreteType = JsonConvert.DeserializeObject<T>(responseAsString);
return responseAsConcreteType;
}
}
$('p:after').css('display','none');
For fixing this issue from Eclipse:
1) Add below dependency in Maven pom.xml and save the pom.xml file.
<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.3.1</version>
</dependency>
2) Go to project >> Maven >> Update Project
select the project and click OK.
3) Optional step, if it's not resolved till step 2 then do below step after doing step-1
Go to project >> Maven >> Update Project >> check in the checkbox 'Force Update of Snapshots/Releases'
select the project and click OK.
Use Rational class from JScience library. It's the best thing for fractional arithmetic I seen in Java.
public async Task<bool> Update(MyObject item)
{
Context.Entry(await Context.MyDbSet.FirstOrDefaultAsync(x => x.Id == item.Id)).CurrentValues.SetValues(item);
return (await Context.SaveChangesAsync()) > 0;
}
I use this simple one-liner:
public static DateTime GetLastDayOfPreviousMonth(this DateTime date)
{
return date.AddDays(-date.Day);
}
Be aware, that it retains the time.
How do I determine the size of an object in Python?
The answer, "Just use sys.getsizeof
", is not a complete answer.
That answer does work for builtin objects directly, but it does not account for what those objects may contain, specifically, what types, such as custom objects, tuples, lists, dicts, and sets contain. They can contain instances each other, as well as numbers, strings and other objects.
Using 64-bit Python 3.6 from the Anaconda distribution, with sys.getsizeof
, I have determined the minimum size of the following objects, and note that sets and dicts preallocate space so empty ones don't grow again until after a set amount (which may vary by implementation of the language):
Python 3:
Empty
Bytes type scaling notes
28 int +4 bytes about every 30 powers of 2
37 bytes +1 byte per additional byte
49 str +1-4 per additional character (depending on max width)
48 tuple +8 per additional item
64 list +8 for each additional
224 set 5th increases to 736; 21nd, 2272; 85th, 8416; 341, 32992
240 dict 6th increases to 368; 22nd, 1184; 43rd, 2280; 86th, 4704; 171st, 9320
136 func def does not include default args and other attrs
1056 class def no slots
56 class inst has a __dict__ attr, same scaling as dict above
888 class def with slots
16 __slots__ seems to store in mutable tuple-like structure
first slot grows to 48, and so on.
How do you interpret this? Well say you have a set with 10 items in it. If each item is 100 bytes each, how big is the whole data structure? The set is 736 itself because it has sized up one time to 736 bytes. Then you add the size of the items, so that's 1736 bytes in total
Some caveats for function and class definitions:
Note each class definition has a proxy __dict__
(48 bytes) structure for class attrs. Each slot has a descriptor (like a property
) in the class definition.
Slotted instances start out with 48 bytes on their first element, and increase by 8 each additional. Only empty slotted objects have 16 bytes, and an instance with no data makes very little sense.
Also, each function definition has code objects, maybe docstrings, and other possible attributes, even a __dict__
.
Also note that we use sys.getsizeof()
because we care about the marginal space usage, which includes the garbage collection overhead for the object, from the docs:
getsizeof()
calls the object’s__sizeof__
method and adds an additional garbage collector overhead if the object is managed by the garbage collector.
Also note that resizing lists (e.g. repetitively appending to them) causes them to preallocate space, similarly to sets and dicts. From the listobj.c source code:
/* This over-allocates proportional to the list size, making room
* for additional growth. The over-allocation is mild, but is
* enough to give linear-time amortized behavior over a long
* sequence of appends() in the presence of a poorly-performing
* system realloc().
* The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
* Note: new_allocated won't overflow because the largest possible value
* is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
*/
new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
Python 2.7 analysis, confirmed with guppy.hpy
and sys.getsizeof
:
Bytes type empty + scaling notes
24 int NA
28 long NA
37 str + 1 byte per additional character
52 unicode + 4 bytes per additional character
56 tuple + 8 bytes per additional item
72 list + 32 for first, 8 for each additional
232 set sixth item increases to 744; 22nd, 2280; 86th, 8424
280 dict sixth item increases to 1048; 22nd, 3352; 86th, 12568 *
120 func def does not include default args and other attrs
64 class inst has a __dict__ attr, same scaling as dict above
16 __slots__ class with slots has no dict, seems to store in
mutable tuple-like structure.
904 class def has a proxy __dict__ structure for class attrs
104 old class makes sense, less stuff, has real dict though.
Note that dictionaries (but not sets) got a more compact representation in Python 3.6
I think 8 bytes per additional item to reference makes a lot of sense on a 64 bit machine. Those 8 bytes point to the place in memory the contained item is at. The 4 bytes are fixed width for unicode in Python 2, if I recall correctly, but in Python 3, str becomes a unicode of width equal to the max width of the characters.
And for more on slots, see this answer.
We want a function that searches the elements in lists, tuples, sets, dicts, obj.__dict__
's, and obj.__slots__
, as well as other things we may not have yet thought of.
We want to rely on gc.get_referents
to do this search because it works at the C level (making it very fast). The downside is that get_referents can return redundant members, so we need to ensure we don't double count.
Classes, modules, and functions are singletons - they exist one time in memory. We're not so interested in their size, as there's not much we can do about them - they're a part of the program. So we'll avoid counting them if they happen to be referenced.
We're going to use a blacklist of types so we don't include the entire program in our size count.
import sys
from types import ModuleType, FunctionType
from gc import get_referents
# Custom objects know their class.
# Function objects seem to know way too much, including modules.
# Exclude modules as well.
BLACKLIST = type, ModuleType, FunctionType
def getsize(obj):
"""sum size of object & members."""
if isinstance(obj, BLACKLIST):
raise TypeError('getsize() does not take argument of type: '+ str(type(obj)))
seen_ids = set()
size = 0
objects = [obj]
while objects:
need_referents = []
for obj in objects:
if not isinstance(obj, BLACKLIST) and id(obj) not in seen_ids:
seen_ids.add(id(obj))
size += sys.getsizeof(obj)
need_referents.append(obj)
objects = get_referents(*need_referents)
return size
To contrast this with the following whitelisted function, most objects know how to traverse themselves for the purposes of garbage collection (which is approximately what we're looking for when we want to know how expensive in memory certain objects are. This functionality is used by gc.get_referents
.) However, this measure is going to be much more expansive in scope than we intended if we are not careful.
For example, functions know quite a lot about the modules they are created in.
Another point of contrast is that strings that are keys in dictionaries are usually interned so they are not duplicated. Checking for id(key)
will also allow us to avoid counting duplicates, which we do in the next section. The blacklist solution skips counting keys that are strings altogether.
To cover most of these types myself, instead of relying on the gc
module, I wrote this recursive function to try to estimate the size of most Python objects, including most builtins, types in the collections module, and custom types (slotted and otherwise).
This sort of function gives much more fine-grained control over the types we're going to count for memory usage, but has the danger of leaving types out:
import sys
from numbers import Number
from collections import Set, Mapping, deque
try: # Python 2
zero_depth_bases = (basestring, Number, xrange, bytearray)
iteritems = 'iteritems'
except NameError: # Python 3
zero_depth_bases = (str, bytes, Number, range, bytearray)
iteritems = 'items'
def getsize(obj_0):
"""Recursively iterate to sum size of object & members."""
_seen_ids = set()
def inner(obj):
obj_id = id(obj)
if obj_id in _seen_ids:
return 0
_seen_ids.add(obj_id)
size = sys.getsizeof(obj)
if isinstance(obj, zero_depth_bases):
pass # bypass remaining control flow and return
elif isinstance(obj, (tuple, list, Set, deque)):
size += sum(inner(i) for i in obj)
elif isinstance(obj, Mapping) or hasattr(obj, iteritems):
size += sum(inner(k) + inner(v) for k, v in getattr(obj, iteritems)())
# Check for custom object instances - may subclass above too
if hasattr(obj, '__dict__'):
size += inner(vars(obj))
if hasattr(obj, '__slots__'): # can have __slots__ with __dict__
size += sum(inner(getattr(obj, s)) for s in obj.__slots__ if hasattr(obj, s))
return size
return inner(obj_0)
And I tested it rather casually (I should unittest it):
>>> getsize(['a', tuple('bcd'), Foo()])
344
>>> getsize(Foo())
16
>>> getsize(tuple('bcd'))
194
>>> getsize(['a', tuple('bcd'), Foo(), {'foo': 'bar', 'baz': 'bar'}])
752
>>> getsize({'foo': 'bar', 'baz': 'bar'})
400
>>> getsize({})
280
>>> getsize({'foo':'bar'})
360
>>> getsize('foo')
40
>>> class Bar():
... def baz():
... pass
>>> getsize(Bar())
352
>>> getsize(Bar().__dict__)
280
>>> sys.getsizeof(Bar())
72
>>> getsize(Bar.__dict__)
872
>>> sys.getsizeof(Bar.__dict__)
280
This implementation breaks down on class definitions and function definitions because we don't go after all of their attributes, but since they should only exist once in memory for the process, their size really doesn't matter too much.
Rather than preg_replace
, you could always use PHP's filter functions using the filter_var()
function with FILTER_SANITIZE_STRING
.
My idea:
public enum SomeKindOfEnum{
ENUM_NAME("initialValue");
private String value;
SomeKindOfEnum(String value){
this.value = value;
}
public boolean equalValue(String passedValue){
return this.value.equals(passedValue);
}
}
And if u want to check Value u write:
SomeKindOfEnum.ENUM_NAME.equalValue("initialValue")
Kinda looks nice for me :). Maybe somebody will find it useful.
In my situation, I created a new SSRS report and new stored procedure for the dataset. I forgot to add the stored procedure to the database role that had permission to execute it. Once I added the permissions to SQL database role with EXECUTE, all was fine!
The error message encountered by the user was "An error occurred during client rendering. An error has occurred during report processing (rsProcessingAborted). Query execution failed for dataset "DataSet1'. (rsErrorExecutingCommand) For more information..."
you must #include <algorithm>
, then you can use std::find
Now I return Object
. I don't know better solution, but it works.
@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Object> getAll() {
List<Entity> entityList = entityManager.findAll();
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject Entity = new JSONObject();
entity.put("id", n.getId());
entity.put("address", n.getAddress());
entities.add(entity);
}
return new ResponseEntity<Object>(entities, HttpStatus.OK);
}
There are two things to remember here. One is to add the -PassThru
argument and two is to add the -Wait
argument. You need to add the wait argument because of this defect: http://connect.microsoft.com/PowerShell/feedback/details/520554/start-process-does-not-return-exitcode-property
-PassThru [<SwitchParameter>]
Returns a process object for each process that the cmdlet started. By d
efault, this cmdlet does not generate any output.
Once you do this a process object is passed back and you can look at the ExitCode property of that object. Here is an example:
$process = start-process ping.exe -windowstyle Hidden -ArgumentList "-n 1 -w 127.0.0.1" -PassThru -Wait
$process.ExitCode
# This will print 1
If you run it without -PassThru
or -Wait
, it will print out nothing.
The same answer is here: How do I run a Windows installer and get a succeed/fail value in PowerShell?
Open file
D:\wamp\www\yiistore2\common\config\params-local.php
Paste below code before return
Yii::setAlias('@anyname', realpath(dirname(__FILE__).'/../../'));
After inserting above code in params-local.php file your file should look like this.
Yii::setAlias('@anyname', realpath(dirname(__FILE__).'/../../'));
return [
];
Now to get path of your root (in my case its D:\wamp\www\yiistore2
) directory you can use below code in any php file.
echo Yii::getAlias('@anyname');
Adding "-EA Stop" solved this for me.
Use restart: always in your docker compose file.
Docker-compose up -d
will launch container from images again. Use docker-compose start
to start the stopped containers, it never launches new containers from images.
nginx:
restart: always
image: nginx
ports:
- "80:80"
- "443:443" links:
- other_container:other_container
Also you can write the code up in the docker file so that it gets created first, if it has the dependency of other containers.
Using ddl.Items.Clear()
will clear the dropdownlist however you must be sure that your dropdownlist is not set to:
AppendDataBoundItems="True"
This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.
SOLUTION
Add AppendDataBoundItems="False"
to your dropdownlist.
Now when data is rebound it will automatically clear all existing data beforehand.
Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
ddl2.DataSource = sql2
ddl2.DataBind()
End Sub
NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.
TOP TIP
Still want a default list item adding to your dropdown but need to rebind data?
Use AppendDataBoundItems="False"
to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.
ddl.Items.Insert(0, New ListItem("Select ...", ""))
Use a variable to store the timeout function. Then use clearTimeout()
to clear this variable of any active timeout functions, and then use setTimeout()
to set the active timeout function again. We run clearTimeout()
first, because if a user is typing "hello", we want our function to run shortly after the user presses the "o" key (and not once for each letter).
Super simple approach, designed to run a function after a user has finished typing in a text field...
$(document).ready(function(e) {
var timeout;
var delay = 2000; // 2 seconds
$('.text-input').keyup(function(e) {
$('#status').html("User started typing!");
if(timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
myFunction();
}, delay);
});
function myFunction() {
$('#status').html("Executing function for user!");
}
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Status: <span id="status">Default Status</span><br>
<textarea name="text-input" class="text-input"></textarea>
_x000D_
Useful differences:
Use notify() if all your waiting threads are interchangeable (the order they wake up doesn't matter), or if you only ever have one waiting thread. A common example is a thread pool used to execute jobs from a queue--when a job is added, one of threads is notified to wake up, execute the next job and go back to sleep.
Use notifyAll() for other cases where the waiting threads may have different purposes and should be able to run concurrently. An example is a maintenance operation on a shared resource, where multiple threads are waiting for the operation to complete before accessing the resource.
This should work:
$(document).ready(function() {
$("someTableSelector").find("tr:gt(0)").remove();
});
select {
outline: 0;
overflow: hidden;
height: 30px;
background: #2c343c;
color: #747a80;
border: #2c343c;
padding: 5px 3px 5px 10px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 10px;
}
select option {border: 1px solid #000; background: #010;}
Similar to other posts, but with an important distinction to make this work inside a div. The simpler answers aren't very copy-paste-able because they directly modify div or draw over the entire page.
The key here is that the containing div dividedbox has relative positioning, allowing it to sit nicely in your document with the other elements, while the quarters within have absolute positioning, giving you vertical/horizontal control inside the containing div.
As a bonus, text is responsively centered in the quarters.
HTML:
<head>
<meta charset="utf-8">
<title>Box model</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="title">Title Bar</h1>
<div id="dividedbox">
<div class="quarter" id="NW">
<p>NW</p>
</div>
<div class="quarter" id="NE">
<p>NE</p>
</div>
<div class="quarter" id="SE">
<p>SE</p>
</div>?
<div class="quarter" id="SW">
<p>SW</p>
</div>
</div>
</body>
</html>
CSS:
html, body { height:95%;} /* Important to make sure your divs have room to grow in the document */
#title { background: lightgreen}
#dividedbox { position: relative; width:100%; height:95%} /* for div growth */
.quarter {position: absolute; width:50%; height:50%; /* gives quarters their size */
display: flex; justify-content: center; align-items: center;} /* centers text */
#NW { top:0; left:0; background:orange; }
#NE { top:0; left:50%; background:lightblue; }
#SW { top:50%; left:0; background:green; }
#SE { top:50%; left:50%; background:red; }
For the newer versions use:
var datatable = $('#table').dataTable().api();
$.get('myUrl', function(newDataArray) {
datatable.clear();
datatable.rows.add(newDataArray);
datatable.draw();
});
Taken from: https://stackoverflow.com/a/27781459/4059810
Check whether your config string is okay:
Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9999
I just had this issue today, and in my case it was because there was an invisible character in the jpda config parameter.
To be precise, I had dos line endings in my setenv.sh file on tomcat, causing a carriage-return character right after 'dt_socket'
You can call native methods trough trigger in jQuery. Just do this:
$('.play').trigger("play");
And the same for pause: $('.play').trigger("pause");
EDIT: as F... pointed out in the comments, you can do something similar to access properties: $('.play').prop("paused");
If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT
. This means that the path is dynamic, and can be moved between servers without messing about with the code.
<?php
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation,"w");
$content = "Your text here";
fwrite($file,$content);
fclose($file);
?>
Since you've already stashed your changes, all you need is this one-liner:
git stash branch <branchname> [<stash>]
From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):
Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.
This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.
This is how I do this with JQuery...
using the jquery-watermark plugin (http://code.google.com/p/jquery-watermark/)
$('#inputId').watermark('Please select a name');
works like a charm!!
There is some good documentation at that google code site.
Hope this helps!
I created a version that searches all stylesheets and returns matches as a key/value object. You can also specify startsWith to match child styles.
getStylesBySelector('.pure-form-html', true);
returns:
{
".pure-form-html body": "padding: 0; margin: 0; font-size: 14px; font-family: tahoma;",
".pure-form-html h1": "margin: 0; font-size: 18px; font-family: tahoma;"
}
from:
.pure-form-html body {
padding: 0;
margin: 0;
font-size: 14px;
font-family: tahoma;
}
.pure-form-html h1 {
margin: 0;
font-size: 18px;
font-family: tahoma;
}
The code:
/**
* Get all CSS style blocks matching a CSS selector from stylesheets
* @param {string} className - class name to match
* @param {boolean} startingWith - if true matches all items starting with selector, default = false (exact match only)
* @example getStylesBySelector('pure-form .pure-form-html ')
* @returns {object} key/value object containing matching styles otherwise null
*/
function getStylesBySelector(className, startingWith) {
if (!className || className === '') throw new Error('Please provide a css class name');
var styleSheets = window.document.styleSheets;
var result = {};
// go through all stylesheets in the DOM
for (var i = 0, l = styleSheets.length; i < l; i++) {
var classes = styleSheets[i].rules || styleSheets[i].cssRules || [];
// go through all classes in each document
for (var x = 0, ll = classes.length; x < ll; x++) {
var selector = classes[x].selectorText || '';
var content = classes[x].cssText || classes[x].style.cssText || '';
// if the selector matches
if ((startingWith && selector.indexOf(className) === 0) || selector === className) {
// create an object entry with selector as key and value as content
result[selector] = content.split(/(?:{|})/)[1].trim();
}
}
}
// only return object if we have values, otherwise null
return Object.keys(result).length > 0 ? result : null;
}
I'm using this in production as part of the pure-form project. Hope it helps.
Assuming all of these columns are int
, then the first thing to sort out is converting one or more of them to a better data type - int
division performs truncation, so anything less than 100% would give you a result of 0:
select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)
from
CSPGI09_OVERSHIPMENT
Here, I've mutiplied one of the numbers by 100.0
which will force the result of the calculation to be done with float
s rather than int
s. By choosing 100
, I'm also getting it ready to be treated as a %
.
I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (-
and /
) at the same level, and so were relying on the precedence rules to define which operator applied first.
You can use jQuery
to achieve this
Example:
$(function () {
$('.map').maphilight();
});
Go through this LINK to know more.
If the above one doesnt work then go through this link.
EDIT :
Give same class to each area
tag like class="mapping"
and try this below code
$('.mapping').mouseover(function() {
alert($(this).attr('id'));
}).mouseout(function(){
alert('Mouseout....');
});
where T : struct
The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.
where T : class
The type argument must be a reference type, including any class, interface, delegate, or array type. (See note below.)
where T : new() The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last.
where T : [base class name]
The type argument must be or derive from the specified base class.
where T : [interface name]
The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.
where T : U
The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.
autoResetEvent.WaitOne()
is similar to
try
{
manualResetEvent.WaitOne();
}
finally
{
manualResetEvent.Reset();
}
as an atomic operation
You can center absolute items by providing the left property with the width of the device divided by two and subtracting out half of the element you'd like to center's width.
For example, your style might look something like this.
bottom: {
position: 'absolute',
left: (Dimensions.get('window').width / 2) - 25,
top: height*0.93,
}
var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});
Larvel 5.3 this actually worked for me by just updating LoginController.php
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
Session::set('backUrl', URL::previous());
}
public function redirectTo()
{
return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
}
ref: https://laracasts.com/discuss/channels/laravel/redirect-to-previous-page-after-login
the best way I can think of is using processing there are a few introductions on the net like displaying serial data, arduino graph and arduino radar
Since Arduino is based on processing its not that hard to learn
If you want to know the list of procedures you can run the following command -
show procedure status;
It will give you the list of procedures and their definers
Then you can run the show create procedure <procedurename>;
Your setting is all right. Some web servers require to specify the media and static folder files specifically. For example in pythonanywhere.com you have to go to the 'Web' section and add the url od the media folders and static folder. For example:
URL Directory
/static/ /home/Saidmamad/discoverthepamirs/static
/accounts/static/ /home/Saidmamad/discoverthepamirs/accounts/static
/media/ /home/Saidmamad/discoverthepamirs/discoverthepamirs/media
I know that it is late, but just to help those who visit this link because of the same problem ;)
To directly answer the question of how to "get a copy of that file":
svn cat -r 666 file > file_r666
then you can view the newly created file_r666
with any viewer or comparison program, e.g.
kompare file_r666 file
nicely shows the differences.
I posted the answer because the accepted answer's commands do actually not give a copy of the file and because svn cat -r 666 file | vim
does not work with my system (Vim: Error reading input, exiting...
)
The answer is correct, but you don't need to declare a variable. A string can contain your character:
"This string contains omega, that looks like this: \u03A9"
Unfortunately still those codes in ASCII are needed for displaying UTF-8, but I am still waiting (since too many years...) the day when UTF-8 will be same as ASCII was, and ASCII will be just a remembrance of the past.
Nobody mentioned the limit on the size of the stack frame.
There are two places memory can be allocated:
Thus if you allocate an array dynamically (the limit is large and described in detail by other posts.
int* a1 = new int[SIZE]; // SIZE limited only by OS/Hardware
Alternatively if the array is allocated on the stack then you are limited by the size of the stack frame. N.B. vectors and other containers have a small presence in the stack but usually the bulk of the data will be on the heap.
int a2[SIZE]; // SIZE limited by COMPILER to the size of the stack frame
A more detailed explanation. In your model, add:
def as_dict(self):
return {c.name: str(getattr(self, c.name)) for c in self.__table__.columns}
The str()
is for python 3 so if using python 2 use unicode()
. It should help deserialize dates. You can remove it if not dealing with those.
You can now query the database like this
some_result = User.query.filter_by(id=current_user.id).first().as_dict()
First()
is needed to avoid weird errors. as_dict()
will now deserialize the result. After deserialization, it is ready to be turned to json
jsonify(some_result)
I received this same error in the following Linq statement regarding DailyReport. The problem was that DailyReport had no default constructor. Apparently, it instantiates the object before populating the properties.
var sums = reports
.GroupBy(r => r.CountryRegion)
.Select(cr => new DailyReport
{
CountryRegion = cr.Key,
ProvinceState = "All",
RecordDate = cr.First().RecordDate,
Confirmed = cr.Sum(c => c.Confirmed),
Recovered = cr.Sum(c => c.Recovered),
Deaths = cr.Sum(c => c.Deaths)
});
The PDF/pdflib extension documentation in PHP is sparse (something that has been noted in bugs.php.net) - I reccommend you use the Zend library.
I post my final way of doing it based on the accepted answer:
@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {
private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
private String uploadsDirName;
@Override
public void init() throws ServletException {
super.init();
uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// ...
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Collection<Part> parts = req.getParts();
for (Part part : parts) {
File save = new File(uploadsDirName, getFilename(part) + "_"
+ System.currentTimeMillis());
final String absolutePath = save.getAbsolutePath();
log.debug(absolutePath);
part.write(absolutePath);
sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
}
}
// helpers
private static String getFilename(Part part) {
// courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1)
.substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
}
where :
@SuppressWarnings("serial")
class Controller extends HttpServlet {
static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
static ServletContext sc;
Logger log;
// private
// "/WEB-INF/app.properties" also works...
private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
private Properties properties;
@Override
public void init() throws ServletException {
super.init();
// synchronize !
if (sc == null) sc = getServletContext();
log = LoggerFactory.getLogger(this.getClass());
try {
loadProperties();
} catch (IOException e) {
throw new RuntimeException("Can't load properties file", e);
}
}
private void loadProperties() throws IOException {
try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
if (is == null)
throw new RuntimeException("Can't locate properties file");
properties = new Properties();
properties.load(is);
}
}
String property(final String key) {
return properties.getProperty(key);
}
}
and the /WEB-INF/app.properties :
upload.location=C:/_/
HTH and if you find a bug let me know
In Bootstrap 4.0.0 you cannot use the col-*
classes reliably (works in Firefox, but not in Chrome).
You need to use OhadR's answer:
<tr>
<th style="width: 16.66%">Col 1</th>
<th style="width: 25%">Col 2</th>
<th style="width: 50%">Col 4</th>
<th style="width: 8.33%">Col 5</th>
</tr>
With twitter bootstrap 3 use: class="col-md-*"
where * is a number of columns of width.
<tr class="something">
<td class="col-md-2">A</td>
<td class="col-md-3">B</td>
<td class="col-md-6">C</td>
<td class="col-md-1">D</td>
</tr>
With twitter bootstrap 2 use: class="span*"
where * is a number of columns of width.
<tr class="something">
<td class="span2">A</td>
<td class="span3">B</td>
<td class="span6">C</td>
<td class="span1">D</td>
</tr>
** If you have <th>
elements set the width there and not on the <td>
elements.
babel-regenerator-runtime
is now deprecated, instead one should use regenerator-runtime
.
To use the runtime generator with webpack
and babel
v7:
install regenerator-runtime
:
npm i -D regenerator-runtime
And then add within webpack configuration :
entry: [
'regenerator-runtime/runtime',
YOUR_APP_ENTRY
]
This is the perfect solution that worked for me without any 3rd party library.
Rendering a PDF Document in Android Activity/Fragment (Using PdfRenderer)
It's worth noting that console.log
in IE8 isn't a true Javascript function. It doesn't support the apply
or call
methods.
One caveat! If you want to compose this via OR or AND you cannot use it in this form:
-myfield:*
but you must use
(*:* NOT myfield:*)
This form is perfectly composable. Apparently SOLR will expand the first form to the second, but only when it is a top node. Hope this saves you some time!
If I understand your question correctly, is it the fact that the required
attribute appears to have default behaviour in Safari that's confusing you? If so, see: http://w3c.github.io/html/sec-forms.html#the-required-attribute
required
is not a custom attribute in HTML 5. It's defined in the spec, and is used in precisely the way you're presently using it.
EDIT: Well, not precisely. As ms2ger has pointed out, the required
attribute is a boolean attribute, and here's what the HTML 5 spec has to say about those:
Note: The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
See: http://w3c.github.io/html/infrastructure.html#sec-boolean-attributes
This article can provide a lot of insight here: http://redis.io/topics/memory-optimization
There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):
Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:
INCR id:users
SET user:{id} '{"name":"Fred","age":25}'
SADD users {id}
Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.
Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.
Store each Object's properties in a Redis hash.
INCR id:users
HMSET user:{id} name "Fred" age 25
SADD users {id}
Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.
Store each Object as a JSON string in a Redis hash.
INCR id:users
HMSET users {id} '{"name":"Fred","age":25}'
This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.
Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."
Store each property of each Object in a dedicated key.
INCR id:users
SET user:{id}:name "Fred"
SET user:{id}:age 25
SADD users {id}
According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).
Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.
Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).
If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)
I'd like to add df.values.tolist()
. (as long as you don't mind to get a column of lists rather than tuples)
import pandas as pd
import numpy as np
size = int(1e+07)
df = pd.DataFrame({'a': np.random.rand(size), 'b': np.random.rand(size)})
%timeit df.values.tolist()
1.47 s ± 38.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit list(zip(df.a,df.b))
1.92 s ± 131 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
UseParNewGC A parallel version of the young generation copying collector is used with the concurrent collector (i.e. if -XX:+ UseConcMarkSweepGC is used on the command line then the flag UseParNewGC is also set to true if it is not otherwise explicitly set on the command line).
Perhaps the easiest way to understand was combinations of garbage collection algorithms made by Alexey Ragozin
<table border="1" style="width:100%">_x000D_
<tr>_x000D_
<td align="center">Young collector</td>_x000D_
<td align="center">Old collector</td>_x000D_
<td align="center">JVM option</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Serial (DefNew)</td>_x000D_
<td>Serial Mark-Sweep-Compact</td>_x000D_
<td>-XX:+UseSerialGC</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Parallel scavenge (PSYoungGen)</td>_x000D_
<td>Serial Mark-Sweep-Compact (PSOldGen)</td>_x000D_
<td>-XX:+UseParallelGC</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Parallel scavenge (PSYoungGen)</td>_x000D_
<td>Parallel Mark-Sweep-Compact (ParOldGen)</td>_x000D_
<td>-XX:+UseParallelOldGC</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Serial (DefNew)</td>_x000D_
<td>Concurrent Mark Sweep</td>_x000D_
<td>_x000D_
<p>-XX:+UseConcMarkSweepGC</p>_x000D_
<p>-XX:-UseParNewGC</p>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Parallel (ParNew)</td>_x000D_
<td>Concurrent Mark Sweep</td>_x000D_
<td>_x000D_
<p>-XX:+UseConcMarkSweepGC</p>_x000D_
<p>-XX:+UseParNewGC</p>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan="2">G1</td>_x000D_
<td>-XX:+UseG1GC</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Conclusion:
Your question is not 100% clear, but I'm assuming you want to find every piece of text inside [P][/P]
tags:
>>> import re
>>> line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
>>> re.findall('\[P\]\s?(.+?)\s?\[\/P\]', line)
['Barack Obama', 'Bill Gates']
From the Errata:
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Should be:
ModelState.AddModelErrors(dinner.GetRuleViolations());
As a note ,
for those who need to have null value for things other than "true" or "false" strings , you can use the function below
public Boolean tryParseBoolean(String inputBoolean)
{
if(!inputBoolean.equals("true")&&!inputBoolean.equals("false")) return null;
return Boolean.valueOf(inputBoolean);
}
There's a very nice and concise answer to your question here. (It struck me as such a nicely straightforward way of explaining it that I want to link it from here.)
If you are on android and using threetenbp you can use DateTimeUtils
instead.
ex:
Date date = DateTimeUtils.toDate(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
you can't use Date.from
since it's only supported on api 26+
You should probably use a StringBuilder
with the append
method to construct your result, but otherwise this is as good of a solution as Java has to offer.
The first thing that comes to my mind is a one-liner regex:
var pageNum = $("#specificLink").attr("href").match(/page=([0-9]+)/)[1];
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
You can do this because regular expressions define extractors but you need to define the regex pattern first. I don't have access to a Scala REPL to test this but something like this should work.
val Pattern = "([a-cA-C])".r
word.firstLetter match {
case Pattern(c) => c bound to capture group here
case _ =>
}
declare -a arr
echo "-------------------------------------"
echo "Here another example with arr numeric"
echo "-------------------------------------"
arr=( 10 200 3000 40000 500000 60 700 8000 90000 100000 )
echo -e "\n Elements in arr are:\n ${arr[0]} \n ${arr[1]} \n ${arr[2]} \n ${arr[3]} \n ${arr[4]} \n ${arr[5]} \n ${arr[6]} \n ${arr[7]} \n ${arr[8]} \n ${arr[9]}"
echo -e " \n Total elements in arr are : ${arr[*]} \n"
echo -e " \n Total lenght of arr is : ${#arr[@]} \n"
for (( i=0; i<10; i++ ))
do echo "The value in position $i for arr is [ ${arr[i]} ]"
done
for (( j=0; j<10; j++ ))
do echo "The length in element $j is ${#arr[j]}"
done
for z in "${!arr[@]}"
do echo "The key ID is $z"
done
~
Kotlin example:
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
from Fragment:
inputMethodManager.hideSoftInputFromWindow(activity?.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
from Activity:
inputMethodManager.hideSoftInputFromWindow(currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
It would be better to use jQuery,
$(document).ready(function() {
$("a").css("cursor", "pointer");
});
and omit both href="#"
and href="javascript:void(0)"
.
The anchor tag markup will be like
<a onclick="hello()">Hello</a>
Simple enough!
Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve()
, dgesv spits this kind of error when the matrix you passed as a parameter is singular.
As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)
I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.
If you are using CSS to style (Not recommended.) you can use display:block;
, however, this will only give you line breaks before and after the styled element.
Make sure JAVA_HOME is set and the path in environment variables. The PATH should be able to find the keytools.exe
Open “Windows search” and search for "Environment Variables"
Under “System variables” click the “New…” button and enter JAVA_HOME as “Variable name” and the path to your Java JDK directory under “Variable value” it should be similar to this C:\Program Files\Java\jre1.8.0_231
Yes, this is probably a bit late. But one thing to add to everyone else's comments is that, Camel is actually a toolbox rather than a complete set of features. You should bear this in mind when developing and need to do various transformations and protocol conversions.
Camel itself relies on other frameworks and therefore sometimes you need to understand those as well in order to understand which is best suited for your needs. There are for example multiple ways to handle REST. This can get a bit confusing at first, but once you starting using and testing you will feel at ease and your knowledge of the different concepts will increase.
it also happens when you call a function from jsx directly rather than in an event. like
it will show the error if you write like
<h1>{this.myFunc}<h2>
it will go if you write:
<h1 onClick={this.myFunc}>Hit Me</h1>
That's not possible. localhost
always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.
If you want to access it e.g. in a browser, connect to it using the local IP instead:
http://192.168.180.1:8000
This is just an example of course, you can find out the actual IP by issuing an ifconfig
command on a shell in the guest operating system.
Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager
and EntityManagerFactory
, without explicit Spring dependencies in your code:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa
This allows you to either inject the EntityManagerFactory
, or else inject a thread-safe, transactional proxy of an EntityManager
directly. The latter makes for simpler code, but means more Spring plumbing is required.
You can change the CSS color
property using JavaScript in the onclick
event handler (in the same way you change the value
property):
<input type="text" onclick="this.value=''; this.style.color='#000'" />
Note that it's not the best practice to use inline JavaScript. You'd be better off giving your input an ID, and moving your JavaScript out to a <script>
block instead:
document.getElementById("yourInput").onclick = function() {
this.value = '';
this.style.color = '#000';
}
If you are trying to "Submit and Reset" the the "form" with one Button click, Try this!
Here I have used jQuery function, it can be done by simple JavaScript also...
<form id="form_data">
<input type="anything" name="anything" />
<input type="anything" name="anything" />
<!-- Save and Reset button -->
<button type="button" id="btn_submit">Save</button>
<button type="reset" id="btn_reset" style="display: none;"></button>
</form>
<script type="text/javascript">
$(function(){
$('#btn_submit').click(function(){
// Do what ever you want
$('#btn_reset').click(); // Clicking reset button
});
});
</script>
I just placed a short-cut to the XAMPP control panel in my startup folder. That works just fine on Window 7. Start -> All Programs -> Startup. There is also an option to start XAMPP control panel minimized, that is very useful for getting a clean unobstructed view of your desktop at start-up.**
I use these defines:
/** Use to init the clock */
#define TIMER_INIT \
LARGE_INTEGER frequency; \
LARGE_INTEGER t1,t2; \
double elapsedTime; \
QueryPerformanceFrequency(&frequency);
/** Use to start the performance timer */
#define TIMER_START QueryPerformanceCounter(&t1);
/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
#define TIMER_STOP \
QueryPerformanceCounter(&t2); \
elapsedTime=(float)(t2.QuadPart-t1.QuadPart)/frequency.QuadPart; \
std::wcout<<elapsedTime<<L" sec"<<endl;
Usage (brackets to prevent redefines):
TIMER_INIT
{
TIMER_START
Sleep(1000);
TIMER_STOP
}
{
TIMER_START
Sleep(1234);
TIMER_STOP
}
Output from usage example:
1.00003 sec
1.23407 sec
Alternative way to Deep_Copy that worked for me.
h1 = {:a => 'foo'}
h2 = Hash[h1.to_a]
This produced a deep_copy since h2 is formed using an array representation of h1 rather than h1's references.
In Eclipse:
You need to make the x-factor into an ordered
factor with the ordering you want, e.g
x <- data.frame("variable"=letters[1:5], "value"=rnorm(5)) ## example data
x <- x[with(x,order(-value)), ] ## Sorting
x$variable <- ordered(x$variable, levels=levels(x$variable)[unclass(x$variable)])
ggplot(x, aes(x=variable,y=value)) + geom_bar() +
scale_y_continuous("",formatter="percent") + coord_flip()
I don't know any better way to do the ordering operation. What I have there will only work if there are no duplicate levels for x$variable
.
I explain both why you would want to call a PowerShell script from a batch file and how to do it in my blog post here.
This is basically what you are looking for:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Users\SE\Desktop\ps.ps1'"
And if you need to run your PowerShell script as an admin, use this:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Users\SE\Desktop\ps.ps1""' -Verb RunAs}"
Rather than hard-coding the entire path to the PowerShell script though, I recommend placing the batch file and PowerShell script file in the same directory, as my blog post describes.
Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:
Delivery -> Package (One -> Many)
CREATE TABLE Delivery(
Id INT IDENTITY PRIMARY KEY,
NoteNumber NVARCHAR(255) NOT NULL
)
CREATE TABLE Package(
Id INT IDENTITY PRIMARY KEY,
Status INT NOT NULL DEFAULT 0,
Delivery_Id INT NOT NULL,
CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)
The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).
So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.
I got the same error and figured out that i wrote my script using Anaconda but pyinstaller
tries to pack script on pure python. So, modules not exist in pythons library folder cause this problem.
string utf8String = "Acción";
string propEncodeString = string.Empty;
byte[] utf8_Bytes = new byte[utf8String.Length];
for (int i = 0; i < utf8String.Length; ++i)
{
utf8_Bytes[i] = (byte)utf8String[i];
}
propEncodeString = Encoding.UTF8.GetString(utf8_Bytes, 0, utf8_Bytes.Length);
Output should look like
Acción
day’s displays day's
call DecodeFromUtf8();
private static void DecodeFromUtf8()
{
string utf8_String = "day’s";
byte[] bytes = Encoding.Default.GetBytes(utf8_String);
utf8_String = Encoding.UTF8.GetString(bytes);
}
I used this:
myElement = document.getElemenById("xyz");
Get_Offset_From_Start ( myElement ); // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement ); // returns positions from current scrolled view's TOP and LEFT
code:
function Get_Offset_From_Start (object, offset) {
offset = offset || {x : 0, y : 0};
offset.x += object.offsetLeft; offset.y += object.offsetTop;
if(object.offsetParent) {
offset = Get_Offset_From_Start (object.offsetParent, offset);
}
return offset;
}
function Get_Offset_From_CurrentView (myElement) {
if (!myElement) return;
var offset = Get_Offset_From_Start (myElement);
var scrolled = GetScrolled (myElement.parentNode);
var posX = offset.x - scrolled.x; var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
scrolled = scrolled || {x : 0, y : 0};
scrolled.x += object.scrollLeft; scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
return scrolled;
}
/*
// live monitoring
window.addEventListener('scroll', function (evt) {
var Positionsss = Get_Offset_From_CurrentView(myElement);
console.log(Positionsss);
});
*/
Maybe it's a coincidence that the column order you want happens to have column names in descending alphabetical order. Since that's the case you could just do:
df<-df[,order(colnames(df),decreasing=TRUE)]
That's what I use when I have large files with many columns.
Use Subscript Generating Functions.
http://www.postgresql.org/docs/current/static/functions-srf.html#FUNCTIONS-SRF-SUBSCRIPTS
For example:
SELECT
id
, elements[i] AS elem
, i AS nr
FROM
( SELECT
id
, elements
, generate_subscripts(elements, 1) AS i
FROM
( SELECT
id
, string_to_array(elements, ',') AS elements
FROM
myTable
) AS foo
) bar
;
More simply:
SELECT
id
, unnest(elements) AS elem
, generate_subscripts(elements, 1) AS nr
FROM
( SELECT
id
, string_to_array(elements, ',') AS elements
FROM
myTable
) AS foo
;
If you want to exit a program because of a fatal error, use:
sys.exit("Your program caused a fatal error. ... description ...")
and import sys
in the header.
You are checking it the array index contains a string "undefined"
, you should either use the typeof
operator:
typeof predQuery[preId] == 'undefined'
Or use the undefined
global property:
predQuery[preId] === undefined
The first way is safer, because the undefined
global property is writable, and it can be changed to any other value.
I created a gem to make URI encoding stuff cleaner to use in your code. It takes care of binary encoding for you.
Run gem install uri-handler
, then use:
require 'uri-handler'
str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a".to_uri
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"
It adds the URI conversion functionality into the String class. You can also pass it an argument with the optional encoding string you would like to use. By default it sets to encoding 'binary' if the straight UTF-8 encoding fails.
You need to have a rmiregistry
running before attempting to connect (register) a RMI service with it.
The LocateRegistry.createRegistry(2020)
method call creates and exports a registry on the specified port number.
See the documentation for LocateRegistry
The basic difference between Linear Regression and Logistic Regression is : Linear Regression is used to predict a continuous or numerical value but when we are looking for predicting a value that is categorical Logistic Regression come into picture.
Logistic Regression is used for binary classification.
I know this question has already been answered, but I decided to add my two cents. Here is code for a merge sort that only uses additional space in the merge operation (and that additional space is temporary space which will be destroyed when the stack is popped). In fact, you will see in this code that there is not usage of heap operations (no declaring new
anywhere).
Hope this helps.
void merge(int *arr, int size1, int size2) {
int temp[size1+size2];
int ptr1=0, ptr2=0;
int *arr1 = arr, *arr2 = arr+size1;
while (ptr1+ptr2 < size1+size2) {
if (ptr1 < size1 && arr1[ptr1] <= arr2[ptr2] || ptr1 < size1 && ptr2 >= size2)
temp[ptr1+ptr2] = arr1[ptr1++];
if (ptr2 < size2 && arr2[ptr2] < arr1[ptr1] || ptr2 < size2 && ptr1 >= size1)
temp[ptr1+ptr2] = arr2[ptr2++];
}
for (int i=0; i < size1+size2; i++)
arr[i] = temp[i];
}
void mergeSort(int *arr, int size) {
if (size == 1)
return;
int size1 = size/2, size2 = size-size1;
mergeSort(arr, size1);
mergeSort(arr+size1, size2);
merge(arr, size1, size2);
}
int main(int argc, char** argv) {
int num;
cout << "How many numbers do you want to sort: ";
cin >> num;
int a[num];
for (int i = 0; i < num; i++) {
cout << (i + 1) << ": ";
cin >> a[i];
}
// Start merge sort
mergeSort(a, num);
// Print the sorted array
cout << endl;
for (int i = 0; i < num; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
Ensure your Message class looks like below:
[Serializable, XmlRoot("Message")]
public class Message
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
This works for me fine:
string xml = File.ReadAllText("c:\\Message.xml");
var result = DeserializeFromXml<Message>(xml);
The name of the XML root element that is generated and recognized in an XML-document instance. The default is the name of the serialized class.
So it might be your class name is not Message
and this is why deserializer was not able find it using default behaviour.
This is because with {{}}
the angular compiler considers both the text node and it's parent as there is a possibility of merging of 2 {{}}
nodes. Hence there are additional linkers that add to the load time. Of course for a few such occurrences the difference is immaterial, however when you are using this inside a repeater of large number of items, it will cause an impact in slower runtime environment.
Try adding the following lines of code to the file httpd-vhosts.conf:
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "C:\wamp\www"
ServerName localhost
</VirtualHost>
To understand event handlers, you need to understand delegates. In C#, you can think of a delegate as a pointer (or a reference) to a method. This is useful because the pointer can be passed around as a value.
The central concept of a delegate is its signature, or shape. That is (1) the return type and (2) the input arguments. For example, if we create a delegate void MyDelegate(object sender, EventArgs e)
, it can only point to methods which return void
, and take an object
and EventArgs
. Kind of like a square hole and a square peg. So we say these methods have the same signature, or shape, as the delegate.
So knowing how to create a reference to a method, let's think about the purpose of events: we want to cause some code to be executed when something happens elsewhere in the system - or "handle the event". To do this, we create specific methods for the code we want to be executed. The glue between the event and the methods to be executed are the delegates. The event must internally store a "list" of pointers to the methods to call when the event is raised.* Of course, to be able to call a method, we need to know what arguments to pass to it! We use the delegate as the "contract" between the event and all the specific methods that will be called.
So the default EventHandler
(and many like it) represents a specific shape of method (again, void/object-EventArgs). When you declare an event, you are saying which shape of method (EventHandler) that event will invoke, by specifying a delegate:
//This delegate can be used to point to methods
//which return void and take a string.
public delegate void MyEventHandler(string foo);
//This event can cause any method which conforms
//to MyEventHandler to be called.
public event MyEventHandler SomethingHappened;
//Here is some code I want to be executed
//when SomethingHappened fires.
void HandleSomethingHappened(string foo)
{
//Do some stuff
}
//I am creating a delegate (pointer) to HandleSomethingHappened
//and adding it to SomethingHappened's list of "Event Handlers".
myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened);
//To raise the event within a method.
SomethingHappened("bar");
(*This is the key to events in .NET and peels away the "magic" - an event is really, under the covers, just a list of methods of the same "shape". The list is stored where the event lives. When the event is "raised", it's really just "go through this list of methods and call each one, using these values as the parameters". Assigning an event handler is just a prettier, easier way of adding your method to this list of methods to be called).
You can use Little Snitch to cut off network traffic to any individual process, including ones that run on the iOS simulator. That way you can keep your internet connection and disconnect your running app.
Just use \t
to space it.
Example:
System.out.println(monthlyInterest + "\t")
//as far as the two 0 in front of it just use a if else statement. ex:
x = x+1;
if (x < 10){
System.out.println("00" +x);
}
else if( x < 100){
System.out.println("0" +x);
}
else{
System.out.println(x);
}
There are other ways to do it, but this is the simplest.
TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)
Here is the FIX for 2.3 and below when using colours:
As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape
drawable containing the colour you want, and to use that instead of the colour.
I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).
Have you tried adding the semicolon to onclick="googleMapsQuery(422111);"
. I don't have enough of your code to test if the missing semicolon would cause the error, but ie is more picky about syntax.
The Popup class might be better than the Stage class, depending on what you want. Stage is either modal (you can't click on anything else in your app) or it vanishes if you click elsewhere in your app (because it's a separate window). Popup stays on top but is not modal.
See this Popup Window example.
df = df[[col for col in df.columns if not ('Unnamed' in col)]]
Finding max and min value the easy and manual way. This code is much faster than Math.max.apply
; I have tried up to 1000k numbers in array.
function findmax(array)
{
var max = 0;
var a = array.length;
for (counter=0;counter<a;counter++)
{
if (array[counter] > max)
{
max = array[counter];
}
}
return max;
}
function findmin(array)
{
var min = array[0];
var a = array.length;
for (counter=0;counter<a;counter++)
{
if (array[counter] < min)
{
min = array[counter];
}
}
return min;
}
I followed Telvin's suggestion and it worked on Windows 7:
Exact same thing, just omit the -c
option. Apache's docs on it here.
htpasswd /etc/apache2/.htpasswd newuser
Also, htpasswd
typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).
My guess is that you are using MySQL where the +
operator does addition, along with silent conversion of the values to numbers. If a value does not start with a digit, then the converted value is 0
.
So try this:
select concat(column1, column2)
Two ways to add a space:
select concat(column1, ' ', column2)
select concat_ws(' ', column1, column2)
JavaScript's forEach works a bit different from how one might be used to from other languages for each loops. If reading on the MDN, it says that a function is executed for each of the elements in the array, in ascending order. To continue to the next element, that is, run the next function, you can simply return the current function without having it do any computation.
Adding a return and it will go to the next run of the loop:
var myArr = [1,2,3,4];_x000D_
_x000D_
myArr.forEach(function(elem){_x000D_
if (elem === 3) {_x000D_
return;_x000D_
}_x000D_
_x000D_
console.log(elem);_x000D_
});
_x000D_
Output: 1, 2, 4
First, the default is not Arial. The default is Droid Sans.
Second, to change to a different built-in font, use android:typeface
in layout XML or setTypeface()
in Java.
Third, there is no Helvetica font in Android. The built-in choices are Droid Sans (sans
), Droid Sans Mono (monospace
), and Droid Serif (serif
). While you can bundle your own fonts with your application and use them via setTypeface()
, bear in mind that font files are big and, in some cases, require licensing agreements (e.g., Helvetica, a Linotype font).
EDIT
The Android design language relies on traditional typographic tools such as scale, space, rhythm, and alignment with an underlying grid. Successful deployment of these tools is essential to help users quickly understand a screen of information. To support such use of typography, Ice Cream Sandwich introduced a new type family named Roboto, created specifically for the requirements of UI and high-resolution screens.
The current TextView framework offers Roboto in thin, light, regular and bold weights, along with an italic style for each weight. The framework also offers the Roboto Condensed variant in regular and bold weights, along with an italic style for each weight.
After ICS, android includes Roboto fonts style, Read more Roboto
EDIT 2
With the advent of Support Library 26, Android now supports custom fonts by default. You can insert new fonts in res/fonts which can be set to TextViews individually either in XML or programmatically. The default font for the whole application can also be changed by defining it styles.xml The android developer documentation has a clear guide on this here
As Marineio said, you could use the onclick
attribute of the <li>
to change location.href
, through javascript:
<li onclick="location.href='http://example';"> ... </li>
Alternatively, you could remove any margins or padding in the <li>
, and add a large padding to the left side of the <a>
to avoid text going over the bullet.
jQuery has very limited array functions since JavaScript has most of them itself. But here are the ones they have: Utilities - jQuery API.
The error is because fName
is included in the SELECT
list, but is not included in a GROUP BY
clause and is not part of an aggregate function (Count()
, Min()
, Max()
, Sum()
, etc.)
You can fix that problem by including fName
in a GROUP BY
. But then you will face the same issue with surname
. So put both in the GROUP BY
:
SELECT
fName,
surname,
Count(*) AS num_rows
FROM
author
INNER JOIN book
ON author.aID = book.authorID;
GROUP BY
fName,
surname
Note I used Count(*)
where you wanted SUM(orders.quantity)
. However, orders
isn't included in the FROM
section of your query, so you must include it before you can Sum()
one of its fields.
If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.
Here's a simplified example based on of your problem:
if (test)
{//begin scope 1
int y = 1;
}//end scope 1
else
{//begin scope 2
int y = 2;//error, y is not in scope
}//end scope 2
int x = y;//error, y is not in scope
In the above version you have a variable called y
that is confined to scope 1, and another different variable called y
that is confined to scope 2. You then try to refer to a variable named y
after the end of the if
, and not such variable y
can be seen because no such variable exists in that scope.
You solve the problem by placing y
in the outermost scope which contains all references to it:
int y;
if (test)
{
y = 1;
}
else
{
y = 2;
}
int x = y;
I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.
This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.
This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.
public class HexColor
{
public static void main (String[] args)
{
JSlider sRed = new JSlider(0,255,1);
JSlider sGreen = new JSlider(0,255,1);
JSlider sBlue = new JSlider(0,255,1);
JLabel hexCode = new JLabel();
JPanel myPanel = new JPanel();
GridBagLayout layout = new GridBagLayout();
JFrame frame = new JFrame();
//set frame to organize components using GridBagLayout
frame.setLayout(layout);
//create gray filled rectangle
myPanel.paintComponent();
myPanel.setBackground(Color.GRAY);
//In practice this code is replicated and applied to sGreen and sBlue.
//For the sake of brevity I only show sRed in this post.
sRed.addChangeListener(
new ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e){
myPanel.setBackground(changeColor());
myPanel.repaint();
hexCode.setText(toHex());
}
}
);
//add each component to JFrame
frame.add(myPanel);
frame.add(sRed);
frame.add(sGreen);
frame.add(sBlue);
frame.add(hexCode);
} //end of main
//creates JPanel filled rectangle
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawRect(360, 300, 10, 10);
g.fillRect(360, 300, 10, 10);
}
//changes the display color in JPanel
private Color changeColor()
{
int r = sRed.getValue();
int b = sBlue.getValue();
int g = sGreen.getValue();
Color c;
return c = new Color(r,g,b);
}
//Displays hex representation of displayed color
private String toHex()
{
Integer r = sRed.getValue();
Integer g = sGreen.getValue();
Integer b = sBlue.getValue();
Color hC;
hC = new Color(r,g,b);
String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
while(hex.length() < 6){
hex = "0" + hex;
}
hex = "Hex Code: #" + hex;
return hex;
}
}
A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.
you can send your DateTime value into SQL as a String with its special format. this format is "yyyy-MM-dd HH:mm:ss"
Example: CurrentTime is a variable as datetime Type in SQL. And dt is a DateTime variable in .Net.
DateTime dt=DateTime.Now;
string sql = "insert into Users (CurrentTime) values (‘{0}’)";
sql = string.Format(sql, dt.ToString("yyyy-MM-dd HH:mm:ss") );
I had a similar issue when I tried to get a pull with a single quote ' in it's name.
I had to escape the pull request name:
git pull https://github.com/foo/bar namewithsingle"'"quote
Tools -> Options -> ReSharper (Tick "Show All setting" if ReSharper option not available ). Then you can do Suspend or Resume. Hope it helps (I tested only in VS2005)
You are close already. Just make sure to hide the checkbox and associate it with a label you style via input[checkbox] + label
Complete Code: http://gist.github.com/592332
JSFiddle: http://jsfiddle.net/4huzr/
Here is how I add parameters:
sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB
I am assuming when you write out DOB there are no quotes.
Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.
Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?
You can also use exists
, since sometimes it's faster than left join
. You'd have to benchmark them to figure out which one you want to use.
select
id
from
tableA a
where
not exists
(select 1 from tableB b where b.id = a.id)
To show that exists
can be more efficient than a left join
, here's the execution plans of these queries in SQL Server 2008:
left join
- total subtree cost: 1.09724:
exists
- total subtree cost: 1.07421:
If you have no time, submit the malware to cwsandbox:
http://jon.oberheide.org/blog/2008/01/15/detecting-and-evading-cwsandbox/
HTH
This is a generic Comparator
for any kind of Comparable
object, not just String
:
package util;
import java.util.Comparator;
/**
* The Default Comparator for classes implementing Comparable.
*
* @param <E> the type of the comparable objects.
*
* @author Michael Belivanakis (michael.gr)
*/
public final class DefaultComparator<E extends Comparable<E>> implements Comparator<E>
{
@SuppressWarnings( "rawtypes" )
private static final DefaultComparator<?> INSTANCE = new DefaultComparator();
/**
* Get an instance of DefaultComparator for any type of Comparable.
*
* @param <T> the type of Comparable of interest.
*
* @return an instance of DefaultComparator for comparing instances of the requested type.
*/
public static <T extends Comparable<T>> Comparator<T> getInstance()
{
@SuppressWarnings("unchecked")
Comparator<T> result = (Comparator<T>)INSTANCE;
return result;
}
private DefaultComparator()
{
}
@Override
public int compare( E o1, E o2 )
{
if( o1 == o2 )
return 0;
if( o1 == null )
return 1;
if( o2 == null )
return -1;
return o1.compareTo( o2 );
}
}
How to use with String
:
Comparator<String> stringComparator = DefaultComparator.getInstance();
Dependency management for Docker images is a real problem. I'm part of a team that built a tool, MicroBadger, to help with this by monitoring container images and inspecting metadata. One of its features is to let you set up a notification webhook that gets called when an image you're interested in (e.g. a base image) changes.
open your browser,check whether Tomcat homepage is visible by below command.
http://ipaddress:portnumber
also check this
Try this:
jQuery('#main').css('opacity', '0.6');
or
jQuery('#main').css({'filter':'alpha(opacity=60)', 'zoom':'1', 'opacity':'0.6'});
if you want to support IE7, IE8 and so on.
A ListView
is basically like a ListBox
(and inherits from it), but it also has a View
property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView
, but you can easily create your own.
Another difference is the default selection mode: it's Single
for a ListBox
, but Extended
for a ListView
Who ever also stumbles over this post.
I belive is the correct way:
<div *ngFor="let appointment of (_nextFourAppointments | async).availabilities;">
<div>{{ appointment }}</div>
</div>
To fix, I deleted the app from Simulator.
I also ran Clean first.
I do not think anything orientation-related triggered it. The biggest thing that changed before this symptom started is that a Swift framework started calling NSLog
on worker threads instead of main thread.
Based on other answers, there are basically two approaches: subclassing HashMap
or wrapping String
. The first one requires a little more work. In fact, if you want to do it correctly, you must override almost all methods (containsKey, entrySet, get, put, putAll and remove
).
Anyway, it has a problem. If you want to avoid future problems, you must specify a Locale
in String
case operations. So you would create new methods (get(String, Locale)
, ...). Everything is easier and clearer wrapping String:
public final class CaseInsensitiveString {
private final String s;
public CaseInsensitiveString(String s, Locale locale) {
this.s = s.toUpperCase(locale);
}
// equals, hashCode & toString, no need for memoizing hashCode
}
And well, about your worries on performance: premature optimization is the root of all evil :)
This will remove the last comma and any whitespace after it:
str = str.replace(/,\s*$/, "");
It uses a regular expression:
The /
mark the beginning and end of the regular expression
The ,
matches the comma
The \s
means whitespace characters (space, tab, etc) and the *
means 0 or more
The $
at the end signifies the end of the string
According to Java Persistence with Hibernate, cascade orphan delete is not available as a JPA annotation.
It is also not supported in JPA XML.
You can declare variables within a switch statement if you start a new block:
switch (thing)
{
case A:
{
int i = 0; // Completely legal
}
break;
}
The reason is to do with allocating (and reclaiming) space on the stack for storage of the local variable(s).
Use
find \( -path "./tmp" -o -path "./scripts" \) -prune -o -name "*_peaks.bed" -print
or
find \( -path "./tmp" -o -path "./scripts" \) -prune -false -o -name "*_peaks.bed"
or
find \( -path "./tmp" -path "./scripts" \) ! -prune -o -name "*_peaks.bed"
The order is important. It evaluates from left to right. Always begin with the path exclusion.
Do not use -not
(or !
) to exclude whole directory. Use -prune
.
As explained in the manual:
-prune The primary shall always evaluate as true; it
shall cause find not to descend the current
pathname if it is a directory. If the -depth
primary is specified, the -prune primary shall
have no effect.
and in the GNU find manual:
-path pattern
[...]
To ignore a whole
directory tree, use -prune rather than checking
every file in the tree.
Indeed, if you use -not -path "./pathname"
,
find will evaluate the expression for each node under "./pathname"
.
find expressions are just condition evaluation.
\( \)
- groups operation (you can use -path "./tmp" -prune -o -path "./scripts" -prune -o
, but it is more verbose).-path "./script" -prune
- if -path
returns true and is a directory, return true for that directory and do not descend into it.-path "./script" ! -prune
- it evaluates as (-path "./script") AND (! -prune)
. It revert the "always true" of prune to always false. It avoids printing "./script"
as a match.-path "./script" -prune -false
- since -prune
always returns true, you can follow it with -false
to do the same than !
.-o
- OR operator. If no operator is specified between two expressions, it defaults to AND operator.Hence, \( -path "./tmp" -o -path "./scripts" \) -prune -o -name "*_peaks.bed" -print
is expanded to:
[ (-path "./tmp" OR -path "./script") AND -prune ] OR ( -name "*_peaks.bed" AND print )
The print is important here because without it is expanded to:
{ [ (-path "./tmp" OR -path "./script" ) AND -prune ] OR (-name "*_peaks.bed" ) } AND print
-print
is added by find - that is why most of the time, you do not need to add it in you expression. And since -prune
returns true, it will print "./script" and "./tmp".
It is not necessary in the others because we switched -prune
to always return false.
Hint: You can use find -D opt expr 2>&1 1>/dev/null
to see how it is optimized and expanded,
find -D search expr 2>&1 1>/dev/null
to see which path is checked.
I'm presuming you're using Java 6 and that the ResultSet that you're using is a java.sql.ResultSet
.
The JavaDoc for the ResultSet.next() method states:
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.
So, if(rs.next(){ //do something }
means "If the result set still has results, move to the next result and do something".
As BalusC pointed out, you need to replace
ResultSet rs = stmt.executeQuery(sql);
with
ResultSet rs = stmt.executeQuery();
Because you've already set the SQL to use in the statement with your previous line
PreparedStatement stmt = conn.prepareStatement(sql);
If you weren't using the PreparedStatement
, then ResultSet rs = stmt.executeQuery(sql);
would work.
Let's face it: this one appears a lot when recording macros:
Range("X1").Select
Selection.Copy
Range("Y9).Select
Selection.Paste
While the only thing the person wants is:
Range("Y9").Value = Range("X1").Value
Therefore, instead of using copy-paste in VBA macros, I'd advise the following simple approach:
Destination_Range.Value = Source_Range.Value
If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:
class YourNonActivityClass{
// variable to hold context
private Context context;
//save the context recievied via constructor in a local variable
public YourNonActivityClass(Context context){
this.context=context;
}
}
You can create instance of this class from the activity as follows:
new YourNonActivityClass(this);
You can resolve it by configuring settings.xml in Eclipse.
Go to Window --> Preferences --> Maven --> User Settings --> select the actual path of settings.xml
You can use comments like in regular JavaScript:
[...] TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax.
[...] This document describes the syntactic grammar added by TypeScript [...]
Source: TypeScript Language Specification
The only two mentions of the word "comments" in the spec are:
[...] TypeScript also provides to JavaScript programmers a system of optional type annotations. These type annotations are like the JSDoc comments found in the Closure system, but in TypeScript they are integrated directly into the language syntax. This integration makes the code more readable and reduces the maintenance cost of synchronizing type annotations with their corresponding variables.
11.1.1 Source Files Dependencies
[...] A comment of the form
/// <reference path="..."/>
adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file.
It seems you (and/or your company) have a fundamental misunderstanding of what a family tree is supposed to be.
Let me clarify, I also work for a company that has (as one of its products) a family tree in its portfolio, and we have been struggling with similar problems.
The problem, in our case, and I assume your case as well, comes from the GEDCOM format that is extremely opinionated about what a family should be. However this format contains some severe misconceptions about what a family tree really looks like.
GEDCOM has many issues, such as incompatibility with same sex relations, incest, etc... Which in real life happens more often than you'd imagine (especially when going back in time to the 1700-1800).
We have modeled our family tree to what happens in the real world: Events (for example, births, weddings, engagement, unions, deaths, adoptions, etc.). We do not put any restrictions on these, except for logically impossible ones (for example, one can't be one's own parent, relations need two individuals, etc...)
The lack of validations gives us a more "real world", simpler and more flexible solution.
As for this specific case, I would suggest removing the assertions as they do not hold universally.
For displaying issues (that will arise) I would suggest drawing the same node as many times as needed, hinting at the duplication by lighting up all the copies on selecting one of them.
I am not an expert but this is what I noticed:
if your code is mycode.py for instance, and you type just 'import mycode', Python will execute it but it will not make all your variables available to the interpreter. I found that you should type actually 'from mycode import *' if you want to make all variables available to the interpreter.
The correct format for passing variables in a GET request is
?variable1=value1&variable2=value2&variable3=value3...
^ ---notice &--- ^
But essentially, you have the right idea.
Import connect
from react-redux
and use it to connect the component with the state connect(mapStates,mapDispatch)(component)
import React from "react";
import { connect } from "react-redux";
const MyComponent = (props) => {
return (
<div>
<h1>{props.title}</h1>
</div>
);
}
}
Finally you need to map the states to the props to access them with this.props
const mapStateToProps = state => {
return {
title: state.title
};
};
export default connect(mapStateToProps)(MyComponent);
Only the states that you map will be accessible via props
Check out this answer: https://stackoverflow.com/a/36214059/4040563
For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132
Use multiple text shadows:
text-shadow: 2px 0 0 #fff, -2px 0 0 #fff, 0 2px 0 #fff, 0 -2px 0 #fff, 1px 1px #fff, -1px -1px 0 #fff, 1px -1px 0 #fff, -1px 1px 0 #fff;
body {_x000D_
font-family: sans-serif;_x000D_
background: #222;_x000D_
color: darkred;_x000D_
}_x000D_
h1 {_x000D_
text-shadow: 2px 0 0 #fff, -2px 0 0 #fff, 0 2px 0 #fff, 0 -2px 0 #fff, 1px 1px #fff, -1px -1px 0 #fff, 1px -1px 0 #fff, -1px 1px 0 #fff;_x000D_
}
_x000D_
<h1>test</h1>
_x000D_
Alternatively, you could use text stroke, which only works in webkit:
-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: #fff;
body {_x000D_
font-family: sans-serif;_x000D_
background: #222;_x000D_
color: darkred;_x000D_
}_x000D_
h1 {_x000D_
-webkit-text-stroke-width: 2px;_x000D_
-webkit-text-stroke-color: #fff;_x000D_
}
_x000D_
<h1>test</h1>
_x000D_
Also read more as CSS-Tricks.
oops! just found myself: just add this line on any element you need
-webkit-appearance: none;
If you want a management option, try the envs npm package. It returns environment values if they are set. Otherwise, you can specify a default value that is stored in a global defaults object variable if it is not in your environment.
Using .env ("dot ee-en-vee") or environment files is good for many reasons. Individuals may manage their own configs. You can deploy different environments (dev, stage, prod) to cloud services with their own environment settings. And you can set sensible defaults.
Inside your .env
file each line is an entry, like this example:
NODE_ENV=development
API_URL=http://api.domain.com
TRANSLATION_API_URL=/translations/
GA_UA=987654321-0
NEW_RELIC_KEY=hi-mom
SOME_TOKEN=asdfasdfasdf
SOME_OTHER_TOKEN=zxcvzxcvzxcv
You should not include the .env
in your version control repository (add it to your .gitignore
file).
To get variables from the .env
file into your environment, you can use a bash script to do the equivalent of export NODE_ENV=development
right before you start your application.
#!/bin/bash
while read line; do export "$line";
done <source .env
Then this goes in your application javascript:
var envs = require('envs');
// If NODE_ENV is not set,
// then this application will assume it's prod by default.
app.set('environment', envs('NODE_ENV', 'production'));
// Usage examples:
app.set('ga_account', envs('GA_UA'));
app.set('nr_browser_key', envs('NEW_RELIC_BROWSER_KEY'));
app.set('other', envs('SOME_OTHER_TOKEN));
Look here:
It recommends using pscp.exe
from PuTTY, which can be found here: https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html
A direct transfer like FTP is not possible, because all commands during your session are send to the server.
In my case problem was in using PowerShell instead of CMD :)
You need to add a subview to the first window with the UITextEffectsWindow type. To the first, because custom keyboards add their UITextEffectsWindow, and if you add a subview to it this won't work correctly. Also, you cannot add a subview to the last window because the keyboard, for example, is also a window and you can`t present from the keyboard window. So the best solution I found is to add subview (or even push view controller) to the first window with UITextEffectsWindow type, this window covers accessory view, navbar - everything.
let myView = MyView()
myView.frame = UIScreen.main.bounds
guard let textEffectsWindow = NSClassFromString("UITextEffectsWindow") else { return }
let window = UIApplication.shared.windows.first { window in
window.isKind(of: textEffectsWindow)
}
window?.rootViewController?.view.addSubview(myView)
HTML
create div with id='dvFile'
;
create a button
;
onclick
of that button calling function add_more()
JavaScript
function add_more() {
var txt = "<br><input type=\"file\" name=\"item_file[]\">";
document.getElementById("dvFile").innerHTML += txt;
}
PHP
if(count($_FILES["item_file"]['name'])>0)
{
//check if any file uploaded
$GLOBALS['msg'] = ""; //initiate the global message
for($j=0; $j < count($_FILES["item_file"]['name']); $j++)
{ //loop the uploaded file array
$filen = $_FILES["item_file"]['name']["$j"]; //file name
$path = 'uploads/'.$filen; //generate the destination path
if(move_uploaded_file($_FILES["item_file"]['tmp_name']["$j"],$path))
{
//upload the file
$GLOBALS['msg'] .= "File# ".($j+1)." ($filen) uploaded successfully<br>";
//Success message
}
}
}
else {
$GLOBALS['msg'] = "No files found to upload"; //No file upload message
}
In this way you can add file/images, as many as required, and handle them through php script.
Use a regex to extract the "video id" after watch?v=
Store the video id in a variable, let's call this variable vid
Get the embed code from a random video, remove the video id from the embed code and replace it with the vid
you got.
I don't know how to deal with regex in php, but it shouldn't be too hard
Here's example code in python:
>>> ytlink = 'http://www.youtube.com/watch?v=7-dXUEbBz70'
>>> import re
>>> vid = re.findall( r'v\=([\-\w]+)', ytlink )[0]
>>> vid
'7-dXUEbBz70'
>>> print '''<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/%s&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/%s&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>''' % (vid,vid)
<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/7-dXUEbBz70&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
>>>
The regular expression v\=([\-\w]+)
captures a (sub)string of characters and dashes that comes after v=
Just to add to Matt's answer, which helped, here is a more fleshed-out example to show the use of a callback.
private static Primes primes = new Primes();
public static void main(String[] args) throws InterruptedException {
getPrimeAsync((p) ->
System.out.println("onPrimeListener; p=" + p));
System.out.println("Adios mi amigito");
}
public interface OnPrimeListener {
void onPrime(int prime);
}
public static void getPrimeAsync(OnPrimeListener listener) {
CompletableFuture.supplyAsync(primes::getNextPrime)
.thenApply((prime) -> {
System.out.println("getPrimeAsync(); prime=" + prime);
if (listener != null) {
listener.onPrime(prime);
}
return prime;
});
}
The output is:
getPrimeAsync(); prime=241
onPrimeListener; p=241
Adios mi amigito
You need to use Regular Expression For Website URL it is
var urlPattern = /(http|ftp|https)://[\w-]+(.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/
Use this Expression as in example
var regex = new RegExp(urlPattern ); var t = 'www.google.com';
var res = t.match(regex /g);
For You have to pass your web page as string to this javascript in variable t and get array
You can insert an image that looks like a button. Then attach a script to the image.
You can insert any image. The image can be edited in the spreadsheet
Image of a Button
Assign a function name to an image:
Not knowing your code, it's a bit hard to answer your question, but based on all the info here, I believe the issue is you're trying to use Collections.sort passing in an object defined as Collection, and sort doesn't support that.
First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?
If client was defined as a List, Map or Set, you wouldn't have this issue, as then you'd be able to directly use Collections.sort(client).
HTH
Also you can set option:
{plotOptions: {column: {colorByPoint: true}}}
for more information read docs
The following worked for me:
ol {
list-style-type: none;
counter-reset: item;
margin: 0;
padding: 0;
}
ol > li {
display: table;
counter-increment: item;
margin-bottom: 0.6em;
}
ol > li:before {
content: counters(item, ".") ") ";
display: table-cell;
padding-right: 0.6em;
}
li ol > li {
margin: 0;
}
li ol > li:before {
content: counters(item, ".") ") ";
}
Look at: http://jsfiddle.net/rLebz84u/2/
or this one http://jsfiddle.net/rLebz84u/3/ with more and justified text
My answer differs slightly to @FlavorScape in that I had a single (default export) function in the imported module, I did the following:
import * as functionToTest from 'whatever-lib';
const fooSpy = spyOn(functionToTest, 'default');
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
The two functions below I have found to be very useful when dealing with many variable testing cases.
def nz(value, none_value, strict=True):
''' This function is named after an old VBA function. It returns a default
value if the passed in value is None. If strict is False it will
treat an empty string as None as well.
example:
x = None
nz(x,"hello")
--> "hello"
nz(x,"")
--> ""
y = ""
nz(y,"hello")
--> ""
nz(y,"hello", False)
--> "hello" '''
if value is None and strict:
return_val = none_value
elif strict and value is not None:
return_val = value
elif not strict and not is_not_null(value):
return_val = none_value
else:
return_val = value
return return_val
def is_not_null(value):
''' test for None and empty string '''
return value is not None and len(str(value)) > 0
IMO OP does not actually want np.bitwise_and()
(aka &
) but actually wants np.logical_and()
because they are comparing logical values such as True
and False
- see this SO post on logical vs. bitwise to see the difference.
>>> x = array([5, 2, 3, 1, 4, 5])
>>> y = array(['f','o','o','b','a','r'])
>>> output = y[np.logical_and(x > 1, x < 5)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
dtype='|S1')
And equivalent way to do this is with np.all()
by setting the axis
argument appropriately.
>>> output = y[np.all([x > 1, x < 5], axis=0)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
dtype='|S1')
by the numbers:
>>> %timeit (a < b) & (b < c)
The slowest run took 32.97 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.15 µs per loop
>>> %timeit np.logical_and(a < b, b < c)
The slowest run took 32.59 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.17 µs per loop
>>> %timeit np.all([a < b, b < c], 0)
The slowest run took 67.47 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.06 µs per loop
so using np.all()
is slower, but &
and logical_and
are about the same.
If you use a type="button"
with an onclick
handler to login using ajax
, then the browser won't offer to save the password.
<form id="loginform">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="doLogin" type="button" value="Login" onclick="login(this.form);" />
</form>
Since this form does not have a submit button and has no action field, the browser will not offer to save the password.
However, if you change the button to type="submit"
and handle the submit, then the browser will offer to save the password.
<form id="loginform" action="login.php" onSubmit="return login(this);">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="doLogin" type="submit" value="Login" />
</form>
Using this method, the browser should offer to save the password.
Here's the Javascript used in both methods:
function login(f){
var username = f.username.value;
var password = f.password.value;
/* Make your validation and ajax magic here. */
return false; //or the form will post your data to login.php
}
int *p=(int *)0x1234 = 10; //0x1234 is the memory address and value 10 is assigned in that address
unsigned int *ptr=(unsigned int *)0x903jf = 20;//0x903j is memory address and value 20 is assigned
Basically in Embedded platform we are using directly addresses instead of names
I tried to create a mapped network driver via 'net use' with admin privilege but failed, it does not show. And if I add it through UI, it disappeared after reboot, now I made that through powershell. So, I think you can run powershell scripts from a .bat file, and the script is
New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Public"
add -persist
at the end, you will create a persisted mapped network drive
New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Scripts" -Persist
for more details, refer New-PSDrive - Microsoft Docs
Model = code for CRUD database operations.
Controller = responds to user actions, and passes the user requests for data retrieval or delete/update to the model, subject to the business rules specific to an organization. These business rules could be implemented in helper classes, or if they are not too complex, just directly in the controller actions. The controller finally asks the view to update itself so as to give feedback to the user in the form of a new display, or a message like 'updated, thanks', etc.,
View = UI that is generated based on a query on the model.
There are no hard and fast rules regarding where business rules should go. In some designs they go into model, whereas in others they are included with the controller. But I think it is better to keep them with the controller. Let the model worry only about database connectivity.
I can usually resolve this problem when a computer is under my control, but it's more of a nuisance when working with a grid. When a grid is not homogenous, not all libraries may be installed, and my experience has often been that a package wasn't installed because a dependency wasn't installed. To address this, I check the following:
.libPaths()
is a good check.ldd
results for R, to be sure about shared librariesHaving encountered this quite a bit, some of these steps become fairly routine. Although #7 might seem like a good starting point, these are listed in approximate order of the frequency that I use them.
Very similar to Marc, only difference I would make would be to spool to a parameter like so:
WHENEVER SQLERROR EXIT 1
SET LINES 32000
SET TERMOUT OFF ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET SERVEROUTPUT ON
spool &1
-- Code
spool off
exit
And then to call the SQLPLUS as
sqlplus -s username/password@sid @tmp.sql /tmp/output.txt
Okay. I finally found what actually works to answer the question that seems to be asked;
"When needing many modules and forms, how can I declare a variable to be public to all of them such that they each reference the same variable?"
Amazingly to me, I spent considerable time searching the web for that seemingly simple question, finding nothing but vagueness that left me still getting errors.
But thanks to Cody Gray's link to an example, I was able to discern a proper answer;
Situation; You have multiple Modules and/or Forms and want to reference a particular variable from each or all.
"A" way that works; On one module place the following code (wherein "DefineGlobals" is an arbitrarily chosen name);
Public Module DefineGlobals
Public Parts As Integer 'Assembled-particle count
Public FirstPrtAff As Long 'Addr into Link List
End Module
And then in each Module/Form in need of addressing that variable "Parts", place the following code (as an example of the "InitForm2" form);
Public Class InitForm2
Private Sub InitForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Parts = Parts + 3
End Sub
End Class
And perhaps another Form; Public Class FormX
Sub CreateAff()
Parts = 1000
End Sub
End Class
That type of coding seems to have worked on my VB2008 Express and seems to be all needed at the moment (void of any unknown files being loaded in the background) even though I have found no end to the "Oh btw..." surprise details. And I'm certain a greater degree of standardization would be preferred, but the first task is simply to get something working at all, with or without standards.
Nothing beats exact and well worded, explicit examples.
Thanks again, Cody
After reading all of this, I might just embed a hyperlink in the email body like this:
To reply to this email, click here <a href="mailto:...">[email protected]</a>
Try this (I've used Home controller and Index View):
return RedirectToAction("Index", "Home");
You can use now()
like:
Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();
Go via POSIXct
and you want to set a TZ
there -- here you see my (Chicago) default:
R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05"
R>
Edit: A few years later, we can now use the anytime package:
R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R>
Note how all this works without any format or origin arguments.
To be totally sure of rather the resultset is empty or not regardless of cursor position, I would do something like this:
public static boolean isMyResultSetEmpty(ResultSet rs) throws SQLException {
return (!rs.isBeforeFirst() && rs.getRow() == 0);
}
This function will return true if ResultSet is empty, false if not or throw an SQLException if that ResultSet is closed/uninitialized.
In some cases you can just use the flex-box
property order
.
Very simple:
.flex-item {
order: 2;
}
Prerequisites: You already have the service and published WSDL file, and you want to call your web service from C# client application.
There are 2 main way of doing this:
A) ASP.NET services, which is old way of doing SOA
B) WCF, as John suggested, which is the latest framework from MS and provides many protocols, including open and MS proprietary ones.
The simplest way is to generate proxy classes in C# application (this process is called adding service reference).
A dialog should appear shown in screenshot below. Enter the url of your wsdl file and hit Ok. Note that if you'll receive error message after hitting ok, try removing ?wsdl part from url.
I'm using http://www.dneonline.com/calculator.asmx?WSDL as an example
Expand Service References in Solution Explorer and double click CalculatorServiceReference
(or whatever you named the named the service in the previous step).
You should see generated proxy class name and namespace.
In my case, the namespace is SoapClient.CalculatorServiceReference
, the name of proxy class is CalculatorSoapClient
. As I said above, class names may vary in your case.
Go to your C# source code and add the following
using WindowsFormsApplication1.ServiceReference1
Now you can call the service this way.
Service1Client service = new Service1Client();
int year = service.getCurrentYear();
Hope this helps. If you encounter any problems, let us know.
I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process
You will need to subscribe to your observables:
this.CountryService.GetCountries()
.subscribe(countries => {
this.myGridOptions.rowData = countries as CountryData[]
})
And, in your html, wherever needed, you can pass the async
pipe to it.
If you only have degrees minutes seconds you can pass them on the url :
https://maps.google.com/maps?q=latDegrees latMinutes latSeconds longDegrees longMinutes longSeconds
substitute in %20 for the spaces