because your jQuery code is wrong. Correctly would be:
var theParent = $(this).parent().get(0);
$(theParent).css('z-index', 3000);
The accepted answer does not tell the entire story.
Yes, whenever you see zeros, a NULL
pointer is involved. That is because NULL
is by definition zero. So calling zero NULL
may not be saying much.
What is interesting about the message you get is the fact that NULL
is mentioned twice. In fact, the message you report looks a little bit like the messages Windows-brand operating systems show the user.
The message says the address NULL
tried to read NULL
. So what does that mean? Specifically, how does an address read itself?
We typically think of the instructions at an address reading and writing from memory at certain addresses. Knowing that allows us to parse the error message. The message is trying to articulate that the instruction at address NULL
tried to read NULL
.
Of course, there is no instruction at address NULL
, that is why we think of NULL
as special in our code. But every instruction can be thought of as commencing with the attempt to read itself. If the CPUs EIP
register is at address NULL
, then the CPU will attempt to read the opcode for an instruction from address 0x00000000 (NULL
). This attempt to read NULL
will fail, and generate the message you have received.
In the debugger, notice that EIP
equals 0x00000000 when you receive this message. This confirms the description I have given you.
The question then becomes, "why does my program attempt to execute the NULL
address." There are three possibilities which spring to mind:
NULL
, never initialized otherwise, and are dereferencing.NULL
entry in the object's vtable. These are created in your code with the syntax virtual function_name()=0
.ret
instruction, the value 0x00000000 (NULL
) is loaded from the overwritten memory spot. This type of error, stack overflow, is the eponym of our forum.Since you mention that you are calling a third-party library, I will point out that it may be a situation of the library expecting you to provide a non-NULL
function pointer as input to some API. These are sometimes known as "call back" functions.
You will have to use the debugger to narrow down the cause of your problem further, but the above possiblities should help you solve the riddle.
You can use a modulus to get the remainder. Though @cnicutar's answer seems cleaner/more direct.
Did you try something like:
body {background: url('[url to your image]') no-repeat right bottom;}
Here is a solution in case you use jquery and Facebook Asynchronous Lazy Loading:
// listen to an Event
$(document).bind('fbInit',function(){
console.log('fbInit complete; FB Object is Available');
});
// FB Async
window.fbAsyncInit = function() {
FB.init({appId: 'app_id',
status: true,
cookie: true,
oauth:true,
xfbml: true});
$(document).trigger('fbInit'); // trigger event
};
How about:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));
> 31/05/2011
Use an ID to uniquely identify the checkbox. Your current example is trying to select the checkbox with an id of '#chk0':
<input type="checkbox" id="chk0" name="chk0" value="true" disabled>
$('#chk0').attr("disabled", "disabled");
You'll also need to remove the attribute for disabled
to enable the checkbox. Something like:
$('#chk0').removeAttr("disabled");
See the docs for removeAttr
The value XHTML for disabling/enabling an input element is as follows:
<input type="checkbox" id="chk0" name="chk0" value="true" disabled="disabled" />
<input type="checkbox" id="chk0" name="chk0" value="true" />
Note that it's the absence of the disabled attribute that makes the input element enabled.
First you need to allocate an array of the combined length, then use arraycopy to fill it from both sources.
byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = new byte[ciphertext.length + mac.length];
System.arraycopy(ciphertext, 0, out, 0, ciphertext.length);
System.arraycopy(mac, 0, out, ciphertext.length, mac.length);
One-liner:
if (!dir.exists(output_dir)) {dir.create(output_dir)}
Example:
dateDIR <- as.character(Sys.Date())
outputDIR <- file.path(outD, dateDIR)
if (!dir.exists(outputDIR)) {dir.create(outputDIR)}
Well I used the advice here and it screwed me as it merged my local code directly to master. .... so take it all with a grain of salt. My coworker said the following helped resolve the issue, needed to repoint my branch.
git branch --set-upstream-to=origin/feature/my-current-branch feature/my-current-branch
Its a very late answer, but you can also use the Collections.singleton
:
List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
list.removeAll(Collections.singleton(null));
list.removeAll(Collections.singleton(""));
So if you're like me and developing a website on localhost where you're trying to fetch data from Laravel API and use it in your Vue front-end, and you see this problem, here is how I solved it:
php artisan make:middleware Cors
. This will create app/Http/Middleware/Cors.php
for you.Add the following code inside the handles
function in Cors.php
:
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
In app/Http/kernel.php
, add the following entry in $routeMiddleware
array:
‘cors’ => \App\Http\Middleware\Cors::class
(There would be other entries in the array like auth
, guest
etc. Also make sure you're doing this in app/Http/kernel.php
because there is another kernel.php
too in Laravel)
Add this middleware on route registration for all the routes where you want to allow access, like this:
Route::group(['middleware' => 'cors'], function () {
Route::get('getData', 'v1\MyController@getData');
Route::get('getData2', 'v1\MyController@getData2');
});
mounted()
function and not in data()
. Also make sure you use http://
or https://
with the URL in your fetch()
call.Full credits to Pete Houston's blog article.
You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings. For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:
<?php
$string = 'Cién cañones por banda';
echo mb_strlen($string, '8bit');
?>
You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php
For trim the string by byte length without split in middle of a multibyte character you can use:
mb_strcut(string $str, int $start [, int $length [, string $encoding ]] )
UPDATE: From the comments this answer seems to be out of date
The Flutter documentation points out where you can change the display name of your application for both Android and iOS. This may be what you are looking for:
For Android
It seems you have already found this in the AndroidManifest.xml
as the application
entry.
Review the default App Manifest file AndroidManifest.xml located in /android/app/src/main/ and verify the values are correct, especially:
application: Edit the application tag to reflect the final name of the app.
For iOS
See the Review Xcode project settings
section:
Navigate to your target’s settings in Xcode:
In Xcode, open Runner.xcworkspace in your app’s ios folder.
To view your app’s settings, select the Runner project in the Xcode project navigator. Then, in the main view sidebar, select the Runner target.
Select the General tab. Next, you’ll verify the most important settings:
Display Name: the name of the app to be displayed on the home screen and elsewhere.
Here is a concrete example with the delegation pattern.
Setup your Protocol:
@objc protocol MyProtocol:class
{
func requiredMethod()
optional func optionalMethod()
}
class MyClass: NSObject
{
weak var delegate:MyProtocol?
func callDelegate()
{
delegate?.requiredMethod()
delegate?.optionalMethod?()
}
}
Set the delegate to a class and implement the Protocol. See that the optional method does not need to be implemented.
class AnotherClass: NSObject, MyProtocol
{
init()
{
super.init()
let myInstance = MyClass()
myInstance.delegate = self
}
func requiredMethod()
{
}
}
One important thing is that the optional method is optional and needs a "?" when calling. Mention the second question mark.
delegate?.optionalMethod?()
There's more than one way to skin this problem so here's my solution:
dict.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine);
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseYou are tying one had behind your back saying that you won't use the LESS files. I built my first Twitter Bootstrap theme using 2.0, and I did everything in CSS -- creating an override.css file. It took days to get things to work correctly.
Now we have 3.0. Let me assure you that it takes less time to learn LESS, which is pretty straight forward if you're comfortable with CSS, than doing all of those crazy CSS overrides. Making changes like the one you want is a piece of cake.
In Bootstrap 3.0, the container class controls the width, and all of the contained styles adjust to fill the container. The container width variables are at the bottom of the variables.less file.
// Container sizes
// --------------------------------------------------
// Small screen / tablet
@container-tablet: ((720px + @grid-gutter-width));
// Medium screen / desktop
@container-desktop: ((940px + @grid-gutter-width));
// Large screen / wide desktop
@container-lg-desktop: ((1020px + @grid-gutter-width));
Some sites either don't have enough content to fill the 1020 display or you want a narrower frame for aesthetic reasons. Because BS uses a 12-column grid I use a multiple like 960.
try this package, works wonders, and was made for date/time...
library(lubridate)
Portfolio$Date2 <- mdy(Portfolio.all$Date2)
Disclaimer: I have used bootstrap in the past, but I never really appreciated what it actually is before, this description comes from me coming to my own definition, today. And I know that bootstrap v4 is out, but I found the bootstrap v3 documentation to be much clearer, so I used that. The library is not going to fundamentally change what it provides.
Bootstrap is a collection of CSS and javascript files that provides some nice-looking default styling for standard html elements, and a few common web content objects that are not standard html elements.
To make an analogy, it's kind of like applying a theme in powerpoint, but for your website: it makes things look pretty nice without too much initial effort.
The official v3 documentation breaks it up into three sections:
These roughly correspond to the three main things that Bootstrap provides:
<input class="btn btn-default" type="button" value="Input">Click me</button>
<span class="glyphicon glyphicon-align-left"></span>
Bootstrap extends jQuery quite a bit. If we look at the source code, we can see that it uses jQuery to do things like: set up listeners for keydown event to interact with dropdowns. It does all of this jQuery setup when you import it in your <script>
tag, so you need to make sure jQuery is loaded before Bootstrap is.
Additionally, it ties the javascript to the DOM more tightly than plain jQuery, providing a javascript class interface. e.g. toggle a button programmatically. Remember that CSS just defines how a thing looks, so the major job of these operations will tend to be to modify which CSS classes apply to the element at that moment in time. This kind of change, based on user input, can't be done with plain CSS.
There are other standard interactions with a user that we denizens of the internet are used to that are not covered by CSS. Like, clicking a link that scrolls you down a page instead of changing pages. One of the things that Bootstrap gives you is an easy way to implement this behaviour on your own website.
I have mentioned the word "standard" a lot here, and for good reason. I think the best thing that Bootstrap provides is a set of good-looking standards. You're free to modify the default theme as much as you want, but it's a better baseline than raw html, css and js. And this is why it's called "framework".
Different web browsers have different default styles and can act differently, and need different CSS prefixes and things like that. A major benefit of Bootstrap is that it is much more reliable than writing all that cross-browser stuff yourself (you will still have problems, I'm sure, but it's easier).
I think that Bootstrap was preferred more when gulp and babel weren't as popular. Looking at Bootstrap it seems to come from a time before everyone compiled their javascript. It's still relevant, but you can get some of the benefits from other sources now.
More recent versions of CSS have allowed you to define transitions between these static lists as they change. The original version of Bootstrap actually predates wide-spread adoption of this capability in browsers, so they still have their own animation classes. There are a few bits of Bootstrap that are like this: that other stuff has come up around it and makes it look a bit redundant.
From the documentation for ast.literal_eval()
:
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
Decimal
isn't on the list of things allowed by ast.literal_eval()
.
Rob's answer (most voted above) is correct. I would like to add that in some situations using IDs is useful as it allows for comparison of objects and finding which objects refer to your objects.
The later usually helps you for example to debug strange bugs where mutable objects are passed as parameter to say classes and are assigned to local vars in a class. Mutating those objects will mutate vars in a class. This manifests itself in strange behavior where multiple things change at the same time.
Recently I had this problem with a Python/Tkinter app where editing text in one text entry field changed the text in another as I typed :)
Here is an example on how you might use function id() to trace where those references are. By all means this is not a solution covering all possible cases, but you get the idea. Again IDs are used in the background and user does not see them:
class democlass:
classvar = 24
def __init__(self, var):
self.instancevar1 = var
self.instancevar2 = 42
def whoreferencesmylocalvars(self, fromwhere):
return {__l__: {__g__
for __g__ in fromwhere
if not callable(__g__) and id(eval(__g__)) == id(getattr(self,__l__))
}
for __l__ in dir(self)
if not callable(getattr(self, __l__)) and __l__[-1] != '_'
}
def whoreferencesthisclassinstance(self, fromwhere):
return {__g__
for __g__ in fromwhere
if not callable(__g__) and id(eval(__g__)) == id(self)
}
a = [1,2,3,4]
b = a
c = b
democlassinstance = democlass(a)
d = democlassinstance
e = d
f = democlassinstance.classvar
g = democlassinstance.instancevar2
print( 'My class instance is of', type(democlassinstance), 'type.')
print( 'My instance vars are referenced by:', democlassinstance.whoreferencesmylocalvars(globals()) )
print( 'My class instance is referenced by:', democlassinstance.whoreferencesthisclassinstance(globals()) )
OUTPUT:
My class instance is of <class '__main__.democlass'> type.
My instance vars are referenced by: {'instancevar2': {'g'}, 'classvar': {'f'}, 'instancevar1': {'a', 'c', 'b'}}
My class instance is referenced by: {'e', 'd', 'democlassinstance'}
Underscores in variable names are used to prevent name colisions. Functions use "fromwhere" argument so that you can let them know where to start searching for references. This argument is filled by a function that lists all names in a given namespace. Globals() is one such function.
See full query from SHOW PROCESSLIST :
SHOW FULL PROCESSLIST;
Or
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;
I think the difference is nearly self-explanatory. And it's super trivial to test.
jQuery.html()
treats the string as HTML, jQuery.text()
treats the content as text
<html>
<head>
<title>Test Page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#div1").html('<a href="example.html">Link</a><b>hello</b>');
$("#div2").text('<a href="example.html">Link</a><b>hello</b>');
});
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
A difference that may not be so obvious is described in the jQuery API documentation
In the documentation for .html():
The
.html()
method is not available in XML documents.
And in the documentation for .text():
Unlike the
.html()
method,.text()
can be used in both XML and HTML documents.
$(function() {_x000D_
$("#div1").html('<a href="example.html">Link</a><b>hello</b>');_x000D_
$("#div2").text('<a href="example.html">Link</a><b>hello</b>');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>_x000D_
<div id="div1"></div>_x000D_
<div id="div2"></div>
_x000D_
Use \Q
to autoescape any potentially problematic characters in your variable.
if($text_to_search =~ m/\Q$search_string/) print "wee";
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
(Similar to Azder's answer, but a slightly different tact.)
I don't believe there is a predefined protocol handler for content from the classpath. (The so-called classpath:
protocol).
However, Java does allow you to add your own protocols. This is done through providing concrete implementations java.net.URLStreamHandler
and java.net.URLConnection
.
This article describes how a custom stream handler can be implemented: http://java.sun.com/developer/onlineTraining/protocolhandlers/.
Below is a solution for WINDOWS ONLY
In cases where the application (like Tomcat) is started as a windows service, the System.getProperty("user.name") or System.getenv().get("USERNAME") return the user who started the service and not the current logged in user name.
Also in Java 9 the NTSystem etc classes will not be accessible
So workaround for windows: You can use wmic, so you have to run the below command
wmic ComputerSystem get UserName
If available, this will return output of the form:
UserName
{domain}\{logged-in-user-name}
Note: For windows you need to use cmd /c as a prefix, so below is a crude program as an example:
Process exec = Runtime.getRuntime().exec("cmd /c wmic ComputerSystem get UserName".split(" "));
System.out.println(exec.waitFor());
try (BufferedReader bw = new BufferedReader(new InputStreamReader(exec.getInputStream()))) {
System.out.println(bw.readLine() + "\n" + bw.readLine()+ "\n" + bw.readLine());
}
In C# it also works with a null as the 4th parameter.
@Html.ActionLink( "Front Page", "Index", "Home", null, new { @class = "MenuButtons" })
If length
is undefined you can use:
function count(array){
var c = 0;
for(i in array) // in returns key, not object
if(array[i] != undefined)
c++;
return c;
}
var total = count(array);
I used the following code:
import urllib
def read_text():
quotes = urllib.urlopen("https://s3.amazonaws.com/udacity-hosted-downloads/ud036/movie_quotes.txt")
contents_file = quotes.read()
print contents_file
read_text()
Easy approach:
CREATE TABLE T
(
C [nvarchar](100) NOT NULL UNIQUE,
);
SET XACT_ABORT ON -- Turns on rollback if T-SQL statement raises a run-time error.
SELECT * FROM T; -- Check before.
BEGIN TRAN
INSERT INTO T VALUES ('A');
INSERT INTO T VALUES ('B');
INSERT INTO T VALUES ('B');
INSERT INTO T VALUES ('C');
COMMIT TRAN
SELECT * FROM T; -- Check after.
DELETE T;
You don't need any date-specific functions for this, it's just string manipulation:
var parts = fecha2.value.split('-');
var newdate = parts[1]+'-'+parts[2]+'-'+(parseInt(parts[0], 10)%100);
I think in general, you'd want a web service for a blocking task (this tasks needs to be completed before we execute more code), and a message queue for a non-blocking task (could take quite a while, but we don't need to wait for it).
subprocess.check_output()
returns a bytestring.
In Python 3, there's no implicit conversion between unicode (str
) objects and bytes
objects. If you know the encoding of the output, you can .decode()
it to get a string, or you can turn the \n
you want to add to bytes
with "\n".encode('ascii')
Eric Sink, who appeared on SO podcast#36 in January 2009, wrote an excellent series of articles under the title Source Control How-to.
(Eric is the founder of SourceGear who market a plug-compatible version of SourceSafe, but without the horribleness.)
I don't think you need/want the timeout.
onhover (hover) would be defined as the time period while "over" something. IMHO
onmouseover = start...
onmouseout = ...end
For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.
There is an easier way to get the exact version .NET version installed on your machine from a cmd prompt. Just follow the following instructions;
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP"
(This will list all the .NET versions.)
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\full" /v version
Please find the attached image below to see how it is shown.
It's not open source, but you can at least get a free personal use license to Prince, which really does a lovely job.
If your project contains a RouteConfig.cs file, then you probably need to ignore the route to the root by adding routes.IgnoreRoute("");
in this file.
If it doen't solve your problem, try this :
void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.AppRelativeCurrentExecutionFilePath == "~/")
Response.Redirect("~/index.aspx");
}
In any given Bash session, set the history file to /dev/null by typing:
export HISTFILE=/dev/null
Note that, as pointed out in the comments, this will not write any commands in that session to the history!
Just don't mess with your system administrator's hard work, please ;)
Doodad's solution is more elegant. Simply unset the variable: unset HISTFILE
(thanks!)
Try this one
string redirect = "<script>window.open('http://www.google.com');</script>";
Response.Write(redirect);
There's a property for that:
a.m_title {
text-transform: capitalize;
}
If your links can contain multiple words and you only want the first letter of the first word to be uppercase, use :first-letter
with a different transform instead (although it doesn't really matter). Note that in order for :first-letter
to work your a
elements need to be block containers (which can be display: block
, display: inline-block
, or any of a variety of other combinations of one or more properties):
a.m_title {
display: block;
}
a.m_title:first-letter {
text-transform: uppercase;
}
easiest way:
Dim newBook As Workbook
Set newBook = Workbooks.Add
Sheets("Sheet1").Copy Before:=newBook.Sheets(1)
For fixing:
No matching client found for package name 'com.example.exampleapp:
You should get a valid google-service.json
file for your package from here
For fixing:
Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 8.3.0.:
You should move apply plugin: 'com.google.gms.google-services'
to the end of your app gradle.build
file. Something like this:
dependencies {
...
}
apply plugin: 'com.google.gms.google-services'
Hmm, this seems to be a bit of an old question, but since I've been messing about with Doxygen configuration last few days, while my head's still full of current info let's have a stab at it -
I think the previous answers almost have it:
The missing option is to add COLLABORATION_GRAPH = YES
in the Doxyfile. I assume you can do the equivalent thing somewhere in the doxywizard GUI (I don't use doxywizard).
So, as a more complete example, typical "Doxyfile" options related to UML output that I tend to use are:
EXTRACT_ALL = YES
CLASS_DIAGRAMS = YES
HIDE_UNDOC_RELATIONS = NO
HAVE_DOT = YES
CLASS_GRAPH = YES
COLLABORATION_GRAPH = YES
UML_LOOK = YES
UML_LIMIT_NUM_FIELDS = 50
TEMPLATE_RELATIONS = YES
DOT_GRAPH_MAX_NODES = 100
MAX_DOT_GRAPH_DEPTH = 0
DOT_TRANSPARENT = YES
These settings will generate both "inheritance" (CLASS_GRAPH=YES
) and "collaboration" (COLLABORATION_GRAPH=YES
) diagrams.
Depending on your target for "deployment" of the doxygen output, setting DOT_IMAGE_FORMAT = svg
may also be of use. With svg output the diagrams are "scalable" instead of the fixed resolution of bitmap formats such as .png. Apparently, if viewing the output in browsers other than IE, there is also INTERACTIVE_SVG = YES
which will allow "interactive zooming and panning" of the generated svg diagrams. I did try this some time ago, and the svg output was very visually attractive, but at the time, browser support for svg was still a bit inconsistent, so hopefully that situation may have improved lately.
As other comments have mentioned, some of these settings (DOT_GRAPH_MAX_NODES
in particular) do have potential performance impacts, so YMMV.
I tend to hate "RTFM" style answers, so apologies for this sentence, but in this case the Doxygen documentation really is your friend, so check out the Doxygen docs on the above mentioned settings- last time I looked you can find the details at http://www.doxygen.nl/manual/config.html.
Opening the debug console in Chrome, or even looking at the html source file (after it is loaded in the browser), make sure that all the paths there are valid (i.e. when you follow a link you get to it's content, and not an error). When something is not valid, fix the path (e.g. get rid of the server specific part and make sure you only refer to files that are part of your extension through paths like /js/jquery-123-min.js
).
I wouldn't go with MSTest. Although it's probably the most future proof of the frameworks with Microsoft behind it's not the most flexible solution. It won't run stand alone without some hacks. So running it on a build server other than TFS without installing Visual Studio is hard. The visual studio test-runner is actually slower than Testdriven.Net + any of the other frameworks. And because the releases of this framework are tied to releases of Visual Studio there are less updates and if you have to work with an older VS you're tied to an older MSTest.
I don't think it matters a lot which of the other frameworks you use. It's really easy to switch from one to another.
I personally use XUnit.Net or NUnit depending on the preference of my coworkers. NUnit is the most standard. XUnit.Net is the leanest framework.
I modified the above technique which was close to what I wanted for angular and turned it into a service :-). I included ie9 because I was having some issues in my angularjs app, but could be something I'm doing, so feel free to take it out.
angular.module('myModule').service('browserDetectionService', function() {
return {
isCompatible: function () {
var browserInfo = navigator.userAgent;
var browserFlags = {};
browserFlags.ISFF = browserInfo.indexOf('Firefox') != -1;
browserFlags.ISOPERA = browserInfo.indexOf('Opera') != -1;
browserFlags.ISCHROME = browserInfo.indexOf('Chrome') != -1;
browserFlags.ISSAFARI = browserInfo.indexOf('Safari') != -1 && !browserFlags.ISCHROME;
browserFlags.ISWEBKIT = browserInfo.indexOf('WebKit') != -1;
browserFlags.ISIE = browserInfo.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
browserFlags.ISIE6 = browserInfo.indexOf('MSIE 6') > 0;
browserFlags.ISIE7 = browserInfo.indexOf('MSIE 7') > 0;
browserFlags.ISIE8 = browserInfo.indexOf('MSIE 8') > 0;
browserFlags.ISIE9 = browserInfo.indexOf('MSIE 9') > 0;
browserFlags.ISIE10 = browserInfo.indexOf('MSIE 10') > 0;
browserFlags.ISOLD = browserFlags.ISIE6 || browserFlags.ISIE7 || browserFlags.ISIE8 || browserFlags.ISIE9; // MUST be here
browserFlags.ISIE11UP = browserInfo.indexOf('MSIE') == -1 && browserInfo.indexOf('Trident') > 0;
browserFlags.ISIE10UP = browserFlags.ISIE10 || browserFlags.ISIE11UP;
browserFlags.ISIE9UP = browserFlags.ISIE9 || browserFlags.ISIE10UP;
return !browserFlags.ISOLD;
}
};
});
EDIT: I wrote this answer up in haste, before realizing that your question is about sending values to a chan inside a goroutine. The approach below can be used either with an additional chan as suggested above, or using the fact that the chan you have already is bi-directional, you can use just the one...
If your goroutine exists solely to process the items coming out of the chan, you can make use of the "close" builtin and the special receive form for channels.
That is, once you're done sending items on the chan, you close it. Then inside your goroutine you get an extra parameter to the receive operator that shows whether the channel has been closed.
Here is a complete example (the waitgroup is used to make sure that the process continues until the goroutine completes):
package main
import "sync"
func main() {
var wg sync.WaitGroup
wg.Add(1)
ch := make(chan int)
go func() {
for {
foo, ok := <- ch
if !ok {
println("done")
wg.Done()
return
}
println(foo)
}
}()
ch <- 1
ch <- 2
ch <- 3
close(ch)
wg.Wait()
}
I am using bootstrap calender for future date not allow with allow change in months & year only..
var j = jQuery.noConflict();
j(function () {
j(".datepicker").datepicker({ dateFormat: "dd-M-yy" }).val()
});
j(function () {
j(".Futuredatenotallowed").datepicker({
changeMonth: true,
maxDate: 0,
changeYear: true,
dateFormat: 'dd-M-yy',
language: "tr"
}).on('changeDate', function (ev) {
$(this).blur();
$(this).datepicker('hide');
}).val()
});
Simplest approach in printing ASCII values of a given alphabet.
Here is an example :
#include<stdio.h>
int main()
{
//we are printing the ASCII value of 'a'
char a ='a'
printf("%d",a)
return 0;
}
There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
Solution 2: Using lexical_cast
(Most Appropriate & simplest)
int x = boost::lexical_cast<int>("12345");
Solution 3: Using C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
First of all, if table2
's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT
on that table
SET IDENTITY_INSERT table2 ON;
before the insert.
So one of two, you modify your second stored and call it with only the parameters productName
and productDescription
and then get the new ID
EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()
or you already have the ID of the product and you don't need to call SCOPE_IDENTITY()
and can make the insert on table1
with that ID
Yes, Promises are asynchronous callbacks. They can't do anything that callbacks can't do, and you face the same problems with asynchrony as with plain callbacks.
However, Promises are more than just callbacks. They are a very mighty abstraction, allow cleaner and better, functional code with less error-prone boilerplate.
So what's the main idea?
Promises are objects representing the result of a single (asynchronous) computation. They resolve to that result only once. There's a few things what this means:
Promises implement an observer pattern:
return
a Promise objectPromises are chainable (monadic, if you want):
.then()
method. It will take a callback to be called with the first result, and returns a promise for the result of the promise that the callback returns.Sounds complicated? Time for a code example.
var p1 = api1(); // returning a promise
var p3 = p1.then(function(api1Result) {
var p2 = api2(); // returning a promise
return p2; // The result of p2 …
}); // … becomes the result of p3
// So it does not make a difference whether you write
api1().then(function(api1Result) {
return api2().then(console.log)
})
// or the flattened version
api1().then(function(api1Result) {
return api2();
}).then(console.log)
Flattening does not come magically, but you can easily do it. For your heavily nested example, the (near) equivalent would be
api1().then(api2).then(api3).then(/* do-work-callback */);
If seeing the code of these methods helps understanding, here's a most basic promise lib in a few lines.
What's the big fuss about promises?
The Promise abstraction allows much better composability of functions. For example, next to then
for chaining, the all
function creates a promise for the combined result of multiple parallel-waiting promises.
Last but not least Promises come with integrated error handling. The result of the computation might be that either the promise is fulfilled with a value, or it is rejected with a reason. All the composition functions handle this automatically and propagate errors in promise chains, so that you don't need to care about it explicitly everywhere - in contrast to a plain-callback implementation. In the end, you can add a dedicated error callback for all occurred exceptions.
Not to mention having to convert things to promises.
That's quite trivial actually with good promise libraries, see How do I convert an existing callback API to promises?
Here's a plugin that simplifies life https://github.com/rootical/jQueryDataSelector
Use it like that:
data selector jQuery selector
$$('name') $('[data-name]')
$$('name', 10) $('[data-name=10]')
$$('name', false) $('[data-name=false]')
$$('name', null) $('[data-name]')
$$('name', {}) Syntax error
I accomplished the above using relative positioning and floating to the right.
HTML code:
<div class="clearfix">
<div class="outer-div">
<div class="inner-div">
<div class="floating-div">Float 1</div>
<div class="floating-div">Float 2</div>
<div class="floating-div">Float 3</div>
</div>
</div>
</div>
CSS:
.outer-div { position: relative; float: right; right: 50%; }
.inner-div { position: relative; float: right; right: -50%; }
.floating-div { float: left; border: 1px solid red; margin: 0 1.5em; }
.clearfix:before,
.clearfix:after { content: " "; display: table; }
.clearfix:after { clear: both; }
.clearfix { *zoom: 1; }
JSFiddle: http://jsfiddle.net/MJ9yp/
This will work in IE8 and up, but not earlier (surprise, surprise!)
I do not recall the source of this method unfortunately, so I cannot give credit to the original author. If anybody else knows, please post the link!
No, see this question which I asked - Upcasting in .NET using generics
The best way is to make a default constructor on the class, construct and then call an Initialise
method
setTimeout(() => {
this.setState({ position: 1 });
}, 3000);
The above would also work because the ES6 arrow function does not change the context of this
.
You can use Graphics.DrawImage
to draw a cropped image onto the graphics object from a bitmap.
Rectangle cropRect = new Rectangle(...);
Bitmap src = Image.FromFile(fileName) as Bitmap;
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
using(Graphics g = Graphics.FromImage(target))
{
g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height),
cropRect,
GraphicsUnit.Pixel);
}
My solution is the same as @Krishnrohit:
ALTER TABLE `table` CHANGE `column_current_name` `new_column_name` DATETIME NULL;
I actually had the column set as NOT NULL
but with the above query it was changed to NULL
.
P.S. I know this an old thread but nobody seems to acknowledge that CHANGE
is also correct.
I have a angular 5 + spring boot app(application.properties 1.3+) with help of compression(link attached below) was able to reduce the size of main.bundle.ts size from 2.7 MB to 530 KB.
Also by default --aot and --build-optimizer are enabled with --prod mode you need not specify those separately.
I would not make the primary key of the "info" table a composite of the two values from other tables.
Others can articulate the reasons better, but it feels wrong to have a column that is really made up of two pieces of information. What if you want to sort on the ID from the second table for some reason? What if you want to count the number of times a value from either table is present?
I would always keep these as two distinct columns. You could use a two-column primay key in mysql ...PRIMARY KEY(id_a, id_b)... but I prefer using a two-column unique index, and having an auto-increment primary key field.
I've got the same issue as stated by Grigoriy Yuschenko. Same Intellij 2018 3.3
I was able to start my project by setting (like stated by Grigoriy)
File->Project Structure->Modules ->> Language level to 8 ( my maven project was set to 1.8 java)
AND
File -> Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler -> 8 also there
I hope it would be useful
Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.
Short answer to your question: Yes there are other stuff included than whats in the list.
What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.
From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.
Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.
Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.
In angular 1.4 +, in addition to adding the dependency
angular.module('myApp', ['ngRoute'])
,we also need to reference the separate angular-route.js file
<script src="angular.js">
<script src="angular-route.js">
I have a Maven3 project using JUnit 4.12 and Java8.
In order to get the path of a file called myxml.xml
under src/test/resources
, I do this from within the test case:
@Test
public void testApp()
{
File inputXmlFile = new File(this.getClass().getResource("/myxml.xml").getFile());
System.out.println(inputXmlFile.getAbsolutePath());
...
}
Tested on Ubuntu 14.04 with IntelliJ IDE. Reference here.
Figuring out what path to take requires answering not only CommonsWare's key question of "why" but also the question of "to what?" are you passing it.
The reality is that the only thing that can go through bundles is plain data - everything else is based on interpretations of what that data means or points to. You can't literally pass an object, but what you can do is one of three things:
1) You can break the object down to its constitute data, and if what's on the other end has knowledge of the same sort of object, it can assemble a clone from the serialized data. That's how most of the common types pass through bundles.
2) You can pass an opaque handle. If you are passing it within the same context (though one might ask why bother) that will be a handle you can invoke or dereference. But if you pass it through Binder to a different context it's literal value will be an arbitrary number (in fact, these arbitrary numbers count sequentially from startup). You can't do anything but keep track of it, until you pass it back to the original context which will cause Binder to transform it back into the original handle, making it useful again.
3) You can pass a magic handle, such as a file descriptor or reference to certain os/platform objects, and if you set the right flags Binder will create a clone pointing to the same resource for the recipient, which can actually be used on the other end. But this only works for a very few types of objects.
Most likely, you are either passing your class just so the other end can keep track of it and give it back to you later, or you are passing it to a context where a clone can be created from serialized constituent data... or else you are trying to do something that just isn't going to work and you need to rethink the whole approach.
from PyPDF2 import PdfFileMerger
import webbrowser
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
def list_files(directory, extension):
return (f for f in os.listdir(directory) if f.endswith('.' + extension))
pdfs = list_files(dir_path, "pdf")
merger = PdfFileMerger()
for pdf in pdfs:
merger.append(open(pdf, 'rb'))
with open('result.pdf', 'wb') as fout:
merger.write(fout)
webbrowser.open_new('file://'+ dir_path + '/result.pdf')
Git Repo: https://github.com/mahaguru24/Python_Merge_PDF.git
Selector name{
font-weight:bold;
}
Suppose you want to make bold for p element
p{
font-weight:bold;
}
You can use other alternative value instead of bold like
p{
font-weight:bolder;
font-weight:600;
}
This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen
from the copied link was in a different encoding and hence the curl_exec()
was always returning false
because it was unable to communicate with the server.
It took me a couple hours to finally understand the diference in the characters bellow:
https://www.e-example.com/api
https://www.e-example.com/api
Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api
.
It may seem to you that they are equal but if you check the encoding of the hyphens
here you'll see that the first hyphen
is a unicode characters U+2010 and the other is a U+002D.
Hope this helps someone.
I'm not able to comment divega's post, but among the different solutions presented here, divega's solution produces the best SQL. Both performance wise and length wise. I just checked with SQL Server Profiler and by looking at the execution plan (with "SET STATISTICS PROFILE ON").
Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.
When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.
(It would really have been nice if you'd mentioned which Color
type you were interested in to start with...)
One simple way of doing this is to just build up a dictionary via reflection:
public static class Colors
{
private static readonly Dictionary<string, Color> dictionary =
typeof(Color).GetProperties(BindingFlags.Public |
BindingFlags.Static)
.Where(prop => prop.PropertyType == typeof(Color))
.ToDictionary(prop => prop.Name,
prop => (Color) prop.GetValue(null, null)));
public static Color FromName(string name)
{
// Adjust behaviour for lookup failure etc
return dictionary[name];
}
}
That will be relatively slow for the first lookup (while it uses reflection to find all the properties) but should be very quick after that.
If you want it to be case-insensitive, you can pass in something like StringComparer.OrdinalIgnoreCase
as an extra argument in the ToDictionary
call. You can easily add TryParse
etc methods should you wish.
Of course, if you only need this in one place, don't bother with a separate class etc :)
SET @table = 'the_table';
SELECT GROUP_CONCAT(IF(COLUMN_NAME IN ('id'), 0, CONCAT("\`", COLUMN_NAME, "\`"))) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = @table INTO @columns;
SET @s = CONCAT('INSERT INTO ', @table, ' SELECT ', @columns,' FROM ', @table, ' WHERE id=1');
PREPARE stmt FROM @s;
EXECUTE stmt;
int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);
This overload starts looking for the substring from the given index.
It for example happens in this case here:
void initializeJSP(unknownType Experiment);
Try using std::string
instead of just string
(and include the <string>
header). C++ Standard library classes are within the namespace std::
.
You can use TextFormField widget of Flutter Form as your requirement.
TextFormField(
maxLines: 1,
decoration: InputDecoration(
prefixIcon: const Icon(
Icons.search,
color: Colors.grey,
),
hintText: 'Search your trips',
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
),
),
),
You can use this function :
function SendByFTP {
param (
$userFTP = "anonymous",
$passFTP = "anonymous",
[Parameter(Mandatory=$True)]$serverFTP,
[Parameter(Mandatory=$True)]$localFile,
[Parameter(Mandatory=$True)]$remotePath
)
if(Test-Path $localFile){
$remoteFile = $localFile.Split("\")[-1]
$remotePath = Join-Path -Path $remotePath -ChildPath $remoteFile
$ftpAddr = "ftp://${userFTP}:${passFTP}@${serverFTP}/$remotePath"
$browser = New-Object System.Net.WebClient
$url = New-Object System.Uri($ftpAddr)
$browser.UploadFile($url, $localFile)
}
else{
Return "Unable to find $localFile"
}
}
This function send specified file by FTP. You must call the function with these parameters :
For example :
SendByFTP -userFTP "USERNAME" -passFTP "PASSWORD" -serverFTP "MYSERVER" -localFile "toto.zip" -remotePath "path/on/the/FTP/"
Modify your CSS like this:
.vertical_banner {_x000D_
border: 1px solid #E9E3DD;_x000D_
float: left;_x000D_
height: 210px;_x000D_
margin: 2px;_x000D_
padding: 4px 2px 10px 10px;_x000D_
text-align: left;_x000D_
width: 117px;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
#bottom_link{_x000D_
position:absolute; /* added */_x000D_
bottom:0; /* added */_x000D_
left:0; /* added */_x000D_
}
_x000D_
<div class="vertical_banner">_x000D_
<div id="bottom_link">_x000D_
<input type="submit" value="Continue">_x000D_
</div>_x000D_
</div>
_x000D_
I'm assuming you're using DB2 for z/OS, which unfortunately (for whatever reason, I never really understood why) doesn't support using a values-list where a full-select would be appropriate.
You can use a select like below. It's a little unwieldy, but it works:
INSERT INTO tableName (col1, col2, col3, col4, col5)
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1
Your statement would work on DB2 for Linux/Unix/Windows (LUW), at least when I tested it on my LUW 9.7.
keytool
comes with the JDK installation (in the bin
folder):
keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"
This will create a new keystore and add just your certificate to it.
So, you can't convert a certificate to a keystore: you add a certificate to a keystore.
i tried money_format()
but it didn't work for me at all. then i tried the following one. it worked perfect for me. hopefully it will work in right way for you too.. :)
you should use this one
number_format($money, 2,'.', ',')
it will show money number in terms of money format up to 2 decimal.
Try
$waffles = foo($waffles);
Or pass the array by reference, like suggested in the other answers.
In addition, you can add new elements to an array without writing the index, e.g.
$waffles = array(1,2,3); // filling on initialization
or
$waffles = array();
$waffles[] = 1;
$waffles[] = 2;
$waffles[] = 3;
On a sidenote, if you want to sum all values in an array, use array_sum()
// export in index.js
export { default as Foo } from './Foo';
export { default as Bar } from './Bar';
// then import both
import { Foo, Bar } from 'my/module';
Mockito cannot capture static methods, but since Mockito 2.14.0 you can simulate it by creating invocation instances of static methods.
Example (extracted from their tests):
public class StaticMockingExperimentTest extends TestBase {
Foo mock = Mockito.mock(Foo.class);
MockHandler handler = Mockito.mockingDetails(mock).getMockHandler();
Method staticMethod;
InvocationFactory.RealMethodBehavior realMethod = new InvocationFactory.RealMethodBehavior() {
@Override
public Object call() throws Throwable {
return null;
}
};
@Before
public void before() throws Throwable {
staticMethod = Foo.class.getDeclaredMethod("staticMethod", String.class);
}
@Test
public void verify_static_method() throws Throwable {
//register staticMethod call on mock
Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"some arg");
handler.handle(invocation);
//verify staticMethod on mock
//Mockito cannot capture static methods so we will simulate this scenario in 3 steps:
//1. Call standard 'verify' method. Internally, it will add verificationMode to the thread local state.
// Effectively, we indicate to Mockito that right now we are about to verify a method call on this mock.
verify(mock);
//2. Create the invocation instance using the new public API
// Mockito cannot capture static methods but we can create an invocation instance of that static invocation
Invocation verification = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"some arg");
//3. Make Mockito handle the static method invocation
// Mockito will find verification mode in thread local state and will try verify the invocation
handler.handle(verification);
//verify zero times, method with different argument
verify(mock, times(0));
Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"different arg");
handler.handle(differentArg);
}
@Test
public void stubbing_static_method() throws Throwable {
//register staticMethod call on mock
Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"foo");
handler.handle(invocation);
//register stubbing
when(null).thenReturn("hey");
//validate stubbed return value
assertEquals("hey", handler.handle(invocation));
assertEquals("hey", handler.handle(invocation));
//default null value is returned if invoked with different argument
Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"different arg");
assertEquals(null, handler.handle(differentArg));
}
static class Foo {
private final String arg;
public Foo(String arg) {
this.arg = arg;
}
public static String staticMethod(String arg) {
return "";
}
@Override
public String toString() {
return "foo:" + arg;
}
}
}
Their goal is not to directly support static mocking, but to improve its public APIs so that other libraries, like Powermockito, don't have to rely on internal APIs or directly have to duplicate some Mockito code. (source)
Disclaimer: Mockito team thinks that the road to hell is paved with static methods. However, Mockito's job is not to protect your code from static methods. If you don’t like your team doing static mocking, stop using Powermockito in your organization. Mockito needs to evolve as a toolkit with an opinionated vision on how Java tests should be written (e.g. don't mock statics!!!). However, Mockito is not dogmatic. We don't want to block unrecommended use cases like static mocking. It's just not our job.
This method may avoid the need to hard code or configure proxy credentials, which may be desirable.
Put this in your application configuration file - probably app.config. Visual Studio will rename it to yourappname.exe.config on build, and it will end up next to your executable. If you don't have an application configuration file, just add one using Add New Item in Visual Studio.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
</configuration>
I am using Primefaces 6.0 and in order to remove borders from my panel grid i use this style class "ui-noborder" as follow:
<p:panelGrid columns="3" styleClass="ui-noborder">
<!--panel grid contents -->
</p:panelGrid>
It uses a css file named "components" in primefaces lib
Definitely you will need to store old value manually, depending on what moment you are interested (before focusing, from last change). Initial value can be taken from defaultValue property:
function onChange() {
var oldValue = this.defaultValue;
var newValue = this.value;
}
Value before focusing can be taken as shown in Gone Coding's answer. But you have to keep in mind that value can be changed without focusing.
There is an open source program that I find online it uses openssl to encrypt and decrypt files. It does this with a single password. The great thing about this open source script is that it deletes the original unencrypted file by shredding the file. But the dangerous thing about is once the original unencrypted file is gone you have to make sure you remember your password otherwise they be no other way to decrypt your file.
Here the link it is on github
https://github.com/EgbieAnderson1/linux_file_encryptor/blob/master/file_encrypt.py
The above are all excellent answers. I just wanted to add that when there are multiple characters to check against, an if-else might turn out better since you could instead write the following.
// switch on vowels, digits, punctuation, or consonants
char c; // assign some character to 'c'
if ("aeiouAEIOU".indexOf(c) != -1) {
// handle vowel case
} else if ("!@#$%,.".indexOf(c) != -1) {
// handle punctuation case
} else if ("0123456789".indexOf(c) != -1) {
// handle digit case
} else {
// handle consonant case, assuming other characters are not possible
}
Of course, if this gets any more complicated, I'd recommend a regex matcher.
Convert an iterable to a list may have a cost. Instead, to get the the first item, you can use:
next(iter(keys))
Or, if you want to iterate over all items, you can use:
items = iter(keys)
while True:
try:
item = next(items)
except StopIteration as e:
pass # finish
When subclassing immutable built-in types like numbers and strings, and occasionally in other situations, the static method new comes in handy. new is the first step in instance construction, invoked before init.
The new method is called with the class as its first argument; its responsibility is to return a new instance of that class.
Compare this to init: init is called with an instance as its first argument, and it doesn't return anything; its responsibility is to initialize the instance.
There are situations where a new instance is created without calling init (for example when the instance is loaded from a pickle). There is no way to create a new instance without calling new (although in some cases you can get away with calling a base class's new).
Regarding what you wish to achieve, there also in same doc info about Singleton pattern
class Singleton(object):
def __new__(cls, *args, **kwds):
it = cls.__dict__.get("__it__")
if it is not None:
return it
cls.__it__ = it = object.__new__(cls)
it.init(*args, **kwds)
return it
def init(self, *args, **kwds):
pass
you may also use this implementation from PEP 318, using a decorator
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
Here is an easy way that guarantee to output the myFixedNumber rounded to two decimal places:
import java.text.DecimalFormat;
public class TwoDecimalPlaces {
static double myFixedNumber = 98765.4321;
public static void main(String[] args) {
System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
}
}
The result is: 98765.43
If I understand your request correctly, you have to do the following:
public class Section
{
public String Head
{
get
{
return SubHead.LastOrDefault();
}
set
{
SubHead.Add(value);
}
public List<string> SubHead { get; private set; }
public List<string> Content { get; private set; }
}
You use it like this:
var section = new Section();
section.Head = "Test string";
Now "Test string" is added to the subHeads collection and will be available through the getter:
var last = section.Head; // last will be "Test string"
Hope I understood you correctly.
So by default you can open CMD and write
java -jar jenkins.war
But if your port 8080 is already is in use,so you have to change the Jenkins port number, so for that open Jenkins folder in Program File and open Jenkins.XML file and change the port number such as 8088
Now Open CMD and write
java -jar jenkins.war --httpPort=8088
This is probably what you wanted:
$('#elem').fadeTo('slow', 0.3, function()
{
$(this).css('background-image', 'url(' + $img + ')');
}).fadeTo('slow', 1);
With a 1 second delay:
$('#elem').fadeTo('slow', 0.3, function()
{
$(this).css('background-image', 'url(' + $img + ')');
}).delay(1000).fadeTo('slow', 1);
For completeness - adding to accepted answer above - in case you are interested in any sibling regardless of the element type you can use variation:
following-sibling::*
The problem is that SQL 2008 MS has a bug where connecting to a remote server (say like a service provider collocation) it will always try to open the fist db in the list, and since the possibilities of been ur db the first on the list are really low, it will throw and error and fail to display the list of dbs... which using sql 2005 management studio it just works.
Wished I could use SQL 2008 MS, but looks like as far I connect to remote SQL 2005, SQL 2008 is out of the question on my dev machine :(
You can replace
document.getElementById(this.state.baction).addPrecent(10);
with
this.refs[this.state.baction].addPrecent(10);
<Progressbar completed={25} ref="Progress1" id="Progress1"/>
I have found one related behaviour that may help (sounds like your specific problem runs deeper though):
Flash checks whether a source file needs recompiling by looking at timestamps. If its compiled version is older than the source file, it will recompile. But it doesn't check whether the compiled version was generated from the same source file or not.
Specifically, if you have your actionscript files under version control, and you Revert a change, the reverted file will usually have an older timestamp, and Flash will ignore it.
There is no one-to-one correlation. For a really good article please see Efficient String Concatenation in Python:
Building long strings in the Python progamming language can sometimes result in very slow running code. In this article I investigate the computational performance of various string concatenation methods.
Add these lines to your build.gradle file:
android {
lintOptions {
abortOnError false
}
}
Then clean your project :D
If you like long cuts, here is another way tuple(tuple(a_m.tolist()) for a_m in a )
from numpy import array
a = array([[1, 2],
[3, 4]])
tuple(tuple(a_m.tolist()) for a_m in a )
The output is ((1, 2), (3, 4))
Note just (tuple(a_m.tolist()) for a_m in a ) will give a generator expresssion. Sort of inspired by @norok2's comment to Greg von Winckel's answer
java force indeed big endian : https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.11
This error is fairly self-explanatory. Dictionary keys are unique and you cannot have more than one of the same key. To fix this, you should modify your code like so:
Dictionary<string, string> rct3Features = new Dictionary<string, string>();
Dictionary<string, string> rct4Features = new Dictionary<string, string>();
foreach (string line in rct3Lines)
{
string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);
if (!rct3Features.ContainsKey(items[0]))
{
rct3Features.Add(items[0], items[1]);
}
////To print out the dictionary (to see if it works)
//foreach (KeyValuePair<string, string> item in rct3Features)
//{
// Console.WriteLine(item.Key + " " + item.Value);
//}
}
This simple if
statement ensures that you are only attempting to add a new entry to the Dictionary when the Key (items[0]
) is not already present.
By using a div
with style z-index:1;
and position: absolute;
you can overlay your div
on any other div
.
z-index
determines the order in which divs 'stack'. A div with a higher z-index
will appear in front of a div with a lower z-index
. Note that this property only works with positioned elements.
Each browser provides a default stylesheet, called the user agent stylesheet, in case an HTML file does not specify one. Styles that you specify override the defaults.
Because you have not specified values for the table element’s box, the default styles have been applied.
Use Microsoft Sysinternals Sigcheck. This sample outputs just the version:
sigcheck -q -n foo.dll
Unpacked sigcheck.exe is only 228 KB.
It's pretty simple. Pay attention and you'll get it right away! :)
You will create a html array, which will be then sent to php array. Your html code will look like this:
<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">
Where [1] [2] [3]
are the ID
s of your messages, meaning that you will echo
your $row['Report ID']
in their place.
Then, when you submit the form, your PHP array will look like this:
print_r($check_list)
[1] => checked
[3] => checked
Depending on which were checked and which were not.
I'm sure you can continue from this point forward.
This will let you read, write and create the file if it don't exist:
f = open('filename.txt','a+')
f = open('filename.txt','r+')
Often used commands:
f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file
Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:
var myXslTrans = new XslCompiledTransform();
myXslTrans.Load("stylesheet.xsl");
myXslTrans.Transform("source.xml", "result.html");
(Sorry for posing this as an answer, but the code block
support in comments is rather limited.)
In VB.NET, you don't even need a variable:
With New XslCompiledTransform()
.Load("stylesheet.xsl")
.Transform("source.xml", "result.html")
End With
The correct syntax to install cron in cygwin as Windows service is to pass -n as argument and not -D:
cygrunsrv --install cron --path /usr/sbin/cron --args -n
-D returns usage error when starting cron in cygwin:
$
$cygrunsrv --install cron --path /usr/sbin/cron --args -D
$cygrunsrv --start cron
cygrunsrv: Error starting a service: QueryServiceStatus: Win32 error 1062:
The service has not been started.
$cat /var/log/cron.log
cron: unknown option -- D
usage: /usr/sbin/cron [-n] [-x [ext,sch,proc,parc,load,misc,test,bit]]
$
Below page has a good explanation.
Installing & Configuring the Cygwin Cron Service in Windows: https://www.davidjnice.com/cygwin_cron_service.html
P.S. I had to run Cygwin64 Terminal on my Windows 10 PC as administrator in order to install cron as Windows service.
Instead of using a margin, could you use a border? You should do this with <div>
, anyway.
Something like this?
Another way is to use a public static field in which you store data, i.e.:
public class MyActivity extends Activity {
public static String SharedString;
public static SomeObject SharedObject;
//...
There is anew tool called Codename one: One SDK based on JAVA to code in WP8, Android, iOS with all extensive features
Features:
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
<input name='id[]' type='checkbox' value='".$shopnumb."\'>
$id = implode(',',$_POST['id']);
echo $id
you cannot echo an array because it will just print out Array. If you wanna print out an array use print_r
.
print_r($_POST['id']);
Well, @+id/listaVista
ListView is drawn after @+id/texto
and on top of it. So change in ListView from:
android:layout_below="@+id/editText1"
to:
android:layout_above="@+id/texto"
Also, since the list is drawn after textview, I find it dangerous to have android:layout_alignRight="@+id/listaVista"
in TextView. So remove it and find another way of aligning.
EDIT Taking a second look at your layout I think this is what you really want to have:
<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="wrap_content"
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=".EnviarMensaje" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Escriba el mensaje y luego clickee el canal a ser enviado"
android:textSize="20sp" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/textView1"
android:ems="10"
android:inputType="text" />
<TextView
android:id="@+id/texto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/listaVista"
android:layout_alignParentBottom="true"
android:text="TextView" />
<ListView
android:id="@+id/listaVista"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/texto"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText1" >
</ListView>
</RelativeLayout>
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
A different variant of the cause/solution:
My issue was that I was not getting an output because I was writing the result set from an asynchronous LINQ call to the console in a loop in an asynchronous context:
var p = _context.Payment.Where(pp => pp.applicationNumber.Trim() == "12345");
p.ForEachAsync(payment => Console.WriteLine(payment.Amount));
And so the test was not writing to the console before the console object was cleaned up by the runtime (when running only one test).
The solution was to convert the result set to a list first, so I could use the non-asynchronous version of forEach():
var p = _context.Payment.Where(pp => pp.applicationNumber.Trim() == "12345").ToList();
p.ForEachAsync(payment =>Console.WriteLine(payment.Amount));
Modern browsers allow cross-domain AJAX queries, it's called Cross-Origin Resource Sharing (see also this document for a shorter and more practical introduction), and recent versions of jQuery support it out of the box; you need a relatively recent browser version though (FF3.5+, IE8+, Safari 4+, Chrome4+; no Opera support AFAIK).
Null OR an empty string?
if (!empty($user)) {}
Use empty().
After realizing that $user ~= $_POST['user'] (thanks matt):
var uservariable='<?php
echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input';
?>';
In android studio you can specify where the source, res, assets folders are located. for each module/app in the build.gradle file you can add something like:
android {
compileSdkVersion 21
buildToolsVersion "21.1.1"
sourceSets {
main {
java.srcDirs = ['src']
assets.srcDirs = ['assets']
res.srcDirs = ['res']
manifest.srcFile 'AndroidManifest.xml'
}
}
}
You can see that JSONObject extends a HashMap
, so you can simply use it as a HashMap:
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
for (Map.Entry in jsonChildOBject.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
You want to reshape
the array.
B = np.reshape(A, (-1, 2))
where -1
infers the size of the new dimension from the size of the input array.
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
Just to continue to all the answers that were given here, especially @James Lanes
the size of the integer type can be expressed by this formula:
total range = (2 ^ bit system)
lower limit = -(2 ^ bit system)*0.5 upper limit = ((2 ^ bit system)*0.5) - 1
There are so many reasons for this error.I also got one and solved it.
It may be possible that you are adding a third party framework and not including it in the Copy Bundle Resources.That solved the problem for me.
Do this as follows. Go to Target -> BuildPhases -> CopyBundleResources -> Drag and drop your framework and run the code.
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
To do this, I had to come up with an intermediate data structure:
class KeyDataPoint {
String key;
DateTime timestamp;
Number data;
// obvious constructor and getters
}
With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.
Then, we apply a groupingBy
operation on the string key in order to gather the data for each key together. Note that a simple groupingBy
would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy
which is a mapping
operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping
operation is simply toList
which collects the DataPoint objects of the same group into a list.
Now we have a Map<String, List<DataPoint>>
and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.
The code ends up looking like this:
Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.getData().entrySet().stream()
.map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
.collect(groupingBy(KeyDataPoint::getKey,
mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
I took some liberties with constructors and getters, but I think they should be obvious.
How Magento log cleaning can be done both manually, automatically and other Magento database maintenance. Below the three things are most important of Magento database maintenance and optimization techniques;
To get more information http://blog.contus.com/magento-database-maintenance-and-optimization/
foreach (GridViewRow gvr in gvMyGridView.Rows)
{
string PrimaryKey = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
}
You can use this code while doing an iteration with foreach
or for any GridView event like OnRowDataBound
.
Here you can input multiple values for DataKeyNames
by separating with comma ,
. For example, DataKeyNames="ProductID,ItemID,OrderID"
.
You can now access each of DataKeys
by providing its index like below:
string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values[1].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values[2].ToString();
You can also use Key Name instead of its index to get the values from DataKeyNames
collection like below:
string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ProductID"].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ItemID"].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values["OrderID"].ToString();
An operating system provides a GUI (and CLI) that you can interact with. It also provides an API that you can interact with programmatically.
Similarly, a website provides HTML pages that you can interact with and may also provide an API that offers the same information and operations programmatically. Or those services may only be available via an API with no associated user interface.
You can use the function toprettyxml()
from xml.dom.minidom
in order to do that:
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
The idea is to print your Element
in a string, parse it using minidom and convert it again in XML using the toprettyxml
function.
Source: http://pymotw.com/2/xml/etree/ElementTree/create.html
MySQL documentation covers this topic.
Here is a synopsis. When using join
or inner join
, the on
condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join
. Similarly, you can use an on
clause with cross join
, which also differs from standard SQL.
A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.
In practice, if you want to do a cross join, then use cross join
:
from A cross join B
is much better than:
from A, B
and:
from A join B -- with no on clause
The on
clause is required for a right or left outer join, so the discussion is not relevant for them.
If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.
You can use Future-AsyncResult for this.
@Async
public Future<Page> findPage(String page) throws InterruptedException {
System.out.println("Looking up " + page);
Page results = restTemplate.getForObject("http://graph.facebook.com/" + page, Page.class);
Thread.sleep(1000L);
return new AsyncResult<Page>(results);
}
Reference: https://spring.io/guides/gs/async-method/
Hi had the exact same problem and I don't see the answer I used posted, so here it is.
I created and connected my text field via IB. When I connected it to my code via Control+Drag, I chose Action, then selected the Editing Changed event. This triggers the method on each character entry. You can use a different event to suit.
Afterwards, I used this simple code to replace the text. Note that I created my own character set to include the decimal/period character and numbers. Basically separates the string on the invalid characters, then rejoins them with empty string.
- (IBAction)myTextFieldEditingChangedMethod:(UITextField *)sender {
NSCharacterSet *validCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@".0123456789"];
NSCharacterSet *invalidCharacterSet = validCharacterSet.invertedSet;
sender.text = [[sender.text componentsSeparatedByCharactersInSet:invalidCharacterSet] componentsJoinedByString:@""];
}
Credits: Remove all but numbers from NSString
From String literals:
\n
'. But, if your multi-line string has to include a backquote (`), then you will have to use an interpreted string literal:
`line one
line two ` +
"`" + `line three
line four`
You cannot directly put a backquote (`) in a raw string literal (``xx\
).
You have to use (as explained in "how to put a backquote in a backquoted string?"):
+ "`" + ...
If you only want to read the first 999,999 (non-header) rows:
read_csv(..., nrows=999999)
If you only want to read rows 1,000,000 ... 1,999,999
read_csv(..., skiprows=1000000, nrows=999999)
nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*
skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file
and for large files, you'll probably also want to use chunksize:
chunksize : int, default None Return TextFileReader object for iteration
int max = items.Max(i => i.ID);
var item = items.First(x => x.ID == max);
This assumes there are elements in the items collection of course.
copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,
A cs class will be generated use that cs file as below:
var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);
where RootObject is the name of the generated cs file;
I like using a background image. I find it easier and more flexible:
CSS:
#menu {
max-width: 1200px;
text-align: center;
margin: auto;
}
.zoomimg {
display: inline-block;
width: 250px;
height: 375px;
padding: 0px 5px 0px 5px;
background-size: 100% 100%;
background-repeat: no-repeat;
background-position: center center;
transition: all .5s ease;
}
.zoomimg:hover {
cursor: pointer;
background-size: 150% 150%;
}
.blog {
background-image: url(http://s18.postimg.org/il7hbk7i1/image.png);
}
.music {
background-image: url(http://s18.postimg.org/4st2fxgqh/image.png);
}
.projects {
background-image: url(http://s18.postimg.org/sxtrxn115/image.png);
}
.bio {
background-image: url(http://s18.postimg.org/5xn4lb37d/image.png);
}
HTML:
<div id="menu">
<div class="blog zoomimg"></div>
<div class="music zoomimg"></div>
<div class="projects zoomimg"></div>
<div class="bio zoomimg"></div>
</div>
If in the listener you get the root layout of the item (say itemLayout
), and you gave some id's to the textviews, you can then get them with something like itemLayout.findViewById(R.id.textView1)
.
javac
(or java
during runtime) looks for the classes
being imported in the classpath
. If they are not there in the classpath
then classnotfound
exceptions are thrown.
classpath
is just like the path
variable in a shell, which is used by the shell to find a command or executable.
Entire directories or individual jar files can be put in the classpath
. Also, yes a classpath
can perhaps include a path which is not local but is somewhere on the internet. Please read more about classpath to resolve your doubts.
To disable all access to sub dirs (safest) use:
<Directory full-path-to/USERS>
Order Deny,Allow
Deny from All
</Directory>
If you want to block only PHP files from being served directly, then do:
1 - Make sure you know what file extensions the server recognizes as PHP (and dont' allow people to override in htaccess). One of my servers is set to:
# Example of existing recognized extenstions:
AddType application/x-httpd-php .php .phtml .php3
2 - Based on the extensions add a Regular Expression to FilesMatch (or LocationMatch)
<Directory full-path-to/USERS>
<FilesMatch "(?i)\.(php|php3?|phtml)$">
Order Deny,Allow
Deny from All
</FilesMatch>
</Directory>
Or use Location to match php files (I prefer the above files approach)
<LocationMatch "/USERS/.*(?i)\.(php3?|phtml)$">
Order Deny,Allow
Deny from All
</LocationMatch>
Difference between @Component, @Repository, @Controller & @Service annotations
@Component – generic and can be used across application.
@Service – annotate classes at service layer level.
@Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
@Repository – annotate classes at persistence layer, which will act as database repository.
@Controller
= @Component ( Internal Annotation ) + Presentation layer Features
@Service
= @Component ( Internal Annotation ) + Service layer Features
@Component
= Actual Components ( Beans )
@Repository
= @Component ( Internal Annotation ) + Data Layer Features ( use for handling the Domain Beans )
.inspect
is what you're looking for, it's way easier IMO than .to_yaml
!
user = User.new
user.name = "will"
user.email = "[email protected]"
user.inspect
#<name: "will", email: "[email protected]">
If possible, for special things like this, I like to use CLR functions.
In this case:
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlDateTime DateOnly(SqlDateTime input)
{
if (!input.IsNull)
{
SqlDateTime dt = new SqlDateTime(input.Value.Year, input.Value.Month, input.Value.Day, 0, 0, 0);
return dt;
}
else
return SqlDateTime.Null;
}
Typically, permissions issues with a host volume mount are because the uid/gid inside the container does not have access to the file according to the uid/gid permissions of the file on the host. However, this specific case is different.
The dot at the end of the permission string, drwxr-xr-x.
, indicates SELinux is configured. When using a host mount with SELinux, you need to pass an extra option to the end of the volume definition:
- The
z
option indicates that the bind mount content is shared among multiple containers.- The
Z
option indicates that the bind mount content is private and unshared.
Your volume mount command would then look like:
sudo docker run -i -v /data1/Downloads:/Downloads:z ubuntu bash
See more about host mounts with SELinux at: https://docs.docker.com/storage/bind-mounts/#configure-the-selinux-label
For others that see this issue with containers running as a different user, you need to ensure the uid/gid of the user inside the container has permissions to the file on the host. On production servers, this is often done by controlling the uid/gid in the image build process to match a uid/gid on the host that has access to the files (or even better, do not use host mounts in production).
A named volume is often preferred to host mounts because it will initialize the volume directory from the image directory, including any file ownership and permissions. This happens when the volume is empty and the container is created with the named volume.
MacOS users now have OSXFS which handles uid/gid's automatically between the Mac host and containers. One place it doesn't help with are files from inside the embedded VM that get mounted into the container, like /var/lib/docker.sock.
For development environments where the host uid/gid may change per developer, my preferred solution is to start the container with an entrypoint running as root, fix the uid/gid of the user inside the container to match the host volume uid/gid, and then use gosu
to drop from root to the container user to run the application inside the container. The important script for this is fix-perms
in my base image scripts, which can be found at: https://github.com/sudo-bmitch/docker-base
The important bit from the fix-perms
script is:
# update the uid
if [ -n "$opt_u" ]; then
OLD_UID=$(getent passwd "${opt_u}" | cut -f3 -d:)
NEW_UID=$(stat -c "%u" "$1")
if [ "$OLD_UID" != "$NEW_UID" ]; then
echo "Changing UID of $opt_u from $OLD_UID to $NEW_UID"
usermod -u "$NEW_UID" -o "$opt_u"
if [ -n "$opt_r" ]; then
find / -xdev -user "$OLD_UID" -exec chown -h "$opt_u" {} \;
fi
fi
fi
That gets the uid of the user inside the container, and the uid of the file, and if they do not match, calls usermod
to adjust the uid. Lastly it does a recursive find to fix any files which have not changed uid's. I like this better than running a container with a -u $(id -u):$(id -g)
flag because the above entrypoint code doesn't require each developer to run a script to start the container, and any files outside of the volume that are owned by the user will have their permissions corrected.
You can also have docker initialize a host directory from an image by using a named volume that performs a bind mount. This directory must exist in advance, and you need to provide an absolute path to the host directory, unlike host volumes in a compose file which can be relative paths. The directory must also be empty for docker to initialize it. Three different options for defining a named volume to a bind mount look like:
# create the volume in advance
$ docker volume create --driver local \
--opt type=none \
--opt device=/home/user/test \
--opt o=bind \
test_vol
# create on the fly with --mount
$ docker run -it --rm \
--mount type=volume,dst=/container/path,volume-driver=local,volume-opt=type=none,volume-opt=o=bind,volume-opt=device=/home/user/test \
foo
# inside a docker-compose file
...
volumes:
bind-test:
driver: local
driver_opts:
type: none
o: bind
device: /home/user/test
...
Lastly, if you try using user namespaces, you'll find that host volumes have permission issues because uid/gid's of the containers are shifted. In that scenario, it's probably easiest to avoid host volumes and only use named volumes.
In case anyone doesn't get results from the other answers, I fixed a similar problem by:
adding --hidden-import
flags as needed for any missing modules
cleaning up the associated folders and spec files:
rmdir /s /q dist
rmdir /s /q build
del /s /q my_service.spec
You can do this by using Apace common lang package (org.apache.commons.lang.ArrayUtils
class ). You need to do the following
byte[] concatBytes = ArrayUtils.addAll(one,two);
Action Sheet in iOS10 with Swift3.0. Follow this link.
@IBAction func ShowActionSheet(_ sender: UIButton) {
// Create An UIAlertController with Action Sheet
let optionMenuController = UIAlertController(title: nil, message: "Choose Option from Action Sheet", preferredStyle: .actionSheet)
// Create UIAlertAction for UIAlertController
let addAction = UIAlertAction(title: "Add", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Add")
})
let saveAction = UIAlertAction(title: "Edit", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Edit")
})
let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Delete")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancel")
})
// Add UIAlertAction in UIAlertController
optionMenuController.addAction(addAction)
optionMenuController.addAction(saveAction)
optionMenuController.addAction(deleteAction)
optionMenuController.addAction(cancelAction)
// Present UIAlertController with Action Sheet
self.present(optionMenuController, animated: true, completion: nil)
}
RTM
From the docs for the Python random
module:
Functions for integers:
random.randrange(stop)
random.randrange(start, stop[, step])
Return a randomly selected element from range(start, stop, step).
This is equivalent to choice(range(start, stop, step)), but doesn’t
actually build a range object.
That explains why it only gives you 0, doesn't it. range(0,1)
is [0]
. It is choosing from a list consisting of only that value.
Also from those docs:
random.random()
Return the next random floating point number in the range [0.0, 1.0).
But if your inclusion of the numpy
tag is intentional, you can generate many random floats in that range with one call using a np.random
function.
Simple Get Request using HttpClient Class
using System.Net.Http;
class Program
{
static void Main(string[] args)
{
HttpClient httpClient = new HttpClient();
var result = httpClient.GetAsync("https://www.google.com").Result;
}
}
There is an easier way. Just pass your string date to the following function, it will give you the day name :)
func getDayNameBy(stringDate: String) -> String
{
let df = NSDateFormatter()
df.dateFormat = "YYYY-MM-dd"
let date = df.dateFromString(stringDate)!
df.dateFormat = "EEEE"
return df.stringFromDate(date);
}
please try to do
make clean
(instead of make
), then
make
again.
I have Visual Studio Code version 1.27.2 and can do this:
Sometimes, you don't have two files but want to copy text from somewhere and do a quick diff without having to save the contents to files first. Then you can do this:
Try this way.
var socket = io.connect('http://...');
console.log(socket.Socket.sessionid);
<script type="text/javascript" src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script> <script type="text/javascript"> $(document).ready(function() { function myDate(){ var now = new Date(); var outHour = now.getHours(); if (outHour >12){newHour = outHour-12;outHour = newHour;} if(outHour<10){document.getElementById('HourDiv').innerHTML="0"+outHour;} else{document.getElementById('HourDiv').innerHTML=outHour;} var outMin = now.getMinutes(); if(outMin<10){document.getElementById('MinutDiv').innerHTML="0"+outMin;} else{document.getElementById('MinutDiv').innerHTML=outMin;} var outSec = now.getSeconds(); if(outSec<10){document.getElementById('SecDiv').innerHTML="0"+outSec;} else{document.getElementById('SecDiv').innerHTML=outSec;}} myDate(); setInterval(function(){ myDate();}, 1000); }); </script> <style> body {font-family:"Comic Sans MS", cursive;} h1 {text-align:center;background: gray;color:#fff;padding:5px;padding-bottom:10px;} #Content {margin:0 auto;border:solid 1px gray;width:140px;display:table;background:gray;} #HourDiv, #MinutDiv, #SecDiv {float:left;color:#fff;width:40px;text-align:center;font-size:25px;} span {float:left;color:#fff;font-size:25px;} </style> <div id="clockDiv"></div> <h1>My jQery Clock</h1> <div id="Content"> <div id="HourDiv"></div><span>:</span><div id="MinutDiv"></div><span>:</span><div id="SecDiv"></div> </div>
There are two problems on our way to the absolute path:
The following code will give us all useful paths:
URL localPackage = this.getClass().getResource("");
URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
String localDir = localPackage.getPath();
String loaderDir = urlLoader.getPath();
System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);
Here both functions that can be used for localization of the resource folder are researched. As for class
, it can be got in either way, statically or dynamically.
If the project is not in the plugin, the code if run in JUnit, will print:
loaderDir = /C:.../ws/source.dir/target/test-classes/
localDir = /C:.../ws/source.dir/target/test-classes/package/
So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName)
, for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.
If the class is in the package that is in the plugin, the output of the same test will be:
loaderDir = /C:.../ws/plugin/bin/
localDir = /C:.../ws/plugin/bin/package/
So, again we should go up and down the folder tree.
The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:
loaderDir = /C:.../ws/plugin/
localDir = /package/
Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src
or src/test/resource
here.
You can insert the code into yours and see the paths that you have.
possible answer, if you want to keep the order of the html and not use flex.
HTML
<div class="a">
<div class="c">
the
</div>
<div class="c e">
jai ho
</div>
<div class="c d">
watsup
</div>
</div>
CSS
.a {
width: 500px;
margin: 0 auto;
border: 1px solid red;
position: relative;
display: table;
}
.c {
display: table-cell;
width:33%;
}
.d {
text-align: right;
}
.e {
position: absolute;
left: 50%;
display: inline;
width: auto;
transform: translateX(-50%);
}
try to send content type header from server use this just before echoing
header('Content-Type: application/json');
The default for matrix
is to have 1 column. To explicitly have 0 columns, you need to write
matrix(, nrow = 15, ncol = 0)
A better way would be to preallocate the entire matrix and then fill it in
mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
mat[, column] <- vector
}
For Bootstrap v4;
for a thin line;
<div class="divider"></div>
for a medium thick line;
<div class="divider py-1 bg-dark"></div>
for a thick line;
<div class="divider py-1 bg-dark"><hr></div>
You shouldn't use LIs in email. They are unpredictable across email clients. Instead you have to code each bullet point like this:
<table width="100%" cellspacing="0" border="0" cellpadding="0">
<tr>
<td align="left" valign="top" width="10" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">•</td>
<td align="left" valign="top" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">This is the first bullet point</td>
</tr>
<tr>
<td align="left" valign="top" width="10" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">•</td>
<td align="left" valign="top" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">This is the second bullet point</td>
</tr>
</table>
This will ensure that your bullets work in every email client.
Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.
[string]$filePath = "C:\tempFile.zip";
[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);
Move-Item -LiteralPath $filePath -Destination $newFilePath;
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
This is the most direct way to unset a value if you know it's position.
$ array=(one two three)
$ echo ${#array[@]}
3
$ unset 'array[1]'
$ echo ${array[@]}
one three
$ echo ${#array[@]}
2
Please note that there is no such thing as "private method" in Python. Double underscore is just name mangling:
>>> class A(object):
... def __foo(self):
... pass
...
>>> a = A()
>>> A.__dict__.keys()
['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']
>>> a._A__foo()
So therefore __
prefix is useful when you need the mangling to occur, for example to not clash with names up or below inheritance chain. For other uses, single underscore would be better, IMHO.
EDIT, regarding confusion on __
, PEP-8 is quite clear on that:
If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.
Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.
So if you don't expect subclass to accidentally re-define own method with same name, don't use it.
function uploadFile() {
var fileElement = document.getElementById("fileToUpload");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension == "odx-d"||fileExtension == "odx"||fileExtension == "pdx"||fileExtension == "cmo"||fileExtension == "xml") {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/post_uploadReq");
xhr.send(fd);
}
else {
alert("You must select a valid odx,pdx,xml or cmo file for upload");
return false;
}
}
tried this , works very well
You can do this, I am using
DataTable 1.10.5
using this code:
var versionNo = $.fn.dataTable.version;
alert(versionNo);
This is how I insert new record on my DataTable using row.add (My table has 10 columns), which can also includes HTML tag elements:
function fncInsertNew() {
var table = $('#tblRecord').DataTable();
table.row.add([
"Tiger Nixon",
"System Architect",
"$3,120",
"2011/04/25",
"Edinburgh",
"5421",
"Tiger Nixon",
"System Architect",
"$3,120",
"<p>Hello</p>"
]).draw();
}
For multiple inserts at the same time, use rows.add instead:
var table = $('#tblRecord').DataTable();
table.rows.add( [ {
"Tiger Nixon",
"System Architect",
"$3,120",
"2011/04/25",
"Edinburgh",
"5421"
}, {
"Garrett Winters",
"Director",
"$5,300",
"2011/07/25",
"Edinburgh",
"8422"
}]).draw();
check this out A little framework: a complete cookies reader/writer with full Unicode support
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*| https://github.com/madmurphy/cookies.js
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
As others have said this can be caused when you've not installed an app that is listed in INSTALLED_APPS
.
In my case, manage.py
was attempting to log the exception, which led to an attempt to render it which failed due to the app not being initialized yet. By
commenting out the except
clause in manage.py
the exception was displayed without special rendering, avoiding the confusing error.
# Temporarily commenting out the log statement.
#try:
execute_from_command_line(sys.argv)
#except Exception as e:
# log.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
# raise e
Found a solution.
1) Go to where your SDK is located that android studio/eclipse is using.
If you are using Android studio, go to extras\android\m2repository\com\android\support\
.
If you are using eclipse, go to \extras\android\support\
2) See what folders you have, for me I had gridlayout-v7, support-v4 and support-v13.
3) click into support-v4 and see what number the following folder is, mine was named 13.0
Since you are using "com.android.support:support-v4:18.0.+", change this to reflect what version you have, for example I have support-v4 so first part v4 stays the same. Since the next path is 13.0, change your 18.0 to:
"com.android.support:support-v4:13.0.+"
This worked for me, hope it helps!
Update:
I noticed I had android studio set up with the wrong SDK which is why originally had difficulty updating! The path should be C:\Users\Username\AppData\Local\Android\android-sdk\extras\
Also note, if your SDK is up to date, the code will be:
"com.android.support:support-v4:19.0.+"
I've spent a day on trying to put all the pieces together, been in hundreds of sites and tutorials, but they all skip trivial steps.
So here's the full guide:
New Project:
C:\Program Files\Java\jdk{version}
C:\Program Files\Android\android-sdk-windows
.Compiling:
we can use java 8 to do a null-friendly comparasion between object. supposed i hava a Boy class with 2 fields: String name and Integer age and i want to first compare names and then ages if both are equal.
static void test2() {
List<Boy> list = new ArrayList<>();
list.add(new Boy("Peter", null));
list.add(new Boy("Tom", 24));
list.add(new Boy("Peter", 20));
list.add(new Boy("Peter", 23));
list.add(new Boy("Peter", 18));
list.add(new Boy(null, 19));
list.add(new Boy(null, 12));
list.add(new Boy(null, 24));
list.add(new Boy("Peter", null));
list.add(new Boy(null, 21));
list.add(new Boy("John", 30));
List<Boy> list2 = list.stream()
.sorted(comparing(Boy::getName,
nullsLast(naturalOrder()))
.thenComparing(Boy::getAge,
nullsLast(naturalOrder())))
.collect(toList());
list2.stream().forEach(System.out::println);
}
private static class Boy {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boy(String name, Integer age) {
this.name = name;
this.age = age;
}
public String toString() {
return "name: " + name + " age: " + age;
}
}
and the result:
name: John age: 30
name: Peter age: 18
name: Peter age: 20
name: Peter age: 23
name: Peter age: null
name: Peter age: null
name: Tom age: 24
name: null age: 12
name: null age: 19
name: null age: 21
name: null age: 24
I had this problem while the other class (CarService) was still empty, no methods, nothing. When it had methods and variables, the error was gone.
Html Markup
Tool-tip Control with class ".why", and Tool-tip Content Area with class ".customTolltip"
$(function () {
$('.why').attr('title', function () {
return $(this).next('.customTolltip').remove().html();
});
$(document).tooltip();
});
The workaround I'm using (and the one Android itself seems to favor) is to essentially substitute an underscore for a forward slash, so your structure would look something like this:
sandwich_tunaOnRye.png
sandwich_hamAndSwiss.png
drink_coldOne.png
drink_hotTea.png
The approach requires you to be meticulous in your naming and doesn't make it much easier to wrangle the files themselves (if you decided that drinks and sandwiches should really all be "food
", you'd have to do a mass rename rather than simply moving them to the directory); but your programming logic's complexity doesn't suffer too badly compared to the folder structure equivalent.
This situation sucks indeed. Android is a mixed bag of wonderful and terrible design decisions. We can only hope for the latter portion to get weeded out with all due haste :)
SELECT GETVARIABLE('SYSIBM.VERSION') FROM SYSIBM.SYSDUMMY1
Not sure if Access supports it, but in most engines (including SQL Server
) this is called a correlated subquery and works fine:
SELECT TypesAndBread.Type, TypesAndBread.TBName,
(
SELECT Count(Sandwiches.[SandwichID]) As SandwichCount
FROM Sandwiches
WHERE (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
) As SandwichCount
FROM TypesAndBread
This can be made more efficient by indexing Type
and Bread
and distributing the subqueries over the UNION
:
SELECT [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
)
FROM [Sandwiches Types]
UNION ALL
SELECT [Breads].[Bread] As TBName, "Bread" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Bread = [Breads].[Bread]
)
FROM [Breads]
df['New_column_name'] = df['Column1'].map(str) + 'X' + df['Steps']
X= x is any delimiter (eg: space) by which you want to separate two merged column.
2020 Update: An updated version of the function provided by many in this thread but now for C# 7.3 onwards:
Now you can restrict generic methods to enums types so you can write a single method extension to use it with all your enums like this:
The generic extension method:
public static string ATexto<T>(this T enumeración) where T : struct, Enum {
var tipo = enumeración.GetType();
return tipo.GetMember(enumeración.ToString())
.Where(x => x.MemberType == MemberTypes.Field && ((FieldInfo)x).FieldType == tipo).First()
.GetCustomAttribute<DisplayAttribute>()?.Name ?? enumeración.ToString();
}
The enum:
public enum TipoImpuesto {
IVA, INC, [Display(Name = "IVA e INC")]IVAeINC, [Display(Name = "No aplica")]NoAplica };
How to use it:
var tipoImpuesto = TipoImpuesto.IVAeINC;
var textoTipoImpuesto = tipoImpuesto.ATexto(); // Prints "IVA e INC".
Bonus, Enums with Flags: If you are dealing with normal enums the function above is enough, but if any of your enums can take multiple values with the use of flags then you will need to modify it like this (This code uses C#8 features):
public static string ATexto<T>(this T enumeración) where T : struct, Enum {
var tipo = enumeración.GetType();
var textoDirecto = enumeración.ToString();
string obtenerTexto(string textoDirecto) => tipo.GetMember(textoDirecto)
.Where(x => x.MemberType == MemberTypes.Field && ((FieldInfo)x).FieldType == tipo)
.First().GetCustomAttribute<DisplayAttribute>()?.Name ?? textoDirecto;
if (textoDirecto.Contains(", ")) {
var texto = new StringBuilder();
foreach (var textoDirectoAux in textoDirecto.Split(", ")) {
texto.Append($"{obtenerTexto(textoDirectoAux)}, ");
}
return texto.ToString()[0..^2];
} else {
return obtenerTexto(textoDirecto);
}
}
The enum with flags:
[Flags] public enum TipoContribuyente {
[Display(Name = "Común")] Común = 1,
[Display(Name = "Gran Contribuyente")] GranContribuyente = 2,
Autorretenedor = 4,
[Display(Name = "Retenedor de IVA")] RetenedorIVA = 8,
[Display(Name = "Régimen Simple")] RégimenSimple = 16 }
How to use it:
var tipoContribuyente = TipoContribuyente.RetenedorIVA | TipoContribuyente.GranContribuyente;
var textoAux = tipoContribuyente.ATexto(); // Prints "Gran Contribuyente, Retenedor de IVA".
Try numpy.array_split
.
From the documentation:
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
Identical to numpy.split
, but won't raise an exception if the groups aren't equal length.
If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a
, then you can remove empty arrays by:
[x for x in a if x.size > 0]
Just save that back in a
if you wish.
It's probably because size of a frame includes the size of the border.
A Frame is a top-level window with a title and a border. The size of the frame includes any area designated for the border. The dimensions of the border area may be obtained using the getInsets method. Since the border area is included in the overall size of the frame, the border effectively obscures a portion of the frame, constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an upper-left corner location of (insets.left, insets.top), and has a size of width - (insets.left + insets.right) by height - (insets.top + insets.bottom).
Source: http://download.oracle.com/javase/tutorial/uiswing/components/frame.html
Yes. But remember that such primary key allow NULL
values in both columns multiple times.
Create a table as such:
sqlite> CREATE TABLE something (
column1, column2, value, PRIMARY KEY (column1, column2));
Now this works without any warning:
sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> select * from something;
NULL|NULL|bla-bla
NULL|NULL|bla-bla
We can add ng-click event conditionally without using disabled class.
HTML:
<div ng-repeat="object in objects">
<span ng-click="!object.status && disableIt(object)">{{object.value}}</span>
</div>
#!/bin/bash
for i in $(seq 1 2 10)
do
echo "skip by 2 value $i"
done
Going with what you've started:
row = [[]]
crimefile = open(fileName, 'r')
for line in crimefile.readlines():
tmp = []
for element in line[0:-1].split(','):
tmp.append(element)
row.append(tmp)
Here is one way to do it.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script language="JavaScript">
function showInput() {
document.getElementById('display').innerHTML =
document.getElementById("user_input").value;
}
</script>
</head>
<body>
<form>
<label><b>Enter a Message</b></label>
<input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showInput();"><br/>
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
And this is what it looks like when run.Cheers.
From JAVA's GregorianCalendar sourcecode:
/**
* Returns true if {@code year} is a leap year.
*/
public boolean isLeapYear(int year) {
if (year > changeYear) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
return year % 4 == 0;
}
Where changeYear is the year the Julian Calendar becomes the Gregorian Calendar (1582).
The Julian calendar specifies leap years every four years, whereas the Gregorian calendar omits century years which are not divisible by 400.
In the Gregorian Calendar documentation you can found more information about it.
Yes an Untrusted certificate can cause this. Look at the certificate path for the webservice by opening the websservice in a browser and use the browser tools to look at the certificate path. You may need to install one or more intermediate certificates onto the computer calling the webservice. In the browser you may see "Certificate errors" with an option to "Install Certificate" when you investigate further - this could be the certificate you missing.
My particular problem was a Geotrust Geotrust DV SSL CA intermediate certificate missing following an upgrade to their root server in July 2010 https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422
(2020 update deadlink preserved here: https://web.archive.org/web/20140724085537/https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422 )
Goto Package properties->Configurations->Enable Package Configurations->Add->xml configuration file->Specify dtsconfig file->click next->In OLEDB Properties tick the connection string->connection string value will be displayed->click next and finish package is hence configured.
You can add Environment variable also in this process
You can't modify SQLite tables in any significant way after they have been created. The accepted suggested solution is to create a new table with the correct requirements and copy your data into it, then drop the old table.
here is the official documentation about this: http://sqlite.org/faq.html#q11
TL;DR;
@Html.TextBoxFor(m => m.DOB,"{0:yyyy-MM-dd}", new { type = "date" })
Applying [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
didn't work out for me!
Explanation:
The date of an html input
element of type date
must be formatted in respect to ISO8601, which is: yyyy-MM-dd
The displayed date is formatted based on the locale of the user's browser, but the parsed value is always formatted yyyy-mm-dd.
My experience is, that the language is not determined by the Accept-Language
header, but by either the browser display language or OS system language.
In order to display a date property of your model using Html.TextBoxFor
:
Date property of your model class:
public DateTime DOB { get; set; }
Nothing else is needed on the model side.
In Razor you do:
@Html.TextBoxFor(m => m.DOB,"{0:yyyy-MM-dd}", new { type = "date" })
Perhaps use this:
[a[i] for i in (1,2,5)]
# [11, 12, 15]
min_element
and max_element
return iterators, not values. So you need *min_element...
and *max_element...
.
You could analyse the user agent ($_SERVER['HTTP_USER_AGENT']
) or compare the client’s IP address ($_SERVER['REMOTE_ADDR']
) with a list of IP addresses of search engine bots.