Just more details about Transfer(), it's actually is Server.Execute() + Response.End(), its source code is below (from Mono/.net 4.0):
public void Transfer (string path, bool preserveForm)
{
this.Execute (path, null, preserveForm, true);
this.context.Response.End ();
}
and for Execute(), what it is to run is the handler of the given path, see
ASP.NET does not verify that the current user is authorized to view the resource delivered by the Execute method. Although the ASP.NET authorization and authentication logic runs before the original resource handler is called, ASP.NET directly calls the handler indicated by the Execute method and does not rerun authentication and authorization logic for the new resource. If your application's security policy requires clients to have appropriate authorization to access the resource, the application should force reauthorization or provide a custom access-control mechanism.
You can force reauthorization by using the Redirect method instead of the Execute method. Redirect performs a client-side redirect in which the browser requests the new resource. Because this redirect is a new request entering the system, it is subjected to all the authentication and authorization logic of both Internet Information Services (IIS) and ASP.NET security policy.
SELECT
Q.DateInQuarter,
D.[Year],
Quarter = D.Year + '-Q'
+ Convert(varchar(1), ((Q.DateInQuarter % 10000 - 100) / 300 + 1))
FROM
dbo.QuarterDates Q
CROSS APPLY (
VALUES (Convert(varchar(4), Q.DateInQuarter / 10000))
) D ([Year])
;
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
^(-?\d+\.)?-?\d+$
allow:
23425.23425
10.10
100
0
0.00
-100
-10.10
10.-10
-10.-10
-23425.23425
-23425.-23425
0.234
You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode
before it can encode it back to UTF-8. That is what is failing here:
>>> data = u'\u00c3' # Unicode data
>>> data = data.encode('utf8') # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8') # Try to *re*-encode it
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
Just write your data directly to the file, there is no need to encode already-encoded data.
If you instead build up unicode
values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open()
instead, which returns a file object that will encode unicode values to UTF-8 for you.
You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).
For your MySQL insert problem, you need to do two things:
Add charset='utf8'
to your MySQLdb.connect()
call.
Use unicode
objects, not str
objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:
artiste = artiste.decode('utf8') # it is already UTF8, decode to unicode
c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
# ...
c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
It may actually work better if you used codecs.open()
to decode the contents automatically instead:
import codecs
sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')
with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
for line in findex:
if u'#artiste' not in line:
continue
artiste=line.split(u'[:::]')[1].strip()
cursor = sql.cursor()
cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
if not cursor.fetchone()[0]:
cursor = sql.cursor()
cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
artists_inserted += 1
You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:
Check out the request module.
It's more full featured than node's built-in http client.
var request = require('request');
var propertiesObject = { field1:'test1', field2:'test2' };
request({url:url, qs:propertiesObject}, function(err, response, body) {
if(err) { console.log(err); return; }
console.log("Get response: " + response.statusCode);
});
Some of these fall into the category of general NLog (or logging) tips rather than strictly configuration suggestions.
Here are some general logging links from here at SO (you might have seen some or all of these already):
What's the point of a logging facade?
Why do loggers recommend using a logger per class?
Use the common pattern of naming your logger based on the class Logger logger = LogManager.GetCurrentClassLogger()
. This gives you a high degree of granularity in your loggers and gives you great flexibility in the configuration of the loggers (control globally, by namespace, by specific logger name, etc).
Use non-classname-based loggers where appropriate. Maybe you have one function for which you really want to control the logging separately. Maybe you have some cross-cutting logging concerns (performance logging).
If you don't use classname-based logging, consider naming your loggers in some kind of hierarchical structure (maybe by functional area) so that you can maintain greater flexibility in your configuration. For example, you might have a "database" functional area, an "analysis" FA, and a "ui" FA. Each of these might have sub-areas. So, you might request loggers like this:
Logger logger = LogManager.GetLogger("Database.Connect");
Logger logger = LogManager.GetLogger("Database.Query");
Logger logger = LogManager.GetLogger("Database.SQL");
Logger logger = LogManager.GetLogger("Analysis.Financial");
Logger logger = LogManager.GetLogger("Analysis.Personnel");
Logger logger = LogManager.GetLogger("Analysis.Inventory");
And so on. With hierarchical loggers, you can configure logging globally (the "*" or root logger), by FA (Database, Analysis, UI), or by subarea (Database.Connect, etc).
Loggers have many configuration options:
<logger name="Name.Space.Class1" minlevel="Debug" writeTo="f1" />
<logger name="Name.Space.Class1" levels="Debug,Error" writeTo="f1" />
<logger name="Name.Space.*" writeTo="f3,f4" />
<logger name="Name.Space.*" minlevel="Debug" maxlevel="Error" final="true" />
See the NLog help for more info on exactly what each of the options means. Probably the most notable items here are the ability to wildcard logger rules, the concept that multiple logger rules can "execute" for a single logging statement, and that a logger rule can be marked as "final" so subsequent rules will not execute for a given logging statement.
Use the GlobalDiagnosticContext, MappedDiagnosticContext, and NestedDiagnosticContext to add additional context to your output.
Use "variable" in your config file to simplify. For example, you might define variables for your layouts and then reference the variable in the target configuration rather than specify the layout directly.
<variable name="brief" value="${longdate} | ${level} | ${logger} | ${message}"/>
<variable name="verbose" value="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | ${message}"/>
<targets>
<target name="file" xsi:type="File" layout="${verbose}" fileName="${basedir}/${shortdate}.log" />
<target name="console" xsi:type="ColoredConsole" layout="${brief}" />
</targets>
Or, you could create a "custom" set of properties to add to a layout.
<variable name="mycontext" value="${gdc:item=appname} , ${mdc:item=threadprop}"/>
<variable name="fmt1withcontext" value="${longdate} | ${level} | ${logger} | [${mycontext}] |${message}"/>
<variable name="fmt2withcontext" value="${shortdate} | ${level} | ${logger} | [${mycontext}] |${message}"/>
Or, you can do stuff like create "day" or "month" layout renderers strictly via configuration:
<variable name="day" value="${date:format=dddd}"/>
<variable name="month" value="${date:format=MMMM}"/>
<variable name="fmt" value="${longdate} | ${level} | ${logger} | ${day} | ${month} | ${message}"/>
<targets>
<target name="console" xsi:type="ColoredConsole" layout="${fmt}" />
</targets>
You can also use layout renders to define your filename:
<variable name="day" value="${date:format=dddd}"/>
<targets>
<target name="file" xsi:type="File" layout="${verbose}" fileName="${basedir}/${day}.log" />
</targets>
If you roll your file daily, each file could be named "Monday.log", "Tuesday.log", etc.
Don't be afraid to write your own layout renderer. It is easy and allows you to add your own context information to the log file via configuration. For example, here is a layout renderer (based on NLog 1.x, not 2.0) that can add the Trace.CorrelationManager.ActivityId to the log:
[LayoutRenderer("ActivityId")]
class ActivityIdLayoutRenderer : LayoutRenderer
{
int estimatedSize = Guid.Empty.ToString().Length;
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
builder.Append(Trace.CorrelationManager.ActivityId);
}
protected override int GetEstimatedBufferSize(LogEventInfo logEvent)
{
return estimatedSize;
}
}
Tell NLog where your NLog extensions (what assembly) like this:
<extensions>
<add assembly="MyNLogExtensions"/>
</extensions>
Use the custom layout renderer like this:
<variable name="fmt" value="${longdate} | ${ActivityId} | ${message}"/>
Use async targets:
<nlog>
<targets async="true">
<!-- all targets in this section will automatically be asynchronous -->
</targets>
</nlog>
And default target wrappers:
<nlog>
<targets>
<default-wrapper xsi:type="BufferingWrapper" bufferSize="100"/>
<target name="f1" xsi:type="File" fileName="f1.txt"/>
<target name="f2" xsi:type="File" fileName="f2.txt"/>
</targets>
<targets>
<default-wrapper xsi:type="AsyncWrapper">
<wrapper xsi:type="RetryingWrapper"/>
</default-wrapper>
<target name="n1" xsi:type="Network" address="tcp://localhost:4001"/>
<target name="n2" xsi:type="Network" address="tcp://localhost:4002"/>
<target name="n3" xsi:type="Network" address="tcp://localhost:4003"/>
</targets>
</nlog>
where appropriate. See the NLog docs for more info on those.
Tell NLog to watch and automatically reload the configuration if it changes:
<nlog autoReload="true" />
There are several configuration options to help with troubleshooting NLog
<nlog throwExceptions="true" />
<nlog internalLogFile="file.txt" />
<nlog internalLogLevel="Trace|Debug|Info|Warn|Error|Fatal" />
<nlog internalLogToConsole="false|true" />
<nlog internalLogToConsoleError="false|true" />
See NLog Help for more info.
NLog 2.0 adds LayoutRenderer wrappers that allow additional processing to be performed on the output of a layout renderer (such as trimming whitespace, uppercasing, lowercasing, etc).
Don't be afraid to wrap the logger if you want insulate your code from a hard dependency on NLog, but wrap correctly. There are examples of how to wrap in the NLog's github repository. Another reason to wrap might be that you want to automatically add specific context information to each logged message (by putting it into LogEventInfo.Context).
There are pros and cons to wrapping (or abstracting) NLog (or any other logging framework for that matter). With a little effort, you can find plenty of info here on SO presenting both sides.
If you are considering wrapping, consider using Common.Logging. It works pretty well and allows you to easily switch to another logging framework if you desire to do so. Also if you are considering wrapping, think about how you will handle the context objects (GDC, MDC, NDC). Common.Logging does not currently support an abstraction for them, but it is supposedly in the queue of capabilities to add.
The best way is to use your code and then store the image in OG tags in the page you are linking to, then Facebook will pick them up.
<meta property="og:title" content="Facebook Open Graph Demo">
<meta property="og:image" content="http://example.com/main-image.png">
<meta property="og:site_name" content="Example Website">
<meta property="og:description" content="Here is a nice description">
You can find documentation to OG tags and how to use them with share buttons here
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
Ok solved it.
Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting
In my app.js routing config:
$routeProvider.when('/pages/:name', {
templateUrl: '/pages/home.html',
controller: CMSController
});
Then in my CMS controller:
function CMSController($scope, $route, $routeParams) {
$route.current.templateUrl = '/pages/' + $routeParams.name + ".html";
$.get($route.current.templateUrl, function (data) {
$scope.$apply(function () {
$('#views').html($compile(data)($scope));
});
});
...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];
With #views being my <div id="views" ng-view></div>
So now it works with standard routing and dynamic routing.
To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio
into my browser and hey presto portfolio.html was displayed....
Updated Added $apply and $compile to the html so that dynamic content can be injected.
You want options(warn=-1)
. However, note that warn=0
is not the safest warning level and it should not be assumed as the current one, particularly within scripts or functions. Thus the safest way to temporary turn off warnings is:
oldw <- getOption("warn")
options(warn = -1)
[your "silenced" code]
options(warn = oldw)
Try this code using the hostip.info service:
$country=file_get_contents('http://api.hostip.info/get_html.php?ip=');
echo $country;
// Reformat the data returned (Keep only country and country abbr.)
$only_country=explode (" ", $country);
echo "Country : ".$only_country[1]." ".substr($only_country[2],0,4);
To add to Sweko's point:
The reason why the cast
var listOfX = new List<X>();
ListOf<Y> ys = (List<Y>)listOfX; // Compile error: Cannot implicitly cast X to Y
is not possible is because the List<T>
is invariant in the Type T and thus it doesn't matter whether X
derives from Y
) - this is because List<T>
is defined as:
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T> ... // Other interfaces
(Note that in this declaration, type T
here has no additional variance modifiers)
However, if mutable collections are not required in your design, an upcast on many of the immutable collections, is possible, e.g. provided that Giraffe
derives from Animal
:
IEnumerable<Animal> animals = giraffes;
This is because IEnumerable<T>
supports covariance in T
- this makes sense given that IEnumerable
implies that the collection cannot be changed, since it has no support for methods to Add or Remove elements from the collection. Note the out
keyword in the declaration of IEnumerable<T>
:
public interface IEnumerable<out T> : IEnumerable
(Here's further explanation for the reason why mutable collections like List
cannot support covariance
, whereas immutable iterators and collections can.)
Casting with .Cast<T>()
As others have mentioned, .Cast<T>()
can be applied to a collection to project a new collection of elements casted to T, however doing so will throw an InvalidCastException
if the cast on one or more elements is not possible (which would be the same behaviour as doing the explicit cast in the OP's foreach
loop).
Filtering and Casting with OfType<T>()
If the input list contains elements of different, incompatable types, the potential InvalidCastException
can be avoided by using .OfType<T>()
instead of .Cast<T>()
. (.OfType<>()
checks to see whether an element can be converted to the target type, before attempting the conversion, and filters out incompatable types.)
foreach
Also note that if the OP had written this instead: (note the explicit Y y
in the foreach
)
List<Y> ListOfY = new List<Y>();
foreach(Y y in ListOfX)
{
ListOfY.Add(y);
}
that the casting will also be attempted. However, if no cast is possible, an InvalidCastException
will result.
Examples
For example, given the simple (C#6) class hierarchy:
public abstract class Animal
{
public string Name { get; }
protected Animal(string name) { Name = name; }
}
public class Elephant : Animal
{
public Elephant(string name) : base(name){}
}
public class Zebra : Animal
{
public Zebra(string name) : base(name) { }
}
When working with a collection of mixed types:
var mixedAnimals = new Animal[]
{
new Zebra("Zed"),
new Elephant("Ellie")
};
foreach(Animal animal in mixedAnimals)
{
// Fails for Zed - `InvalidCastException - cannot cast from Zebra to Elephant`
castedAnimals.Add((Elephant)animal);
}
var castedAnimals = mixedAnimals.Cast<Elephant>()
// Also fails for Zed with `InvalidCastException
.ToList();
Whereas:
var castedAnimals = mixedAnimals.OfType<Elephant>()
.ToList();
// Ellie
filters out only the Elephants - i.e. Zebras are eliminated.
Re: Implicit cast operators
Without dynamic, user defined conversion operators are only used at compile-time*, so even if a conversion operator between say Zebra and Elephant was made available, the above run time behaviour of the approaches to conversion wouldn't change.
If we add a conversion operator to convert a Zebra to an Elephant:
public class Zebra : Animal
{
public Zebra(string name) : base(name) { }
public static implicit operator Elephant(Zebra z)
{
return new Elephant(z.Name);
}
}
Instead, given the above conversion operator, the compiler will be able to change the type of the below array from Animal[]
to Elephant[]
, given that the Zebras can be now converted to a homogeneous collection of Elephants:
var compilerInferredAnimals = new []
{
new Zebra("Zed"),
new Elephant("Ellie")
};
Using Implicit Conversion Operators at run time
*As mentioned by Eric, the conversion operator can however be accessed at run time by resorting to dynamic
:
var mixedAnimals = new Animal[] // i.e. Polymorphic collection
{
new Zebra("Zed"),
new Elephant("Ellie")
};
foreach (dynamic animal in mixedAnimals)
{
castedAnimals.Add(animal);
}
// Returns Zed, Ellie
Into Preferences > Settings - Users
File : Preferences.sublime-settings
Write this :
"show_encoding" : true,
It's explain on the release note date 17 December 2013. Build 3059. Official site Sublime Text 3
In VB.NET using Function,
Dim query = From order In dc.Orders
From vendor In
dc.Vendors.Where(Function(v) v.Id = order.VendorId).DefaultIfEmpty()
From status In
dc.Status.Where(Function(s) s.Id = order.StatusId).DefaultIfEmpty()
Select Order = order, Vendor = vendor, Status = status
<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');
// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author']; // name
echo $tags['keywords']; // php documentation
echo $tags['description']; // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>
In Webdriver, you should use driver.switchTo().defaultContent();
to get out of a frame.
You need to get out of all the frames first, then switch into outer frame again.
// between step 4 and step 5
// remove selenium.selectFrame("relative=up");
driver.switchTo().defaultContent(); // you are now outside both frames
driver.switchTo().frame("cq-cf-frame");
// now continue step 6
driver.findElement(By.xpath("//button[text()='OK']")).click();
In general, bless
associates an object with a class.
package MyClass;
my $object = { };
bless $object, "MyClass";
Now when you invoke a method on $object
, Perl know which package to search for the method.
If the second argument is omitted, as in your example, the current package/class is used.
For the sake of clarity, your example might be written as follows:
sub new {
my $class = shift;
my $self = { };
bless $self, $class;
}
You need to access the page_source
property:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://example.com")
html_source = browser.page_source
if "whatever" in html_source:
# do something
else:
# do something else
I got this error ORA-12505, TNS:listener does not currently know of SID given in connect descriptor when I tried to connect to oracle DB using SQL developer.
The JDBC string used was jdbc:oracle:thin:@myserver:1521/XE, obviously the correct one and the two mandatory oracle services OracleServiceXE, OracleXETNSListener were up and running.
The way I solved this issue (In Windows 10)
1. Open run command.
2. Type services.msc
3. Find services with name OracleServiceXE and OracleXETNSListener in the list.
4. Restart OracleServiceXE service first. After completing the restart try restarting OracleXETNSListener service.
atm they are working on that issue https://github.com/firebase/quickstart-android/issues/4
when you send a notification from the Firebase console is uses your app icon by default, and the Android system will turn that icon solid white when in the notification bar.
If you are unhappy with that result you should implement FirebaseMessagingService and create the notifications manually when you receive a message. We are working on a way to improve this but for now that's the only way.
edit: with SDK 9.8.0 add to AndroidManifest.xml
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/my_favorite_pic"/>
It is the NextStep (= NS) heritage. NeXT was the computer company that Steve Jobs formed after he quit Apple in 1985, and NextStep was it's operating system (UNIX based) together with the Obj-C language and runtime. Together with it's libraries and tools, NextStep was later renamed OpenStep (which was also the name on an API that NeXT developed together with Sun), which in turn later became Cocoa.
These different names are actually quite confusing (especially since some of the names differs only in which characters are upper or lower case..), try this for an explanation:
This error is generally caused by one of your Chrome extensions.
I recommend installing this One-Click Extension Disabler, I use it with the keyboard shortcut COMMAND (?) + SHIFT (?) + D — to quickly disable/enable all my extensions.
Once the extensions are disabled this error message should go away.
Peace! ??
What worked for me was manually adding the path variable in my system.
I followed the instructions from Method 3 in this post:
https://appuals.com/fix-git-is-not-recognized-as-an-internal-or-external-command/
4 spaces do the trick even inside definition list:
Endpoint
: `/listAgencies`
Method
: `GET`
Arguments
: * `level` - bla-bla.
* `withDisabled` - should we include disabled `AGENT`s.
* `userId` - bla-bla.
I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).
This post shows a complete working HTML file as an example of triggering code to run when a tab is clicked. The .on() method is now the way that jQuery suggests that you handle events.
To make something happen when the user clicks a tab can be done by giving the list element an id.
<li id="list">
Then referring to the id.
$("#list").on("click", function() {
alert("Tab Clicked!");
});
Make sure that you are using a current version of the jQuery api. Referencing the jQuery api from Google, you can get the link here:
https://developers.google.com/speed/libraries/devguide#jquery
Here is a complete working copy of a tabbed page that triggers an alert when the horizontal tab 1 is clicked.
<!-- This HTML doc is modified from an example by: -->
<!-- http://keith-wood.name/uiTabs.html#tabs-nested -->
<head>
<meta charset="utf-8">
<title>TabDemo</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/south-street/jquery-ui.css">
<style>
pre {
clear: none;
}
div.showCode {
margin-left: 8em;
}
.tabs {
margin-top: 0.5em;
}
.ui-tabs {
padding: 0.2em;
background: url(http://code.jquery.com/ui/1.8.23/themes/south-street/images/ui-bg_highlight-hard_100_f5f3e5_1x100.png) repeat-x scroll 50% top #F5F3E5;
border-width: 1px;
}
.ui-tabs .ui-tabs-nav {
padding-left: 0.2em;
background: url(http://code.jquery.com/ui/1.8.23/themes/south-street/images/ui-bg_gloss-wave_100_ece8da_500x100.png) repeat-x scroll 50% 50% #ECE8DA;
border: 1px solid #D4CCB0;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 6px;
}
.ui-tabs-nav .ui-state-active {
border-color: #D4CCB0;
}
.ui-tabs .ui-tabs-panel {
background: transparent;
border-width: 0px;
}
.ui-tabs-panel p {
margin-top: 0em;
}
#minImage {
margin-left: 6.5em;
}
#minImage img {
padding: 2px;
border: 2px solid #448844;
vertical-align: bottom;
}
#tabs-nested > .ui-tabs-panel {
padding: 0em;
}
#tabs-nested-left {
position: relative;
padding-left: 6.5em;
}
#tabs-nested-left .ui-tabs-nav {
position: absolute;
left: 0.25em;
top: 0.25em;
bottom: 0.25em;
width: 6em;
padding: 0.2em 0 0.2em 0.2em;
}
#tabs-nested-left .ui-tabs-nav li {
right: 1px;
width: 100%;
border-right: none;
border-bottom-width: 1px !important;
-moz-border-radius: 4px 0px 0px 4px;
-webkit-border-radius: 4px 0px 0px 4px;
border-radius: 4px 0px 0px 4px;
overflow: hidden;
}
#tabs-nested-left .ui-tabs-nav li.ui-tabs-selected,
#tabs-nested-left .ui-tabs-nav li.ui-state-active {
border-right: 1px solid transparent;
}
#tabs-nested-left .ui-tabs-nav li a {
float: right;
width: 100%;
text-align: right;
}
#tabs-nested-left > div {
height: 10em;
overflow: auto;
}
</pre>
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script>
$(function() {
$('article.tabs').tabs();
});
</script>
</head>
<body>
<header role="banner">
<h1>jQuery UI Tabs Styling</h1>
</header>
<section>
<article id="tabs-nested" class="tabs">
<script>
$(document).ready(function(){
$("#ForClick").on("click", function() {
alert("Tab Clicked!");
});
});
</script>
<ul>
<li id="ForClick"><a href="#tabs-nested-1">First</a></li>
<li><a href="#tabs-nested-2">Second</a></li>
<li><a href="#tabs-nested-3">Third</a></li>
</ul>
<div id="tabs-nested-1">
<article id="tabs-nested-left" class="tabs">
<ul>
<li><a href="#tabs-nested-left-1">First</a></li>
<li><a href="#tabs-nested-left-2">Second</a></li>
<li><a href="#tabs-nested-left-3">Third</a></li>
</ul>
<div id="tabs-nested-left-1">
<p>Nested tabs, horizontal then vertical.</p>
<form action="/sign" method="post">
<div><textarea name="content" rows="5" cols="100"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
</div>
<div id="tabs-nested-left-2">
<p>Nested Left Two</p>
</div>
<div id="tabs-nested-left-3">
<p>Nested Left Three</p>
</div>
</article>
</div>
<div id="tabs-nested-2">
<p>Tab Two Main</p>
</div>
<div id="tabs-nested-3">
<p>Tab Three Main</p>
</div>
</article>
</section>
</body>
</html>
Okay, here is a solution to reduce the physical size of the transaction file, but without changing the recovery mode to simple.
Within your database, locate the file_id of the log file using the following query.
SELECT * FROM sys.database_files;
In my instance, the log file is file_id 2. Now we want to locate the virtual logs in use, and do this with the following command.
DBCC LOGINFO;
Here you can see if any virtual logs are in use by seeing if the status is 2 (in use), or 0 (free). When shrinking files, empty virtual logs are physically removed starting at the end of the file until it hits the first used status. This is why shrinking a transaction log file sometimes shrinks it part way but does not remove all free virtual logs.
If you notice a status 2's that occur after 0's, this is blocking the shrink from fully shrinking the file. To get around this do another transaction log backup, and immediately run these commands, supplying the file_id found above, and the size you would like your log file to be reduced to.
-- DBCC SHRINKFILE (file_id, LogSize_MB)
DBCC SHRINKFILE (2, 100);
DBCC LOGINFO;
This will then show the virtual log file allocation, and hopefully you'll notice that it's been reduced somewhat. Because virtual log files are not always allocated in order, you may have to backup the transaction log a couple of times and run this last query again; but I can normally shrink it down within a backup or two.
std::string + const char*
results in another std::string
. system
does not take a std::string
, and you cannot concatenate char*
's with the +
operator. If you want to use the code this way you will need:
std::string name = "john";
std::string tmp =
"quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '" +
name + ".jpg'";
system(tmp.c_str());
Load - Test S/W at max Load. Stress - Beyond the Load of S/W.Or To determine the breaking point of s/w.
No code? For shame!
Here is a simple JavaScript address parser. It's pretty awful for every single reason that Matt gives in his dissertation above (which I almost 100% agree with: addresses are complex types, and humans make mistakes; better to outsource and automate this - when you can afford to).
But rather than cry, I decided to try:
This code works OK for parsing most Esri results for findAddressCandidate
and also with some other (reverse)geocoders that return single-line address where street/city/state are delimited by commas. You can extend if you want or write country-specific parsers. Or just use this as case study of how challenging this exercise can be or at how lousy I am at JavaScript. I admit I only spent about thirty mins on this (future iterations could add caches, zip validation, and state lookups as well as user location context), but it worked for my use case: End user sees form that parses geocode search response into 4 textboxes. If address parsing comes out wrong (which is rare unless source data was poor) it's no big deal - the user gets to verify and fix it! (But for automated solutions could either discard/ignore or flag as error so dev can either support the new format or fix source data.)
/* _x000D_
address assumptions:_x000D_
- US addresses only (probably want separate parser for different countries)_x000D_
- No country code expected._x000D_
- if last token is a number it is probably a postal code_x000D_
-- 5 digit number means more likely_x000D_
- if last token is a hyphenated string it might be a postal code_x000D_
-- if both sides are numeric, and in form #####-#### it is more likely_x000D_
- if city is supplied, state will also be supplied (city names not unique)_x000D_
- zip/postal code may be omitted even if has city & state_x000D_
- state may be two-char code or may be full state name._x000D_
- commas: _x000D_
-- last comma is usually city/state separator_x000D_
-- second-to-last comma is possibly street/city separator_x000D_
-- other commas are building-specific stuff that I don't care about right now._x000D_
- token count:_x000D_
-- because units, street names, and city names may contain spaces token count highly variable._x000D_
-- simplest address has at least two tokens: 714 OAK_x000D_
-- common simple address has at least four tokens: 714 S OAK ST_x000D_
-- common full (mailing) address has at least 5-7:_x000D_
--- 714 OAK, RUMTOWN, VA 59201_x000D_
--- 714 S OAK ST, RUMTOWN, VA 59201_x000D_
-- complex address may have a dozen or more:_x000D_
--- MAGICICIAN SUPPLY, LLC, UNIT 213A, MAGIC TOWN MALL, 13 MAGIC CIRCLE DRIVE, LAND OF MAGIC, MA 73122-3412_x000D_
*/_x000D_
_x000D_
var rawtext = $("textarea").val();_x000D_
var rawlist = rawtext.split("\n");_x000D_
_x000D_
function ParseAddressEsri(singleLineaddressString) {_x000D_
var address = {_x000D_
street: "",_x000D_
city: "",_x000D_
state: "",_x000D_
postalCode: ""_x000D_
};_x000D_
_x000D_
// tokenize by space (retain commas in tokens)_x000D_
var tokens = singleLineaddressString.split(/[\s]+/);_x000D_
var tokenCount = tokens.length;_x000D_
var lastToken = tokens.pop();_x000D_
if (_x000D_
// if numeric assume postal code (ignore length, for now)_x000D_
!isNaN(lastToken) ||_x000D_
// if hyphenated assume long zip code, ignore whether numeric, for now_x000D_
lastToken.split("-").length - 1 === 1) {_x000D_
address.postalCode = lastToken;_x000D_
lastToken = tokens.pop();_x000D_
}_x000D_
_x000D_
if (lastToken && isNaN(lastToken)) {_x000D_
if (address.postalCode.length && lastToken.length === 2) {_x000D_
// assume state/province code ONLY if had postal code_x000D_
// otherwise it could be a simple address like "714 S OAK ST"_x000D_
// where "ST" for "street" looks like two-letter state code_x000D_
// possibly this could be resolved with registry of known state codes, but meh. (and may collide anyway)_x000D_
address.state = lastToken;_x000D_
lastToken = tokens.pop();_x000D_
}_x000D_
if (address.state.length === 0) {_x000D_
// check for special case: might have State name instead of State Code._x000D_
var stateNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
// check remaining tokens from right-to-left for the first comma_x000D_
while (2 + 2 != 5) {_x000D_
lastToken = tokens.pop();_x000D_
if (!lastToken) break;_x000D_
else if (lastToken.endsWith(",")) {_x000D_
// found separator, ignore stuff on left side_x000D_
tokens.push(lastToken); // put it back_x000D_
break;_x000D_
} else {_x000D_
stateNameParts.unshift(lastToken);_x000D_
}_x000D_
}_x000D_
address.state = stateNameParts.join(' ');_x000D_
lastToken = tokens.pop();_x000D_
}_x000D_
}_x000D_
_x000D_
if (lastToken) {_x000D_
// here is where it gets trickier:_x000D_
if (address.state.length) {_x000D_
// if there is a state, then assume there is also a city and street._x000D_
// PROBLEM: city may be multiple words (spaces)_x000D_
// but we can pretty safely assume next-from-last token is at least PART of the city name_x000D_
// most cities are single-name. It would be very helpful if we knew more context, like_x000D_
// the name of the city user is in. But ignore that for now._x000D_
// ideally would have zip code service or lookup to give city name for the zip code._x000D_
var cityNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
// assumption / RULE: street and city must have comma delimiter_x000D_
// addresses that do not follow this rule will be wrong only if city has space_x000D_
// but don't care because Esri formats put comma before City_x000D_
var streetNameParts = [];_x000D_
_x000D_
// check remaining tokens from right-to-left for the first comma_x000D_
while (2 + 2 != 5) {_x000D_
lastToken = tokens.pop();_x000D_
if (!lastToken) break;_x000D_
else if (lastToken.endsWith(",")) {_x000D_
// found end of street address (may include building, etc. - don't care right now)_x000D_
// add token back to end, but remove trailing comma (it did its job)_x000D_
tokens.push(lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken);_x000D_
streetNameParts = tokens;_x000D_
break;_x000D_
} else {_x000D_
cityNameParts.unshift(lastToken);_x000D_
}_x000D_
}_x000D_
address.city = cityNameParts.join(' ');_x000D_
address.street = streetNameParts.join(' ');_x000D_
} else {_x000D_
// if there is NO state, then assume there is NO city also, just street! (easy)_x000D_
// reasoning: city names are not very original (Portland, OR and Portland, ME) so if user wants city they need to store state also (but if you are only ever in Portlan, OR, you don't care about city/state)_x000D_
// put last token back in list, then rejoin on space_x000D_
tokens.push(lastToken);_x000D_
address.street = tokens.join(' ');_x000D_
}_x000D_
}_x000D_
// when parsing right-to-left hard to know if street only vs street + city/state_x000D_
// hack fix for now is to shift stuff around._x000D_
// assumption/requirement: will always have at least street part; you will never just get "city, state" _x000D_
// could possibly tweak this with options or more intelligent parsing&sniffing_x000D_
if (!address.city && address.state) {_x000D_
address.city = address.state;_x000D_
address.state = '';_x000D_
}_x000D_
if (!address.street) {_x000D_
address.street = address.city;_x000D_
address.city = '';_x000D_
}_x000D_
_x000D_
return address;_x000D_
}_x000D_
_x000D_
// get list of objects with discrete address properties_x000D_
var addresses = rawlist_x000D_
.filter(function(o) {_x000D_
return o.length > 0_x000D_
})_x000D_
.map(ParseAddressEsri);_x000D_
$("#output").text(JSON.stringify(addresses));_x000D_
console.log(addresses);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea>_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
13212 E SPRAGUE AVE, FAIR VALLEY, MD 99201_x000D_
1005 N Gravenstein Highway, Sebastopol CA 95472_x000D_
A. P. Croll & Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947_x000D_
11522 Shawnee Road, Greenwood, DE 19950_x000D_
144 Kings Highway, S.W. Dover, DE 19901_x000D_
Intergrated Const. Services 2 Penns Way Suite 405, New Castle, DE 19720_x000D_
Humes Realty 33 Bridle Ridge Court, Lewes, DE 19958_x000D_
Nichols Excavation 2742 Pulaski Hwy, Newark, DE 19711_x000D_
2284 Bryn Zion Road, Smyrna, DE 19904_x000D_
VEI Dover Crossroads, LLC 1500 Serpentine Road, Suite 100 Baltimore MD 21_x000D_
580 North Dupont Highway, Dover, DE 19901_x000D_
P.O. Box 778, Dover, DE 19903_x000D_
714 S OAK ST_x000D_
714 S OAK ST, RUM TOWN, VA, 99201_x000D_
3142 E SPRAGUE AVE, WHISKEY VALLEY, WA 99281_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
</textarea>_x000D_
<div id="output">_x000D_
</div>
_x000D_
Loren Brichter the developer of Tweetie2 wrote this little app called SimFinger to make iphone screencasts top notch!
http://blog.atebits.com/2009/03/not-your-average-iphone-screencast/
Love apps that make amateurs look like pros :)
Detached head means you are no longer on a branch, you have checked out a single commit in the history (in this case the commit previous to HEAD, i.e. HEAD^).
You only need to checkout the branch you were on, e.g.
git checkout master
Next time you have changed a file and want to restore it to the state it is in the index, don't delete the file first, just do
git checkout -- path/to/foo
This will restore the file foo to the state it is in the index.
git branch tmp
- this will save your changes in a new branch called tmp
.git checkout master
master
, run git merge tmp
from the master
branch. You should be on the master
branch after running git checkout master
.Under linux there's a package called binfmt-support
that allows you to run directly your jar without typing java -jar
:
sudo apt-get install binfmt-support
chmod u+x my-jar.jar
./my-jar.jar # there you go!
I actually had the same problem with a completely new repository. I had even tried creating one with git checkout -b master
, but it would not create the branch. I then realized if I made some changes and committed them, git created my master branch.
Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.
"F:\- Big Packets -\kitterengine\Common\Template.bat"
maybe prefaced with call
(see call /?
). Or Cd /d "F:\- Big Packets -\kitterengine\Common\" & Template.bat
.
CMD Cheat Sheet
Cmd.exe
Getting Help
Punctuation
Naming Files
Starting Programs
Keys
CMD.exe
First thing to remember its a way of operating a computer. It's the way we did it before WIMP (Windows, Icons, Mouse, Popup menus) became common. It owes it roots to CPM, VMS, and Unix. It was used to start programs and copy and delete files. Also you could change the time and date.
For help on starting CMD type cmd /?
. You must start it with either the /k
or /c
switch unless you just want to type in it.
Getting Help
For general help. Type Help
in the command prompt. For each command listed type help <command>
(eg help dir
) or <command> /?
(eg dir /?
).
Some commands have sub commands. For example schtasks /create /?
.
The NET
command's help is unusual. Typing net use /?
is brief help. Type net help use
for full help. The same applies at the root - net /?
is also brief help, use net help
.
References in Help to new behaviour are describing changes from CMD in OS/2 and Windows NT4 to the current CMD which is in Windows 2000 and later.
WMIC
is a multipurpose command. Type wmic /?
.
Punctuation
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's
errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
2> Redirects command error output to the file specified. (0 is StdInput, 1 is StdOutput, and 2 is StdError)
2>&1 Redirects command error output to the same location as command output.
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed
to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatenate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files
modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution
time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0
is the batchfile's name.
%* (%*) the entire command line.
%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor (from set /?).
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop.
Single % sign at command prompt and double % sign in a batch file.
\\ (\\servername\sharename\folder\file.ext) access files and folders via UNC naming.
: (win.ini:streamname) accesses an alternative steam. Also separates drive from rest of path.
. (win.ini) the LAST dot in a file path separates the name from extension
. (dir .\*.txt) the current directory
.. (cd ..) the parent directory
\\?\ (\\?\c:\windows\win.ini) When a file path is prefixed with \\?\ filename checks are turned off.
Naming Files
< > : " / \ | Reserved characters. May not be used in filenames.
Reserved names. These refer to devices eg,
copy filename con
which copies a file to the console window.
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4,
COM5, COM6, COM7, COM8, COM9, LPT1, LPT2,
LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9
CONIN$, CONOUT$, CONERR$
--------------------------------
Maximum path length 260 characters
Maximum path length (\\?\) 32,767 characters (approx - some rare characters use 2 characters of storage)
Maximum filename length 255 characters
Starting a Program
See start /?
and call /?
for help on all three ways.
There are two types of Windows programs - console or non console (these are called GUI even if they don't have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows.
If a full path isn't given then Windows looks in
The directory from which the application loaded.
The current directory for the parent process.
Windows NT/2000/XP: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is System32.
Windows NT/2000/XP: The 16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The directories that are listed in the PATH environment variable.
Specify a program name
This is the standard way to start a program.
c:\windows\notepad.exe
In a batch file the batch will wait for the program to exit. When typed the command prompt does not wait for graphical programs to exit.
If the program is a batch file control is transferred and the rest of the calling batch file is not executed.
Use Start command
Start
starts programs in non standard ways.
start "" c:\windows\notepad.exe
Start
starts a program and does not wait. Console programs start in a new window. Using the /b
switch forces console programs into the same window, which negates the main purpose of Start.
Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try
start shell:cache
Also program names registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
can also be typed without specifying a full path.
Also note the first set of quotes, if any, MUST be the window title.
Use Call command
Call is used to start batch files and wait for them to exit and continue the current batch file.
Other Filenames
Typing a non program filename is the same as double clicking the file.
Keys
Ctrl + C exits a program without exiting the console window.
For other editing keys type Doskey /?
.
? and ? recall commands
ESC clears command line
F7 displays command history
ALT+F7 clears command history
F8 searches command history
F9 selects a command by number
ALT+F10 clears macro definitions
Also not listed
Ctrl + ?or? Moves a word at a time
Ctrl + Backspace Deletes the previous word
Home Beginning of line
End End of line
Ctrl + End Deletes to end of line
Change the file content of c:\wamp\alias\phpmyadmin.conf
to the following.
Note: You should set the Allow
Directive to allow from your local machine for security purposes. The directive Allow from all
is insecure and should be limited to your local machine.
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Allow from all
</Directory>
Here my WAMP installation is in the c:\wamp
folder. Change it according to your installation.
Previously, it was like this:
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Directory>
Modern versions of Apache 2.2 and up will look for a IPv6 loopback instead of a IPv4 loopback (your localhost).
The real problem is that wamp is binding to an IPv6 address. The fix: just add
Allow from ::1
- Tiberiu-Ionu? Stan
<Directory "c:/wamp22/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from localhost 127.0.0.1 ::1
</Directory>
This will allow only the local machine to access local apps for Apache.
Restart your Apache server after making these changes.
I ran into a similar issue a while back.
Your problem could be in two different areas. It's either how you're creating the file to write to, or your method of writing could be flawed in that it is phone dependent.
If you're writing the file to a specific location on the SD card, try using Environment variables. They should always point to a valid location. Here's an example to write to the downloads folder:
java.io.File xmlFile = new java.io.File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
+ "/Filename.xml");
If you're writing the file to the application's internal storage. Try this example:
java.io.File xmlFile = new java.io.File((getActivity()
.getApplicationContext().getFileStreamPath("FileName.xml")
.getPath()));
Personally I rely on external libraries to handle the streaming to file. This one hasn't failed me yet.
org.apache.commons.io.FileUtils.copyInputStreamToFile(is, file);
I've lost data one too many times on a failed write command, so I rely on well-known and tested libraries for my IO heavy lifting.
If the files are large, you may also want to look into running the IO in the background, or use callbacks.
If you're already using environment variables, it could be a permissions issue. Check out Justin Fiedler's answer below.
On my case, just to be safe regarding scrolling, I added the window.scroll to the equation:
var element = document.getElementById('myElement');
var topPos = element.getBoundingClientRect().top + window.scrollY;
var leftPos = element.getBoundingClientRect().left + window.scrollX;
That allows me to get the real relative position of element on document, even if it has been scrolled.
actually, if you already know the property, this will do it...
for example:
<a href="test.html" style="color:white;zoom:1.2" id="MyLink"></a>
var txt = "";
txt = getStyle(InterTabLink);
setStyle(InterTabLink, txt.replace("zoom\:1\.2\;","");
function setStyle(element, styleText){
if(element.style.setAttribute)
element.style.setAttribute("cssText", styleText );
else
element.setAttribute("style", styleText );
}
/* getStyle function */
function getStyle(element){
var styleText = element.getAttribute('style');
if(styleText == null)
return "";
if (typeof styleText == 'string') // !IE
return styleText;
else // IE
return styleText.cssText;
}
Note that this only works for inline styles... not styles you've specified through a class or something like that...
Other note: you may have to escape some characters in that replace statement, but you get the idea.
1st answer of Denis is the answer to resolve the trouble. But in fact it is no more a find with several commands in only one exec like the title suggest. To answer the one exec with several commands thing we will have to look for something else to resolv. Here is a example:
Keep last 10000 lines of .log files which has been modified in the last 7 days using 1 exec command using severals {} references
1) see what the command will do on which files:
find / -name "*.log" -a -type f -a -mtime -7 -exec sh -c "echo tail -10000 {} \> fictmp; echo cat fictmp \> {} " \;
2) Do it: (note no more "\>" but only ">" this is wanted)
find / -name "*.log" -a -type f -a -mtime -7 -exec sh -c "tail -10000 {} > fictmp; cat fictmp > {} ; rm fictmp" \;
Check for the SendCommand tool.
You can use it as follows:
perl sendcommand.pl -i login.txt -t cisco -c "show ip route"
FIRST --> rm catalina.engine
THEN -->./startup.sh
NEXT TIME you restart --> ./shutdown.sh -force
As easy as
SELECT lpad(42::text, 4, '0')
References:
sqlfiddle: http://sqlfiddle.com/#!15/d41d8/3665
SELECT SUBSTRING(subject, 1, 10) FROM tbl
The answer, as given, is to use format-patch but since the question was how to cherry-pick from another folder, here is a piece of code to do just that:
$ git --git-dir=../<some_other_repo>/.git \
format-patch -k -1 --stdout <commit SHA> | \
git am -3 -k
(explanation from @cong ma)
The
git format-patch
command creates a patch fromsome_other_repo
's commit specified by its SHA (-1
for one single commit alone). This patch is piped togit am
, which applies the patch locally (-3
means trying the three-way merge if the patch fails to apply cleanly). Hope that explains.
About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.
The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).
Set the insetForSectionAt
property of the UICollectionViewFlowLayout
object attached to your UICollectionView
Make sure to add this protocol
UICollectionViewDelegateFlowLayout
Swift
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets (top: top, left: left, bottom: bottom, right: right)
}
Objective - C
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(top, left, bottom, right);
}
The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.
Once it has implemented that interface, you could do anything you want in the method it overrides.
The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException if not done correctly.
There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.
I hope this was helpful to you!
Maybe slight overkill but created library ngx-if-empty-or-has-items it checks if an object, set, map or array is not empty. Maybe it will help somebody. It has the same functionality as ngIf (then, else and 'as' syntax is supported).
arrayOrObjWithData = ['1'] || {id: 1}
<h1 *ngxIfNotEmpty="arrayOrObjWithData">
You will see it
</h1>
or
// store the result of async pipe in variable
<h1 *ngxIfNotEmpty="arrayOrObjWithData$ | async as obj">
{{obj.id}}
</h1>
or
noData = [] || {}
<h1 *ngxIfHasItems="noData">
You will NOT see it
</h1>
For casting varchar fields/values to number format can be little hack used:
SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`
In cPanel search for php, You will find "Select PHP version" under Software.
Software -> Select PHP Version -> Switch to Php Options -> Change Value -> save.
An on-line syntax highlighter:
or
Just copy and paste into your document.
We can completely avoid using the slow Math.pow()
and Math.log()
methods without sacrificing simplicity since the factor between the units (for example, B, KB, MB, etc.) is 1024 which is 2^10. The Long
class has a handy numberOfLeadingZeros()
method which we can use to tell which unit the size value falls in.
Key point: Size units have a distance of 10 bits (1024 = 2^10) meaning the position of the highest one bit–or in other words the number of leading zeros–differ by 10 (Bytes = KB*1024, KB = MB*1024, etc.).
Correlation between number of leading zeros and size unit:
# of leading 0's Size unit
-------------------------------
>53 B (Bytes)
>43 KB
>33 MB
>23 GB
>13 TB
>3 PB
<=2 EB
The final code:
public static String formatSize(long v) {
if (v < 1024) return v + " B";
int z = (63 - Long.numberOfLeadingZeros(v)) / 10;
return String.format("%.1f %sB", (double)v / (1L << (z*10)), " KMGTPE".charAt(z));
}
If you cancel and see that run
sp_who2 'active'
(Activity Monitor won't be available on old sql server 2000 FYI )
Spot the SPID you wish to kill e.g. 81
Kill 81
Run the sp_who2 'active'
again and you will probably notice it is sleeping ... rolling back
To get the STATUS run again the KILL
Kill 81
Then you will get a message like this
SPID 81: transaction rollback in progress. Estimated rollback completion: 63%. Estimated time remaining: 992 seconds.
An update to Adam's answer considering tryp's answer too. Don't have to instantiate a String in the loop.
public static URI appendUri(String uri, Map<String, String> parameters) throws URISyntaxException {
URI oldUri = new URI(uri);
StringBuilder queries = new StringBuilder();
for(Map.Entry<String, String> query: parameters.entrySet()) {
queries.append( "&" + query.getKey()+"="+query.getValue());
}
String newQuery = oldUri.getQuery();
if (newQuery == null) {
newQuery = queries.substring(1);
} else {
newQuery += queries.toString();
}
URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(),
oldUri.getPath(), newQuery, oldUri.getFragment());
return newUri;
}
Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".
And also it would require to run the docker in privileged mode, so the commands would be:
sudo chmod 757 /var/run/docker.sock
docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...
Probably there's something wrong with the input values for X and/or T. The function from the question works ok:
import numpy as np
from math import e
def sigmoid(X, T):
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])
print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))
Result:
[[15 16]
[ 5 10]]
[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]
[[ 0.99999969 0.99999989]
[ 0.99330715 0.9999546 ]]
Probably it's the dtype of your input arrays. Changing X to:
X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)
Gives:
Traceback (most recent call last):
File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
print sigmoid(X, T)
File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp
Your code was very close to working.
Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.
Here's some code that writes each key/value pair on a separate row:
import csv
somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerows(somedict.items())
If instead you want all the keys on one row and all the values on the next, that is also easy:
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerow(somedict.keys())
w.writerow(somedict.values())
Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr)
so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f)
.
you need to use backslash before ". like \"
From the doc here you can see that
A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.
and " (double quote) is a escacpe sequence
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence
She said "Hello!" to me.
you would write
System.out.println("She said \"Hello!\" to me.");
You could fill the C Column with variations on the following formula:
=IF(ISERROR(MATCH(A1,$B:$B,0)),"",A1)
Then C would only contain values that were in A and C.
This worked for me to return an array of strings from my config:
var allowedMethods = Configuration.GetSection("AppSettings:CORS-Settings:Allow-Methods")
.Get<string[]>();
My configuration section looks like this:
"AppSettings": {
"CORS-Settings": {
"Allow-Origins": [ "http://localhost:8000" ],
"Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
}
}
I suggest using vlookup function to get the nearest match.
Prepare data range and name it: 'numberRange':
Select the range. Go to menu: Data ? Named ranges... ? define the new named range.
Use this simple formula:
=VLOOKUP(A2,numberRange,2)
This way you can ommit errors, and easily correct the result.
I believe you are looking for this:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());
I had used JCL about 2 years back so cannot write a code for you but here is the idea;
again i apologize for solution without code, but i am out of touch by 2 yrs+
A quicker way for me was to delete the tables and re-add them. It Auto-mapped them. :)
>>> r = re.compile("([a-zA-Z]+)([0-9]+)")
>>> m = r.match("foobar12345")
>>> m.group(1)
'foobar'
>>> m.group(2)
'12345'
So, if you have a list of strings with that format:
import re
r = re.compile("([a-zA-Z]+)([0-9]+)")
strings = ['foofo21', 'bar432', 'foobar12345']
print [r.match(string).groups() for string in strings]
Output:
[('foofo', '21'), ('bar', '432'), ('foobar', '12345')]
There are many ways to do it. here are some of them:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
Very simple code with Bootstrap and JQuery without any additionnal javascript code :
HTML :
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<form class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<label class="dropdown-item"><input type="checkbox" name="" value="one">First checkbox</label>
<label class="dropdown-item"><input type="checkbox" name="" value="two">Second checkbox</label>
<label class="dropdown-item"><input type="checkbox" name="" value="three">Third checkbox</label>
</form>
</div>
CSS :
.dropdown-menu label {
display: block;
}
If you want the style to apply globally you could use the adjacent sibling combinator from css.
.my-button-style + .my-button-style {
margin-left: 40px;
}
/* general button style */
.my-button-style {
height: 100px;
width: 150px;
}
Here is a fiddle: https://jsfiddle.net/caeLosby/10/
It is similar to some of the existing answers but it does not set the margin on the first button. For example in the case
<button id="btn1" class="my-button-style"/>
<button id="btn2" class="my-button-style"/>
only btn2
will get the margin.
For further information see https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator
For start date of current year:
SELECT DATEADD(DD,-DATEPART(DY,GETDATE())+1,GETDATE())
For end date of current year:
SELECT DATEADD(DD,-1,DATEADD(YY,DATEDIFF(YY,0,GETDATE())+1,0))
If you want to redirect a whole subfolder, the url
argument in RedirectView is actually interpolated, so you can do something like this in urls.py
:
from django.conf.urls.defaults import url
from django.views.generic import RedirectView
urlpatterns = [
url(r'^old/(?P<path>.*)$', RedirectView.as_view(url='/new_path/%(path)s')),
]
The ?P<path>
you capture will be fed into RedirectView
. This captured variable will then be replaced in the url
argument you gave, giving us /new_path/yay/mypath
if your original path was /old/yay/mypath
.
You can also do ….as_view(url='…', query_string=True)
if you want to copy the query string over as well.
You have empty $entry_database
variable. As you see in error: ListEmail, Title FROM WHERE ID
bewteen FROM and WHERE should be name of table. Proper syntax of SELECT:
SELECT columns FROM table [optional things as WHERE/ORDER/GROUP/JOIN etc]
which in your way should become:
SELECT ID, ListStID, ListEmail, Title FROM some_table_you_got WHERE ID = '4'
I update my Hibernate JPA to 2.1 and It works.
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
I don't know what is the value/usefulness of renaming a function and call it with the new name. But using a string as function name, e.g. obtained from the command line, has some value/usefulness:
import sys
fun = eval(sys.argv[1])
fun()
In the present case, fun = x.
Great question: How does our
differ from my
and what does our
do?
In Summary:
Available since Perl 5, my
is a way to declare non-package variables, that are:
$package_name::variable
.On the other hand, our
variables are package variables, and thus automatically:
$package_name::variable
.Declaring a variable with our
allows you to predeclare variables in order to use them under use strict
without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete use vars
, which was only file-scoped, and not lexically scoped as is our
.
For example, the formal, qualified name for variable $x
inside package main
is $main::x
. Declaring our $x
allows you to use the bare $x
variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses use strict
or use strict "vars"
. The scope might be one, or two, or more packages, or one small block.
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
For fix this issue just call notifyDataSetChanged() with empty list before updating recycle view.
For example
//Method for refresh recycle view
if (!hcpArray.isEmpty())
hcpArray.clear();//The list for update recycle view
adapter.notifyDataSetChanged();
I got the same error while using the imagefield in Django.
post_picture = models.ImageField(upload_to='home2/khamulat/mydomain.com/static/assets/images/uploads/blog/%Y/%m/%d', height_field=None, default=None, width_field=None, max_length=None)
I just removed the excess code as shown above to post_picture = models.ImageField(upload_to='images/uploads/blog/%Y/%m/%d', height_field=None, default=None, width_field=None, max_length=None)
and the error was gone
You can add your attribute on callback function ({key} , speed.callback, like is
$('.usercontent').animate( {
backgroundColor:'#ddd',
},1000,function () {
$(this).css("backgroundColor","red")
});
SELECT
CONNECTIONPROPERTY('net_transport') AS net_transport,
CONNECTIONPROPERTY('protocol_type') AS protocol_type,
CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,
CONNECTIONPROPERTY('local_net_address') AS local_net_address,
CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
CONNECTIONPROPERTY('client_net_address') AS client_net_address
The code here Will give you the IP Address;
This will work for a remote client request to SQL 2008 and newer.
If you have Shared Memory connections allowed, then running above on the server itself will give you
<local machine>
' will be shown in 'client_net_address'.'client_net_address' is the address of the computer that the request originated from, whereas 'local_net_address' would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can't use the server's NetBios name or FQDN for some reason.
I advice strongly against using this answer. Enabling the shell out is a very bad idea on a production SQL Server.
function fn_DateCompare(DateA, DateB) { // this function is good for dates > 01/01/1970
var a = new Date(DateA);
var b = new Date(DateB);
var msDateA = Date.UTC(a.getFullYear(), a.getMonth()+1, a.getDate());
var msDateB = Date.UTC(b.getFullYear(), b.getMonth()+1, b.getDate());
if (parseFloat(msDateA) < parseFloat(msDateB))
return -1; // lt
else if (parseFloat(msDateA) == parseFloat(msDateB))
return 0; // eq
else if (parseFloat(msDateA) > parseFloat(msDateB))
return 1; // gt
else
return null; // error
}
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
Code for set background color, for SolidColor
:
button.Background = new SolidColorBrush(Color.FromArgb(Avalue, rValue, gValue, bValue));
When used with storybook and typescirpt, I had to add
.storybook/webpack.config.js
const path = require('path');
module.exports = async ({ config, mode }) => {
config.module.rules.push({
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/],
transpileOnly: true
},
}
],
});
return config;
};
v-model
it is two way data binding, it is used to bind html input element when you change input value then bounded data will be change.
v-model is used only for HTML input elements
ex: <input type="text" v-model="name" >
v-bind
it is one way data binding,means you can only bind data to input element but can't change bounded data changing input element.
v-bind is used to bind html attribute
ex:
<input type="text" v-bind:class="abc" v-bind:value="">
<a v-bind:href="home/abc" > click me </a>
http://martinfowler.com/articles/microservice-testing/
Martin Fowler's blog post speaks about strategies to test code (Especially in a micro-services architecture) but most of it applies to any application.
I'll quote from his summary slide:
- Unit tests - exercise the smallest pieces of testable software in the application to determine whether they behave as expected.
- Integration tests - verify the communication paths and interactions between components to detect interface defects.
- Component tests - limit the scope of the exercised software to a portion of the system under test, manipulating the system through internal code interfaces and using test doubles to isolate the code under test from other components.
- Contract tests - verify interactions at the boundary of an external service asserting that it meets the contract expected by a consuming service.
- End-To-End tests - verify that a system meets external requirements and achieves its goals, testing the entire system, from end to end.
Hit F6
Insert::
npp_open $(PLUGINS_CONFIG_DIR)\..\..\shortcuts.xml
Click OK
You now have the file opened in your editor.
Before altering things checkout the related docs:
Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:
step 1)
create a .sh
file with the below content, say hive_table_ddl.sh
#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use $1; show tables;" > tableNames.txt
wait
cat tableNames.txt |while read LINE
do
hive -e "use $1;show create table $LINE;" >>HiveTableDDL.txt
echo -e "\n" >> HiveTableDDL.txt
done
rm -f tableNames.txt
echo "Table DDL generated"
step 2)
Run the above shell script by passing 'db name' as paramanter
>bash hive_table_dd.sh <<databasename>>
output :
All the create table statements of your DB will be written into the HiveTableDDL.txt
Bear in mind that ES6 Sets/Maps don't appear to be reactive as far as i can tell, at time of writing.
I'll slightly expand @assylias answer to take time zone into account. There are at least two ways to get LocalDateTime for specific time zone.
You can use setDefault time zone for whole application. It should be called before any timestamp -> java.time conversion:
public static void main(String... args) {
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(utcTimeZone);
...
timestamp.toLocalDateTime().toLocalDate();
}
Or you can use toInstant.atZone chain:
timestamp.toInstant()
.atZone(ZoneId.of("UTC"))
.toLocalDate();
@Howard Hinnant's answer is both correct and comprehensive. But it might be misunderstood if it's read too quickly, because std::terminate()
(whole process) happens to have the same name as the "terminating" that @Alexander V had in mind (1 thread).
Summary: "terminate 1 thread + forcefully (target thread doesn't cooperate) + pure C++11 = No way."
There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.
For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):
<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>
You can't initialize arrays like this:
int cipher[Array_size][Array_size]=0;
The syntax for 2D arrays is:
int cipher[Array_size][Array_size]={{0}};
Note the curly braces on the right hand side of the initialization statement.
for 1D arrays:
int tomultiply[Array_size]={0};
The below code is working,
<style>
.PanelFloat {
position: fixed;
overflow: hidden;
z-index: 2400;
opacity: 0.70;
right: 30px;
top: 0px !important;
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-ms-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
</style>
<script>
//The below script will keep the panel float on normal state
$(function () {
$(document).on('scroll', function () {
//Multiplication value shall be changed based on user window
$('#MyFloatPanel').css('top', 4 * ($(window).scrollTop() / 5));
});
});
//To make the panel float over a bootstrap model which has z-index: 2300, so i specified custom value as 2400
$(document).on('click', '.btnSearchView', function () {
$('#MyFloatPanel').addClass('PanelFloat');
});
$(document).on('click', '.btnSearchClose', function () {
$('#MyFloatPanel').removeClass('PanelFloat');
});
</script>
<div class="col-lg-12 col-md-12">
<div class="col-lg-8 col-md-8" >
//My scrollable content is here
</div>
//This below panel will float while scrolling the above div content
<div class="col-lg-4 col-md-4" id="MyFloatPanel">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">Panel Head </div>
<div class="panel-body ">//Your panel content</div>
</div>
</div>
</div>
</div>
The best solution is to get a copy of Node's type definitions. This will solve all kinds of dependency issues, not only require()
. This was previously done using packages like typings
, but as Mike Chamberlain mentioned, Typings are deprecated. The modern way is doing it like this:
npm install --save-dev @types/node
Not only will it fix the compiler error, it will also add the definitions of the Node API to your IDE.
I think that favicon.ico should be in root folder. It just belongs there.
If you want to servere diferent icons - put it into controler. You can do that. If not - just leave it in the root folder.
I encountered this issue due to mismatch between the runtime versions of the assemblies. Please verify the runtime versions of the main assembly (calling application) and the referred assembly
Arrow functions which is denoted by symbol (=>) helps you to create anonymous functions and methods. That leads to more shorter syntax. For example, below is a simple “Add” function which returns addition of two numbers.
function Add(num1 , num2 ){
return num1 + num2;
}
The above function becomes shorter by using “Arrow” syntax as shown below.
Above code has two parts as shown in the above diagram: -
Input: — This section specifies the input parameters to the anonymous function.
Logic: — This section comes after the symbol “=>”. This section has the logic of the actual function.
Many developers think that arrow function makes your syntax shorter, simpler and thus makes your code readable.
If you believe the above sentence, then let me assure you it’s a myth. If you think for a moment a properly written function with name is much readable than cryptic functions created in one line using an arrow symbol.
The main use of arrow function is to ensure that code runs in the callers context.
See the below code in which have a global variable "context" defined , this global variable is accessed inside a function "SomeOtherMethod" which is called from other method "SomeMethod".
This "SomeMethod" has local "context" variable. Now because "SomeOtherMethod" is called from ""SomeMethod" we expect it to display "local context" , but it displays "global context".
var context = “global context”;
function SomeOtherMethod(){
alert(this.context);
}
function SomeMethod(){
this.context = “local context”;
SomeOtherMethod();
}
var instance = new SomeMethod();
But if replace the call by using Arrow function it will display "local context".
var context = "global context";
function SomeMethod(){
this.context = "local context";
SomeOtherMethod = () => {
alert(this.context);
}
SomeOtherMethod();
}
var instance = new SomeMethod();
I would encourage you to read this link ( Arrow function in JavaScript ) which explain all the scenarios of javascript context and in which scenarios the callers context is not respected.
You can also see the demonstration of Arrow function with javascript in this youtube video which demonstrates practically the term Context.
This is a very bad idea for all of the reasons given, and more. That said, here's how you do it using jQuery:
<body>
<div id="msg" style="font-size:largest;">
<!-- you can set whatever style you want on this -->
Loading, please wait...
</div>
<div id="body" style="display:none;">
<!-- everything else -->
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#body').show();
$('#msg').hide();
});
</script>
</body>
If the user has JavaScript disabled, they never see the page. If the page never finishes loading, they never see the page. If the page takes too long to load, they may assume something went wrong and just go elsewhere instead of *please wait...*ing.
As per my understanding, When ever we execute print statements output will be written to buffer. And we will see the output on screen when buffer get flushed(cleared). By default buffer will be flushed when program exits. BUT WE CAN ALSO FLUSH THE BUFFER MANUALLY by using "sys.stdout.flush()" statement in the program. In the below code buffer will be flushed when value of i reaches 5.
You can understand by executing the below code.
chiru@online:~$ cat flush.py
import time
import sys
for i in range(10):
print i
if i == 5:
print "Flushing buffer"
sys.stdout.flush()
time.sleep(1)
for i in range(10):
print i,
if i == 5:
print "Flushing buffer"
sys.stdout.flush()
chiru@online:~$ python flush.py
0 1 2 3 4 5 Flushing buffer
6 7 8 9 0 1 2 3 4 5 Flushing buffer
6 7 8 9
I think you missed this step:
source ~/.nvm/nvm.sh
You can run this command on the bash OR you can put it in the file /.bashrc or ~/.profile or ~/.zshrc to automatically load it
What worked in my case is this:
I opened the pom.xml
and replaced the one of the plug-ins as below.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
Before I edited the source and target tags both had 1.8
, I changed that to 1.7
and it worked.
To break a loop, use break
instead of return
.
Or put the loop or control construct into a function, only functions can return values.
Use I
for "inline" to send the PDF to the browser, opposed to F
to save it as a file.
$pdf->Output('name.pdf', 'I');
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
try ORDER BY MONTH(Date),DAY(DATE)
Try this:
ORDER BY YEAR(Date) DESC, MONTH(Date) DESC, DAY(DATE) DESC
Worked perfectly on a JET DB.
Look carefully at your includes - perhaps you have a blank line after a closing ?> ?
This will cause some literal whitespace to be sent as output, preventing you from making subsequent header calls.
Note that it is legal to leave the close ?> off the include file, which is a useful idiom for avoiding this problem.
(EDIT: looking at your header, you need to avoid doing any HTML output if you want to output headers, or use output buffering to capture it).
Finally, as the PHP manual page for header points out, you should really use full URLs to redirect:
Note: HTTP/1.1 requires an absolute URI as argument to Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:
In a batch file I usually create a file in the temp directory and append output from a program, then I call it with a variable-name to set that variable. Like this:
:: Create a set_var.cmd file containing: set %1=
set /p="set %%1="<nul>"%temp%\set_var.cmd"
:: Append output from a command
ipconfig | find "IPv4" >> "%temp%\set_var.cmd"
call "%temp%\set_var.cmd" IPAddress
echo %IPAddress%
Its simple.. add this dependency in your project and create a button with 1. Any shape 2. Any color 3. Any border 4. With material effects
https://github.com/manojbhadane/QButton
<com.manojbhadane.QButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="OK"
app:qb_backgroundColor="@color/green"
app:qb_radius="100"
app:qb_strokeColor="@color/darkGreen"
app:qb_strokeWidth="5" />
Add "ref" to h1 tag :
<h1 ref="source">Hey there.</h1>
and
const { source } = this.props;
change to const { source } = this.refs;
The CSS solution for Angular Bootstrap is
::ng-deep .tooltip-inner {
white-space: pre-wrap;
}
No need to use a parent element or class selector if you don't need to restrict it's use. Copy/Pasta, and this rule will apply to all sub-components
As you can see in the Java Source of the java.lang.String class:
/**
* Allocates a new <code>String</code> that contains characters from
* a subarray of the character array argument. The <code>offset</code>
* argument is the index of the first character of the subarray and
* the <code>count</code> argument specifies the length of the
* subarray. The contents of the subarray are copied; subsequent
* modification of the character array does not affect the newly
* created string.
*
* @param value array that is the source of characters.
* @param offset the initial offset.
* @param count the length.
* @exception IndexOutOfBoundsException if the <code>offset</code>
* and <code>count</code> arguments index characters outside
* the bounds of the <code>value</code> array.
*/
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = new char[count];
this.count = count;
System.arraycopy(value, offset, this.value, 0, count);
}
Parameter references are surrounded by <code></code>
tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).
As the other have mentioned, the load event does not bubble. Instead you can manually trigger a load-like event with a custom event:
$('#item').on('namespace/onload', handleOnload).trigger('namespace/onload')
If your element is already listening to a change
event:
$('#item').on('change', handleChange).trigger('change')
I find this works well. Though, I stick to custom events to be more explicit and avoid side effects.
You can USE PyPDF2 package
#install pyDF2
pip install PyPDF2
# importing all the required modules
import PyPDF2
# creating an object
file = open('example.pdf', 'rb')
# creating a pdf reader object
fileReader = PyPDF2.PdfFileReader(file)
# print the number of pages in pdf file
print(fileReader.numPages)
Follow this Documentation http://pythonhosted.org/PyPDF2/
You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility. This is still true in SQL Server 2014 - you cannot restore a 2014 backup on anything other than another 2014 box (or something newer).
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts
) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.
The compatibility mode setting just controls what T-SQL features are available to you - which can help to prevent accidentally using new features not available in other servers. But it does NOT change the internal file format for the .mdf
files - this is NOT a solution for that particular problem - there is no solution for restoring a backup from a newer version of SQL Server on an older instance.
You can pass all similar type values in the function while calling it. In the function definition put a array so that all the passed values can be collected in that array. e.g. .
static void demo (String ... stringArray) {
your code goes here where read the array stringArray
}
Old question but anyway !
Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)
So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!
Simple resolution: Open the csv file in excel & save it with different name file of csv format. Again try importing it spyder, Your problem will be resolved!
It is there to specify another column as the default id column of the other table, e.g. consider the following
TableA
id int identity
tableb_key varchar
TableB
id int identity
key varchar unique
// in class for TableA
@JoinColumn(name="tableb_key", referencedColumnName="key")
You have to add the jar/war of the module B in the module A and add the classpath in your new spring-module file. Just add this line
spring-moduleA.xml - is a file in module A under the resource folder. By adding this line, it imports all the bean definition from module A to module B.
MODULE B/ spring-moduleB.xml
import resource="classpath:spring-moduleA.xml"/>
<bean id="helloBeanB" class="basic.HelloWorldB">
<property name="name" value="BMVNPrj" />
</bean>
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Just append below property in your query and the first header or line int the record will not load or it will be skipped.
Try this
tblproperties ("skip.header.line.count"="1");
PROPAGATION_REQUIRED = 0; If DataSourceTransactionObject T1 is already started for Method M1. If for another Method M2 Transaction object is required, no new Transaction object is created. Same object T1 is used for M2.
PROPAGATION_MANDATORY = 2; method must run within a transaction. If no existing transaction is in progress, an exception will be thrown.
PROPAGATION_REQUIRES_NEW = 3; If DataSourceTransactionObject T1 is already started for Method M1 and it is in progress (executing method M1). If another method M2 start executing then T1 is suspended for the duration of method M2 with new DataSourceTransactionObject T2 for M2. M2 run within its own transaction context.
PROPAGATION_NOT_SUPPORTED = 4; If DataSourceTransactionObject T1 is already started for Method M1. If another method M2 is run concurrently. Then M2 should not run within transaction context. T1 is suspended till M2 is finished.
PROPAGATION_NEVER = 5; None of the methods run in transaction context.
An isolation level: It is about how much a transaction may be impacted by the activities of other concurrent transactions. It a supports consistency leaving the data across many tables in a consistent state. It involves locking rows and/or tables in a database.
The problem with multiple transaction
Scenario 1. If T1 transaction reads data from table A1 that was written by another concurrent transaction T2. If on the way T2 is rollback, the data obtained by T1 is invalid one. E.g. a=2 is original data. If T1 read a=1 that was written by T2. If T2 rollback then a=1 will be rollback to a=2 in DB. But, now, T1 has a=1 but in DB table it is changed to a=2.
Scenario2. If T1 transaction reads data from table A1. If another concurrent transaction (T2) update data on table A1. Then the data that T1 has read is different from table A1. Because T2 has updated the data on table A1. E.g. if T1 read a=1 and T2 updated a=2. Then a!=b.
Scenario 3. If T1 transaction reads data from table A1 with certain number of rows. If another concurrent transaction (T2) inserts more rows on table A1. The number of rows read by T1 is different from rows on table A1.
Scenario 1 is called Dirty reads.
Scenario 2 is called Non-repeatable reads.
Scenario 3 is called Phantom reads.
So, isolation level is the extend to which Scenario 1, Scenario 2, Scenario 3 can be prevented. You can obtain complete isolation level by implementing locking. That is preventing concurrent reads and writes to the same data from occurring. But it affects performance. The level of isolation depends upon application to application how much isolation is required.
ISOLATION_READ_UNCOMMITTED: Allows to read changes that haven’t yet been committed. It suffer from Scenario 1, Scenario 2, Scenario 3.
ISOLATION_READ_COMMITTED: Allows reads from concurrent transactions that have been committed. It may suffer from Scenario 2 and Scenario 3. Because other transactions may be updating the data.
ISOLATION_REPEATABLE_READ: Multiple reads of the same field will yield the same results untill it is changed by itself. It may suffer from Scenario 3. Because other transactions may be inserting the data.
ISOLATION_SERIALIZABLE: Scenario 1, Scenario 2, Scenario 3 never happen. It is complete isolation. It involves full locking. It affects performace because of locking.
You can test using:
public class TransactionBehaviour {
// set is either using xml Or annotation
DataSourceTransactionManager manager=new DataSourceTransactionManager();
SimpleTransactionStatus status=new SimpleTransactionStatus();
;
public void beginTransaction()
{
DefaultTransactionDefinition Def = new DefaultTransactionDefinition();
// overwrite default PROPAGATION_REQUIRED and ISOLATION_DEFAULT
// set is either using xml Or annotation
manager.setPropagationBehavior(XX);
manager.setIsolationLevelName(XX);
status = manager.getTransaction(Def);
}
public void commitTransaction()
{
if(status.isCompleted()){
manager.commit(status);
}
}
public void rollbackTransaction()
{
if(!status.isCompleted()){
manager.rollback(status);
}
}
Main method{
beginTransaction()
M1();
If error(){
rollbackTransaction()
}
commitTransaction();
}
}
You can debug and see the result with different values for isolation and propagation.
Usually, IllegalStateException
is used to indicate that "a method has been invoked at an illegal or inappropriate time." However, this doesn't look like a particularly typical use of it.
The code you've linked to shows that it can be thrown within that code at line 259 - but only after dumping a SQLException
to standard output.
We can't tell what's wrong just from that exception - and better code would have used the original SQLException
as a "cause" exception (or just let the original exception propagate up the stack) - but you should be able to see more details on standard output. Look at that information, and you should be able to see what caused the exception, and fix it.
You could use Range.Rows
, Range.Columns
or Range.Cells
. Each of these collections contain Range
objects.
Here's how you could modify Dick's example so as to work with Rows
:
Sub LoopRange()
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("A1:A6")
For Each rCell In rRng.Rows
Debug.Print rCell.Address, rCell.Value
Next rCell
End Sub
And Columns
:
Sub LoopRange()
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("A1:A6")
For Each rCol In rRng.Columns
For Each rCell In rCol.Rows
Debug.Print rCell.Address, rCell.Value
Next rCell
Next rCol
End Sub
Use position:fixed
on the video, set it to 100% width/height, and put a negative z-index
on it so it appears behind everything.
If you look at VideoJS, the controls are just html elements sitting on top of the video, using z-index to make sure they're above.
HTML
<video id="video_background" src="video.mp4" autoplay>
(Add webm and ogg sources to support more browsers)
CSS
#video_background {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: -1000;
}
It'll work in most HTML5 browsers, but probably not iPhone/iPad, where the video needs to be activated, and doesn't like elements over it.
You can use the UpdateProgress control:
Hi the problem is in FileDownloader class
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.
Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)
Attaching the working code with screenshots.
MainActivity.java
package com.example.downloadread;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void download(View v)
{
new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
}
public void view(View v)
{
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try{
startActivity(pdfIntent);
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
private class DownloadFile extends AsyncTask<String, Void, Void>{
@Override
protected Void doInBackground(String... strings) {
String fileUrl = strings[0]; // -> http://maven.apache.org/maven-1.x/maven.pdf
String fileName = strings[1]; // -> maven.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "testthreepdf");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try{
pdfFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
}
}
FileDownloader.java
package com.example.downloadread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadread"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.downloadread.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="download"
android:onClick="download" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/button1"
android:layout_marginTop="38dp"
android:text="view"
android:onClick="view" />
</RelativeLayout>
return numberString.TrimStart('0');
I wrote quick test program to demonstrate one difference:
#include <stdio.h>
enum {ENUM_DEFINED=16};
enum {ENUM_DEFINED=32};
#define DEFINED_DEFINED 16
#define DEFINED_DEFINED 32
int main(int argc, char *argv[]) {
printf("%d, %d\n", DEFINED_DEFINED, ENUM_DEFINED);
return(0);
}
This compiles with these errors and warnings:
main.c:6:7: error: redefinition of enumerator 'ENUM_DEFINED'
enum {ENUM_DEFINED=32};
^
main.c:5:7: note: previous definition is here
enum {ENUM_DEFINED=16};
^
main.c:9:9: warning: 'DEFINED_DEFINED' macro redefined [-Wmacro-redefined]
#define DEFINED_DEFINED 32
^
main.c:8:9: note: previous definition is here
#define DEFINED_DEFINED 16
^
Note that enum gives an error when define gives a warning.
Changing the data frames list into a list of tuples.
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
print(df)
OUTPUT
col1 col2
0 1 4
1 2 5
2 3 6
records = df.to_records(index=False)
result = list(records)
print(result)
OUTPUT
[(1, 4), (2, 5), (3, 6)]
Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
Why not use Model.update? After all you're not using the found user for anything else than to update it's properties:
User.update({username: oldUsername}, {
username: newUser.username,
password: newUser.password,
rights: newUser.rights
}, function(err, numberAffected, rawResponse) {
//handle it
})
People gave good answers but forgot to mention the most important part in my opinion:
In the second example the X
of the list comprehension is NOT the same as the X
of the lambda
function, they are totally unrelated.
So the second example is actually the same as:
[Lambda X: X*X for I in range(10)]
The internal iterations on range(10)
are only responsible for creating 10 similar lambda functions in a list (10 separate functions but totally similar - returning the power 2 of each input).
On the other hand, the first example works totally different, because the X of the iterations DO interact with the results, for each iteration the value is X*X
so the result would be [0,1,4,9,16,25, 36, 49, 64 ,81]
You probably need to do something like :
Paint red = new Paint();
red.setColor(android.graphics.Color.RED);
red.setStyle(Paint.Style.FILL);
And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the first one, it makes sense also.
Tell me if it works please !
SELECT TOP 1 column_name, LEN(column_name) AS Lenght FROM table_name ORDER BY LEN(column_name) DESC
Use conditional formatting.
You can enter a condition using any cell you like and a format to apply if the formula is true.
This should fulfill your requirements.
ABC:\s*(\(\D+\)\s*.*?)\\n
Here it is with some tests http://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyDgsSBlJlY2lwZRiEjiUM/index.html
Futher reading on regular expressions: http://www.regular-expressions.info/characters.html
I had same problem. After one day, I got it.
Problem was from adding two smtp
tags in mailSettings
under <system.net>
.
Here's some functional code (Java 8) which returns the x position of the right most edge of the right most screen. If no screens are found, then it returns 0.
GraphicsDevice devices[];
devices = GraphicsEnvironment.
getLocalGraphicsEnvironment().
getScreenDevices();
return Stream.
of(devices).
map(GraphicsDevice::getDefaultConfiguration).
map(GraphicsConfiguration::getBounds).
mapToInt(bounds -> bounds.x + bounds.width).
max().
orElse(0);
Here are links to the JavaDoc.
GraphicsEnvironment.getLocalGraphicsEnvironment()
GraphicsEnvironment.getScreenDevices()
GraphicsDevice.getDefaultConfiguration()
GraphicsConfiguration.getBounds()
It is possible to upack without node installed using the following 7-Zip plugin:
http://www.tc4shell.com/en/7zip/asar/
Thanks @MayaPosch for mentioning that in this comment.
As neat solution, try-
$ open -a /Applications/Utilities/Terminal.app *.py
or
$ open -b com.apple.terminal *.py
For the shell launched, you can go to Preferences > Shell > set it to exit if no error.
That's it.
Your rows
object holds an Item
attribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString()
on the row.
You should access each column from the row separately, use a for
or a foreach
to walk the array of columns.
Here, take a look at the class:
http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx
With RubyMotion / RedPotion, paste this into your TableScreen:
def tableView(_, willDisplayHeaderView: view, forSection: section)
view.textLabel.textColor = rmq.color.your_text_color
view.contentView.backgroundColor = rmq.color.your_background_color
end
Works like a charm!
The answers presented before mine provide apt solutions to the problem, however, I feel that it is important to understand why this error results:
The Session
property of the Page
returns an instance of type HttpSessionState
relative to that particular request. Page.Session
is actually equivalent to calling Page.Context.Session
.
MSDN explains how this is possible:
Because ASP.NET pages contain a default reference to the System.Web namespace (which contains the
HttpContext
class), you can reference the members ofHttpContext
on an .aspx page without the fully qualified class reference toHttpContext
.
However, When you try to access this property within a class in App_Code, the property will not be available to you unless your class derives from the Page Class.
My solution to this oft-encountered scenario is that I never pass page objects to classes. I would rather extract the required objects from the page Session and pass them to the Class in the form of a name-value collection / Array / List, depending on the case.
I was facing a similar issue and found that a few fields like Date were not getting a concrete value, once given the values things worked fine. Please make sure you do not have date or any other field present on the form which needs a concrete value.
Just open file by nano /file_name
Once done, press CTRL+O and then Enter to save. Then press CTRL+X to return.
Here CTRL+O : is CTRL and O for Orange Not 0 Zero
If you install PHP with homebrew, you can switch between versions very easily. Say you want php56
to point to Version 5.6.17, you just do:
brew switch php56 5.6.17
Use Python 2.7, is has more 3rd party libs at the moment. (Edit: see below).
I recommend you using the stdlib module urllib2
, it will allow you to comfortably get web resources.
Example:
import urllib2
response = urllib2.urlopen("http://google.de")
page_source = response.read()
For parsing the code, have a look at BeautifulSoup
.
BTW: what exactly do you want to do:
Just for background, I need to download a page and replace any img with ones I have
Edit: It's 2014 now, most of the important libraries have been ported, and you should definitely use Python 3 if you can. python-requests
is a very nice high-level library which is easier to use than urllib2
.
It works like this:
mpintro = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/intro.mp3"));
mpintro.setLooping(true);
mpintro.start();
It did not work properly as string filepath...
Please note on iPad Safari, NoviceCoding's solution won't work if you have -webkit-overflow-scrolling: touch;
somewhere in your CSS.
The solution is either removing all the occurrences of -webkit-overflow-scrolling: touch;
or putting -webkit-overflow-scrolling: auto;
with
NoviceCoding's solution.
The solution was to call...
$scope.$apply();
...in my jQuery event callback.
If the DataGridView
has been populated by DataSource = x
(i.e. is databound) then you need to change the bound data, not the DataGridView cells themselves.
One way of getting to that data from a known row or column is thus:
(YourRow.DataBoundItem as DataRowView).Row['YourColumn'] = NewValue;
On Button
click event write this:
Uri uri = Uri.parse("http://www.google.com"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
that open the your URL.
I am using PostgreSQL with closure tables for my hierarchies. I have one universal stored procedure for the whole database:
CREATE FUNCTION nomen_tree() RETURNS trigger
LANGUAGE plpgsql
AS $_$
DECLARE
old_parent INTEGER;
new_parent INTEGER;
id_nom INTEGER;
txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
IF TG_OP = 'INSERT' THEN
EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
SELECT $1.id,$1.id,0 UNION ALL
SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
ELSE
-- EXECUTE does not support conditional statements inside
EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
EXECUTE '
-- prevent cycles in the tree
UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
|| ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
|| TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
-- first remove edges between all old parents of node and its descendants
DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
(SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
AND ancestor_id IN
(SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
-- then add edges for all new parents ...
INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
SELECT child_id,ancestor_id,d_c+d_a FROM
(SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
CROSS JOIN
(SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.'
|| TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
END IF;
END IF;
RETURN NULL;
END;
$_$;
Then for each table where I have a hierarchy, I create a trigger
CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');
For populating a closure table from existing hierarchy I use this stored procedure:
CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
EXECUTE 'TRUNCATE ' || tbl_closure || ';
INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth)
WITH RECURSIVE tree AS
(
SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
UNION ALL
SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
JOIN tree ON child_id = ' || fld_parent || '
)
SELECT * FROM tree;';
END;
$$;
Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:
-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;
0 */2 * * *
The answer is from https://crontab.guru/every-2-hours. It is interesting.
Old one but I would add my answer as per my findings:
var ancestralState = context.findAncestorStateOfType<ParentState>();
ancestralState.setState(() {
// here you can access public vars and update state.
...
});
A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common
only returns a tuple. I often couple this with a json output for handy log files:
from collections import Counter, OrderedDict
x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())
With the output:
OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
"c": 7,
"a": 5,
"b": 3
}
With the newer Spring versions One can do as follows:
If not using native query this can done as below:
public interface ProjectMini {
String getProjectId();
String getProjectName();
}
public interface ProjectRepository extends JpaRepository<Project, String> {
@Query("SELECT p FROM Project p")
List<ProjectMini> findAllProjectsMini();
}
Using native query the same can be done as below:
public interface ProjectRepository extends JpaRepository<Project, String> {
@Query(value = "SELECT projectId, projectName FROM project", nativeQuery = true)
List<ProjectMini> findAllProjectsMini();
}
For detail check the docs
A quick search using...
apt search Xlib.h
Turns up the package libx11-dev but you shouldn't need this for pure OpenGL programming. What tutorial are you using?
You can add Xlib.h to your system by running the following...
sudo apt install libx11-dev
Just complementing the answer.
Merging the last tag on a branch:
git checkout my-branch
git merge $(git describe --tags $(git rev-list --tags --max-count=1))
Inspired by https://gist.github.com/rponte/fdc0724dd984088606b0
If you only have one occurrence of the target string you can use:
str[target] = ''
or
str.sub(target, '')
If you have multiple occurrences of target use:
str.gsub(target, '')
For instance:
asdf = 'foo bar'
asdf['bar'] = ''
asdf #=> "foo "
asdf = 'foo bar'
asdf.sub('bar', '') #=> "foo "
asdf = asdf + asdf #=> "foo barfoo bar"
asdf.gsub('bar', '') #=> "foo foo "
If you need to do in-place substitutions use the "!"
versions of gsub!
and sub!
.
error: package android.support.v4.content does not exist import android.support.v4.content.FileProvider;
using jetify helped to solve .
from jcesarmobile' s post --- >https://github.com/ionic-team/capacitor/pull/2832
Error: "package android.support.* does not exist" This error occurs when some Cordova or Capacitor plugin has old android support dependencies instead of using the new AndroidX equivalent. You should report the issue in the plugin repository so the maintainers can update the plugin to use AndroidX dependencies.
As workaround you can also patch the plugin using jetifier
npm install jetifier
npx jetify
npx cap sync android
html_entity_decode('エ', 0, 'UTF-8');
This works too. However the json_decode() solution is a lot faster (around 50 times).
Ctrl + C + V works for me on VS2012 with no extension.
I made this in my code to do that
note: I am a beginner.
It is my jsp code.
<%
java.sql.Connection Conn = DBconnector.SetDBConnection(); /* make connector as you make in your code */
Statement st = null;
ResultSet rs = null;
st = Conn.createStatement();
rs = st.executeQuery("select * from department"); %>
<tr>
<td>
Student Major : <select name ="Major">
<%while(rs.next()){ %>
<option value="<%=rs.getString(1)%>"><%=rs.getString(1)%></option>
<%}%>
</select>
</td>
Step 1: Add following content to the file .gitignore.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
_x000D_
Step 2: Make sure take effect
If the issue still exists, that's because settings in .gitignore can only ignore files that were originally not tracked. If some files have already been included in the version control system, then modifying .gitignore is invalid. To solve this issue completely, you need to open Git Bash or Package Manager Console (see screenshot below) to run following commands in the repository root folder.
git rm -r --cached .
git add .
git commit -m "Update .gitignore"
_x000D_
I will answer this question in terms of AngularFire, Firebase's library for Angular.
Tl;dr: superpowers. :-)
AngularFire's three-way data binding. Angular binds the view and the $scope, i.e., what your users do in the view automagically updates in the local variables, and when your JavaScript updates a local variable the view automagically updates. With Firebase the cloud database also updates automagically. You don't need to write $http.get or $http.put requests, the data just updates.
Five-way data binding, and seven-way, nine-way, etc. I made a tic-tac-toe game using AngularFire. Two players can play together, with the two views updating the two $scopes and the cloud database. You could make a game with three or more players, all sharing one Firebase database.
AngularFire's OAuth2 library makes authorization easy with Facebook, GitHub, Google, Twitter, tokens, and passwords.
Double security. You can set up your Angular routes to require authorization, and set up rules in Firebase about who can read and write data.
There's no back end. You don't need to make a server with Node and Express. Running your own server can be a lot of work, require knowing about security, require that someone do something if the server goes down, etc.
Fast. If your server is in San Francisco and the client is in San Jose, fine. But for a client in Bangalore connecting to your server will be slower. Firebase is deployed around the world for fast connections everywhere.
You can make a view with a different dtype, and then copy in-place into the view:
import numpy as np
x = np.arange(10, dtype='int32')
y = x.view('float32')
y[:] = x
print(y)
yields
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float32)
To show the conversion was in-place, note that copying from x
to y
altered x
:
print(x)
prints
array([ 0, 1065353216, 1073741824, 1077936128, 1082130432,
1084227584, 1086324736, 1088421888, 1090519040, 1091567616])
I found this also works...
var select = document.getElementById("selectNumber");
var options = ["1", "2", "3", "4", "5"];
// Optional: Clear all existing options first:
select.innerHTML = "";
// Populate list with options:
for(var i = 0; i < options.length; i++) {
var opt = options[i];
select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}
The emulator tries to find a numeric keypad on the mac, but this is not found (MacBook Pro, MacBook Air and "normal/small" keyboard do not have it). You can deselect the option Connect Hardware Keyboard or just ignore the error message, it will have no negative effect on application.
For those whose any solution did not work, try:
cd /etc/mysql
check if my.cnf is present
nano my.cnf
and make sure you have only one bind-address as follows:
bind-address = 127.0.0.1
If not, that might be the problem, just exit nano and save the file.
and service mysql start
note that if you don't have nano (its a text editor) just install it with apt-get install nano
and once in just press Ctrl+X to exit, dont forget to say Y to save and use the same file)
I was recently struggling with a similar problem. It turned out that the database was missing indexes on foreign keys. That caused Oracle to lock many more records than required which quickly led to a deadlock during high concurrency.
Here is an excellent article with lots of good detail, suggestions, and details about how to fix a deadlock: http://www.oratechinfo.co.uk/deadlocks.html#unindex_fk
FYI, you can substitute the /*csv*/
for other formats as well including /*xml*/
and /*html*/
.
select /*xml*/ * from emp
would return an xml document with the query results for example.
I came across this article while looking for an easy way to return xml from a query.
Take a look on MDN
It will render html element using creating SVG images.
For Example:
There is <em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>
HTML element. And I want to add it into <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
Canvas Element.
Here is Javascript Code to add HTML element to canvas.
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
_x000D_
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +_x000D_
'<foreignObject width="100%" height="100%">' +_x000D_
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +_x000D_
'<em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>' +_x000D_
'</div>' +_x000D_
'</foreignObject>' +_x000D_
'</svg>';_x000D_
_x000D_
var DOMURL = window.URL || window.webkitURL || window;_x000D_
_x000D_
var img = new Image();_x000D_
var svg = new Blob([data], {_x000D_
type: 'image/svg+xml;charset=utf-8'_x000D_
});_x000D_
var url = DOMURL.createObjectURL(svg);_x000D_
_x000D_
img.onload = function() {_x000D_
ctx.drawImage(img, 0, 0);_x000D_
DOMURL.revokeObjectURL(url);_x000D_
}_x000D_
_x000D_
img.src = url;
_x000D_
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
_x000D_
You care about two things when querying - accuracy and performance. With that in mind, I tested a few different approaches in MongoDB v3.0.14.
TL;DR db.doc.find({ nums: { $gt: -Infinity }})
is the fastest and most reliable (at least in the MongoDB version I tested).
EDIT: This no longer works in MongoDB v3.6! See the comments under this post for a potential solution.
I inserted 1k docs w/o a list field, 1k docs with an empty list, and 5 docs with a non-empty list.
for (var i = 0; i < 1000; i++) { db.doc.insert({}); }
for (var i = 0; i < 1000; i++) { db.doc.insert({ nums: [] }); }
for (var i = 0; i < 5; i++) { db.doc.insert({ nums: [1, 2, 3] }); }
db.doc.createIndex({ nums: 1 });
I recognize this isn't enough of a scale to take performance as seriously as I am in the tests below, but it's enough to present the correctness of various queries and behavior of chosen query plans.
db.doc.find({'nums': {'$exists': true}})
returns wrong results (for what we're trying to accomplish).
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': {'$exists': true}}).count()
1005
--
db.doc.find({'nums.0': {'$exists': true}})
returns correct results, but it's also slow using a full collection scan (notice COLLSCAN
stage in the explanation).
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': {'$exists': true}}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': {'$exists': true}}).explain()
{
"queryPlanner": {
"plannerVersion": 1,
"namespace": "test.doc",
"indexFilterSet": false,
"parsedQuery": {
"nums.0": {
"$exists": true
}
},
"winningPlan": {
"stage": "COLLSCAN",
"filter": {
"nums.0": {
"$exists": true
}
},
"direction": "forward"
},
"rejectedPlans": [ ]
},
"serverInfo": {
"host": "MacBook-Pro",
"port": 27017,
"version": "3.0.14",
"gitVersion": "08352afcca24bfc145240a0fac9d28b978ab77f3"
},
"ok": 1
}
--
db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}})
returns wrong results. That's because of an invalid index scan advancing no documents. It will likely be accurate but slow without the index.
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}}).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}}).explain('executionStats').executionStats.executionStages
{
"stage": "KEEP_MUTATIONS",
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 2,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"inputStage": {
"stage": "FETCH",
"filter": {
"$and": [
{
"nums": {
"$gt": {
"$size": 0
}
}
},
{
"nums": {
"$exists": true
}
}
]
},
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 1,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"docsExamined": 0,
"alreadyHasObj": 0,
"inputStage": {
"stage": "IXSCAN",
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 1,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"keyPattern": {
"nums": 1
},
"indexName": "nums_1",
"isMultiKey": true,
"direction": "forward",
"indexBounds": {
"nums": [
"({ $size: 0.0 }, [])"
]
},
"keysExamined": 0,
"dupsTested": 0,
"dupsDropped": 0,
"seenInvalidated": 0,
"matchTested": 0
}
}
}
--
db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}})
returns correct results, but the performance is bad. It technically does an index scan, but then it still advances all the docs and then has to filter through them).
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}}).explain('executionStats').executionStats.executionStages
{
"stage": "KEEP_MUTATIONS",
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 2016,
"advanced": 5,
"needTime": 2010,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"inputStage": {
"stage": "FETCH",
"filter": {
"$and": [
{
"nums": {
"$exists": true
}
},
{
"$not": {
"nums": {
"$size": 0
}
}
}
]
},
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 2016,
"advanced": 5,
"needTime": 2010,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"docsExamined": 2005,
"alreadyHasObj": 0,
"inputStage": {
"stage": "IXSCAN",
"nReturned": 2005,
"executionTimeMillisEstimate": 0,
"works": 2015,
"advanced": 2005,
"needTime": 10,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"keyPattern": {
"nums": 1
},
"indexName": "nums_1",
"isMultiKey": true,
"direction": "forward",
"indexBounds": {
"nums": [
"[MinKey, MaxKey]"
]
},
"keysExamined": 2015,
"dupsTested": 2015,
"dupsDropped": 10,
"seenInvalidated": 0,
"matchTested": 0
}
}
}
--
db.doc.find({'nums': { $exists: true, $ne: [] }})
returns correct results and is slightly faster, but the performance is still not ideal. It uses IXSCAN which only advances docs with an existing list field, but then has to filter out the empty lists one by one.
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $ne: [] }}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $ne: [] }}).explain('executionStats').executionStats.executionStages
{
"stage": "KEEP_MUTATIONS",
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 1018,
"advanced": 5,
"needTime": 1011,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"inputStage": {
"stage": "FETCH",
"filter": {
"$and": [
{
"$not": {
"nums": {
"$eq": [ ]
}
}
},
{
"nums": {
"$exists": true
}
}
]
},
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 1017,
"advanced": 5,
"needTime": 1011,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"docsExamined": 1005,
"alreadyHasObj": 0,
"inputStage": {
"stage": "IXSCAN",
"nReturned": 1005,
"executionTimeMillisEstimate": 0,
"works": 1016,
"advanced": 1005,
"needTime": 11,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"keyPattern": {
"nums": 1
},
"indexName": "nums_1",
"isMultiKey": true,
"direction": "forward",
"indexBounds": {
"nums": [
"[MinKey, undefined)",
"(undefined, [])",
"([], MaxKey]"
]
},
"keysExamined": 1016,
"dupsTested": 1015,
"dupsDropped": 10,
"seenInvalidated": 0,
"matchTested": 0
}
}
}
--
db.doc.find({'nums': { $gt: [] }})
IS DANGEROUS BECAUSE DEPENDING ON THE INDEX USED IT MIGHT GIVE UNEXPECTED RESULTS. That's because of an invalid index scan which advances no documents.
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).hint({ nums: 1 }).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).hint({ _id: 1 }).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).explain('executionStats').executionStats.executionStages
{
"stage": "KEEP_MUTATIONS",
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 1,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"inputStage": {
"stage": "FETCH",
"filter": {
"nums": {
"$gt": [ ]
}
},
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 1,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"docsExamined": 0,
"alreadyHasObj": 0,
"inputStage": {
"stage": "IXSCAN",
"nReturned": 0,
"executionTimeMillisEstimate": 0,
"works": 1,
"advanced": 0,
"needTime": 0,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"keyPattern": {
"nums": 1
},
"indexName": "nums_1",
"isMultiKey": true,
"direction": "forward",
"indexBounds": {
"nums": [
"([], BinData(0, ))"
]
},
"keysExamined": 0,
"dupsTested": 0,
"dupsDropped": 0,
"seenInvalidated": 0,
"matchTested": 0
}
}
}
--
db.doc.find({'nums.0’: { $gt: -Infinity }})
returns correct results, but has bad performance (uses a full collection scan).
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': { $gt: -Infinity }}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': { $gt: -Infinity }}).explain('executionStats').executionStats.executionStages
{
"stage": "COLLSCAN",
"filter": {
"nums.0": {
"$gt": -Infinity
}
},
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 2007,
"advanced": 5,
"needTime": 2001,
"needFetch": 0,
"saveState": 15,
"restoreState": 15,
"isEOF": 1,
"invalidates": 0,
"direction": "forward",
"docsExamined": 2005
}
--
db.doc.find({'nums': { $gt: -Infinity }})
surprisingly, this works very well! It gives the right results and it's fast, advancing 5 docs from the index scan phase.
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: -Infinity }}).explain('executionStats').executionStats.executionStages
{
"stage": "FETCH",
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 16,
"advanced": 5,
"needTime": 10,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"docsExamined": 5,
"alreadyHasObj": 0,
"inputStage": {
"stage": "IXSCAN",
"nReturned": 5,
"executionTimeMillisEstimate": 0,
"works": 15,
"advanced": 5,
"needTime": 10,
"needFetch": 0,
"saveState": 0,
"restoreState": 0,
"isEOF": 1,
"invalidates": 0,
"keyPattern": {
"nums": 1
},
"indexName": "nums_1",
"isMultiKey": true,
"direction": "forward",
"indexBounds": {
"nums": [
"(-inf.0, inf.0]"
]
},
"keysExamined": 15,
"dupsTested": 15,
"dupsDropped": 10,
"seenInvalidated": 0,
"matchTested": 0
}
}
To sum it up, #pragma
tells the compiler to do stuff. Here are a couple of ways I use it:
#pragma
can be used to ignore compiler warnings. For example, to make GCC shut up about implicit function declarations, you can write:
#pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
An older version of libportable
does this portably.
#pragma once
, when written at the top of a header file, will cause said header file to be included once. libportable
checks for pragma once support.
select convert(varchar(8), getdate(), 3)
simply use this for dd/mm/yy and this
select convert(varchar(8), getdate(), 1)
for mm/dd/yy
If the remote server is using SNI (that is, sharing multiple SSL hosts on a single IP address) you will need to send the correct hostname in order to get the right certificate.
openssl s_client -showcerts -servername www.example.com -connect www.example.com:443 </dev/null
If the remote server is not using SNI, then you can skip -servername
parameter:
openssl s_client -showcerts -connect www.example.com:443 </dev/null
To view the full details of a site's cert you can use this chain of commands as well:
$ echo | \
openssl s_client -servername www.example.com -connect www.example.com:443 2>/dev/null | \
openssl x509 -text
Here is example of taking XML file from raw folder:
InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML
Then you can:
String sxml = readTextFile(XmlFileInputStream);
when:
public String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
You can add header "Content-Type: text/html; charset=UTF-8" to your message body.
$headers = "Content-Type: text/html; charset=UTF-8";
If you use native mail()
function $headers array will be the 4th parameter
mail($to, $subject, $message, $headers)
If you user PEAR Mail::factory() code will be:
$smtp = Mail::factory('smtp', $params);
$mail = $smtp->send($to, $headers, $body);
I think one error in the original code might have been that it had:
$message = echo getRequestURI();
instead of:
$message = getRequestURI();
(The code has since been edited though.)
From 6.11. Boolean operations:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.
The expression '/bla/bla/bla'
will be treated as true where a Boolean expression is expected (like in an if
statement), but the expressions '/bla/bla/bla' is True
and '/bla/bla/bla' == True
will evaluate to False for the reasons in Ignacio's answer.
In regards to @bmasterswizzle
's BRILLIANT answer - more specifically - to @DanRamos
' question about how to force the new interface's link-state to "up".. I use this script, of whose origin I cannot recall, but which works fabulously (in coordination with @bmasterswizzles "Mona Lisa" of answers)...
#!/bin/zsh
[[ "$UID" -ne "0" ]] && echo "You must be root. Goodbye..." && exit 1
echo "starting"
exec 4<>/dev/tap0
ifconfig tap0 10.10.10.1 10.10.10.255
ifconfig tap0 up
ping -c1 10.10.10.1
echo "ending"
export PS1="tap interface>"
dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null
I am NOT quite sure I understand the alteration to the prompt at the end, or...
dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null
but WHATEVER. it works. link light: green?. loves it.
install nvm (Node Version Manager) and downgrade node version from 14 to 12 solved the issue in my case
The width will be rounded to an integer number of pixels.
I don't know if every browser will round it the same way though. They all seem to have a different strategy when rounding sub-pixel percentages. If you're interested in the details of sub-pixel rounding in different browsers, there's an excellent article on ElastiCSS.
edit: I tested @Skilldrick's demo in some browsers for the sake of curiosity. When using fractional pixel values (not percentages, they work as suggested in the article I linked) IE9p7 and FF4b7 seem to round to the nearest pixel, while Opera 11b, Chrome 9.0.587.0 and Safari 5.0.3 truncate the decimal places. Not that I hoped that they had something in common after all...
It's undefined; doing things like Jon Skeet suggested will get you an approximation on a given platform, but the way to know precisely for a specific platform is to use a profiler.
In the project path Terminal django_project#
sudo chown django:django *
You can simply use Substring
method of C#. For ex.
string str = "1110000";
string lastFourDigits = str.Substring((str.Length - 4), 4);
It will return result 0000.
'\r' = carriage return and '\n' = line feed.
In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.
I tried all the above solution but nothing worked for me. I did some brainstorming and found this and worked fine in IE11 as well.
value="2020-08-10 05:22:44.0";
var date=new Date(value.replace(" ","T")).$format("d/m/yy h:i:s");
console.log(date);
_x000D_
if $format is not working for you use format only.
I don't have enough reputation to comment on any answer. In one of the comments, someone has asked how to ignore the hidden folders in the list. Below is how you can do this.
dir /b /AD-H
SQL
a language for talking to the
database. It lets you select data,
mutate and create database objects
(like tables, views, etc.), change
database settings.PL-SQL
a procedural programming language (with embedded SQL) T-SQL
(procedural) extensions for SQL used
by SQL Servertv.setText(Integer.toString(intValue))
I have the same problem. I have resolved the problem with following code:
app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/css',express.static(path.join(__dirname, 'public/stylesheets')));
Static request example:
http://pruebaexpress.lite.c9.io/js/socket.io.js
I need a more simple solution. Does it exist?
var args = [ 'p0', 'p1', 'p2' ];
function call_me (param0, param1, param2 ) {
// ...
}
// Calling the function using the array with apply()
call_me.apply(this, args);
And here a link to the original post that I personally liked for its readability
I had a similar problem in a MS-Access query, and I solved it by changing my equivalent fName
to an "Expression" (as opposed to "Group By" or "Sum"). So long as all of my fields were "Expression", the Access query builder did not require any Group By
clause at the end.
Instead of navigating through the commits, you can also hit the y key (Github Help, Keyboard Shortcuts) to get the "permalink" for the current revision / commit.
This will change the URL from https://github.com/<user>/<repository>
(master / HEAD) to https://github.com/<user>/<repository>/tree/<commit id>
.
In order to download the specific commit, you'll need to reload the page from that URL, so the Clone or Download
button will point to the "snapshot" https://github.com/<user>/<repository>/archive/<commit id>.zip
instead of the latest https://github.com/<user>/<repository>/archive/master.zip
.