Apparently, you cannot just set an elevation on a View and have it appear. You also need to specify a background.
The following lines added to my LinearLayout finally showed a shadow:
android:background="@android:color/white"
android:elevation="10dp"
This worked for me but only after forcing the specific verbs to be handled by the default handler.
<system.web>
...
<httpHandlers>
...
<add path="*" verb="OPTIONS" type="System.Web.DefaultHttpHandler" validate="true"/>
<add path="*" verb="TRACE" type="System.Web.DefaultHttpHandler" validate="true"/>
<add path="*" verb="HEAD" type="System.Web.DefaultHttpHandler" validate="true"/>
You still use the same configuration as you have above, but also force the verbs to be handled with the default handler and validated. Source: http://forums.asp.net/t/1311323.aspx
An easy way to test is just to deny GET and see if your site loads.
All the code is client side, I hope you fine this helpful:
First thing there are 3 functions we will use:
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function DeleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}
Now we will start with the page load:
$(window).load(function () {
//if IsRefresh cookie exists
var IsRefresh = getCookie("IsRefresh");
if (IsRefresh != null && IsRefresh != "") {
//cookie exists then you refreshed this page(F5, reload button or right click and reload)
//SOME CODE
DeleteCookie("IsRefresh");
}
else {
//cookie doesnt exists then you landed on this page
//SOME CODE
setCookie("IsRefresh", "true", 1);
}
})
I did some benchmarks to compare the execution time of COUNT(*)
vs COUNT(id)
(id is the primary key of the table - indexed).
Number of trials: 10 * 1000 queries
Results:
COUNT(*)
is faster 7%
VIEW GRAPH: benchmarkgraph
My advice is to use: SELECT COUNT(*) FROM table
In Asp.Net Core you can edit the web.config files like so:
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
You can remove the server header in the Kestrel options:
.UseKestrel(c =>
{
// removes the server header
c.AddServerHeader = false;
})
Most OLD c++ and c functions, when deal with strings, use const char*
.
With STL and std::string
, string.c_str()
is introduced to be able to convert from std::string
to const char*
.
That means that if you promise not to change the buffer, you'll be able to use read only string contents. PROMISE = const char*
Try this:
public class MyVmBase : INotifyPropertyChanged
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler( MyAction));
}
}
public void MyAction(object message)
{
if(message == null)
{
Notify($"Method {message} not defined");
return;
}
switch (message.ToString())
{
case "btnAdd":
{
btnAdd_Click();
break;
}
case "BtnEdit_Click":
{
BtnEdit_Click();
break;
}
default:
throw new Exception($"Method {message} not defined");
break;
}
}
}
public class CommandHandler : ICommand
{
private Action<object> _action;
private Func<object, bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action<object> action, Func<object, bool> canExecute)
{
if (action == null) throw new ArgumentNullException(nameof(action));
_action = action;
_canExecute = canExecute ?? (x => true);
}
public CommandHandler(Action<object> action) : this(action, null)
{
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_action(parameter);
}
public void Refresh()
{
CommandManager.InvalidateRequerySuggested();
}
}
And in xaml:
<Button
Command="{Binding ClickCommand}"
CommandParameter="BtnEdit_Click"/>
is that what your looking for?
<table border="1">
<tr>
<th scope="col">Header</th>
<th scope="col">Header</th>
<th scope="col" colspan="2">Header</th>
</tr>
<tr>
<th scope="row"> </th>
<td> </td>
<td>Split this one</td>
<td>into two columns</td>
</tr>
</table>
It is a security issue, so to fix it simply do the following:
i++ is post increment. The increment takes place after the value is returned.
Ulrich Drepper's paper on "How to Write Shared Libraries" is also good resource that details how best to take advantage of shared libraries, or what he refers to as "Dynamic Shared Objects" (DSOs). It focuses more on shared libraries in the ELF binary format, but some discussions are suitable for Windows DLLs as well.
I got confused by this also. There are two commands relevant here:
docker run Run a command in a new container
docker start Start one or more stopped containers
Yes, you can use jQuery to make this done, the idea is
Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.
<form name="input" action="handle_email.php" method="post">
<input type="hidden" name="email" id="email" />
<input type="submit" value="Submit" />
</form>
<script>
$("form").submit(function() {
var emailFromOtherTextBox = $("#email_textbox").val();
$("#email").val(emailFromOtherTextBox );
return true;
});
</script>
also see http://api.jquery.com/submit/
Copying the ".txt" file from one folder to another is very simple and question contains the logic. Only missing part is substituting with right information as below:
import os, shutil, glob
src_fldr = r"Source Folder/Directory path"; ## Edit this
dst_fldr = "Destiantion Folder/Directory path"; ## Edit this
try:
os.makedirs(dst_fldr); ## it creates the destination folder
except:
print "Folder already exist or some error";
below lines of code will copy the file with *.txt extension files from src_fldr to dst_fldr
for txt_file in glob.glob(src_fldr+"\\*.txt"):
shutil.copy2(txt_file, dst_fldr);
Unix will only run commands if they are available on the system path, as you can view by the $PATH variable
echo $PATH
Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such
./my-exec
Where my-exec
is the name of your program.
Matlab code of two methods that have been published in highly regarded journals (IEEE Transactions on Image Processing) are available here: https://ivulab.asu.edu/software
check the CPBDM and JNBM algorithms. If you check the code it's not very hard to be ported and incidentally it is based on the Marzialiano's method as basic feature.
A javascript fix to apply the 'active' class to all labels that are parents of checked inputs:
$(':input:checked').parent('.btn').addClass('active');
insert right after
$('.btn').button();
Check \httpdocs\bootstrap\cache\config.php file in plesk to see if there are some unwanted paths.
You need to give a function to be called after the time delay as the second argument to after
:
after(delay_ms, callback=None, *args)
Registers an alarm callback that is called after a given time.
So what you really want to do is this:
tiles_letter = ['a', 'b', 'c', 'd', 'e']
def add_letter():
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
root.after(0, add_letter) # add_letter will run as soon as the mainloop starts.
root.mainloop()
You also need to schedule the function to be called again by repeating the call to after
inside the callback function, since after
only executes the given function once. This is also noted in the documentation:
The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself
Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter
, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter
to make sure the list isn't empty, and just return
if it is:
def add_letter():
if not tiles_letter:
return
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
Live-Demo: repl.it
You say you cannot convert the numbers into int because the array can contain elements that cannot be converted to int, but there is no harm in trying:
string[] things = new string[] { "105", "101", "102", "103", "90", "paul", "bob", "lauren", "007", "90" };
Array.Sort(things, CompareThings);
foreach (var thing in things)
Debug.WriteLine(thing);
Then compare like this:
private static int CompareThings(string x, string y)
{
int intX, intY;
if (int.TryParse(x, out intX) && int.TryParse(y, out intY))
return intX.CompareTo(intY);
return x.CompareTo(y);
}
Output: 007, 90, 90, 101, 102, 103, 105, bob, lauren, paul
You can also use Rsync
and find
. For find
:
find $FOLDER -type f | cut -d/ -f2- | sort > /tmp/file_list_$FOLDER
But files with the same names and in the same subfolders, but with different content, will not be shown in the lists.
If you are a fan of GUI, you may check Meld that @Alexander mentioned. It works fine in both windows and linux.
It's quite simple, when explained in C#/Java terms:
A monad is a function that takes arguments and returns a special type.
The special type that this monad returns is also called monad. (A monad is a combination of #1 and #2)
There's some syntactic sugar to make calling this function and conversion of types easier.
A monad is useful to make the life of the functional programmer easier. The typical example: The Maybe
monad takes two parameters, a value and a function. It returns null
if the passed value is null
. Otherwise it evaluates the function. If we needed a special return type, we would call this return type Maybe
as well. A very crude implementation would look like this:
object Maybe(object value, Func<object,object> function)
{
if(value==null)
return null;
return function(value);
}
This is spectacularly useless in C# because this language lacks the required syntactic sugar to make monads useful. But monads allow you to write more concise code in functional programming languages.
Oftentimes programmers call monads in chains, like so:
var x = Maybe(x, x2 => Maybe(y, y2 => Add(x2, y2)));
In this example the Add
method would only be called if x
and y
are both non-null
, otherwise null
will be returned.
To answer the original question: A monad is a function AND a type. Like an implementation of a special interface
.
Regular expressions are your friends:
R> ## also adds missing ')' and sets column name
R> group<-data.frame(group=c("12357e", "12575e", "197e18", "e18947")) )
R> group
group
1 12357e
2 12575e
3 197e18
4 e18947
Now use gsub()
with the simplest possible replacement pattern: empty string:
R> group$groupNoE <- gsub("e", "", group$group)
R> group
group groupNoE
1 12357e 12357
2 12575e 12575
3 197e18 19718
4 e18947 18947
R>
Sometimes you don't have the luxury of indexing, or perhaps you want to reverse the results of a Linq query, or maybe you don't want to modify the source collection, if any of these are true, Linq can help you.
A Linq extension method using anonymous types with Linq Select to provide a sorting key for Linq OrderByDescending;
public static IEnumerable<T> Invert<T>(this IEnumerable<T> source)
{
var transform = source.Select(
(o, i) => new
{
Index = i,
Object = o
});
return transform.OrderByDescending(o => o.Index)
.Select(o => o.Object);
}
Usage:
var eable = new[]{ "a", "b", "c" };
foreach(var o in eable.Invert())
{
Console.WriteLine(o);
}
// "c", "b", "a"
It is named "Invert" because it is synonymous with "Reverse" and enables disambiguation with the List Reverse implementation.
It is possible to reverse certain ranges of a collection too, since Int32.MinValue and Int32.MaxValue are out of the range of any kind of collection index, we can leverage them for the ordering process; if an element index is below the given range, it is assigned Int32.MaxValue so that its order doesn't change when using OrderByDescending, similarly, elements at an index greater than the given range, will be assigned Int32.MinValue, so that they appear to the end of the ordering process. All elements within the given range are assigned their normal index and are reversed accordingly.
public static IEnumerable<T> Invert<T>(this IEnumerable<T> source, int index, int count)
{
var transform = source.Select(
(o, i) => new
{
Index = i < index ? Int32.MaxValue : i >= index + count ? Int32.MinValue : i,
Object = o
});
return transform.OrderByDescending(o => o.Index)
.Select(o => o.Object);
}
Usage:
var eable = new[]{ "a", "b", "c", "d" };
foreach(var o in eable.Invert(1, 2))
{
Console.WriteLine(o);
}
// "a", "c", "b", "d"
I'm not sure of the performance hits of these Linq implementations versus using a temporary List to wrap a collection for reversing.
At time of writing, I was not aware of Linq's own Reverse implementation, still, it was fun working this out. https://msdn.microsoft.com/en-us/library/vstudio/bb358497(v=vs.100).aspx
JaredPar's code works but only for one level of inheritance. For unlimited levels of inheritance, use the following code
public bool IsTypeDerivedFromGenericType(Type typeToCheck, Type genericType)
{
if (typeToCheck == typeof(object))
{
return false;
}
else if (typeToCheck == null)
{
return false;
}
else if (typeToCheck.IsGenericType && typeToCheck.GetGenericTypeDefinition() == genericType)
{
return true;
}
else
{
return IsTypeDerivedFromGenericType(typeToCheck.BaseType, genericType);
}
}
The $queryString property mentioned will probably only return the query passed in, without the parameters replaced with their values. In .Net, I have the catch part of my query executer do a simple search replace on the parameters with their values which was supplied so that the error log can show actual values that were being used for the query. You should be able to enumerate the parameters in PHP, and replace the parameters with their assigned value.
I ran into this type error by updating the Xcode version to 8.0,
and under the Code signing is required for product type 'Application' in SDK 'iOS 10.0'
There is a warning:
isn't code signed but requires entitlements. It is not possible to add entitlements to a binary without signing it.
My solution is go to the TARGET ? General ? Signing -> click the Enable signing... button, and I solved the issue.
To get the lines that contain the texts 8768
, 9875
or 2353
, use:
^.*(8768|9875|2353).*$
What it means:
^ from the beginning of the line
.* get any character except \n (0 or more times)
(8768|9875|2353) if the line contains the string '8768' OR '9875' OR '2353'
.* and get any character except \n (0 or more times)
$ until the end of the line
If you do want the literal *
char, you'd have to escape it:
^.*(\*8768|\*9875|\*2353).*$
Git 1.7.0 has “sparse checkouts”. See “core.sparseCheckout” in the git config manpage, “Sparse checkout” in the git read-tree manpage, and “Skip-worktree bit” in the git update-index manpage.
The interface is not as convenient as SVN’s (e.g. there is no way to make a sparse checkout at the time of an initial clone), but the base functionality upon which simpler interfaces could be built is now available.
If you need to see your partitions and/or filers with available space, mentioned utilities are what you need. You just need to use options.
For instance: df -h
will print you those information in "human-readable" form. If you need information only about free space, you could use: df -h | awk '{print $1" "$4}'
.
Create proxy.conf.json
and paste this configuration
{
"/api/*":
{
"target": "http://localhost:7070/your api project name/",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
Replace:
let url = 'api/'+ your path;
Run from CLI:
ng serve --host port.number —-proxy-config proxy.conf.json
/!\ Best anwser is not correct, is_numeric() returns true for integer AND all numeric forms like "9.1"
For integer only you can use the unfriendly preg_match('/^\d+$/', $var) or the explicit and 2 times faster comparison :
if ((int) $var == $var) {
// $var is an integer
}
PS: i know this is an old post but still the third in google looking for "php is integer"
If you want to just run a quick code snippet you can use the -r option:
php -r "echo 'hi';"
-r allows to run code without using script tags <?..?>
You need to check for the parameter being blank: if "%~1"=="" goto blank
Once you've done that, then do an if/else switch on -b: if "%~1"=="-b" (goto specific) else goto unknown
Surrounding the parameters with quotes makes checking for things like blank/empty/missing parameters easier. "~" ensures double quotes are stripped if they were on the command line argument.
If running
source ~/.bashrc
results in "No such file or directory"
On windows:
source <pasteCopiedPathHere>
-> for example: source "C:\Users\John\.bashhrc"
Importing a whole library seems inefficient when all you need is essentially two lines of code...
$ldap = ldap_connect("ldap.example.com");
if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['password'])) {
// log them in!
} else {
// error message
}
In xml add
<ListView android:longClickable="true">
In java file
lv.setLongClickable(true)
try this setOnItemLongClickListener()
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long l) {
//final String category = "Position at : "+pos;
final String category = ((TextView) view.findViewById(R.id.textView)).getText().toString();
Toast.makeText(getActivity(),""+category,Toast.LENGTH_LONG).show();
args = new Bundle();
args.putString("category", category);
return false;
}
});
To get class name you can use ReflectionClass
class MyClass {
public function myNameIs(){
return (new \ReflectionClass($this))->getShortName();
}
}
This works fine for Laravel 5.6
<?php echo "$text"; ?>
In a different way
{!! $text !!}
It will not render HTML code and print as a string.
For more details open link:- Display HTML with Blade
Web Applications generate 3 different types of pop-ups; namely,
1| JavaScript PopUps
2| Browser PopUps
3| Native OS PopUps [e.g., Windows Popup like Upload/Download]
In General, the JavaScript pop-ups are generated by the web application code. Selenium provides an API to handle these JavaScript pop-ups, such as Alert
.
Eventually, the simplest way to ignore Browser pop-up and download files is done by making use of Browser profiles; There are couple of ways to do this:
Before you start working with pop-ups on Browser profiles, make sure that the Download options are set default to Save File.
(Open Firefox) Tools > Options > Applications
Make use of the below snippet and do edits whenever necessary.
FirefoxProfile profile = new FirefoxProfile();
String path = "C:\\Test\\";
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir", path);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.focusWhenStarting", false);
profile.setPreference("browser.download.useDownloadDir", true);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.useWindow", false);
profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
profile.setPreference("pdfjs.disabled", true);
driver = new FirefoxDriver(profile);
On MacOS you may also just stop Dropbox, make your changes and then relaunch Dropbox. I am using the following combination and am quite happy with it:
In both (your local git managed project directory and your remote git repository located on Dropbox) run the following command to disable auto-packing (which is the main problem with dropbox syncing)
git config --global gc.auto 0
Then from time to time, compress the repositories with dropbox disabled. For example I do the following in my bash-build-script whenever I make new releases of my apps.
osascript -e "tell application \"Dropbox\" to quit"
# Compress local
git gc --prune=now; git repack -a -d
# Compress remote
REPOS_DIR_REMOTE=`git remote get-url --push origin`
cd "${REPOS_DIR_REMOTE}"
git gc --prune=now; git repack -a -d
osascript -e "tell application \"Dropbox\" to launch"
osascript -e "display notification with title \"Compress Done\""
Just use os.path.join
to join your path with the filename and extension. Use sys.argv
to access arguments passed to the script when executing it:
#!/usr/bin/env python3
# coding: utf-8
# import netCDF4 as nc
import numpy as np
import numpy.ma as ma
import csv as csv
import os.path
import sys
basedir = '/data/reu_data/soil_moisture/'
suffix = 'nc'
def read_fid(filename):
fid = nc.MFDataset(filename,'r')
fid.close()
return fid
def read_var(file, varname):
fid = nc.Dataset(file, 'r')
out = fid.variables[varname][:]
fid.close()
return out
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please specify a year')
else:
filename = os.path.join(basedir, '.'.join((sys.argv[1], suffix)))
time = read_var(ncf, 'time')
lat = read_var(ncf, 'lat')
lon = read_var(ncf, 'lon')
soil = read_var(ncf, 'soilw')
Simply run the script like:
# on windows-based systems
python script.py year
# on unix-based systems
./script.py year
2017 update: use toLocaleDateString and toLocaleTimeString to format dates and times. The first parameter passed to these methods is a locale value, such as en-us. The second parameter, where present, specifies formatting options, such as the long form for the weekday.
let date = new Date(); _x000D_
let options = { _x000D_
weekday: "long", year: "numeric", month: "short", _x000D_
day: "numeric", hour: "2-digit", minute: "2-digit" _x000D_
}; _x000D_
_x000D_
console.log(date.toLocaleTimeString("en-us", options));
_x000D_
Output : Wednesday, Oct 25, 2017, 8:19 PM
Please refer below link for more details.
document.getElementById("whatever").className += "classToKeep";
With the plus sign ('+') appending the class as opposed to overwriting any existing classes
System environment variables are globally accessed by all users.
User environment variables are specific only to the currently logged-in user.
I was searching a solution to get height and width of an image using JavaScript. I found many, but all those solutions only worked when the image was present in browser cache.
Finally I found a solution to get the image height and width even if the image does not exist in the browser cache:
<script type="text/javascript">
var imgHeight;
var imgWidth;
function findHHandWW() {
imgHeight = this.height;
imgWidth = this.width;
return true;
}
function showImage(imgPath) {
var myImage = new Image();
myImage.name = imgPath;
myImage.onload = findHHandWW;
myImage.src = imgPath;
}
</script>
Thanks,
Binod Suman
http://binodsuman.blogspot.com/2009/06/how-to-get-height-and-widht-of-image.html
you can use File to return a file like View, Content etc
public ActionResult PrintDocInfo(string Attachment)
{
string test = Attachment;
if (test != string.Empty || test != "" || test != null)
{
string filename = Attachment.Split('\\').Last();
string filepath = Attachment;
byte[] filedata = System.IO.File.ReadAllBytes(Attachment);
string contentType = MimeMapping.GetMimeMapping(Attachment);
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
else { return Content("<h3> Patient Clinical Document Not Uploaded</h3>"); }
}
The methods above work great. If you're using apache commons (org.apache.commons.math.random) check out RandomData. It has a method: nextLong(long lower, long upper)
Java Beans are not the same thing as EJBs.
The JavaBeans specification in Java 1.0 was Sun's attempt to allow Java objects to be manipulated in an IDE that looked like VB. There were rules laid down for objects that qualified as "Java Beans":
EJBs came later. They combine distributed components and a transactional model, running in a container that manages threads, pooling, life cycle, and provides services. They are a far cry from Java Beans.
DTOs came about in the Java context because people found out that the EJB 1.0 spec was too "chatty" with the database. Rather than make a roundtrip for every data element, people would package them into Java Beans in bulk and ship them around.
POJOs were a reaction against EJBs.
Whilst I'm sure POCO means Plain Old Class Object or Plain Old C Object to 99.9% of people here, POCO is also Animator Pro's (Autodesk) built in scripting language.
One more approach to consider:
When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.
$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
// non-repetitive markup code here
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
Edit: By request, I added a check to make sure the value entered was within the ASCII range of 0 to 127. Whether you want to limit this is up to you. In C# (and I believe .NET in general), char
s are represented using UTF-16, so any valid UTF-16 character value could be cast into it. However, it is possible a system does not know what every Unicode character should look like so it may show up incorrectly.
// Read a line of input
string input = Console.ReadLine();
int value;
// Try to parse the input into an Int32
if (Int32.TryParse(input, out value)) {
// Parse was successful
if (value >= 0 and value < 128) {
//value entered was within the valid ASCII range
//cast value to a char and print it
char c = (char)value;
Console.WriteLine(c);
}
}
Code:
if [[ -e $1 && ! -e $2 ]]; then
mkdir --parents --verbose -- "$(dirname -- "$2")"
fi
mv --verbose -- "$1" "$2"
Example:
arguments: "d1" "d2/sub"
mkdir: created directory 'd2'
renamed 'd1' -> 'd2/sub'
img {
max-width: 100%;
}
Should set the image to take up 100% of its containing element.
Based on gbinflames' answer, I kept the POST and URL, so that the form would continue to work for those with JS off.
<form class="myform" action="http://XXXXXXXXXlist-manage2.com/subscribe/post" method="POST">
<input type="hidden" name="u" value="XXXXXXXXXXXXXXXX">
<input type="hidden" name="id" value="XXXXXXXXX">
<input class="input" type="text" value="" name="MERGE1" placeholder="First Name" required>
<input type="submit" value="Send" name="submit" id="mc-embedded-subscribe">
</form>
Then, using jQuery's .submit() changed the type, and URL to handle JSON repsonses.
$('.myform').submit(function(e) {
var $this = $(this);
$.ajax({
type: "GET", // GET & url for json slightly different
url: "http://XXXXXXXX.list-manage2.com/subscribe/post-json?c=?",
data: $this.serialize(),
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, parse data.msg string and display message
} else {
// It worked, so hide form and display thank-you message.
}
}
});
return false;
});
We can force vbscript always run with 32 bit mode by changing "system32" to "sysWOW64" in default value of key "Computer\HKLM\SOFTWARE]\Classes\VBSFile\Shell\Open\Command"
If you have a weighted dictionary instead of a list you can write this
items = { "a": 10, "b": 5, "c": 1 }
random.choice([k for k in items for dummy in range(items[k])])
Note that [k for k in items for dummy in range(items[k])]
produces this list ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'b', 'b', 'b', 'b', 'b']
Spring sets the default content-type to octet-stream
when the response is missing that field. All you need to do is to add a message converter to fix this.
For Windows Server 2012, the solution is very similar to faester's (see above). From the Server Manager, click on Add roles and features
, select the appropriate server, then select Features
. Under .NET Framework 4.5 Features
, you'll see WCF Services
, and under that, you'll find HTTP Activation
.
If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.
If you already have a table pre_loaded_tbl with some data. You can use a trick to load the data into your table with following query
INSERT INTO TABLE tweet_table
SELECT "my_data" AS my_column
FROM pre_loaded_tbl
LIMIT 5;
Also please note that "my_data" is independent of any data in the pre_loaded_tbl. You can select any data and write any column name (here my_data and my_column). Hive does not require it to have same column name. However structure of select statement should be same as that of your tweet_table. You can use limit to determine how many times you can insert into the tweet_table.
However if you haven't' created any table, you will have to load the data using file copy or load data commands in above answers.
I was having a problem where setting element.Visible = true in my code behind wasn't having any effect on the actual screen. The solution for me was to wrap the area of my page where I wanted to show the div in an ASP UpdatePanel, which is used to cause partial screen updates.
http://msdn.microsoft.com/en-us/library/bb399001.aspx
Having the element runat=server gave me access to it from the codebehind, and placing it in the UpdatePanel let it actually be updated on the screen.
java can not support multiple inheritence.but u can do this in this way
class X
{
}
class Y extends X
{
}
class Z extends Y{
}
This will handle negative numbers, fractions, string, everything:
ORDER BY ISNUMERIC(col) DESC, Try_Parse(col AS decimal(10,2)), col;
LaTeX will usually not indent the first paragraph of a section. This is standard typographical practice. However, if you really want to override this default setting, use the package indentfirst available on CTAN.
You can always cancel()
the Notification
from whatever is being invoked by the action (e.g., in onCreate()
of the activity tied to the PendingIntent
you supply to addAction()
).
Yes! Here is how you set it up.
Create a Remote run configuration:
The configuration above provides three read-only fields. These are options that tell the JVM to open up port 5005 for remote debugging when running your application. Add the appropriate one to the JVM options of the application you are debugging. One way you might do this would be like so:
export JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
But it depends on how your run your application. If you're not sure which of the three applies to you, start with the first and go down the list until you find the one that works.
You can change suspend=n
to suspend=y
to force your application to wait until you connect with IntelliJ before it starts up. This is helpful if the breakpoint you want to hit occurs on application startup.
Start your application as you would normally, then in IntelliJ select the new configuration and hit 'Debug'.
IntelliJ will connect to the JVM and initiate remote debugging.
You can now debug the application by adding breakpoints to your code where desired. The output of the application will still appear wherever it did before, but your breakpoints will hit in IntelliJ.
To get the first n
elements of an array, use
array.slice(0, n);
Error 4 means "The cause was a user-mode read resulting in no page being found.". There's a tool that decodes it here.
Here's the definition from the kernel. Keep in mind that 4 means that bit 2 is set and no other bits are set. If you convert it to binary that becomes clear.
/*
* Page fault error code bits
* bit 0 == 0 means no page found, 1 means protection fault
* bit 1 == 0 means read, 1 means write
* bit 2 == 0 means kernel, 1 means user-mode
* bit 3 == 1 means use of reserved bit detected
* bit 4 == 1 means fault was an instruction fetch
*/
#define PF_PROT (1<<0)
#define PF_WRITE (1<<1)
#define PF_USER (1<<2)
#define PF_RSVD (1<<3)
#define PF_INSTR (1<<4)
Now then, "ip 00007f9bebcca90d" means the instruction pointer was at 0x00007f9bebcca90d when the segfault happened.
"libQtWebKit.so.4.5.2[7f9beb83a000+f6f000]" tells you:
If you take the base address and subtract it from the ip, you get the offset into that object:
0x00007f9bebcca90d - 0x7f9beb83a000 = 0x49090D
Then you can run addr2line on it:
addr2line -e /usr/lib64/qt45/lib/libQtWebKit.so.4.5.2 -fCi 0x49090D
??
??:0
In my case it wasn't successful, either the copy I installed isn't identical to yours, or it's stripped.
It looks like windows tries to run the script using its own EXE framework rather than call it like
python /the/script.py
Try,
subprocess.Popen(["python", "/the/script.py"])
Edit: "python" would need to be on your path.
I resolved my problem through this below:
compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0'){
exclude module: 'log4j-slf4j-impl'
exclude module: 'logback-classic'
}
compile('org.springframework.boot:spring-boot-starter-web'){
exclude module: 'log4j-slf4j-impl'
exclude module: 'logback-classic'
}
As others have noted, most likely you don't have .html
set up to handle php code.
Having said that, if all you're doing is using index.html
to include index.php
, your question should probably be 'how do I use index.php
as index document?
In which case, for Apache (httpd.conf), search for DirectoryIndex
and replace the line with this (will only work if you have dir_module
enabled, but that's default on most installs):
DirectoryIndex index.php
If you use other directory indexes, list them in order of preference i.e.
DirectoryIndex index.php index.phtml index.html index.htm
You also could allocate using new
and initialize all fields by hand
package main
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := new(Configuration)
c.Val = "test"
c.Proxy.Address = "addr"
c.Proxy.Port = "80"
}
See in playground: https://play.golang.org/p/sFH_-HawO_M
The next solution helped me. Add to build.gradle
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
I only put this in for completeness. I've learned plenty from marius and mdml. Here are the edge weights. Sorry about the arrows. Looks like I'm not the only one saying it can't be helped. I couldn't render this with ipython notebook I had to go straight from python which was the problem with getting my edge weights in sooner.
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab
G = nx.DiGraph()
G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2)
G.add_edges_from([('B','C'),('E','F')], weight=3)
G.add_edges_from([('C','F')], weight=4)
val_map = {'A': 1.0,
'D': 0.5714285714285714,
'H': 0.0}
values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_labels=dict([((u,v,),d['weight'])
for u,v,d in G.edges(data=True)])
red_edges = [('C','D'),('D','A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]
pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()
git apply --reverse --reject example.patch
When you created a patch file with the branch names reversed:
ie. git diff feature_branch..master
instead of git diff master..feature_branch
"WORKSPACE" environment variable works for the latest version of Jenkins Pipeline. You can use this in your Jenkins file: "${env.WORKSPACE}"
Sample use below:
def files = findFiles glob: '**/reports/*.json'
for (def i=0; i<files.length; i++) {
jsonFilePath = "${files[i].path}"
jsonPath = "${env.WORKSPACE}" + "/" + jsonFilePath
echo jsonPath
hope that helps!!
Do statement as below:
ActiveSheet.Cells(ActiveWindow.SplitRow+1,ActiveWindow.SplitColumn+1).Select
From the output of "ps aux | grep docker", it looks like docker daemon is not running. Try using below methods to see what is wrong and why docker is not starting
$ sudo tail -f /var/log/upstart/docker.log
$ sudo docker -d -D
You can either use -FLT_MAX
(or -DBL_MAX
) for the maximum magnitude negative number and FLT_MAX
(or DBL_MAX
) for positive. This gives you the range of possible float (or double) values.
You probably don't want to use FLT_MIN
; it corresponds to the smallest magnitude positive number that can be represented with a float, not the most negative value representable with a float.
FLT_MIN
and FLT_MAX
correspond to std::numeric_limits<float>::min()
and std::numeric_limits<float>::max()
.
Find the below code in xampp/phpmyadmin/config.inc.php
$cfg['Servers'][$i]['controluser'] = 'user_name/root';
$cfg['Servers'][$i]['controlpass'] = 'passwaord';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'user_name/root';
$cfg['Servers'][$i]['password'] = 'password';
Replace each statement above with the corresponding entry below:
$cfg['Servers'][$i]['controluser'] = 'root';
$cfg['Servers'][$i]['controlpass'] = 'xxxx';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'xxxx';
Doing this caused localhost/phpmyadmin in the browser and the MySQL command prompt to work properly.
<script type="text/javascript">
function test()
{
var path = "C:/es/h221.txt";
var pos =path.lastIndexOf( path.charAt( path.indexOf(":")+1) );
alert("pos=" + pos );
var filename = path.substring( pos+1);
alert( filename );
}
</script>
<form name="InputForm"
action="page2.asp"
method="post">
<P><input type="button" name="b1" value="test file button"
onClick="test()">
</form>
Add a string at the end of your URL to break the cache. I usually do (with PHP):
<script src="/my/js/file.js?<?=time()?>"></script>
So that it reloads every time while I'm working on it, and then take it off when it goes into production. In reality I abstract this out a little more but the idea remains the same.
If you check out the source of this website, they append the revision number at the end of the URL in a similar fashion to force the changes upon us whenever they update the javascript files.
The usual way is to use zip()
:
for x, y in zip(a, b):
# x is from a, y is from b
This will stop when the shorter of the two iterables a
and b
is exhausted. Also worth noting: itertools.izip()
(Python 2 only) and itertools.izip_longest()
(itertools.zip_longest()
in Python 3).
On unix systems, you can use the following command to determine where git is installed:
whereis git
If you are using MacOS and did a recent update, it is possible you have to agree to the licence terms again. Try typing 'git' in a terminal, and see if you get the following message:
Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.
Here's how I'd go about it in pure JavaScript, in the most minimal manner I can think of that works in ECMAScript 3 or later. It returns as soon as a match is found.
var getKeyValueById = function(array, key, id) {
var testArray = array.slice(), test;
while(test = testArray.pop()) {
if (test.id === id) {
return test[key];
}
}
// return undefined if no matching id is found in array
return;
}
var myArray = [{'id':'73', 'foo':'bar'}, {'id':'45', 'foo':'bar'}]
var result = getKeyValueById(myArray, 'foo', '45');
// result is 'bar', obtained from object with id of '45'
Use ng-switch with expression and ng-switch-when
for matching expression value:
<div ng-switch="data.id">
<div ng-switch-when="5">...</div>
<div ng-switch-default>...</div>
</div>
In my case, it was not working even after trying all solutions and setting all limits to max. In last I found out that a Microsoft IIS filtering module Url Scan 3.1 was installed on IIS/website, which have it's own limit to reject incoming requests based on content size and return "404 Not found page".
It's limit can be updated in %windir%\System32\inetsrv\urlscan\UrlScan.ini
file by setting MaxAllowedContentLength
to the required value.
For eg. following will allow upto 300 mb requests
MaxAllowedContentLength=314572800
Hope it will help someone!
It's worth noting that perldoc perllocal will only report on modules installed via CPAN. If someone installs modules manually, it won't find them. Also, if you have multiple people installing modules and the perllocal.pod is under source control, people might resolve conflicts incorrectly and corrupt the list (this has happened here at work, for example).
Regrettably, the solution appears to be walking through @INC with File::Find or something similar. However, that doesn't just find the modules, it also finds related modules in a distribution. For example, it would report TAP::Harness and TAP::Parser in addition to the actual distribution name of Test::Harness (assuming you have version 3 or above). You could potentially match them up with distribution names and discard those names which don't match, but then you might be discarding locally built and installed modules.
I believe brian d foy's backpan indexing work is supposed to have code to hand it at .pm file and it will attempt to infer the distribution, but even this fails at times because what's in a package is not necessarily installed (see Devel::Cover::Inc for an example).
If you are using the default template that is created when you select a new ASP.net Web application and selected Individual User accounts as Authentication and trying to create users with Roles so here is the solution. In the Account Controller's Register method which is called using [HttpPost], add the following lines in if condition
.
using Microsoft.AspNet.Identity.EntityFramework;
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
var roleManager = new RoleManager<IdentityRole>(roleStore);
if(!await roleManager.RoleExistsAsync("YourRoleName"))
await roleManager.CreateAsync(new IdentityRole("YourRoleName"));
await UserManager.AddToRoleAsync(user.Id, "YourRoleName");
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
This will create first create a role in your database and then add the newly created user to this role.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button").click(function(){
alert("Hello");
});
});
</script>
<input type="button" id="button" value="Click me">
a=[100,200,300,400,500]
def search(b):
try:
k=a.index(b)
return a[k]
except ValueError:
return 'not found'
print(search(500))
it'll return the object if found else it'll return "not found"
I think there is no out-of-the-box support for that in VS Code.
You can install a plugin to give you similar functionality. Eg.:
https://marketplace.visualstudio.com/items?itemName=micnil.vscode-checkpoints
Or the more famous:
https://marketplace.visualstudio.com/items?itemName=xyz.local-history
Some details may need to be configured: The VS Code search gets confused sometimes because of additional folders created by this type of plugins. You can configure it to ignore such folders or change their locations (adding such folders to your .gitignore
file also solves this problem).
foreach(var newAnimal in NewAnimals)
Animals.Add(newAnimal.Key,newAnimal.Value)
Note: this throws an exception on a duplicate key.
Or if you really want to go the extension method route(I wouldn't), then you could define a general AddRange
extension method that works on any ICollection<T>
, and not just on Dictionary<TKey,TValue>
.
public static void AddRange<T>(this ICollection<T> target, IEnumerable<T> source)
{
if(target==null)
throw new ArgumentNullException(nameof(target));
if(source==null)
throw new ArgumentNullException(nameof(source));
foreach(var element in source)
target.Add(element);
}
(throws on duplicate keys for dictionaries)
No need to do so much of trouble! Its simple
This will create 2 * 3 matrix of string.
var array=[];
var x = 2, y = 3;
var s = 'abcdefg';
for(var i = 0; i<x; i++){
array[i]=new Array();
for(var j = 0; j<y; j++){
array[i].push(s.charAt(counter++));
}
}
I think it is better practice to keep your response under single control and for this reason I found out the most official solution.
response()->json([...])
->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);
add this after namespace
declaration:
use Illuminate\Http\Response;
if (!file_exists('http://example.com/images/thumbnail_1286954822.jpg')) {
$filefound = '0';
}
even it was getting the above error. i found out that IIS was not registered on the server.
registering the iis fixed the issue.
Thanks,
SQL stands for Structured Query Language, and is the basis for which all Relational Database Management Systems allow the user to add, remove, update, or select records. Things like MySQ are the actual Management Systems which allow you to store and retrieve your data, whereas SQL is the actual language to do so.
The basic SQL is somewhat universal - Selects usually look the same, Inserts, Updates, Deletes, etc. Once you get beyond the basics, the commands and abilities of your individual Databases vary, and this is where you get people who are Oracle experts, MySQL, SQL Server, etc.
Basically, MySQL is one of many books holding everything, and SQL is how you go about reading that book.
$(window).load(function() {
$("html, body").animate({ scrollTop: $(document).height() }, 1000);
});
This grabs the height of the page and scrolls it down once the window has loaded. Change the 1000
to whatever you need to do it faster/slower once the page is ready.
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.
For more information read this.
Hope it helps.
You can do it the simple way:
string pathToHTMLFile = @"C:\temp\someFile.html";
string htmlString = File.ReadAllText(pathToHTMLFile);
Or you could stream it in with FileStream/StreamReader:
using (FileStream fs = File.Open(pathToHTMLFile, FileMode.Open, FileAccess.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
htmlString = sr.ReadToEnd();
}
}
This latter method allows you to open the file while still permitting others to perform Read/Write operations on the file. I can't imagine an HTML file being very big, but it has the added benefit of streaming the file instead of capturing it as one large chunk like the first method.
This is a cheeky answer, but if you are constrained to CSS only and able to reverse your items in the DOM, it might be worth considering. It relies on the fact that while there is no selector for the last element of a specific class, it is actually possible to style the first. The trick is to then use flexbox to display the elements in reverse order.
ul {_x000D_
display: flex;_x000D_
flex-direction: column-reverse;_x000D_
}_x000D_
_x000D_
/* Apply desired style to all matching elements. */_x000D_
ul > li.list {_x000D_
background-color: #888;_x000D_
}_x000D_
_x000D_
/* Using a more specific selector, "unstyle" elements which are not the first. */_x000D_
ul > li.list ~ li.list {_x000D_
background-color: inherit;_x000D_
}
_x000D_
<ul>_x000D_
<li class="list">0</li>_x000D_
<li>1</li>_x000D_
<li class="list">2</li>_x000D_
</ul>_x000D_
<ul>_x000D_
<li>0</li>_x000D_
<li class="list">1</li>_x000D_
<li class="list">2</li>_x000D_
<li>3</li>_x000D_
</ul>
_x000D_
It means that the method accepts a variable number of arguments ("varargs") of type JID
. Within the method, recipientJids
is presented.
This is handy for cases where you've a method that can optionally handle more than one argument in a natural way, and allows you to write calls which can pass one, two or three parameters to the same method, without having the ugliness of creating an array on the fly.
It also enables idioms such as sprintf
from C; see String.format()
, for example.
easy if its pdf or img use
return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));
$letters = array("a", "b", "c", "d", "e", "f", "g"); // this array can n no. of values
$result = substr(implode(", ", $letters), 0);
echo $result
output-> a,b,c,d,e,f,g
>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple([list(tup) for tup in zip(*original)])
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])
Gives a tuple of lists as in the question.
list1, list2 = [list(tup) for tup in zip(*original)]
Unpacks the two lists.
increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin
heap size can be changed based on Requirements.
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
I have same issue , i solved issue :
step-1 : download docker-compose using following command.
1. sudo su
2. sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
Step-2 : Run command
chmod +x /usr/local/bin/docker-compose
Step-3 : Check docker-compose version
docker-compose --version
There is a difference between click() and submit().
submit() submits the form and executes the url that is given by the "action" attribute. If you have any javascript-function or jquery-plugin running to submit the form e.g. via ajax, submit() will ignore it. With click() the javascript-functions will be executed.
Depends on what you mean by better. This works if your goal is removal of redundancy.
s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))
RESTful (Representational state transfer) API programming is writing web applications in any programming language by following 5 basic software architectural style principles:
In other words you're writing simple point-to-point network applications over HTTP which uses verbs such as GET, POST, PUT or DELETE by implementing RESTful architecture which proposes standardization of the interface each “resource” exposes. It is nothing that using current features of the web in a simple and effective way (highly successful, proven and distributed architecture). It is an alternative to more complex mechanisms like SOAP, CORBA and RPC.
RESTful programming conforms to Web architecture design and, if properly implemented, it allows you to take the full advantage of scalable Web infrastructure.
What have you tried, what was the problem?
Creating DataColumns
and add values to a DataTable
is straight forward:
Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
dt.Rows.Add(i, "Row #" & i)
Next
Edit:
If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml
.
From what I've learned with Alex Cowan in the course Continuous Delivery & DevOps, CI and CD is part of a product pipeline that consists in the time it goes from an Observations to a Released Product.
From Observations to Designs the goal is to get high quality testable ideas. This part of the process is considered Continuous Design.
What happens after, when we go from the Code onwards, it's considered a Continuous Delivery capability whose aim is to execute the ideas and release to the customer very fast (you can read Jez Humble's book Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation for more details). The following pipeline explains which steps Continuous Integration (CI) and Continuous Delivery (CD) consist of.
Continuous Integration, as Mattias Petter Johansson explains,
is when a software team has habit of doing multiple merges per day and they have an automated verification system in place to check those merges for problems.
(you can watch the following two videos for a more pratical overview using CircleCI - Getting started with CircleCI - Continuous Integration P2 and Running CircleCI on Pull Request).
One can specify the CI/CD pipeline as following, that goes from New Code to a released Product.
The first three steps have to do with Tests, extending the boundary of what's being tested.
Continuous Deployment, on the other hand, is to handle the Deployment automatically. So, any code commit that passes the automated testing phase is automatically released into the production.
Note: This isn't necessarily what your pipelines should look like, yet they can serve as reference.
Try margin: 0 auto
, the div will need a fixed with.
val() should handle both cases
<option value="1">it's me</option>
$('select').val('1'); // selects "it's me"
$('select').val("it's me"); // also selects "it's me"
For me on iOS 5.1.1 on a iPhone 3GS I had to clear the styling of a search field and the set it to the style intended
input[type="search"] {-webkit-appearance: none; border-radius: 0 3px 3px 0;}
Doing -webkit-border-radius: 0;
alone did not clear the native styling. This was also for a webview on a native app.
For Swift 4.2 / Alamofire 4.7.3
Alamofire.upload(multipartFormData: { multipart in
multipart.append(fileData, withName: "payload", fileName: "someFile.jpg", mimeType: "image/jpeg")
multipart.append("comment".data(using: .utf8)!, withName :"comment")
}, to: "endPointURL", method: .post, headers: nil) { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { answer in
print("statusCode: \(answer.response?.statusCode)")
}
upload.uploadProgress { progress in
//call progress callback here if you need it
}
case .failure(let encodingError):
print("multipart upload encodingError: \(encodingError)")
}
}
Also you could take a look at CodyFire lib it makes API calls easier using Codable for everything. Example for Multipart call using CodyFire
//Declare your multipart payload model
struct MyPayload: MultipartPayload {
var attachment: Attachment //or you could use just Data instead
var comment: String
}
// Prepare payload for request
let imageAttachment = Attachment(data: UIImage(named: "cat")!.jpeg(.high)!,
fileName: "cat.jpg",
mimeType: .jpg)
let payload = MyPayload(attachment: imageAttachment, comment: "Some text")
//Send request easily
APIRequest("endpoint", payload: payload)
.method(.post)
.desiredStatus(.created) //201 CREATED
.onError { error in
switch error.code {
case .notFound: print("Not found")
default: print("Another error: " + error.description)
}
}.onSuccess { result in
print("here is your decoded result")
}
//Btw normally it should be wrapped into an extension
//so it should look even easier API.some.upload(payload).onError{}.onSuccess{}
You could take a look at all the examples in lib's readme
Just add android:gravity="right" this line parent layout this will work.
<LinearLayout
android:id="@+id/withdrawbuttonContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary"
android:orientation="horizontal"
**android:gravity="right"**
android:weightSum="5"
android:visibility="visible">
<Button
android:id="@+id/bt_withDraw"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/BTN_ADD"
app:delay="1500" />
<Button
android:id="@+id/btn_orderdetail_amend"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/BTN_CANCEL"
app:delay="1500" />
</LinearLayout>
Another approach is to use ls
when reading the file list within a directory so as to give you what you want, i.e. "just the file name/s". As opposed to reading the full file path and then extracting the "file name" component in the body of the for loop.
Example below that follows your original:
for filename in $(ls /home/user/)
do
echo $filename
done;
If you are running the script in the same directory as the files, then it simply becomes:
for filename in $(ls)
do
echo $filename
done;
No, that's more or less what they're meant to do.
In C (and many other languages), you can insert hard-to-see/type characters using \
notation:
\a
is alert/bell\b
is backspace/rubout\n
is newline\r
is carriage return (return to left margin)\t
is tabYou can also specify the octal value of any character using \0
nnn, or the hexadecimal value of any character with \x
nn.
_
is octal 137, hex 5f, so it can also be typed \0137
or \x5f
, if your keyboard didn't have a _
key or something. This is more useful for control characters like NUL (\0
) and ESC (\033
)As someone posted (then deleted their answer before I could +1 it), there are also some less-frequently-used ones:
\f
is a form feed/new page (eject page from printer)\v
is a vertical tab (move down one line, on the same column)On screens, \f
usually works the same as \v
, but on some printers/teletypes, it will
go all the way to the next form/sheet of paper.
edtFTPnet is a free, fast, open source FTP library for .NET, written in C#.
You might find this link helpful:
http://tldp.org/LDP/abs/html/string-manipulation.html
In general,
To replace the first match of $substring with $replacement:
${string/substring/replacement}
To replace all matches of $substring with $replacement:
${string//substring/replacement}
EDIT: Note that this applies to a variable named $string.
my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)
public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}
}
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
cd "Your File Location without inverted commas"
example : cd C:\Users*****\Desktop\directory\target
java -jar myjar.jar
example bat file looks like this:
@echo OFF
cd C:\Users\****\Desktop\directory\target
java -jar myjar.jar
This will work fine.
Try this, just an example:
u.UserTypeOptions = new SelectList(new[]
{
new { ID="1", Name="name1" },
new { ID="2", Name="name2" },
new { ID="3", Name="name3" },
}, "ID", "Name", 1);
Or
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
},"Value","Text");
Rather than using direct tags, you can edit the css attribute for the color so that any tables you make will have the same color header text.
thead {
color: #FFFFFF;
}
public class DemoFragment extends Fragment {
MapView mapView;
GoogleMap map;
LatLng CENTER = null;
public LocationManager locationManager;
double longitudeDouble;
double latitudeDouble;
String snippet;
String title;
Location location;
String myAddress;
String LocationId;
String CityName;
String imageURL;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater
.inflate(R.layout.fragment_layout, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
setMapView();
}
private void setMapView() {
try {
MapsInitializer.initialize(getActivity());
switch (GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getActivity())) {
case ConnectionResult.SUCCESS:
// Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT)
// .show();
// Gets to GoogleMap from the MapView and does initialization
// stuff
if (mapView != null) {
locationManager = ((LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE));
Boolean localBoolean = Boolean.valueOf(locationManager
.isProviderEnabled("network"));
if (localBoolean.booleanValue()) {
CENTER = new LatLng(latitude, longitude);
} else {
}
map = mapView.getMap();
if (map == null) {
Log.d("", "Map Fragment Not Found or no Map in it!!");
}
map.clear();
try {
map.addMarker(new MarkerOptions().position(CENTER)
.title(CityName).snippet(""));
} catch (Exception e) {
e.printStackTrace();
}
map.setIndoorEnabled(true);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.zoomTo(5));
if (CENTER != null) {
map.animateCamera(
CameraUpdateFactory.newLatLng(CENTER), 1750,
null);
}
// add circle
CircleOptions circle = new CircleOptions();
circle.center(CENTER).fillColor(Color.BLUE).radius(10);
map.addCircle(circle);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
} catch (Exception e) {
}
}
in fragment_layout
<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_marginRight="10dp" />
IN bootstrap 4 you need to add popper js for tooltip, I also don`t understand why bootstrap 4 includes external popper.js, It means bootstrap makes more complicated instead of easy when upgrading to the latest versions.
You can import popper js before bootstrap on angular or a simple html, Angular import would be like this
npm install popper.js --save
then go to .angular-cli.json and change the order like below.
"scripts": [
"../node_modules/jquery/dist/jquery.slim.min.js",
"../node_modules/tether/dist/js/tether.min.js",
"../node_modules/popper.js/dist/umd/popper.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js"
],
you can also use CDN direct call popper js into your any project.
https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.js https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.min.js
You can specify it in the set cookie function see the php manual
setcookie('Foo','Bar',0,'/', 'www.sample.com' , FALSE, TRUE);
You might no need to having export, just add this line in catalina.sh :
CATALINA_OPTS="-Xms512M -Xmx1024M"
Here is a more modular and cleaner way to circle crop your bitmap in Glide:
BitmapTransformation
then override transform
method like this : For Glide 4.x.x
public class CircularTransformation extends BitmapTransformation {
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(null, toTransform);
circularBitmapDrawable.setCircular(true);
Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
circularBitmapDrawable.draw(canvas);
return bitmap;
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {}
}
For Glide 3.x.x
public class CircularTransformation extends BitmapTransformation {
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(null, toTransform);
circularBitmapDrawable.setCircular(true);
Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
circularBitmapDrawable.draw(canvas);
return bitmap;
}
@Override
public String getId() {
// Return some id that uniquely identifies your transformation.
return "CircularTransformation";
}
}
Glide.with(yourActivity)
.load(yourUrl)
.asBitmap()
.transform(new CircularTransformation())
.into(yourView);
Hope this helps :)
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
That header doesn't exist in standard C++. It was part of some pre-1990s compilers, but it is certainly not part of C++.
Use #include <iostream>
instead. And all the library classes are in the std::
namespace, for example std::cout
.
Also, throw away any book or notes that mention the thing you said.
Sometimes in situations like this I miss my youth, when Access was my poison of choice, and I could give each radio button in a group its own value.
My hack in C# is to use the tag to set the value, and when I make a selection from the group, I read the value of the tag of the selected radiobutton. In this example, directionGroup is the group in which I have four five radio buttons with "None" and "NE", "SE", "NW" and "SW" as the tags on the other four radiobuttons.
I proactively used a button to capture the value of the checked button, because because assigning one event handler to all of the buttons' CHeckCHanged event causes EACH button to fire, because changing one changes them all. So the value of sender is always the first RadioButton in the group. Instead, I use this method when I need to find out which one is selected, with the values I want to retrieve in the Tag property of each RadioButton.
private void ShowSelectedRadioButton()
{
List<RadioButton> buttons = new List<RadioButton>();
string selectedTag = "No selection";
foreach (Control c in directionGroup.Controls)
{
if (c.GetType() == typeof(RadioButton))
{
buttons.Add((RadioButton)c);
}
}
var selectedRb = (from rb in buttons where rb.Checked == true select rb).FirstOrDefault();
if (selectedRb!=null)
{
selectedTag = selectedRb.Tag.ToString();
}
FormattableString result = $"Selected Radio button tag ={selectedTag}";
MessageBox.Show(result.ToString());
}
FYI, I have tested and used this in my work.
Joey
This is answered in some of the answers to Can't find how to use HttpContent as well as in this blog post.
In summary, you can't directly set up an instance of HttpContent
because it is an abstract class. You need to use one the classes derived from it depending on your need. Most likely StringContent
, which lets you set the string value of the response, the encoding, and the media type in the constructor. See: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx
As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2))
.
The question is specific to SQL Server, but I would like to extend Martin Smith's answer.
SQL:2003 standard allows to define multiple values for simple case expression:
SELECT CASE c.Number
WHEN '1121231','31242323' THEN 1
WHEN '234523','2342423' THEN 2
END AS Test
FROM tblClient c;
It is optional feature: Comma-separated predicates in simple CASE expression“ (F263).
Syntax:
CASE <common operand>
WHEN <expression>[, <expression> ...] THEN <result>
[WHEN <expression>[, <expression> ...] THEN <result>
...]
[ELSE <result>]
END
As for know I am not aware of any RDBMS that actually supports that syntax.
var sources = images.map(function (img) {
if(img.src.split('.').pop() === "json"){ // if extension is .json
return null; // skip
}
else{
return img.src;
}
}).filter(Boolean);
The .filter(Boolean)
will filter out any falsey values in a given array, which in your case is the null
.
Your problem here is that the dtype of 'Date' remained as str/object. You can use the parse_dates
parameter when using read_csv
import pandas as pd
file = '/pathtocsv.csv'
df = pd.read_csv(file, sep = ',', parse_dates= [col],encoding='utf-8-sig', usecols= ['Date', 'ids'],)
df['Month'] = df['Date'].dt.month
From the documentation for the parse_dates
parameter
parse_dates : bool or list of int or names or list of lists or dict, default False
The behavior is as follows:
- boolean. If True -> try parsing the index.
- list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
- list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column.
- dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’
If a column or index cannot be represented as an array of datetimes, say because of an unparseable value or a mixture of timezones, the column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use
pd.to_datetime
afterpd.read_csv
. To parse an index or column with a mixture of timezones, specifydate_parser
to be a partially-appliedpandas.to_datetime()
withutc=True
. See Parsing a CSV with mixed timezones for more.Note: A fast-path exists for iso8601-formatted dates.
The relevant case for this question is the "list of int or names" one.
col is the columns index of 'Date' which parses as a separate date column.
I use this mnemonic :
a.compareTo(b) < 0 // a < b
a.compareTo(b) > 0 // a > b
a.compareTo(b) == 0 // a == b
You keep the signs and always compare the result of compareTo()
to 0
I asked myself the very same questions. When I looked into it I found the choices overwhelming.
Fortunately I found this excellent spreadsheet that helps you choice the best loader based on your requirements:
https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ
check out jquery ui 1.8.5 it's available here http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js and it has the new button for dialog ui implementation
If the array is statically allocated, use sizeof(array) / sizeof(array[0])
If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0])
(which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.
For,Adding System.Drawing Follow some steps: Firstly, right click on the solution and click on add Reference. Secondly, Select the .NET Folder. And then double click on the Using.System.Drawing;
I have same problem and i found solution which is given below with full datepicker using simple HTML,Javascript and CSS. In this code i prepare formate like dd/mm/yyyy but you can work any.
HTML Code:
<body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>
CSS Code:
#dt{text-indent: -500px;height:25px; width:200px;}
Javascript Code :
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}
Output:
The following example shows how to pass variables between siblings controllers and take an action when the value changes.
Use case example: you have a filter in a sidebar that changes the content of another view.
angular.module('myApp', [])_x000D_
_x000D_
.factory('MyService', function() {_x000D_
_x000D_
// private_x000D_
var value = 0;_x000D_
_x000D_
// public_x000D_
return {_x000D_
_x000D_
getValue: function() {_x000D_
return value;_x000D_
},_x000D_
_x000D_
setValue: function(val) {_x000D_
value = val;_x000D_
}_x000D_
_x000D_
};_x000D_
})_x000D_
_x000D_
.controller('Ctrl1', function($scope, $rootScope, MyService) {_x000D_
_x000D_
$scope.update = function() {_x000D_
MyService.setValue($scope.value);_x000D_
$rootScope.$broadcast('increment-value-event');_x000D_
};_x000D_
})_x000D_
_x000D_
.controller('Ctrl2', function($scope, MyService) {_x000D_
_x000D_
$scope.value = MyService.getValue();_x000D_
_x000D_
$scope.$on('increment-value-event', function() { _x000D_
$scope.value = MyService.getValue();_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp">_x000D_
_x000D_
<h3>Controller 1 Scope</h3>_x000D_
<div ng-controller="Ctrl1">_x000D_
<input type="text" ng-model="value"/>_x000D_
<button ng-click="update()">Update</button>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<h3>Controller 2 Scope</h3>_x000D_
<div ng-controller="Ctrl2">_x000D_
Value: {{ value }}_x000D_
</div> _x000D_
_x000D_
</div>
_x000D_
Unfortunately, this is not currently possible in the latest version of DataContractJsonSerializer. See: http://connect.microsoft.com/VisualStudio/feedback/details/558686/datacontractjsonserializer-should-serialize-dictionary-k-v-as-a-json-associative-array
The current suggested workaround is to use the JavaScriptSerializer as Mark suggested above.
Good luck!
I followed these steps (for Mac).
In /etc/ssh/sshd_config
change
#ChallengeResponseAuthentication yes
#PasswordAuthentication yes
to
ChallengeResponseAuthentication no
PasswordAuthentication no
Now generate the RSA key:
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
(For me an RSA key worked. A DSA key did not work.)
A private key will be generated in ~/.ssh/id_rsa
along with ~/.ssh/id_rsa.pub
(public key).
Now move to the .ssh folder: cd ~/.ssh
Enter rm -rf authorized_keys
(sometimes multiple keys lead to an error).
Enter vi authorized_keys
Enter :wq
to save this empty file
Enter cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
Restart the SSH:
sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd
Use
__DIR__
to get the current path of the script and this should fix your problem.
So:
require_once(__DIR__.'/../class/user.php');
This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.
Edit: slash problem fixed
by VB function:
Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue
If Not m_RowNr(1) = strQName Then
m_RowNr(0) = 1
m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
m_RowNr(0) = m_RowNr(0) + 1
End If
m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)
End Function
Usage(without sorting option):
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id
if sorting required or multiple tables join then create intermediate table:
SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
INTO table_with_Nr
From table A
Order By A.id
I had this issue when after rebooted and the last copy of VSCode reopened. The above fix did not work, but when I closed and reopened VSCode via explorer it worked. Here are the steps I did:
//received fatal error_x000D_
git remote remove origin_x000D_
git init_x000D_
git remote add origin git@github:<yoursite>/<your project>.git_x000D_
// still received an err _x000D_
//restarted VSCode and folder via IE _x000D_
//updated one char and resaved the index.html _x000D_
git add ._x000D_
git commit -m "blah"_x000D_
git push origin master
_x000D_
Just as normal, using data-original-title
:
Html:
<div rel='tooltip' data-original-title='<h1>big tooltip</h1>'>Visible text</div>
Javascript:
$("[rel=tooltip]").tooltip({html:true});
The html parameter specifies how the tooltip text should be turned into DOM elements. By default Html code is escaped in tooltips to prevent XSS attacks. Say you display a username on your site and you show a small bio in a tooltip. If the html code isn't escaped and the user can edit the bio themselves they could inject malicious code.
The simplest approach that I have implemented is to use Date() itself. `
const days = 15;
// Date.now() gives the epoch date value (in milliseconds) of current date
nextDate = new Date( Date.now() + days * 24 * 60 * 60 * 1000)
`
I used concat method and works well.
concat(//SomeElement/text(),'_',//OtherElement/text())
Just try this:
Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();
If bitmapdata
is the byte array then getting Bitmap
is done like this:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
Returns the decoded Bitmap
, or null
if the image could not be decoded.
if you are using windows try to pass encoding='latin1', encoding='iso-8859-1' or encoding='cp1252' example:
csv_data = pd.read_csv(csvpath,encoding='iso-8859-1')
print(print(soup.encode('iso-8859-1')))
Create a public integer in the General Declaration.
Then in your function you can increase its value each time. See example (function to save attachements of an email as CSV).
Public Numerator As Integer
Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim FileName As String
saveFolder = "c:\temp\"
For Each objAtt In itm.Attachments
FileName = objAtt.DisplayName & "_" & Numerator & "_" & Format(Now, "yyyy-mm-dd H-mm-ss") & ".CSV"
objAtt.SaveAsFile saveFolder & "\" & FileName
Numerator = Numerator + 1
Set objAtt = Nothing
Next
End Sub
in my case it was a cross-origin frame and wasn't loading sometimes. the solution that worked for me is: if it's loaded successfully then if you try this code:
var iframe = document.getElementsByTagName('iframe')[0];
console.log(iframe.contentDocument);
it won't allow you to access contentDocument
and throw a cross-origin error
however if frame is not loaded successfully then contentDocument
will return a #document
object
I think that is a bad solution. If you want to pass a Function into component with @Input()
, @Output()
decorator is what you are looking for.
export class SuggestionMenuComponent {
@Output() onSuggest: EventEmitter<any> = new EventEmitter();
suggestionWasClicked(clickedEntry: SomeModel): void {
this.onSuggest.emit([clickedEntry, this.query]);
}
}
<suggestion-menu (onSuggest)="insertSuggestion($event[0],$event[1])">
</suggestion-menu>
For posterity, I'd like to note that I ended up choosing Raphael, because of the clean API and "free" IE support, and also because the active development looks promising (event support was just added in 0.7, for instance). However, I'll leave the question unanswered, and I'd still be interested to hear about others' experiences using Javascript + SVG libraries.
A classic "or" would be |
. For example, ab|de
would match either side of the expression.
However, for something like your case you might want to use the ?
quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:
\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+
This pattern will match:
\d+
: One or more numbers.\s+
: One or more whitespaces.[A-Z\s]+
: One or more uppercase characters or space characters\s+
: One or more whitespaces.[A-Z][A-Za-z\s]+
: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.If you'd like a more static check, e.g. indeed only match ABC
and A ABC
, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):
\d (?:ABC|A ABC) Street
Or another alternative using a quantifier:
\d (?:A )?ABC Street
A little late to the party, but I think regular expressions are not the right tool for the job.
The problem is that you'll come across edge cases which would add extranous complexity to the regular expression. @est mentioned an example line:
for (int i = 0; i < 10; doSomethingTo("("));
This string literal contains an (unbalanced!) parenthesis, which breaks the logic. Apparently, you must ignore contents of string literals. In order to do this, you must take the double quotes into account. But string literals itself can contain double quotes. For instance, try this:
for (int i = 0; i < 10; doSomethingTo("\"(\\"));
If you address this using regular expressions, it'll add even more complexity to your pattern.
I think you are better off parsing the language. You could, for instance, use a language recognition tool like ANTLR. ANTLR is a parser generator tool, which can also generate a parser in Python. You must provide a grammar defining the target language, in your case C++. There are already numerous grammars for many languages out there, so you can just grab the C++ grammar.
Then you can easily walk the parser tree, searching for empty statements as while
or for
loop body.
If you would like to have live reload you can use gulp-webserver, which will watch for your file changes and reload page, this way you don't have to press F5 every time on your page:
Here is how to do it:
Open command prompt (cmd) and type
npm install --save-dev gulp-webserver
Enter Ctrl+Shift+P in VS Code and type Configure Task Runner. Select it and press enter. It will open tasks.json file for you. Remove everything from it end enter just following code
tasks.json
{
"version": "0.1.0",
"command": "gulp",
"isShellCommand": true,
"args": [
"--no-color"
],
"tasks": [
{
"taskName": "webserver",
"isBuildCommand": true,
"showOutput": "always"
}
]
}
gulpfile.js
var gulp = require('gulp'),
webserver = require('gulp-webserver');
gulp.task('webserver', function () {
gulp.src('app')
.pipe(webserver({
livereload: true,
open: true
}));
});
Your webserver now will open your page in your default browser. Now any changes that you will do to your HTML or CSS pages will be automatically reloaded.
Here is an information on how to configure 'gulp-webserver' for instance port, and what page to load, ...
You can also run your task just by entering Ctrl+P and type task webserver
You can try this instead
var myu = document.getElementById('myu').value;
var myp = document.getElementById('myp').value;
window.opener.location.href='myurl.php?myu='+ myu +'&myp='+ myp;
Note: Do not use this method to pass sensitive information like username, password.
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
TLDR; The formula is n(n-1)/2
where n
is the number of items in the set.
To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA)
, you can calculate the summation of 1 + 2 + ... + (n-1)
where n
is the number of items in the set.
The reasoning is as follows, say you have 4 items:
A
B
C
D
The number of items that can be paired with A
is 3, or n-1
:
AB
AC
AD
It follows that the number of items that can be paired with B
is n-2
(because B
has already been paired with A
):
BC
BD
and so on...
(n-1) + (n-2) + ... + (n-(n-1))
which is the same as
1 + 2 + ... + (n-1)
or
n(n-1)/2
fedorqui has a working solution but there is another way to do the same thing.
Chock if a variable is set
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
An alternative, you can also use fopen
$params = array('http' => array(
'method' => 'POST',
'content' => 'toto=1&tata=2'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false)
{
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
Here is just a reply from Richard Pickup on LinkedIn to a similar question of mine:
I've used cocos 2dx marmalade and unity on both iOS and android. For 2d games cocos2dx is the way to go every time. Unity is just too much overkill for 2d games and as already stated marmalade is just a thin abstraction layer not really a game engine. You can even run cocos2d on top of marmalade. My approach would be to use cocos2dx on iOS and android then in future run cocosd2dx code on top of marmalade as an easy way to port to bb10 and win phone 7
You can add a new formula for unique record count
=IF(COUNTIF($A$2:A2,A2)>1,0,1)
Now you can use a pivot table and get a SUM
of unique record count.
This solution works best if you have two or more rows where the same value exist, but you want the pivot table to report an unique count.
Instant.now()
.toString()
2018-02-02T00:28:02.487114Z
Instant.parse(
"2018-02-02T00:28:02.487114Z"
)
The accepted Answer by ppeterka is correct. Your abuse of the formatting pattern results in an erroneous display of data, while the internal value is always limited milliseconds.
The troublesome SimpleDateFormat
and Date
classes you are using are now legacy, supplanted by the java.time classes. The java.time classes handle nanoseconds resolution, much finer than the milliseconds limit of the legacy classes.
The equivalent to java.util.Date
is java.time.Instant
. You can even convert between them using new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Capture the current moment in UTC. Java 8 captures the current moment in milliseconds, while a new Clock
implementation in Java 9 captures the moment in finer granularity, typically microseconds though it depends on the capabilities of your computer hardware clock & OS & JVM implementation.
Instant instant = Instant.now() ;
Generate a String in standard ISO 8601 format.
String output = instant.toString() ;
2018-02-02T00:28:02.487114Z
To generate strings in other formats, search Stack Overflow for DateTimeFormatter
, already covered many times.
To adjust into a time zone other than UTC, use ZonedDateTime
.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.
For example, add an empty file called .gitkeep
to the folder you want to keep, then in your .gitignore
file write:
# exclude everything
somefolder/*
# exception to the rule
!somefolder/.gitkeep
Commit your .gitignore
and .gitkeep
files and this should resolve your issue.
With gawk, you can use the match
function to capture parenthesized groups.
gawk 'match($0, pattern, ary) {print ary[1]}'
example:
echo "abcdef" | gawk 'match($0, /b(.*)e/, a) {print a[1]}'
outputs cd
.
Note the specific use of gawk which implements the feature in question.
For a portable alternative you can achieve similar results with match()
and substr
.
example:
echo "abcdef" | awk 'match($0, /b[^e]*/) {print substr($0, RSTART+1, RLENGTH-1)}'
outputs cd
.
1) First you need to generate EDMX
model using your database. To do that you should add new item to your project:
ADO.NET Entity Data Model
from the Templates list. So now you have Model1.edmx
file in your project.
2) To generate classes using your model:
EDMX
model designer.EF 4.x DbContext Generator for C#
.Notice that two items are added to your project:
Model1.tt
(This template generates very simple POCO classes for each entity in your model) Model1.Context.tt
(This template generates a derived DbContext to use for querying and persisting data)3) Read/Write Data example:
var dbContext = new YourModelClass(); //class derived from DbContext
var contacts = from c in dbContext.Contacts select c; //read data
contacts.FirstOrDefault().FirstName = "Alex"; //edit data
dbContext.SaveChanges(); //save data to DB
Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.
To reference the contents of the single array containing one or more objects i.e. everything in the brackets of something like this {messages: [{"a":1,"b":2}] } ,just add [0] to the query to get the first array element
e.g. messages[0] will reference the object {"a":1,"b":2} as opposed to just messages which would reference the entire array [{"a":1,"b":2}]
from there you can work with the result as typical object and use Object.keys for example to get "a" and "b".
It's worth mentioning that Java 8 has the methods Integer.parseUnsignedInt
and Long.parseUnsignedLong
that does what you wanted, specifically:
Integer.parseUnsignedInt("ffff8000",16) == -32768
The name is a bit confusing, as it parses a signed integer from a hex string, but it does the work.
According to the Python documentation:
The sequence
prog = re.compile(pattern)
result = prog.match(string)
is equivalent to
result = re.match(pattern, string)
but using re.compile()
and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.
So my conclusion is, if you are going to match the same pattern for many different texts, you better precompile it.
You can use an optional parameter of JSON.stringify()
JSON.stringify(value[, replacer [, space]])
Parameters
- value The value to convert to a JSON string.
- replacer If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string. A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
- space Causes the resulting string to be pretty-printed.
For example:
JSON.stringify({a:1,b:2,c:{d:3, e:4}},null," ")
will give you following result:
"{
"a": 1,
"b": 2,
"c": {
"d": 3,
"e": 4
}
}"
If you want to do something in the UI on regular time intervals very good option is to use CountDownTimer:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Just subtract the string address from what strchr returns:
char *string = "qwerty";
char *e;
int index;
e = strchr(string, 'e');
index = (int)(e - string);
Note that the result is zero based, so in above example it will be 2.
You probably want kbhit();
//Example will loop until a key is pressed
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
while(1)
{
if(kbhit())
{
break;
}
}
}
this may not work on all environments. A portable way would be to create a monitoring thread and set some flag on getch();
String
is immutable for several reasons, here is a summary:
String
in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.String
is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).That being said, immutability of String
only means you cannot change it using its public API. You can in fact bypass the normal API using reflection. See the answer here.
In your example, if String
was mutable, then consider the following example:
String a="stack";
System.out.println(a);//prints stack
a.setValue("overflow");
System.out.println(a);//if mutable it would print overflow
This is an updated version for .NET 4.5 and newer using async/await and IEnumerables:
public static class CompressionExtensions
{
public static async Task<IEnumerable<byte>> Zip(this object obj)
{
byte[] bytes = obj.Serialize();
using (MemoryStream msi = new MemoryStream(bytes))
using (MemoryStream mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
await msi.CopyToAsync(gs);
return mso.ToArray().AsEnumerable();
}
}
public static async Task<object> Unzip(this byte[] bytes)
{
using (MemoryStream msi = new MemoryStream(bytes))
using (MemoryStream mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
// Sync example:
//gs.CopyTo(mso);
// Async way (take care of using async keyword on the method definition)
await gs.CopyToAsync(mso);
}
return mso.ToArray().Deserialize();
}
}
}
public static class SerializerExtensions
{
public static byte[] Serialize<T>(this T objectToWrite)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
return stream.GetBuffer();
}
}
public static async Task<T> _Deserialize<T>(this byte[] arr)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
await stream.WriteAsync(arr, 0, arr.Length);
stream.Position = 0;
return (T)binaryFormatter.Deserialize(stream);
}
}
public static async Task<object> Deserialize(this byte[] arr)
{
object obj = await arr._Deserialize<object>();
return obj;
}
}
With this you can serialize everything BinaryFormatter
supports, instead only of strings.
Edit:
In case, you need take care of Encoding
, you could just use Convert.ToBase64String(byte[])...
I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in. The fact that your python interpreter may store things as binary internally doesn't affect how you work with it - if you have an integer type, just use +, -, etc.
If you have strings of binary digits, you'll have to either write your own implementation or convert them using the int(binaryString, 2) function.
For date:
#!/usr/bin/ruby -w
date = Time.new
#set 'date' equal to the current date/time.
date = date.day.to_s + "/" + date.month.to_s + "/" + date.year.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display DD/MM/YYYY
puts date
#output the date
The above will display, for example, 10/01/15
And for time
time = Time.new
#set 'time' equal to the current time.
time = time.hour.to_s + ":" + time.min.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display hour and minute
puts time
#output the time
The above will display, for example, 11:33
Then to put it together, add to the end:
puts date + " " + time
using javascript:
here input element is used
<input type="text" id="fname" onkeyup="javascript:console.log(window.event.key)">
if you want to use multiline code use curly braces after javascript:
<input type="text" id="fname" onkeyup="javascript:{ console.log(window.event.key); alert('hello'); }">
Assuming your int array is sorted, i would do...
int count = 0, occur = 0, high = 0, a;
for (a = 1; a < n.length; a++) {
if (n[a - 1] == n[a]) {
count++;
if (count > occur) {
occur = count;
high = n[a];
}
} else {
count = 0;
}
}
System.out.println("highest occurence = " + high);
mv -f source target
From the man page:
-f, --force
do not prompt before overwriting
I had exactly the same problem (always seems to occur when I try to implement a Interface onto a userform. Download and install Code Cleaner from here. This is a freeware utility that has saved me on numerous occasions. With your VBA project open, run the "Clean Code..."
option. Make sure you check the "backup project" and/or "export all code modules" to safe locations before running the clean. As far as I understand it, this utility exports and then re-imports all modules and classes, which eliminates compiler errors that have crept into the code. Worked like a charm for me! Good luck.
Here is my version of the steps:
if adb shell shows empty host name, restart device
#Creating dictionary
animals = {"Cat" : "Pat", "Dog" : "Pat", "Tiger" : "Wild"}
#Convert dictionary to list (array)
keys = list(animals)
#Printing 1st dictionary key by index
print(keys[0])
#Done :)
An alternative to darindaCoder's answer:
path = r'C:\DRO\DCL_rawdata_files' # use your path
all_files = glob.glob(os.path.join(path, "*.csv")) # advisable to use os.path.join as this makes concatenation OS independent
df_from_each_file = (pd.read_csv(f) for f in all_files)
concatenated_df = pd.concat(df_from_each_file, ignore_index=True)
# doesn't create a list, nor does it append to one
Id advice you to use a bit simplier method -
$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
alert(resp);
});
try this one, I just feels its syntax is simplier than the $.ajax's one...
Well you can disable skype to use port 80. Click tools --> Options --> Advanced --> Connection and uncheck the appropriate checkbox.
It is a pretty old post, but I just had to do it today. I just right-clicked database from SQL2014 and selected Export Data option and that helped me to move data to SQL2012.