tl;dr: use OSX's native process launcher and manager, launchd
.
To do so, make a launchctl
daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.
.plist
file according to the instructions in the Apple Dev docs here or more detail below.~/Library/LaunchAgents
launchctl load [filename.plist]
)For more on launchd
, the wikipedia article is quite good and describes the system and its advantages over other older systems.
Here's the specific plist file to run a script at login.
Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.user.loginscript</string>
<key>ProgramArguments</key>
<array><string>/path/to/executable/script.sh</string></array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
Replace the <string>
after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh
to ensure it is for all users).
Save as ~/Library/LaunchAgents/com.user.loginscript.plist
Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist
and log out/in to test (or to test directly, run launchctl start com.user.loginscript
)
Tail /var/log/system.log
for error messages.
The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons
) are run on boot.
If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.
This is how did it works like a charm.
#loader {
position:fixed;
left:1px;
top:1px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('../images/ajax-loader100X100.gif') 50% 50% no-repeat rgb(249,249,249);
}
in _layout file inside body tag but outside the container div. Every time page loads it shows loading. Once page is loaded JS fadeout(second)
<div id="loader">
</div>
JS at the bottom of _layout file
<script type="text/javascript">
// With the element initially shown, we can hide it slowly:
$("#loader").fadeOut(1000);
</script>
You can use GroupBy
with anonymous type, and then get First
:
list.GroupBy(e => new {
empLoc = e.empLoc,
empPL = e.empPL,
empShift = e.empShift
})
.Select(g => g.First());
The next link will bring you to a great tutorial, that helped me a lot!
I nearly used everything in that article to create the SQLite database for my own C# Application.
Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.
After you added the reference, refer to the dll from your code using the following line on top of your class:
using System.Data.SQLite;
You can find the dll's here:
You can find the NuGet way here:
Up next is the create script. Creating a database file:
SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "insert into highscores (name, score) values ('Me', 9001)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
m_dbConnection.Close();
After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.
Example on how to use transactions:
using (TransactionScope tran = new TransactionScope())
{
//Insert create script here.
//Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
tran.Complete();
}
man ssh
gives me this options would could be useful.
-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).
So you could create an alias in your bash config with something like
alias ssh="ssh -i /path/to/private_key"
I haven't looked into a ssh configuration file, but like the -i
option this too could be aliased
-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.
You can search for the "environmental variable for you account". If you have added the Python in the path, it'll show as "path" in your environmental variable account.
but almost always you will find it in "C:\Users\%User_name%\AppData\Local\Programs\Python\Python_version"
the 'AppData' folder may be hidden, make it visible from the view section of toolbar.
Compact solution (provided you don't need other environment variables):
call('sqsub -np {} /homedir/anotherdir/executable'.format(var1).split(),
env=dict(LD_LIBRARY_PATH=my_path))
Using the env command line tool:
call('env LD_LIBRARY_PATH=my_path sqsub -np {} /homedir/anotherdir/executable'.format(var1).split())
The easiest way is to use the create
Manager method, which creates and saves the object in a single step.
for item in items:
MyModel.objects.create(name=item.name)
Suppose you want to create a vector x whose length is zero. Now let v be any vector.
> v<-c(4,7,8)
> v
[1] 4 7 8
> x<-v[0]
> length(x)
[1] 0
Styling widget instances
If you want to make one widget instance look different from another, you will need to specify additional attributes at the time when the widget object is instantiated and assigned to a form field (and perhaps add some rules to your CSS files).
https://docs.djangoproject.com/en/2.2/ref/forms/widgets/
To do this, you use the Widget.attrs argument when creating the widget:
class CommentForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
url = forms.URLField()
comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))
You can also modify a widget in the form definition:
class CommentForm(forms.Form):
name = forms.CharField()
url = forms.URLField()
comment = forms.CharField()
name.widget.attrs.update({'class': 'special'})
comment.widget.attrs.update(size='40')
Or if the field isn’t declared directly on the form (such as model form fields), you can use the Form.fields attribute:
class CommentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'special'})
self.fields['comment'].widget.attrs.update(size='40')
Django will then include the extra attributes in the rendered output:
>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr><th>Name:</th><td><input type="text" name="name" class="special" required></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" size="40" required></td></tr>
The environment variable PYTHONPATH
is actually only added to the list of locations Python searches for modules. You can print out the full list in the terminal like this:
python -c "import sys; print(sys.path)"
Or if want the output in the UNIX directory list style (separated by :
) you can do this:
python -c "import sys; print(':'.join(x for x in sys.path if x))"
Which will output something like this:
/usr/local/lib/python2.7/dist-packages/feedparser-5.1.3-py2.7.egg:/usr/local/lib/ python2.7/dist-packages/stripogram-1.5-py2.7.egg:/home/qiime/lib:/home/debian:/us r/lib/python2.7:/usr/lib/python2.7/plat-linux2:/usr/lib/python2.7/lib-tk:/usr/lib /python2.7/lib-old:/usr/lib/python2.7/lib- dynload:/usr/local/lib/python2.7/dist- packages:/usr/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages/PIL:/u sr/lib/python2.7/dist-packages/gst-0.10:/usr/lib/python2.7/dist-packages/gtk-2.0: /usr/lib/pymodules/python2.7
JSON.stringify
JSON.stringify(`{
a:"a"
}`)
would convert the above string to
"{ \n a:\"a\"\n }"
as mentioned here
This function adds double quotes at the beginning and end of the input string and escapes special JSON characters. In particular, a newline is replaced by the \n character, a tab is replaced by the \t character, a backslash is replaced by two backslashes \, and a backslash is placed before each quotation mark.
mysqli_error()
As in:
$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);
Trigger error is better than die because you can use it for development AND production, it's the permanent solution.
This is documentation from Moq site:
// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);
// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
sequenceName
is the name of the sequence in the DB. This is how you specify a sequence that already exists in the DB. If you go this route, you have to specify the allocationSize
which needs to be the same value that the DB sequence uses as its "auto increment".
Usage:
@GeneratedValue(generator="my_seq")
@SequenceGenerator(name="my_seq",sequenceName="MY_SEQ", allocationSize=1)
If you want, you can let it create a sequence for you. But to do this, you must use SchemaGeneration to have it created. To do this, use:
@GeneratedValue(strategy=GenerationType.SEQUENCE)
Also, you can use the auto-generation, which will use a table to generate the IDs. You must also use SchemaGeneration at some point when using this feature, so the generator table can be created. To do this, use:
@GeneratedValue(strategy=GenerationType.AUTO)
Cecil Curry has a great answer, however his answer only works for multiline regular expressions. Multiline regular expressions are more rarely used, but they are handy sometimes.
Here is an improvement upon his sed_inplace function that allows it to function with multiline regular expressions if asked to do so.
WARNING: In multiline mode, it will read the entire file in, and then perform the regular expression substitution, so you'll only want to use this mode on small-ish files - don't try to run this on gigabyte-sized files when running in multiline mode.
import re, shutil, tempfile
def sed_inplace(filename, pattern, repl, multiline = False):
'''
Perform the pure-Python equivalent of in-place `sed` substitution: e.g.,
`sed -i -e 's/'${pattern}'/'${repl}' "${filename}"`.
'''
re_flags = 0
if multiline:
re_flags = re.M
# For efficiency, precompile the passed regular expression.
pattern_compiled = re.compile(pattern, re_flags)
# For portability, NamedTemporaryFile() defaults to mode "w+b" (i.e., binary
# writing with updating). This is usually a good thing. In this case,
# however, binary writing imposes non-trivial encoding constraints trivially
# resolved by switching to text writing. Let's do that.
with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp_file:
with open(filename) as src_file:
if multiline:
content = src_file.read()
tmp_file.write(pattern_compiled.sub(repl, content))
else:
for line in src_file:
tmp_file.write(pattern_compiled.sub(repl, line))
# Overwrite the original file with the munged temporary file in a
# manner preserving file attributes (e.g., permissions).
shutil.copystat(filename, tmp_file.name)
shutil.move(tmp_file.name, filename)
from os.path import expanduser
sed_inplace('%s/.gitconfig' % expanduser("~"), r'^(\[user\]$\n[ \t]*name = ).*$(\n[ \t]*email = ).*', r'\1John Doe\[email protected]', multiline=True)
I see this is a fairly old question, but this looks like one of those times when something's been written without knowledge of a language feature. The collections
library exists to fulfill these purposes.
from collections import Counter
letter_counter = Counter()
for letter in 'The quick brown fox jumps over the lazy dog':
letter_counter[letter] += 1
>>> letter_counter
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 'T': 1, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})
In this example the spaces are being counted, obviously, but whether or not you want those filtered is up to you.
As for the dict.get(a_key, default_value)
, there have been several answers to this particular question -- this method returns the value of the key, or the default_value you supply. The first argument is the key you're looking for, the second argument is the default for when that key is not present.
The part you should be interested in is the /?
part, which should solve most other questions you have with the tool.
Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\>cmd /? Starts a new instance of the Windows XP command interpreter CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF] [[/S] [/C | /K] string] /C Carries out the command specified by string and then terminates /K Carries out the command specified by string but remains /S Modifies the treatment of string after /C or /K (see below) /Q Turns echo off /D Disable execution of AutoRun commands from registry (see below) /A Causes the output of internal commands to a pipe or file to be ANSI /U Causes the output of internal commands to a pipe or file to be Unicode /T:fg Sets the foreground/background colors (see COLOR /? for more info) /E:ON Enable command extensions (see below) /E:OFF Disable command extensions (see below) /F:ON Enable file and directory name completion characters (see below) /F:OFF Disable file and directory name completion characters (see below) /V:ON Enable delayed environment variable expansion using ! as the delimiter. For example, /V:ON would allow !var! to expand the variable var at execution time. The var syntax expands variables at input time, which is quite a different thing when inside of a FOR loop. /V:OFF Disable delayed environment expansion.
You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.
1) Give Alphas a Beta in the constructor. In class Alpha write:
public class Alpha {
private Beta beta;
public Alpha(Beta beta) {
this.beta = beta;
}
and call cAlpha = new Alpha(cBeta) from main()
2) give Alphas a mutator that gives them a beta. In class Alpha write:
public class Alpha {
private Beta beta;
public void setBeta (Beta newBeta) {
this.beta = beta;
}
and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or
3) have a beta as an argument to doSomethingAlpha. in class Alpha write:
public void DoSomethingAlpha(Beta cBeta) {
cbeta.DoSomethingBeta()
}
Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!
The best thing is to use @Value
annotation it will automatically assign value to your object private Environment en
.
This will reduce your code and it will be easy to filter your files.
I have tuned up previous code a little bit. First of all range.Changed hasn't work for me. After I changed range.Changed to richTextBox.TextChanged it turns out that TextChanged event handler can invoke SetDocumentXaml recursively, so I've provided protection against it. I also used XamlReader/XamlWriter instead of TextRange.
public class RichTextBoxHelper : DependencyObject
{
private static HashSet<Thread> _recursionProtection = new HashSet<Thread>();
public static string GetDocumentXaml(DependencyObject obj)
{
return (string)obj.GetValue(DocumentXamlProperty);
}
public static void SetDocumentXaml(DependencyObject obj, string value)
{
_recursionProtection.Add(Thread.CurrentThread);
obj.SetValue(DocumentXamlProperty, value);
_recursionProtection.Remove(Thread.CurrentThread);
}
public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(
"DocumentXaml",
typeof(string),
typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata(
"",
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
(obj, e) => {
if (_recursionProtection.Contains(Thread.CurrentThread))
return;
var richTextBox = (RichTextBox)obj;
// Parse the XAML to a document (or use XamlReader.Parse())
try
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(GetDocumentXaml(richTextBox)));
var doc = (FlowDocument)XamlReader.Load(stream);
// Set the document
richTextBox.Document = doc;
}
catch (Exception)
{
richTextBox.Document = new FlowDocument();
}
// When the document changes update the source
richTextBox.TextChanged += (obj2, e2) =>
{
RichTextBox richTextBox2 = obj2 as RichTextBox;
if (richTextBox2 != null)
{
SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));
}
};
}
)
);
}
You paste this inside :
<A HREF = "index.html">Click here</A>
"Requery" is indeed what you what you want to run, but you could do that in Form A's "On Got Focus" event. If you have code in your Form_Load, perhaps you can move it to Form_Got_Focus.
There really isn't any way of doing this as most of the useful information is discarded in the compilation process. However, you may want to take a look at this site to see if you can find some way of extracting something from the DLL.
RedirectToAction("actionName", "controllerName");
It has other overloads as well, please check up!
Also, If you are new and you are not using T4MVC, then I would recommend you to use it!
It gives you intellisence for actions,Controllers,views etc (no more magic strings)
Take a look here. Should be:
yourcommand &>filename
(redirects both stdout
and stderr
to filename).
Look carefully at your output:
5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
^ ^ ^
I've highlighted the "5", "9", "5" of your original string. The Python join()
method is a string method, and takes a list of things to join with the string. A simpler example might help explain:
>>> ",".join(["a", "b", "c"])
'a,b,c'
The "," is inserted between each element of the given list. In your case, your "list" is the string representation "595", which is treated as the list ["5", "9", "5"].
It appears that you're looking for +
instead:
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid
You can do a serialization-based deep clone using org.apache.commons.lang3.SerializationUtils.clone(T)
in Apache Commons Lang, but be careful—the performance is abysmal.
In general, it is best practice to write your own clone methods for each class of an object in the object graph needing cloning.
Inspired by samneric's answer using DataRowComparer.Default but needing something that would only compare a subset of columns within a DataTable, I made a DataTableComparer object where you can specify which columns to use in the comparison. Especially great if they have different columns/schemas.
DataRowComparer.Default works because it implements IEqualityComparer. Then I created an object where you can define which columns of the DataRow will be compared.
public class DataTableComparer : IEqualityComparer<DataRow>
{
private IEnumerable<String> g_TestColumns;
public void SetCompareColumns(IEnumerable<String> p_Columns)
{
g_TestColumns = p_Columns;
}
public bool Equals(DataRow x, DataRow y)
{
foreach (String sCol in g_TestColumns)
if (!x[sCol].Equals(y[sCol])) return false;
return true;
}
public int GetHashCode(DataRow obj)
{
StringBuilder hashBuff = new StringBuilder();
foreach (String sCol in g_TestColumns)
hashBuff.AppendLine(obj[sCol].ToString());
return hashBuff.ToString().GetHashCode();
}
}
You can use this by:
DataTableComparer comp = new DataTableComparer();
comp.SetCompareColumns(new String[] { "Name", "DoB" });
DataTable celebrities = SomeDataTableSource();
DataTable politicians = SomeDataTableSource2();
List<DataRow> celebrityPoliticians = celebrities.AsEnumerable().Intersect(politicians.AsEnumerable(), comp).ToList();
Just call this.finish() before startActivity(intent) like this-
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
this.finish();
startActivity(intent);
Similar to nesting the callbacks, this technique relies on closures. Yet, the chain stays flat - instead of passing only the latest result, some state object is passed for every step. These state objects accumulate the results of the previous actions, handing down all values that will be needed later again plus the result of the current task.
function getExample() {
return promiseA(…).then(function(resultA) {
// some processing
return promiseB(…).then(b => [resultA, b]); // function(b) { return [resultA, b] }
}).then(function([resultA, resultB]) {
// more processing
return // something using both resultA and resultB
});
}
Here, that little arrow b => [resultA, b]
is the function that closes over resultA
, and passes an array of both results to the next step. Which uses parameter destructuring syntax to break it up in single variables again.
Before destructuring became available with ES6, a nifty helper method called .spread()
was provided by many promise libraries (Q, Bluebird, when, …). It takes a function with multiple parameters - one for each array element - to be used as .spread(function(resultA, resultB) { …
.
Of course, that closure needed here can be further simplified by some helper functions, e.g.
function addTo(x) {
// imagine complex `arguments` fiddling or anything that helps usability
// but you get the idea with this simple one:
return res => [x, res];
}
…
return promiseB(…).then(addTo(resultA));
Alternatively, you can employ Promise.all
to produce the promise for the array:
function getExample() {
return promiseA(…).then(function(resultA) {
// some processing
return Promise.all([resultA, promiseB(…)]); // resultA will implicitly be wrapped
// as if passed to Promise.resolve()
}).then(function([resultA, resultB]) {
// more processing
return // something using both resultA and resultB
});
}
And you might not only use arrays, but arbitrarily complex objects. For example, with _.extend
or Object.assign
in a different helper function:
function augment(obj, name) {
return function (res) { var r = Object.assign({}, obj); r[name] = res; return r; };
}
function getExample() {
return promiseA(…).then(function(resultA) {
// some processing
return promiseB(…).then(augment({resultA}, "resultB"));
}).then(function(obj) {
// more processing
return // something using both obj.resultA and obj.resultB
});
}
While this pattern guarantees a flat chain and explicit state objects can improve clarity, it will become tedious for a long chain. Especially when you need the state only sporadically, you still have to pass it through every step. With this fixed interface, the single callbacks in the chain are rather tightly coupled and inflexible to change. It makes factoring out single steps harder, and callbacks cannot be supplied directly from other modules - they always need to be wrapped in boilerplate code that cares about the state. Abstract helper functions like the above can ease the pain a bit, but it will always be present.
If all the above methods are not working then change implementation 'com.google.firebase:firebase-core:12.0.0'
to implementation 'com.google.firebase:firebase-core:10.0.0'
in your app level build.gradle file.
This would surely work.
If this issue occurs, kindly check web.config in below section
Below section gives the version of particular dll used
after checking this section in web.config, open solution explorer and select reference from the project tree as shown . Solution Explorer->Reference
After expanding reference, find the dll which caused the error. Right click on the dll reference and check for version like shown in the image above.
If both config dll version and referenced dll is different you would get this exception. Make sure both are of same version which would help.
if num % 2 == 0:
pass # Even
else:
pass # Odd
The %
sign is like division only it checks for the remainder, so if the number divided by 2
has a remainder of 0
it's even otherwise odd.
Or reverse them for a little speed improvement, since any number above 0 is also considered "True" you can skip needing to do any equality check:
if num % 2:
pass # Odd
else:
pass # Even
Here is my solution
public class GenericClass<T>
{
private Class<T> realType;
public GenericClass() {
findTypeArguments(getClass());
}
private void findTypeArguments(Type t) {
if (t instanceof ParameterizedType) {
Type[] typeArgs = ((ParameterizedType) t).getActualTypeArguments();
realType = (Class<T>) typeArgs[0];
} else {
Class c = (Class) t;
findTypeArguments(c.getGenericSuperclass());
}
}
public Type getMyType()
{
// How do I return the type of T? (your question)
return realType;
}
}
No matter how many level does your class hierarchy has, this solution still works, for example:
public class FirstLevelChild<T> extends GenericClass<T> {
}
public class SecondLevelChild extends FirstLevelChild<String> {
}
In this case, getMyType() = java.lang.String
Look at the article I wrote on CodeProject, one that answers the question precisely:
There is way too much for re-posting it all here, and even less point since that article has an attachment with the key/required source file.
At the moment you're calling ToUniversalTime()
- just get rid of that:
private long ConvertToTimestamp(DateTime value)
{
long epoch = (value.Ticks - 621355968000000000) / 10000000;
return epoch;
}
Alternatively, and rather more readably IMO:
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
...
private static long ConvertToTimestamp(DateTime value)
{
TimeSpan elapsedTime = value - Epoch;
return (long) elapsedTime.TotalSeconds;
}
EDIT: As noted in the comments, the Kind
of the DateTime
you pass in isn't taken into account when you perform subtraction. You should really pass in a value with a Kind
of Utc
for this to work. Unfortunately, DateTime
is a bit broken in this respect - see my blog post (a rant about DateTime
) for more details.
You might want to use my Noda Time date/time API instead which makes everything rather clearer, IMO.
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
Also there is
aRange.EntireColumn.AutoFit();
See What is the difference between Range.Columns and Range.EntireColumn.
:noh
(short for nohighlight) will do the trick.
Actually, upon further reading on the file_get_contents()
function:
// Create a stream
$opts = [
"http" => [
"method" => "GET",
"header" => "Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
]
];
// DOCS: https://www.php.net/manual/en/function.stream-context-create.php
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
// DOCS: https://www.php.net/manual/en/function.file-get-contents.php
$file = file_get_contents('http://www.example.com/', false, $context);
You may be able to follow this pattern to achieve what you are seeking to, I haven't personally tested this though. (and if it doesn't work, feel free to check out my other answer)
In Access 2007 - 2010, go to Database Tools and click Compact and Repair Database, and it will automatically reset the ID.
Try:
$("#"+styleTarget).css({ 'font-size': $(this).val() });
By putting the value in quotes, it becomes a string, and "+$(this).val()+"px
is definitely not close to a font value. There are a couple of ways of setting the style properties of an element:
Using a map:
$("#elem").css({
fontSize: 20
});
Using key and value parameters:
All of these are valid.
$("#elem").css("fontSize", 20);
$("#elem").css("fontSize", "20px");
$("#elem").css("font-size", "20");
$("#elem").css("font-size", "20px");
You can replace "fontSize"
with "font-size"
but it will have to be quoted then.
The answer of Mintir4 is fine, I would also do the following to load the file.
FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";
while ((s = r.readLine()) != null) {
txt += s;
}
r.close();
If you need by several params:
$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
->whereNotIn('id', $not_ids)
->where('status', 1)
->get();
Try using cURL instead. cURL implements a cookie jar, while file_get_contents doesn't.
You can see if the file is locked by trying to read or lock it yourself first.
var myString = 'sample String'; var length = myString.length ;
first you need to defined a keypressed handler or some kind of a event trigger to listen , btw , getting the length is really simple like mentioned above
Adding @WebAppConfiguration
(org.springframework.test.context.web.WebAppConfiguration
) annotation to your DemoApplicationTests class will work.
The key is to keep the declarations of the variable in the header file and source file the same.
I use this trick
------sample.c------
#define sample_c
#include sample.h
(rest of sample .c)
------sample.h------
#ifdef sample_c
#define EXTERN
#else
#define EXTERN extern
#endif
EXTERN int x;
Sample.c is only compiled once and it defines the variables. Any file that includes sample.h is only given the "extern" of the variable; it does allocate space for that variable.
When you change the type of x, it will change for everybody. You won't need to remember to change it in the source file and the header file.
If you had MyPhoneExplorer installed and connected (not sure this is a must, happened to be my setup already), you could use it to control the screen with your computer mouse. It connects via ADB, for which your normal USB cable is enough.
Another solution I found that even worked without a reboot is updating tables in settings.db and locksettings.db I had to switch to root to open the settings.db though:
adb shell
su
sqlite3 /data/data/com.android.providers.settings/databases/settings.db
update secure set value=1 where name='lockscreen.disabled';
.quit
sqlite3 /data/system/locksettings.db
update locksettings set value=0 where name='lock_pattern_autlock';
update locksettings set value=1 where name='lockscreen.disabled';
.quit
To turn off line numbering, again follow the preceding instructions, except this time enter the following line at the : prompt:
set nonumber
I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.
One can write his own customised ufunc
in C, which surely is more efficient, or by invoking np.frompyfunc
, which is built-in factory method. After testing, this is more efficient than np.vectorize
:
f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)
%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms
I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post
As much as people like to say "order doesn't matter its just convention" this breaks down when entering cross domain interfaces, IE transfer from C ordering to Fortran ordering or some other ordering scheme. There, precisely how your data is layed out and how shape is represented in numpy is very important.
By default, numpy uses C ordering, which means contiguous elements in memory are the elements stored in rows. You can also do FORTRAN ordering ("F"), this instead orders elements based on columns, indexing contiguous elements.
Numpy's shape further has its own order in which it displays the shape. In numpy, shape is largest stride first, ie, in a 3d vector, it would be the least contiguous dimension, Z, or pages, 3rd dim etc... So when executing:
np.zeros((2,3,4)).shape
you will get
(2,3,4)
which is actually (frames, rows, columns)
. doing np.zeros((2,2,3,4)).shape
instead would mean (metaframs, frames, rows, columns)
. This makes more sense when you think of creating multidimensional arrays in C like langauges. For C++, creating a non contiguously defined 4D array results in an array [ of arrays [ of arrays [ of elements ]]]
. This forces you to de reference the first array that holds all the other arrays (4th dimension) then the same all the way down (3rd, 2nd, 1st) resulting in syntax like:
double element = array4d[w][z][y][x]
;
In fortran, this indexed ordering is reversed (x is instead first array4d[x][y][z][w]
), most contiguous to least contiguous and in matlab, it gets all weird.
Matlab tried to preserve both mathematical default ordering (row, column) but also use column major internally for libraries, and not follow C convention of dimensional ordering. In matlab, you order this way:
double element = array4d[y][x][z][w]
;
which deifies all convention and creates weird situations where you are sometimes indexing as if row ordered and sometimes column ordered (such as with matrix creation).
In reality, Matlab is the unintuitive one, not Numpy.
There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.
There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)
The article is definitely worth a read.
I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause
:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.
From the documentation get_or_create:
# get_or_create() a person with similar first names.
p, created = Person.objects.get_or_create(
first_name='John',
last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)},
)
# get_or_create() didn't have to create an object.
>>> created
False
Explanation:
Fields to be evaluated for similarity, have to be mentioned outside defaults
. Rest of the fields have to be included in defaults
. In case CREATE event occurs, all the fields are taken into consideration.
It looks like you need to be returning into a tuple, instead of a single variable, do like this:
customer.source,created = Source.objects.get_or_create(name="Website")
Use -d
(full list of file tests)
if (-d "cgi-bin") {
# directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
# cgi-bin exists but is not a directory
}
else {
# nothing called cgi-bin exists
}
As a note, -e
doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f
.
Given this route
app.get('/hi/:param1', function(req,res){} );
and given this URL
http://www.google.com/hi/there?qs1=you&qs2=tube
You will have:
req.query
{
qs1: 'you',
qs2: 'tube'
}
req.params
{
param1: 'there'
}
Make a surrounding div-tag, and set for it display: grid
in its style attribute.
<div style='display: grid;
text-align: center;
background-color: antiquewhite'
>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
</div>
The text-align property is set only to show, that the text in the regular table cells are affected by it, even though it is set on the surrounding div. The same with the background-color but it is hard to say which element actually holds the background-color.
I found the below stuff in ffmpeg Docs. Hope this helps! :)
Reference: http://ffmpeg.org/ffmpeg.html#toc-Generic-options
‘-report’ Dump full command line and console output to a file named program-YYYYMMDD-HHMMSS.log in the current directory. This file can be useful for bug reports. It also implies -loglevel verbose.
Note: setting the environment variable FFREPORT to any value has the same effect.
If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.
at the command line
:\> cd <path you wish your server to reside>
:\> npm install connect
Then in a file (I named) Server.js
var connect = require('connect'),
http = require('http');
connect()
.use(connect.static('<pathyouwishtoserve>'))
.use(connect.directory('<pathyouwishtoserve>'))
.listen(8080);
Finally
:\>node Server.js
Caveats:
If you don't want to display the directory contents, exclude the .use(connect.directory line.
So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.
If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.
I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.
Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.
Commands I used (for better or worse):
Create a new file called node
:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$@"
sudo chmod -x /usr/local/bin/node
That ought to make
node Server.js
work just fine
You can get the full download here: http://download.microsoft.com/download/8/3/a/83aad8f9-38ba-4503-b3cd-ba28c360c27b/ENU/vcsetup.exe
I don't think there's anything wrong with either solutions you proposed in your question.
In my own code, I would implement it like this though:
(x for x in seq if predicate(x)).next()
The syntax with ()
creates a generator, which is more efficient than generating all the list at once with []
.
Any fields you don't want serialized in general you should use the "transient" modifier, and this also applies to json serializers (at least it does to a few that I have used, including gson).
If you don't want name to show up in the serialized json give it a transient keyword, eg:
private transient String name;
An example using jQuery is below. Hope this helps
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
url: "https://example.com/api/",
type: "POST",
data: { apiKey: "23462", method: "example", ip: "208.74.35.5" },
dataType: "json",
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
</head>
<body>
<h1>My jQuery JSON Web Page</h1>
<div id="resultDivContainer"></div>
<button type="button" onclick="JSONTest()">JSON</button>
</body>
</html>
Firebug debug process
Till yesterday I was able to connect to phpMyAdmin, but today I started getting this error:
2002-no-connection-could-be-made-because-the-target-machine-actively-refused
None of the answers here really helped me fix the problem, what helped me is shared below:
I looked at the mysql logs.[C:\wamp\logs\mysql.log]
It said
2015-09-18 01:16:30 5920 [Note] Plugin 'FEDERATED' is disabled.
2015-09-18 01:16:30 5920 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-09-18 01:16:30 5920 [Note] InnoDB: The InnoDB memory heap is disabled
2015-09-18 01:16:30 5920 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2015-09-18 01:16:30 5920 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-09-18 01:16:30 5920 [Note] InnoDB: Not using CPU crc32 instructions
2015-09-18 01:16:30 5920 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-09-18 01:16:30 5920 [Note] InnoDB: Completed initialization of buffer pool
2015-09-18 01:16:30 5920 [Note] InnoDB: Highest supported file format is Barracuda.
2015-09-18 01:16:30 5920 [Note] InnoDB: The log sequence numbers 1765410 and 1765410 in ibdata files do not match the log sequence number 2058233 in the ib_logfiles!
2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!
2015-09-18 01:16:30 5920 [Note] InnoDB: Starting crash recovery.
2015-09-18 01:16:30 5920 [Note] InnoDB: Reading tablespace information from the .ibd files...
2015-09-18 01:16:30 5920 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous tablespace harley/login_confirm uses space ID: 6 at filepath: .\harley\login_confirm.ibd. Cannot open tablespace testdb/testtable which uses space ID: 6 at filepath: .\testdb\testtable.ibd
InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.
I got the clue that this guy is creating a problem - InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd
and this line 2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!
hmmm, For me the testdb was just a test-db! hence I decided to delete this file inside C:\wamp\bin\mysql\mysql5.6.17\data\testdb
and restarted all services, and went to phpMyAdmin, and this time no issues, phpMyAdmin opened :)
Yes, you may put comments in there. They however must start at the beginning of a line.
cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files
The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]
The comment character is #
, example:
# no .a files
*.a
There are several ways, but first you need to understand why object cleanup is important, and hence the reason std::exit
is marginalized among C++ programmers.
C++ makes use of a idiom called RAII, which in simple terms means objects should perform initialization in the constructor and cleanup in the destructor. For instance the std::ofstream
class [may] open the file during the constructor, then the user performs output operations on it, and finally at the end of its life cycle, usually determined by its scope, the destructor is called that essentially closes the file and flushes any written content into the disk.
What happens if you don't get to the destructor to flush and close the file? Who knows! But possibly it won't write all the data it was supposed to write into the file.
For instance consider this code
#include <fstream>
#include <exception>
#include <memory>
void inner_mad()
{
throw std::exception();
}
void mad()
{
auto ptr = std::make_unique<int>();
inner_mad();
}
int main()
{
std::ofstream os("file.txt");
os << "Content!!!";
int possibility = /* either 1, 2, 3 or 4 */;
if(possibility == 1)
return 0;
else if(possibility == 2)
throw std::exception();
else if(possibility == 3)
mad();
else if(possibility == 4)
exit(0);
}
What happens in each possibility is:
os
thus calling its destructor and doing proper cleanup by closing and flushing the file to disk.inner_mad
, the unwinder will go though the stack of mad
and main
to perform proper cleanup, all the objects are going to be destructed properly, including ptr
and os
.exit
is a C function and it's not aware nor compatible with the C++ idioms. It does not perform cleanup on your objects, including os
in the very same scope. So your file won't be closed properly and for this reason the content might never get written into it!return 0
and thus having the same effect as possibility 1, i.e. proper cleanup.But don't be so certain about what I just told you (mainly possibilities 2 and 3); continue reading and we'll find out how to perform a proper exception based cleanup.
You should do this whenever possible; always prefer to return from your program by returning a proper exit status from main.
The caller of your program, and possibly the operating system, might want to know whether what your program was supposed to do was done successfully or not. For this same reason you should return either zero or EXIT_SUCCESS
to signal that the program successfully terminated and EXIT_FAILURE
to signal the program terminated unsuccessfully, any other form of return value is implementation-defined (§18.5/8).
However you may be very deep in the call stack, and returning all of it may be painful...
Throwing a exception will perform proper object cleanup using stack unwinding, by calling the destructor of every object in any previous scope.
But here's the catch! It's implementation-defined whether stack unwinding is performed when a thrown exception is not handled (by the catch(...) clause) or even if you have a noexcept
function in the middle of the call stack. This is stated in §15.5.1 [except.terminate]:
In some situations exception handling must be abandoned for less subtle error handling techniques. [Note: These situations are:
[...]
— when the exception handling mechanism cannot find a handler for a thrown exception (15.3), or when the search for a handler (15.3) encounters the outermost block of a function with a
noexcept
-specification that does not allow the exception (15.4), or [...][...]
In such cases, std::terminate() is called (18.8.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called [...]
So we have to catch it!
Since uncaught exceptions may not perform stack unwinding (and consequently won't perform proper cleanup), we should catch the exception in main and then return a exit status (EXIT_SUCCESS
or EXIT_FAILURE
).
So a possibly good setup would be:
int main()
{
/* ... */
try
{
// Insert code that will return by throwing a exception.
}
catch(const std::exception&) // Consider using a custom exception type for intentional
{ // throws. A good idea might be a `return_exception`.
return EXIT_FAILURE;
}
/* ... */
}
This does not perform any sort of stack unwinding, and no alive object on the stack will call its respective destructor to perform cleanup.
This is enforced in §3.6.1/4 [basic.start.init]:
Terminating the program without leaving the current block (e.g., by calling the function std::exit(int) (18.5)) does not destroy any objects with automatic storage duration (12.4). If std::exit is called to end a program during the destruction of an object with static or thread storage duration, the program has undefined behavior.
Think about it now, why would you do such a thing? How many objects have you painfully damaged?
There are other ways to terminate a program (other than crashing), but they aren't recommended. Just for the sake of clarification they are going to be presented here. Notice how normal program termination does not mean stack unwinding but an okay state for the operating system.
std::_Exit
causes a normal program termination, and that's it.std::quick_exit
causes a normal program termination and calls std::at_quick_exit
handlers, no other cleanup is performed.std::exit
causes a normal program termination and then calls std::atexit
handlers. Other sorts of cleanups are performed such as calling static objects destructors.std::abort
causes an abnormal program termination, no cleanup is performed. This should be called if the program terminated in a really, really unexpected way. It'll do nothing but signal the OS about the abnormal termination. Some systems perform a core dump in this case.std::terminate
calls the std::terminate_handler
which calls std::abort
by default.You can use COPY. You need to specify the directory explicitly. It won't be created by itself
COPY go /usr/local/go
Reference: Docker CP reference
When you entered in mongo shell using "mongo" command , that time only you will notice
MongoDB shell version v3.4.0-rc2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0-rc2
also you can try command,in mongo shell ,
db.version()
This worked out for me. I made a custom php code to force redirect it to https. Just include this code on the header.php
<?php
if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$protocol = 'https://';
}
else {
$protocol = 'http://';
}
$notssl = 'http://';
if($protocol==$notssl){
$url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";?>
<script>
window.location.href ='<?php echo $url?>';
</script>
<?php } ?>
You can fix this problem by adding "$(ProjectDir)" (or wherever the stdafx.h is) to list of directories under Project->Properties->Configuration Properties->C/C++->General->Additional Include Directories.
I was trying to create a borderless window with WindowStyle="None"
but when I tested it, seems that appears a white bar in the top, after some research it appears to be a "Resize border", here is an image (I remarked in yellow):
After some research over the internet, and lots of difficult non xaml solutions, all the solutions that I found were code behind in C# and lots of code lines, I found indirectly the solution here: Maximum custom window loses drop shadow effect
<WindowChrome.WindowChrome>
<WindowChrome
CaptionHeight="0"
ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>
Note : You need to use .NET 4.5 framework, or if you are using an older version use WPFShell, just reference the shell and use Shell:WindowChrome.WindowChrome
instead.
I used the WindowChrome
property of Window, if you use this that white "resize border" disappears, but you need to define some properties to work correctly.
CaptionHeight: This is the height of the caption area (headerbar) that allows for the Aero snap, double clicking behaviour as a normal title bar does. Set this to 0 (zero) to make the buttons work.
ResizeBorderThickness: This is thickness at the edge of the window which is where you can resize the window. I put to 5 because i like that number, and because if you put zero its difficult to resize the window.
After using this short code the result is this:
And now, the white border disappeared without using ResizeMode="NoResize"
and AllowsTransparency="True"
, also it shows a shadow in the window.
Later I will explain how to make to work the buttons (I didn't used images for the buttons) easily with simple and short code, Im new and i think that I can post to codeproject, because here I didn't find the place to post the tutorial.
Maybe there is another solution (I know that there are hard and difficult solutions for noobs like me) but this works for my personal projects.
Here is the complete code
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Concursos"
mc:Ignorable="d"
Title="Concuros" Height="350" Width="525"
WindowStyle="None"
WindowState="Normal"
ResizeMode="CanResize"
>
<WindowChrome.WindowChrome>
<WindowChrome
CaptionHeight="0"
ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>
<Grid>
<Rectangle Fill="#D53736" HorizontalAlignment="Stretch" Height="35" VerticalAlignment="Top" PreviewMouseDown="Rectangle_PreviewMouseDown" />
<Button x:Name="Btnclose" Content="r" HorizontalAlignment="Right" VerticalAlignment="Top" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
<Button x:Name="Btnmax" Content="2" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,35,0" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
<Button x:Name="Btnmin" Content="0" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,70,0" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
</Grid>
Thank you!
As you are not trying to move the files around in the tree, you should be able to just checkout the directory:
git checkout master -- dirname
Only a few items => INSERTION SORT
Items are mostly sorted already => INSERTION SORT
Concerned about worst-case scenarios => HEAP SORT
Interested in a good average-case result => QUICKSORT
Items are drawn from a dense universe => BUCKET SORT
Desire to write as little code as possible => INSERTION SORT
setTimeout('$("#someDivId").hide()',1500);
I'm not a WCF expert but I'm wondering if you aren't running into a DDOS protection on IIS. I know from experience that if you run a bunch of simultaneous connections from a single client to a server at some point the server stops responding to the calls as it suspects a DDOS attack. It will also hold the connections open until they time-out in order to slow the client down in his attacks.
Multiple connection coming from different machines/IP's should not be a problem however.
There's more info in this MSDN post:
http://msdn.microsoft.com/en-us/library/bb463275.aspx
Check out the MaxConcurrentSession sproperty.
This is the progress bar I have used.
<ProgressBar
android:padding="@dimen/dimen_5"
android:layout_below="@+id/txt_chklist_progress"
android:id="@+id/pb_media_progress"
style="@style/MyProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:progress="70"
android:scaleY="5"
android:max="100"
android:progressBackgroundTint="@color/white"
android:progressTint="@color/green_above_avg" />
And this is my style tag
<style name="MyProgressBar" parent="@style/Widget.AppCompat.ProgressBar.Horizontal">
<item name="android:progressBackgroundTint">@color/white</item>
<item name="android:progressTint">@color/green_above_avg</item>
</style>
Try changing
git checkout -- a
to
git checkout -- `git ls-files -m -- a`
Since version 1.7.0, Git's ls-files
honors the skip-worktree flag.
Running your test script (with some minor tweaks changing git commit
... to git commit -q
and git status
to git status --short
) outputs:
Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
D a/a/aa
D a/b/ab
M b/a/ba
After checkout:
M b/a/ba
a/a/aa
a/c/ac
a/b/ab
b/a/ba
Running your test script with the proposed checkout
change outputs:
Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
D a/a/aa
D a/b/ab
M b/a/ba
After checkout:
M b/a/ba
a/a/aa
a/b/ab
b/a/ba
If you are using phpmyadmin then just go to the table structure
e.g.
Space usage
Data 1.5 MiB
Index 0 B
Total 1.5 Mi
I found the xmessage command, which is sort of good enough.
When you have changes on your working copy, from command line do:
git stash
This will stash your changes and clear your status report
git pull
This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge
git stash pop
This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.
if you need to see what is in your stash
git stash list
Perhaps the two most efficient ways to find the last index:
def rindex(lst, value):
lst.reverse()
i = lst.index(value)
lst.reverse()
return len(lst) - i - 1
def rindex(lst, value):
return len(lst) - operator.indexOf(reversed(lst), value) - 1
Both take only O(1) extra space and the two in-place reversals of the first solution are much faster than creating a reverse copy. Let's compare it with the other solutions posted previously:
def rindex(lst, value):
return len(lst) - lst[::-1].index(value) - 1
def rindex(lst, value):
return len(lst) - next(i for i, val in enumerate(reversed(lst)) if val == value) - 1
Benchmark results, my solutions are the red and green ones:
This is for searching a number in a list of a million numbers. The x-axis is for the location of the searched element: 0% means it's at the start of the list, 100% means it's at the end of the list. All solutions are fastest at location 100%, with the two reversed
solutions taking pretty much no time for that, the double-reverse solution taking a little time, and the reverse-copy taking a lot of time.
A closer look at the right end:
At location 100%, the reverse-copy solution and the double-reverse solution spend all their time on the reversals (index()
is instant), so we see that the two in-place reversals are about seven times as fast as creating the reverse copy.
The above was with lst = list(range(1_000_000, 2_000_001))
, which pretty much creates the int objects sequentially in memory, which is extremely cache-friendly. Let's do it again after shuffling the list with random.shuffle(lst)
(probably less realistic, but interesting):
All got a lot slower, as expected. The reverse-copy solution suffers the most, at 100% it now takes about 32 times (!) as long as the double-reverse solution. And the enumerate
-solution is now second-fastest only after location 98%.
Overall I like the operator.indexOf
solution best, as it's the fastest one for the last half or quarter of all locations, which are perhaps the more interesting locations if you're actually doing rindex
for something. And it's only a bit slower than the double-reverse solution in earlier locations.
All benchmarks done with CPython 3.9.0 64-bit on Windows 10 Pro 1903 64-bit.
Republishing the site fixed the issue for me.
I don't know if this will help, but I did this:
LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
In that version of Android, when a view is inflated, the focus will be set to the first focusable control by default - and if there's no physical keyboard, the on-screen keyboard will pop up.
To fix this, explicitly set focus somewhere else. If focus is set to anything other than an EditText, the on-screen keyboard will not appear.
Have you tried testing this by running Android 1.5 in the emulator?
Consider using INTERSECT like this:
SELECT contactid WHERE flag = 'Volunteer'
INTERSECT
SELECT contactid WHERE flag = 'Uploaded'
I think it it the most logistic solution.
To get this in excel or csv format- right click the folder and select "copy response"- paste to excel and use text to columns.
if you datatype is datetime of the table.col , then database store data contain two partial : 1 (date) 2 (time)
Just in display data use convert or cast.
Example:
create table #test(part varchar(10),lastTime datetime)
go
insert into #test (part ,lastTime )
values('A','2012-11-05 ')
insert into #test (part ,lastTime )
values('B','2012-11-05 10:30')
go
select * from #test
A 2012-11-05 00:00:00.000
B 2012-11-05 10:30:00.000
select part,CONVERT (varchar,lastTime,111) from #test
A 2012/11/05
B 2012/11/05
select part,CONVERT (varchar(10),lastTime,20) from #test
A 2012-11-05
B 2012-11-05
For my answer, it is worth remembering that the TPL (Task-Parallel-Library), Task
class and TaskStatus
enumeration were introduced prior to the async-await keywords and the async-await keywords were not the original motivation of the TPL.
In the context of methods marked as async
, the resulting Task
is not a Task
representing the execution of the method, but a Task
for the continuation of the method.
This is only able to make use of a few possible states:
I understand that Running
could appear to have been a better default than WaitingForActivation
, however this could be misleading, as the majority of the time, an async method being executed is not actually running (i.e. it may be await
-ing something else). The other option may have been to add a new value to TaskStatus
, however this could have been a breaking change for existing applications and libraries.
All of this is very different to when making use of Task.Run
which is a part of the original TPL, this is able to make use of all the possible values of the TaskStatus
enumeration.
If you wish to keep track of the status of an async method, take a look at the IProgress(T)
interface, this will allow you to report the ongoing progress. This blog post, Async in 4.5: Enabling Progress and Cancellation in Async APIs will provide further information on the use of the IProgress(T)
interface.
Here's a version, again using the cross product logic, written in Clojure.
(defn is-left? [line point]
(let [[[x1 y1] [x2 y2]] (sort line)
[x-pt y-pt] point]
(> (* (- x2 x1) (- y-pt y1)) (* (- y2 y1) (- x-pt x1)))))
Example usage:
(is-left? [[-3 -1] [3 1]] [0 10])
true
Which is to say that the point (0, 10) is to the left of the line determined by (-3, -1) and (3, 1).
NOTE: This implementation solves a problem that none of the others (so far) does! Order matters when giving the points that determine the line. I.e., it's a "directed line", in a certain sense. So with the above code, this invocation also produces the result of true
:
(is-left? [[3 1] [-3 -1]] [0 10])
true
That's because of this snippet of code:
(sort line)
Finally, as with the other cross product based solutions, this solution returns a boolean, and does not give a third result for collinearity. But it will give a result that makes sense, e.g.:
(is-left? [[1 1] [3 1]] [10 1])
false
Are you looking for the code to do it or understanding the algorithm?
Does this do what you need? Specifically a2b_uu
and b2a_uu
? There are LOTS of other options in there in case those aren't what you want.
(NOTE: Not a Python guy but this seemed like an obvious answer)
It will return an empty enumerable. It wont be null. You can sleep sound :)
The level of version information given out by an Apache server can be configured by the ServerTokens setting in its configuration.
I believe there is also a setting that controls whether the version appears in server error pages, although I can't remember what it is off the top of my head. If you don't have direct access to the server, and the server administrator is competent and doesn't want you to know the version they're running... I think you may be SOL.
From my point of view, java.io.PipedInputStream/java.io.PipedOutputStream is the best option to considere. In some situations you may want to use ByteArrayInputStream/ByteArrayOutputStream. The problem is that you need to duplicate the buffer to convert a ByteArrayOutputStream to a ByteArrayInputStream. Also ByteArrayOutpuStream/ByteArrayInputStream are limited to 2GB. Here is an OutpuStream/InputStream implementation I wrote to bypass ByteArrayOutputStream/ByteArrayInputStream limitations (Scala code, but easily understandable for java developpers):
import java.io.{IOException, InputStream, OutputStream}
import scala.annotation.tailrec
/** Acts as a replacement for ByteArrayOutputStream
*
*/
class HugeMemoryOutputStream(capacity: Long) extends OutputStream {
private val PAGE_SIZE: Int = 1024000
private val ALLOC_STEP: Int = 1024
/** Pages array
*
*/
private var streamBuffers: Array[Array[Byte]] = Array.empty[Array[Byte]]
/** Allocated pages count
*
*/
private var pageCount: Int = 0
/** Allocated bytes count
*
*/
private var allocatedBytes: Long = 0
/** Current position in stream
*
*/
private var position: Long = 0
/** Stream length
*
*/
private var length: Long = 0
allocSpaceIfNeeded(capacity)
/** Gets page count based on given length
*
* @param length Buffer length
* @return Page count to hold the specified amount of data
*/
private def getPageCount(length: Long) = {
var pageCount = (length / PAGE_SIZE).toInt + 1
if ((length % PAGE_SIZE) == 0) {
pageCount -= 1
}
pageCount
}
/** Extends pages array
*
*/
private def extendPages(): Unit = {
if (streamBuffers.isEmpty) {
streamBuffers = new Array[Array[Byte]](ALLOC_STEP)
}
else {
val newStreamBuffers = new Array[Array[Byte]](streamBuffers.length + ALLOC_STEP)
Array.copy(streamBuffers, 0, newStreamBuffers, 0, streamBuffers.length)
streamBuffers = newStreamBuffers
}
pageCount = streamBuffers.length
}
/** Ensures buffers are bug enough to hold specified amount of data
*
* @param value Amount of data
*/
private def allocSpaceIfNeeded(value: Long): Unit = {
@tailrec
def allocSpaceIfNeededIter(value: Long): Unit = {
val currentPageCount = getPageCount(allocatedBytes)
val neededPageCount = getPageCount(value)
if (currentPageCount < neededPageCount) {
if (currentPageCount == pageCount) extendPages()
streamBuffers(currentPageCount) = new Array[Byte](PAGE_SIZE)
allocatedBytes = (currentPageCount + 1).toLong * PAGE_SIZE
allocSpaceIfNeededIter(value)
}
}
if (value < 0) throw new Error("AllocSpaceIfNeeded < 0")
if (value > 0) {
allocSpaceIfNeededIter(value)
length = Math.max(value, length)
if (position > length) position = length
}
}
/**
* Writes the specified byte to this output stream. The general
* contract for <code>write</code> is that one byte is written
* to the output stream. The byte to be written is the eight
* low-order bits of the argument <code>b</code>. The 24
* high-order bits of <code>b</code> are ignored.
* <p>
* Subclasses of <code>OutputStream</code> must provide an
* implementation for this method.
*
* @param b the <code>byte</code>.
*/
@throws[IOException]
override def write(b: Int): Unit = {
val buffer: Array[Byte] = new Array[Byte](1)
buffer(0) = b.toByte
write(buffer)
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this output stream.
* The general contract for <code>write(b, off, len)</code> is that
* some of the bytes in the array <code>b</code> are written to the
* output stream in order; element <code>b[off]</code> is the first
* byte written and <code>b[off+len-1]</code> is the last byte written
* by this operation.
* <p>
* The <code>write</code> method of <code>OutputStream</code> calls
* the write method of one argument on each of the bytes to be
* written out. Subclasses are encouraged to override this method and
* provide a more efficient implementation.
* <p>
* If <code>b</code> is <code>null</code>, a
* <code>NullPointerException</code> is thrown.
* <p>
* If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, then an <tt>IndexOutOfBoundsException</tt> is thrown.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
*/
@throws[IOException]
override def write(b: Array[Byte], off: Int, len: Int): Unit = {
@tailrec
def writeIter(b: Array[Byte], off: Int, len: Int): Unit = {
val currentPage: Int = (position / PAGE_SIZE).toInt
val currentOffset: Int = (position % PAGE_SIZE).toInt
if (len != 0) {
val currentLength: Int = Math.min(PAGE_SIZE - currentOffset, len)
Array.copy(b, off, streamBuffers(currentPage), currentOffset, currentLength)
position += currentLength
writeIter(b, off + currentLength, len - currentLength)
}
}
allocSpaceIfNeeded(position + len)
writeIter(b, off, len)
}
/** Gets an InputStream that points to HugeMemoryOutputStream buffer
*
* @return InputStream
*/
def asInputStream(): InputStream = {
new HugeMemoryInputStream(streamBuffers, length)
}
private class HugeMemoryInputStream(streamBuffers: Array[Array[Byte]], val length: Long) extends InputStream {
/** Current position in stream
*
*/
private var position: Long = 0
/**
* Reads the next byte of data from the input stream. The value byte is
* returned as an <code>int</code> in the range <code>0</code> to
* <code>255</code>. If no byte is available because the end of the stream
* has been reached, the value <code>-1</code> is returned. This method
* blocks until input data is available, the end of the stream is detected,
* or an exception is thrown.
*
* <p> A subclass must provide an implementation of this method.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
*/
@throws[IOException]
def read: Int = {
val buffer: Array[Byte] = new Array[Byte](1)
if (read(buffer) == 0) throw new Error("End of stream")
else buffer(0)
}
/**
* Reads up to <code>len</code> bytes of data from the input stream into
* an array of bytes. An attempt is made to read as many as
* <code>len</code> bytes, but a smaller number may be read.
* The number of bytes actually read is returned as an integer.
*
* <p> This method blocks until input data is available, end of file is
* detected, or an exception is thrown.
*
* <p> If <code>len</code> is zero, then no bytes are read and
* <code>0</code> is returned; otherwise, there is an attempt to read at
* least one byte. If no byte is available because the stream is at end of
* file, the value <code>-1</code> is returned; otherwise, at least one
* byte is read and stored into <code>b</code>.
*
* <p> The first byte read is stored into element <code>b[off]</code>, the
* next one into <code>b[off+1]</code>, and so on. The number of bytes read
* is, at most, equal to <code>len</code>. Let <i>k</i> be the number of
* bytes actually read; these bytes will be stored in elements
* <code>b[off]</code> through <code>b[off+</code><i>k</i><code>-1]</code>,
* leaving elements <code>b[off+</code><i>k</i><code>]</code> through
* <code>b[off+len-1]</code> unaffected.
*
* <p> In every case, elements <code>b[0]</code> through
* <code>b[off]</code> and elements <code>b[off+len]</code> through
* <code>b[b.length-1]</code> are unaffected.
*
* <p> The <code>read(b,</code> <code>off,</code> <code>len)</code> method
* for class <code>InputStream</code> simply calls the method
* <code>read()</code> repeatedly. If the first such call results in an
* <code>IOException</code>, that exception is returned from the call to
* the <code>read(b,</code> <code>off,</code> <code>len)</code> method. If
* any subsequent call to <code>read()</code> results in a
* <code>IOException</code>, the exception is caught and treated as if it
* were end of file; the bytes read up to that point are stored into
* <code>b</code> and the number of bytes read before the exception
* occurred is returned. The default implementation of this method blocks
* until the requested amount of input data <code>len</code> has been read,
* end of file is detected, or an exception is thrown. Subclasses are encouraged
* to provide a more efficient implementation of this method.
*
* @param b the buffer into which the data is read.
* @param off the start offset in array <code>b</code>
* at which the data is written.
* @param len the maximum number of bytes to read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @see java.io.InputStream#read()
*/
@throws[IOException]
override def read(b: Array[Byte], off: Int, len: Int): Int = {
@tailrec
def readIter(acc: Int, b: Array[Byte], off: Int, len: Int): Int = {
val currentPage: Int = (position / PAGE_SIZE).toInt
val currentOffset: Int = (position % PAGE_SIZE).toInt
val count: Int = Math.min(len, length - position).toInt
if (count == 0 || position >= length) acc
else {
val currentLength = Math.min(PAGE_SIZE - currentOffset, count)
Array.copy(streamBuffers(currentPage), currentOffset, b, off, currentLength)
position += currentLength
readIter(acc + currentLength, b, off + currentLength, len - currentLength)
}
}
readIter(0, b, off, len)
}
/**
* Skips over and discards <code>n</code> bytes of data from this input
* stream. The <code>skip</code> method may, for a variety of reasons, end
* up skipping over some smaller number of bytes, possibly <code>0</code>.
* This may result from any of a number of conditions; reaching end of file
* before <code>n</code> bytes have been skipped is only one possibility.
* The actual number of bytes skipped is returned. If <code>n</code> is
* negative, the <code>skip</code> method for class <code>InputStream</code> always
* returns 0, and no bytes are skipped. Subclasses may handle the negative
* value differently.
*
* The <code>skip</code> method of this class creates a
* byte array and then repeatedly reads into it until <code>n</code> bytes
* have been read or the end of the stream has been reached. Subclasses are
* encouraged to provide a more efficient implementation of this method.
* For instance, the implementation may depend on the ability to seek.
*
* @param n the number of bytes to be skipped.
* @return the actual number of bytes skipped.
*/
@throws[IOException]
override def skip(n: Long): Long = {
if (n < 0) 0
else {
position = Math.min(position + n, length)
length - position
}
}
}
}
Easy to use, no buffer duplication, no 2GB memory limit
val out: HugeMemoryOutputStream = new HugeMemoryOutputStream(initialCapacity /*may be 0*/)
out.write(...)
...
val in1: InputStream = out.asInputStream()
in1.read(...)
...
val in2: InputStream = out.asInputStream()
in2.read(...)
...
Easier alternative to above answers
If Object(Model Class/POJO) contains the date in String datatype.
private void sortArray(ArrayList<myObject> arraylist) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //your own date format
if (reports != null) {
Collections.sort(arraylist, new Comparator<myObject>() {
@Override
public int compare(myObject o1, myObject o2) {
try {
return simpleDateFormat.parse(o2.getCreated_at()).compareTo(simpleDateFormat.parse(o1.getCreated_at()));
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
});
}
If Object(Model Class/POJO) contains date in Date datatype
private void sortArray(ArrayList<myObject> arrayList) {
if (arrayList != null) {
Collections.sort(arrayList, new Comparator<myObject>() {
@Override
public int compare(myObject o1, myObject o2) {
return o2.getCreated_at().compareTo(o1.getCreated_at()); }
});
} }
The above code is for sorting the array in descending order of date, swap o1 and o2 for ascending order.
Just a slight solution change for checking the version of numpy with Python,
import numpy as np
print("Numpy Version:",np.__version__)
Or,
import numpy as np
print("Numpy Version:",np.version.version)
My projects in PyCharm are currently running version
1.17.4
What helped me was a look at the source code of the two functions.
Map - wraps the result in an Optional.
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value)); //<--- wraps in an optional
}
}
flatMap - returns the 'raw' object
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value)); //<--- returns 'raw' object
}
}
'use strict'
var fs = require("fs");
/***
* implementation of readFileSync
*/
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
/***
* implementation of readFile
*/
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
For better understanding run the above code and compare the results..
First off, see How Big can a Python Array Get? and Numpy, problem with long arrays
Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
If you are using jQuery, there is a redirect plugin that works with the POST or GET method. It creates a form with hidden inputs and submits it for you. An example of how to get it working:
$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
Note: You can pass the method types GET or POST as an optional third parameter; POST is the default.
Using Zxing this way requires a user to also install the barcode scanner app, which isn't ideal. What you probably want is to bundle Zxing into your app directly.
I highly recommend using this library: https://github.com/dm77/barcodescanner
It takes all the crazy build issues you're going to run into trying to integrate Xzing or Zbar directly. It uses those libraries under the covers, but wraps them in a very simple to use API.
Javadocs don't offer any special tools for external links, so you should just use standard html:
See <a href="http://groversmill.com/">Grover's Mill</a> for a history of the
Martian invasion.
or
@see <a href="http://groversmill.com/">Grover's Mill</a> for a history of
the Martian invasion.
Don't use {@link ...}
or {@linkplain ...}
because these are for links to the javadocs of other classes and methods.
Personally I would suggest this is an error as opposed to a setting that needs adjusting. In my code it was because I had a class that had the same name as a library within one of my controllers and it seemed to trip it up.
Output errors and see where this is being triggered.
MySQL is most likely in STRICT
mode, which isn't necessarily a bad thing, as you'll identify bugs/issues early and not just blindly think everything is working as you intended.
Change the column to allow null:
ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NULL
or, give it a default value as empty string:
ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NOT NULL DEFAULT ''
Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.
When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.
When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.
You'll find more details about the specification and how to generate such a certificate in this answer.
The easiest way is simply to pay attention to the order in which the Views are added to your XML file. Lower down in the file means higher up in the Z-axis.
Edit: This is documented here and here on the Android developer site. (Thanks @flightplanner)
For Microsoft Query you can go into Connections --> Properties and untick "Enable background refresh".
This will stop anything happening while the refresh is taking place. I needed to refresh data upon entry and then run a userform on the refreshed data, and this method worked perfectly for me.
Use:
$("tr").find("td:first");
js fiddle - this example has .text()
on the end to show that it is returning the elements.
Alternatively, you can use:
$("td:first-child");
.find()
- jQuery API Documentation
A foreach loop in php will iterate over a copy of the original array, making next()
and prev()
functions useless. If you have an associative array and need to fetch the next item, you could iterate over the array keys instead:
foreach (array_keys($items) as $index => $key) {
// first, get current item
$item = $items[$key];
// now get next item in array
$next = $items[array_keys($items)[$index + 1]];
}
Since the resulting array of keys has a continuous index itself, you can use that instead to access the original array.
Be aware that $next
will be null
for the last iteration, since there is no next item after the last. Accessing non existent array keys will throw a php notice. To avoid that, either:
$next
index + 1
exists with array_key_exists()
Using method 2 the complete foreach could look like this:
foreach (array_keys($items) as $index => $key) {
// first, get current item
$item = $items[$key];
// now get next item in array
$next = null;
if (array_key_exists($index + 1, array_keys($items))) {
$next = $items[array_keys($items)[$index + 1]];
}
}
Be careful that when you using:
curl -H "Authorization: token_str" http://www.example.com
token_str
and Authorization
must be separated by white space, otherwise server-side will not get the HTTP_AUTHORIZATION
environment.
An easy fix to this question is to add '[' in the start of your json file, and ending it with a ']'. This solved it for me.
No need to create a GD resource, as someone else suggested.
$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));
Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.
Okay, here's a list of things to look into:
1) If you're not running a webserver of any kind and just testing with file://index.html, then you're probably running into same-origin policy issues. See:
https://code.google.com/archive/p/browsersec/wikis/Part2.wiki#Same-origin_policy
Many browsers don't allow locally hosted files to access other locally hosted files. Firefox does allow it, but only if the file you're loading is contained in the same folder as the html file (or a subfolder).
2) The success function returned from $http.get() already splits up the result object for you:
$http({method: 'GET', url: '/someUrl'}).success(function(data, status, headers, config) {
So it's redundant to call success with function(response) and return response.data.
3) The success function does not return the result of the function you pass it, so this does not do what you think it does:
var mainInfo = $http.get('content.json').success(function(response) {
return response.data;
});
This is closer to what you intended:
var mainInfo = null;
$http.get('content.json').success(function(data) {
mainInfo = data;
});
4) But what you really want to do is return a reference to an object with a property that will be populated when the data loads, so something like this:
theApp.factory('mainInfo', function($http) {
var obj = {content:null};
$http.get('content.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
mainInfo.content will start off null, and when the data loads, it will point at it.
Alternatively you can return the actual promise the $http.get returns and use that:
theApp.factory('mainInfo', function($http) {
return $http.get('content.json');
});
And then you can use the value asynchronously in calculations in a controller:
$scope.foo = "Hello World";
mainInfo.success(function(data) {
$scope.foo = "Hello "+data.contentItem[0].username;
});
It is possible to set autofocus
on input elements
<input type="text" class="b_calle" id="b_calle" placeholder="Buscar por nombre de calle" autofocus="autofocus">
You just need to put -y
with the install command.
For example: yum install <package_to_install> -y
Your server process has received a SIGPIPE
writing to a socket. This usually happens when you write to a socket fully closed on the other (client) side. This might be happening when a client program doesn't wait till all the data from the server is received and simply closes a socket (using close
function).
In a C program you would normally try setting to ignore SIGPIPE
signal or setting a dummy signal handler for it. In this case a simple error will be returned when writing to a closed socket. In your case a python seems to throw an exception that can be handled as a premature disconnect of the client.
After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:
In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:
http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html
Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.
Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .
Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:
@Resource
private SessionContext sessionContext;
With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation
EJB.
I also looked around for the best way to logout. The best one that I've found is using a Servlet:
@WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
public class LogoutServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
// Destroys the session for this user.
if (session != null)
session.invalidate();
// Redirects back to the initial page.
response.sendRedirect(request.getContextPath());
}
}
Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.
Ciao,
Vítor Souza
subprocess.Popen()
is prefered over os.system()
as it offers more control and visibility. However, If you find subprocess.Popen()
too verbose or complex, peasyshell
is a small wrapper I wrote above it, which makes it easy to interact with bash from Python.
Derek's answer above didn't work for me. I am using VS 2013 Ultimate and after signing out of Visual Studio, when i tried to sign in as another user, it gave error.
Then when connecting to the Team Project i saw the option to switch user, which is what i wanted all along.
Why don't you use the Modulus Operator?
Try this:
while ($s % 6 != 0) $s++;
Or is this what you meant?
<?
$s= <some_number>;
$k= $s % 6;
if($k !=0) $s=$s+6-$k;
?>
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
Until ES5, there was no string format that browsers were required to support, though there are a number that are widely supported. However browser support is unreliable an inconsistent, e.g. some will allow out of bounds values and others wont, some support certain formats and others don't, etc.
ES5 introduced support for some ISO 8601 formats, however the OP is not compliant with ISO 8601 and not all browsers in use support it anyway.
The only reliable way is to use a small parsing function. The following parses the format in the OP and also validates the values.
/* Parse date string in format yyyy-mm-dd hh:mm:ss_x000D_
** If string contains out of bounds values, an invalid date is returned_x000D_
** _x000D_
** @param {string} s - string to parse, e.g. "2010-08-17 12:09:36"_x000D_
** treated as "local" date and time_x000D_
** @returns {Date} - Date instance created from parsed string_x000D_
*/_x000D_
function parseDateString(s) {_x000D_
var b = s.split(/\D/);_x000D_
var d = new Date(b[0], --b[1], b[2], b[3], b[4], b[5]);_x000D_
return d && d.getMonth() == b[1] && d.getHours() == b[3] &&_x000D_
d.getMinutes() == b[4]? d : new Date(NaN);_x000D_
}_x000D_
_x000D_
document.write(_x000D_
parseDateString('2010-08-17 12:09:36') + '<br>' + // Valid values_x000D_
parseDateString('2010-08-45 12:09:36') // Out of bounds date_x000D_
);
_x000D_
**node_modules
This works for me
recursive approach to ignore all node_modules present in sub folders
For your case, you may use regex:
boolean checkFormat;
if (input.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
checkFormat=true;
else
checkFormat=false;
For a larger scope or if you want a flexible solution, refer to MadProgrammer's answer.
Almost 5 years after posting this answer, I realize that this is a stupid way to validate a date format. But i'll just leave this here to tell people that using regex to validate a date is unacceptable
If you have the option pre-existing in a fixed-with <select>
, and you don't want to change the width programmatically, you could be out of luck unless you get a little creative.
title
attribute to each option. This is non-standard HTML (if you care for this minor infraction here), but IE (and Firefox as well) will display the entire text in a mouse popup on mouse hover.If you are adding a long option later through JavaScript, look here: How to update HTML “select” box dynamically in IE
As many people said you need to use an external service and call it. And that will only get you the DNS resolution from the server perspective.
If that's good enough and if you just need DNS resolution you can use the following Docker container:
https://github.com/kuralabs/docker-webaiodns
Endpoints:
[GET] /ipv6/[domain]
:
Perform a DNS resolution for given domain and return the associated IPv6
addresses.
{
"addresses": [
"2a01:91ff::f03c:7e01:51bd:fe1f"
]
}
[GET] /ipv4/[domain]
:
Perform a DNS resolution for given domain and return the associated IPv4
addresses.
{
"addresses": [
"139.180.232.162"
]
}
My recommendation is that you setup your web server to reverse proxy to the container on a particular endpoint in your server serving your Javascript and call it using your standard Javascript Ajax functions.
You need to stringify the json, not calling toString
var buf = Buffer.from(JSON.stringify(obj));
And for converting string to json obj :
var temp = JSON.parse(buf.toString());
Removed and added back in the table using Scaffold-DbContext and the error went away
This is the solution for you: http://blogs.technet.com/b/wardpond/archive/2005/08/01/the-openrowset-trick-accessing-stored-procedure-output-in-a-select-statement.aspx
select * from openrowset ('SQLOLEDB', '192.168.x.x\DATA'; 'user'; 'password', 'sp_who')
$(function() {
$('#sortable').sortable({
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
change: function(event, ui) {
var start_pos = ui.item.data('start_pos');
var index = ui.placeholder.index();
if (start_pos < index) {
$('#sortable li:nth-child(' + index + ')').addClass('highlights');
} else {
$('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
}
},
update: function(event, ui) {
$('#sortable li').removeClass('highlights');
}
});
});
To both check if it exists and create if it doesn't, including intermediaries:
QDir dir("path/to/dir");
if (!dir.exists())
dir.mkpath(".");
I know it's been said already, but I'd highly recommend the requests
Python package.
If you've used languages other than python, you're probably thinking urllib
and urllib2
are easy to use, not much code, and highly capable, that's how I used to think. But the requests
package is so unbelievably useful and short that everyone should be using it.
First, it supports a fully restful API, and is as easy as:
import requests
resp = requests.get('http://www.mywebsite.com/user')
resp = requests.post('http://www.mywebsite.com/user')
resp = requests.put('http://www.mywebsite.com/user/put')
resp = requests.delete('http://www.mywebsite.com/user/delete')
Regardless of whether GET / POST, you never have to encode parameters again, it simply takes a dictionary as an argument and is good to go:
userdata = {"firstname": "John", "lastname": "Doe", "password": "jdoe123"}
resp = requests.post('http://www.mywebsite.com/user', data=userdata)
Plus it even has a built in JSON decoder (again, I know json.loads()
isn't a lot more to write, but this sure is convenient):
resp.json()
Or if your response data is just text, use:
resp.text
This is just the tip of the iceberg. This is the list of features from the requests site:
Renaming a worksheet manually in Excel, you hit a limit of 31 chars, so I'd suggest that that's a hard limit.
When you import a module (or a member of it) for the first time, the code inside the module is executed sequentially like any other code; e.g., it is not treated any differently that the body of a function. An import
is just a command like any other (assignment, a function call, def
, class
). Assuming your imports occur at the top of the script, then here's what's happening:
World
from world
, the world
script gets executed.world
script imports Field
, which causes the entities.field
script to get executed.entities.post
script because you tried to import Post
entities.post
script causes physics
module to be executed because it tries to import PostBody
physics
tries to import Post
from entities.post
entities.post
module exists in memory yet, but it really doesn't matter. Either the module is not in memory, or the module doesn't yet have a Post
member because it hasn't finished executing to define Post
Post
is not there to be importedSo no, it's not "working further up in the call stack". This is a stack trace of where the error occurred, which means it errored out trying to import Post
in that class. You shouldn't use circular imports. At best, it has negligible benefit (typically, no benefit), and it causes problems like this. It burdens any developer maintaining it, forcing them to walk on egg shells to avoid breaking it. Refactor your module organization.
Your folder/file structure seems a little odd to me. I can't quite figure out how you've got this laid out.
Hello I am using CodeIgniter for two applications (a public and an admin app).
This sounds to me like you've got two separate CI installations. If this is the case, I'd recommend against it. Why not just handle all admin stuff in an admin controller? If you do want two separate CI installations, make sure they are definitely distinct entities and that the two aren't conflicting with one another. This line:
$system_folder = "../system";
$application_folder = "../application/admin"; (this line exists of course twice)
And the place you said this exists (/admin/index.php...or did you mean /admin/application/config?) has me scratching my head. You have admin/application/admin and a system folder at the top level?
$str = "http://www.vimeo.com/1234567";
$s = explode("/",$str);
print end($s);
Probably something like this:
original_list = dictionary.get('C1')
new_list = []
for item in original_list:
new_list.append(item+10)
dictionary['C1'] = new_list
I use a Tuple
as the keys in a Dictionary
.
public class Tuple<T1, T2> {
public T1 Item1 { get; private set; }
public T2 Item2 { get; private set; }
// implementation details
}
Be sure to override Equals
and GetHashCode
and define operator!=
and operator==
as appropriate. You can expand the Tuple
to hold more items as needed. .NET 4.0 will include a built-in Tuple
.
DECLARE @first AS INT = 1
DECLARE @last AS INT = 300
WHILE(@first <= @last)
BEGIN
INSERT INTO tblFoo VALUES(@first)
SET @first += 1
END
It can be done without the use of View State or Session. Current order can be determined based on value in first and last row in the column we sort by:
protected void gvItems_Sorting(object sender, GridViewSortEventArgs e)
{
GridView grid = sender as GridView; // get reference to grid
SortDirection currentSortDirection = SortDirection.Ascending; // default order
// get column index by SortExpression
int columnIndex = grid.Columns.IndexOf(grid.Columns.OfType<DataControlField>()
.First(x => x.SortExpression == e.SortExpression));
// sort only if grid has more than 1 row
if (grid.Rows.Count > 1)
{
// get cells
TableCell firstCell = grid.Rows[0].Cells[columnIndex];
TableCell lastCell = grid.Rows[grid.Rows.Count - 1].Cells[columnIndex];
// if field type of the cell is 'TemplateField' Text property is always empty.
// Below assumes that value is binded to Label control in 'TemplateField'.
string firstCellValue = firstCell.Controls.Count == 0 ? firstCell.Text : ((Label)firstCell.Controls[1]).Text;
string lastCellValue = lastCell.Controls.Count == 0 ? lastCell.Text : ((Label)lastCell.Controls[1]).Text;
DateTime tmpDate;
decimal tmpDecimal;
// try to determinate cell type to ensure correct ordering
// by date or number
if (DateTime.TryParse(firstCellValue, out tmpDate)) // sort as DateTime
{
currentSortDirection =
DateTime.Compare(Convert.ToDateTime(firstCellValue),
Convert.ToDateTime(lastCellValue)) < 0 ?
SortDirection.Ascending : SortDirection.Descending;
}
else if (Decimal.TryParse(firstCellValue, out tmpDecimal)) // sort as any numeric type
{
currentSortDirection = Decimal.Compare(Convert.ToDecimal(firstCellValue),
Convert.ToDecimal(lastCellValue)) < 0 ?
SortDirection.Ascending : SortDirection.Descending;
}
else // sort as string
{
currentSortDirection = string.CompareOrdinal(firstCellValue, lastCellValue) < 0 ?
SortDirection.Ascending : SortDirection.Descending;
}
}
// then bind GridView using correct sorting direction (in this example I use Linq)
if (currentSortDirection == SortDirection.Descending)
{
grid.DataSource = myItems.OrderBy(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));
}
else
{
grid.DataSource = myItems.OrderByDescending(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));
}
grid.DataBind();
}
There are several ways to get a string length:
package main
import (
"bytes"
"fmt"
"strings"
"unicode/utf8"
)
func main() {
b := "?????"
len1 := len([]rune(b))
len2 := bytes.Count([]byte(b), nil) -1
len3 := strings.Count(b, "") - 1
len4 := utf8.RuneCountInString(b)
fmt.Println(len1)
fmt.Println(len2)
fmt.Println(len3)
fmt.Println(len4)
}
The method boolean shouldOverrideUrlLoading(WebView view, String url)
was deprecated in API 24. If you are supporting new devices you should use boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request)
.
You can use both by doing something like this:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
newsItem.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return true;
}
});
} else {
newsItem.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
You can call the method like pump.getPumps()
. By adding @classmethod
decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.
class Pump:
def __init__(self):
print ("init") # never prints
@classmethod
def getPumps(cls):
# Open database connection
# some stuff here that never gets executed because of error
So, simply call Pump.getPumps()
.
In java, it is termed as static
method.
The function below will create and add to the document all the stylesheets that you wish to load asynchronously. (But, thanks to the Event Listener
, it will only do so after all the window's other resources have loaded.)
See the following:
function loadAsyncStyleSheets() {
var asyncStyleSheets = [
'/stylesheets/async-stylesheet-1.css',
'/stylesheets/async-stylesheet-2.css'
];
for (var i = 0; i < asyncStyleSheets.length; i++) {
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', asyncStyleSheets[i]);
document.head.appendChild(link);
}
}
window.addEventListener('load', loadAsyncStyleSheets, false);
Here is a little one-liner that will let you know if your current branch incorporates or is out of data from a remote origin/master branch:
$ git fetch && git branch -r --merged | grep -q origin/master && echo Incorporates origin/master || echo Out of date from origin/master
I came across this question when working on a feature branch and frequently wanting to make sure that I have the most recent work incorporated into my own separate working branch.
To generalize this test I have added the following alias to my ~/.gitconfig:
[alias]
current = !git branch -r --merged | grep -q $1 && echo Incorporates $1 || echo Out of date from $1 && :
Then I can call:
$ git current origin/master
to check if I am current.
From the command line:
psql my_database -c 'SHOW SERVER_ENCODING'
From within psql
, an SQL IDE or an API:
SHOW SERVER_ENCODING
Create new project in Android studio;
Press Ctrl+Shift+Alt+S
Proceed to "Project" section
You can see actual gradle version and android pluging version. Copy that to your project.
Material UI have implemented their own Flexbox layout via the Grid component.
It appears they initially wanted to keep themselves as purely a 'components' library. But one of the core developers decided it was too important not to have their own. It has now been merged into the core code and was released with v1.0.0.
You can install it via:
npm install @material-ui/core
It is now in the official documentation with code examples.
string sample = "ratty";
Console.WriteLine(sample[0]);
And
Console.WriteLine(sample.Chars(0));
Reference: http://msdn.microsoft.com/en-us/library/system.string.chars%28v=VS.71%29.aspx
The above is same as using indexers in c#.
You can compare datetime.datetime objects directly
E.g:
>>> a
datetime.datetime(2009, 12, 2, 10, 24, 34, 198130)
>>> b
datetime.datetime(2009, 12, 2, 10, 24, 36, 910128)
>>> a < b
True
>>> a > b
False
>>> a == a
True
>>> b == b
True
>>>
Following two configuration is working for me.
1 .tomcat-users.xml details
--------------------------------
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<role rolename="admin-gui"/>
<role rolename="admin-script"/>
<role rolename="tomcat"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="admin" password="admin" roles="admin-gui"/>
<user username="adminscript" password="adminscrip" roles="admin-script"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>
<user username="status" password="status" roles="manager-status"/>
<user username="both" password="both" roles="manager-gui,manager-status"/>
<user username="script" password="script" roles="manager-script"/>
<user username="jmx" password="jmx" roles="manager-jmx"/>
2. context.xml of <tomcat>/webapps/manager/META-INF/context.xml and
<tomcat>/webapps/host-manager/META-INF/context.xml
------------------------------------------------------------------------
<Context antiResourceLocking="false" privileged="true" >
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow=".*" />
<Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
you can compile the ui files like this
pyuic4 -x helloworld.ui -o helloworld.py
javac HelloWorld.java -classpath ./javax.jar , assuming javax is in current folder, and compile target is "HelloWorld.java", and you can compile without a main method
Just hook up the onclick event:
<input id="button" type="submit" name="button" value="enter" onclick="myFunction();"/>
Efran Cobisi's suggestion of using an Auto Mapper is a good one. I have used Auto Mapper for a while and it worked well, until I found the much faster alternative, Mapster.
Given a large list or IEnumerable, Mapster outperforms Auto Mapper. I found a benchmark somewhere that showed Mapster being 6 times as fast, but I could not find it again. You could look it up and then, if it is suits you, use Mapster.
If you want to use a link then: in the html have:
<button type="button" id="btnOpenLine" class="btn btn-default btn-sm" ng-click="orderMaster.openLineItems()">Order Line Items</button>
in the typescript file
public openLineItems() {
if (this.$stateParams.id == 0) {
this.Flash.create('warning', "Need to save order!", 3000);
return
}
this.$window.open('#/orderLineitems/' + this.$stateParams.id);
}
I hope you see this example helpful as it was for me along with the other answers.
This may answer your question:
select cast(xmlField as xml) xmlField into tmp from (
select '<person><firstName>Jon</firstName><lastName>Johnson</lastName></person>' xmlField
union select '<person><firstName>Kathy</firstName><lastName>Carter</lastName></person>'
union select '<person><firstName>Bob</firstName><lastName>Burns</lastName></person>'
) tb
SELECT
xmlField.value('(person/firstName)[1]', 'nvarchar(max)') as FirstName
,xmlField.value('(person/lastName)[1]', 'nvarchar(max)') as LastName
FROM tmp
drop table tmp
I am not sure why no one mentioned this but in C# for things that I cannot assign const, I use static read-only properties.
Example:
public static readonly Dictionary<string, string[]> NewDictionary = new Dictionary<string, string[]>()
{
{ "Reference1", Array1 },
{ "Reference2", Array2 },
{ "Reference3", Array3 },
{ "Reference4", Array4 },
{ "Reference5", Array5 }
};
The short version
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://almondmendoza.com/android-applications/")));
should work as well...
You can expose the service in two different endpoints. the SOAP one can use the binding that support SOAP e.g. basicHttpBinding, the RESTful one can use the webHttpBinding. I assume your REST service will be in JSON, in that case, you need to configure the two endpoints with the following behaviour configuration
<endpointBehaviors>
<behavior name="jsonBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
An example of endpoint configuration in your scenario is
<services>
<service name="TestService">
<endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
<endpoint address="json" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="ITestService"/>
</service>
</services>
so, the service will be available at
Apply [WebGet] to the operation contract to make it RESTful. e.g.
public interface ITestService
{
[OperationContract]
[WebGet]
string HelloWorld(string text)
}
Note, if the REST service is not in JSON, parameters of the operations can not contain complex type.
For plain old XML as return format, this is an example that would work both for SOAP and XML.
[ServiceContract(Namespace = "http://test")]
public interface ITestService
{
[OperationContract]
[WebGet(UriTemplate = "accounts/{id}")]
Account[] GetAccount(string id);
}
POX behavior for REST Plain Old XML
<behavior name="poxBehavior">
<webHttp/>
</behavior>
Endpoints
<services>
<service name="TestService">
<endpoint address="soap" binding="basicHttpBinding" contract="ITestService"/>
<endpoint address="xml" binding="webHttpBinding" behaviorConfiguration="poxBehavior" contract="ITestService"/>
</service>
</services>
Service will be available at
REST request try it in browser,
SOAP request client endpoint configuration for SOAP service after adding the service reference,
<client>
<endpoint address="http://www.example.com/soap" binding="basicHttpBinding"
contract="ITestService" name="BasicHttpBinding_ITestService" />
</client>
in C#
TestServiceClient client = new TestServiceClient();
client.GetAccount("A123");
Another way of doing it is to expose two different service contract and each one with specific configuration. This may generate some duplicates at code level, however at the end of the day, you want to make it working.
I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:
If you wish to print as you have specified then:
scala> def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]
scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)
scala> println(manOf(x))
scala.collection.immutable.List[Int]
If you are in repl mode then
scala> :type List(1,2,3)
List[Int]
Or if you just wish to know what the class type then as @monkjack explains "string".getClass
might solve the purpose
All type information is erased in JavaScript side and therefore you can't new up T just like @Sohnee states, but I would prefer having typed parameter passed in to constructor:
class A {
}
class B<T> {
Prop: T;
constructor(TCreator: { new (): T; }) {
this.Prop = new TCreator();
}
}
var test = new B<A>(A);
If you want them to show up one at a time, you can do this:
import time
import sys
for i in range(20):
sys.stdout.write('a')
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.flush()
is necessary to force the character to be written each time the loop is run.
Yeah I had the same problem and it was driving me crazy because I couldn't find the image.
This may help you out...
You will then see something like this...
.ui-widget-content {
border: 1px solid #aaaaaa;
background: #ffffff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x;
color: #222222;
}
And comment out the background and save the CSS document. Or you can set an absolute path to that background property and see if that works for you. (i.e. background: #ffffff url(http://.../image.png
);
Hope this helps
Time saver for people who are facing the same issue (Mockito + Final Class) on Android + Kotlin. As in Kotlin classes are final by default. I found a solution in one of Google Android samples with Architecture component. Solution picked from here : https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample
Create following annotations :
/**
* This annotation allows us to open some classes for mocking purposes while they are final in
* release builds.
*/
@Target(AnnotationTarget.ANNOTATION_CLASS)
annotation class OpenClass
/**
* Annotate a class with [OpenForTesting] if you want it to be extendable in debug builds.
*/
@OpenClass
@Target(AnnotationTarget.CLASS)
annotation class OpenForTesting
Modify your gradle file. Take example from here : https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/build.gradle
apply plugin: 'kotlin-allopen'
allOpen {
// allows mocking for classes w/o directly opening them for release builds
annotation 'com.android.example.github.testing.OpenClass'
}
Now you can annotate any class to make it open for testing :
@OpenForTesting
class RepoRepository
You can use the concept of selector. onFocus removes the hint.
android:hint="Email"
So when TextView
has focus, or has user input (i.e. not empty) the hint will not display.
You can use perl to replace various characters, for example:
$ echo "Hello\ world" | perl -pe 's/\\/\\\\/g'
Hello\\ world
Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.
Use Guzzle. It's a "PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services". Working with Guzzle is much easier than working with cURL.
Here's an example from the Web site:
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode(); // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody(); // {"type":"User"...'
var_export($res->json()); // Outputs the JSON decoded data
If just wanted to show math in the browser for yourself, you could try the Chrome extension GitHub with MathJax. It's quite convenient.
Check the package plotext which allows to plot data directly on terminal using python3. It is very intuitive as its use is very similar to the matplotlib package.
Here is a basic example:
You can install it with the following command:
sudo -H pip install plotext
As for matplotlib, the main functions are scatter (for single points), plot (for points joined by lines) and show (to actually print the plot on terminal). It is easy to specify the plot dimensions, the point and line styles and whatever to show the axes, number ticks and final equations, which are used to convert the plotted coordinates to the original real values.
Here is the code to produce the plot shown above:
import plotext.plot as plx
import numpy as np
l=3000
x=np.arange(0, l)
y=np.sin(4*np.pi/l*np.array(x))*np.exp(-0.5*np.pi/l*x)
plx.scatter(x, y, rows = 17, cols = 70)
plx.show(clear = 0)
The option clear=True
inside show
is used to clear the terminal before plotting: this is useful, for example, when plotting a continuous flow of data.
An example of plotting a continuous data flow is shown here:
The package description provides more information how to customize the plot. The package has been tested on Ubuntu 16 where it works perfectly. Possible future developments (upon request) could involve extension to python2 and to other graphical interfaces (e.g. jupiter). Please let me know if you have any issues using it. Thanks.
I hope this answers your problem.
More fast way using directly a no-string array but a string:
string[] StringSplit(string StringToSplit, string Delimitator)
{
return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}
StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/
As Leo points out, the code you added to your question would not suggest a strong reference cycle (a.k.a., retain cycle). One operation-related issue that could cause a strong reference cycle would be if the operation is not getting released. While your code snippet suggests that you have not defined your operation to be concurrent, but if you have, it wouldn't be released if you never posted isFinished
, or if you had circular dependencies, or something like that. And if the operation isn't released, the view controller wouldn't be released either. I would suggest adding a breakpoint or NSLog
in your operation's dealloc
method and confirm that's getting called.
You said:
I understand the notion of retain cycles, but I am not quite sure what happens in blocks, so that confuses me a little bit
The retain cycle (strong reference cycle) issues that occur with blocks are just like the retain cycle issues you're familiar with. A block will maintain strong references to any objects that appear within the block, and it will not release those strong references until the block itself is released. Thus, if block references self
, or even just references an instance variable of self
, that will maintain strong reference to self, that is not resolved until the block is released (or in this case, until the NSOperation
subclass is released.
For more information, see the Avoid Strong Reference Cycles when Capturing self section of the Programming with Objective-C: Working with Blocks document.
If your view controller is still not getting released, you simply have to identify where the unresolved strong reference resides (assuming you confirmed the NSOperation
is getting deallocated). A common example is the use of a repeating NSTimer
. Or some custom delegate
or other object that is erroneously maintaining a strong
reference. You can often use Instruments to track down where objects are getting their strong references, e.g.:
Or in Xcode 5:
Right I think I know what you mean so lets see....
<div id="con">
<div id="content">Results will go here</div>
<div id="footer">Footer will always be at the bottom</div>
</div>
html,
body {
margin:0;
padding:0;
height:100%;
}
div {
outline: 1px solid;
}
#con {
min-height:100%;
position:relative;
}
#content {
height: 1000px; /* Changed this height */
padding-bottom:60px;
}
#footer {
position:absolute;
bottom:0;
width:100%;
height:60px;
}
This demo have the height of contentheight: 1000px;
so you can see what it would look like scrolling down the bottom.
This demo has the height of content height: 100px;
so you can see what it would look like with no scrolling.
So this will move the footer below the div content
but if content is not bigger then the screen (no scrolling) the footer will sit at the bottom of the screen. Think this is what you want. Have a look and a play with it.
Updated fiddles so its easier to see with backgrounds.
You have an error in your syntax here:
this._possessions = new Thing[100]();
This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:
this._possessions = [];
Of the array constructor if you want to set the length:
this._possessions = new Array(100);
I have created a brief working example you can try in the playground.
module Entities {
class Thing {
}
export class Person {
private _name: string;
private _possessions: Thing[];
private _mostPrecious: Thing;
constructor (name: string) {
this._name = name;
this._possessions = [];
this._possessions.push(new Thing())
this._possessions[100] = new Thing();
}
}
}
(tomcat 7.0.32) I had problems to see debug messages althought was enabling TldLocationsCache row in tomcat/conf/logging.properties file. All I could see was a warning but not what libs were scanned. Changed every loglevel tried everything no luck. Then I went rogue debug mode (=remove one by one, clean install etc..) and finally found a reason.
My webapp had a customized tomcat/webapps/mywebapp/WEB-INF/classes/logging.properties file. I copied TldLocationsCache row to this file, finally I could see jars filenames.
# To see debug messages in TldLocationsCache, uncomment the following line: org.apache.jasper.compiler.TldLocationsCache.level = FINE
Add this to your CSS:
#artiststhumbnail a img {
display: block;
margin-left: auto;
margin-right: auto;
}
Just referencing a child element which in that case is the image.
You could make use the System.Uri class. The Uri class isn't just useful for web URLs, it also handles file system paths as well. Use the Uri.TryCreate method to find if the path is rooted then use the IsLoopback property to determine if the Uri references the local machine.
Here is a simple method which determines if a string is a valid, local, and rooted file path.
public bool IsPathValidRootedLocal(String pathString) {
Uri pathUri;
Boolean isValidUri = Uri.TryCreate(pathString, UriKind.Absolute, out pathUri);
return isValidUri && pathUri != null && pathUri.IsLoopback;
}
I am confident this will work.
put it inside. You can keep processing (if you want) or you can throw a helpful exception that tells the client the value of myString and the index of the array containing the bad value. I think NumberFormatException will already tell you the bad value but the principle is to place all the helpful data in the exceptions that you throw. Think about what would be interesting to you in the debugger at this point in the program.
Consider:
try {
// parse
} catch (NumberFormatException nfe){
throw new RuntimeException("Could not parse as a Float: [" + myString +
"] found at index: " + i, nfe);
}
In the time of need you will really appreciate an exception like this with as much information in it as possible.
Here is the source of these column flags
http://dev.mysql.com/doc/workbench/en/wb-table-editor-columns-tab.html
demo - http://jsfiddle.net/victor_007/ywevz8ra/
added border for better view (testing)
more info about white-space
table{
width:100%;
}
table td{
white-space: nowrap; /** added **/
}
table td:last-child{
width:100%;
}
table {_x000D_
width: 100%;_x000D_
}_x000D_
table td {_x000D_
white-space: nowrap;_x000D_
}_x000D_
table td:last-child {_x000D_
width: 100%;_x000D_
}
_x000D_
<table border="1">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column A</th>_x000D_
<th>Column B</th>_x000D_
<th>Column C</th>_x000D_
<th class="absorbing-column">Column D</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data A.1 lorem</td>_x000D_
<td>Data B.1 ip</td>_x000D_
<td>Data C.1 sum l</td>_x000D_
<td>Data D.1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data A.2 ipsum</td>_x000D_
<td>Data B.2 lorem</td>_x000D_
<td>Data C.2 some data</td>_x000D_
<td>Data D.2 a long line of text that is long</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data A.3</td>_x000D_
<td>Data B.3</td>_x000D_
<td>Data C.3</td>_x000D_
<td>Data D.3</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
jQuery has an AjaxSetup()
function that allows you to register global ajax handlers such as beforeSend
and complete
for all ajax calls as well as allow you to access the xhr
object to do the progress that you are looking for
Another method uses the triangle ABC area formula. The intersection test is simpler and more efficient than the projection method, but finding the coordinates of the intersection point requires more work. At least it will be delayed to the point it is required.
The formula to compute the triangle area is : area = bh/2
where b is the base length and h is the height. We chose the segment AB to be the base so that h is the shortest distance from C, the circle center, to the line.
Since the triangle area can also be computed by a vector dot product we can determine h.
// compute the triangle area times 2 (area = area2/2)
area2 = abs( (Bx-Ax)*(Cy-Ay) - (Cx-Ax)(By-Ay) )
// compute the AB segment length
LAB = sqrt( (Bx-Ax)² + (By-Ay)² )
// compute the triangle height
h = area2/LAB
// if the line intersects the circle
if( h < R )
{
...
}
UPDATE 1 :
You could optimize the code by using the fast inverse square root computation described here to get a good approximation of 1/LAB.
Computing the intersection point is not that difficult. Here it goes
// compute the line AB direction vector components
Dx = (Bx-Ax)/LAB
Dy = (By-Ay)/LAB
// compute the distance from A toward B of closest point to C
t = Dx*(Cx-Ax) + Dy*(Cy-Ay)
// t should be equal to sqrt( (Cx-Ax)² + (Cy-Ay)² - h² )
// compute the intersection point distance from t
dt = sqrt( R² - h² )
// compute first intersection point coordinate
Ex = Ax + (t-dt)*Dx
Ey = Ay + (t-dt)*Dy
// compute second intersection point coordinate
Fx = Ax + (t+dt)*Dx
Fy = Ay + (t+dt)*Dy
If h = R then the line AB is tangent to the circle and the value dt = 0 and E = F. The point coordinates are those of E and F.
You should check that A is different of B and the segment length is not null if this may happen in your application.
protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
grvSecondaryLocations.EditIndex = e.NewEditIndex;
DropDownList ddlPbx = (DropDownList)(grvSecondaryLocations.Rows[grvSecondaryLocations.EditIndex].FindControl("ddlPBXTypeNS"));
if (ddlPbx != null)
{
ddlPbx.DataSource = _pbxTypes;
ddlPbx.DataBind();
}
.... (more stuff)
}
Nvm. For anyone else having this problem you need to reboot your mac and press ?+R when booting up. Then go into Utilities > Terminal and type the following commands:
csrutil disable
reboot
This is a result of System Integrity Protection. More info here.
EDIT
If you know what you are doing and are used to running Linux, you should use the above solution as many of the SIP restrictions are a complete pain in the ass.
However, if you are a tinkerer/noob/"poweruser" and don't know what you are doing, this can be very dangerous and you are better off using the answer below.
Use this code:
$this->db->where(['id'=>2])->from("table name")->count_all_results();
or
$this->db->from("table name")->count_all_results();
Attention, this is only advised if your
runOnceOnStartup
method depends on a fully initialized spring context. For example: you wan to call a dao with transaction demarcation
You can also use a scheduled method with fixedDelay set very high
@Scheduled(fixedDelay = Long.MAX_VALUE)
public void runOnceOnStartup() {
dosomething();
}
This has the advantage that the whole application is wired up (Transactions, Dao, ...)
seen in Scheduling tasks to run once, using the Spring task namespace
The mappedBy
attribute is referencing customer
while the property is mCustomer
, hence the error message. So either change your mapping into:
/** The collection of stores. */
@OneToMany(mappedBy = "mCustomer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<Store> stores;
Or change the entity property into customer
(which is what I would do).
The mappedBy reference indicates "Go look over on the bean property named 'customer' on the thing I have a collection of to find the configuration."
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
You can send your data like the "POST" request through the "HEADERS".
Something like this:
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
headers: ['id1':1, 'id2':2, 'id3':3],
data: "",
contentType: "text/plain",
dataType: "json",
success: onSuccess,
error: onError
});
A number of things can cause session state to mysteriously disappear.
-
If you are using IIS 7 or 7.5, here are a few things to look for:
If you are using IIS 6, the same settings apply (for the most part but with different ways of getting to them), however getting them to log the recycles is more of a pain. Here is a link to a way to get IIS 6 to log AppPool recycle events:
-
If you are updating files on your web app, you should expect all session to be lost. That's just the nature of the beast. However, you might not expect it to happen multiple times. If you update 15 or more files (aspx, dll, etc), there is a likelyhood that you will have multiple restarts over a period of time as these pages are recompiled by users accessing the site. See these two links:
http://support.microsoft.com/kb/319947
Setting the numCompilesBeforeAppRestart to a higher number (or manually bouncing your AppPool) will eliminate this issue.
-
You can always handle Application_SessionStart and Application_SessionEnd to be notified when a session is created or ended. The HttpSessionState class also has an IsNewSession property you can check on any page request to determine if a new session is created for the active user.
-
Finally, if it's possible in your circumstance, I have used the SQL Server session mode with good success. It's not recommended if you are storing a large amount of data in it (every request loads and saves the full amount of data from SQL Server) and it can be a pain if you are putting custom objects in it (as they have to be serializable), but it has helped me in a shared hosting scenario where I couldn't configure my AppPool to not recycle couple hours. In my case, I stored limited information and it had no adverse performance effect. Add to this the fact that an existing user will reuse their SessionID by default and my users never noticed the fact that their in-memory Session was dropped by an AppPool recycle because all their state was stored in SQL Server.
You can create a linked server and reference the table in the other instance using its fully qualified Server.Catalog.Schema.Table name.
# You can install xclip using `apt-get`
apt-get install xclip
# or `pacman`
pacman -S xclip
# or `dnf`
dnf install xclip
If you do not have access to apt-get
nor pacman
, nor dnf
, the sources are available on sourceforge.
In ~/.bash_aliases
, add:
alias setclip="xclip -selection c"
alias getclip="xclip -selection c -o"
Do not forget to load your new configuration using . ~/.bash_aliases
or by restarting your profile.
In ~/.config/fish/config.fish
, add:
abbr setclip "xclip -selection c"
abbr getclip "xclip -selection c -o"
Do not forget to restart your fish instance by restarting your terminal for changes to apply.
You can now use setclip
and getclip
, e.g:
$ echo foo | setclip
$ getclip
foo
You need to make the changes in the binding configuration (in the app.config file) on the SERVER and the CLIENT, or it will not take effect.
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding maxReceivedMessageSize="2147483647 " max...=... />
</basicHttpBinding>
</bindings>
</system.serviceModel>
For JavaScript arrays, you use push()
.
var a = [];
a.push(12);
a.push(32);
For jQuery objects, there's add()
.
$('div.test').add('p.blue');
Note that while push()
modifies the original array in-place, add()
returns a new jQuery object, it does not modify the original one.
I had the same problem and I found papermill. The advantages against the others solutions is that you can see the results while the notebook is running. I find this feature interesting when the notebook takes very long. It is very easy to use:
pip install papermill
papermill notebook.ipynb output.ipynb
It has also, other handy options as saving the output file to Amazon S3, Google Cloud, etc. See the page for more information.
From pandas 1.1 you have better control over this behavior, NA values are now allowed in the grouper using dropna=False
:
pd.__version__
# '1.1.0.dev0+2004.g8d10bfb6f'
# Example from the docs
df
a b c
0 1 2.0 3
1 1 NaN 4
2 2 1.0 3
3 1 2.0 2
# without NA (the default)
df.groupby('b').sum()
a c
b
1.0 2 3
2.0 2 5
# with NA
df.groupby('b', dropna=False).sum()
a c
b
1.0 2 3
2.0 2 5
NaN 1 4